Merge ../linux-2.6-watchdog-mm
[linux-drm-fsl-dcu.git] / arch / x86_64 / kernel / smpboot.c
1 /*
2  *      x86 SMP booting functions
3  *
4  *      (c) 1995 Alan Cox, Building #3 <alan@redhat.com>
5  *      (c) 1998, 1999, 2000 Ingo Molnar <mingo@redhat.com>
6  *      Copyright 2001 Andi Kleen, SuSE Labs.
7  *
8  *      Much of the core SMP work is based on previous work by Thomas Radke, to
9  *      whom a great many thanks are extended.
10  *
11  *      Thanks to Intel for making available several different Pentium,
12  *      Pentium Pro and Pentium-II/Xeon MP machines.
13  *      Original development of Linux SMP code supported by Caldera.
14  *
15  *      This code is released under the GNU General Public License version 2
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  *      Andi Kleen              :       Changed for SMP boot into long mode.
33  *              Rusty Russell   :       Hacked into shape for new "hotplug" boot process.
34  *      Andi Kleen              :       Converted to new state machine.
35  *                                      Various cleanups.
36  *                                      Probably mostly hotplug CPU ready now.
37  *      Ashok Raj                       : CPU hotplug support
38  */
39
40
41 #include <linux/init.h>
42
43 #include <linux/mm.h>
44 #include <linux/kernel_stat.h>
45 #include <linux/smp_lock.h>
46 #include <linux/bootmem.h>
47 #include <linux/thread_info.h>
48 #include <linux/module.h>
49 #include <linux/delay.h>
50 #include <linux/mc146818rtc.h>
51 #include <linux/smp.h>
52
53 #include <asm/mtrr.h>
54 #include <asm/pgalloc.h>
55 #include <asm/desc.h>
56 #include <asm/kdebug.h>
57 #include <asm/tlbflush.h>
58 #include <asm/proto.h>
59 #include <asm/nmi.h>
60 #include <asm/irq.h>
61 #include <asm/hw_irq.h>
62 #include <asm/numa.h>
63
64 /* Number of siblings per CPU package */
65 int smp_num_siblings = 1;
66 EXPORT_SYMBOL(smp_num_siblings);
67
68 /* Last level cache ID of each logical CPU */
69 u8 cpu_llc_id[NR_CPUS] __cpuinitdata  = {[0 ... NR_CPUS-1] = BAD_APICID};
70 EXPORT_SYMBOL(cpu_llc_id);
71
72 /* Bitmask of currently online CPUs */
73 cpumask_t cpu_online_map __read_mostly;
74
75 EXPORT_SYMBOL(cpu_online_map);
76
77 /*
78  * Private maps to synchronize booting between AP and BP.
79  * Probably not needed anymore, but it makes for easier debugging. -AK
80  */
81 cpumask_t cpu_callin_map;
82 cpumask_t cpu_callout_map;
83 EXPORT_SYMBOL(cpu_callout_map);
84
85 cpumask_t cpu_possible_map;
86 EXPORT_SYMBOL(cpu_possible_map);
87
88 /* Per CPU bogomips and other parameters */
89 struct cpuinfo_x86 cpu_data[NR_CPUS] __cacheline_aligned;
90 EXPORT_SYMBOL(cpu_data);
91
92 /* Set when the idlers are all forked */
93 int smp_threads_ready;
94
95 /* representing HT siblings of each logical CPU */
96 cpumask_t cpu_sibling_map[NR_CPUS] __read_mostly;
97 EXPORT_SYMBOL(cpu_sibling_map);
98
99 /* representing HT and core siblings of each logical CPU */
100 cpumask_t cpu_core_map[NR_CPUS] __read_mostly;
101 EXPORT_SYMBOL(cpu_core_map);
102
103 /*
104  * Trampoline 80x86 program as an array.
105  */
106
107 extern unsigned char trampoline_data[];
108 extern unsigned char trampoline_end[];
109
110 /* State of each CPU */
111 DEFINE_PER_CPU(int, cpu_state) = { 0 };
112
113 /*
114  * Store all idle threads, this can be reused instead of creating
115  * a new thread. Also avoids complicated thread destroy functionality
116  * for idle threads.
117  */
118 struct task_struct *idle_thread_array[NR_CPUS] __cpuinitdata ;
119
120 #define get_idle_for_cpu(x)     (idle_thread_array[(x)])
121 #define set_idle_for_cpu(x,p)   (idle_thread_array[(x)] = (p))
122
123 /*
124  * Currently trivial. Write the real->protected mode
125  * bootstrap into the page concerned. The caller
126  * has made sure it's suitably aligned.
127  */
128
129 static unsigned long __cpuinit setup_trampoline(void)
130 {
131         void *tramp = __va(SMP_TRAMPOLINE_BASE); 
132         memcpy(tramp, trampoline_data, trampoline_end - trampoline_data);
133         return virt_to_phys(tramp);
134 }
135
136 /*
137  * The bootstrap kernel entry code has set these up. Save them for
138  * a given CPU
139  */
140
141 static void __cpuinit smp_store_cpu_info(int id)
142 {
143         struct cpuinfo_x86 *c = cpu_data + id;
144
145         *c = boot_cpu_data;
146         identify_cpu(c);
147         print_cpu_info(c);
148 }
149
150 /*
151  * New Funky TSC sync algorithm borrowed from IA64.
152  * Main advantage is that it doesn't reset the TSCs fully and
153  * in general looks more robust and it works better than my earlier
154  * attempts. I believe it was written by David Mosberger. Some minor
155  * adjustments for x86-64 by me -AK
156  *
157  * Original comment reproduced below.
158  *
159  * Synchronize TSC of the current (slave) CPU with the TSC of the
160  * MASTER CPU (normally the time-keeper CPU).  We use a closed loop to
161  * eliminate the possibility of unaccounted-for errors (such as
162  * getting a machine check in the middle of a calibration step).  The
163  * basic idea is for the slave to ask the master what itc value it has
164  * and to read its own itc before and after the master responds.  Each
165  * iteration gives us three timestamps:
166  *
167  *      slave           master
168  *
169  *      t0 ---\
170  *             ---\
171  *                 --->
172  *                      tm
173  *                 /---
174  *             /---
175  *      t1 <---
176  *
177  *
178  * The goal is to adjust the slave's TSC such that tm falls exactly
179  * half-way between t0 and t1.  If we achieve this, the clocks are
180  * synchronized provided the interconnect between the slave and the
181  * master is symmetric.  Even if the interconnect were asymmetric, we
182  * would still know that the synchronization error is smaller than the
183  * roundtrip latency (t0 - t1).
184  *
185  * When the interconnect is quiet and symmetric, this lets us
186  * synchronize the TSC to within one or two cycles.  However, we can
187  * only *guarantee* that the synchronization is accurate to within a
188  * round-trip time, which is typically in the range of several hundred
189  * cycles (e.g., ~500 cycles).  In practice, this means that the TSCs
190  * are usually almost perfectly synchronized, but we shouldn't assume
191  * that the accuracy is much better than half a micro second or so.
192  *
193  * [there are other errors like the latency of RDTSC and of the
194  * WRMSR. These can also account to hundreds of cycles. So it's
195  * probably worse. It claims 153 cycles error on a dual Opteron,
196  * but I suspect the numbers are actually somewhat worse -AK]
197  */
198
199 #define MASTER  0
200 #define SLAVE   (SMP_CACHE_BYTES/8)
201
202 /* Intentionally don't use cpu_relax() while TSC synchronization
203    because we don't want to go into funky power save modi or cause
204    hypervisors to schedule us away.  Going to sleep would likely affect
205    latency and low latency is the primary objective here. -AK */
206 #define no_cpu_relax() barrier()
207
208 static __cpuinitdata DEFINE_SPINLOCK(tsc_sync_lock);
209 static volatile __cpuinitdata unsigned long go[SLAVE + 1];
210 static int notscsync __cpuinitdata;
211
212 #undef DEBUG_TSC_SYNC
213
214 #define NUM_ROUNDS      64      /* magic value */
215 #define NUM_ITERS       5       /* likewise */
216
217 /* Callback on boot CPU */
218 static __cpuinit void sync_master(void *arg)
219 {
220         unsigned long flags, i;
221
222         go[MASTER] = 0;
223
224         local_irq_save(flags);
225         {
226                 for (i = 0; i < NUM_ROUNDS*NUM_ITERS; ++i) {
227                         while (!go[MASTER])
228                                 no_cpu_relax();
229                         go[MASTER] = 0;
230                         rdtscll(go[SLAVE]);
231                 }
232         }
233         local_irq_restore(flags);
234 }
235
236 /*
237  * Return the number of cycles by which our tsc differs from the tsc
238  * on the master (time-keeper) CPU.  A positive number indicates our
239  * tsc is ahead of the master, negative that it is behind.
240  */
241 static inline long
242 get_delta(long *rt, long *master)
243 {
244         unsigned long best_t0 = 0, best_t1 = ~0UL, best_tm = 0;
245         unsigned long tcenter, t0, t1, tm;
246         int i;
247
248         for (i = 0; i < NUM_ITERS; ++i) {
249                 rdtscll(t0);
250                 go[MASTER] = 1;
251                 while (!(tm = go[SLAVE]))
252                         no_cpu_relax();
253                 go[SLAVE] = 0;
254                 rdtscll(t1);
255
256                 if (t1 - t0 < best_t1 - best_t0)
257                         best_t0 = t0, best_t1 = t1, best_tm = tm;
258         }
259
260         *rt = best_t1 - best_t0;
261         *master = best_tm - best_t0;
262
263         /* average best_t0 and best_t1 without overflow: */
264         tcenter = (best_t0/2 + best_t1/2);
265         if (best_t0 % 2 + best_t1 % 2 == 2)
266                 ++tcenter;
267         return tcenter - best_tm;
268 }
269
270 static __cpuinit void sync_tsc(unsigned int master)
271 {
272         int i, done = 0;
273         long delta, adj, adjust_latency = 0;
274         unsigned long flags, rt, master_time_stamp, bound;
275 #ifdef DEBUG_TSC_SYNC
276         static struct syncdebug {
277                 long rt;        /* roundtrip time */
278                 long master;    /* master's timestamp */
279                 long diff;      /* difference between midpoint and master's timestamp */
280                 long lat;       /* estimate of tsc adjustment latency */
281         } t[NUM_ROUNDS] __cpuinitdata;
282 #endif
283
284         printk(KERN_INFO "CPU %d: Syncing TSC to CPU %u.\n",
285                 smp_processor_id(), master);
286
287         go[MASTER] = 1;
288
289         /* It is dangerous to broadcast IPI as cpus are coming up,
290          * as they may not be ready to accept them.  So since
291          * we only need to send the ipi to the boot cpu direct
292          * the message, and avoid the race.
293          */
294         smp_call_function_single(master, sync_master, NULL, 1, 0);
295
296         while (go[MASTER])      /* wait for master to be ready */
297                 no_cpu_relax();
298
299         spin_lock_irqsave(&tsc_sync_lock, flags);
300         {
301                 for (i = 0; i < NUM_ROUNDS; ++i) {
302                         delta = get_delta(&rt, &master_time_stamp);
303                         if (delta == 0) {
304                                 done = 1;       /* let's lock on to this... */
305                                 bound = rt;
306                         }
307
308                         if (!done) {
309                                 unsigned long t;
310                                 if (i > 0) {
311                                         adjust_latency += -delta;
312                                         adj = -delta + adjust_latency/4;
313                                 } else
314                                         adj = -delta;
315
316                                 rdtscll(t);
317                                 wrmsrl(MSR_IA32_TSC, t + adj);
318                         }
319 #ifdef DEBUG_TSC_SYNC
320                         t[i].rt = rt;
321                         t[i].master = master_time_stamp;
322                         t[i].diff = delta;
323                         t[i].lat = adjust_latency/4;
324 #endif
325                 }
326         }
327         spin_unlock_irqrestore(&tsc_sync_lock, flags);
328
329 #ifdef DEBUG_TSC_SYNC
330         for (i = 0; i < NUM_ROUNDS; ++i)
331                 printk("rt=%5ld master=%5ld diff=%5ld adjlat=%5ld\n",
332                        t[i].rt, t[i].master, t[i].diff, t[i].lat);
333 #endif
334
335         printk(KERN_INFO
336                "CPU %d: synchronized TSC with CPU %u (last diff %ld cycles, "
337                "maxerr %lu cycles)\n",
338                smp_processor_id(), master, delta, rt);
339 }
340
341 static void __cpuinit tsc_sync_wait(void)
342 {
343         /*
344          * When the CPU has synchronized TSCs assume the BIOS
345          * or the hardware already synced.  Otherwise we could
346          * mess up a possible perfect synchronization with a
347          * not-quite-perfect algorithm.
348          */
349         if (notscsync || !cpu_has_tsc || !unsynchronized_tsc())
350                 return;
351         sync_tsc(0);
352 }
353
354 static __init int notscsync_setup(char *s)
355 {
356         notscsync = 1;
357         return 1;
358 }
359 __setup("notscsync", notscsync_setup);
360
361 static atomic_t init_deasserted __cpuinitdata;
362
363 /*
364  * Report back to the Boot Processor.
365  * Running on AP.
366  */
367 void __cpuinit smp_callin(void)
368 {
369         int cpuid, phys_id;
370         unsigned long timeout;
371
372         /*
373          * If waken up by an INIT in an 82489DX configuration
374          * we may get here before an INIT-deassert IPI reaches
375          * our local APIC.  We have to wait for the IPI or we'll
376          * lock up on an APIC access.
377          */
378         while (!atomic_read(&init_deasserted))
379                 cpu_relax();
380
381         /*
382          * (This works even if the APIC is not enabled.)
383          */
384         phys_id = GET_APIC_ID(apic_read(APIC_ID));
385         cpuid = smp_processor_id();
386         if (cpu_isset(cpuid, cpu_callin_map)) {
387                 panic("smp_callin: phys CPU#%d, CPU#%d already present??\n",
388                                         phys_id, cpuid);
389         }
390         Dprintk("CPU#%d (phys ID: %d) waiting for CALLOUT\n", cpuid, phys_id);
391
392         /*
393          * STARTUP IPIs are fragile beasts as they might sometimes
394          * trigger some glue motherboard logic. Complete APIC bus
395          * silence for 1 second, this overestimates the time the
396          * boot CPU is spending to send the up to 2 STARTUP IPIs
397          * by a factor of two. This should be enough.
398          */
399
400         /*
401          * Waiting 2s total for startup (udelay is not yet working)
402          */
403         timeout = jiffies + 2*HZ;
404         while (time_before(jiffies, timeout)) {
405                 /*
406                  * Has the boot CPU finished it's STARTUP sequence?
407                  */
408                 if (cpu_isset(cpuid, cpu_callout_map))
409                         break;
410                 cpu_relax();
411         }
412
413         if (!time_before(jiffies, timeout)) {
414                 panic("smp_callin: CPU%d started up but did not get a callout!\n",
415                         cpuid);
416         }
417
418         /*
419          * the boot CPU has finished the init stage and is spinning
420          * on callin_map until we finish. We are free to set up this
421          * CPU, first the APIC. (this is probably redundant on most
422          * boards)
423          */
424
425         Dprintk("CALLIN, before setup_local_APIC().\n");
426         setup_local_APIC();
427
428         /*
429          * Get our bogomips.
430          *
431          * Need to enable IRQs because it can take longer and then
432          * the NMI watchdog might kill us.
433          */
434         local_irq_enable();
435         calibrate_delay();
436         local_irq_disable();
437         Dprintk("Stack at about %p\n",&cpuid);
438
439         disable_APIC_timer();
440
441         /*
442          * Save our processor parameters
443          */
444         smp_store_cpu_info(cpuid);
445
446         /*
447          * Allow the master to continue.
448          */
449         cpu_set(cpuid, cpu_callin_map);
450 }
451
452 /* maps the cpu to the sched domain representing multi-core */
453 cpumask_t cpu_coregroup_map(int cpu)
454 {
455         struct cpuinfo_x86 *c = cpu_data + cpu;
456         /*
457          * For perf, we return last level cache shared map.
458          * And for power savings, we return cpu_core_map
459          */
460         if (sched_mc_power_savings || sched_smt_power_savings)
461                 return cpu_core_map[cpu];
462         else
463                 return c->llc_shared_map;
464 }
465
466 /* representing cpus for which sibling maps can be computed */
467 static cpumask_t cpu_sibling_setup_map;
468
469 static inline void set_cpu_sibling_map(int cpu)
470 {
471         int i;
472         struct cpuinfo_x86 *c = cpu_data;
473
474         cpu_set(cpu, cpu_sibling_setup_map);
475
476         if (smp_num_siblings > 1) {
477                 for_each_cpu_mask(i, cpu_sibling_setup_map) {
478                         if (c[cpu].phys_proc_id == c[i].phys_proc_id &&
479                             c[cpu].cpu_core_id == c[i].cpu_core_id) {
480                                 cpu_set(i, cpu_sibling_map[cpu]);
481                                 cpu_set(cpu, cpu_sibling_map[i]);
482                                 cpu_set(i, cpu_core_map[cpu]);
483                                 cpu_set(cpu, cpu_core_map[i]);
484                                 cpu_set(i, c[cpu].llc_shared_map);
485                                 cpu_set(cpu, c[i].llc_shared_map);
486                         }
487                 }
488         } else {
489                 cpu_set(cpu, cpu_sibling_map[cpu]);
490         }
491
492         cpu_set(cpu, c[cpu].llc_shared_map);
493
494         if (current_cpu_data.x86_max_cores == 1) {
495                 cpu_core_map[cpu] = cpu_sibling_map[cpu];
496                 c[cpu].booted_cores = 1;
497                 return;
498         }
499
500         for_each_cpu_mask(i, cpu_sibling_setup_map) {
501                 if (cpu_llc_id[cpu] != BAD_APICID &&
502                     cpu_llc_id[cpu] == cpu_llc_id[i]) {
503                         cpu_set(i, c[cpu].llc_shared_map);
504                         cpu_set(cpu, c[i].llc_shared_map);
505                 }
506                 if (c[cpu].phys_proc_id == c[i].phys_proc_id) {
507                         cpu_set(i, cpu_core_map[cpu]);
508                         cpu_set(cpu, cpu_core_map[i]);
509                         /*
510                          *  Does this new cpu bringup a new core?
511                          */
512                         if (cpus_weight(cpu_sibling_map[cpu]) == 1) {
513                                 /*
514                                  * for each core in package, increment
515                                  * the booted_cores for this new cpu
516                                  */
517                                 if (first_cpu(cpu_sibling_map[i]) == i)
518                                         c[cpu].booted_cores++;
519                                 /*
520                                  * increment the core count for all
521                                  * the other cpus in this package
522                                  */
523                                 if (i != cpu)
524                                         c[i].booted_cores++;
525                         } else if (i != cpu && !c[cpu].booted_cores)
526                                 c[cpu].booted_cores = c[i].booted_cores;
527                 }
528         }
529 }
530
531 /*
532  * Setup code on secondary processor (after comming out of the trampoline)
533  */
534 void __cpuinit start_secondary(void)
535 {
536         /*
537          * Dont put anything before smp_callin(), SMP
538          * booting is too fragile that we want to limit the
539          * things done here to the most necessary things.
540          */
541         cpu_init();
542         preempt_disable();
543         smp_callin();
544
545         /* otherwise gcc will move up the smp_processor_id before the cpu_init */
546         barrier();
547
548         Dprintk("cpu %d: setting up apic clock\n", smp_processor_id());         
549         setup_secondary_APIC_clock();
550
551         Dprintk("cpu %d: enabling apic timer\n", smp_processor_id());
552
553         if (nmi_watchdog == NMI_IO_APIC) {
554                 disable_8259A_irq(0);
555                 enable_NMI_through_LVT0(NULL);
556                 enable_8259A_irq(0);
557         }
558
559         enable_APIC_timer();
560
561         /*
562          * The sibling maps must be set before turing the online map on for
563          * this cpu
564          */
565         set_cpu_sibling_map(smp_processor_id());
566
567         /* 
568          * Wait for TSC sync to not schedule things before.
569          * We still process interrupts, which could see an inconsistent
570          * time in that window unfortunately. 
571          * Do this here because TSC sync has global unprotected state.
572          */
573         tsc_sync_wait();
574
575         /*
576          * We need to hold call_lock, so there is no inconsistency
577          * between the time smp_call_function() determines number of
578          * IPI receipients, and the time when the determination is made
579          * for which cpus receive the IPI in genapic_flat.c. Holding this
580          * lock helps us to not include this cpu in a currently in progress
581          * smp_call_function().
582          */
583         lock_ipi_call_lock();
584         spin_lock(&vector_lock);
585
586         /* Setup the per cpu irq handling data structures */
587         __setup_vector_irq(smp_processor_id());
588         /*
589          * Allow the master to continue.
590          */
591         cpu_set(smp_processor_id(), cpu_online_map);
592         per_cpu(cpu_state, smp_processor_id()) = CPU_ONLINE;
593         spin_unlock(&vector_lock);
594         unlock_ipi_call_lock();
595
596         cpu_idle();
597 }
598
599 extern volatile unsigned long init_rsp;
600 extern void (*initial_code)(void);
601
602 #ifdef APIC_DEBUG
603 static void inquire_remote_apic(int apicid)
604 {
605         unsigned i, regs[] = { APIC_ID >> 4, APIC_LVR >> 4, APIC_SPIV >> 4 };
606         char *names[] = { "ID", "VERSION", "SPIV" };
607         int timeout, status;
608
609         printk(KERN_INFO "Inquiring remote APIC #%d...\n", apicid);
610
611         for (i = 0; i < sizeof(regs) / sizeof(*regs); i++) {
612                 printk("... APIC #%d %s: ", apicid, names[i]);
613
614                 /*
615                  * Wait for idle.
616                  */
617                 apic_wait_icr_idle();
618
619                 apic_write(APIC_ICR2, SET_APIC_DEST_FIELD(apicid));
620                 apic_write(APIC_ICR, APIC_DM_REMRD | regs[i]);
621
622                 timeout = 0;
623                 do {
624                         udelay(100);
625                         status = apic_read(APIC_ICR) & APIC_ICR_RR_MASK;
626                 } while (status == APIC_ICR_RR_INPROG && timeout++ < 1000);
627
628                 switch (status) {
629                 case APIC_ICR_RR_VALID:
630                         status = apic_read(APIC_RRR);
631                         printk("%08x\n", status);
632                         break;
633                 default:
634                         printk("failed\n");
635                 }
636         }
637 }
638 #endif
639
640 /*
641  * Kick the secondary to wake up.
642  */
643 static int __cpuinit wakeup_secondary_via_INIT(int phys_apicid, unsigned int start_rip)
644 {
645         unsigned long send_status = 0, accept_status = 0;
646         int maxlvt, timeout, num_starts, j;
647
648         Dprintk("Asserting INIT.\n");
649
650         /*
651          * Turn INIT on target chip
652          */
653         apic_write(APIC_ICR2, SET_APIC_DEST_FIELD(phys_apicid));
654
655         /*
656          * Send IPI
657          */
658         apic_write(APIC_ICR, APIC_INT_LEVELTRIG | APIC_INT_ASSERT
659                                 | APIC_DM_INIT);
660
661         Dprintk("Waiting for send to finish...\n");
662         timeout = 0;
663         do {
664                 Dprintk("+");
665                 udelay(100);
666                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
667         } while (send_status && (timeout++ < 1000));
668
669         mdelay(10);
670
671         Dprintk("Deasserting INIT.\n");
672
673         /* Target chip */
674         apic_write(APIC_ICR2, SET_APIC_DEST_FIELD(phys_apicid));
675
676         /* Send IPI */
677         apic_write(APIC_ICR, APIC_INT_LEVELTRIG | APIC_DM_INIT);
678
679         Dprintk("Waiting for send to finish...\n");
680         timeout = 0;
681         do {
682                 Dprintk("+");
683                 udelay(100);
684                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
685         } while (send_status && (timeout++ < 1000));
686
687         mb();
688         atomic_set(&init_deasserted, 1);
689
690         num_starts = 2;
691
692         /*
693          * Run STARTUP IPI loop.
694          */
695         Dprintk("#startup loops: %d.\n", num_starts);
696
697         maxlvt = get_maxlvt();
698
699         for (j = 1; j <= num_starts; j++) {
700                 Dprintk("Sending STARTUP #%d.\n",j);
701                 apic_write(APIC_ESR, 0);
702                 apic_read(APIC_ESR);
703                 Dprintk("After apic_write.\n");
704
705                 /*
706                  * STARTUP IPI
707                  */
708
709                 /* Target chip */
710                 apic_write(APIC_ICR2, SET_APIC_DEST_FIELD(phys_apicid));
711
712                 /* Boot on the stack */
713                 /* Kick the second */
714                 apic_write(APIC_ICR, APIC_DM_STARTUP | (start_rip >> 12));
715
716                 /*
717                  * Give the other CPU some time to accept the IPI.
718                  */
719                 udelay(300);
720
721                 Dprintk("Startup point 1.\n");
722
723                 Dprintk("Waiting for send to finish...\n");
724                 timeout = 0;
725                 do {
726                         Dprintk("+");
727                         udelay(100);
728                         send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
729                 } while (send_status && (timeout++ < 1000));
730
731                 /*
732                  * Give the other CPU some time to accept the IPI.
733                  */
734                 udelay(200);
735                 /*
736                  * Due to the Pentium erratum 3AP.
737                  */
738                 if (maxlvt > 3) {
739                         apic_write(APIC_ESR, 0);
740                 }
741                 accept_status = (apic_read(APIC_ESR) & 0xEF);
742                 if (send_status || accept_status)
743                         break;
744         }
745         Dprintk("After Startup.\n");
746
747         if (send_status)
748                 printk(KERN_ERR "APIC never delivered???\n");
749         if (accept_status)
750                 printk(KERN_ERR "APIC delivery error (%lx).\n", accept_status);
751
752         return (send_status | accept_status);
753 }
754
755 struct create_idle {
756         struct task_struct *idle;
757         struct completion done;
758         int cpu;
759 };
760
761 void do_fork_idle(void *_c_idle)
762 {
763         struct create_idle *c_idle = _c_idle;
764
765         c_idle->idle = fork_idle(c_idle->cpu);
766         complete(&c_idle->done);
767 }
768
769 /*
770  * Boot one CPU.
771  */
772 static int __cpuinit do_boot_cpu(int cpu, int apicid)
773 {
774         unsigned long boot_error;
775         int timeout;
776         unsigned long start_rip;
777         struct create_idle c_idle = {
778                 .cpu = cpu,
779                 .done = COMPLETION_INITIALIZER_ONSTACK(c_idle.done),
780         };
781         DECLARE_WORK(work, do_fork_idle, &c_idle);
782
783         /* allocate memory for gdts of secondary cpus. Hotplug is considered */
784         if (!cpu_gdt_descr[cpu].address &&
785                 !(cpu_gdt_descr[cpu].address = get_zeroed_page(GFP_KERNEL))) {
786                 printk(KERN_ERR "Failed to allocate GDT for CPU %d\n", cpu);
787                 return -1;
788         }
789
790         /* Allocate node local memory for AP pdas */
791         if (cpu_pda(cpu) == &boot_cpu_pda[cpu]) {
792                 struct x8664_pda *newpda, *pda;
793                 int node = cpu_to_node(cpu);
794                 pda = cpu_pda(cpu);
795                 newpda = kmalloc_node(sizeof (struct x8664_pda), GFP_ATOMIC,
796                                       node);
797                 if (newpda) {
798                         memcpy(newpda, pda, sizeof (struct x8664_pda));
799                         cpu_pda(cpu) = newpda;
800                 } else
801                         printk(KERN_ERR
802                 "Could not allocate node local PDA for CPU %d on node %d\n",
803                                 cpu, node);
804         }
805
806         alternatives_smp_switch(1);
807
808         c_idle.idle = get_idle_for_cpu(cpu);
809
810         if (c_idle.idle) {
811                 c_idle.idle->thread.rsp = (unsigned long) (((struct pt_regs *)
812                         (THREAD_SIZE +  task_stack_page(c_idle.idle))) - 1);
813                 init_idle(c_idle.idle, cpu);
814                 goto do_rest;
815         }
816
817         /*
818          * During cold boot process, keventd thread is not spun up yet.
819          * When we do cpu hot-add, we create idle threads on the fly, we should
820          * not acquire any attributes from the calling context. Hence the clean
821          * way to create kernel_threads() is to do that from keventd().
822          * We do the current_is_keventd() due to the fact that ACPI notifier
823          * was also queuing to keventd() and when the caller is already running
824          * in context of keventd(), we would end up with locking up the keventd
825          * thread.
826          */
827         if (!keventd_up() || current_is_keventd())
828                 work.func(work.data);
829         else {
830                 schedule_work(&work);
831                 wait_for_completion(&c_idle.done);
832         }
833
834         if (IS_ERR(c_idle.idle)) {
835                 printk("failed fork for CPU %d\n", cpu);
836                 return PTR_ERR(c_idle.idle);
837         }
838
839         set_idle_for_cpu(cpu, c_idle.idle);
840
841 do_rest:
842
843         cpu_pda(cpu)->pcurrent = c_idle.idle;
844
845         start_rip = setup_trampoline();
846
847         init_rsp = c_idle.idle->thread.rsp;
848         per_cpu(init_tss,cpu).rsp0 = init_rsp;
849         initial_code = start_secondary;
850         clear_tsk_thread_flag(c_idle.idle, TIF_FORK);
851
852         printk(KERN_INFO "Booting processor %d/%d APIC 0x%x\n", cpu,
853                 cpus_weight(cpu_present_map),
854                 apicid);
855
856         /*
857          * This grunge runs the startup process for
858          * the targeted processor.
859          */
860
861         atomic_set(&init_deasserted, 0);
862
863         Dprintk("Setting warm reset code and vector.\n");
864
865         CMOS_WRITE(0xa, 0xf);
866         local_flush_tlb();
867         Dprintk("1.\n");
868         *((volatile unsigned short *) phys_to_virt(0x469)) = start_rip >> 4;
869         Dprintk("2.\n");
870         *((volatile unsigned short *) phys_to_virt(0x467)) = start_rip & 0xf;
871         Dprintk("3.\n");
872
873         /*
874          * Be paranoid about clearing APIC errors.
875          */
876         apic_write(APIC_ESR, 0);
877         apic_read(APIC_ESR);
878
879         /*
880          * Status is now clean
881          */
882         boot_error = 0;
883
884         /*
885          * Starting actual IPI sequence...
886          */
887         boot_error = wakeup_secondary_via_INIT(apicid, start_rip);
888
889         if (!boot_error) {
890                 /*
891                  * allow APs to start initializing.
892                  */
893                 Dprintk("Before Callout %d.\n", cpu);
894                 cpu_set(cpu, cpu_callout_map);
895                 Dprintk("After Callout %d.\n", cpu);
896
897                 /*
898                  * Wait 5s total for a response
899                  */
900                 for (timeout = 0; timeout < 50000; timeout++) {
901                         if (cpu_isset(cpu, cpu_callin_map))
902                                 break;  /* It has booted */
903                         udelay(100);
904                 }
905
906                 if (cpu_isset(cpu, cpu_callin_map)) {
907                         /* number CPUs logically, starting from 1 (BSP is 0) */
908                         Dprintk("CPU has booted.\n");
909                 } else {
910                         boot_error = 1;
911                         if (*((volatile unsigned char *)phys_to_virt(SMP_TRAMPOLINE_BASE))
912                                         == 0xA5)
913                                 /* trampoline started but...? */
914                                 printk("Stuck ??\n");
915                         else
916                                 /* trampoline code not run */
917                                 printk("Not responding.\n");
918 #ifdef APIC_DEBUG
919                         inquire_remote_apic(apicid);
920 #endif
921                 }
922         }
923         if (boot_error) {
924                 cpu_clear(cpu, cpu_callout_map); /* was set here (do_boot_cpu()) */
925                 clear_bit(cpu, &cpu_initialized); /* was set by cpu_init() */
926                 clear_node_cpumask(cpu); /* was set by numa_add_cpu */
927                 cpu_clear(cpu, cpu_present_map);
928                 cpu_clear(cpu, cpu_possible_map);
929                 x86_cpu_to_apicid[cpu] = BAD_APICID;
930                 x86_cpu_to_log_apicid[cpu] = BAD_APICID;
931                 return -EIO;
932         }
933
934         return 0;
935 }
936
937 cycles_t cacheflush_time;
938 unsigned long cache_decay_ticks;
939
940 /*
941  * Cleanup possible dangling ends...
942  */
943 static __cpuinit void smp_cleanup_boot(void)
944 {
945         /*
946          * Paranoid:  Set warm reset code and vector here back
947          * to default values.
948          */
949         CMOS_WRITE(0, 0xf);
950
951         /*
952          * Reset trampoline flag
953          */
954         *((volatile int *) phys_to_virt(0x467)) = 0;
955 }
956
957 /*
958  * Fall back to non SMP mode after errors.
959  *
960  * RED-PEN audit/test this more. I bet there is more state messed up here.
961  */
962 static __init void disable_smp(void)
963 {
964         cpu_present_map = cpumask_of_cpu(0);
965         cpu_possible_map = cpumask_of_cpu(0);
966         if (smp_found_config)
967                 phys_cpu_present_map = physid_mask_of_physid(boot_cpu_id);
968         else
969                 phys_cpu_present_map = physid_mask_of_physid(0);
970         cpu_set(0, cpu_sibling_map[0]);
971         cpu_set(0, cpu_core_map[0]);
972 }
973
974 #ifdef CONFIG_HOTPLUG_CPU
975
976 int additional_cpus __initdata = -1;
977
978 /*
979  * cpu_possible_map should be static, it cannot change as cpu's
980  * are onlined, or offlined. The reason is per-cpu data-structures
981  * are allocated by some modules at init time, and dont expect to
982  * do this dynamically on cpu arrival/departure.
983  * cpu_present_map on the other hand can change dynamically.
984  * In case when cpu_hotplug is not compiled, then we resort to current
985  * behaviour, which is cpu_possible == cpu_present.
986  * - Ashok Raj
987  *
988  * Three ways to find out the number of additional hotplug CPUs:
989  * - If the BIOS specified disabled CPUs in ACPI/mptables use that.
990  * - The user can overwrite it with additional_cpus=NUM
991  * - Otherwise don't reserve additional CPUs.
992  * We do this because additional CPUs waste a lot of memory.
993  * -AK
994  */
995 __init void prefill_possible_map(void)
996 {
997         int i;
998         int possible;
999
1000         if (additional_cpus == -1) {
1001                 if (disabled_cpus > 0)
1002                         additional_cpus = disabled_cpus;
1003                 else
1004                         additional_cpus = 0;
1005         }
1006         possible = num_processors + additional_cpus;
1007         if (possible > NR_CPUS) 
1008                 possible = NR_CPUS;
1009
1010         printk(KERN_INFO "SMP: Allowing %d CPUs, %d hotplug CPUs\n",
1011                 possible,
1012                 max_t(int, possible - num_processors, 0));
1013
1014         for (i = 0; i < possible; i++)
1015                 cpu_set(i, cpu_possible_map);
1016 }
1017 #endif
1018
1019 /*
1020  * Various sanity checks.
1021  */
1022 static int __init smp_sanity_check(unsigned max_cpus)
1023 {
1024         if (!physid_isset(hard_smp_processor_id(), phys_cpu_present_map)) {
1025                 printk("weird, boot CPU (#%d) not listed by the BIOS.\n",
1026                        hard_smp_processor_id());
1027                 physid_set(hard_smp_processor_id(), phys_cpu_present_map);
1028         }
1029
1030         /*
1031          * If we couldn't find an SMP configuration at boot time,
1032          * get out of here now!
1033          */
1034         if (!smp_found_config) {
1035                 printk(KERN_NOTICE "SMP motherboard not detected.\n");
1036                 disable_smp();
1037                 if (APIC_init_uniprocessor())
1038                         printk(KERN_NOTICE "Local APIC not detected."
1039                                            " Using dummy APIC emulation.\n");
1040                 return -1;
1041         }
1042
1043         /*
1044          * Should not be necessary because the MP table should list the boot
1045          * CPU too, but we do it for the sake of robustness anyway.
1046          */
1047         if (!physid_isset(boot_cpu_id, phys_cpu_present_map)) {
1048                 printk(KERN_NOTICE "weird, boot CPU (#%d) not listed by the BIOS.\n",
1049                                                                  boot_cpu_id);
1050                 physid_set(hard_smp_processor_id(), phys_cpu_present_map);
1051         }
1052
1053         /*
1054          * If we couldn't find a local APIC, then get out of here now!
1055          */
1056         if (!cpu_has_apic) {
1057                 printk(KERN_ERR "BIOS bug, local APIC #%d not detected!...\n",
1058                         boot_cpu_id);
1059                 printk(KERN_ERR "... forcing use of dummy APIC emulation. (tell your hw vendor)\n");
1060                 nr_ioapics = 0;
1061                 return -1;
1062         }
1063
1064         /*
1065          * If SMP should be disabled, then really disable it!
1066          */
1067         if (!max_cpus) {
1068                 printk(KERN_INFO "SMP mode deactivated, forcing use of dummy APIC emulation.\n");
1069                 nr_ioapics = 0;
1070                 return -1;
1071         }
1072
1073         return 0;
1074 }
1075
1076 /*
1077  * Prepare for SMP bootup.  The MP table or ACPI has been read
1078  * earlier.  Just do some sanity checking here and enable APIC mode.
1079  */
1080 void __init smp_prepare_cpus(unsigned int max_cpus)
1081 {
1082         nmi_watchdog_default();
1083         current_cpu_data = boot_cpu_data;
1084         current_thread_info()->cpu = 0;  /* needed? */
1085         set_cpu_sibling_map(0);
1086
1087         if (smp_sanity_check(max_cpus) < 0) {
1088                 printk(KERN_INFO "SMP disabled\n");
1089                 disable_smp();
1090                 return;
1091         }
1092
1093
1094         /*
1095          * Switch from PIC to APIC mode.
1096          */
1097         setup_local_APIC();
1098
1099         if (GET_APIC_ID(apic_read(APIC_ID)) != boot_cpu_id) {
1100                 panic("Boot APIC ID in local APIC unexpected (%d vs %d)",
1101                       GET_APIC_ID(apic_read(APIC_ID)), boot_cpu_id);
1102                 /* Or can we switch back to PIC here? */
1103         }
1104
1105         /*
1106          * Now start the IO-APICs
1107          */
1108         if (!skip_ioapic_setup && nr_ioapics)
1109                 setup_IO_APIC();
1110         else
1111                 nr_ioapics = 0;
1112
1113         /*
1114          * Set up local APIC timer on boot CPU.
1115          */
1116
1117         setup_boot_APIC_clock();
1118 }
1119
1120 /*
1121  * Early setup to make printk work.
1122  */
1123 void __init smp_prepare_boot_cpu(void)
1124 {
1125         int me = smp_processor_id();
1126         cpu_set(me, cpu_online_map);
1127         cpu_set(me, cpu_callout_map);
1128         per_cpu(cpu_state, me) = CPU_ONLINE;
1129 }
1130
1131 /*
1132  * Entry point to boot a CPU.
1133  */
1134 int __cpuinit __cpu_up(unsigned int cpu)
1135 {
1136         int err;
1137         int apicid = cpu_present_to_apicid(cpu);
1138
1139         WARN_ON(irqs_disabled());
1140
1141         Dprintk("++++++++++++++++++++=_---CPU UP  %u\n", cpu);
1142
1143         if (apicid == BAD_APICID || apicid == boot_cpu_id ||
1144             !physid_isset(apicid, phys_cpu_present_map)) {
1145                 printk("__cpu_up: bad cpu %d\n", cpu);
1146                 return -EINVAL;
1147         }
1148
1149         /*
1150          * Already booted CPU?
1151          */
1152         if (cpu_isset(cpu, cpu_callin_map)) {
1153                 Dprintk("do_boot_cpu %d Already started\n", cpu);
1154                 return -ENOSYS;
1155         }
1156
1157         per_cpu(cpu_state, cpu) = CPU_UP_PREPARE;
1158         /* Boot it! */
1159         err = do_boot_cpu(cpu, apicid);
1160         if (err < 0) {
1161                 Dprintk("do_boot_cpu failed %d\n", err);
1162                 return err;
1163         }
1164
1165         /* Unleash the CPU! */
1166         Dprintk("waiting for cpu %d\n", cpu);
1167
1168         while (!cpu_isset(cpu, cpu_online_map))
1169                 cpu_relax();
1170         err = 0;
1171
1172         return err;
1173 }
1174
1175 /*
1176  * Finish the SMP boot.
1177  */
1178 void __init smp_cpus_done(unsigned int max_cpus)
1179 {
1180         smp_cleanup_boot();
1181         setup_ioapic_dest();
1182         check_nmi_watchdog();
1183         time_init_gtod();
1184 }
1185
1186 #ifdef CONFIG_HOTPLUG_CPU
1187
1188 static void remove_siblinginfo(int cpu)
1189 {
1190         int sibling;
1191         struct cpuinfo_x86 *c = cpu_data;
1192
1193         for_each_cpu_mask(sibling, cpu_core_map[cpu]) {
1194                 cpu_clear(cpu, cpu_core_map[sibling]);
1195                 /*
1196                  * last thread sibling in this cpu core going down
1197                  */
1198                 if (cpus_weight(cpu_sibling_map[cpu]) == 1)
1199                         c[sibling].booted_cores--;
1200         }
1201                         
1202         for_each_cpu_mask(sibling, cpu_sibling_map[cpu])
1203                 cpu_clear(cpu, cpu_sibling_map[sibling]);
1204         cpus_clear(cpu_sibling_map[cpu]);
1205         cpus_clear(cpu_core_map[cpu]);
1206         c[cpu].phys_proc_id = 0;
1207         c[cpu].cpu_core_id = 0;
1208         cpu_clear(cpu, cpu_sibling_setup_map);
1209 }
1210
1211 void remove_cpu_from_maps(void)
1212 {
1213         int cpu = smp_processor_id();
1214
1215         cpu_clear(cpu, cpu_callout_map);
1216         cpu_clear(cpu, cpu_callin_map);
1217         clear_bit(cpu, &cpu_initialized); /* was set by cpu_init() */
1218         clear_node_cpumask(cpu);
1219 }
1220
1221 int __cpu_disable(void)
1222 {
1223         int cpu = smp_processor_id();
1224
1225         /*
1226          * Perhaps use cpufreq to drop frequency, but that could go
1227          * into generic code.
1228          *
1229          * We won't take down the boot processor on i386 due to some
1230          * interrupts only being able to be serviced by the BSP.
1231          * Especially so if we're not using an IOAPIC   -zwane
1232          */
1233         if (cpu == 0)
1234                 return -EBUSY;
1235
1236         if (nmi_watchdog == NMI_LOCAL_APIC)
1237                 stop_apic_nmi_watchdog(NULL);
1238         clear_local_APIC();
1239
1240         /*
1241          * HACK:
1242          * Allow any queued timer interrupts to get serviced
1243          * This is only a temporary solution until we cleanup
1244          * fixup_irqs as we do for IA64.
1245          */
1246         local_irq_enable();
1247         mdelay(1);
1248
1249         local_irq_disable();
1250         remove_siblinginfo(cpu);
1251
1252         spin_lock(&vector_lock);
1253         /* It's now safe to remove this processor from the online map */
1254         cpu_clear(cpu, cpu_online_map);
1255         spin_unlock(&vector_lock);
1256         remove_cpu_from_maps();
1257         fixup_irqs(cpu_online_map);
1258         return 0;
1259 }
1260
1261 void __cpu_die(unsigned int cpu)
1262 {
1263         /* We don't do anything here: idle task is faking death itself. */
1264         unsigned int i;
1265
1266         for (i = 0; i < 10; i++) {
1267                 /* They ack this in play_dead by setting CPU_DEAD */
1268                 if (per_cpu(cpu_state, cpu) == CPU_DEAD) {
1269                         printk ("CPU %d is now offline\n", cpu);
1270                         if (1 == num_online_cpus())
1271                                 alternatives_smp_switch(0);
1272                         return;
1273                 }
1274                 msleep(100);
1275         }
1276         printk(KERN_ERR "CPU %u didn't die...\n", cpu);
1277 }
1278
1279 static __init int setup_additional_cpus(char *s)
1280 {
1281         return s && get_option(&s, &additional_cpus) ? 0 : -EINVAL;
1282 }
1283 early_param("additional_cpus", setup_additional_cpus);
1284
1285 #else /* ... !CONFIG_HOTPLUG_CPU */
1286
1287 int __cpu_disable(void)
1288 {
1289         return -ENOSYS;
1290 }
1291
1292 void __cpu_die(unsigned int cpu)
1293 {
1294         /* We said "no" in __cpu_disable */
1295         BUG();
1296 }
1297 #endif /* CONFIG_HOTPLUG_CPU */