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