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