Merge branch 'x86-apic-cleanups-for-linus' of git://git.kernel.org/pub/scm/linux...
[pandora-kernel.git] / arch / x86 / kernel / apic / apic.c
1 /*
2  *      Local APIC handling, local APIC timers
3  *
4  *      (c) 1999, 2000, 2009 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/perf_event.h>
18 #include <linux/kernel_stat.h>
19 #include <linux/mc146818rtc.h>
20 #include <linux/acpi_pmtmr.h>
21 #include <linux/clockchips.h>
22 #include <linux/interrupt.h>
23 #include <linux/bootmem.h>
24 #include <linux/ftrace.h>
25 #include <linux/ioport.h>
26 #include <linux/module.h>
27 #include <linux/sysdev.h>
28 #include <linux/delay.h>
29 #include <linux/timex.h>
30 #include <linux/dmar.h>
31 #include <linux/init.h>
32 #include <linux/cpu.h>
33 #include <linux/dmi.h>
34 #include <linux/smp.h>
35 #include <linux/mm.h>
36
37 #include <asm/perf_event.h>
38 #include <asm/x86_init.h>
39 #include <asm/pgalloc.h>
40 #include <asm/atomic.h>
41 #include <asm/mpspec.h>
42 #include <asm/i8253.h>
43 #include <asm/i8259.h>
44 #include <asm/proto.h>
45 #include <asm/apic.h>
46 #include <asm/desc.h>
47 #include <asm/hpet.h>
48 #include <asm/idle.h>
49 #include <asm/mtrr.h>
50 #include <asm/smp.h>
51 #include <asm/mce.h>
52 #include <asm/kvm_para.h>
53 #include <asm/tsc.h>
54
55 unsigned int num_processors;
56
57 unsigned disabled_cpus __cpuinitdata;
58
59 /* Processor that is doing the boot up */
60 unsigned int boot_cpu_physical_apicid = -1U;
61
62 /*
63  * The highest APIC ID seen during enumeration.
64  */
65 unsigned int max_physical_apicid;
66
67 /*
68  * Bitmask of physically existing CPUs:
69  */
70 physid_mask_t phys_cpu_present_map;
71
72 /*
73  * Map cpu index to physical APIC ID
74  */
75 DEFINE_EARLY_PER_CPU(u16, x86_cpu_to_apicid, BAD_APICID);
76 DEFINE_EARLY_PER_CPU(u16, x86_bios_cpu_apicid, BAD_APICID);
77 EXPORT_EARLY_PER_CPU_SYMBOL(x86_cpu_to_apicid);
78 EXPORT_EARLY_PER_CPU_SYMBOL(x86_bios_cpu_apicid);
79
80 #ifdef CONFIG_X86_32
81 /*
82  * Knob to control our willingness to enable the local APIC.
83  *
84  * +1=force-enable
85  */
86 static int force_enable_local_apic;
87 /*
88  * APIC command line parameters
89  */
90 static int __init parse_lapic(char *arg)
91 {
92         force_enable_local_apic = 1;
93         return 0;
94 }
95 early_param("lapic", parse_lapic);
96 /* Local APIC was disabled by the BIOS and enabled by the kernel */
97 static int enabled_via_apicbase;
98
99 /*
100  * Handle interrupt mode configuration register (IMCR).
101  * This register controls whether the interrupt signals
102  * that reach the BSP come from the master PIC or from the
103  * local APIC. Before entering Symmetric I/O Mode, either
104  * the BIOS or the operating system must switch out of
105  * PIC Mode by changing the IMCR.
106  */
107 static inline void imcr_pic_to_apic(void)
108 {
109         /* select IMCR register */
110         outb(0x70, 0x22);
111         /* NMI and 8259 INTR go through APIC */
112         outb(0x01, 0x23);
113 }
114
115 static inline void imcr_apic_to_pic(void)
116 {
117         /* select IMCR register */
118         outb(0x70, 0x22);
119         /* NMI and 8259 INTR go directly to BSP */
120         outb(0x00, 0x23);
121 }
122 #endif
123
124 #ifdef CONFIG_X86_64
125 static int apic_calibrate_pmtmr __initdata;
126 static __init int setup_apicpmtimer(char *s)
127 {
128         apic_calibrate_pmtmr = 1;
129         notsc_setup(NULL);
130         return 0;
131 }
132 __setup("apicpmtimer", setup_apicpmtimer);
133 #endif
134
135 int x2apic_mode;
136 #ifdef CONFIG_X86_X2APIC
137 /* x2apic enabled before OS handover */
138 static int x2apic_preenabled;
139 static __init int setup_nox2apic(char *str)
140 {
141         if (x2apic_enabled()) {
142                 pr_warning("Bios already enabled x2apic, "
143                            "can't enforce nox2apic");
144                 return 0;
145         }
146
147         setup_clear_cpu_cap(X86_FEATURE_X2APIC);
148         return 0;
149 }
150 early_param("nox2apic", setup_nox2apic);
151 #endif
152
153 unsigned long mp_lapic_addr;
154 int disable_apic;
155 /* Disable local APIC timer from the kernel commandline or via dmi quirk */
156 static int disable_apic_timer __cpuinitdata;
157 /* Local APIC timer works in C2 */
158 int local_apic_timer_c2_ok;
159 EXPORT_SYMBOL_GPL(local_apic_timer_c2_ok);
160
161 int first_system_vector = 0xfe;
162
163 /*
164  * Debug level, exported for io_apic.c
165  */
166 unsigned int apic_verbosity;
167
168 int pic_mode;
169
170 /* Have we found an MP table */
171 int smp_found_config;
172
173 static struct resource lapic_resource = {
174         .name = "Local APIC",
175         .flags = IORESOURCE_MEM | IORESOURCE_BUSY,
176 };
177
178 static unsigned int calibration_result;
179
180 static int lapic_next_event(unsigned long delta,
181                             struct clock_event_device *evt);
182 static void lapic_timer_setup(enum clock_event_mode mode,
183                               struct clock_event_device *evt);
184 static void lapic_timer_broadcast(const struct cpumask *mask);
185 static void apic_pm_activate(void);
186
187 /*
188  * The local apic timer can be used for any function which is CPU local.
189  */
190 static struct clock_event_device lapic_clockevent = {
191         .name           = "lapic",
192         .features       = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT
193                         | CLOCK_EVT_FEAT_C3STOP | CLOCK_EVT_FEAT_DUMMY,
194         .shift          = 32,
195         .set_mode       = lapic_timer_setup,
196         .set_next_event = lapic_next_event,
197         .broadcast      = lapic_timer_broadcast,
198         .rating         = 100,
199         .irq            = -1,
200 };
201 static DEFINE_PER_CPU(struct clock_event_device, lapic_events);
202
203 static unsigned long apic_phys;
204
205 /*
206  * Get the LAPIC version
207  */
208 static inline int lapic_get_version(void)
209 {
210         return GET_APIC_VERSION(apic_read(APIC_LVR));
211 }
212
213 /*
214  * Check, if the APIC is integrated or a separate chip
215  */
216 static inline int lapic_is_integrated(void)
217 {
218 #ifdef CONFIG_X86_64
219         return 1;
220 #else
221         return APIC_INTEGRATED(lapic_get_version());
222 #endif
223 }
224
225 /*
226  * Check, whether this is a modern or a first generation APIC
227  */
228 static int modern_apic(void)
229 {
230         /* AMD systems use old APIC versions, so check the CPU */
231         if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD &&
232             boot_cpu_data.x86 >= 0xf)
233                 return 1;
234         return lapic_get_version() >= 0x14;
235 }
236
237 /*
238  * right after this call apic become NOOP driven
239  * so apic->write/read doesn't do anything
240  */
241 void apic_disable(void)
242 {
243         pr_info("APIC: switched to apic NOOP\n");
244         apic = &apic_noop;
245 }
246
247 void native_apic_wait_icr_idle(void)
248 {
249         while (apic_read(APIC_ICR) & APIC_ICR_BUSY)
250                 cpu_relax();
251 }
252
253 u32 native_safe_apic_wait_icr_idle(void)
254 {
255         u32 send_status;
256         int timeout;
257
258         timeout = 0;
259         do {
260                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
261                 if (!send_status)
262                         break;
263                 udelay(100);
264         } while (timeout++ < 1000);
265
266         return send_status;
267 }
268
269 void native_apic_icr_write(u32 low, u32 id)
270 {
271         apic_write(APIC_ICR2, SET_APIC_DEST_FIELD(id));
272         apic_write(APIC_ICR, low);
273 }
274
275 u64 native_apic_icr_read(void)
276 {
277         u32 icr1, icr2;
278
279         icr2 = apic_read(APIC_ICR2);
280         icr1 = apic_read(APIC_ICR);
281
282         return icr1 | ((u64)icr2 << 32);
283 }
284
285 /**
286  * enable_NMI_through_LVT0 - enable NMI through local vector table 0
287  */
288 void __cpuinit enable_NMI_through_LVT0(void)
289 {
290         unsigned int v;
291
292         /* unmask and set to NMI */
293         v = APIC_DM_NMI;
294
295         /* Level triggered for 82489DX (32bit mode) */
296         if (!lapic_is_integrated())
297                 v |= APIC_LVT_LEVEL_TRIGGER;
298
299         apic_write(APIC_LVT0, v);
300 }
301
302 #ifdef CONFIG_X86_32
303 /**
304  * get_physical_broadcast - Get number of physical broadcast IDs
305  */
306 int get_physical_broadcast(void)
307 {
308         return modern_apic() ? 0xff : 0xf;
309 }
310 #endif
311
312 /**
313  * lapic_get_maxlvt - get the maximum number of local vector table entries
314  */
315 int lapic_get_maxlvt(void)
316 {
317         unsigned int v;
318
319         v = apic_read(APIC_LVR);
320         /*
321          * - we always have APIC integrated on 64bit mode
322          * - 82489DXs do not report # of LVT entries
323          */
324         return APIC_INTEGRATED(GET_APIC_VERSION(v)) ? GET_APIC_MAXLVT(v) : 2;
325 }
326
327 /*
328  * Local APIC timer
329  */
330
331 /* Clock divisor */
332 #define APIC_DIVISOR 16
333
334 /*
335  * This function sets up the local APIC timer, with a timeout of
336  * 'clocks' APIC bus clock. During calibration we actually call
337  * this function twice on the boot CPU, once with a bogus timeout
338  * value, second time for real. The other (noncalibrating) CPUs
339  * call this function only once, with the real, calibrated value.
340  *
341  * We do reads before writes even if unnecessary, to get around the
342  * P5 APIC double write bug.
343  */
344 static void __setup_APIC_LVTT(unsigned int clocks, int oneshot, int irqen)
345 {
346         unsigned int lvtt_value, tmp_value;
347
348         lvtt_value = LOCAL_TIMER_VECTOR;
349         if (!oneshot)
350                 lvtt_value |= APIC_LVT_TIMER_PERIODIC;
351         if (!lapic_is_integrated())
352                 lvtt_value |= SET_APIC_TIMER_BASE(APIC_TIMER_BASE_DIV);
353
354         if (!irqen)
355                 lvtt_value |= APIC_LVT_MASKED;
356
357         apic_write(APIC_LVTT, lvtt_value);
358
359         /*
360          * Divide PICLK by 16
361          */
362         tmp_value = apic_read(APIC_TDCR);
363         apic_write(APIC_TDCR,
364                 (tmp_value & ~(APIC_TDR_DIV_1 | APIC_TDR_DIV_TMBASE)) |
365                 APIC_TDR_DIV_16);
366
367         if (!oneshot)
368                 apic_write(APIC_TMICT, clocks / APIC_DIVISOR);
369 }
370
371 /*
372  * Setup extended LVT, AMD specific
373  *
374  * Software should use the LVT offsets the BIOS provides.  The offsets
375  * are determined by the subsystems using it like those for MCE
376  * threshold or IBS.  On K8 only offset 0 (APIC500) and MCE interrupts
377  * are supported. Beginning with family 10h at least 4 offsets are
378  * available.
379  *
380  * Since the offsets must be consistent for all cores, we keep track
381  * of the LVT offsets in software and reserve the offset for the same
382  * vector also to be used on other cores. An offset is freed by
383  * setting the entry to APIC_EILVT_MASKED.
384  *
385  * If the BIOS is right, there should be no conflicts. Otherwise a
386  * "[Firmware Bug]: ..." error message is generated. However, if
387  * software does not properly determines the offsets, it is not
388  * necessarily a BIOS bug.
389  */
390
391 static atomic_t eilvt_offsets[APIC_EILVT_NR_MAX];
392
393 static inline int eilvt_entry_is_changeable(unsigned int old, unsigned int new)
394 {
395         return (old & APIC_EILVT_MASKED)
396                 || (new == APIC_EILVT_MASKED)
397                 || ((new & ~APIC_EILVT_MASKED) == old);
398 }
399
400 static unsigned int reserve_eilvt_offset(int offset, unsigned int new)
401 {
402         unsigned int rsvd;                      /* 0: uninitialized */
403
404         if (offset >= APIC_EILVT_NR_MAX)
405                 return ~0;
406
407         rsvd = atomic_read(&eilvt_offsets[offset]) & ~APIC_EILVT_MASKED;
408         do {
409                 if (rsvd &&
410                     !eilvt_entry_is_changeable(rsvd, new))
411                         /* may not change if vectors are different */
412                         return rsvd;
413                 rsvd = atomic_cmpxchg(&eilvt_offsets[offset], rsvd, new);
414         } while (rsvd != new);
415
416         return new;
417 }
418
419 /*
420  * If mask=1, the LVT entry does not generate interrupts while mask=0
421  * enables the vector. See also the BKDGs.
422  */
423
424 int setup_APIC_eilvt(u8 offset, u8 vector, u8 msg_type, u8 mask)
425 {
426         unsigned long reg = APIC_EILVTn(offset);
427         unsigned int new, old, reserved;
428
429         new = (mask << 16) | (msg_type << 8) | vector;
430         old = apic_read(reg);
431         reserved = reserve_eilvt_offset(offset, new);
432
433         if (reserved != new) {
434                 pr_err(FW_BUG "cpu %d, try to use APIC%lX (LVT offset %d) for "
435                        "vector 0x%x, but the register is already in use for "
436                        "vector 0x%x on another cpu\n",
437                        smp_processor_id(), reg, offset, new, reserved);
438                 return -EINVAL;
439         }
440
441         if (!eilvt_entry_is_changeable(old, new)) {
442                 pr_err(FW_BUG "cpu %d, try to use APIC%lX (LVT offset %d) for "
443                        "vector 0x%x, but the register is already in use for "
444                        "vector 0x%x on this cpu\n",
445                        smp_processor_id(), reg, offset, new, old);
446                 return -EBUSY;
447         }
448
449         apic_write(reg, new);
450
451         return 0;
452 }
453 EXPORT_SYMBOL_GPL(setup_APIC_eilvt);
454
455 /*
456  * Program the next event, relative to now
457  */
458 static int lapic_next_event(unsigned long delta,
459                             struct clock_event_device *evt)
460 {
461         apic_write(APIC_TMICT, delta);
462         return 0;
463 }
464
465 /*
466  * Setup the lapic timer in periodic or oneshot mode
467  */
468 static void lapic_timer_setup(enum clock_event_mode mode,
469                               struct clock_event_device *evt)
470 {
471         unsigned long flags;
472         unsigned int v;
473
474         /* Lapic used as dummy for broadcast ? */
475         if (evt->features & CLOCK_EVT_FEAT_DUMMY)
476                 return;
477
478         local_irq_save(flags);
479
480         switch (mode) {
481         case CLOCK_EVT_MODE_PERIODIC:
482         case CLOCK_EVT_MODE_ONESHOT:
483                 __setup_APIC_LVTT(calibration_result,
484                                   mode != CLOCK_EVT_MODE_PERIODIC, 1);
485                 break;
486         case CLOCK_EVT_MODE_UNUSED:
487         case CLOCK_EVT_MODE_SHUTDOWN:
488                 v = apic_read(APIC_LVTT);
489                 v |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
490                 apic_write(APIC_LVTT, v);
491                 apic_write(APIC_TMICT, 0);
492                 break;
493         case CLOCK_EVT_MODE_RESUME:
494                 /* Nothing to do here */
495                 break;
496         }
497
498         local_irq_restore(flags);
499 }
500
501 /*
502  * Local APIC timer broadcast function
503  */
504 static void lapic_timer_broadcast(const struct cpumask *mask)
505 {
506 #ifdef CONFIG_SMP
507         apic->send_IPI_mask(mask, LOCAL_TIMER_VECTOR);
508 #endif
509 }
510
511 /*
512  * Setup the local APIC timer for this CPU. Copy the initialized values
513  * of the boot CPU and register the clock event in the framework.
514  */
515 static void __cpuinit setup_APIC_timer(void)
516 {
517         struct clock_event_device *levt = &__get_cpu_var(lapic_events);
518
519         if (cpu_has(&current_cpu_data, X86_FEATURE_ARAT)) {
520                 lapic_clockevent.features &= ~CLOCK_EVT_FEAT_C3STOP;
521                 /* Make LAPIC timer preferrable over percpu HPET */
522                 lapic_clockevent.rating = 150;
523         }
524
525         memcpy(levt, &lapic_clockevent, sizeof(*levt));
526         levt->cpumask = cpumask_of(smp_processor_id());
527
528         clockevents_register_device(levt);
529 }
530
531 /*
532  * In this functions we calibrate APIC bus clocks to the external timer.
533  *
534  * We want to do the calibration only once since we want to have local timer
535  * irqs syncron. CPUs connected by the same APIC bus have the very same bus
536  * frequency.
537  *
538  * This was previously done by reading the PIT/HPET and waiting for a wrap
539  * around to find out, that a tick has elapsed. I have a box, where the PIT
540  * readout is broken, so it never gets out of the wait loop again. This was
541  * also reported by others.
542  *
543  * Monitoring the jiffies value is inaccurate and the clockevents
544  * infrastructure allows us to do a simple substitution of the interrupt
545  * handler.
546  *
547  * The calibration routine also uses the pm_timer when possible, as the PIT
548  * happens to run way too slow (factor 2.3 on my VAIO CoreDuo, which goes
549  * back to normal later in the boot process).
550  */
551
552 #define LAPIC_CAL_LOOPS         (HZ/10)
553
554 static __initdata int lapic_cal_loops = -1;
555 static __initdata long lapic_cal_t1, lapic_cal_t2;
556 static __initdata unsigned long long lapic_cal_tsc1, lapic_cal_tsc2;
557 static __initdata unsigned long lapic_cal_pm1, lapic_cal_pm2;
558 static __initdata unsigned long lapic_cal_j1, lapic_cal_j2;
559
560 /*
561  * Temporary interrupt handler.
562  */
563 static void __init lapic_cal_handler(struct clock_event_device *dev)
564 {
565         unsigned long long tsc = 0;
566         long tapic = apic_read(APIC_TMCCT);
567         unsigned long pm = acpi_pm_read_early();
568
569         if (cpu_has_tsc)
570                 rdtscll(tsc);
571
572         switch (lapic_cal_loops++) {
573         case 0:
574                 lapic_cal_t1 = tapic;
575                 lapic_cal_tsc1 = tsc;
576                 lapic_cal_pm1 = pm;
577                 lapic_cal_j1 = jiffies;
578                 break;
579
580         case LAPIC_CAL_LOOPS:
581                 lapic_cal_t2 = tapic;
582                 lapic_cal_tsc2 = tsc;
583                 if (pm < lapic_cal_pm1)
584                         pm += ACPI_PM_OVRRUN;
585                 lapic_cal_pm2 = pm;
586                 lapic_cal_j2 = jiffies;
587                 break;
588         }
589 }
590
591 static int __init
592 calibrate_by_pmtimer(long deltapm, long *delta, long *deltatsc)
593 {
594         const long pm_100ms = PMTMR_TICKS_PER_SEC / 10;
595         const long pm_thresh = pm_100ms / 100;
596         unsigned long mult;
597         u64 res;
598
599 #ifndef CONFIG_X86_PM_TIMER
600         return -1;
601 #endif
602
603         apic_printk(APIC_VERBOSE, "... PM-Timer delta = %ld\n", deltapm);
604
605         /* Check, if the PM timer is available */
606         if (!deltapm)
607                 return -1;
608
609         mult = clocksource_hz2mult(PMTMR_TICKS_PER_SEC, 22);
610
611         if (deltapm > (pm_100ms - pm_thresh) &&
612             deltapm < (pm_100ms + pm_thresh)) {
613                 apic_printk(APIC_VERBOSE, "... PM-Timer result ok\n");
614                 return 0;
615         }
616
617         res = (((u64)deltapm) *  mult) >> 22;
618         do_div(res, 1000000);
619         pr_warning("APIC calibration not consistent "
620                    "with PM-Timer: %ldms instead of 100ms\n",(long)res);
621
622         /* Correct the lapic counter value */
623         res = (((u64)(*delta)) * pm_100ms);
624         do_div(res, deltapm);
625         pr_info("APIC delta adjusted to PM-Timer: "
626                 "%lu (%ld)\n", (unsigned long)res, *delta);
627         *delta = (long)res;
628
629         /* Correct the tsc counter value */
630         if (cpu_has_tsc) {
631                 res = (((u64)(*deltatsc)) * pm_100ms);
632                 do_div(res, deltapm);
633                 apic_printk(APIC_VERBOSE, "TSC delta adjusted to "
634                                           "PM-Timer: %lu (%ld)\n",
635                                         (unsigned long)res, *deltatsc);
636                 *deltatsc = (long)res;
637         }
638
639         return 0;
640 }
641
642 static int __init calibrate_APIC_clock(void)
643 {
644         struct clock_event_device *levt = &__get_cpu_var(lapic_events);
645         void (*real_handler)(struct clock_event_device *dev);
646         unsigned long deltaj;
647         long delta, deltatsc;
648         int pm_referenced = 0;
649
650         local_irq_disable();
651
652         /* Replace the global interrupt handler */
653         real_handler = global_clock_event->event_handler;
654         global_clock_event->event_handler = lapic_cal_handler;
655
656         /*
657          * Setup the APIC counter to maximum. There is no way the lapic
658          * can underflow in the 100ms detection time frame
659          */
660         __setup_APIC_LVTT(0xffffffff, 0, 0);
661
662         /* Let the interrupts run */
663         local_irq_enable();
664
665         while (lapic_cal_loops <= LAPIC_CAL_LOOPS)
666                 cpu_relax();
667
668         local_irq_disable();
669
670         /* Restore the real event handler */
671         global_clock_event->event_handler = real_handler;
672
673         /* Build delta t1-t2 as apic timer counts down */
674         delta = lapic_cal_t1 - lapic_cal_t2;
675         apic_printk(APIC_VERBOSE, "... lapic delta = %ld\n", delta);
676
677         deltatsc = (long)(lapic_cal_tsc2 - lapic_cal_tsc1);
678
679         /* we trust the PM based calibration if possible */
680         pm_referenced = !calibrate_by_pmtimer(lapic_cal_pm2 - lapic_cal_pm1,
681                                         &delta, &deltatsc);
682
683         /* Calculate the scaled math multiplication factor */
684         lapic_clockevent.mult = div_sc(delta, TICK_NSEC * LAPIC_CAL_LOOPS,
685                                        lapic_clockevent.shift);
686         lapic_clockevent.max_delta_ns =
687                 clockevent_delta2ns(0x7FFFFF, &lapic_clockevent);
688         lapic_clockevent.min_delta_ns =
689                 clockevent_delta2ns(0xF, &lapic_clockevent);
690
691         calibration_result = (delta * APIC_DIVISOR) / LAPIC_CAL_LOOPS;
692
693         apic_printk(APIC_VERBOSE, "..... delta %ld\n", delta);
694         apic_printk(APIC_VERBOSE, "..... mult: %u\n", lapic_clockevent.mult);
695         apic_printk(APIC_VERBOSE, "..... calibration result: %u\n",
696                     calibration_result);
697
698         if (cpu_has_tsc) {
699                 apic_printk(APIC_VERBOSE, "..... CPU clock speed is "
700                             "%ld.%04ld MHz.\n",
701                             (deltatsc / LAPIC_CAL_LOOPS) / (1000000 / HZ),
702                             (deltatsc / LAPIC_CAL_LOOPS) % (1000000 / HZ));
703         }
704
705         apic_printk(APIC_VERBOSE, "..... host bus clock speed is "
706                     "%u.%04u MHz.\n",
707                     calibration_result / (1000000 / HZ),
708                     calibration_result % (1000000 / HZ));
709
710         /*
711          * Do a sanity check on the APIC calibration result
712          */
713         if (calibration_result < (1000000 / HZ)) {
714                 local_irq_enable();
715                 pr_warning("APIC frequency too slow, disabling apic timer\n");
716                 return -1;
717         }
718
719         levt->features &= ~CLOCK_EVT_FEAT_DUMMY;
720
721         /*
722          * PM timer calibration failed or not turned on
723          * so lets try APIC timer based calibration
724          */
725         if (!pm_referenced) {
726                 apic_printk(APIC_VERBOSE, "... verify APIC timer\n");
727
728                 /*
729                  * Setup the apic timer manually
730                  */
731                 levt->event_handler = lapic_cal_handler;
732                 lapic_timer_setup(CLOCK_EVT_MODE_PERIODIC, levt);
733                 lapic_cal_loops = -1;
734
735                 /* Let the interrupts run */
736                 local_irq_enable();
737
738                 while (lapic_cal_loops <= LAPIC_CAL_LOOPS)
739                         cpu_relax();
740
741                 /* Stop the lapic timer */
742                 lapic_timer_setup(CLOCK_EVT_MODE_SHUTDOWN, levt);
743
744                 /* Jiffies delta */
745                 deltaj = lapic_cal_j2 - lapic_cal_j1;
746                 apic_printk(APIC_VERBOSE, "... jiffies delta = %lu\n", deltaj);
747
748                 /* Check, if the jiffies result is consistent */
749                 if (deltaj >= LAPIC_CAL_LOOPS-2 && deltaj <= LAPIC_CAL_LOOPS+2)
750                         apic_printk(APIC_VERBOSE, "... jiffies result ok\n");
751                 else
752                         levt->features |= CLOCK_EVT_FEAT_DUMMY;
753         } else
754                 local_irq_enable();
755
756         if (levt->features & CLOCK_EVT_FEAT_DUMMY) {
757                 pr_warning("APIC timer disabled due to verification failure\n");
758                         return -1;
759         }
760
761         return 0;
762 }
763
764 /*
765  * Setup the boot APIC
766  *
767  * Calibrate and verify the result.
768  */
769 void __init setup_boot_APIC_clock(void)
770 {
771         /*
772          * The local apic timer can be disabled via the kernel
773          * commandline or from the CPU detection code. Register the lapic
774          * timer as a dummy clock event source on SMP systems, so the
775          * broadcast mechanism is used. On UP systems simply ignore it.
776          */
777         if (disable_apic_timer) {
778                 pr_info("Disabling APIC timer\n");
779                 /* No broadcast on UP ! */
780                 if (num_possible_cpus() > 1) {
781                         lapic_clockevent.mult = 1;
782                         setup_APIC_timer();
783                 }
784                 return;
785         }
786
787         apic_printk(APIC_VERBOSE, "Using local APIC timer interrupts.\n"
788                     "calibrating APIC timer ...\n");
789
790         if (calibrate_APIC_clock()) {
791                 /* No broadcast on UP ! */
792                 if (num_possible_cpus() > 1)
793                         setup_APIC_timer();
794                 return;
795         }
796
797         /*
798          * If nmi_watchdog is set to IO_APIC, we need the
799          * PIT/HPET going.  Otherwise register lapic as a dummy
800          * device.
801          */
802         lapic_clockevent.features &= ~CLOCK_EVT_FEAT_DUMMY;
803
804         /* Setup the lapic or request the broadcast */
805         setup_APIC_timer();
806 }
807
808 void __cpuinit setup_secondary_APIC_clock(void)
809 {
810         setup_APIC_timer();
811 }
812
813 /*
814  * The guts of the apic timer interrupt
815  */
816 static void local_apic_timer_interrupt(void)
817 {
818         int cpu = smp_processor_id();
819         struct clock_event_device *evt = &per_cpu(lapic_events, cpu);
820
821         /*
822          * Normally we should not be here till LAPIC has been initialized but
823          * in some cases like kdump, its possible that there is a pending LAPIC
824          * timer interrupt from previous kernel's context and is delivered in
825          * new kernel the moment interrupts are enabled.
826          *
827          * Interrupts are enabled early and LAPIC is setup much later, hence
828          * its possible that when we get here evt->event_handler is NULL.
829          * Check for event_handler being NULL and discard the interrupt as
830          * spurious.
831          */
832         if (!evt->event_handler) {
833                 pr_warning("Spurious LAPIC timer interrupt on cpu %d\n", cpu);
834                 /* Switch it off */
835                 lapic_timer_setup(CLOCK_EVT_MODE_SHUTDOWN, evt);
836                 return;
837         }
838
839         /*
840          * the NMI deadlock-detector uses this.
841          */
842         inc_irq_stat(apic_timer_irqs);
843
844         evt->event_handler(evt);
845 }
846
847 /*
848  * Local APIC timer interrupt. This is the most natural way for doing
849  * local interrupts, but local timer interrupts can be emulated by
850  * broadcast interrupts too. [in case the hw doesn't support APIC timers]
851  *
852  * [ if a single-CPU system runs an SMP kernel then we call the local
853  *   interrupt as well. Thus we cannot inline the local irq ... ]
854  */
855 void __irq_entry smp_apic_timer_interrupt(struct pt_regs *regs)
856 {
857         struct pt_regs *old_regs = set_irq_regs(regs);
858
859         /*
860          * NOTE! We'd better ACK the irq immediately,
861          * because timer handling can be slow.
862          */
863         ack_APIC_irq();
864         /*
865          * update_process_times() expects us to have done irq_enter().
866          * Besides, if we don't timer interrupts ignore the global
867          * interrupt lock, which is the WrongThing (tm) to do.
868          */
869         exit_idle();
870         irq_enter();
871         local_apic_timer_interrupt();
872         irq_exit();
873
874         set_irq_regs(old_regs);
875 }
876
877 int setup_profiling_timer(unsigned int multiplier)
878 {
879         return -EINVAL;
880 }
881
882 /*
883  * Local APIC start and shutdown
884  */
885
886 /**
887  * clear_local_APIC - shutdown the local APIC
888  *
889  * This is called, when a CPU is disabled and before rebooting, so the state of
890  * the local APIC has no dangling leftovers. Also used to cleanout any BIOS
891  * leftovers during boot.
892  */
893 void clear_local_APIC(void)
894 {
895         int maxlvt;
896         u32 v;
897
898         /* APIC hasn't been mapped yet */
899         if (!x2apic_mode && !apic_phys)
900                 return;
901
902         maxlvt = lapic_get_maxlvt();
903         /*
904          * Masking an LVT entry can trigger a local APIC error
905          * if the vector is zero. Mask LVTERR first to prevent this.
906          */
907         if (maxlvt >= 3) {
908                 v = ERROR_APIC_VECTOR; /* any non-zero vector will do */
909                 apic_write(APIC_LVTERR, v | APIC_LVT_MASKED);
910         }
911         /*
912          * Careful: we have to set masks only first to deassert
913          * any level-triggered sources.
914          */
915         v = apic_read(APIC_LVTT);
916         apic_write(APIC_LVTT, v | APIC_LVT_MASKED);
917         v = apic_read(APIC_LVT0);
918         apic_write(APIC_LVT0, v | APIC_LVT_MASKED);
919         v = apic_read(APIC_LVT1);
920         apic_write(APIC_LVT1, v | APIC_LVT_MASKED);
921         if (maxlvt >= 4) {
922                 v = apic_read(APIC_LVTPC);
923                 apic_write(APIC_LVTPC, v | APIC_LVT_MASKED);
924         }
925
926         /* lets not touch this if we didn't frob it */
927 #ifdef CONFIG_X86_THERMAL_VECTOR
928         if (maxlvt >= 5) {
929                 v = apic_read(APIC_LVTTHMR);
930                 apic_write(APIC_LVTTHMR, v | APIC_LVT_MASKED);
931         }
932 #endif
933 #ifdef CONFIG_X86_MCE_INTEL
934         if (maxlvt >= 6) {
935                 v = apic_read(APIC_LVTCMCI);
936                 if (!(v & APIC_LVT_MASKED))
937                         apic_write(APIC_LVTCMCI, v | APIC_LVT_MASKED);
938         }
939 #endif
940
941         /*
942          * Clean APIC state for other OSs:
943          */
944         apic_write(APIC_LVTT, APIC_LVT_MASKED);
945         apic_write(APIC_LVT0, APIC_LVT_MASKED);
946         apic_write(APIC_LVT1, APIC_LVT_MASKED);
947         if (maxlvt >= 3)
948                 apic_write(APIC_LVTERR, APIC_LVT_MASKED);
949         if (maxlvt >= 4)
950                 apic_write(APIC_LVTPC, APIC_LVT_MASKED);
951
952         /* Integrated APIC (!82489DX) ? */
953         if (lapic_is_integrated()) {
954                 if (maxlvt > 3)
955                         /* Clear ESR due to Pentium errata 3AP and 11AP */
956                         apic_write(APIC_ESR, 0);
957                 apic_read(APIC_ESR);
958         }
959 }
960
961 /**
962  * disable_local_APIC - clear and disable the local APIC
963  */
964 void disable_local_APIC(void)
965 {
966         unsigned int value;
967
968         /* APIC hasn't been mapped yet */
969         if (!x2apic_mode && !apic_phys)
970                 return;
971
972         clear_local_APIC();
973
974         /*
975          * Disable APIC (implies clearing of registers
976          * for 82489DX!).
977          */
978         value = apic_read(APIC_SPIV);
979         value &= ~APIC_SPIV_APIC_ENABLED;
980         apic_write(APIC_SPIV, value);
981
982 #ifdef CONFIG_X86_32
983         /*
984          * When LAPIC was disabled by the BIOS and enabled by the kernel,
985          * restore the disabled state.
986          */
987         if (enabled_via_apicbase) {
988                 unsigned int l, h;
989
990                 rdmsr(MSR_IA32_APICBASE, l, h);
991                 l &= ~MSR_IA32_APICBASE_ENABLE;
992                 wrmsr(MSR_IA32_APICBASE, l, h);
993         }
994 #endif
995 }
996
997 /*
998  * If Linux enabled the LAPIC against the BIOS default disable it down before
999  * re-entering the BIOS on shutdown.  Otherwise the BIOS may get confused and
1000  * not power-off.  Additionally clear all LVT entries before disable_local_APIC
1001  * for the case where Linux didn't enable the LAPIC.
1002  */
1003 void lapic_shutdown(void)
1004 {
1005         unsigned long flags;
1006
1007         if (!cpu_has_apic && !apic_from_smp_config())
1008                 return;
1009
1010         local_irq_save(flags);
1011
1012 #ifdef CONFIG_X86_32
1013         if (!enabled_via_apicbase)
1014                 clear_local_APIC();
1015         else
1016 #endif
1017                 disable_local_APIC();
1018
1019
1020         local_irq_restore(flags);
1021 }
1022
1023 /*
1024  * This is to verify that we're looking at a real local APIC.
1025  * Check these against your board if the CPUs aren't getting
1026  * started for no apparent reason.
1027  */
1028 int __init verify_local_APIC(void)
1029 {
1030         unsigned int reg0, reg1;
1031
1032         /*
1033          * The version register is read-only in a real APIC.
1034          */
1035         reg0 = apic_read(APIC_LVR);
1036         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg0);
1037         apic_write(APIC_LVR, reg0 ^ APIC_LVR_MASK);
1038         reg1 = apic_read(APIC_LVR);
1039         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg1);
1040
1041         /*
1042          * The two version reads above should print the same
1043          * numbers.  If the second one is different, then we
1044          * poke at a non-APIC.
1045          */
1046         if (reg1 != reg0)
1047                 return 0;
1048
1049         /*
1050          * Check if the version looks reasonably.
1051          */
1052         reg1 = GET_APIC_VERSION(reg0);
1053         if (reg1 == 0x00 || reg1 == 0xff)
1054                 return 0;
1055         reg1 = lapic_get_maxlvt();
1056         if (reg1 < 0x02 || reg1 == 0xff)
1057                 return 0;
1058
1059         /*
1060          * The ID register is read/write in a real APIC.
1061          */
1062         reg0 = apic_read(APIC_ID);
1063         apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg0);
1064         apic_write(APIC_ID, reg0 ^ apic->apic_id_mask);
1065         reg1 = apic_read(APIC_ID);
1066         apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg1);
1067         apic_write(APIC_ID, reg0);
1068         if (reg1 != (reg0 ^ apic->apic_id_mask))
1069                 return 0;
1070
1071         /*
1072          * The next two are just to see if we have sane values.
1073          * They're only really relevant if we're in Virtual Wire
1074          * compatibility mode, but most boxes are anymore.
1075          */
1076         reg0 = apic_read(APIC_LVT0);
1077         apic_printk(APIC_DEBUG, "Getting LVT0: %x\n", reg0);
1078         reg1 = apic_read(APIC_LVT1);
1079         apic_printk(APIC_DEBUG, "Getting LVT1: %x\n", reg1);
1080
1081         return 1;
1082 }
1083
1084 /**
1085  * sync_Arb_IDs - synchronize APIC bus arbitration IDs
1086  */
1087 void __init sync_Arb_IDs(void)
1088 {
1089         /*
1090          * Unsupported on P4 - see Intel Dev. Manual Vol. 3, Ch. 8.6.1 And not
1091          * needed on AMD.
1092          */
1093         if (modern_apic() || boot_cpu_data.x86_vendor == X86_VENDOR_AMD)
1094                 return;
1095
1096         /*
1097          * Wait for idle.
1098          */
1099         apic_wait_icr_idle();
1100
1101         apic_printk(APIC_DEBUG, "Synchronizing Arb IDs.\n");
1102         apic_write(APIC_ICR, APIC_DEST_ALLINC |
1103                         APIC_INT_LEVELTRIG | APIC_DM_INIT);
1104 }
1105
1106 /*
1107  * An initial setup of the virtual wire mode.
1108  */
1109 void __init init_bsp_APIC(void)
1110 {
1111         unsigned int value;
1112
1113         /*
1114          * Don't do the setup now if we have a SMP BIOS as the
1115          * through-I/O-APIC virtual wire mode might be active.
1116          */
1117         if (smp_found_config || !cpu_has_apic)
1118                 return;
1119
1120         /*
1121          * Do not trust the local APIC being empty at bootup.
1122          */
1123         clear_local_APIC();
1124
1125         /*
1126          * Enable APIC.
1127          */
1128         value = apic_read(APIC_SPIV);
1129         value &= ~APIC_VECTOR_MASK;
1130         value |= APIC_SPIV_APIC_ENABLED;
1131
1132 #ifdef CONFIG_X86_32
1133         /* This bit is reserved on P4/Xeon and should be cleared */
1134         if ((boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) &&
1135             (boot_cpu_data.x86 == 15))
1136                 value &= ~APIC_SPIV_FOCUS_DISABLED;
1137         else
1138 #endif
1139                 value |= APIC_SPIV_FOCUS_DISABLED;
1140         value |= SPURIOUS_APIC_VECTOR;
1141         apic_write(APIC_SPIV, value);
1142
1143         /*
1144          * Set up the virtual wire mode.
1145          */
1146         apic_write(APIC_LVT0, APIC_DM_EXTINT);
1147         value = APIC_DM_NMI;
1148         if (!lapic_is_integrated())             /* 82489DX */
1149                 value |= APIC_LVT_LEVEL_TRIGGER;
1150         apic_write(APIC_LVT1, value);
1151 }
1152
1153 static void __cpuinit lapic_setup_esr(void)
1154 {
1155         unsigned int oldvalue, value, maxlvt;
1156
1157         if (!lapic_is_integrated()) {
1158                 pr_info("No ESR for 82489DX.\n");
1159                 return;
1160         }
1161
1162         if (apic->disable_esr) {
1163                 /*
1164                  * Something untraceable is creating bad interrupts on
1165                  * secondary quads ... for the moment, just leave the
1166                  * ESR disabled - we can't do anything useful with the
1167                  * errors anyway - mbligh
1168                  */
1169                 pr_info("Leaving ESR disabled.\n");
1170                 return;
1171         }
1172
1173         maxlvt = lapic_get_maxlvt();
1174         if (maxlvt > 3)         /* Due to the Pentium erratum 3AP. */
1175                 apic_write(APIC_ESR, 0);
1176         oldvalue = apic_read(APIC_ESR);
1177
1178         /* enables sending errors */
1179         value = ERROR_APIC_VECTOR;
1180         apic_write(APIC_LVTERR, value);
1181
1182         /*
1183          * spec says clear errors after enabling vector.
1184          */
1185         if (maxlvt > 3)
1186                 apic_write(APIC_ESR, 0);
1187         value = apic_read(APIC_ESR);
1188         if (value != oldvalue)
1189                 apic_printk(APIC_VERBOSE, "ESR value before enabling "
1190                         "vector: 0x%08x  after: 0x%08x\n",
1191                         oldvalue, value);
1192 }
1193
1194 /**
1195  * setup_local_APIC - setup the local APIC
1196  *
1197  * Used to setup local APIC while initializing BSP or bringin up APs.
1198  * Always called with preemption disabled.
1199  */
1200 void __cpuinit setup_local_APIC(void)
1201 {
1202         int cpu = smp_processor_id();
1203         unsigned int value, queued;
1204         int i, j, acked = 0;
1205         unsigned long long tsc = 0, ntsc;
1206         long long max_loops = cpu_khz;
1207
1208         if (cpu_has_tsc)
1209                 rdtscll(tsc);
1210
1211         if (disable_apic) {
1212                 arch_disable_smp_support();
1213                 return;
1214         }
1215
1216 #ifdef CONFIG_X86_32
1217         /* Pound the ESR really hard over the head with a big hammer - mbligh */
1218         if (lapic_is_integrated() && apic->disable_esr) {
1219                 apic_write(APIC_ESR, 0);
1220                 apic_write(APIC_ESR, 0);
1221                 apic_write(APIC_ESR, 0);
1222                 apic_write(APIC_ESR, 0);
1223         }
1224 #endif
1225         perf_events_lapic_init();
1226
1227         /*
1228          * Double-check whether this APIC is really registered.
1229          * This is meaningless in clustered apic mode, so we skip it.
1230          */
1231         BUG_ON(!apic->apic_id_registered());
1232
1233         /*
1234          * Intel recommends to set DFR, LDR and TPR before enabling
1235          * an APIC.  See e.g. "AP-388 82489DX User's Manual" (Intel
1236          * document number 292116).  So here it goes...
1237          */
1238         apic->init_apic_ldr();
1239
1240         /*
1241          * Set Task Priority to 'accept all'. We never change this
1242          * later on.
1243          */
1244         value = apic_read(APIC_TASKPRI);
1245         value &= ~APIC_TPRI_MASK;
1246         apic_write(APIC_TASKPRI, value);
1247
1248         /*
1249          * After a crash, we no longer service the interrupts and a pending
1250          * interrupt from previous kernel might still have ISR bit set.
1251          *
1252          * Most probably by now CPU has serviced that pending interrupt and
1253          * it might not have done the ack_APIC_irq() because it thought,
1254          * interrupt came from i8259 as ExtInt. LAPIC did not get EOI so it
1255          * does not clear the ISR bit and cpu thinks it has already serivced
1256          * the interrupt. Hence a vector might get locked. It was noticed
1257          * for timer irq (vector 0x31). Issue an extra EOI to clear ISR.
1258          */
1259         do {
1260                 queued = 0;
1261                 for (i = APIC_ISR_NR - 1; i >= 0; i--)
1262                         queued |= apic_read(APIC_IRR + i*0x10);
1263
1264                 for (i = APIC_ISR_NR - 1; i >= 0; i--) {
1265                         value = apic_read(APIC_ISR + i*0x10);
1266                         for (j = 31; j >= 0; j--) {
1267                                 if (value & (1<<j)) {
1268                                         ack_APIC_irq();
1269                                         acked++;
1270                                 }
1271                         }
1272                 }
1273                 if (acked > 256) {
1274                         printk(KERN_ERR "LAPIC pending interrupts after %d EOI\n",
1275                                acked);
1276                         break;
1277                 }
1278                 if (cpu_has_tsc) {
1279                         rdtscll(ntsc);
1280                         max_loops = (cpu_khz << 10) - (ntsc - tsc);
1281                 } else
1282                         max_loops--;
1283         } while (queued && max_loops > 0);
1284         WARN_ON(max_loops <= 0);
1285
1286         /*
1287          * Now that we are all set up, enable the APIC
1288          */
1289         value = apic_read(APIC_SPIV);
1290         value &= ~APIC_VECTOR_MASK;
1291         /*
1292          * Enable APIC
1293          */
1294         value |= APIC_SPIV_APIC_ENABLED;
1295
1296 #ifdef CONFIG_X86_32
1297         /*
1298          * Some unknown Intel IO/APIC (or APIC) errata is biting us with
1299          * certain networking cards. If high frequency interrupts are
1300          * happening on a particular IOAPIC pin, plus the IOAPIC routing
1301          * entry is masked/unmasked at a high rate as well then sooner or
1302          * later IOAPIC line gets 'stuck', no more interrupts are received
1303          * from the device. If focus CPU is disabled then the hang goes
1304          * away, oh well :-(
1305          *
1306          * [ This bug can be reproduced easily with a level-triggered
1307          *   PCI Ne2000 networking cards and PII/PIII processors, dual
1308          *   BX chipset. ]
1309          */
1310         /*
1311          * Actually disabling the focus CPU check just makes the hang less
1312          * frequent as it makes the interrupt distributon model be more
1313          * like LRU than MRU (the short-term load is more even across CPUs).
1314          * See also the comment in end_level_ioapic_irq().  --macro
1315          */
1316
1317         /*
1318          * - enable focus processor (bit==0)
1319          * - 64bit mode always use processor focus
1320          *   so no need to set it
1321          */
1322         value &= ~APIC_SPIV_FOCUS_DISABLED;
1323 #endif
1324
1325         /*
1326          * Set spurious IRQ vector
1327          */
1328         value |= SPURIOUS_APIC_VECTOR;
1329         apic_write(APIC_SPIV, value);
1330
1331         /*
1332          * Set up LVT0, LVT1:
1333          *
1334          * set up through-local-APIC on the BP's LINT0. This is not
1335          * strictly necessary in pure symmetric-IO mode, but sometimes
1336          * we delegate interrupts to the 8259A.
1337          */
1338         /*
1339          * TODO: set up through-local-APIC from through-I/O-APIC? --macro
1340          */
1341         value = apic_read(APIC_LVT0) & APIC_LVT_MASKED;
1342         if (!cpu && (pic_mode || !value)) {
1343                 value = APIC_DM_EXTINT;
1344                 apic_printk(APIC_VERBOSE, "enabled ExtINT on CPU#%d\n", cpu);
1345         } else {
1346                 value = APIC_DM_EXTINT | APIC_LVT_MASKED;
1347                 apic_printk(APIC_VERBOSE, "masked ExtINT on CPU#%d\n", cpu);
1348         }
1349         apic_write(APIC_LVT0, value);
1350
1351         /*
1352          * only the BP should see the LINT1 NMI signal, obviously.
1353          */
1354         if (!cpu)
1355                 value = APIC_DM_NMI;
1356         else
1357                 value = APIC_DM_NMI | APIC_LVT_MASKED;
1358         if (!lapic_is_integrated())             /* 82489DX */
1359                 value |= APIC_LVT_LEVEL_TRIGGER;
1360         apic_write(APIC_LVT1, value);
1361
1362 #ifdef CONFIG_X86_MCE_INTEL
1363         /* Recheck CMCI information after local APIC is up on CPU #0 */
1364         if (!cpu)
1365                 cmci_recheck();
1366 #endif
1367 }
1368
1369 void __cpuinit end_local_APIC_setup(void)
1370 {
1371         lapic_setup_esr();
1372
1373 #ifdef CONFIG_X86_32
1374         {
1375                 unsigned int value;
1376                 /* Disable the local apic timer */
1377                 value = apic_read(APIC_LVTT);
1378                 value |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
1379                 apic_write(APIC_LVTT, value);
1380         }
1381 #endif
1382
1383         apic_pm_activate();
1384
1385         /*
1386          * Now that local APIC setup is completed for BP, configure the fault
1387          * handling for interrupt remapping.
1388          */
1389         if (!smp_processor_id() && intr_remapping_enabled)
1390                 enable_drhd_fault_handling();
1391
1392 }
1393
1394 #ifdef CONFIG_X86_X2APIC
1395 void check_x2apic(void)
1396 {
1397         if (x2apic_enabled()) {
1398                 pr_info("x2apic enabled by BIOS, switching to x2apic ops\n");
1399                 x2apic_preenabled = x2apic_mode = 1;
1400         }
1401 }
1402
1403 void enable_x2apic(void)
1404 {
1405         int msr, msr2;
1406
1407         if (!x2apic_mode)
1408                 return;
1409
1410         rdmsr(MSR_IA32_APICBASE, msr, msr2);
1411         if (!(msr & X2APIC_ENABLE)) {
1412                 printk_once(KERN_INFO "Enabling x2apic\n");
1413                 wrmsr(MSR_IA32_APICBASE, msr | X2APIC_ENABLE, 0);
1414         }
1415 }
1416 #endif /* CONFIG_X86_X2APIC */
1417
1418 int __init enable_IR(void)
1419 {
1420 #ifdef CONFIG_INTR_REMAP
1421         if (!intr_remapping_supported()) {
1422                 pr_debug("intr-remapping not supported\n");
1423                 return 0;
1424         }
1425
1426         if (!x2apic_preenabled && skip_ioapic_setup) {
1427                 pr_info("Skipped enabling intr-remap because of skipping "
1428                         "io-apic setup\n");
1429                 return 0;
1430         }
1431
1432         if (enable_intr_remapping(x2apic_supported()))
1433                 return 0;
1434
1435         pr_info("Enabled Interrupt-remapping\n");
1436
1437         return 1;
1438
1439 #endif
1440         return 0;
1441 }
1442
1443 void __init enable_IR_x2apic(void)
1444 {
1445         unsigned long flags;
1446         struct IO_APIC_route_entry **ioapic_entries = NULL;
1447         int ret, x2apic_enabled = 0;
1448         int dmar_table_init_ret;
1449
1450         dmar_table_init_ret = dmar_table_init();
1451         if (dmar_table_init_ret && !x2apic_supported())
1452                 return;
1453
1454         ioapic_entries = alloc_ioapic_entries();
1455         if (!ioapic_entries) {
1456                 pr_err("Allocate ioapic_entries failed\n");
1457                 goto out;
1458         }
1459
1460         ret = save_IO_APIC_setup(ioapic_entries);
1461         if (ret) {
1462                 pr_info("Saving IO-APIC state failed: %d\n", ret);
1463                 goto out;
1464         }
1465
1466         local_irq_save(flags);
1467         legacy_pic->mask_all();
1468         mask_IO_APIC_setup(ioapic_entries);
1469
1470         if (dmar_table_init_ret)
1471                 ret = 0;
1472         else
1473                 ret = enable_IR();
1474
1475         if (!ret) {
1476                 /* IR is required if there is APIC ID > 255 even when running
1477                  * under KVM
1478                  */
1479                 if (max_physical_apicid > 255 || !kvm_para_available())
1480                         goto nox2apic;
1481                 /*
1482                  * without IR all CPUs can be addressed by IOAPIC/MSI
1483                  * only in physical mode
1484                  */
1485                 x2apic_force_phys();
1486         }
1487
1488         x2apic_enabled = 1;
1489
1490         if (x2apic_supported() && !x2apic_mode) {
1491                 x2apic_mode = 1;
1492                 enable_x2apic();
1493                 pr_info("Enabled x2apic\n");
1494         }
1495
1496 nox2apic:
1497         if (!ret) /* IR enabling failed */
1498                 restore_IO_APIC_setup(ioapic_entries);
1499         legacy_pic->restore_mask();
1500         local_irq_restore(flags);
1501
1502 out:
1503         if (ioapic_entries)
1504                 free_ioapic_entries(ioapic_entries);
1505
1506         if (x2apic_enabled)
1507                 return;
1508
1509         if (x2apic_preenabled)
1510                 panic("x2apic: enabled by BIOS but kernel init failed.");
1511         else if (cpu_has_x2apic)
1512                 pr_info("Not enabling x2apic, Intr-remapping init failed.\n");
1513 }
1514
1515 #ifdef CONFIG_X86_64
1516 /*
1517  * Detect and enable local APICs on non-SMP boards.
1518  * Original code written by Keir Fraser.
1519  * On AMD64 we trust the BIOS - if it says no APIC it is likely
1520  * not correctly set up (usually the APIC timer won't work etc.)
1521  */
1522 static int __init detect_init_APIC(void)
1523 {
1524         if (!cpu_has_apic) {
1525                 pr_info("No local APIC present\n");
1526                 return -1;
1527         }
1528
1529         mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
1530         return 0;
1531 }
1532 #else
1533
1534 static int apic_verify(void)
1535 {
1536         u32 features, h, l;
1537
1538         /*
1539          * The APIC feature bit should now be enabled
1540          * in `cpuid'
1541          */
1542         features = cpuid_edx(1);
1543         if (!(features & (1 << X86_FEATURE_APIC))) {
1544                 pr_warning("Could not enable APIC!\n");
1545                 return -1;
1546         }
1547         set_cpu_cap(&boot_cpu_data, X86_FEATURE_APIC);
1548         mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
1549
1550         /* The BIOS may have set up the APIC at some other address */
1551         rdmsr(MSR_IA32_APICBASE, l, h);
1552         if (l & MSR_IA32_APICBASE_ENABLE)
1553                 mp_lapic_addr = l & MSR_IA32_APICBASE_BASE;
1554
1555         pr_info("Found and enabled local APIC!\n");
1556         return 0;
1557 }
1558
1559 int apic_force_enable(void)
1560 {
1561         u32 h, l;
1562
1563         if (disable_apic)
1564                 return -1;
1565
1566         /*
1567          * Some BIOSes disable the local APIC in the APIC_BASE
1568          * MSR. This can only be done in software for Intel P6 or later
1569          * and AMD K7 (Model > 1) or later.
1570          */
1571         rdmsr(MSR_IA32_APICBASE, l, h);
1572         if (!(l & MSR_IA32_APICBASE_ENABLE)) {
1573                 pr_info("Local APIC disabled by BIOS -- reenabling.\n");
1574                 l &= ~MSR_IA32_APICBASE_BASE;
1575                 l |= MSR_IA32_APICBASE_ENABLE | APIC_DEFAULT_PHYS_BASE;
1576                 wrmsr(MSR_IA32_APICBASE, l, h);
1577                 enabled_via_apicbase = 1;
1578         }
1579         return apic_verify();
1580 }
1581
1582 /*
1583  * Detect and initialize APIC
1584  */
1585 static int __init detect_init_APIC(void)
1586 {
1587         /* Disabled by kernel option? */
1588         if (disable_apic)
1589                 return -1;
1590
1591         switch (boot_cpu_data.x86_vendor) {
1592         case X86_VENDOR_AMD:
1593                 if ((boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model > 1) ||
1594                     (boot_cpu_data.x86 >= 15))
1595                         break;
1596                 goto no_apic;
1597         case X86_VENDOR_INTEL:
1598                 if (boot_cpu_data.x86 == 6 || boot_cpu_data.x86 == 15 ||
1599                     (boot_cpu_data.x86 == 5 && cpu_has_apic))
1600                         break;
1601                 goto no_apic;
1602         default:
1603                 goto no_apic;
1604         }
1605
1606         if (!cpu_has_apic) {
1607                 /*
1608                  * Over-ride BIOS and try to enable the local APIC only if
1609                  * "lapic" specified.
1610                  */
1611                 if (!force_enable_local_apic) {
1612                         pr_info("Local APIC disabled by BIOS -- "
1613                                 "you can enable it with \"lapic\"\n");
1614                         return -1;
1615                 }
1616                 if (apic_force_enable())
1617                         return -1;
1618         } else {
1619                 if (apic_verify())
1620                         return -1;
1621         }
1622
1623         apic_pm_activate();
1624
1625         return 0;
1626
1627 no_apic:
1628         pr_info("No local APIC present or hardware disabled\n");
1629         return -1;
1630 }
1631 #endif
1632
1633 /**
1634  * init_apic_mappings - initialize APIC mappings
1635  */
1636 void __init init_apic_mappings(void)
1637 {
1638         unsigned int new_apicid;
1639
1640         if (x2apic_mode) {
1641                 boot_cpu_physical_apicid = read_apic_id();
1642                 return;
1643         }
1644
1645         /* If no local APIC can be found return early */
1646         if (!smp_found_config && detect_init_APIC()) {
1647                 /* lets NOP'ify apic operations */
1648                 pr_info("APIC: disable apic facility\n");
1649                 apic_disable();
1650         } else {
1651                 apic_phys = mp_lapic_addr;
1652
1653                 /*
1654                  * acpi lapic path already maps that address in
1655                  * acpi_register_lapic_address()
1656                  */
1657                 if (!acpi_lapic && !smp_found_config)
1658                         register_lapic_address(apic_phys);
1659         }
1660
1661         /*
1662          * Fetch the APIC ID of the BSP in case we have a
1663          * default configuration (or the MP table is broken).
1664          */
1665         new_apicid = read_apic_id();
1666         if (boot_cpu_physical_apicid != new_apicid) {
1667                 boot_cpu_physical_apicid = new_apicid;
1668                 /*
1669                  * yeah -- we lie about apic_version
1670                  * in case if apic was disabled via boot option
1671                  * but it's not a problem for SMP compiled kernel
1672                  * since smp_sanity_check is prepared for such a case
1673                  * and disable smp mode
1674                  */
1675                 apic_version[new_apicid] =
1676                          GET_APIC_VERSION(apic_read(APIC_LVR));
1677         }
1678 }
1679
1680 void __init register_lapic_address(unsigned long address)
1681 {
1682         mp_lapic_addr = address;
1683
1684         if (!x2apic_mode) {
1685                 set_fixmap_nocache(FIX_APIC_BASE, address);
1686                 apic_printk(APIC_VERBOSE, "mapped APIC to %16lx (%16lx)\n",
1687                             APIC_BASE, mp_lapic_addr);
1688         }
1689         if (boot_cpu_physical_apicid == -1U) {
1690                 boot_cpu_physical_apicid  = read_apic_id();
1691                 apic_version[boot_cpu_physical_apicid] =
1692                          GET_APIC_VERSION(apic_read(APIC_LVR));
1693         }
1694 }
1695
1696 /*
1697  * This initializes the IO-APIC and APIC hardware if this is
1698  * a UP kernel.
1699  */
1700 int apic_version[MAX_LOCAL_APIC];
1701
1702 int __init APIC_init_uniprocessor(void)
1703 {
1704         if (disable_apic) {
1705                 pr_info("Apic disabled\n");
1706                 return -1;
1707         }
1708 #ifdef CONFIG_X86_64
1709         if (!cpu_has_apic) {
1710                 disable_apic = 1;
1711                 pr_info("Apic disabled by BIOS\n");
1712                 return -1;
1713         }
1714 #else
1715         if (!smp_found_config && !cpu_has_apic)
1716                 return -1;
1717
1718         /*
1719          * Complain if the BIOS pretends there is one.
1720          */
1721         if (!cpu_has_apic &&
1722             APIC_INTEGRATED(apic_version[boot_cpu_physical_apicid])) {
1723                 pr_err("BIOS bug, local APIC 0x%x not detected!...\n",
1724                         boot_cpu_physical_apicid);
1725                 return -1;
1726         }
1727 #endif
1728
1729         default_setup_apic_routing();
1730
1731         verify_local_APIC();
1732         connect_bsp_APIC();
1733
1734 #ifdef CONFIG_X86_64
1735         apic_write(APIC_ID, SET_APIC_ID(boot_cpu_physical_apicid));
1736 #else
1737         /*
1738          * Hack: In case of kdump, after a crash, kernel might be booting
1739          * on a cpu with non-zero lapic id. But boot_cpu_physical_apicid
1740          * might be zero if read from MP tables. Get it from LAPIC.
1741          */
1742 # ifdef CONFIG_CRASH_DUMP
1743         boot_cpu_physical_apicid = read_apic_id();
1744 # endif
1745 #endif
1746         physid_set_mask_of_physid(boot_cpu_physical_apicid, &phys_cpu_present_map);
1747         setup_local_APIC();
1748
1749 #ifdef CONFIG_X86_IO_APIC
1750         /*
1751          * Now enable IO-APICs, actually call clear_IO_APIC
1752          * We need clear_IO_APIC before enabling error vector
1753          */
1754         if (!skip_ioapic_setup && nr_ioapics)
1755                 enable_IO_APIC();
1756 #endif
1757
1758         end_local_APIC_setup();
1759
1760 #ifdef CONFIG_X86_IO_APIC
1761         if (smp_found_config && !skip_ioapic_setup && nr_ioapics)
1762                 setup_IO_APIC();
1763         else {
1764                 nr_ioapics = 0;
1765         }
1766 #endif
1767
1768         x86_init.timers.setup_percpu_clockev();
1769         return 0;
1770 }
1771
1772 /*
1773  * Local APIC interrupts
1774  */
1775
1776 /*
1777  * This interrupt should _never_ happen with our APIC/SMP architecture
1778  */
1779 void smp_spurious_interrupt(struct pt_regs *regs)
1780 {
1781         u32 v;
1782
1783         exit_idle();
1784         irq_enter();
1785         /*
1786          * Check if this really is a spurious interrupt and ACK it
1787          * if it is a vectored one.  Just in case...
1788          * Spurious interrupts should not be ACKed.
1789          */
1790         v = apic_read(APIC_ISR + ((SPURIOUS_APIC_VECTOR & ~0x1f) >> 1));
1791         if (v & (1 << (SPURIOUS_APIC_VECTOR & 0x1f)))
1792                 ack_APIC_irq();
1793
1794         inc_irq_stat(irq_spurious_count);
1795
1796         /* see sw-dev-man vol 3, chapter 7.4.13.5 */
1797         pr_info("spurious APIC interrupt on CPU#%d, "
1798                 "should never happen.\n", smp_processor_id());
1799         irq_exit();
1800 }
1801
1802 /*
1803  * This interrupt should never happen with our APIC/SMP architecture
1804  */
1805 void smp_error_interrupt(struct pt_regs *regs)
1806 {
1807         u32 v, v1;
1808
1809         exit_idle();
1810         irq_enter();
1811         /* First tickle the hardware, only then report what went on. -- REW */
1812         v = apic_read(APIC_ESR);
1813         apic_write(APIC_ESR, 0);
1814         v1 = apic_read(APIC_ESR);
1815         ack_APIC_irq();
1816         atomic_inc(&irq_err_count);
1817
1818         /*
1819          * Here is what the APIC error bits mean:
1820          * 0: Send CS error
1821          * 1: Receive CS error
1822          * 2: Send accept error
1823          * 3: Receive accept error
1824          * 4: Reserved
1825          * 5: Send illegal vector
1826          * 6: Received illegal vector
1827          * 7: Illegal register address
1828          */
1829         pr_debug("APIC error on CPU%d: %02x(%02x)\n",
1830                 smp_processor_id(), v , v1);
1831         irq_exit();
1832 }
1833
1834 /**
1835  * connect_bsp_APIC - attach the APIC to the interrupt system
1836  */
1837 void __init connect_bsp_APIC(void)
1838 {
1839 #ifdef CONFIG_X86_32
1840         if (pic_mode) {
1841                 /*
1842                  * Do not trust the local APIC being empty at bootup.
1843                  */
1844                 clear_local_APIC();
1845                 /*
1846                  * PIC mode, enable APIC mode in the IMCR, i.e.  connect BSP's
1847                  * local APIC to INT and NMI lines.
1848                  */
1849                 apic_printk(APIC_VERBOSE, "leaving PIC mode, "
1850                                 "enabling APIC mode.\n");
1851                 imcr_pic_to_apic();
1852         }
1853 #endif
1854         if (apic->enable_apic_mode)
1855                 apic->enable_apic_mode();
1856 }
1857
1858 /**
1859  * disconnect_bsp_APIC - detach the APIC from the interrupt system
1860  * @virt_wire_setup:    indicates, whether virtual wire mode is selected
1861  *
1862  * Virtual wire mode is necessary to deliver legacy interrupts even when the
1863  * APIC is disabled.
1864  */
1865 void disconnect_bsp_APIC(int virt_wire_setup)
1866 {
1867         unsigned int value;
1868
1869 #ifdef CONFIG_X86_32
1870         if (pic_mode) {
1871                 /*
1872                  * Put the board back into PIC mode (has an effect only on
1873                  * certain older boards).  Note that APIC interrupts, including
1874                  * IPIs, won't work beyond this point!  The only exception are
1875                  * INIT IPIs.
1876                  */
1877                 apic_printk(APIC_VERBOSE, "disabling APIC mode, "
1878                                 "entering PIC mode.\n");
1879                 imcr_apic_to_pic();
1880                 return;
1881         }
1882 #endif
1883
1884         /* Go back to Virtual Wire compatibility mode */
1885
1886         /* For the spurious interrupt use vector F, and enable it */
1887         value = apic_read(APIC_SPIV);
1888         value &= ~APIC_VECTOR_MASK;
1889         value |= APIC_SPIV_APIC_ENABLED;
1890         value |= 0xf;
1891         apic_write(APIC_SPIV, value);
1892
1893         if (!virt_wire_setup) {
1894                 /*
1895                  * For LVT0 make it edge triggered, active high,
1896                  * external and enabled
1897                  */
1898                 value = apic_read(APIC_LVT0);
1899                 value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
1900                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
1901                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
1902                 value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
1903                 value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_EXTINT);
1904                 apic_write(APIC_LVT0, value);
1905         } else {
1906                 /* Disable LVT0 */
1907                 apic_write(APIC_LVT0, APIC_LVT_MASKED);
1908         }
1909
1910         /*
1911          * For LVT1 make it edge triggered, active high,
1912          * nmi and enabled
1913          */
1914         value = apic_read(APIC_LVT1);
1915         value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
1916                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
1917                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
1918         value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
1919         value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_NMI);
1920         apic_write(APIC_LVT1, value);
1921 }
1922
1923 void __cpuinit generic_processor_info(int apicid, int version)
1924 {
1925         int cpu;
1926
1927         /*
1928          * Validate version
1929          */
1930         if (version == 0x0) {
1931                 pr_warning("BIOS bug, APIC version is 0 for CPU#%d! "
1932                            "fixing up to 0x10. (tell your hw vendor)\n",
1933                                 version);
1934                 version = 0x10;
1935         }
1936         apic_version[apicid] = version;
1937
1938         if (num_processors >= nr_cpu_ids) {
1939                 int max = nr_cpu_ids;
1940                 int thiscpu = max + disabled_cpus;
1941
1942                 pr_warning(
1943                         "ACPI: NR_CPUS/possible_cpus limit of %i reached."
1944                         "  Processor %d/0x%x ignored.\n", max, thiscpu, apicid);
1945
1946                 disabled_cpus++;
1947                 return;
1948         }
1949
1950         num_processors++;
1951         cpu = cpumask_next_zero(-1, cpu_present_mask);
1952
1953         if (version != apic_version[boot_cpu_physical_apicid])
1954                 WARN_ONCE(1,
1955                         "ACPI: apic version mismatch, bootcpu: %x cpu %d: %x\n",
1956                         apic_version[boot_cpu_physical_apicid], cpu, version);
1957
1958         physid_set(apicid, phys_cpu_present_map);
1959         if (apicid == boot_cpu_physical_apicid) {
1960                 /*
1961                  * x86_bios_cpu_apicid is required to have processors listed
1962                  * in same order as logical cpu numbers. Hence the first
1963                  * entry is BSP, and so on.
1964                  */
1965                 cpu = 0;
1966         }
1967         if (apicid > max_physical_apicid)
1968                 max_physical_apicid = apicid;
1969
1970 #if defined(CONFIG_SMP) || defined(CONFIG_X86_64)
1971         early_per_cpu(x86_cpu_to_apicid, cpu) = apicid;
1972         early_per_cpu(x86_bios_cpu_apicid, cpu) = apicid;
1973 #endif
1974
1975         set_cpu_possible(cpu, true);
1976         set_cpu_present(cpu, true);
1977 }
1978
1979 int hard_smp_processor_id(void)
1980 {
1981         return read_apic_id();
1982 }
1983
1984 void default_init_apic_ldr(void)
1985 {
1986         unsigned long val;
1987
1988         apic_write(APIC_DFR, APIC_DFR_VALUE);
1989         val = apic_read(APIC_LDR) & ~APIC_LDR_MASK;
1990         val |= SET_APIC_LOGICAL_ID(1UL << smp_processor_id());
1991         apic_write(APIC_LDR, val);
1992 }
1993
1994 #ifdef CONFIG_X86_32
1995 int default_apicid_to_node(int logical_apicid)
1996 {
1997 #ifdef CONFIG_SMP
1998         return apicid_2_node[hard_smp_processor_id()];
1999 #else
2000         return 0;
2001 #endif
2002 }
2003 #endif
2004
2005 /*
2006  * Power management
2007  */
2008 #ifdef CONFIG_PM
2009
2010 static struct {
2011         /*
2012          * 'active' is true if the local APIC was enabled by us and
2013          * not the BIOS; this signifies that we are also responsible
2014          * for disabling it before entering apm/acpi suspend
2015          */
2016         int active;
2017         /* r/w apic fields */
2018         unsigned int apic_id;
2019         unsigned int apic_taskpri;
2020         unsigned int apic_ldr;
2021         unsigned int apic_dfr;
2022         unsigned int apic_spiv;
2023         unsigned int apic_lvtt;
2024         unsigned int apic_lvtpc;
2025         unsigned int apic_lvt0;
2026         unsigned int apic_lvt1;
2027         unsigned int apic_lvterr;
2028         unsigned int apic_tmict;
2029         unsigned int apic_tdcr;
2030         unsigned int apic_thmr;
2031 } apic_pm_state;
2032
2033 static int lapic_suspend(struct sys_device *dev, pm_message_t state)
2034 {
2035         unsigned long flags;
2036         int maxlvt;
2037
2038         if (!apic_pm_state.active)
2039                 return 0;
2040
2041         maxlvt = lapic_get_maxlvt();
2042
2043         apic_pm_state.apic_id = apic_read(APIC_ID);
2044         apic_pm_state.apic_taskpri = apic_read(APIC_TASKPRI);
2045         apic_pm_state.apic_ldr = apic_read(APIC_LDR);
2046         apic_pm_state.apic_dfr = apic_read(APIC_DFR);
2047         apic_pm_state.apic_spiv = apic_read(APIC_SPIV);
2048         apic_pm_state.apic_lvtt = apic_read(APIC_LVTT);
2049         if (maxlvt >= 4)
2050                 apic_pm_state.apic_lvtpc = apic_read(APIC_LVTPC);
2051         apic_pm_state.apic_lvt0 = apic_read(APIC_LVT0);
2052         apic_pm_state.apic_lvt1 = apic_read(APIC_LVT1);
2053         apic_pm_state.apic_lvterr = apic_read(APIC_LVTERR);
2054         apic_pm_state.apic_tmict = apic_read(APIC_TMICT);
2055         apic_pm_state.apic_tdcr = apic_read(APIC_TDCR);
2056 #ifdef CONFIG_X86_THERMAL_VECTOR
2057         if (maxlvt >= 5)
2058                 apic_pm_state.apic_thmr = apic_read(APIC_LVTTHMR);
2059 #endif
2060
2061         local_irq_save(flags);
2062         disable_local_APIC();
2063
2064         if (intr_remapping_enabled)
2065                 disable_intr_remapping();
2066
2067         local_irq_restore(flags);
2068         return 0;
2069 }
2070
2071 static int lapic_resume(struct sys_device *dev)
2072 {
2073         unsigned int l, h;
2074         unsigned long flags;
2075         int maxlvt;
2076         int ret = 0;
2077         struct IO_APIC_route_entry **ioapic_entries = NULL;
2078
2079         if (!apic_pm_state.active)
2080                 return 0;
2081
2082         local_irq_save(flags);
2083         if (intr_remapping_enabled) {
2084                 ioapic_entries = alloc_ioapic_entries();
2085                 if (!ioapic_entries) {
2086                         WARN(1, "Alloc ioapic_entries in lapic resume failed.");
2087                         ret = -ENOMEM;
2088                         goto restore;
2089                 }
2090
2091                 ret = save_IO_APIC_setup(ioapic_entries);
2092                 if (ret) {
2093                         WARN(1, "Saving IO-APIC state failed: %d\n", ret);
2094                         free_ioapic_entries(ioapic_entries);
2095                         goto restore;
2096                 }
2097
2098                 mask_IO_APIC_setup(ioapic_entries);
2099                 legacy_pic->mask_all();
2100         }
2101
2102         if (x2apic_mode)
2103                 enable_x2apic();
2104         else {
2105                 /*
2106                  * Make sure the APICBASE points to the right address
2107                  *
2108                  * FIXME! This will be wrong if we ever support suspend on
2109                  * SMP! We'll need to do this as part of the CPU restore!
2110                  */
2111                 rdmsr(MSR_IA32_APICBASE, l, h);
2112                 l &= ~MSR_IA32_APICBASE_BASE;
2113                 l |= MSR_IA32_APICBASE_ENABLE | mp_lapic_addr;
2114                 wrmsr(MSR_IA32_APICBASE, l, h);
2115         }
2116
2117         maxlvt = lapic_get_maxlvt();
2118         apic_write(APIC_LVTERR, ERROR_APIC_VECTOR | APIC_LVT_MASKED);
2119         apic_write(APIC_ID, apic_pm_state.apic_id);
2120         apic_write(APIC_DFR, apic_pm_state.apic_dfr);
2121         apic_write(APIC_LDR, apic_pm_state.apic_ldr);
2122         apic_write(APIC_TASKPRI, apic_pm_state.apic_taskpri);
2123         apic_write(APIC_SPIV, apic_pm_state.apic_spiv);
2124         apic_write(APIC_LVT0, apic_pm_state.apic_lvt0);
2125         apic_write(APIC_LVT1, apic_pm_state.apic_lvt1);
2126 #if defined(CONFIG_X86_MCE_P4THERMAL) || defined(CONFIG_X86_MCE_INTEL)
2127         if (maxlvt >= 5)
2128                 apic_write(APIC_LVTTHMR, apic_pm_state.apic_thmr);
2129 #endif
2130         if (maxlvt >= 4)
2131                 apic_write(APIC_LVTPC, apic_pm_state.apic_lvtpc);
2132         apic_write(APIC_LVTT, apic_pm_state.apic_lvtt);
2133         apic_write(APIC_TDCR, apic_pm_state.apic_tdcr);
2134         apic_write(APIC_TMICT, apic_pm_state.apic_tmict);
2135         apic_write(APIC_ESR, 0);
2136         apic_read(APIC_ESR);
2137         apic_write(APIC_LVTERR, apic_pm_state.apic_lvterr);
2138         apic_write(APIC_ESR, 0);
2139         apic_read(APIC_ESR);
2140
2141         if (intr_remapping_enabled) {
2142                 reenable_intr_remapping(x2apic_mode);
2143                 legacy_pic->restore_mask();
2144                 restore_IO_APIC_setup(ioapic_entries);
2145                 free_ioapic_entries(ioapic_entries);
2146         }
2147 restore:
2148         local_irq_restore(flags);
2149
2150         return ret;
2151 }
2152
2153 /*
2154  * This device has no shutdown method - fully functioning local APICs
2155  * are needed on every CPU up until machine_halt/restart/poweroff.
2156  */
2157
2158 static struct sysdev_class lapic_sysclass = {
2159         .name           = "lapic",
2160         .resume         = lapic_resume,
2161         .suspend        = lapic_suspend,
2162 };
2163
2164 static struct sys_device device_lapic = {
2165         .id     = 0,
2166         .cls    = &lapic_sysclass,
2167 };
2168
2169 static void __cpuinit apic_pm_activate(void)
2170 {
2171         apic_pm_state.active = 1;
2172 }
2173
2174 static int __init init_lapic_sysfs(void)
2175 {
2176         int error;
2177
2178         if (!cpu_has_apic)
2179                 return 0;
2180         /* XXX: remove suspend/resume procs if !apic_pm_state.active? */
2181
2182         error = sysdev_class_register(&lapic_sysclass);
2183         if (!error)
2184                 error = sysdev_register(&device_lapic);
2185         return error;
2186 }
2187
2188 /* local apic needs to resume before other devices access its registers. */
2189 core_initcall(init_lapic_sysfs);
2190
2191 #else   /* CONFIG_PM */
2192
2193 static void apic_pm_activate(void) { }
2194
2195 #endif  /* CONFIG_PM */
2196
2197 #ifdef CONFIG_X86_64
2198
2199 static int __cpuinit apic_cluster_num(void)
2200 {
2201         int i, clusters, zeros;
2202         unsigned id;
2203         u16 *bios_cpu_apicid;
2204         DECLARE_BITMAP(clustermap, NUM_APIC_CLUSTERS);
2205
2206         bios_cpu_apicid = early_per_cpu_ptr(x86_bios_cpu_apicid);
2207         bitmap_zero(clustermap, NUM_APIC_CLUSTERS);
2208
2209         for (i = 0; i < nr_cpu_ids; i++) {
2210                 /* are we being called early in kernel startup? */
2211                 if (bios_cpu_apicid) {
2212                         id = bios_cpu_apicid[i];
2213                 } else if (i < nr_cpu_ids) {
2214                         if (cpu_present(i))
2215                                 id = per_cpu(x86_bios_cpu_apicid, i);
2216                         else
2217                                 continue;
2218                 } else
2219                         break;
2220
2221                 if (id != BAD_APICID)
2222                         __set_bit(APIC_CLUSTERID(id), clustermap);
2223         }
2224
2225         /* Problem:  Partially populated chassis may not have CPUs in some of
2226          * the APIC clusters they have been allocated.  Only present CPUs have
2227          * x86_bios_cpu_apicid entries, thus causing zeroes in the bitmap.
2228          * Since clusters are allocated sequentially, count zeros only if
2229          * they are bounded by ones.
2230          */
2231         clusters = 0;
2232         zeros = 0;
2233         for (i = 0; i < NUM_APIC_CLUSTERS; i++) {
2234                 if (test_bit(i, clustermap)) {
2235                         clusters += 1 + zeros;
2236                         zeros = 0;
2237                 } else
2238                         ++zeros;
2239         }
2240
2241         return clusters;
2242 }
2243
2244 static int __cpuinitdata multi_checked;
2245 static int __cpuinitdata multi;
2246
2247 static int __cpuinit set_multi(const struct dmi_system_id *d)
2248 {
2249         if (multi)
2250                 return 0;
2251         pr_info("APIC: %s detected, Multi Chassis\n", d->ident);
2252         multi = 1;
2253         return 0;
2254 }
2255
2256 static const __cpuinitconst struct dmi_system_id multi_dmi_table[] = {
2257         {
2258                 .callback = set_multi,
2259                 .ident = "IBM System Summit2",
2260                 .matches = {
2261                         DMI_MATCH(DMI_SYS_VENDOR, "IBM"),
2262                         DMI_MATCH(DMI_PRODUCT_NAME, "Summit2"),
2263                 },
2264         },
2265         {}
2266 };
2267
2268 static void __cpuinit dmi_check_multi(void)
2269 {
2270         if (multi_checked)
2271                 return;
2272
2273         dmi_check_system(multi_dmi_table);
2274         multi_checked = 1;
2275 }
2276
2277 /*
2278  * apic_is_clustered_box() -- Check if we can expect good TSC
2279  *
2280  * Thus far, the major user of this is IBM's Summit2 series:
2281  * Clustered boxes may have unsynced TSC problems if they are
2282  * multi-chassis.
2283  * Use DMI to check them
2284  */
2285 __cpuinit int apic_is_clustered_box(void)
2286 {
2287         dmi_check_multi();
2288         if (multi)
2289                 return 1;
2290
2291         if (!is_vsmp_box())
2292                 return 0;
2293
2294         /*
2295          * ScaleMP vSMPowered boxes have one cluster per board and TSCs are
2296          * not guaranteed to be synced between boards
2297          */
2298         if (apic_cluster_num() > 1)
2299                 return 1;
2300
2301         return 0;
2302 }
2303 #endif
2304
2305 /*
2306  * APIC command line parameters
2307  */
2308 static int __init setup_disableapic(char *arg)
2309 {
2310         disable_apic = 1;
2311         setup_clear_cpu_cap(X86_FEATURE_APIC);
2312         return 0;
2313 }
2314 early_param("disableapic", setup_disableapic);
2315
2316 /* same as disableapic, for compatibility */
2317 static int __init setup_nolapic(char *arg)
2318 {
2319         return setup_disableapic(arg);
2320 }
2321 early_param("nolapic", setup_nolapic);
2322
2323 static int __init parse_lapic_timer_c2_ok(char *arg)
2324 {
2325         local_apic_timer_c2_ok = 1;
2326         return 0;
2327 }
2328 early_param("lapic_timer_c2_ok", parse_lapic_timer_c2_ok);
2329
2330 static int __init parse_disable_apic_timer(char *arg)
2331 {
2332         disable_apic_timer = 1;
2333         return 0;
2334 }
2335 early_param("noapictimer", parse_disable_apic_timer);
2336
2337 static int __init parse_nolapic_timer(char *arg)
2338 {
2339         disable_apic_timer = 1;
2340         return 0;
2341 }
2342 early_param("nolapic_timer", parse_nolapic_timer);
2343
2344 static int __init apic_set_verbosity(char *arg)
2345 {
2346         if (!arg)  {
2347 #ifdef CONFIG_X86_64
2348                 skip_ioapic_setup = 0;
2349                 return 0;
2350 #endif
2351                 return -EINVAL;
2352         }
2353
2354         if (strcmp("debug", arg) == 0)
2355                 apic_verbosity = APIC_DEBUG;
2356         else if (strcmp("verbose", arg) == 0)
2357                 apic_verbosity = APIC_VERBOSE;
2358         else {
2359                 pr_warning("APIC Verbosity level %s not recognised"
2360                         " use apic=verbose or apic=debug\n", arg);
2361                 return -EINVAL;
2362         }
2363
2364         return 0;
2365 }
2366 early_param("apic", apic_set_verbosity);
2367
2368 static int __init lapic_insert_resource(void)
2369 {
2370         if (!apic_phys)
2371                 return -1;
2372
2373         /* Put local APIC into the resource map. */
2374         lapic_resource.start = apic_phys;
2375         lapic_resource.end = lapic_resource.start + PAGE_SIZE - 1;
2376         insert_resource(&iomem_resource, &lapic_resource);
2377
2378         return 0;
2379 }
2380
2381 /*
2382  * need call insert after e820_reserve_resources()
2383  * that is using request_resource
2384  */
2385 late_initcall(lapic_insert_resource);