4b120fcd1db2e5530d06c32528f5456fe908b005
[linux-2.6.git] / arch / i386 / 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  *
7  *      Much of the core SMP work is based on previous work by Thomas Radke, to
8  *      whom a great many thanks are extended.
9  *
10  *      Thanks to Intel for making available several different Pentium,
11  *      Pentium Pro and Pentium-II/Xeon MP machines.
12  *      Original development of Linux SMP code supported by Caldera.
13  *
14  *      This code is released under the GNU General Public License version 2 or
15  *      later.
16  *
17  *      Fixes
18  *              Felix Koop      :       NR_CPUS used properly
19  *              Jose Renau      :       Handle single CPU case.
20  *              Alan Cox        :       By repeated request 8) - Total BogoMIPS report.
21  *              Greg Wright     :       Fix for kernel stacks panic.
22  *              Erich Boleyn    :       MP v1.4 and additional changes.
23  *      Matthias Sattler        :       Changes for 2.1 kernel map.
24  *      Michel Lespinasse       :       Changes for 2.1 kernel map.
25  *      Michael Chastain        :       Change trampoline.S to gnu as.
26  *              Alan Cox        :       Dumb bug: 'B' step PPro's are fine
27  *              Ingo Molnar     :       Added APIC timers, based on code
28  *                                      from Jose Renau
29  *              Ingo Molnar     :       various cleanups and rewrites
30  *              Tigran Aivazian :       fixed "0.00 in /proc/uptime on SMP" bug.
31  *      Maciej W. Rozycki       :       Bits for genuine 82489DX APICs
32  *              Martin J. Bligh :       Added support for multi-quad systems
33  *              Dave Jones      :       Report invalid combinations of Athlon CPUs.
34 *               Rusty Russell   :       Hacked into shape for new "hotplug" boot process. */
35
36 #include <linux/module.h>
37 #include <linux/config.h>
38 #include <linux/init.h>
39 #include <linux/kernel.h>
40
41 #include <linux/mm.h>
42 #include <linux/sched.h>
43 #include <linux/kernel_stat.h>
44 #include <linux/smp_lock.h>
45 #include <linux/irq.h>
46 #include <linux/bootmem.h>
47
48 #include <linux/delay.h>
49 #include <linux/mc146818rtc.h>
50 #include <asm/tlbflush.h>
51 #include <asm/desc.h>
52 #include <asm/arch_hooks.h>
53
54 #include <mach_apic.h>
55 #include <mach_wakecpu.h>
56 #include <smpboot_hooks.h>
57
58 /* Set if we find a B stepping CPU */
59 static int __initdata smp_b_stepping;
60
61 /* Number of siblings per CPU package */
62 int smp_num_siblings = 1;
63 int phys_proc_id[NR_CPUS]; /* Package ID of each logical CPU */
64 EXPORT_SYMBOL(phys_proc_id);
65
66 /* bitmap of online cpus */
67 cpumask_t cpu_online_map;
68
69 cpumask_t cpu_callin_map;
70 cpumask_t cpu_callout_map;
71 static cpumask_t smp_commenced_mask;
72
73 /* Per CPU bogomips and other parameters */
74 struct cpuinfo_x86 cpu_data[NR_CPUS] __cacheline_aligned;
75
76 u8 x86_cpu_to_apicid[NR_CPUS] =
77                         { [0 ... NR_CPUS-1] = 0xff };
78 EXPORT_SYMBOL(x86_cpu_to_apicid);
79
80 /* Set when the idlers are all forked */
81 int smp_threads_ready;
82
83 /*
84  * Trampoline 80x86 program as an array.
85  */
86
87 extern unsigned char trampoline_data [];
88 extern unsigned char trampoline_end  [];
89 static unsigned char *trampoline_base;
90 static int trampoline_exec;
91
92 /*
93  * Currently trivial. Write the real->protected mode
94  * bootstrap into the page concerned. The caller
95  * has made sure it's suitably aligned.
96  */
97
98 static unsigned long __init setup_trampoline(void)
99 {
100         memcpy(trampoline_base, trampoline_data, trampoline_end - trampoline_data);
101         return virt_to_phys(trampoline_base);
102 }
103
104 /*
105  * We are called very early to get the low memory for the
106  * SMP bootup trampoline page.
107  */
108 void __init smp_alloc_memory(void)
109 {
110         trampoline_base = (void *) alloc_bootmem_low_pages(PAGE_SIZE);
111         /*
112          * Has to be in very low memory so we can execute
113          * real-mode AP code.
114          */
115         if (__pa(trampoline_base) >= 0x9F000)
116                 BUG();
117         /*
118          * Make the SMP trampoline executable:
119          */
120         trampoline_exec = set_kernel_exec((unsigned long)trampoline_base, 1);
121 }
122
123 /*
124  * The bootstrap kernel entry code has set these up. Save them for
125  * a given CPU
126  */
127
128 static void __init smp_store_cpu_info(int id)
129 {
130         struct cpuinfo_x86 *c = cpu_data + id;
131
132         *c = boot_cpu_data;
133         if (id!=0)
134                 identify_cpu(c);
135         /*
136          * Mask B, Pentium, but not Pentium MMX
137          */
138         if (c->x86_vendor == X86_VENDOR_INTEL &&
139             c->x86 == 5 &&
140             c->x86_mask >= 1 && c->x86_mask <= 4 &&
141             c->x86_model <= 3)
142                 /*
143                  * Remember we have B step Pentia with bugs
144                  */
145                 smp_b_stepping = 1;
146
147         /*
148          * Certain Athlons might work (for various values of 'work') in SMP
149          * but they are not certified as MP capable.
150          */
151         if ((c->x86_vendor == X86_VENDOR_AMD) && (c->x86 == 6)) {
152
153                 /* Athlon 660/661 is valid. */  
154                 if ((c->x86_model==6) && ((c->x86_mask==0) || (c->x86_mask==1)))
155                         goto valid_k7;
156
157                 /* Duron 670 is valid */
158                 if ((c->x86_model==7) && (c->x86_mask==0))
159                         goto valid_k7;
160
161                 /*
162                  * Athlon 662, Duron 671, and Athlon >model 7 have capability bit.
163                  * It's worth noting that the A5 stepping (662) of some Athlon XP's
164                  * have the MP bit set.
165                  * See http://www.heise.de/newsticker/data/jow-18.10.01-000 for more.
166                  */
167                 if (((c->x86_model==6) && (c->x86_mask>=2)) ||
168                     ((c->x86_model==7) && (c->x86_mask>=1)) ||
169                      (c->x86_model> 7))
170                         if (cpu_has_mp)
171                                 goto valid_k7;
172
173                 /* If we get here, it's not a certified SMP capable AMD system. */
174                 tainted |= TAINT_UNSAFE_SMP;
175         }
176
177 valid_k7:
178         ;
179 }
180
181 /*
182  * TSC synchronization.
183  *
184  * We first check whether all CPUs have their TSC's synchronized,
185  * then we print a warning if not, and always resync.
186  */
187
188 static atomic_t tsc_start_flag = ATOMIC_INIT(0);
189 static atomic_t tsc_count_start = ATOMIC_INIT(0);
190 static atomic_t tsc_count_stop = ATOMIC_INIT(0);
191 static unsigned long long tsc_values[NR_CPUS];
192
193 #define NR_LOOPS 5
194
195 static void __init synchronize_tsc_bp (void)
196 {
197         int i;
198         unsigned long long t0;
199         unsigned long long sum, avg;
200         long long delta;
201         unsigned long one_usec;
202         int buggy = 0;
203
204         printk(KERN_INFO "checking TSC synchronization across %u CPUs: ", num_booting_cpus());
205
206         /* convert from kcyc/sec to cyc/usec */
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) != num_booting_cpus()-1)
227                         mb();
228                 atomic_set(&tsc_count_stop, 0);
229                 wmb();
230                 /*
231                  * this lets the APs save their current TSC:
232                  */
233                 atomic_inc(&tsc_count_start);
234
235                 rdtscll(tsc_values[smp_processor_id()]);
236                 /*
237                  * We clear the TSC in the last loop:
238                  */
239                 if (i == NR_LOOPS-1)
240                         write_tsc(0, 0);
241
242                 /*
243                  * Wait for all APs to leave the synchronization point:
244                  */
245                 while (atomic_read(&tsc_count_stop) != num_booting_cpus()-1)
246                         mb();
247                 atomic_set(&tsc_count_start, 0);
248                 wmb();
249                 atomic_inc(&tsc_count_stop);
250         }
251
252         sum = 0;
253         for (i = 0; i < NR_CPUS; i++) {
254                 if (cpu_isset(i, cpu_callout_map)) {
255                         t0 = tsc_values[i];
256                         sum += t0;
257                 }
258         }
259         avg = sum;
260         do_div(avg, num_booting_cpus());
261
262         sum = 0;
263         for (i = 0; i < NR_CPUS; i++) {
264                 if (!cpu_isset(i, cpu_callout_map))
265                         continue;
266                 delta = tsc_values[i] - avg;
267                 if (delta < 0)
268                         delta = -delta;
269                 /*
270                  * We report bigger than 2 microseconds clock differences.
271                  */
272                 if (delta > 2*one_usec) {
273                         long realdelta;
274                         if (!buggy) {
275                                 buggy = 1;
276                                 printk("\n");
277                         }
278                         realdelta = delta;
279                         do_div(realdelta, one_usec);
280                         if (tsc_values[i] < avg)
281                                 realdelta = -realdelta;
282
283                         printk(KERN_INFO "CPU#%d had %ld usecs TSC skew, fixed it up.\n", i, realdelta);
284                 }
285
286                 sum += delta;
287         }
288         if (!buggy)
289                 printk("passed.\n");
290 }
291
292 static void __init synchronize_tsc_ap (void)
293 {
294         int i;
295
296         /*
297          * Not every cpu is online at the time
298          * this gets called, so we first wait for the BP to
299          * finish SMP initialization:
300          */
301         while (!atomic_read(&tsc_start_flag)) mb();
302
303         for (i = 0; i < NR_LOOPS; i++) {
304                 atomic_inc(&tsc_count_start);
305                 while (atomic_read(&tsc_count_start) != num_booting_cpus())
306                         mb();
307
308                 rdtscll(tsc_values[smp_processor_id()]);
309                 if (i == NR_LOOPS-1)
310                         write_tsc(0, 0);
311
312                 atomic_inc(&tsc_count_stop);
313                 while (atomic_read(&tsc_count_stop) != num_booting_cpus()) mb();
314         }
315 }
316 #undef NR_LOOPS
317
318 extern void calibrate_delay(void);
319
320 static atomic_t init_deasserted;
321
322 void __init smp_callin(void)
323 {
324         int cpuid, phys_id;
325         unsigned long timeout;
326
327         /*
328          * If waken up by an INIT in an 82489DX configuration
329          * we may get here before an INIT-deassert IPI reaches
330          * our local APIC.  We have to wait for the IPI or we'll
331          * lock up on an APIC access.
332          */
333         wait_for_init_deassert(&init_deasserted);
334
335         /*
336          * (This works even if the APIC is not enabled.)
337          */
338         phys_id = GET_APIC_ID(apic_read(APIC_ID));
339         cpuid = smp_processor_id();
340         if (cpu_isset(cpuid, cpu_callin_map)) {
341                 printk("huh, phys CPU#%d, CPU#%d already present??\n",
342                                         phys_id, cpuid);
343                 BUG();
344         }
345         Dprintk("CPU#%d (phys ID: %d) waiting for CALLOUT\n", cpuid, phys_id);
346
347         /*
348          * STARTUP IPIs are fragile beasts as they might sometimes
349          * trigger some glue motherboard logic. Complete APIC bus
350          * silence for 1 second, this overestimates the time the
351          * boot CPU is spending to send the up to 2 STARTUP IPIs
352          * by a factor of two. This should be enough.
353          */
354
355         /*
356          * Waiting 2s total for startup (udelay is not yet working)
357          */
358         timeout = jiffies + 2*HZ;
359         while (time_before(jiffies, timeout)) {
360                 /*
361                  * Has the boot CPU finished it's STARTUP sequence?
362                  */
363                 if (cpu_isset(cpuid, cpu_callout_map))
364                         break;
365                 rep_nop();
366         }
367
368         if (!time_before(jiffies, timeout)) {
369                 printk("BUG: CPU%d started up but did not get a callout!\n",
370                         cpuid);
371                 BUG();
372         }
373
374         /*
375          * the boot CPU has finished the init stage and is spinning
376          * on callin_map until we finish. We are free to set up this
377          * CPU, first the APIC. (this is probably redundant on most
378          * boards)
379          */
380
381         Dprintk("CALLIN, before setup_local_APIC().\n");
382         smp_callin_clear_local_apic();
383         setup_local_APIC();
384         map_cpu_to_logical_apicid();
385
386         /*
387          * Get our bogomips.
388          */
389         calibrate_delay();
390         Dprintk("Stack at about %p\n",&cpuid);
391
392         /*
393          * Save our processor parameters
394          */
395         smp_store_cpu_info(cpuid);
396
397         disable_APIC_timer();
398
399         /*
400          * Allow the master to continue.
401          */
402         cpu_set(cpuid, cpu_callin_map);
403
404         /*
405          *      Synchronize the TSC with the BP
406          */
407         if (cpu_has_tsc && cpu_khz)
408                 synchronize_tsc_ap();
409 }
410
411 int cpucount;
412
413 /*
414  * Activate a secondary processor.
415  */
416 static void __init start_secondary(void *unused)
417 {
418         /*
419          * Dont put anything before smp_callin(), SMP
420          * booting is too fragile that we want to limit the
421          * things done here to the most necessary things.
422          */
423         cpu_init();
424         smp_callin();
425         while (!cpu_isset(smp_processor_id(), smp_commenced_mask))
426                 rep_nop();
427         setup_secondary_APIC_clock();
428         if (nmi_watchdog == NMI_IO_APIC) {
429                 disable_8259A_irq(0);
430                 enable_NMI_through_LVT0(NULL);
431                 enable_8259A_irq(0);
432         }
433         enable_APIC_timer();
434         /*
435          * low-memory mappings have been cleared, flush them from
436          * the local TLBs too.
437          */
438         local_flush_tlb();
439         cpu_set(smp_processor_id(), cpu_online_map);
440
441         /* We can take interrupts now: we're officially "up". */
442         local_irq_enable();
443
444         wmb();
445         cpu_idle();
446 }
447
448 /*
449  * Everything has been set up for the secondary
450  * CPUs - they just need to reload everything
451  * from the task structure
452  * This function must not return.
453  */
454 void __init initialize_secondary(void)
455 {
456         /*
457          * We don't actually need to load the full TSS,
458          * basically just the stack pointer and the eip.
459          */
460
461         asm volatile(
462                 "movl %0,%%esp\n\t"
463                 "jmp *%1"
464                 :
465                 :"r" (current->thread.esp),"r" (current->thread.eip));
466 }
467
468 extern struct {
469         void * esp;
470         unsigned short ss;
471 } stack_start;
472
473 #ifdef CONFIG_NUMA
474
475 /* which logical CPUs are on which nodes */
476 cpumask_t node_2_cpu_mask[MAX_NUMNODES] =
477                                 { [0 ... MAX_NUMNODES-1] = CPU_MASK_NONE };
478 /* which node each logical CPU is on */
479 int cpu_2_node[NR_CPUS] = { [0 ... NR_CPUS-1] = 0 };
480 EXPORT_SYMBOL(cpu_2_node);
481
482 /* set up a mapping between cpu and node. */
483 static inline void map_cpu_to_node(int cpu, int node)
484 {
485         printk("Mapping cpu %d to node %d\n", cpu, node);
486         cpu_set(cpu, node_2_cpu_mask[node]);
487         cpu_2_node[cpu] = node;
488 }
489
490 /* undo a mapping between cpu and node. */
491 static inline void unmap_cpu_to_node(int cpu)
492 {
493         int node;
494
495         printk("Unmapping cpu %d from all nodes\n", cpu);
496         for (node = 0; node < MAX_NUMNODES; node ++)
497                 cpu_clear(cpu, node_2_cpu_mask[node]);
498         cpu_2_node[cpu] = 0;
499 }
500 #else /* !CONFIG_NUMA */
501
502 #define map_cpu_to_node(cpu, node)      ({})
503 #define unmap_cpu_to_node(cpu)  ({})
504
505 #endif /* CONFIG_NUMA */
506
507 u8 cpu_2_logical_apicid[NR_CPUS] = { [0 ... NR_CPUS-1] = BAD_APICID };
508
509 void map_cpu_to_logical_apicid(void)
510 {
511         int cpu = smp_processor_id();
512         int apicid = logical_smp_processor_id();
513
514         cpu_2_logical_apicid[cpu] = apicid;
515         map_cpu_to_node(cpu, apicid_to_node(apicid));
516 }
517
518 void unmap_cpu_to_logical_apicid(int cpu)
519 {
520         cpu_2_logical_apicid[cpu] = BAD_APICID;
521         unmap_cpu_to_node(cpu);
522 }
523
524 #if APIC_DEBUG
525 static inline void __inquire_remote_apic(int apicid)
526 {
527         int i, regs[] = { APIC_ID >> 4, APIC_LVR >> 4, APIC_SPIV >> 4 };
528         char *names[] = { "ID", "VERSION", "SPIV" };
529         int timeout, status;
530
531         printk("Inquiring remote APIC #%d...\n", apicid);
532
533         for (i = 0; i < sizeof(regs) / sizeof(*regs); i++) {
534                 printk("... APIC #%d %s: ", apicid, names[i]);
535
536                 /*
537                  * Wait for idle.
538                  */
539                 apic_wait_icr_idle();
540
541                 apic_write_around(APIC_ICR2, SET_APIC_DEST_FIELD(apicid));
542                 apic_write_around(APIC_ICR, APIC_DM_REMRD | regs[i]);
543
544                 timeout = 0;
545                 do {
546                         udelay(100);
547                         status = apic_read(APIC_ICR) & APIC_ICR_RR_MASK;
548                 } while (status == APIC_ICR_RR_INPROG && timeout++ < 1000);
549
550                 switch (status) {
551                 case APIC_ICR_RR_VALID:
552                         status = apic_read(APIC_RRR);
553                         printk("%08x\n", status);
554                         break;
555                 default:
556                         printk("failed\n");
557                 }
558         }
559 }
560 #endif
561
562 #ifdef WAKE_SECONDARY_VIA_NMI
563 /* 
564  * Poke the other CPU in the eye via NMI to wake it up. Remember that the normal
565  * INIT, INIT, STARTUP sequence will reset the chip hard for us, and this
566  * won't ... remember to clear down the APIC, etc later.
567  */
568 static int __init
569 wakeup_secondary_cpu(int logical_apicid, unsigned long start_eip)
570 {
571         unsigned long send_status = 0, accept_status = 0;
572         int timeout, maxlvt;
573
574         /* Target chip */
575         apic_write_around(APIC_ICR2, SET_APIC_DEST_FIELD(logical_apicid));
576
577         /* Boot on the stack */
578         /* Kick the second */
579         apic_write_around(APIC_ICR, APIC_DM_NMI | APIC_DEST_LOGICAL);
580
581         Dprintk("Waiting for send to finish...\n");
582         timeout = 0;
583         do {
584                 Dprintk("+");
585                 udelay(100);
586                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
587         } while (send_status && (timeout++ < 1000));
588
589         /*
590          * Give the other CPU some time to accept the IPI.
591          */
592         udelay(200);
593         /*
594          * Due to the Pentium erratum 3AP.
595          */
596         maxlvt = get_maxlvt();
597         if (maxlvt > 3) {
598                 apic_read_around(APIC_SPIV);
599                 apic_write(APIC_ESR, 0);
600         }
601         accept_status = (apic_read(APIC_ESR) & 0xEF);
602         Dprintk("NMI sent.\n");
603
604         if (send_status)
605                 printk("APIC never delivered???\n");
606         if (accept_status)
607                 printk("APIC delivery error (%lx).\n", accept_status);
608
609         return (send_status | accept_status);
610 }
611 #endif  /* WAKE_SECONDARY_VIA_NMI */
612
613 #ifdef WAKE_SECONDARY_VIA_INIT
614 static int __init
615 wakeup_secondary_cpu(int phys_apicid, unsigned long start_eip)
616 {
617         unsigned long send_status = 0, accept_status = 0;
618         int maxlvt, timeout, num_starts, j;
619
620         /*
621          * Be paranoid about clearing APIC errors.
622          */
623         if (APIC_INTEGRATED(apic_version[phys_apicid])) {
624                 apic_read_around(APIC_SPIV);
625                 apic_write(APIC_ESR, 0);
626                 apic_read(APIC_ESR);
627         }
628
629         Dprintk("Asserting INIT.\n");
630
631         /*
632          * Turn INIT on target chip
633          */
634         apic_write_around(APIC_ICR2, SET_APIC_DEST_FIELD(phys_apicid));
635
636         /*
637          * Send IPI
638          */
639         apic_write_around(APIC_ICR, APIC_INT_LEVELTRIG | APIC_INT_ASSERT
640                                 | APIC_DM_INIT);
641
642         Dprintk("Waiting for send to finish...\n");
643         timeout = 0;
644         do {
645                 Dprintk("+");
646                 udelay(100);
647                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
648         } while (send_status && (timeout++ < 1000));
649
650         mdelay(10);
651
652         Dprintk("Deasserting INIT.\n");
653
654         /* Target chip */
655         apic_write_around(APIC_ICR2, SET_APIC_DEST_FIELD(phys_apicid));
656
657         /* Send IPI */
658         apic_write_around(APIC_ICR, APIC_INT_LEVELTRIG | APIC_DM_INIT);
659
660         Dprintk("Waiting for send to finish...\n");
661         timeout = 0;
662         do {
663                 Dprintk("+");
664                 udelay(100);
665                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
666         } while (send_status && (timeout++ < 1000));
667
668         atomic_set(&init_deasserted, 1);
669
670         /*
671          * Should we send STARTUP IPIs ?
672          *
673          * Determine this based on the APIC version.
674          * If we don't have an integrated APIC, don't send the STARTUP IPIs.
675          */
676         if (APIC_INTEGRATED(apic_version[phys_apicid]))
677                 num_starts = 2;
678         else
679                 num_starts = 0;
680
681         /*
682          * Run STARTUP IPI loop.
683          */
684         Dprintk("#startup loops: %d.\n", num_starts);
685
686         maxlvt = get_maxlvt();
687
688         for (j = 1; j <= num_starts; j++) {
689                 Dprintk("Sending STARTUP #%d.\n",j);
690                 apic_read_around(APIC_SPIV);
691                 apic_write(APIC_ESR, 0);
692                 apic_read(APIC_ESR);
693                 Dprintk("After apic_write.\n");
694
695                 /*
696                  * STARTUP IPI
697                  */
698
699                 /* Target chip */
700                 apic_write_around(APIC_ICR2, SET_APIC_DEST_FIELD(phys_apicid));
701
702                 /* Boot on the stack */
703                 /* Kick the second */
704                 apic_write_around(APIC_ICR, APIC_DM_STARTUP
705                                         | (start_eip >> 12));
706
707                 /*
708                  * Give the other CPU some time to accept the IPI.
709                  */
710                 udelay(300);
711
712                 Dprintk("Startup point 1.\n");
713
714                 Dprintk("Waiting for send to finish...\n");
715                 timeout = 0;
716                 do {
717                         Dprintk("+");
718                         udelay(100);
719                         send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
720                 } while (send_status && (timeout++ < 1000));
721
722                 /*
723                  * Give the other CPU some time to accept the IPI.
724                  */
725                 udelay(200);
726                 /*
727                  * Due to the Pentium erratum 3AP.
728                  */
729                 if (maxlvt > 3) {
730                         apic_read_around(APIC_SPIV);
731                         apic_write(APIC_ESR, 0);
732                 }
733                 accept_status = (apic_read(APIC_ESR) & 0xEF);
734                 if (send_status || accept_status)
735                         break;
736         }
737         Dprintk("After Startup.\n");
738
739         if (send_status)
740                 printk("APIC never delivered???\n");
741         if (accept_status)
742                 printk("APIC delivery error (%lx).\n", accept_status);
743
744         return (send_status | accept_status);
745 }
746 #endif  /* WAKE_SECONDARY_VIA_INIT */
747
748 extern cpumask_t cpu_initialized;
749
750 static int __init do_boot_cpu(int apicid)
751 /*
752  * NOTE - on most systems this is a PHYSICAL apic ID, but on multiquad
753  * (ie clustered apic addressing mode), this is a LOGICAL apic ID.
754  * Returns zero if CPU booted OK, else error code from wakeup_secondary_cpu.
755  */
756 {
757         struct task_struct *idle;
758         unsigned long boot_error;
759         int timeout, cpu;
760         unsigned long start_eip;
761         unsigned short nmi_high = 0, nmi_low = 0;
762
763         cpu = ++cpucount;
764         /*
765          * We can't use kernel_thread since we must avoid to
766          * reschedule the child.
767          */
768         idle = fork_idle(cpu);
769         if (IS_ERR(idle))
770                 panic("failed fork for CPU %d", cpu);
771         idle->thread.eip = (unsigned long) start_secondary;
772         /* start_eip had better be page-aligned! */
773         start_eip = setup_trampoline();
774
775         /* So we see what's up   */
776         printk("Booting processor %d/%d eip %lx\n", cpu, apicid, start_eip);
777         /* Stack for startup_32 can be just as for start_secondary onwards */
778         stack_start.esp = (void *) idle->thread.esp;
779
780         irq_ctx_init(cpu);
781
782         /*
783          * This grunge runs the startup process for
784          * the targeted processor.
785          */
786
787         atomic_set(&init_deasserted, 0);
788
789         Dprintk("Setting warm reset code and vector.\n");
790
791         store_NMI_vector(&nmi_high, &nmi_low);
792
793         smpboot_setup_warm_reset_vector(start_eip);
794
795         /*
796          * Starting actual IPI sequence...
797          */
798         boot_error = wakeup_secondary_cpu(apicid, start_eip);
799
800         if (!boot_error) {
801                 /*
802                  * allow APs to start initializing.
803                  */
804                 Dprintk("Before Callout %d.\n", cpu);
805                 cpu_set(cpu, cpu_callout_map);
806                 Dprintk("After Callout %d.\n", cpu);
807
808                 /*
809                  * Wait 5s total for a response
810                  */
811                 for (timeout = 0; timeout < 50000; timeout++) {
812                         if (cpu_isset(cpu, cpu_callin_map))
813                                 break;  /* It has booted */
814                         udelay(100);
815                 }
816
817                 if (cpu_isset(cpu, cpu_callin_map)) {
818                         /* number CPUs logically, starting from 1 (BSP is 0) */
819                         Dprintk("OK.\n");
820                         printk("CPU%d: ", cpu);
821                         print_cpu_info(&cpu_data[cpu]);
822                         Dprintk("CPU has booted.\n");
823                 } else {
824                         boot_error= 1;
825                         if (*((volatile unsigned char *)trampoline_base)
826                                         == 0xA5)
827                                 /* trampoline started but...? */
828                                 printk("Stuck ??\n");
829                         else
830                                 /* trampoline code not run */
831                                 printk("Not responding.\n");
832                         inquire_remote_apic(apicid);
833                 }
834         }
835         x86_cpu_to_apicid[cpu] = apicid;
836         if (boot_error) {
837                 /* Try to put things back the way they were before ... */
838                 unmap_cpu_to_logical_apicid(cpu);
839                 cpu_clear(cpu, cpu_callout_map); /* was set here (do_boot_cpu()) */
840                 cpu_clear(cpu, cpu_initialized); /* was set by cpu_init() */
841                 cpucount--;
842         }
843
844         /* mark "stuck" area as not stuck */
845         *((volatile unsigned long *)trampoline_base) = 0;
846
847         return boot_error;
848 }
849
850 cycles_t cacheflush_time;
851 unsigned long cache_decay_ticks;
852
853 static void smp_tune_scheduling (void)
854 {
855         unsigned long cachesize;       /* kB   */
856         unsigned long bandwidth = 350; /* MB/s */
857         /*
858          * Rough estimation for SMP scheduling, this is the number of
859          * cycles it takes for a fully memory-limited process to flush
860          * the SMP-local cache.
861          *
862          * (For a P5 this pretty much means we will choose another idle
863          *  CPU almost always at wakeup time (this is due to the small
864          *  L1 cache), on PIIs it's around 50-100 usecs, depending on
865          *  the cache size)
866          */
867
868         if (!cpu_khz) {
869                 /*
870                  * this basically disables processor-affinity
871                  * scheduling on SMP without a TSC.
872                  */
873                 cacheflush_time = 0;
874                 return;
875         } else {
876                 cachesize = boot_cpu_data.x86_cache_size;
877                 if (cachesize == -1) {
878                         cachesize = 16; /* Pentiums, 2x8kB cache */
879                         bandwidth = 100;
880                 }
881
882                 cacheflush_time = (cpu_khz>>10) * (cachesize<<10) / bandwidth;
883         }
884
885         cache_decay_ticks = (long)cacheflush_time/cpu_khz + 1;
886
887         printk("per-CPU timeslice cutoff: %ld.%02ld usecs.\n",
888                 (long)cacheflush_time/(cpu_khz/1000),
889                 ((long)cacheflush_time*100/(cpu_khz/1000)) % 100);
890         printk("task migration cache decay timeout: %ld msecs.\n",
891                 cache_decay_ticks);
892 }
893
894 /*
895  * Cycle through the processors sending APIC IPIs to boot each.
896  */
897
898 static int boot_cpu_logical_apicid;
899 /* Where the IO area was mapped on multiquad, always 0 otherwise */
900 void *xquad_portio;
901
902 cpumask_t cpu_sibling_map[NR_CPUS] __cacheline_aligned;
903
904 static void __init smp_boot_cpus(unsigned int max_cpus)
905 {
906         int apicid, cpu, bit, kicked;
907         unsigned long bogosum = 0;
908
909         /*
910          * Setup boot CPU information
911          */
912         smp_store_cpu_info(0); /* Final full version of the data */
913         printk("CPU%d: ", 0);
914         print_cpu_info(&cpu_data[0]);
915
916         boot_cpu_physical_apicid = GET_APIC_ID(apic_read(APIC_ID));
917         boot_cpu_logical_apicid = logical_smp_processor_id();
918         x86_cpu_to_apicid[0] = boot_cpu_physical_apicid;
919
920         current_thread_info()->cpu = 0;
921         smp_tune_scheduling();
922         cpus_clear(cpu_sibling_map[0]);
923         cpu_set(0, cpu_sibling_map[0]);
924
925         /*
926          * If we couldn't find an SMP configuration at boot time,
927          * get out of here now!
928          */
929         if (!smp_found_config && !acpi_lapic) {
930                 printk(KERN_NOTICE "SMP motherboard not detected.\n");
931                 smpboot_clear_io_apic_irqs();
932                 phys_cpu_present_map = physid_mask_of_physid(0);
933                 if (APIC_init_uniprocessor())
934                         printk(KERN_NOTICE "Local APIC not detected."
935                                            " Using dummy APIC emulation.\n");
936                 map_cpu_to_logical_apicid();
937                 return;
938         }
939
940         /*
941          * Should not be necessary because the MP table should list the boot
942          * CPU too, but we do it for the sake of robustness anyway.
943          * Makes no sense to do this check in clustered apic mode, so skip it
944          */
945         if (!check_phys_apicid_present(boot_cpu_physical_apicid)) {
946                 printk("weird, boot CPU (#%d) not listed by the BIOS.\n",
947                                 boot_cpu_physical_apicid);
948                 physid_set(hard_smp_processor_id(), phys_cpu_present_map);
949         }
950
951         /*
952          * If we couldn't find a local APIC, then get out of here now!
953          */
954         if (APIC_INTEGRATED(apic_version[boot_cpu_physical_apicid]) && !cpu_has_apic) {
955                 printk(KERN_ERR "BIOS bug, local APIC #%d not detected!...\n",
956                         boot_cpu_physical_apicid);
957                 printk(KERN_ERR "... forcing use of dummy APIC emulation. (tell your hw vendor)\n");
958                 smpboot_clear_io_apic_irqs();
959                 phys_cpu_present_map = physid_mask_of_physid(0);
960                 return;
961         }
962
963         verify_local_APIC();
964
965         /*
966          * If SMP should be disabled, then really disable it!
967          */
968         if (!max_cpus) {
969                 smp_found_config = 0;
970                 printk(KERN_INFO "SMP mode deactivated, forcing use of dummy APIC emulation.\n");
971                 smpboot_clear_io_apic_irqs();
972                 phys_cpu_present_map = physid_mask_of_physid(0);
973                 return;
974         }
975
976         connect_bsp_APIC();
977         setup_local_APIC();
978         map_cpu_to_logical_apicid();
979
980
981         setup_portio_remap();
982
983         /*
984          * Scan the CPU present map and fire up the other CPUs via do_boot_cpu
985          *
986          * In clustered apic mode, phys_cpu_present_map is a constructed thus:
987          * bits 0-3 are quad0, 4-7 are quad1, etc. A perverse twist on the 
988          * clustered apic ID.
989          */
990         Dprintk("CPU present map: %lx\n", physids_coerce(phys_cpu_present_map));
991
992         kicked = 1;
993         for (bit = 0; kicked < NR_CPUS && bit < MAX_APICS; bit++) {
994                 apicid = cpu_present_to_apicid(bit);
995                 /*
996                  * Don't even attempt to start the boot CPU!
997                  */
998                 if ((apicid == boot_cpu_apicid) || (apicid == BAD_APICID))
999                         continue;
1000
1001                 if (!check_apicid_present(bit))
1002                         continue;
1003                 if (max_cpus <= cpucount+1)
1004                         continue;
1005
1006                 if (do_boot_cpu(apicid))
1007                         printk("CPU #%d not responding - cannot use it.\n",
1008                                                                 apicid);
1009                 else
1010                         ++kicked;
1011         }
1012
1013         /*
1014          * Cleanup possible dangling ends...
1015          */
1016         smpboot_restore_warm_reset_vector();
1017
1018         /*
1019          * Allow the user to impress friends.
1020          */
1021         Dprintk("Before bogomips.\n");
1022         for (cpu = 0; cpu < NR_CPUS; cpu++)
1023                 if (cpu_isset(cpu, cpu_callout_map))
1024                         bogosum += cpu_data[cpu].loops_per_jiffy;
1025         printk(KERN_INFO
1026                 "Total of %d processors activated (%lu.%02lu BogoMIPS).\n",
1027                 cpucount+1,
1028                 HZ*(bogosum >> 3)/62500,
1029                 (HZ*(bogosum >> 3)/625) % 100);
1030         
1031         Dprintk("Before bogocount - setting activated=1.\n");
1032
1033         if (smp_b_stepping)
1034                 printk(KERN_WARNING "WARNING: SMP operation may be unreliable with B stepping processors.\n");
1035
1036         /*
1037          * Don't taint if we are running SMP kernel on a single non-MP
1038          * approved Athlon
1039          */
1040         if (tainted & TAINT_UNSAFE_SMP) {
1041                 if (cpucount)
1042                         printk (KERN_INFO "WARNING: This combination of AMD processors is not suitable for SMP.\n");
1043                 else
1044                         tainted &= ~TAINT_UNSAFE_SMP;
1045         }
1046
1047         Dprintk("Boot done.\n");
1048
1049         /*
1050          * construct cpu_sibling_map[], so that we can tell sibling CPUs
1051          * efficiently.
1052          */
1053         for (cpu = 0; cpu < NR_CPUS; cpu++)
1054                 cpus_clear(cpu_sibling_map[cpu]);
1055
1056         for (cpu = 0; cpu < NR_CPUS; cpu++) {
1057                 int siblings = 0;
1058                 int i;
1059                 if (!cpu_isset(cpu, cpu_callout_map))
1060                         continue;
1061
1062                 if (smp_num_siblings > 1) {
1063                         for (i = 0; i < NR_CPUS; i++) {
1064                                 if (!cpu_isset(i, cpu_callout_map))
1065                                         continue;
1066                                 if (phys_proc_id[cpu] == phys_proc_id[i]) {
1067                                         siblings++;
1068                                         cpu_set(i, cpu_sibling_map[cpu]);
1069                                 }
1070                         }
1071                 } else {
1072                         siblings++;
1073                         cpu_set(cpu, cpu_sibling_map[cpu]);
1074                 }
1075
1076                 if (siblings != smp_num_siblings)
1077                         printk(KERN_WARNING "WARNING: %d siblings found for CPU%d, should be %d\n", siblings, cpu, smp_num_siblings);
1078         }
1079
1080         if (nmi_watchdog == NMI_LOCAL_APIC)
1081                 check_nmi_watchdog();
1082
1083         smpboot_setup_io_apic();
1084
1085         setup_boot_APIC_clock();
1086
1087         /*
1088          * Synchronize the TSC with the AP
1089          */
1090         if (cpu_has_tsc && cpucount && cpu_khz)
1091                 synchronize_tsc_bp();
1092 }
1093
1094 /* These are wrappers to interface to the new boot process.  Someone
1095    who understands all this stuff should rewrite it properly. --RR 15/Jul/02 */
1096 void __init smp_prepare_cpus(unsigned int max_cpus)
1097 {
1098         smp_boot_cpus(max_cpus);
1099 }
1100
1101 void __devinit smp_prepare_boot_cpu(void)
1102 {
1103         cpu_set(smp_processor_id(), cpu_online_map);
1104         cpu_set(smp_processor_id(), cpu_callout_map);
1105 }
1106
1107 int __devinit __cpu_up(unsigned int cpu)
1108 {
1109         /* This only works at boot for x86.  See "rewrite" above. */
1110         if (cpu_isset(cpu, smp_commenced_mask)) {
1111                 local_irq_enable();
1112                 return -ENOSYS;
1113         }
1114
1115         /* In case one didn't come up */
1116         if (!cpu_isset(cpu, cpu_callin_map)) {
1117                 local_irq_enable();
1118                 return -EIO;
1119         }
1120
1121         local_irq_enable();
1122         /* Unleash the CPU! */
1123         cpu_set(cpu, smp_commenced_mask);
1124         while (!cpu_isset(cpu, cpu_online_map))
1125                 mb();
1126         return 0;
1127 }
1128
1129 void __init smp_cpus_done(unsigned int max_cpus)
1130 {
1131 #ifdef CONFIG_X86_IO_APIC
1132         setup_ioapic_dest();
1133 #endif
1134         zap_low_mappings();
1135         /*
1136          * Disable executability of the SMP trampoline:
1137          */
1138         set_kernel_exec((unsigned long)trampoline_base, trampoline_exec);
1139 }
1140
1141 void __init smp_intr_init(void)
1142 {
1143         /*
1144          * IRQ0 must be given a fixed assignment and initialized,
1145          * because it's used before the IO-APIC is set up.
1146          */
1147         set_intr_gate(FIRST_DEVICE_VECTOR, interrupt[0]);
1148
1149         /*
1150          * The reschedule interrupt is a CPU-to-CPU reschedule-helper
1151          * IPI, driven by wakeup.
1152          */
1153         set_intr_gate(RESCHEDULE_VECTOR, reschedule_interrupt);
1154
1155         /* IPI for invalidation */
1156         set_intr_gate(INVALIDATE_TLB_VECTOR, invalidate_interrupt);
1157
1158         /* IPI for generic function call */
1159         set_intr_gate(CALL_FUNCTION_VECTOR, call_function_interrupt);
1160 }