]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - arch/x86/kernel/apic_32.c
x86: make apic_32/64.c more like
[linux-2.6-omap-h63xx.git] / arch / x86 / kernel / apic_32.c
1 /*
2  *      Local APIC handling, local APIC timers
3  *
4  *      (c) 1999, 2000 Ingo Molnar <mingo@redhat.com>
5  *
6  *      Fixes
7  *      Maciej W. Rozycki       :       Bits for genuine 82489DX APICs;
8  *                                      thanks to Eric Gilmore
9  *                                      and Rolf G. Tews
10  *                                      for testing these extensively.
11  *      Maciej W. Rozycki       :       Various updates and fixes.
12  *      Mikael Pettersson       :       Power Management for UP-APIC.
13  *      Pavel Machek and
14  *      Mikael Pettersson       :       PM converted to driver model.
15  */
16
17 #include <linux/init.h>
18
19 #include <linux/mm.h>
20 #include <linux/delay.h>
21 #include <linux/bootmem.h>
22 #include <linux/interrupt.h>
23 #include <linux/mc146818rtc.h>
24 #include <linux/kernel_stat.h>
25 #include <linux/sysdev.h>
26 #include <linux/cpu.h>
27 #include <linux/clockchips.h>
28 #include <linux/acpi_pmtmr.h>
29 #include <linux/module.h>
30 #include <linux/dmi.h>
31
32 #include <asm/atomic.h>
33 #include <asm/smp.h>
34 #include <asm/mtrr.h>
35 #include <asm/mpspec.h>
36 #include <asm/desc.h>
37 #include <asm/arch_hooks.h>
38 #include <asm/hpet.h>
39 #include <asm/i8253.h>
40 #include <asm/nmi.h>
41
42 #include <mach_apic.h>
43 #include <mach_apicdef.h>
44 #include <mach_ipi.h>
45
46 /*
47  * Sanity check
48  */
49 #if ((SPURIOUS_APIC_VECTOR & 0x0F) != 0x0F)
50 # error SPURIOUS_APIC_VECTOR definition error
51 #endif
52
53 #ifdef CONFIG_X86_32
54 /*
55  * Knob to control our willingness to enable the local APIC.
56  *
57  * +1=force-enable
58  */
59 static int force_enable_local_apic;
60 /*
61  * APIC command line parameters
62  */
63 static int __init parse_lapic(char *arg)
64 {
65         force_enable_local_apic = 1;
66         return 0;
67 }
68 early_param("lapic", parse_lapic);
69 /* Local APIC was disabled by the BIOS and enabled by the kernel */
70 static int enabled_via_apicbase;
71
72 #endif
73
74 #ifdef CONFIG_X86_64
75 static int apic_calibrate_pmtmr __initdata;
76 static __init int setup_apicpmtimer(char *s)
77 {
78         apic_calibrate_pmtmr = 1;
79         notsc_setup(NULL);
80         return 0;
81 }
82 __setup("apicpmtimer", setup_apicpmtimer);
83 #endif
84
85 unsigned long mp_lapic_addr;
86 int disable_apic;
87 /* Disable local APIC timer from the kernel commandline or via dmi quirk */
88 static int disable_apic_timer __cpuinitdata;
89 /* Local APIC timer works in C2 */
90 int local_apic_timer_c2_ok;
91 EXPORT_SYMBOL_GPL(local_apic_timer_c2_ok);
92
93 int first_system_vector = 0xfe;
94
95 char system_vectors[NR_VECTORS] = { [0 ... NR_VECTORS-1] = SYS_VECTOR_FREE};
96
97 /*
98  * Debug level, exported for io_apic.c
99  */
100 unsigned int apic_verbosity;
101
102 int pic_mode;
103
104 /* Have we found an MP table */
105 int smp_found_config;
106
107 static struct resource lapic_resource = {
108         .name = "Local APIC",
109         .flags = IORESOURCE_MEM | IORESOURCE_BUSY,
110 };
111
112 static unsigned int calibration_result;
113
114 static int lapic_next_event(unsigned long delta,
115                             struct clock_event_device *evt);
116 static void lapic_timer_setup(enum clock_event_mode mode,
117                               struct clock_event_device *evt);
118 static void lapic_timer_broadcast(cpumask_t mask);
119 static void apic_pm_activate(void);
120
121 /*
122  * The local apic timer can be used for any function which is CPU local.
123  */
124 static struct clock_event_device lapic_clockevent = {
125         .name           = "lapic",
126         .features       = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT
127                         | CLOCK_EVT_FEAT_C3STOP | CLOCK_EVT_FEAT_DUMMY,
128         .shift          = 32,
129         .set_mode       = lapic_timer_setup,
130         .set_next_event = lapic_next_event,
131         .broadcast      = lapic_timer_broadcast,
132         .rating         = 100,
133         .irq            = -1,
134 };
135 static DEFINE_PER_CPU(struct clock_event_device, lapic_events);
136
137 static unsigned long apic_phys;
138
139 /*
140  * Get the LAPIC version
141  */
142 static inline int lapic_get_version(void)
143 {
144         return GET_APIC_VERSION(apic_read(APIC_LVR));
145 }
146
147 /*
148  * Check, if the APIC is integrated or a separate chip
149  */
150 static inline int lapic_is_integrated(void)
151 {
152 #ifdef CONFIG_X86_64
153         return 1;
154 #else
155         return APIC_INTEGRATED(lapic_get_version());
156 #endif
157 }
158
159 /*
160  * Check, whether this is a modern or a first generation APIC
161  */
162 static int modern_apic(void)
163 {
164         /* AMD systems use old APIC versions, so check the CPU */
165         if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD &&
166             boot_cpu_data.x86 >= 0xf)
167                 return 1;
168         return lapic_get_version() >= 0x14;
169 }
170
171 /*
172  * Paravirt kernels also might be using these below ops. So we still
173  * use generic apic_read()/apic_write(), which might be pointing to different
174  * ops in PARAVIRT case.
175  */
176 void xapic_wait_icr_idle(void)
177 {
178         while (apic_read(APIC_ICR) & APIC_ICR_BUSY)
179                 cpu_relax();
180 }
181
182 u32 safe_xapic_wait_icr_idle(void)
183 {
184         u32 send_status;
185         int timeout;
186
187         timeout = 0;
188         do {
189                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
190                 if (!send_status)
191                         break;
192                 udelay(100);
193         } while (timeout++ < 1000);
194
195         return send_status;
196 }
197
198 void xapic_icr_write(u32 low, u32 id)
199 {
200         apic_write(APIC_ICR2, SET_APIC_DEST_FIELD(id));
201         apic_write(APIC_ICR, low);
202 }
203
204 u64 xapic_icr_read(void)
205 {
206         u32 icr1, icr2;
207
208         icr2 = apic_read(APIC_ICR2);
209         icr1 = apic_read(APIC_ICR);
210
211         return icr1 | ((u64)icr2 << 32);
212 }
213
214 static struct apic_ops xapic_ops = {
215         .read = native_apic_mem_read,
216         .write = native_apic_mem_write,
217         .icr_read = xapic_icr_read,
218         .icr_write = xapic_icr_write,
219         .wait_icr_idle = xapic_wait_icr_idle,
220         .safe_wait_icr_idle = safe_xapic_wait_icr_idle,
221 };
222
223 struct apic_ops __read_mostly *apic_ops = &xapic_ops;
224 EXPORT_SYMBOL_GPL(apic_ops);
225
226 /**
227  * enable_NMI_through_LVT0 - enable NMI through local vector table 0
228  */
229 void __cpuinit enable_NMI_through_LVT0(void)
230 {
231         unsigned int v;
232
233         /* unmask and set to NMI */
234         v = APIC_DM_NMI;
235
236         /* Level triggered for 82489DX (32bit mode) */
237         if (!lapic_is_integrated())
238                 v |= APIC_LVT_LEVEL_TRIGGER;
239
240         apic_write(APIC_LVT0, v);
241 }
242
243 #ifdef CONFIG_X86_32
244 /**
245  * get_physical_broadcast - Get number of physical broadcast IDs
246  */
247 int get_physical_broadcast(void)
248 {
249         return modern_apic() ? 0xff : 0xf;
250 }
251 #endif
252
253 /**
254  * lapic_get_maxlvt - get the maximum number of local vector table entries
255  */
256 int lapic_get_maxlvt(void)
257 {
258         unsigned int v;
259
260         v = apic_read(APIC_LVR);
261         /*
262          * - we always have APIC integrated on 64bit mode
263          * - 82489DXs do not report # of LVT entries
264          */
265         return APIC_INTEGRATED(GET_APIC_VERSION(v)) ? GET_APIC_MAXLVT(v) : 2;
266 }
267
268 /*
269  * Local APIC timer
270  */
271
272 /* Clock divisor */
273 #ifdef CONFG_X86_64
274 #define APIC_DIVISOR 1
275 #else
276 #define APIC_DIVISOR 16
277 #endif
278
279 /*
280  * This function sets up the local APIC timer, with a timeout of
281  * 'clocks' APIC bus clock. During calibration we actually call
282  * this function twice on the boot CPU, once with a bogus timeout
283  * value, second time for real. The other (noncalibrating) CPUs
284  * call this function only once, with the real, calibrated value.
285  *
286  * We do reads before writes even if unnecessary, to get around the
287  * P5 APIC double write bug.
288  */
289 static void __setup_APIC_LVTT(unsigned int clocks, int oneshot, int irqen)
290 {
291         unsigned int lvtt_value, tmp_value;
292
293         lvtt_value = LOCAL_TIMER_VECTOR;
294         if (!oneshot)
295                 lvtt_value |= APIC_LVT_TIMER_PERIODIC;
296         if (!lapic_is_integrated())
297                 lvtt_value |= SET_APIC_TIMER_BASE(APIC_TIMER_BASE_DIV);
298
299         if (!irqen)
300                 lvtt_value |= APIC_LVT_MASKED;
301
302         apic_write(APIC_LVTT, lvtt_value);
303
304         /*
305          * Divide PICLK by 16
306          */
307         tmp_value = apic_read(APIC_TDCR);
308         apic_write(APIC_TDCR,
309                 (tmp_value & ~(APIC_TDR_DIV_1 | APIC_TDR_DIV_TMBASE)) |
310                 APIC_TDR_DIV_16);
311
312         if (!oneshot)
313                 apic_write(APIC_TMICT, clocks / APIC_DIVISOR);
314 }
315
316 /*
317  * Setup extended LVT, AMD specific (K8, family 10h)
318  *
319  * Vector mappings are hard coded. On K8 only offset 0 (APIC500) and
320  * MCE interrupts are supported. Thus MCE offset must be set to 0.
321  *
322  * If mask=1, the LVT entry does not generate interrupts while mask=0
323  * enables the vector. See also the BKDGs.
324  */
325
326 #define APIC_EILVT_LVTOFF_MCE 0
327 #define APIC_EILVT_LVTOFF_IBS 1
328
329 static void setup_APIC_eilvt(u8 lvt_off, u8 vector, u8 msg_type, u8 mask)
330 {
331         unsigned long reg = (lvt_off << 4) + APIC_EILVT0;
332         unsigned int  v   = (mask << 16) | (msg_type << 8) | vector;
333
334         apic_write(reg, v);
335 }
336
337 u8 setup_APIC_eilvt_mce(u8 vector, u8 msg_type, u8 mask)
338 {
339         setup_APIC_eilvt(APIC_EILVT_LVTOFF_MCE, vector, msg_type, mask);
340         return APIC_EILVT_LVTOFF_MCE;
341 }
342
343 u8 setup_APIC_eilvt_ibs(u8 vector, u8 msg_type, u8 mask)
344 {
345         setup_APIC_eilvt(APIC_EILVT_LVTOFF_IBS, vector, msg_type, mask);
346         return APIC_EILVT_LVTOFF_IBS;
347 }
348 EXPORT_SYMBOL_GPL(setup_APIC_eilvt_ibs);
349
350 /*
351  * Program the next event, relative to now
352  */
353 static int lapic_next_event(unsigned long delta,
354                             struct clock_event_device *evt)
355 {
356         apic_write(APIC_TMICT, delta);
357         return 0;
358 }
359
360 /*
361  * Setup the lapic timer in periodic or oneshot mode
362  */
363 static void lapic_timer_setup(enum clock_event_mode mode,
364                               struct clock_event_device *evt)
365 {
366         unsigned long flags;
367         unsigned int v;
368
369         /* Lapic used as dummy for broadcast ? */
370         if (evt->features & CLOCK_EVT_FEAT_DUMMY)
371                 return;
372
373         local_irq_save(flags);
374
375         switch (mode) {
376         case CLOCK_EVT_MODE_PERIODIC:
377         case CLOCK_EVT_MODE_ONESHOT:
378                 __setup_APIC_LVTT(calibration_result,
379                                   mode != CLOCK_EVT_MODE_PERIODIC, 1);
380                 break;
381         case CLOCK_EVT_MODE_UNUSED:
382         case CLOCK_EVT_MODE_SHUTDOWN:
383                 v = apic_read(APIC_LVTT);
384                 v |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
385                 apic_write(APIC_LVTT, v);
386                 break;
387         case CLOCK_EVT_MODE_RESUME:
388                 /* Nothing to do here */
389                 break;
390         }
391
392         local_irq_restore(flags);
393 }
394
395 /*
396  * Local APIC timer broadcast function
397  */
398 static void lapic_timer_broadcast(cpumask_t mask)
399 {
400 #ifdef CONFIG_SMP
401         send_IPI_mask(mask, LOCAL_TIMER_VECTOR);
402 #endif
403 }
404
405 /*
406  * Setup the local APIC timer for this CPU. Copy the initilized values
407  * of the boot CPU and register the clock event in the framework.
408  */
409 static void __cpuinit setup_APIC_timer(void)
410 {
411         struct clock_event_device *levt = &__get_cpu_var(lapic_events);
412
413         memcpy(levt, &lapic_clockevent, sizeof(*levt));
414         levt->cpumask = cpumask_of_cpu(smp_processor_id());
415
416         clockevents_register_device(levt);
417 }
418
419 /*
420  * In this functions we calibrate APIC bus clocks to the external timer.
421  *
422  * We want to do the calibration only once since we want to have local timer
423  * irqs syncron. CPUs connected by the same APIC bus have the very same bus
424  * frequency.
425  *
426  * This was previously done by reading the PIT/HPET and waiting for a wrap
427  * around to find out, that a tick has elapsed. I have a box, where the PIT
428  * readout is broken, so it never gets out of the wait loop again. This was
429  * also reported by others.
430  *
431  * Monitoring the jiffies value is inaccurate and the clockevents
432  * infrastructure allows us to do a simple substitution of the interrupt
433  * handler.
434  *
435  * The calibration routine also uses the pm_timer when possible, as the PIT
436  * happens to run way too slow (factor 2.3 on my VAIO CoreDuo, which goes
437  * back to normal later in the boot process).
438  */
439
440 #define LAPIC_CAL_LOOPS         (HZ/10)
441
442 static __initdata int lapic_cal_loops = -1;
443 static __initdata long lapic_cal_t1, lapic_cal_t2;
444 static __initdata unsigned long long lapic_cal_tsc1, lapic_cal_tsc2;
445 static __initdata unsigned long lapic_cal_pm1, lapic_cal_pm2;
446 static __initdata unsigned long lapic_cal_j1, lapic_cal_j2;
447
448 /*
449  * Temporary interrupt handler.
450  */
451 static void __init lapic_cal_handler(struct clock_event_device *dev)
452 {
453         unsigned long long tsc = 0;
454         long tapic = apic_read(APIC_TMCCT);
455         unsigned long pm = acpi_pm_read_early();
456
457         if (cpu_has_tsc)
458                 rdtscll(tsc);
459
460         switch (lapic_cal_loops++) {
461         case 0:
462                 lapic_cal_t1 = tapic;
463                 lapic_cal_tsc1 = tsc;
464                 lapic_cal_pm1 = pm;
465                 lapic_cal_j1 = jiffies;
466                 break;
467
468         case LAPIC_CAL_LOOPS:
469                 lapic_cal_t2 = tapic;
470                 lapic_cal_tsc2 = tsc;
471                 if (pm < lapic_cal_pm1)
472                         pm += ACPI_PM_OVRRUN;
473                 lapic_cal_pm2 = pm;
474                 lapic_cal_j2 = jiffies;
475                 break;
476         }
477 }
478
479 static int __init calibrate_APIC_clock(void)
480 {
481         struct clock_event_device *levt = &__get_cpu_var(lapic_events);
482         const long pm_100ms = PMTMR_TICKS_PER_SEC/10;
483         const long pm_thresh = pm_100ms/100;
484         void (*real_handler)(struct clock_event_device *dev);
485         unsigned long deltaj;
486         long delta, deltapm;
487         int pm_referenced = 0;
488
489         local_irq_disable();
490
491         /* Replace the global interrupt handler */
492         real_handler = global_clock_event->event_handler;
493         global_clock_event->event_handler = lapic_cal_handler;
494
495         /*
496          * Setup the APIC counter to 1e9. There is no way the lapic
497          * can underflow in the 100ms detection time frame
498          */
499         __setup_APIC_LVTT(1000000000, 0, 0);
500
501         /* Let the interrupts run */
502         local_irq_enable();
503
504         while (lapic_cal_loops <= LAPIC_CAL_LOOPS)
505                 cpu_relax();
506
507         local_irq_disable();
508
509         /* Restore the real event handler */
510         global_clock_event->event_handler = real_handler;
511
512         /* Build delta t1-t2 as apic timer counts down */
513         delta = lapic_cal_t1 - lapic_cal_t2;
514         apic_printk(APIC_VERBOSE, "... lapic delta = %ld\n", delta);
515
516         /* Check, if the PM timer is available */
517         deltapm = lapic_cal_pm2 - lapic_cal_pm1;
518         apic_printk(APIC_VERBOSE, "... PM timer delta = %ld\n", deltapm);
519
520         if (deltapm) {
521                 unsigned long mult;
522                 u64 res;
523
524                 mult = clocksource_hz2mult(PMTMR_TICKS_PER_SEC, 22);
525
526                 if (deltapm > (pm_100ms - pm_thresh) &&
527                     deltapm < (pm_100ms + pm_thresh)) {
528                         apic_printk(APIC_VERBOSE, "... PM timer result ok\n");
529                 } else {
530                         res = (((u64) deltapm) *  mult) >> 22;
531                         do_div(res, 1000000);
532                         printk(KERN_WARNING "APIC calibration not consistent "
533                                "with PM Timer: %ldms instead of 100ms\n",
534                                (long)res);
535                         /* Correct the lapic counter value */
536                         res = (((u64) delta) * pm_100ms);
537                         do_div(res, deltapm);
538                         printk(KERN_INFO "APIC delta adjusted to PM-Timer: "
539                                "%lu (%ld)\n", (unsigned long) res, delta);
540                         delta = (long) res;
541                 }
542                 pm_referenced = 1;
543         }
544
545         /* Calculate the scaled math multiplication factor */
546         lapic_clockevent.mult = div_sc(delta, TICK_NSEC * LAPIC_CAL_LOOPS,
547                                        lapic_clockevent.shift);
548         lapic_clockevent.max_delta_ns =
549                 clockevent_delta2ns(0x7FFFFF, &lapic_clockevent);
550         lapic_clockevent.min_delta_ns =
551                 clockevent_delta2ns(0xF, &lapic_clockevent);
552
553         calibration_result = (delta * APIC_DIVISOR) / LAPIC_CAL_LOOPS;
554
555         apic_printk(APIC_VERBOSE, "..... delta %ld\n", delta);
556         apic_printk(APIC_VERBOSE, "..... mult: %ld\n", lapic_clockevent.mult);
557         apic_printk(APIC_VERBOSE, "..... calibration result: %u\n",
558                     calibration_result);
559
560         if (cpu_has_tsc) {
561                 delta = (long)(lapic_cal_tsc2 - lapic_cal_tsc1);
562                 apic_printk(APIC_VERBOSE, "..... CPU clock speed is "
563                             "%ld.%04ld MHz.\n",
564                             (delta / LAPIC_CAL_LOOPS) / (1000000 / HZ),
565                             (delta / LAPIC_CAL_LOOPS) % (1000000 / HZ));
566         }
567
568         apic_printk(APIC_VERBOSE, "..... host bus clock speed is "
569                     "%u.%04u MHz.\n",
570                     calibration_result / (1000000 / HZ),
571                     calibration_result % (1000000 / HZ));
572
573         /*
574          * Do a sanity check on the APIC calibration result
575          */
576         if (calibration_result < (1000000 / HZ)) {
577                 local_irq_enable();
578                 printk(KERN_WARNING
579                        "APIC frequency too slow, disabling apic timer\n");
580                 return -1;
581         }
582
583         levt->features &= ~CLOCK_EVT_FEAT_DUMMY;
584
585         /* We trust the pm timer based calibration */
586         if (!pm_referenced) {
587                 apic_printk(APIC_VERBOSE, "... verify APIC timer\n");
588
589                 /*
590                  * Setup the apic timer manually
591                  */
592                 levt->event_handler = lapic_cal_handler;
593                 lapic_timer_setup(CLOCK_EVT_MODE_PERIODIC, levt);
594                 lapic_cal_loops = -1;
595
596                 /* Let the interrupts run */
597                 local_irq_enable();
598
599                 while (lapic_cal_loops <= LAPIC_CAL_LOOPS)
600                         cpu_relax();
601
602                 local_irq_disable();
603
604                 /* Stop the lapic timer */
605                 lapic_timer_setup(CLOCK_EVT_MODE_SHUTDOWN, levt);
606
607                 local_irq_enable();
608
609                 /* Jiffies delta */
610                 deltaj = lapic_cal_j2 - lapic_cal_j1;
611                 apic_printk(APIC_VERBOSE, "... jiffies delta = %lu\n", deltaj);
612
613                 /* Check, if the jiffies result is consistent */
614                 if (deltaj >= LAPIC_CAL_LOOPS-2 && deltaj <= LAPIC_CAL_LOOPS+2)
615                         apic_printk(APIC_VERBOSE, "... jiffies result ok\n");
616                 else
617                         levt->features |= CLOCK_EVT_FEAT_DUMMY;
618         } else
619                 local_irq_enable();
620
621         if (levt->features & CLOCK_EVT_FEAT_DUMMY) {
622                 printk(KERN_WARNING
623                        "APIC timer disabled due to verification failure.\n");
624                         return -1;
625         }
626
627         return 0;
628 }
629
630 /*
631  * Setup the boot APIC
632  *
633  * Calibrate and verify the result.
634  */
635 void __init setup_boot_APIC_clock(void)
636 {
637         /*
638          * The local apic timer can be disabled via the kernel
639          * commandline or from the CPU detection code. Register the lapic
640          * timer as a dummy clock event source on SMP systems, so the
641          * broadcast mechanism is used. On UP systems simply ignore it.
642          */
643         if (disable_apic_timer) {
644                 printk(KERN_INFO "Disabling APIC timer\n");
645                 /* No broadcast on UP ! */
646                 if (num_possible_cpus() > 1) {
647                         lapic_clockevent.mult = 1;
648                         setup_APIC_timer();
649                 }
650                 return;
651         }
652
653         apic_printk(APIC_VERBOSE, "Using local APIC timer interrupts.\n"
654                     "calibrating APIC timer ...\n");
655
656         if (calibrate_APIC_clock()) {
657                 /* No broadcast on UP ! */
658                 if (num_possible_cpus() > 1)
659                         setup_APIC_timer();
660                 return;
661         }
662
663         /*
664          * If nmi_watchdog is set to IO_APIC, we need the
665          * PIT/HPET going.  Otherwise register lapic as a dummy
666          * device.
667          */
668         if (nmi_watchdog != NMI_IO_APIC)
669                 lapic_clockevent.features &= ~CLOCK_EVT_FEAT_DUMMY;
670         else
671                 printk(KERN_WARNING "APIC timer registered as dummy,"
672                         " due to nmi_watchdog=%d!\n", nmi_watchdog);
673
674         /* Setup the lapic or request the broadcast */
675         setup_APIC_timer();
676 }
677
678 void __cpuinit setup_secondary_APIC_clock(void)
679 {
680         setup_APIC_timer();
681 }
682
683 /*
684  * The guts of the apic timer interrupt
685  */
686 static void local_apic_timer_interrupt(void)
687 {
688         int cpu = smp_processor_id();
689         struct clock_event_device *evt = &per_cpu(lapic_events, cpu);
690
691         /*
692          * Normally we should not be here till LAPIC has been initialized but
693          * in some cases like kdump, its possible that there is a pending LAPIC
694          * timer interrupt from previous kernel's context and is delivered in
695          * new kernel the moment interrupts are enabled.
696          *
697          * Interrupts are enabled early and LAPIC is setup much later, hence
698          * its possible that when we get here evt->event_handler is NULL.
699          * Check for event_handler being NULL and discard the interrupt as
700          * spurious.
701          */
702         if (!evt->event_handler) {
703                 printk(KERN_WARNING
704                        "Spurious LAPIC timer interrupt on cpu %d\n", cpu);
705                 /* Switch it off */
706                 lapic_timer_setup(CLOCK_EVT_MODE_SHUTDOWN, evt);
707                 return;
708         }
709
710         /*
711          * the NMI deadlock-detector uses this.
712          */
713 #ifdef CONFIG_X86_64
714         add_pda(apic_timer_irqs, 1);
715 #else
716         per_cpu(irq_stat, cpu).apic_timer_irqs++;
717 #endif
718
719         evt->event_handler(evt);
720 }
721
722 /*
723  * Local APIC timer interrupt. This is the most natural way for doing
724  * local interrupts, but local timer interrupts can be emulated by
725  * broadcast interrupts too. [in case the hw doesn't support APIC timers]
726  *
727  * [ if a single-CPU system runs an SMP kernel then we call the local
728  *   interrupt as well. Thus we cannot inline the local irq ... ]
729  */
730 void smp_apic_timer_interrupt(struct pt_regs *regs)
731 {
732         struct pt_regs *old_regs = set_irq_regs(regs);
733
734         /*
735          * NOTE! We'd better ACK the irq immediately,
736          * because timer handling can be slow.
737          */
738         ack_APIC_irq();
739         /*
740          * update_process_times() expects us to have done irq_enter().
741          * Besides, if we don't timer interrupts ignore the global
742          * interrupt lock, which is the WrongThing (tm) to do.
743          */
744 #ifdef CONFIG_X86_64
745         exit_idle();
746 #endif
747         irq_enter();
748         local_apic_timer_interrupt();
749         irq_exit();
750
751         set_irq_regs(old_regs);
752 }
753
754 int setup_profiling_timer(unsigned int multiplier)
755 {
756         return -EINVAL;
757 }
758
759 /*
760  * Local APIC start and shutdown
761  */
762
763 /**
764  * clear_local_APIC - shutdown the local APIC
765  *
766  * This is called, when a CPU is disabled and before rebooting, so the state of
767  * the local APIC has no dangling leftovers. Also used to cleanout any BIOS
768  * leftovers during boot.
769  */
770 void clear_local_APIC(void)
771 {
772         int maxlvt;
773         u32 v;
774
775         /* APIC hasn't been mapped yet */
776         if (!apic_phys)
777                 return;
778
779         maxlvt = lapic_get_maxlvt();
780         /*
781          * Masking an LVT entry can trigger a local APIC error
782          * if the vector is zero. Mask LVTERR first to prevent this.
783          */
784         if (maxlvt >= 3) {
785                 v = ERROR_APIC_VECTOR; /* any non-zero vector will do */
786                 apic_write(APIC_LVTERR, v | APIC_LVT_MASKED);
787         }
788         /*
789          * Careful: we have to set masks only first to deassert
790          * any level-triggered sources.
791          */
792         v = apic_read(APIC_LVTT);
793         apic_write(APIC_LVTT, v | APIC_LVT_MASKED);
794         v = apic_read(APIC_LVT0);
795         apic_write(APIC_LVT0, v | APIC_LVT_MASKED);
796         v = apic_read(APIC_LVT1);
797         apic_write(APIC_LVT1, v | APIC_LVT_MASKED);
798         if (maxlvt >= 4) {
799                 v = apic_read(APIC_LVTPC);
800                 apic_write(APIC_LVTPC, v | APIC_LVT_MASKED);
801         }
802
803         /* lets not touch this if we didn't frob it */
804 #if defined(CONFIG_X86_MCE_P4THERMAL) || defined(X86_MCE_INTEL)
805         if (maxlvt >= 5) {
806                 v = apic_read(APIC_LVTTHMR);
807                 apic_write(APIC_LVTTHMR, v | APIC_LVT_MASKED);
808         }
809 #endif
810         /*
811          * Clean APIC state for other OSs:
812          */
813         apic_write(APIC_LVTT, APIC_LVT_MASKED);
814         apic_write(APIC_LVT0, APIC_LVT_MASKED);
815         apic_write(APIC_LVT1, APIC_LVT_MASKED);
816         if (maxlvt >= 3)
817                 apic_write(APIC_LVTERR, APIC_LVT_MASKED);
818         if (maxlvt >= 4)
819                 apic_write(APIC_LVTPC, APIC_LVT_MASKED);
820
821         /* Integrated APIC (!82489DX) ? */
822         if (lapic_is_integrated()) {
823                 if (maxlvt > 3)
824                         /* Clear ESR due to Pentium errata 3AP and 11AP */
825                         apic_write(APIC_ESR, 0);
826                 apic_read(APIC_ESR);
827         }
828 }
829
830 /**
831  * disable_local_APIC - clear and disable the local APIC
832  */
833 void disable_local_APIC(void)
834 {
835         unsigned int value;
836
837         clear_local_APIC();
838
839         /*
840          * Disable APIC (implies clearing of registers
841          * for 82489DX!).
842          */
843         value = apic_read(APIC_SPIV);
844         value &= ~APIC_SPIV_APIC_ENABLED;
845         apic_write(APIC_SPIV, value);
846
847 #ifdef CONFIG_X86_32
848         /*
849          * When LAPIC was disabled by the BIOS and enabled by the kernel,
850          * restore the disabled state.
851          */
852         if (enabled_via_apicbase) {
853                 unsigned int l, h;
854
855                 rdmsr(MSR_IA32_APICBASE, l, h);
856                 l &= ~MSR_IA32_APICBASE_ENABLE;
857                 wrmsr(MSR_IA32_APICBASE, l, h);
858         }
859 #endif
860 }
861
862 /*
863  * If Linux enabled the LAPIC against the BIOS default disable it down before
864  * re-entering the BIOS on shutdown.  Otherwise the BIOS may get confused and
865  * not power-off.  Additionally clear all LVT entries before disable_local_APIC
866  * for the case where Linux didn't enable the LAPIC.
867  */
868 void lapic_shutdown(void)
869 {
870         unsigned long flags;
871
872         if (!cpu_has_apic)
873                 return;
874
875         local_irq_save(flags);
876
877 #ifdef CONFIG_X86_32
878         if (!enabled_via_apicbase)
879                 clear_local_APIC();
880         else
881 #endif
882                 disable_local_APIC();
883
884
885         local_irq_restore(flags);
886 }
887
888 /*
889  * This is to verify that we're looking at a real local APIC.
890  * Check these against your board if the CPUs aren't getting
891  * started for no apparent reason.
892  */
893 int __init verify_local_APIC(void)
894 {
895         unsigned int reg0, reg1;
896
897         /*
898          * The version register is read-only in a real APIC.
899          */
900         reg0 = apic_read(APIC_LVR);
901         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg0);
902         apic_write(APIC_LVR, reg0 ^ APIC_LVR_MASK);
903         reg1 = apic_read(APIC_LVR);
904         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg1);
905
906         /*
907          * The two version reads above should print the same
908          * numbers.  If the second one is different, then we
909          * poke at a non-APIC.
910          */
911         if (reg1 != reg0)
912                 return 0;
913
914         /*
915          * Check if the version looks reasonably.
916          */
917         reg1 = GET_APIC_VERSION(reg0);
918         if (reg1 == 0x00 || reg1 == 0xff)
919                 return 0;
920         reg1 = lapic_get_maxlvt();
921         if (reg1 < 0x02 || reg1 == 0xff)
922                 return 0;
923
924         /*
925          * The ID register is read/write in a real APIC.
926          */
927         reg0 = apic_read(APIC_ID);
928         apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg0);
929         apic_write(APIC_ID, reg0 ^ APIC_ID_MASK);
930         reg1 = apic_read(APIC_ID);
931         apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg1);
932         apic_write(APIC_ID, reg0);
933         if (reg1 != (reg0 ^ APIC_ID_MASK))
934                 return 0;
935
936         /*
937          * The next two are just to see if we have sane values.
938          * They're only really relevant if we're in Virtual Wire
939          * compatibility mode, but most boxes are anymore.
940          */
941         reg0 = apic_read(APIC_LVT0);
942         apic_printk(APIC_DEBUG, "Getting LVT0: %x\n", reg0);
943         reg1 = apic_read(APIC_LVT1);
944         apic_printk(APIC_DEBUG, "Getting LVT1: %x\n", reg1);
945
946         return 1;
947 }
948
949 /**
950  * sync_Arb_IDs - synchronize APIC bus arbitration IDs
951  */
952 void __init sync_Arb_IDs(void)
953 {
954         /*
955          * Unsupported on P4 - see Intel Dev. Manual Vol. 3, Ch. 8.6.1 And not
956          * needed on AMD.
957          */
958         if (modern_apic() || boot_cpu_data.x86_vendor == X86_VENDOR_AMD)
959                 return;
960
961         /*
962          * Wait for idle.
963          */
964         apic_wait_icr_idle();
965
966         apic_printk(APIC_DEBUG, "Synchronizing Arb IDs.\n");
967         apic_write(APIC_ICR, APIC_DEST_ALLINC |
968                         APIC_INT_LEVELTRIG | APIC_DM_INIT);
969 }
970
971 /*
972  * An initial setup of the virtual wire mode.
973  */
974 void __init init_bsp_APIC(void)
975 {
976         unsigned int value;
977
978         /*
979          * Don't do the setup now if we have a SMP BIOS as the
980          * through-I/O-APIC virtual wire mode might be active.
981          */
982         if (smp_found_config || !cpu_has_apic)
983                 return;
984
985         /*
986          * Do not trust the local APIC being empty at bootup.
987          */
988         clear_local_APIC();
989
990         /*
991          * Enable APIC.
992          */
993         value = apic_read(APIC_SPIV);
994         value &= ~APIC_VECTOR_MASK;
995         value |= APIC_SPIV_APIC_ENABLED;
996
997 #ifdef CONFIG_X86_32
998         /* This bit is reserved on P4/Xeon and should be cleared */
999         if ((boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) &&
1000             (boot_cpu_data.x86 == 15))
1001                 value &= ~APIC_SPIV_FOCUS_DISABLED;
1002         else
1003 #endif
1004                 value |= APIC_SPIV_FOCUS_DISABLED;
1005         value |= SPURIOUS_APIC_VECTOR;
1006         apic_write(APIC_SPIV, value);
1007
1008         /*
1009          * Set up the virtual wire mode.
1010          */
1011         apic_write(APIC_LVT0, APIC_DM_EXTINT);
1012         value = APIC_DM_NMI;
1013         if (!lapic_is_integrated())             /* 82489DX */
1014                 value |= APIC_LVT_LEVEL_TRIGGER;
1015         apic_write(APIC_LVT1, value);
1016 }
1017
1018 static void __cpuinit lapic_setup_esr(void)
1019 {
1020         unsigned long oldvalue, value, maxlvt;
1021         if (lapic_is_integrated() && !esr_disable) {
1022                 if (esr_disable) {
1023                         /*
1024                          * Something untraceable is creating bad interrupts on
1025                          * secondary quads ... for the moment, just leave the
1026                          * ESR disabled - we can't do anything useful with the
1027                          * errors anyway - mbligh
1028                          */
1029                         printk(KERN_INFO "Leaving ESR disabled.\n");
1030                         return;
1031                 }
1032                 /* !82489DX */
1033                 maxlvt = lapic_get_maxlvt();
1034                 if (maxlvt > 3)         /* Due to the Pentium erratum 3AP. */
1035                         apic_write(APIC_ESR, 0);
1036                 oldvalue = apic_read(APIC_ESR);
1037
1038                 /* enables sending errors */
1039                 value = ERROR_APIC_VECTOR;
1040                 apic_write(APIC_LVTERR, value);
1041                 /*
1042                  * spec says clear errors after enabling vector.
1043                  */
1044                 if (maxlvt > 3)
1045                         apic_write(APIC_ESR, 0);
1046                 value = apic_read(APIC_ESR);
1047                 if (value != oldvalue)
1048                         apic_printk(APIC_VERBOSE, "ESR value before enabling "
1049                                 "vector: 0x%08lx  after: 0x%08lx\n",
1050                                 oldvalue, value);
1051         } else {
1052                 printk(KERN_INFO "No ESR for 82489DX.\n");
1053         }
1054 }
1055
1056
1057 /**
1058  * setup_local_APIC - setup the local APIC
1059  */
1060 void __cpuinit setup_local_APIC(void)
1061 {
1062         unsigned int value;
1063         int i, j;
1064
1065 #ifdef CONFIG_X86_32
1066         /* Pound the ESR really hard over the head with a big hammer - mbligh */
1067         if (esr_disable) {
1068                 apic_write(APIC_ESR, 0);
1069                 apic_write(APIC_ESR, 0);
1070                 apic_write(APIC_ESR, 0);
1071                 apic_write(APIC_ESR, 0);
1072         }
1073 #endif
1074
1075         preempt_disable();
1076
1077         /*
1078          * Double-check whether this APIC is really registered.
1079          * This is meaningless in clustered apic mode, so we skip it.
1080          */
1081         if (!apic_id_registered())
1082                 BUG();
1083
1084         /*
1085          * Intel recommends to set DFR, LDR and TPR before enabling
1086          * an APIC.  See e.g. "AP-388 82489DX User's Manual" (Intel
1087          * document number 292116).  So here it goes...
1088          */
1089         init_apic_ldr();
1090
1091         /*
1092          * Set Task Priority to 'accept all'. We never change this
1093          * later on.
1094          */
1095         value = apic_read(APIC_TASKPRI);
1096         value &= ~APIC_TPRI_MASK;
1097         apic_write(APIC_TASKPRI, value);
1098
1099         /*
1100          * After a crash, we no longer service the interrupts and a pending
1101          * interrupt from previous kernel might still have ISR bit set.
1102          *
1103          * Most probably by now CPU has serviced that pending interrupt and
1104          * it might not have done the ack_APIC_irq() because it thought,
1105          * interrupt came from i8259 as ExtInt. LAPIC did not get EOI so it
1106          * does not clear the ISR bit and cpu thinks it has already serivced
1107          * the interrupt. Hence a vector might get locked. It was noticed
1108          * for timer irq (vector 0x31). Issue an extra EOI to clear ISR.
1109          */
1110         for (i = APIC_ISR_NR - 1; i >= 0; i--) {
1111                 value = apic_read(APIC_ISR + i*0x10);
1112                 for (j = 31; j >= 0; j--) {
1113                         if (value & (1<<j))
1114                                 ack_APIC_irq();
1115                 }
1116         }
1117
1118         /*
1119          * Now that we are all set up, enable the APIC
1120          */
1121         value = apic_read(APIC_SPIV);
1122         value &= ~APIC_VECTOR_MASK;
1123         /*
1124          * Enable APIC
1125          */
1126         value |= APIC_SPIV_APIC_ENABLED;
1127
1128 #ifdef CONFIG_X86_32
1129         /*
1130          * Some unknown Intel IO/APIC (or APIC) errata is biting us with
1131          * certain networking cards. If high frequency interrupts are
1132          * happening on a particular IOAPIC pin, plus the IOAPIC routing
1133          * entry is masked/unmasked at a high rate as well then sooner or
1134          * later IOAPIC line gets 'stuck', no more interrupts are received
1135          * from the device. If focus CPU is disabled then the hang goes
1136          * away, oh well :-(
1137          *
1138          * [ This bug can be reproduced easily with a level-triggered
1139          *   PCI Ne2000 networking cards and PII/PIII processors, dual
1140          *   BX chipset. ]
1141          */
1142         /*
1143          * Actually disabling the focus CPU check just makes the hang less
1144          * frequent as it makes the interrupt distributon model be more
1145          * like LRU than MRU (the short-term load is more even across CPUs).
1146          * See also the comment in end_level_ioapic_irq().  --macro
1147          */
1148
1149         /*
1150          * - enable focus processor (bit==0)
1151          * - 64bit mode always use processor focus
1152          *   so no need to set it
1153          */
1154         value &= ~APIC_SPIV_FOCUS_DISABLED;
1155 #endif
1156
1157         /*
1158          * Set spurious IRQ vector
1159          */
1160         value |= SPURIOUS_APIC_VECTOR;
1161         apic_write(APIC_SPIV, value);
1162
1163         /*
1164          * Set up LVT0, LVT1:
1165          *
1166          * set up through-local-APIC on the BP's LINT0. This is not
1167          * strictly necessary in pure symmetric-IO mode, but sometimes
1168          * we delegate interrupts to the 8259A.
1169          */
1170         /*
1171          * TODO: set up through-local-APIC from through-I/O-APIC? --macro
1172          */
1173         value = apic_read(APIC_LVT0) & APIC_LVT_MASKED;
1174         if (!smp_processor_id() && (pic_mode || !value)) {
1175                 value = APIC_DM_EXTINT;
1176                 apic_printk(APIC_VERBOSE, "enabled ExtINT on CPU#%d\n",
1177                                 smp_processor_id());
1178         } else {
1179                 value = APIC_DM_EXTINT | APIC_LVT_MASKED;
1180                 apic_printk(APIC_VERBOSE, "masked ExtINT on CPU#%d\n",
1181                                 smp_processor_id());
1182         }
1183         apic_write(APIC_LVT0, value);
1184
1185         /*
1186          * only the BP should see the LINT1 NMI signal, obviously.
1187          */
1188         if (!smp_processor_id())
1189                 value = APIC_DM_NMI;
1190         else
1191                 value = APIC_DM_NMI | APIC_LVT_MASKED;
1192         if (!lapic_is_integrated())             /* 82489DX */
1193                 value |= APIC_LVT_LEVEL_TRIGGER;
1194         apic_write(APIC_LVT1, value);
1195
1196         preempt_enable();
1197 }
1198
1199 void __cpuinit end_local_APIC_setup(void)
1200 {
1201         lapic_setup_esr();
1202
1203 #ifdef CONFIG_X86_32
1204         {
1205                 unsigned int value;
1206                 /* Disable the local apic timer */
1207                 value = apic_read(APIC_LVTT);
1208                 value |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
1209                 apic_write(APIC_LVTT, value);
1210         }
1211 #endif
1212
1213         setup_apic_nmi_watchdog(NULL);
1214         apic_pm_activate();
1215 }
1216
1217 /*
1218  * Detect and initialize APIC
1219  */
1220 static int __init detect_init_APIC(void)
1221 {
1222         u32 h, l, features;
1223
1224         /* Disabled by kernel option? */
1225         if (disable_apic)
1226                 return -1;
1227
1228         switch (boot_cpu_data.x86_vendor) {
1229         case X86_VENDOR_AMD:
1230                 if ((boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model > 1) ||
1231                     (boot_cpu_data.x86 == 15))
1232                         break;
1233                 goto no_apic;
1234         case X86_VENDOR_INTEL:
1235                 if (boot_cpu_data.x86 == 6 || boot_cpu_data.x86 == 15 ||
1236                     (boot_cpu_data.x86 == 5 && cpu_has_apic))
1237                         break;
1238                 goto no_apic;
1239         default:
1240                 goto no_apic;
1241         }
1242
1243         if (!cpu_has_apic) {
1244                 /*
1245                  * Over-ride BIOS and try to enable the local APIC only if
1246                  * "lapic" specified.
1247                  */
1248                 if (!force_enable_local_apic) {
1249                         printk(KERN_INFO "Local APIC disabled by BIOS -- "
1250                                "you can enable it with \"lapic\"\n");
1251                         return -1;
1252                 }
1253                 /*
1254                  * Some BIOSes disable the local APIC in the APIC_BASE
1255                  * MSR. This can only be done in software for Intel P6 or later
1256                  * and AMD K7 (Model > 1) or later.
1257                  */
1258                 rdmsr(MSR_IA32_APICBASE, l, h);
1259                 if (!(l & MSR_IA32_APICBASE_ENABLE)) {
1260                         printk(KERN_INFO
1261                                "Local APIC disabled by BIOS -- reenabling.\n");
1262                         l &= ~MSR_IA32_APICBASE_BASE;
1263                         l |= MSR_IA32_APICBASE_ENABLE | APIC_DEFAULT_PHYS_BASE;
1264                         wrmsr(MSR_IA32_APICBASE, l, h);
1265                         enabled_via_apicbase = 1;
1266                 }
1267         }
1268         /*
1269          * The APIC feature bit should now be enabled
1270          * in `cpuid'
1271          */
1272         features = cpuid_edx(1);
1273         if (!(features & (1 << X86_FEATURE_APIC))) {
1274                 printk(KERN_WARNING "Could not enable APIC!\n");
1275                 return -1;
1276         }
1277         set_cpu_cap(&boot_cpu_data, X86_FEATURE_APIC);
1278         mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
1279
1280         /* The BIOS may have set up the APIC at some other address */
1281         rdmsr(MSR_IA32_APICBASE, l, h);
1282         if (l & MSR_IA32_APICBASE_ENABLE)
1283                 mp_lapic_addr = l & MSR_IA32_APICBASE_BASE;
1284
1285         printk(KERN_INFO "Found and enabled local APIC!\n");
1286
1287         apic_pm_activate();
1288
1289         return 0;
1290
1291 no_apic:
1292         printk(KERN_INFO "No local APIC present or hardware disabled\n");
1293         return -1;
1294 }
1295
1296 #ifdef CONFIG_X86_64
1297 void __init early_init_lapic_mapping(void)
1298 {
1299         unsigned long phys_addr;
1300
1301         /*
1302          * If no local APIC can be found then go out
1303          * : it means there is no mpatable and MADT
1304          */
1305         if (!smp_found_config)
1306                 return;
1307
1308         phys_addr = mp_lapic_addr;
1309
1310         set_fixmap_nocache(FIX_APIC_BASE, phys_addr);
1311         apic_printk(APIC_VERBOSE, "mapped APIC to %16lx (%16lx)\n",
1312                     APIC_BASE, phys_addr);
1313
1314         /*
1315          * Fetch the APIC ID of the BSP in case we have a
1316          * default configuration (or the MP table is broken).
1317          */
1318         boot_cpu_physical_apicid = read_apic_id();
1319 }
1320 #endif
1321
1322 /**
1323  * init_apic_mappings - initialize APIC mappings
1324  */
1325 void __init init_apic_mappings(void)
1326 {
1327         /*
1328          * If no local APIC can be found then set up a fake all
1329          * zeroes page to simulate the local APIC and another
1330          * one for the IO-APIC.
1331          */
1332         if (!smp_found_config && detect_init_APIC()) {
1333                 apic_phys = (unsigned long) alloc_bootmem_pages(PAGE_SIZE);
1334                 apic_phys = __pa(apic_phys);
1335         } else
1336                 apic_phys = mp_lapic_addr;
1337
1338         set_fixmap_nocache(FIX_APIC_BASE, apic_phys);
1339         apic_printk(APIC_VERBOSE, "mapped APIC to %16lx (%16lx)\n",
1340                                 APIC_BASE, apic_phys);
1341
1342         /*
1343          * Fetch the APIC ID of the BSP in case we have a
1344          * default configuration (or the MP table is broken).
1345          */
1346         if (boot_cpu_physical_apicid == -1U)
1347                 boot_cpu_physical_apicid = read_apic_id();
1348 }
1349
1350 /*
1351  * This initializes the IO-APIC and APIC hardware if this is
1352  * a UP kernel.
1353  */
1354 int apic_version[MAX_APICS];
1355
1356 int __init APIC_init_uniprocessor(void)
1357 {
1358         if (!smp_found_config && !cpu_has_apic)
1359                 return -1;
1360
1361         /*
1362          * Complain if the BIOS pretends there is one.
1363          */
1364         if (!cpu_has_apic &&
1365             APIC_INTEGRATED(apic_version[boot_cpu_physical_apicid])) {
1366                 printk(KERN_ERR "BIOS bug, local APIC #%d not detected!...\n",
1367                        boot_cpu_physical_apicid);
1368                 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_APIC);
1369                 return -1;
1370         }
1371
1372         verify_local_APIC();
1373
1374         connect_bsp_APIC();
1375
1376         /*
1377          * Hack: In case of kdump, after a crash, kernel might be booting
1378          * on a cpu with non-zero lapic id. But boot_cpu_physical_apicid
1379          * might be zero if read from MP tables. Get it from LAPIC.
1380          */
1381 #ifdef CONFIG_CRASH_DUMP
1382         boot_cpu_physical_apicid = read_apic_id();
1383 #endif
1384         physid_set_mask_of_physid(boot_cpu_physical_apicid, &phys_cpu_present_map);
1385
1386         setup_local_APIC();
1387
1388 #ifdef CONFIG_X86_IO_APIC
1389         if (!smp_found_config || skip_ioapic_setup || !nr_ioapics)
1390 #endif
1391                 localise_nmi_watchdog();
1392         end_local_APIC_setup();
1393 #ifdef CONFIG_X86_IO_APIC
1394         if (smp_found_config)
1395                 if (!skip_ioapic_setup && nr_ioapics)
1396                         setup_IO_APIC();
1397 #endif
1398         setup_boot_clock();
1399
1400         return 0;
1401 }
1402
1403 /*
1404  * Local APIC interrupts
1405  */
1406
1407 /*
1408  * This interrupt should _never_ happen with our APIC/SMP architecture
1409  */
1410 void smp_spurious_interrupt(struct pt_regs *regs)
1411 {
1412         unsigned long v;
1413
1414         irq_enter();
1415         /*
1416          * Check if this really is a spurious interrupt and ACK it
1417          * if it is a vectored one.  Just in case...
1418          * Spurious interrupts should not be ACKed.
1419          */
1420         v = apic_read(APIC_ISR + ((SPURIOUS_APIC_VECTOR & ~0x1f) >> 1));
1421         if (v & (1 << (SPURIOUS_APIC_VECTOR & 0x1f)))
1422                 ack_APIC_irq();
1423
1424         /* see sw-dev-man vol 3, chapter 7.4.13.5 */
1425         printk(KERN_INFO "spurious APIC interrupt on CPU#%d, "
1426                "should never happen.\n", smp_processor_id());
1427         __get_cpu_var(irq_stat).irq_spurious_count++;
1428         irq_exit();
1429 }
1430
1431 /*
1432  * This interrupt should never happen with our APIC/SMP architecture
1433  */
1434 void smp_error_interrupt(struct pt_regs *regs)
1435 {
1436         unsigned long v, v1;
1437
1438         irq_enter();
1439         /* First tickle the hardware, only then report what went on. -- REW */
1440         v = apic_read(APIC_ESR);
1441         apic_write(APIC_ESR, 0);
1442         v1 = apic_read(APIC_ESR);
1443         ack_APIC_irq();
1444         atomic_inc(&irq_err_count);
1445
1446         /* Here is what the APIC error bits mean:
1447            0: Send CS error
1448            1: Receive CS error
1449            2: Send accept error
1450            3: Receive accept error
1451            4: Reserved
1452            5: Send illegal vector
1453            6: Received illegal vector
1454            7: Illegal register address
1455         */
1456         printk(KERN_DEBUG "APIC error on CPU%d: %02lx(%02lx)\n",
1457                 smp_processor_id(), v , v1);
1458         irq_exit();
1459 }
1460
1461 /**
1462  * connect_bsp_APIC - attach the APIC to the interrupt system
1463  */
1464 void __init connect_bsp_APIC(void)
1465 {
1466 #ifdef CONFIG_X86_32
1467         if (pic_mode) {
1468                 /*
1469                  * Do not trust the local APIC being empty at bootup.
1470                  */
1471                 clear_local_APIC();
1472                 /*
1473                  * PIC mode, enable APIC mode in the IMCR, i.e.  connect BSP's
1474                  * local APIC to INT and NMI lines.
1475                  */
1476                 apic_printk(APIC_VERBOSE, "leaving PIC mode, "
1477                                 "enabling APIC mode.\n");
1478                 outb(0x70, 0x22);
1479                 outb(0x01, 0x23);
1480         }
1481 #endif
1482         enable_apic_mode();
1483 }
1484
1485 /**
1486  * disconnect_bsp_APIC - detach the APIC from the interrupt system
1487  * @virt_wire_setup:    indicates, whether virtual wire mode is selected
1488  *
1489  * Virtual wire mode is necessary to deliver legacy interrupts even when the
1490  * APIC is disabled.
1491  */
1492 void disconnect_bsp_APIC(int virt_wire_setup)
1493 {
1494         unsigned int value;
1495
1496 #ifdef CONFIG_X86_32
1497         if (pic_mode) {
1498                 /*
1499                  * Put the board back into PIC mode (has an effect only on
1500                  * certain older boards).  Note that APIC interrupts, including
1501                  * IPIs, won't work beyond this point!  The only exception are
1502                  * INIT IPIs.
1503                  */
1504                 apic_printk(APIC_VERBOSE, "disabling APIC mode, "
1505                                 "entering PIC mode.\n");
1506                 outb(0x70, 0x22);
1507                 outb(0x00, 0x23);
1508                 return;
1509         }
1510 #endif
1511
1512         /* Go back to Virtual Wire compatibility mode */
1513
1514         /* For the spurious interrupt use vector F, and enable it */
1515         value = apic_read(APIC_SPIV);
1516         value &= ~APIC_VECTOR_MASK;
1517         value |= APIC_SPIV_APIC_ENABLED;
1518         value |= 0xf;
1519         apic_write(APIC_SPIV, value);
1520
1521         if (!virt_wire_setup) {
1522                 /*
1523                  * For LVT0 make it edge triggered, active high,
1524                  * external and enabled
1525                  */
1526                 value = apic_read(APIC_LVT0);
1527                 value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
1528                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
1529                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
1530                 value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
1531                 value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_EXTINT);
1532                 apic_write(APIC_LVT0, value);
1533         } else {
1534                 /* Disable LVT0 */
1535                 apic_write(APIC_LVT0, APIC_LVT_MASKED);
1536         }
1537
1538         /*
1539          * For LVT1 make it edge triggered, active high,
1540          * nmi and enabled
1541          */
1542         value = apic_read(APIC_LVT1);
1543         value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
1544                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
1545                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
1546         value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
1547         value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_NMI);
1548         apic_write(APIC_LVT1, value);
1549 }
1550
1551 void __cpuinit generic_processor_info(int apicid, int version)
1552 {
1553         int cpu;
1554         cpumask_t tmp_map;
1555
1556         /*
1557          * Validate version
1558          */
1559         if (version == 0x0) {
1560                 printk(KERN_WARNING "BIOS bug, APIC version is 0 for CPU#%d! "
1561                                 "fixing up to 0x10. (tell your hw vendor)\n",
1562                                 version);
1563                 version = 0x10;
1564         }
1565         apic_version[apicid] = version;
1566
1567         if (num_processors >= NR_CPUS) {
1568                 printk(KERN_WARNING "WARNING: NR_CPUS limit of %i reached."
1569                         "  Processor ignored.\n", NR_CPUS);
1570                 return;
1571         }
1572
1573         num_processors++;
1574         cpus_complement(tmp_map, cpu_present_map);
1575         cpu = first_cpu(tmp_map);
1576
1577         physid_set(apicid, phys_cpu_present_map);
1578         if (apicid == boot_cpu_physical_apicid) {
1579                 /*
1580                  * x86_bios_cpu_apicid is required to have processors listed
1581                  * in same order as logical cpu numbers. Hence the first
1582                  * entry is BSP, and so on.
1583                  */
1584                 cpu = 0;
1585         }
1586         if (apicid > max_physical_apicid)
1587                 max_physical_apicid = apicid;
1588
1589 #ifdef CONFIG_X86_32
1590         /*
1591          * Would be preferable to switch to bigsmp when CONFIG_HOTPLUG_CPU=y
1592          * but we need to work other dependencies like SMP_SUSPEND etc
1593          * before this can be done without some confusion.
1594          * if (CPU_HOTPLUG_ENABLED || num_processors > 8)
1595          *       - Ashok Raj <ashok.raj@intel.com>
1596          */
1597         if (max_physical_apicid >= 8) {
1598                 switch (boot_cpu_data.x86_vendor) {
1599                 case X86_VENDOR_INTEL:
1600                         if (!APIC_XAPIC(version)) {
1601                                 def_to_bigsmp = 0;
1602                                 break;
1603                         }
1604                         /* If P4 and above fall through */
1605                 case X86_VENDOR_AMD:
1606                         def_to_bigsmp = 1;
1607                 }
1608         }
1609 #endif
1610
1611 #if defined(CONFIG_X86_SMP) || defined(CONFIG_X86_64)
1612         /* are we being called early in kernel startup? */
1613         if (early_per_cpu_ptr(x86_cpu_to_apicid)) {
1614                 u16 *cpu_to_apicid = early_per_cpu_ptr(x86_cpu_to_apicid);
1615                 u16 *bios_cpu_apicid = early_per_cpu_ptr(x86_bios_cpu_apicid);
1616
1617                 cpu_to_apicid[cpu] = apicid;
1618                 bios_cpu_apicid[cpu] = apicid;
1619         } else {
1620                 per_cpu(x86_cpu_to_apicid, cpu) = apicid;
1621                 per_cpu(x86_bios_cpu_apicid, cpu) = apicid;
1622         }
1623 #endif
1624
1625         cpu_set(cpu, cpu_possible_map);
1626         cpu_set(cpu, cpu_present_map);
1627 }
1628
1629 #ifdef CONFIG_X86_64
1630 int hard_smp_processor_id(void)
1631 {
1632         return read_apic_id();
1633 }
1634 #endif
1635
1636 /*
1637  * Power management
1638  */
1639 #ifdef CONFIG_PM
1640
1641 static struct {
1642         /*
1643          * 'active' is true if the local APIC was enabled by us and
1644          * not the BIOS; this signifies that we are also responsible
1645          * for disabling it before entering apm/acpi suspend
1646          */
1647         int active;
1648         /* r/w apic fields */
1649         unsigned int apic_id;
1650         unsigned int apic_taskpri;
1651         unsigned int apic_ldr;
1652         unsigned int apic_dfr;
1653         unsigned int apic_spiv;
1654         unsigned int apic_lvtt;
1655         unsigned int apic_lvtpc;
1656         unsigned int apic_lvt0;
1657         unsigned int apic_lvt1;
1658         unsigned int apic_lvterr;
1659         unsigned int apic_tmict;
1660         unsigned int apic_tdcr;
1661         unsigned int apic_thmr;
1662 } apic_pm_state;
1663
1664 static int lapic_suspend(struct sys_device *dev, pm_message_t state)
1665 {
1666         unsigned long flags;
1667         int maxlvt;
1668
1669         if (!apic_pm_state.active)
1670                 return 0;
1671
1672         maxlvt = lapic_get_maxlvt();
1673
1674         apic_pm_state.apic_id = apic_read(APIC_ID);
1675         apic_pm_state.apic_taskpri = apic_read(APIC_TASKPRI);
1676         apic_pm_state.apic_ldr = apic_read(APIC_LDR);
1677         apic_pm_state.apic_dfr = apic_read(APIC_DFR);
1678         apic_pm_state.apic_spiv = apic_read(APIC_SPIV);
1679         apic_pm_state.apic_lvtt = apic_read(APIC_LVTT);
1680         if (maxlvt >= 4)
1681                 apic_pm_state.apic_lvtpc = apic_read(APIC_LVTPC);
1682         apic_pm_state.apic_lvt0 = apic_read(APIC_LVT0);
1683         apic_pm_state.apic_lvt1 = apic_read(APIC_LVT1);
1684         apic_pm_state.apic_lvterr = apic_read(APIC_LVTERR);
1685         apic_pm_state.apic_tmict = apic_read(APIC_TMICT);
1686         apic_pm_state.apic_tdcr = apic_read(APIC_TDCR);
1687 #if defined(CONFIG_X86_MCE_P4THERMAL) || defined(CONFIG_X86_MCE_INTEL)
1688         if (maxlvt >= 5)
1689                 apic_pm_state.apic_thmr = apic_read(APIC_LVTTHMR);
1690 #endif
1691
1692         local_irq_save(flags);
1693         disable_local_APIC();
1694         local_irq_restore(flags);
1695         return 0;
1696 }
1697
1698 static int lapic_resume(struct sys_device *dev)
1699 {
1700         unsigned int l, h;
1701         unsigned long flags;
1702         int maxlvt;
1703
1704         if (!apic_pm_state.active)
1705                 return 0;
1706
1707         maxlvt = lapic_get_maxlvt();
1708
1709         local_irq_save(flags);
1710
1711         {
1712                 /*
1713                  * Make sure the APICBASE points to the right address
1714                  *
1715                  * FIXME! This will be wrong if we ever support suspend on
1716                  * SMP! We'll need to do this as part of the CPU restore!
1717                  */
1718                 rdmsr(MSR_IA32_APICBASE, l, h);
1719                 l &= ~MSR_IA32_APICBASE_BASE;
1720                 l |= MSR_IA32_APICBASE_ENABLE | mp_lapic_addr;
1721                 wrmsr(MSR_IA32_APICBASE, l, h);
1722         }
1723
1724         apic_write(APIC_LVTERR, ERROR_APIC_VECTOR | APIC_LVT_MASKED);
1725         apic_write(APIC_ID, apic_pm_state.apic_id);
1726         apic_write(APIC_DFR, apic_pm_state.apic_dfr);
1727         apic_write(APIC_LDR, apic_pm_state.apic_ldr);
1728         apic_write(APIC_TASKPRI, apic_pm_state.apic_taskpri);
1729         apic_write(APIC_SPIV, apic_pm_state.apic_spiv);
1730         apic_write(APIC_LVT0, apic_pm_state.apic_lvt0);
1731         apic_write(APIC_LVT1, apic_pm_state.apic_lvt1);
1732 #if defined(CONFIG_X86_MCE_P4THERMAL) || defined(CONFIG_X86_MCE_INTEL)
1733         if (maxlvt >= 5)
1734                 apic_write(APIC_LVTTHMR, apic_pm_state.apic_thmr);
1735 #endif
1736         if (maxlvt >= 4)
1737                 apic_write(APIC_LVTPC, apic_pm_state.apic_lvtpc);
1738         apic_write(APIC_LVTT, apic_pm_state.apic_lvtt);
1739         apic_write(APIC_TDCR, apic_pm_state.apic_tdcr);
1740         apic_write(APIC_TMICT, apic_pm_state.apic_tmict);
1741         apic_write(APIC_ESR, 0);
1742         apic_read(APIC_ESR);
1743         apic_write(APIC_LVTERR, apic_pm_state.apic_lvterr);
1744         apic_write(APIC_ESR, 0);
1745         apic_read(APIC_ESR);
1746
1747         local_irq_restore(flags);
1748
1749         return 0;
1750 }
1751
1752 /*
1753  * This device has no shutdown method - fully functioning local APICs
1754  * are needed on every CPU up until machine_halt/restart/poweroff.
1755  */
1756
1757 static struct sysdev_class lapic_sysclass = {
1758         .name           = "lapic",
1759         .resume         = lapic_resume,
1760         .suspend        = lapic_suspend,
1761 };
1762
1763 static struct sys_device device_lapic = {
1764         .id     = 0,
1765         .cls    = &lapic_sysclass,
1766 };
1767
1768 static void __cpuinit apic_pm_activate(void)
1769 {
1770         apic_pm_state.active = 1;
1771 }
1772
1773 static int __init init_lapic_sysfs(void)
1774 {
1775         int error;
1776
1777         if (!cpu_has_apic)
1778                 return 0;
1779         /* XXX: remove suspend/resume procs if !apic_pm_state.active? */
1780
1781         error = sysdev_class_register(&lapic_sysclass);
1782         if (!error)
1783                 error = sysdev_register(&device_lapic);
1784         return error;
1785 }
1786 device_initcall(init_lapic_sysfs);
1787
1788 #else   /* CONFIG_PM */
1789
1790 static void apic_pm_activate(void) { }
1791
1792 #endif  /* CONFIG_PM */
1793
1794 #ifdef CONFIG_X86_64
1795 /*
1796  * apic_is_clustered_box() -- Check if we can expect good TSC
1797  *
1798  * Thus far, the major user of this is IBM's Summit2 series:
1799  *
1800  * Clustered boxes may have unsynced TSC problems if they are
1801  * multi-chassis. Use available data to take a good guess.
1802  * If in doubt, go HPET.
1803  */
1804 __cpuinit int apic_is_clustered_box(void)
1805 {
1806         int i, clusters, zeros;
1807         unsigned id;
1808         u16 *bios_cpu_apicid;
1809         DECLARE_BITMAP(clustermap, NUM_APIC_CLUSTERS);
1810
1811         /*
1812          * there is not this kind of box with AMD CPU yet.
1813          * Some AMD box with quadcore cpu and 8 sockets apicid
1814          * will be [4, 0x23] or [8, 0x27] could be thought to
1815          * vsmp box still need checking...
1816          */
1817         if ((boot_cpu_data.x86_vendor == X86_VENDOR_AMD) && !is_vsmp_box())
1818                 return 0;
1819
1820         bios_cpu_apicid = early_per_cpu_ptr(x86_bios_cpu_apicid);
1821         bitmap_zero(clustermap, NUM_APIC_CLUSTERS);
1822
1823         for (i = 0; i < NR_CPUS; i++) {
1824                 /* are we being called early in kernel startup? */
1825                 if (bios_cpu_apicid) {
1826                         id = bios_cpu_apicid[i];
1827                 }
1828                 else if (i < nr_cpu_ids) {
1829                         if (cpu_present(i))
1830                                 id = per_cpu(x86_bios_cpu_apicid, i);
1831                         else
1832                                 continue;
1833                 }
1834                 else
1835                         break;
1836
1837                 if (id != BAD_APICID)
1838                         __set_bit(APIC_CLUSTERID(id), clustermap);
1839         }
1840
1841         /* Problem:  Partially populated chassis may not have CPUs in some of
1842          * the APIC clusters they have been allocated.  Only present CPUs have
1843          * x86_bios_cpu_apicid entries, thus causing zeroes in the bitmap.
1844          * Since clusters are allocated sequentially, count zeros only if
1845          * they are bounded by ones.
1846          */
1847         clusters = 0;
1848         zeros = 0;
1849         for (i = 0; i < NUM_APIC_CLUSTERS; i++) {
1850                 if (test_bit(i, clustermap)) {
1851                         clusters += 1 + zeros;
1852                         zeros = 0;
1853                 } else
1854                         ++zeros;
1855         }
1856
1857         /* ScaleMP vSMPowered boxes have one cluster per board and TSCs are
1858          * not guaranteed to be synced between boards
1859          */
1860         if (is_vsmp_box() && clusters > 1)
1861                 return 1;
1862
1863         /*
1864          * If clusters > 2, then should be multi-chassis.
1865          * May have to revisit this when multi-core + hyperthreaded CPUs come
1866          * out, but AFAIK this will work even for them.
1867          */
1868         return (clusters > 2);
1869 }
1870 #endif
1871
1872 /*
1873  * APIC command line parameters
1874  */
1875 static int __init setup_disableapic(char *arg)
1876 {
1877         disable_apic = 1;
1878         setup_clear_cpu_cap(X86_FEATURE_APIC);
1879         return 0;
1880 }
1881 early_param("disableapic", setup_disableapic);
1882
1883 /* same as disableapic, for compatibility */
1884 static int __init setup_nolapic(char *arg)
1885 {
1886         return setup_disableapic(arg);
1887 }
1888 early_param("nolapic", setup_nolapic);
1889
1890 static int __init parse_lapic_timer_c2_ok(char *arg)
1891 {
1892         local_apic_timer_c2_ok = 1;
1893         return 0;
1894 }
1895 early_param("lapic_timer_c2_ok", parse_lapic_timer_c2_ok);
1896
1897 static int __init parse_disable_apic_timer(char *arg)
1898 {
1899         disable_apic_timer = 1;
1900         return 0;
1901 }
1902 early_param("noapictimer", parse_disable_apic_timer);
1903
1904 static int __init parse_nolapic_timer(char *arg)
1905 {
1906         disable_apic_timer = 1;
1907         return 0;
1908 }
1909 early_param("nolapic_timer", parse_nolapic_timer);
1910
1911 static int __init apic_set_verbosity(char *arg)
1912 {
1913         if (!arg)  {
1914 #ifdef CONFIG_X86_64
1915                 skip_ioapic_setup = 0;
1916                 ioapic_force = 1;
1917                 return 0;
1918 #endif
1919                 return -EINVAL;
1920         }
1921
1922         if (strcmp("debug", arg) == 0)
1923                 apic_verbosity = APIC_DEBUG;
1924         else if (strcmp("verbose", arg) == 0)
1925                 apic_verbosity = APIC_VERBOSE;
1926         else {
1927                 printk(KERN_WARNING "APIC Verbosity level %s not recognised"
1928                         " use apic=verbose or apic=debug\n", arg);
1929                 return -EINVAL;
1930         }
1931
1932         return 0;
1933 }
1934 early_param("apic", apic_set_verbosity);
1935
1936 static int __init lapic_insert_resource(void)
1937 {
1938         if (!apic_phys)
1939                 return -1;
1940
1941         /* Put local APIC into the resource map. */
1942         lapic_resource.start = apic_phys;
1943         lapic_resource.end = lapic_resource.start + PAGE_SIZE - 1;
1944         insert_resource(&iomem_resource, &lapic_resource);
1945
1946         return 0;
1947 }
1948
1949 /*
1950  * need call insert after e820_reserve_resources()
1951  * that is using request_resource
1952  */
1953 late_initcall(lapic_insert_resource);