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