import of upstream 2.4.34.4 from kernel.org
[linux-2.4.git] / arch / x86_64 / kernel / smpboot.c
1 /*
2  *      x86 SMP booting functions
3  *
4  *      (c) 1995 Alan Cox, Building #3 <alan@redhat.com>
5  *      (c) 1998, 1999, 2000 Ingo Molnar <mingo@redhat.com>
6  *      Copyright 2001 Andi Kleen, SuSE Labs.
7  *
8  *      Much of the core SMP work is based on previous work by Thomas Radke, to
9  *      whom a great many thanks are extended.
10  *
11  *      Thanks to Intel for making available several different Pentium,
12  *      Pentium Pro and Pentium-II/Xeon MP machines.
13  *      Original development of Linux SMP code supported by Caldera.
14  *
15  *      This code is released under the GNU General Public License version 2 or
16  *      later.
17  *
18  *      Fixes
19  *              Felix Koop      :       NR_CPUS used properly
20  *              Jose Renau      :       Handle single CPU case.
21  *              Alan Cox        :       By repeated request 8) - Total BogoMIP report.
22  *              Greg Wright     :       Fix for kernel stacks panic.
23  *              Erich Boleyn    :       MP v1.4 and additional changes.
24  *      Matthias Sattler        :       Changes for 2.1 kernel map.
25  *      Michel Lespinasse       :       Changes for 2.1 kernel map.
26  *      Michael Chastain        :       Change trampoline.S to gnu as.
27  *              Alan Cox        :       Dumb bug: 'B' step PPro's are fine
28  *              Ingo Molnar     :       Added APIC timers, based on code
29  *                                      from Jose Renau
30  *              Ingo Molnar     :       various cleanups and rewrites
31  *              Tigran Aivazian :       fixed "0.00 in /proc/uptime on SMP" bug.
32  *      Maciej W. Rozycki       :       Bits for genuine 82489DX APICs
33  *      Andi Kleen              :       Changed for SMP boot into long mode.
34  */
35
36 #include <linux/config.h>
37 #include <linux/init.h>
38
39 #include <linux/mm.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/smp_lock.h>
42 #include <linux/irq.h>
43 #include <linux/bootmem.h>
44
45 #include <linux/delay.h>
46 #include <linux/mc146818rtc.h>
47 #include <asm/mtrr.h>
48 #include <asm/pgalloc.h>
49 #include <asm/desc.h>
50 #include <asm/kdebug.h>
51 #include <asm/timex.h>
52 #include <asm/proto.h>
53 #include <asm/acpi.h>
54
55 /* Setup configured maximum number of CPUs to activate */
56 unsigned int max_cpus = NR_CPUS;
57
58 static int cpu_mask = -1; 
59
60 /* Total count of live CPUs */
61 int smp_num_cpus = 1;
62
63 /* Number of siblings per CPU package */
64 int smp_num_siblings = 1;
65 int __initdata phys_proc_id[NR_CPUS]; /* Package ID of each logical CPU */
66 int cpu_sibling_map[NR_CPUS] __cacheline_aligned;
67
68 /* Bitmask of currently online CPUs */
69 unsigned long cpu_online_map;
70
71 /* which CPU (physical APIC ID) maps to which logical CPU number */
72 volatile int x86_apicid_to_cpu[NR_CPUS];
73 /* which logical CPU number maps to which CPU (physical APIC ID) */
74 volatile int x86_cpu_to_apicid[NR_CPUS];
75
76 static volatile unsigned long cpu_callin_map;
77 static volatile unsigned long cpu_callout_map;
78
79 /* Per CPU bogomips and other parameters */
80 struct cpuinfo_x86 cpu_data[NR_CPUS] __cacheline_aligned;
81
82 /* Set when the idlers are all forked */
83 int smp_threads_ready;
84
85 extern void time_init_smp(void);
86
87 /*
88  * Setup routine for controlling SMP activation
89  *
90  * Command-line option of "nosmp" or "maxcpus=0" will disable SMP
91  * activation entirely (the MPS table probe still happens, though).
92  */
93
94 static int __init nosmp(char *str)
95 {
96         max_cpus = 0;
97         return 1;
98 }
99
100 __setup("nosmp", nosmp);
101
102 static int __init cpumask(char *str)
103 {
104         get_option(&str, &cpu_mask);
105         return 1;
106 }
107
108 __setup("cpumask=", cpumask); 
109
110 /*
111  * Trampoline 80x86 program as an array.
112  */
113
114 extern unsigned char trampoline_data [];
115 extern unsigned char trampoline_end  [];
116 static unsigned char *trampoline_base;
117
118 /*
119  * Currently trivial. Write the real->protected mode
120  * bootstrap into the page concerned. The caller
121  * has made sure it's suitably aligned.
122  */
123
124 static unsigned long __init setup_trampoline(void)
125 {
126         extern volatile __u32 tramp_gdt_ptr; 
127         tramp_gdt_ptr = __pa_symbol(&gdt_table); 
128         memcpy(trampoline_base, trampoline_data, trampoline_end - trampoline_data);
129         return virt_to_phys(trampoline_base);
130 }
131
132 /*
133  * We are called very early to get the low memory for the
134  * SMP bootup trampoline page.
135  */
136 void __init smp_alloc_memory(void)
137 {
138         trampoline_base = __va(0x6000); /* reserved in setup.c */
139 }
140
141 /*
142  * The bootstrap kernel entry code has set these up. Save them for
143  * a given CPU
144  */
145
146 void __init smp_store_cpu_info(int id)
147 {
148         struct cpuinfo_x86 *c = cpu_data + id;
149
150         *c = boot_cpu_data;
151         identify_cpu(c);
152 }
153
154 /*
155  * Architecture specific routine called by the kernel just before init is
156  * fired off. This allows the BP to have everything in order [we hope].
157  * At the end of this all the APs will hit the system scheduling and off
158  * we go. Each AP will load the system gdt's and jump through the kernel
159  * init into idle(). At this point the scheduler will one day take over
160  * and give them jobs to do. smp_callin is a standard routine
161  * we use to track CPUs as they power up.
162  */
163
164 static atomic_t smp_commenced = ATOMIC_INIT(0);
165
166 void __init smp_commence(void)
167 {
168         /*
169          * Lets the callins below out of their loop.
170          */
171         Dprintk("Setting commenced=1, go go go\n");
172
173         wmb();
174         atomic_set(&smp_commenced,1);
175 }
176
177 /*
178  * TSC synchronization.
179  *
180  * We first check wether all CPUs have their TSC's synchronized,
181  * then we print a warning if not, and always resync.
182  */
183
184 static atomic_t tsc_start_flag = ATOMIC_INIT(0);
185 static atomic_t tsc_count_start = ATOMIC_INIT(0);
186 static atomic_t tsc_count_stop = ATOMIC_INIT(0);
187 static unsigned long long tsc_values[NR_CPUS];
188
189 #define NR_LOOPS 5
190
191 static inline unsigned long long div64 (unsigned long long a, unsigned long b)
192 {
193         return a/b;
194 }
195
196 static void __init synchronize_tsc_bp (void)
197 {
198         int i;
199         unsigned long long t0;
200         unsigned long long sum, avg;
201         long long delta;
202         unsigned long one_usec;
203         int buggy = 0;
204
205         printk("checking TSC synchronization across CPUs: ");
206
207         one_usec = cpu_khz / 1000;
208
209         atomic_set(&tsc_start_flag, 1);
210         wmb();
211
212         /*
213          * We loop a few times to get a primed instruction cache,
214          * then the last pass is more or less synchronized and
215          * the BP and APs set their cycle counters to zero all at
216          * once. This reduces the chance of having random offsets
217          * between the processors, and guarantees that the maximum
218          * delay between the cycle counters is never bigger than
219          * the latency of information-passing (cachelines) between
220          * two CPUs.
221          */
222         for (i = 0; i < NR_LOOPS; i++) {
223                 /*
224                  * all APs synchronize but they loop on '== num_cpus'
225                  */
226                 while (atomic_read(&tsc_count_start) != smp_num_cpus-1) mb();
227                 atomic_set(&tsc_count_stop, 0);
228                 wmb();
229                 /*
230                  * this lets the APs save their current TSC:
231                  */
232                 atomic_inc(&tsc_count_start);
233
234                 sync_core();
235                 rdtscll(tsc_values[smp_processor_id()]);
236
237                 /*
238                  * We clear the TSC in the last loop:
239                  */
240
241                 if (i == NR_LOOPS-1) {
242                         write_tsc(0, 0);
243                 }
244
245                 /*
246                  * Wait for all APs to leave the synchronization point:
247                  */
248                 while (atomic_read(&tsc_count_stop) != smp_num_cpus-1) mb();
249                 atomic_set(&tsc_count_start, 0);
250                 wmb();
251                 atomic_inc(&tsc_count_stop);
252         }
253
254         sum = 0;
255         for (i = 0; i < smp_num_cpus; i++) {
256                 t0 = tsc_values[i];
257                 sum += t0;
258         }
259         avg = div64(sum, smp_num_cpus);
260
261         sum = 0;
262         for (i = 0; i < smp_num_cpus; i++) {
263                 delta = tsc_values[i] - avg;
264                 if (delta < 0)
265                         delta = -delta;
266                 /*
267                  * We report bigger than 2 microseconds clock differences.
268                  */
269                 if (delta > 2*one_usec) {
270                         long realdelta;
271                         if (!buggy) {
272                                 buggy = 1;
273                                 printk("\n");
274                         }
275                         realdelta = div64(delta, one_usec);
276                         if (tsc_values[i] < avg)
277                                 realdelta = -realdelta;
278
279                         printk("BIOS BUG: CPU#%d improperly initialized, has %ld usecs TSC skew! FIXED.\n",
280                                 i, realdelta);
281                 }
282
283                 sum += delta;
284         }
285         if (!buggy)
286                 printk("passed.\n");
287 }
288
289 static void __init synchronize_tsc_ap (void)
290 {
291         int i;
292
293         /*
294          * smp_num_cpus is not necessarily known at the time
295          * this gets called, so we first wait for the BP to
296          * finish SMP initialization:
297          */
298         while (!atomic_read(&tsc_start_flag)) mb();
299
300         for (i = 0; i < NR_LOOPS; i++) {
301                 atomic_inc(&tsc_count_start);
302                 while (atomic_read(&tsc_count_start) != smp_num_cpus) mb();
303
304                 sync_core();
305                 rdtscll(tsc_values[smp_processor_id()]);
306                 if (i == NR_LOOPS-1)
307                         write_tsc(0, 0);
308
309                 atomic_inc(&tsc_count_stop);
310                 while (atomic_read(&tsc_count_stop) != smp_num_cpus) mb();
311         }
312 }
313 #undef NR_LOOPS
314
315 extern void calibrate_delay(void);
316
317 static atomic_t init_deasserted;
318
319 void __init smp_callin(void)
320 {
321         int cpuid, phys_id;
322         unsigned long timeout;
323
324         /*
325          * If waken up by an INIT in an 82489DX configuration
326          * we may get here before an INIT-deassert IPI reaches
327          * our local APIC.  We have to wait for the IPI or we'll
328          * lock up on an APIC access.
329          */
330         while (!atomic_read(&init_deasserted));
331
332         /*
333          * (This works even if the APIC is not enabled.)
334          */
335         phys_id = GET_APIC_ID(apic_read(APIC_ID));
336         cpuid = current->processor;
337         if (test_and_set_bit(cpuid, &cpu_online_map)) {
338                 printk("huh, phys CPU#%d, CPU#%d already present??\n",
339                                         phys_id, cpuid);
340                 BUG();
341         }
342         Dprintk("CPU#%d (phys ID: %d) waiting for CALLOUT\n", cpuid, phys_id);
343
344         /*
345          * STARTUP IPIs are fragile beasts as they might sometimes
346          * trigger some glue motherboard logic. Complete APIC bus
347          * silence for 1 second, this overestimates the time the
348          * boot CPU is spending to send the up to 2 STARTUP IPIs
349          * by a factor of two. This should be enough.
350          */
351
352         /*
353          * Waiting 2s total for startup (udelay is not yet working)
354          */
355         timeout = jiffies + 2*HZ;
356         while (time_before(jiffies, timeout)) {
357                 /*
358                  * Has the boot CPU finished it's STARTUP sequence?
359                  */
360                 if (test_bit(cpuid, &cpu_callout_map))
361                         break;
362                 rep_nop();
363         }
364
365         if (!time_before(jiffies, timeout)) {
366                 printk("BUG: CPU%d started up but did not get a callout!\n",
367                         cpuid);
368                 BUG();
369         }
370
371         /*
372          * the boot CPU has finished the init stage and is spinning
373          * on callin_map until we finish. We are free to set up this
374          * CPU, first the APIC. (this is probably redundant on most
375          * boards)
376          */
377
378         Dprintk("CALLIN, before setup_local_APIC().\n");
379         setup_local_APIC();
380
381         if (nmi_watchdog == NMI_IO_APIC) {
382                 disable_8259A_irq(0);
383                 enable_NMI_through_LVT0(NULL);
384                 enable_8259A_irq(0);
385         }
386
387         sti();
388
389 #ifdef CONFIG_MTRR
390         /*
391          * Must be done before calibration delay is computed
392          */
393         mtrr_init_secondary_cpu ();
394 #endif
395         /*
396          * Get our bogomips.
397          */
398         calibrate_delay();
399         Dprintk("Stack at about %p\n",&cpuid);
400
401         /*
402          * Save our processor parameters
403          */
404         smp_store_cpu_info(cpuid);
405
406         /*
407          * Allow the master to continue.
408          */
409         set_bit(cpuid, &cpu_callin_map);
410
411         /*
412          *      Synchronize the TSC with the BP
413          */
414         if (cpu_has_tsc)
415                 synchronize_tsc_ap();
416 }
417
418 int cpucount;
419
420 /*
421  * Activate a secondary processor.
422  */
423 int __init start_secondary(void *unused)
424 {
425         /*
426          * Dont put anything before smp_callin(), SMP
427          * booting is too fragile that we want to limit the
428          * things done here to the most necessary things.
429          */
430         cpu_init();
431         smp_callin();
432         while (!atomic_read(&smp_commenced))
433                 rep_nop();
434         /*
435          * low-memory mappings have been cleared, flush them from
436          * the local TLBs too.
437          */
438         local_flush_tlb();
439
440         cpu_idle();
441         return 0;
442 }
443
444 /*
445  * Everything has been set up for the secondary
446  * CPUs - they just need to reload everything
447  * from the task structure
448  * This function must not return.
449  */
450 void __init initialize_secondary(void)
451 {
452         struct task_struct *me = stack_current();
453
454         /*
455          * We don't actually need to load the full TSS,
456          * basically just the stack pointer and the eip.
457          */
458
459         asm volatile(
460                 "movq %0,%%rsp\n\t"
461                 "jmp *%1"
462                 :
463                 :"r" (me->thread.rsp),"r" (me->thread.rip));
464 }
465
466 extern volatile void *init_rsp; 
467 extern void (*initial_code)(void);
468
469 static int __init fork_by_hand(void)
470 {
471         struct pt_regs regs;
472         /*
473          * don't care about the eip and regs settings since
474          * we'll never reschedule the forked task.
475          */
476         return do_fork(CLONE_VM|CLONE_PID, 0, &regs, 0);
477 }
478
479 #if APIC_DEBUG
480 static inline void inquire_remote_apic(int apicid)
481 {
482         int i, regs[] = { APIC_ID >> 4, APIC_LVR >> 4, APIC_SPIV >> 4 };
483         char *names[] = { "ID", "VERSION", "SPIV" };
484         int timeout, status;
485
486         printk("Inquiring remote APIC #%d...\n", apicid);
487
488         for (i = 0; i < sizeof(regs) / sizeof(*regs); i++) {
489                 printk("... APIC #%d %s: ", apicid, names[i]);
490
491                 /*
492                  * Wait for idle.
493                  */
494                 apic_wait_icr_idle();
495
496                 apic_write_around(APIC_ICR2, SET_APIC_DEST_FIELD(apicid));
497                 apic_write_around(APIC_ICR, APIC_DM_REMRD | regs[i]);
498
499                 timeout = 0;
500                 do {
501                         udelay(100);
502                         status = apic_read(APIC_ICR) & APIC_ICR_RR_MASK;
503                 } while (status == APIC_ICR_RR_INPROG && timeout++ < 1000);
504
505                 switch (status) {
506                 case APIC_ICR_RR_VALID:
507                         status = apic_read(APIC_RRR);
508                         printk("%08x\n", status);
509                         break;
510                 default:
511                         printk("failed\n");
512                 }
513         }
514 }
515 #endif
516
517 static int __init do_boot_cpu (int apicid)
518 {
519         struct task_struct *idle;
520         unsigned long send_status, accept_status, boot_status, maxlvt;
521         int timeout, num_starts, j, cpu;
522         unsigned long start_eip;
523
524         cpu = ++cpucount;
525
526         /*
527          * We can't use kernel_thread since we must avoid to
528          * reschedule the child.
529          */
530         if (fork_by_hand() < 0)
531                 panic("failed fork for CPU %d", cpu);
532
533         /*
534          * We remove it from the pidhash and the runqueue
535          * once we got the process:
536          */
537         idle = init_task.prev_task;
538         if (!idle)
539                 panic("No idle process for CPU %d", cpu);
540
541         idle->processor = cpu;
542         x86_cpu_to_apicid[cpu] = apicid;
543         x86_apicid_to_cpu[apicid] = cpu;
544         idle->cpus_runnable = 1<<cpu; 
545         idle->cpus_allowed = 1<<cpu;
546         idle->thread.rip = (unsigned long)start_secondary;
547         idle->thread.rsp = (unsigned long)idle + THREAD_SIZE - 8;
548
549         del_from_runqueue(idle);
550         unhash_process(idle);
551         cpu_pda[cpu].pcurrent = init_tasks[cpu] = idle;
552
553         /* start_eip had better be page-aligned! */
554         start_eip = setup_trampoline();
555
556         /* So we see what's up   */
557         printk("Booting processor %d/%d rip %lx page %p\n", cpu, apicid, start_eip, idle);
558         init_rsp = (void *) (THREAD_SIZE + (char *)idle - 16);
559         initial_code = initialize_secondary; 
560
561         /*
562          * This grunge runs the startup process for
563          * the targeted processor.
564          */
565
566         atomic_set(&init_deasserted, 0);
567
568         Dprintk("Setting warm reset code and vector.\n");
569
570         CMOS_WRITE(0xa, 0xf);
571         local_flush_tlb();
572         Dprintk("1.\n");
573         *((volatile unsigned short *) phys_to_virt(0x469)) = start_eip >> 4;
574         Dprintk("2.\n");
575         *((volatile unsigned short *) phys_to_virt(0x467)) = start_eip & 0xf;
576         Dprintk("3.\n");
577
578         /*
579          * Be paranoid about clearing APIC errors.
580          */
581         if (APIC_INTEGRATED(apic_version[apicid])) {
582                 apic_read_around(APIC_SPIV);
583                 apic_write(APIC_ESR, 0);
584                 apic_read(APIC_ESR);
585         }
586
587         /*
588          * Status is now clean
589          */
590         send_status = 0;
591         accept_status = 0;
592         boot_status = 0;
593
594         /*
595          * Starting actual IPI sequence...
596          */
597
598         Dprintk("Asserting INIT.\n");
599
600         /*
601          * Turn INIT on target chip
602          */
603         apic_write_around(APIC_ICR2, SET_APIC_DEST_FIELD(apicid));
604
605         /*
606          * Send IPI
607          */
608         apic_write_around(APIC_ICR, APIC_INT_LEVELTRIG | APIC_INT_ASSERT
609                                 | APIC_DM_INIT);
610
611         Dprintk("Waiting for send to finish...\n");
612         timeout = 0;
613         do {
614                 Dprintk("+");
615                 udelay(100);
616                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
617         } while (send_status && (timeout++ < 1000));
618
619         mdelay(10);
620
621         Dprintk("Deasserting INIT.\n");
622
623         /* Target chip */
624         apic_write_around(APIC_ICR2, SET_APIC_DEST_FIELD(apicid));
625
626         /* Send IPI */
627         apic_write_around(APIC_ICR, APIC_INT_LEVELTRIG | APIC_DM_INIT);
628
629         Dprintk("Waiting for send to finish...\n");
630         timeout = 0;
631         do {
632                 Dprintk("+");
633                 udelay(100);
634                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
635         } while (send_status && (timeout++ < 1000));
636
637         atomic_set(&init_deasserted, 1);
638
639         /*
640          * Should we send STARTUP IPIs ?
641          *
642          * Determine this based on the APIC version.
643          * If we don't have an integrated APIC, don't
644          * send the STARTUP IPIs.
645          */
646         if (APIC_INTEGRATED(apic_version[apicid]))
647                 num_starts = 2;
648         else
649                 num_starts = 0;
650
651         /*
652          * Run STARTUP IPI loop.
653          */
654         Dprintk("#startup loops: %d.\n", num_starts);
655
656         maxlvt = get_maxlvt();
657
658         for (j = 1; j <= num_starts; j++) {
659                 Dprintk("Sending STARTUP #%d.\n",j);
660                 apic_read_around(APIC_SPIV);
661                 apic_write(APIC_ESR, 0);
662                 apic_read(APIC_ESR);
663                 Dprintk("After apic_write.\n");
664
665                 /*
666                  * STARTUP IPI
667                  */
668
669                 /* Target chip */
670                 Dprintk("target apic %x\n", SET_APIC_DEST_FIELD(apicid));
671                 apic_write_around(APIC_ICR2, SET_APIC_DEST_FIELD(apicid));
672
673                 Dprintk("after target chip\n"); 
674
675                 /* Boot on the stack */
676                 /* Kick the second */
677                 apic_write_around(APIC_ICR, APIC_DM_STARTUP
678                                         | (start_eip >> 12));
679
680                 Dprintk("after eip write\n"); 
681
682                 /*
683                  * Give the other CPU some time to accept the IPI.
684                  */
685                 udelay(300);
686
687                 Dprintk("Startup point 1.\n");
688
689                 Dprintk("Waiting for send to finish...\n");
690                 timeout = 0;
691                 do {
692                         Dprintk("+");
693                         udelay(100);
694                         send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
695                 } while (send_status && (timeout++ < 1000));
696
697                 /*
698                  * Give the other CPU some time to accept the IPI.
699                  */
700                 udelay(200);
701                 /*
702                  * Due to the Pentium erratum 3AP.
703                  */
704                 if (maxlvt > 3) {
705                         apic_read_around(APIC_SPIV);
706                         apic_write(APIC_ESR, 0);
707                 }
708                 accept_status = (apic_read(APIC_ESR) & 0xEF);
709                 if (send_status || accept_status)
710                         break;
711         }
712         Dprintk("After Startup.\n");
713
714         if (send_status)
715                 printk("APIC never delivered???\n");
716         if (accept_status)
717                 printk("APIC delivery error (%lx).\n", accept_status);
718
719         if (!send_status && !accept_status) {
720                 /*
721                  * allow APs to start initializing.
722                  */
723                 Dprintk("Before Callout %d.\n", cpu);
724                 set_bit(cpu, &cpu_callout_map);
725                 Dprintk("After Callout %d.\n", cpu);
726
727                 /*
728                  * Wait 5s total for a response
729                  */
730                 for (timeout = 0; timeout < 50000; timeout++) {
731                         if (test_bit(cpu, &cpu_callin_map))
732                                 break;  /* It has booted */
733                         udelay(100);
734                 }
735
736                 if (test_bit(cpu, &cpu_callin_map)) {
737                         /* number CPUs logically, starting from 1 (BSP is 0) */
738                         Dprintk("OK.\n");
739                         printk("CPU%d: ", cpu);
740                         print_cpu_info(&cpu_data[cpu]);
741                         Dprintk("CPU has booted.\n");
742                 } else {
743                         boot_status = 1;
744                         if (*((volatile unsigned char *)phys_to_virt(8192))
745                                         == 0xA5)
746                                 /* trampoline started but...? */
747                                 printk("Stuck ??\n");
748                         else
749                                 /* trampoline code not run */
750                                 printk("Not responding.\n");
751 #if APIC_DEBUG
752                         inquire_remote_apic(apicid);
753 #endif
754                 }
755         }
756         if (send_status || accept_status || boot_status) {
757                 x86_cpu_to_apicid[cpu] = -1;
758                 x86_apicid_to_cpu[apicid] = -1;
759                 cpucount--;
760         }
761
762         /* mark "stuck" area as not stuck */
763         *((volatile unsigned int *)phys_to_virt(8192)) = 0;
764         
765         return cpu; 
766 }
767
768 cycles_t cacheflush_time;
769
770 static __init void smp_tune_scheduling (void)
771 {
772         unsigned long cachesize;       /* kB   */
773         unsigned long bandwidth = 2000; /* MB/s */
774         /*
775          * Rough estimation for SMP scheduling, this is the number of
776          * cycles it takes for a fully memory-limited process to flush
777          * the SMP-local cache.
778          *
779          * (For a P5 this pretty much means we will choose another idle
780          *  CPU almost always at wakeup time (this is due to the small
781          *  L1 cache), on PIIs it's around 50-100 usecs, depending on
782          *  the cache size)
783          */
784
785         if (!cpu_khz) {
786                 /*
787                  * this basically disables processor-affinity
788                  * scheduling on SMP without a TSC.
789                  */
790                 cacheflush_time = 0;
791                 return;
792         } else {
793                 cachesize = boot_cpu_data.x86_cache_size;
794                 if (cachesize == -1) {
795                         cachesize = 16; /* Pentiums, 2x8kB cache */
796                         bandwidth = 100;
797                 }
798
799                 cacheflush_time = (cpu_khz>>10) * (cachesize<<10) / bandwidth;
800         }
801
802         cacheflush_time *= 10;  /* Add an NUMA factor */
803
804         printk("per-CPU timeslice cutoff: %ld.%02ld usecs.\n",
805                 (long)cacheflush_time/(cpu_khz/1000),
806                 ((long)cacheflush_time*100/(cpu_khz/1000)) % 100);
807 }
808
809 /*
810  * Cycle through the processors sending APIC IPIs to boot each.
811  */
812
813 extern int prof_multiplier[NR_CPUS];
814 extern int prof_old_multiplier[NR_CPUS];
815 extern int prof_counter[NR_CPUS];
816
817 void __init smp_boot_cpus(void)
818 {
819         int apicid, cpu, maxcpu;
820
821 #ifdef CONFIG_MTRR
822         /*  Must be done before other processors booted  */
823         mtrr_init_boot_cpu ();
824 #endif
825         /*
826          * Initialize the logical to physical CPU number mapping
827          * and the per-CPU profiling counter/multiplier
828          */
829
830         for (apicid = 0; apicid < NR_CPUS; apicid++) {
831                 x86_apicid_to_cpu[apicid] = -1;
832                 prof_counter[apicid] = 1;
833                 prof_old_multiplier[apicid] = 1;
834                 prof_multiplier[apicid] = 1;
835         }
836
837         /*
838          * Setup boot CPU information
839          */
840         smp_store_cpu_info(0); /* Final full version of the data */
841         printk("CPU%d: ", 0);
842         print_cpu_info(&cpu_data[0]);
843
844         /*
845          * We have the boot CPU online for sure.
846          */
847         set_bit(0, &cpu_online_map);
848         x86_apicid_to_cpu[boot_cpu_id] = 0;
849         x86_cpu_to_apicid[0] = boot_cpu_id;
850         global_irq_holder = 0;
851         current->processor = 0;
852         init_idle();
853         smp_tune_scheduling();
854
855         /*
856          * If we couldnt find an SMP configuration at boot time,
857          * get out of here now!
858          */
859         if (!smp_found_config && !acpi_lapic) {
860                 printk(KERN_NOTICE "SMP motherboard not detected.\n");
861                 io_apic_irqs = 0;
862                 cpu_online_map = phys_cpu_present_map = 1;
863                 smp_num_cpus = 1;
864                 if (APIC_init_uniprocessor())
865                         printk(KERN_NOTICE "Local APIC not detected."
866                                            " Using dummy APIC emulation.\n");
867                 goto smp_done;
868         }
869
870         /*
871          * Should not be necessary because the MP table should list the boot
872          * CPU too, but we do it for the sake of robustness anyway.
873          */
874         if (!test_bit(boot_cpu_id, &phys_cpu_present_map)) {
875                 printk("weird, boot CPU (#%d) not listed by the BIOS.\n",
876                                                                  boot_cpu_id);
877                 phys_cpu_present_map |= (1 << hard_smp_processor_id());
878         }
879
880         /*
881          * If we couldn't find a local APIC, then get out of here now!
882          */
883         if (APIC_INTEGRATED(apic_version[boot_cpu_id]) &&
884             !test_bit(X86_FEATURE_APIC, boot_cpu_data.x86_capability)) {
885                 printk(KERN_ERR "BIOS bug, local APIC #%d not detected!...\n",
886                         boot_cpu_id);
887                 printk(KERN_ERR "... forcing use of dummy APIC emulation. (tell your hw vendor)\n");
888                 io_apic_irqs = 0;
889                 cpu_online_map = phys_cpu_present_map = 1;
890                 smp_num_cpus = 1;
891                 apic_disabled = 1;
892                 goto smp_done;
893         }
894
895         verify_local_APIC();
896
897         /*
898          * If SMP should be disabled, then really disable it!
899          */
900         if (!max_cpus) {
901                 smp_found_config = 0;
902                 printk(KERN_INFO "SMP mode deactivated, forcing use of dummy APIC emulation.\n");
903                 cpu_online_map = phys_cpu_present_map = 1;
904                 smp_num_cpus = 1;
905                 goto smp_done;
906         }
907
908         connect_bsp_APIC();
909         setup_local_APIC();
910
911         if (GET_APIC_ID(apic_read(APIC_ID)) != boot_cpu_id)
912                 BUG();
913
914         /*
915          * Now scan the CPU present map and fire up the other CPUs.
916          */
917         Dprintk("CPU present map: %lx\n", phys_cpu_present_map);
918
919         maxcpu = 0;
920         for (apicid = 0; apicid < NR_CPUS; apicid++) {
921                 /*
922                  * Don't even attempt to start the boot CPU!
923                  */
924                 if (apicid == boot_cpu_id)
925                         continue;
926
927                 if (!(phys_cpu_present_map & (1 << apicid)))
928                         continue;
929                 if (((1<<apicid) & cpu_mask) == 0) 
930                         continue;
931
932                 cpu = do_boot_cpu(apicid);
933
934                 /*
935                  * Make sure we unmap all failed CPUs
936                  */
937                 if ((x86_apicid_to_cpu[apicid] == -1) &&
938                                 (phys_cpu_present_map & (1 << apicid)))
939                         printk("phys CPU #%d not responding - cannot use it.\n",apicid);
940                 else if (cpu > maxcpu) 
941                         maxcpu = cpu; 
942         }
943
944         /*
945          * Cleanup possible dangling ends...
946          */
947         {
948                 /*
949                  * Install writable page 0 entry to set BIOS data area.
950                  */
951                 local_flush_tlb();
952
953                 /*
954                  * Paranoid:  Set warm reset code and vector here back
955                  * to default values.
956                  */
957                 CMOS_WRITE(0, 0xf);
958
959                 *((volatile int *) phys_to_virt(0x467)) = 0;
960         }
961
962         /*
963          * Allow the user to impress friends.
964          */
965
966         Dprintk("Before bogomips.\n");
967         if (!cpucount) {
968                 printk(KERN_ERR "Only one processor found.\n");
969         } else {
970                 unsigned long bogosum = 0;
971                 for (cpu = 0; cpu < NR_CPUS; cpu++)
972                         if (cpu_online_map & (1<<cpu))
973                                 bogosum += cpu_data[cpu].loops_per_jiffy;
974                 printk(KERN_INFO "Total of %d processors activated (%lu.%02lu BogoMIPS).\n",
975                         cpucount+1,
976                         bogosum/(500000/HZ),
977                         (bogosum/(5000/HZ))%100);
978                 Dprintk("Before bogocount - setting activated=1.\n");
979         }
980         smp_num_cpus = maxcpu + 1;
981
982         Dprintk("Boot done.\n");
983
984         /*
985          * If Hyper-Threading is avaialble, construct cpu_sibling_map[], so
986          * that we can tell the sibling CPU efficiently.
987          */
988         if (test_bit(X86_FEATURE_HT, boot_cpu_data.x86_capability)
989             && smp_num_siblings > 1) {
990                 for (cpu = 0; cpu < NR_CPUS; cpu++)
991                         cpu_sibling_map[cpu] = NO_PROC_ID;
992                 
993                 for (cpu = 0; cpu < smp_num_cpus; cpu++) {
994                         int     i;
995                         
996                         for (i = 0; i < smp_num_cpus; i++) {
997                                 if (i == cpu)
998                                         continue;
999                                 if (phys_proc_id[cpu] == phys_proc_id[i]) {
1000                                         cpu_sibling_map[cpu] = i;
1001                                         printk("cpu_sibling_map[%d] = %d\n", cpu, cpu_sibling_map[cpu]);
1002                                         break;
1003                                 }
1004                         }
1005                         if (cpu_sibling_map[cpu] == NO_PROC_ID) {
1006                                 smp_num_siblings = 1;
1007                                 printk(KERN_WARNING "WARNING: No sibling found for CPU %d.\n", cpu);
1008                         }
1009                 }
1010         }
1011              
1012         /*
1013          * Here we can be sure that there is an IO-APIC in the system. Let's
1014          * go and set it up:
1015          */
1016         if (!skip_ioapic_setup && nr_ioapics)
1017                 setup_IO_APIC();
1018         else
1019                 nr_ioapics = 0;
1020
1021         /*
1022          * Set up all local APIC timers in the system:
1023          */
1024         setup_APIC_clocks();
1025
1026         /*
1027          * Synchronize the TSC with the AP
1028          */
1029         if (cpu_has_tsc && cpucount)
1030                 synchronize_tsc_bp();
1031
1032         if (nmi_watchdog != 0) 
1033                 check_nmi_watchdog(); 
1034
1035 smp_done:
1036         zap_low_mappings();
1037         time_init_smp();
1038 }