[PATCH] i386: trust the PM-Timer calibration of the local APIC timer
[powerpc.git] / arch / i386 / kernel / apic.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/smp_lock.h>
23 #include <linux/interrupt.h>
24 #include <linux/mc146818rtc.h>
25 #include <linux/kernel_stat.h>
26 #include <linux/sysdev.h>
27 #include <linux/cpu.h>
28 #include <linux/clockchips.h>
29 #include <linux/acpi_pmtmr.h>
30 #include <linux/module.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 #include "io_ports.h"
47
48 /*
49  * Sanity check
50  */
51 #if (SPURIOUS_APIC_VECTOR & 0x0F) != 0x0F
52 # error SPURIOUS_APIC_VECTOR definition error
53 #endif
54
55 /*
56  * Knob to control our willingness to enable the local APIC.
57  *
58  * -1=force-disable, +1=force-enable
59  */
60 static int enable_local_apic __initdata = 0;
61
62 /* Local APIC timer verification ok */
63 static int local_apic_timer_verify_ok;
64
65 /*
66  * Debug level, exported for io_apic.c
67  */
68 int apic_verbosity;
69
70 static unsigned int calibration_result;
71
72 static int lapic_next_event(unsigned long delta,
73                             struct clock_event_device *evt);
74 static void lapic_timer_setup(enum clock_event_mode mode,
75                               struct clock_event_device *evt);
76 static void lapic_timer_broadcast(cpumask_t mask);
77 static void apic_pm_activate(void);
78
79 /*
80  * The local apic timer can be used for any function which is CPU local.
81  */
82 static struct clock_event_device lapic_clockevent = {
83         .name           = "lapic",
84         .features       = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT
85                         | CLOCK_EVT_FEAT_C3STOP | CLOCK_EVT_FEAT_DUMMY,
86         .shift          = 32,
87         .set_mode       = lapic_timer_setup,
88         .set_next_event = lapic_next_event,
89         .broadcast      = lapic_timer_broadcast,
90         .rating         = 100,
91         .irq            = -1,
92 };
93 static DEFINE_PER_CPU(struct clock_event_device, lapic_events);
94
95 /* Local APIC was disabled by the BIOS and enabled by the kernel */
96 static int enabled_via_apicbase;
97
98 /*
99  * Get the LAPIC version
100  */
101 static inline int lapic_get_version(void)
102 {
103         return GET_APIC_VERSION(apic_read(APIC_LVR));
104 }
105
106 /*
107  * Check, if the APIC is integrated or a seperate chip
108  */
109 static inline int lapic_is_integrated(void)
110 {
111         return APIC_INTEGRATED(lapic_get_version());
112 }
113
114 /*
115  * Check, whether this is a modern or a first generation APIC
116  */
117 static int modern_apic(void)
118 {
119         /* AMD systems use old APIC versions, so check the CPU */
120         if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD &&
121             boot_cpu_data.x86 >= 0xf)
122                 return 1;
123         return lapic_get_version() >= 0x14;
124 }
125
126 /**
127  * enable_NMI_through_LVT0 - enable NMI through local vector table 0
128  */
129 void enable_NMI_through_LVT0 (void * dummy)
130 {
131         unsigned int v = APIC_DM_NMI;
132
133         /* Level triggered for 82489DX */
134         if (!lapic_is_integrated())
135                 v |= APIC_LVT_LEVEL_TRIGGER;
136         apic_write_around(APIC_LVT0, v);
137 }
138
139 /**
140  * get_physical_broadcast - Get number of physical broadcast IDs
141  */
142 int get_physical_broadcast(void)
143 {
144         return modern_apic() ? 0xff : 0xf;
145 }
146
147 /**
148  * lapic_get_maxlvt - get the maximum number of local vector table entries
149  */
150 int lapic_get_maxlvt(void)
151 {
152         unsigned int v = apic_read(APIC_LVR);
153
154         /* 82489DXs do not report # of LVT entries. */
155         return APIC_INTEGRATED(GET_APIC_VERSION(v)) ? GET_APIC_MAXLVT(v) : 2;
156 }
157
158 /*
159  * Local APIC timer
160  */
161
162 /* Clock divisor is set to 16 */
163 #define APIC_DIVISOR 16
164
165 /*
166  * This function sets up the local APIC timer, with a timeout of
167  * 'clocks' APIC bus clock. During calibration we actually call
168  * this function twice on the boot CPU, once with a bogus timeout
169  * value, second time for real. The other (noncalibrating) CPUs
170  * call this function only once, with the real, calibrated value.
171  *
172  * We do reads before writes even if unnecessary, to get around the
173  * P5 APIC double write bug.
174  */
175 static void __setup_APIC_LVTT(unsigned int clocks, int oneshot, int irqen)
176 {
177         unsigned int lvtt_value, tmp_value;
178
179         lvtt_value = LOCAL_TIMER_VECTOR;
180         if (!oneshot)
181                 lvtt_value |= APIC_LVT_TIMER_PERIODIC;
182         if (!lapic_is_integrated())
183                 lvtt_value |= SET_APIC_TIMER_BASE(APIC_TIMER_BASE_DIV);
184
185         if (!irqen)
186                 lvtt_value |= APIC_LVT_MASKED;
187
188         apic_write_around(APIC_LVTT, lvtt_value);
189
190         /*
191          * Divide PICLK by 16
192          */
193         tmp_value = apic_read(APIC_TDCR);
194         apic_write_around(APIC_TDCR, (tmp_value
195                                 & ~(APIC_TDR_DIV_1 | APIC_TDR_DIV_TMBASE))
196                                 | APIC_TDR_DIV_16);
197
198         if (!oneshot)
199                 apic_write_around(APIC_TMICT, clocks/APIC_DIVISOR);
200 }
201
202 /*
203  * Program the next event, relative to now
204  */
205 static int lapic_next_event(unsigned long delta,
206                             struct clock_event_device *evt)
207 {
208         apic_write_around(APIC_TMICT, delta);
209         return 0;
210 }
211
212 /*
213  * Setup the lapic timer in periodic or oneshot mode
214  */
215 static void lapic_timer_setup(enum clock_event_mode mode,
216                               struct clock_event_device *evt)
217 {
218         unsigned long flags;
219         unsigned int v;
220
221         /* Lapic used for broadcast ? */
222         if (!local_apic_timer_verify_ok)
223                 return;
224
225         local_irq_save(flags);
226
227         switch (mode) {
228         case CLOCK_EVT_MODE_PERIODIC:
229         case CLOCK_EVT_MODE_ONESHOT:
230                 __setup_APIC_LVTT(calibration_result,
231                                   mode != CLOCK_EVT_MODE_PERIODIC, 1);
232                 break;
233         case CLOCK_EVT_MODE_UNUSED:
234         case CLOCK_EVT_MODE_SHUTDOWN:
235                 v = apic_read(APIC_LVTT);
236                 v |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
237                 apic_write_around(APIC_LVTT, v);
238                 break;
239         }
240
241         local_irq_restore(flags);
242 }
243
244 /*
245  * Local APIC timer broadcast function
246  */
247 static void lapic_timer_broadcast(cpumask_t mask)
248 {
249 #ifdef CONFIG_SMP
250         send_IPI_mask(mask, LOCAL_TIMER_VECTOR);
251 #endif
252 }
253
254 /*
255  * Setup the local APIC timer for this CPU. Copy the initilized values
256  * of the boot CPU and register the clock event in the framework.
257  */
258 static void __devinit setup_APIC_timer(void)
259 {
260         struct clock_event_device *levt = &__get_cpu_var(lapic_events);
261
262         memcpy(levt, &lapic_clockevent, sizeof(*levt));
263         levt->cpumask = cpumask_of_cpu(smp_processor_id());
264
265         clockevents_register_device(levt);
266 }
267
268 /*
269  * In this functions we calibrate APIC bus clocks to the external timer.
270  *
271  * We want to do the calibration only once since we want to have local timer
272  * irqs syncron. CPUs connected by the same APIC bus have the very same bus
273  * frequency.
274  *
275  * This was previously done by reading the PIT/HPET and waiting for a wrap
276  * around to find out, that a tick has elapsed. I have a box, where the PIT
277  * readout is broken, so it never gets out of the wait loop again. This was
278  * also reported by others.
279  *
280  * Monitoring the jiffies value is inaccurate and the clockevents
281  * infrastructure allows us to do a simple substitution of the interrupt
282  * handler.
283  *
284  * The calibration routine also uses the pm_timer when possible, as the PIT
285  * happens to run way too slow (factor 2.3 on my VAIO CoreDuo, which goes
286  * back to normal later in the boot process).
287  */
288
289 #define LAPIC_CAL_LOOPS         (HZ/10)
290
291 static __initdata volatile int lapic_cal_loops = -1;
292 static __initdata long lapic_cal_t1, lapic_cal_t2;
293 static __initdata unsigned long long lapic_cal_tsc1, lapic_cal_tsc2;
294 static __initdata unsigned long lapic_cal_pm1, lapic_cal_pm2;
295 static __initdata unsigned long lapic_cal_j1, lapic_cal_j2;
296
297 /*
298  * Temporary interrupt handler.
299  */
300 static void __init lapic_cal_handler(struct clock_event_device *dev)
301 {
302         unsigned long long tsc = 0;
303         long tapic = apic_read(APIC_TMCCT);
304         unsigned long pm = acpi_pm_read_early();
305
306         if (cpu_has_tsc)
307                 rdtscll(tsc);
308
309         switch (lapic_cal_loops++) {
310         case 0:
311                 lapic_cal_t1 = tapic;
312                 lapic_cal_tsc1 = tsc;
313                 lapic_cal_pm1 = pm;
314                 lapic_cal_j1 = jiffies;
315                 break;
316
317         case LAPIC_CAL_LOOPS:
318                 lapic_cal_t2 = tapic;
319                 lapic_cal_tsc2 = tsc;
320                 if (pm < lapic_cal_pm1)
321                         pm += ACPI_PM_OVRRUN;
322                 lapic_cal_pm2 = pm;
323                 lapic_cal_j2 = jiffies;
324                 break;
325         }
326 }
327
328 /*
329  * Setup the boot APIC
330  *
331  * Calibrate and verify the result.
332  */
333 void __init setup_boot_APIC_clock(void)
334 {
335         struct clock_event_device *levt = &__get_cpu_var(lapic_events);
336         const long pm_100ms = PMTMR_TICKS_PER_SEC/10;
337         const long pm_thresh = pm_100ms/100;
338         void (*real_handler)(struct clock_event_device *dev);
339         unsigned long deltaj;
340         long delta, deltapm;
341         int pm_referenced = 0;
342
343         apic_printk(APIC_VERBOSE, "Using local APIC timer interrupts.\n"
344                     "calibrating APIC timer ...\n");
345
346         local_irq_disable();
347
348         /* Replace the global interrupt handler */
349         real_handler = global_clock_event->event_handler;
350         global_clock_event->event_handler = lapic_cal_handler;
351
352         /*
353          * Setup the APIC counter to 1e9. There is no way the lapic
354          * can underflow in the 100ms detection time frame
355          */
356         __setup_APIC_LVTT(1000000000, 0, 0);
357
358         /* Let the interrupts run */
359         local_irq_enable();
360
361         while (lapic_cal_loops <= LAPIC_CAL_LOOPS)
362                 cpu_relax();
363
364         local_irq_disable();
365
366         /* Restore the real event handler */
367         global_clock_event->event_handler = real_handler;
368
369         /* Build delta t1-t2 as apic timer counts down */
370         delta = lapic_cal_t1 - lapic_cal_t2;
371         apic_printk(APIC_VERBOSE, "... lapic delta = %ld\n", delta);
372
373         /* Check, if the PM timer is available */
374         deltapm = lapic_cal_pm2 - lapic_cal_pm1;
375         apic_printk(APIC_VERBOSE, "... PM timer delta = %ld\n", deltapm);
376
377         if (deltapm) {
378                 unsigned long mult;
379                 u64 res;
380
381                 mult = clocksource_hz2mult(PMTMR_TICKS_PER_SEC, 22);
382
383                 if (deltapm > (pm_100ms - pm_thresh) &&
384                     deltapm < (pm_100ms + pm_thresh)) {
385                         apic_printk(APIC_VERBOSE, "... PM timer result ok\n");
386                 } else {
387                         res = (((u64) deltapm) *  mult) >> 22;
388                         do_div(res, 1000000);
389                         printk(KERN_WARNING "APIC calibration not consistent "
390                                "with PM Timer: %ldms instead of 100ms\n",
391                                (long)res);
392                         /* Correct the lapic counter value */
393                         res = (((u64) delta ) * pm_100ms);
394                         do_div(res, deltapm);
395                         printk(KERN_INFO "APIC delta adjusted to PM-Timer: "
396                                "%lu (%ld)\n", (unsigned long) res, delta);
397                         delta = (long) res;
398                 }
399                 pm_referenced = 1;
400         }
401
402         /* Calculate the scaled math multiplication factor */
403         lapic_clockevent.mult = div_sc(delta, TICK_NSEC * LAPIC_CAL_LOOPS, 32);
404         lapic_clockevent.max_delta_ns =
405                 clockevent_delta2ns(0x7FFFFF, &lapic_clockevent);
406         lapic_clockevent.min_delta_ns =
407                 clockevent_delta2ns(0xF, &lapic_clockevent);
408
409         calibration_result = (delta * APIC_DIVISOR) / LAPIC_CAL_LOOPS;
410
411         apic_printk(APIC_VERBOSE, "..... delta %ld\n", delta);
412         apic_printk(APIC_VERBOSE, "..... mult: %ld\n", lapic_clockevent.mult);
413         apic_printk(APIC_VERBOSE, "..... calibration result: %u\n",
414                     calibration_result);
415
416         if (cpu_has_tsc) {
417                 delta = (long)(lapic_cal_tsc2 - lapic_cal_tsc1);
418                 apic_printk(APIC_VERBOSE, "..... CPU clock speed is "
419                             "%ld.%04ld MHz.\n",
420                             (delta / LAPIC_CAL_LOOPS) / (1000000 / HZ),
421                             (delta / LAPIC_CAL_LOOPS) % (1000000 / HZ));
422         }
423
424         apic_printk(APIC_VERBOSE, "..... host bus clock speed is "
425                     "%u.%04u MHz.\n",
426                     calibration_result / (1000000 / HZ),
427                     calibration_result % (1000000 / HZ));
428
429         local_apic_timer_verify_ok = 1;
430
431         /* We trust the pm timer based calibration */
432         if (!pm_referenced) {
433                 apic_printk(APIC_VERBOSE, "... verify APIC timer\n");
434
435                 /*
436                  * Setup the apic timer manually
437                  */
438                 levt->event_handler = lapic_cal_handler;
439                 lapic_timer_setup(CLOCK_EVT_MODE_PERIODIC, levt);
440                 lapic_cal_loops = -1;
441
442                 /* Let the interrupts run */
443                 local_irq_enable();
444
445                 while(lapic_cal_loops <= LAPIC_CAL_LOOPS)
446                         cpu_relax();
447
448                 local_irq_disable();
449
450                 /* Stop the lapic timer */
451                 lapic_timer_setup(CLOCK_EVT_MODE_SHUTDOWN, levt);
452
453                 local_irq_enable();
454
455                 /* Jiffies delta */
456                 deltaj = lapic_cal_j2 - lapic_cal_j1;
457                 apic_printk(APIC_VERBOSE, "... jiffies delta = %lu\n", deltaj);
458
459                 /* Check, if the jiffies result is consistent */
460                 if (deltaj >= LAPIC_CAL_LOOPS-2 && deltaj <= LAPIC_CAL_LOOPS+2)
461                         apic_printk(APIC_VERBOSE, "... jiffies result ok\n");
462                 else
463                         local_apic_timer_verify_ok = 0;
464         }
465
466         if (!local_apic_timer_verify_ok) {
467                 printk(KERN_WARNING
468                        "APIC timer disabled due to verification failure.\n");
469                 /* No broadcast on UP ! */
470                 if (num_possible_cpus() == 1)
471                         return;
472         } else {
473                 /*
474                  * If nmi_watchdog is set to IO_APIC, we need the
475                  * PIT/HPET going.  Otherwise register lapic as a dummy
476                  * device.
477                  */
478                 if (nmi_watchdog != NMI_IO_APIC)
479                         lapic_clockevent.features &= ~CLOCK_EVT_FEAT_DUMMY;
480         }
481
482         /* Setup the lapic or request the broadcast */
483         setup_APIC_timer();
484 }
485
486 void __devinit setup_secondary_APIC_clock(void)
487 {
488         setup_APIC_timer();
489 }
490
491 /*
492  * The guts of the apic timer interrupt
493  */
494 static void local_apic_timer_interrupt(void)
495 {
496         int cpu = smp_processor_id();
497         struct clock_event_device *evt = &per_cpu(lapic_events, cpu);
498
499         /*
500          * Normally we should not be here till LAPIC has been initialized but
501          * in some cases like kdump, its possible that there is a pending LAPIC
502          * timer interrupt from previous kernel's context and is delivered in
503          * new kernel the moment interrupts are enabled.
504          *
505          * Interrupts are enabled early and LAPIC is setup much later, hence
506          * its possible that when we get here evt->event_handler is NULL.
507          * Check for event_handler being NULL and discard the interrupt as
508          * spurious.
509          */
510         if (!evt->event_handler) {
511                 printk(KERN_WARNING
512                        "Spurious LAPIC timer interrupt on cpu %d\n", cpu);
513                 /* Switch it off */
514                 lapic_timer_setup(CLOCK_EVT_MODE_SHUTDOWN, evt);
515                 return;
516         }
517
518         per_cpu(irq_stat, cpu).apic_timer_irqs++;
519
520         evt->event_handler(evt);
521 }
522
523 /*
524  * Local APIC timer interrupt. This is the most natural way for doing
525  * local interrupts, but local timer interrupts can be emulated by
526  * broadcast interrupts too. [in case the hw doesn't support APIC timers]
527  *
528  * [ if a single-CPU system runs an SMP kernel then we call the local
529  *   interrupt as well. Thus we cannot inline the local irq ... ]
530  */
531
532 void fastcall smp_apic_timer_interrupt(struct pt_regs *regs)
533 {
534         struct pt_regs *old_regs = set_irq_regs(regs);
535
536         /*
537          * NOTE! We'd better ACK the irq immediately,
538          * because timer handling can be slow.
539          */
540         ack_APIC_irq();
541         /*
542          * update_process_times() expects us to have done irq_enter().
543          * Besides, if we don't timer interrupts ignore the global
544          * interrupt lock, which is the WrongThing (tm) to do.
545          */
546         irq_enter();
547         local_apic_timer_interrupt();
548         irq_exit();
549
550         set_irq_regs(old_regs);
551 }
552
553 int setup_profiling_timer(unsigned int multiplier)
554 {
555         return -EINVAL;
556 }
557
558 /*
559  * Local APIC start and shutdown
560  */
561
562 /**
563  * clear_local_APIC - shutdown the local APIC
564  *
565  * This is called, when a CPU is disabled and before rebooting, so the state of
566  * the local APIC has no dangling leftovers. Also used to cleanout any BIOS
567  * leftovers during boot.
568  */
569 void clear_local_APIC(void)
570 {
571         int maxlvt = lapic_get_maxlvt();
572         unsigned long v;
573
574         /*
575          * Masking an LVT entry can trigger a local APIC error
576          * if the vector is zero. Mask LVTERR first to prevent this.
577          */
578         if (maxlvt >= 3) {
579                 v = ERROR_APIC_VECTOR; /* any non-zero vector will do */
580                 apic_write_around(APIC_LVTERR, v | APIC_LVT_MASKED);
581         }
582         /*
583          * Careful: we have to set masks only first to deassert
584          * any level-triggered sources.
585          */
586         v = apic_read(APIC_LVTT);
587         apic_write_around(APIC_LVTT, v | APIC_LVT_MASKED);
588         v = apic_read(APIC_LVT0);
589         apic_write_around(APIC_LVT0, v | APIC_LVT_MASKED);
590         v = apic_read(APIC_LVT1);
591         apic_write_around(APIC_LVT1, v | APIC_LVT_MASKED);
592         if (maxlvt >= 4) {
593                 v = apic_read(APIC_LVTPC);
594                 apic_write_around(APIC_LVTPC, v | APIC_LVT_MASKED);
595         }
596
597         /* lets not touch this if we didn't frob it */
598 #ifdef CONFIG_X86_MCE_P4THERMAL
599         if (maxlvt >= 5) {
600                 v = apic_read(APIC_LVTTHMR);
601                 apic_write_around(APIC_LVTTHMR, v | APIC_LVT_MASKED);
602         }
603 #endif
604         /*
605          * Clean APIC state for other OSs:
606          */
607         apic_write_around(APIC_LVTT, APIC_LVT_MASKED);
608         apic_write_around(APIC_LVT0, APIC_LVT_MASKED);
609         apic_write_around(APIC_LVT1, APIC_LVT_MASKED);
610         if (maxlvt >= 3)
611                 apic_write_around(APIC_LVTERR, APIC_LVT_MASKED);
612         if (maxlvt >= 4)
613                 apic_write_around(APIC_LVTPC, APIC_LVT_MASKED);
614
615 #ifdef CONFIG_X86_MCE_P4THERMAL
616         if (maxlvt >= 5)
617                 apic_write_around(APIC_LVTTHMR, APIC_LVT_MASKED);
618 #endif
619         /* Integrated APIC (!82489DX) ? */
620         if (lapic_is_integrated()) {
621                 if (maxlvt > 3)
622                         /* Clear ESR due to Pentium errata 3AP and 11AP */
623                         apic_write(APIC_ESR, 0);
624                 apic_read(APIC_ESR);
625         }
626 }
627
628 /**
629  * disable_local_APIC - clear and disable the local APIC
630  */
631 void disable_local_APIC(void)
632 {
633         unsigned long value;
634
635         clear_local_APIC();
636
637         /*
638          * Disable APIC (implies clearing of registers
639          * for 82489DX!).
640          */
641         value = apic_read(APIC_SPIV);
642         value &= ~APIC_SPIV_APIC_ENABLED;
643         apic_write_around(APIC_SPIV, value);
644
645         /*
646          * When LAPIC was disabled by the BIOS and enabled by the kernel,
647          * restore the disabled state.
648          */
649         if (enabled_via_apicbase) {
650                 unsigned int l, h;
651
652                 rdmsr(MSR_IA32_APICBASE, l, h);
653                 l &= ~MSR_IA32_APICBASE_ENABLE;
654                 wrmsr(MSR_IA32_APICBASE, l, h);
655         }
656 }
657
658 /*
659  * If Linux enabled the LAPIC against the BIOS default disable it down before
660  * re-entering the BIOS on shutdown.  Otherwise the BIOS may get confused and
661  * not power-off.  Additionally clear all LVT entries before disable_local_APIC
662  * for the case where Linux didn't enable the LAPIC.
663  */
664 void lapic_shutdown(void)
665 {
666         unsigned long flags;
667
668         if (!cpu_has_apic)
669                 return;
670
671         local_irq_save(flags);
672         clear_local_APIC();
673
674         if (enabled_via_apicbase)
675                 disable_local_APIC();
676
677         local_irq_restore(flags);
678 }
679
680 /*
681  * This is to verify that we're looking at a real local APIC.
682  * Check these against your board if the CPUs aren't getting
683  * started for no apparent reason.
684  */
685 int __init verify_local_APIC(void)
686 {
687         unsigned int reg0, reg1;
688
689         /*
690          * The version register is read-only in a real APIC.
691          */
692         reg0 = apic_read(APIC_LVR);
693         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg0);
694         apic_write(APIC_LVR, reg0 ^ APIC_LVR_MASK);
695         reg1 = apic_read(APIC_LVR);
696         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg1);
697
698         /*
699          * The two version reads above should print the same
700          * numbers.  If the second one is different, then we
701          * poke at a non-APIC.
702          */
703         if (reg1 != reg0)
704                 return 0;
705
706         /*
707          * Check if the version looks reasonably.
708          */
709         reg1 = GET_APIC_VERSION(reg0);
710         if (reg1 == 0x00 || reg1 == 0xff)
711                 return 0;
712         reg1 = lapic_get_maxlvt();
713         if (reg1 < 0x02 || reg1 == 0xff)
714                 return 0;
715
716         /*
717          * The ID register is read/write in a real APIC.
718          */
719         reg0 = apic_read(APIC_ID);
720         apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg0);
721
722         /*
723          * The next two are just to see if we have sane values.
724          * They're only really relevant if we're in Virtual Wire
725          * compatibility mode, but most boxes are anymore.
726          */
727         reg0 = apic_read(APIC_LVT0);
728         apic_printk(APIC_DEBUG, "Getting LVT0: %x\n", reg0);
729         reg1 = apic_read(APIC_LVT1);
730         apic_printk(APIC_DEBUG, "Getting LVT1: %x\n", reg1);
731
732         return 1;
733 }
734
735 /**
736  * sync_Arb_IDs - synchronize APIC bus arbitration IDs
737  */
738 void __init sync_Arb_IDs(void)
739 {
740         /*
741          * Unsupported on P4 - see Intel Dev. Manual Vol. 3, Ch. 8.6.1 And not
742          * needed on AMD.
743          */
744         if (modern_apic())
745                 return;
746         /*
747          * Wait for idle.
748          */
749         apic_wait_icr_idle();
750
751         apic_printk(APIC_DEBUG, "Synchronizing Arb IDs.\n");
752         apic_write_around(APIC_ICR, APIC_DEST_ALLINC | APIC_INT_LEVELTRIG
753                                 | APIC_DM_INIT);
754 }
755
756 /*
757  * An initial setup of the virtual wire mode.
758  */
759 void __init init_bsp_APIC(void)
760 {
761         unsigned long value;
762
763         /*
764          * Don't do the setup now if we have a SMP BIOS as the
765          * through-I/O-APIC virtual wire mode might be active.
766          */
767         if (smp_found_config || !cpu_has_apic)
768                 return;
769
770         /*
771          * Do not trust the local APIC being empty at bootup.
772          */
773         clear_local_APIC();
774
775         /*
776          * Enable APIC.
777          */
778         value = apic_read(APIC_SPIV);
779         value &= ~APIC_VECTOR_MASK;
780         value |= APIC_SPIV_APIC_ENABLED;
781
782         /* This bit is reserved on P4/Xeon and should be cleared */
783         if ((boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) &&
784             (boot_cpu_data.x86 == 15))
785                 value &= ~APIC_SPIV_FOCUS_DISABLED;
786         else
787                 value |= APIC_SPIV_FOCUS_DISABLED;
788         value |= SPURIOUS_APIC_VECTOR;
789         apic_write_around(APIC_SPIV, value);
790
791         /*
792          * Set up the virtual wire mode.
793          */
794         apic_write_around(APIC_LVT0, APIC_DM_EXTINT);
795         value = APIC_DM_NMI;
796         if (!lapic_is_integrated())             /* 82489DX */
797                 value |= APIC_LVT_LEVEL_TRIGGER;
798         apic_write_around(APIC_LVT1, value);
799 }
800
801 /**
802  * setup_local_APIC - setup the local APIC
803  */
804 void __devinit setup_local_APIC(void)
805 {
806         unsigned long oldvalue, value, maxlvt, integrated;
807         int i, j;
808
809         /* Pound the ESR really hard over the head with a big hammer - mbligh */
810         if (esr_disable) {
811                 apic_write(APIC_ESR, 0);
812                 apic_write(APIC_ESR, 0);
813                 apic_write(APIC_ESR, 0);
814                 apic_write(APIC_ESR, 0);
815         }
816
817         integrated = lapic_is_integrated();
818
819         /*
820          * Double-check whether this APIC is really registered.
821          */
822         if (!apic_id_registered())
823                 BUG();
824
825         /*
826          * Intel recommends to set DFR, LDR and TPR before enabling
827          * an APIC.  See e.g. "AP-388 82489DX User's Manual" (Intel
828          * document number 292116).  So here it goes...
829          */
830         init_apic_ldr();
831
832         /*
833          * Set Task Priority to 'accept all'. We never change this
834          * later on.
835          */
836         value = apic_read(APIC_TASKPRI);
837         value &= ~APIC_TPRI_MASK;
838         apic_write_around(APIC_TASKPRI, value);
839
840         /*
841          * After a crash, we no longer service the interrupts and a pending
842          * interrupt from previous kernel might still have ISR bit set.
843          *
844          * Most probably by now CPU has serviced that pending interrupt and
845          * it might not have done the ack_APIC_irq() because it thought,
846          * interrupt came from i8259 as ExtInt. LAPIC did not get EOI so it
847          * does not clear the ISR bit and cpu thinks it has already serivced
848          * the interrupt. Hence a vector might get locked. It was noticed
849          * for timer irq (vector 0x31). Issue an extra EOI to clear ISR.
850          */
851         for (i = APIC_ISR_NR - 1; i >= 0; i--) {
852                 value = apic_read(APIC_ISR + i*0x10);
853                 for (j = 31; j >= 0; j--) {
854                         if (value & (1<<j))
855                                 ack_APIC_irq();
856                 }
857         }
858
859         /*
860          * Now that we are all set up, enable the APIC
861          */
862         value = apic_read(APIC_SPIV);
863         value &= ~APIC_VECTOR_MASK;
864         /*
865          * Enable APIC
866          */
867         value |= APIC_SPIV_APIC_ENABLED;
868
869         /*
870          * Some unknown Intel IO/APIC (or APIC) errata is biting us with
871          * certain networking cards. If high frequency interrupts are
872          * happening on a particular IOAPIC pin, plus the IOAPIC routing
873          * entry is masked/unmasked at a high rate as well then sooner or
874          * later IOAPIC line gets 'stuck', no more interrupts are received
875          * from the device. If focus CPU is disabled then the hang goes
876          * away, oh well :-(
877          *
878          * [ This bug can be reproduced easily with a level-triggered
879          *   PCI Ne2000 networking cards and PII/PIII processors, dual
880          *   BX chipset. ]
881          */
882         /*
883          * Actually disabling the focus CPU check just makes the hang less
884          * frequent as it makes the interrupt distributon model be more
885          * like LRU than MRU (the short-term load is more even across CPUs).
886          * See also the comment in end_level_ioapic_irq().  --macro
887          */
888
889         /* Enable focus processor (bit==0) */
890         value &= ~APIC_SPIV_FOCUS_DISABLED;
891
892         /*
893          * Set spurious IRQ vector
894          */
895         value |= SPURIOUS_APIC_VECTOR;
896         apic_write_around(APIC_SPIV, value);
897
898         /*
899          * Set up LVT0, LVT1:
900          *
901          * set up through-local-APIC on the BP's LINT0. This is not
902          * strictly necessery in pure symmetric-IO mode, but sometimes
903          * we delegate interrupts to the 8259A.
904          */
905         /*
906          * TODO: set up through-local-APIC from through-I/O-APIC? --macro
907          */
908         value = apic_read(APIC_LVT0) & APIC_LVT_MASKED;
909         if (!smp_processor_id() && (pic_mode || !value)) {
910                 value = APIC_DM_EXTINT;
911                 apic_printk(APIC_VERBOSE, "enabled ExtINT on CPU#%d\n",
912                                 smp_processor_id());
913         } else {
914                 value = APIC_DM_EXTINT | APIC_LVT_MASKED;
915                 apic_printk(APIC_VERBOSE, "masked ExtINT on CPU#%d\n",
916                                 smp_processor_id());
917         }
918         apic_write_around(APIC_LVT0, value);
919
920         /*
921          * only the BP should see the LINT1 NMI signal, obviously.
922          */
923         if (!smp_processor_id())
924                 value = APIC_DM_NMI;
925         else
926                 value = APIC_DM_NMI | APIC_LVT_MASKED;
927         if (!integrated)                /* 82489DX */
928                 value |= APIC_LVT_LEVEL_TRIGGER;
929         apic_write_around(APIC_LVT1, value);
930
931         if (integrated && !esr_disable) {               /* !82489DX */
932                 maxlvt = lapic_get_maxlvt();
933                 if (maxlvt > 3)         /* Due to the Pentium erratum 3AP. */
934                         apic_write(APIC_ESR, 0);
935                 oldvalue = apic_read(APIC_ESR);
936
937                 /* enables sending errors */
938                 value = ERROR_APIC_VECTOR;
939                 apic_write_around(APIC_LVTERR, value);
940                 /*
941                  * spec says clear errors after enabling vector.
942                  */
943                 if (maxlvt > 3)
944                         apic_write(APIC_ESR, 0);
945                 value = apic_read(APIC_ESR);
946                 if (value != oldvalue)
947                         apic_printk(APIC_VERBOSE, "ESR value before enabling "
948                                 "vector: 0x%08lx  after: 0x%08lx\n",
949                                 oldvalue, value);
950         } else {
951                 if (esr_disable)
952                         /*
953                          * Something untraceble is creating bad interrupts on
954                          * secondary quads ... for the moment, just leave the
955                          * ESR disabled - we can't do anything useful with the
956                          * errors anyway - mbligh
957                          */
958                         printk(KERN_INFO "Leaving ESR disabled.\n");
959                 else
960                         printk(KERN_INFO "No ESR for 82489DX.\n");
961         }
962
963         /* Disable the local apic timer */
964         value = apic_read(APIC_LVTT);
965         value |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
966         apic_write_around(APIC_LVTT, value);
967
968         setup_apic_nmi_watchdog(NULL);
969         apic_pm_activate();
970 }
971
972 /*
973  * Detect and initialize APIC
974  */
975 static int __init detect_init_APIC (void)
976 {
977         u32 h, l, features;
978
979         /* Disabled by kernel option? */
980         if (enable_local_apic < 0)
981                 return -1;
982
983         switch (boot_cpu_data.x86_vendor) {
984         case X86_VENDOR_AMD:
985                 if ((boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model > 1) ||
986                     (boot_cpu_data.x86 == 15))
987                         break;
988                 goto no_apic;
989         case X86_VENDOR_INTEL:
990                 if (boot_cpu_data.x86 == 6 || boot_cpu_data.x86 == 15 ||
991                     (boot_cpu_data.x86 == 5 && cpu_has_apic))
992                         break;
993                 goto no_apic;
994         default:
995                 goto no_apic;
996         }
997
998         if (!cpu_has_apic) {
999                 /*
1000                  * Over-ride BIOS and try to enable the local APIC only if
1001                  * "lapic" specified.
1002                  */
1003                 if (enable_local_apic <= 0) {
1004                         printk(KERN_INFO "Local APIC disabled by BIOS -- "
1005                                "you can enable it with \"lapic\"\n");
1006                         return -1;
1007                 }
1008                 /*
1009                  * Some BIOSes disable the local APIC in the APIC_BASE
1010                  * MSR. This can only be done in software for Intel P6 or later
1011                  * and AMD K7 (Model > 1) or later.
1012                  */
1013                 rdmsr(MSR_IA32_APICBASE, l, h);
1014                 if (!(l & MSR_IA32_APICBASE_ENABLE)) {
1015                         printk(KERN_INFO
1016                                "Local APIC disabled by BIOS -- reenabling.\n");
1017                         l &= ~MSR_IA32_APICBASE_BASE;
1018                         l |= MSR_IA32_APICBASE_ENABLE | APIC_DEFAULT_PHYS_BASE;
1019                         wrmsr(MSR_IA32_APICBASE, l, h);
1020                         enabled_via_apicbase = 1;
1021                 }
1022         }
1023         /*
1024          * The APIC feature bit should now be enabled
1025          * in `cpuid'
1026          */
1027         features = cpuid_edx(1);
1028         if (!(features & (1 << X86_FEATURE_APIC))) {
1029                 printk(KERN_WARNING "Could not enable APIC!\n");
1030                 return -1;
1031         }
1032         set_bit(X86_FEATURE_APIC, boot_cpu_data.x86_capability);
1033         mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
1034
1035         /* The BIOS may have set up the APIC at some other address */
1036         rdmsr(MSR_IA32_APICBASE, l, h);
1037         if (l & MSR_IA32_APICBASE_ENABLE)
1038                 mp_lapic_addr = l & MSR_IA32_APICBASE_BASE;
1039
1040         if (nmi_watchdog != NMI_NONE)
1041                 nmi_watchdog = NMI_LOCAL_APIC;
1042
1043         printk(KERN_INFO "Found and enabled local APIC!\n");
1044
1045         apic_pm_activate();
1046
1047         return 0;
1048
1049 no_apic:
1050         printk(KERN_INFO "No local APIC present or hardware disabled\n");
1051         return -1;
1052 }
1053
1054 /**
1055  * init_apic_mappings - initialize APIC mappings
1056  */
1057 void __init init_apic_mappings(void)
1058 {
1059         unsigned long apic_phys;
1060
1061         /*
1062          * If no local APIC can be found then set up a fake all
1063          * zeroes page to simulate the local APIC and another
1064          * one for the IO-APIC.
1065          */
1066         if (!smp_found_config && detect_init_APIC()) {
1067                 apic_phys = (unsigned long) alloc_bootmem_pages(PAGE_SIZE);
1068                 apic_phys = __pa(apic_phys);
1069         } else
1070                 apic_phys = mp_lapic_addr;
1071
1072         set_fixmap_nocache(FIX_APIC_BASE, apic_phys);
1073         printk(KERN_DEBUG "mapped APIC to %08lx (%08lx)\n", APIC_BASE,
1074                apic_phys);
1075
1076         /*
1077          * Fetch the APIC ID of the BSP in case we have a
1078          * default configuration (or the MP table is broken).
1079          */
1080         if (boot_cpu_physical_apicid == -1U)
1081                 boot_cpu_physical_apicid = GET_APIC_ID(apic_read(APIC_ID));
1082
1083 #ifdef CONFIG_X86_IO_APIC
1084         {
1085                 unsigned long ioapic_phys, idx = FIX_IO_APIC_BASE_0;
1086                 int i;
1087
1088                 for (i = 0; i < nr_ioapics; i++) {
1089                         if (smp_found_config) {
1090                                 ioapic_phys = mp_ioapics[i].mpc_apicaddr;
1091                                 if (!ioapic_phys) {
1092                                         printk(KERN_ERR
1093                                                "WARNING: bogus zero IO-APIC "
1094                                                "address found in MPTABLE, "
1095                                                "disabling IO/APIC support!\n");
1096                                         smp_found_config = 0;
1097                                         skip_ioapic_setup = 1;
1098                                         goto fake_ioapic_page;
1099                                 }
1100                         } else {
1101 fake_ioapic_page:
1102                                 ioapic_phys = (unsigned long)
1103                                               alloc_bootmem_pages(PAGE_SIZE);
1104                                 ioapic_phys = __pa(ioapic_phys);
1105                         }
1106                         set_fixmap_nocache(idx, ioapic_phys);
1107                         printk(KERN_DEBUG "mapped IOAPIC to %08lx (%08lx)\n",
1108                                __fix_to_virt(idx), ioapic_phys);
1109                         idx++;
1110                 }
1111         }
1112 #endif
1113 }
1114
1115 /*
1116  * This initializes the IO-APIC and APIC hardware if this is
1117  * a UP kernel.
1118  */
1119 int __init APIC_init_uniprocessor (void)
1120 {
1121         if (enable_local_apic < 0)
1122                 clear_bit(X86_FEATURE_APIC, boot_cpu_data.x86_capability);
1123
1124         if (!smp_found_config && !cpu_has_apic)
1125                 return -1;
1126
1127         /*
1128          * Complain if the BIOS pretends there is one.
1129          */
1130         if (!cpu_has_apic &&
1131             APIC_INTEGRATED(apic_version[boot_cpu_physical_apicid])) {
1132                 printk(KERN_ERR "BIOS bug, local APIC #%d not detected!...\n",
1133                        boot_cpu_physical_apicid);
1134                 clear_bit(X86_FEATURE_APIC, boot_cpu_data.x86_capability);
1135                 return -1;
1136         }
1137
1138         verify_local_APIC();
1139
1140         connect_bsp_APIC();
1141
1142         /*
1143          * Hack: In case of kdump, after a crash, kernel might be booting
1144          * on a cpu with non-zero lapic id. But boot_cpu_physical_apicid
1145          * might be zero if read from MP tables. Get it from LAPIC.
1146          */
1147 #ifdef CONFIG_CRASH_DUMP
1148         boot_cpu_physical_apicid = GET_APIC_ID(apic_read(APIC_ID));
1149 #endif
1150         phys_cpu_present_map = physid_mask_of_physid(boot_cpu_physical_apicid);
1151
1152         setup_local_APIC();
1153
1154 #ifdef CONFIG_X86_IO_APIC
1155         if (smp_found_config)
1156                 if (!skip_ioapic_setup && nr_ioapics)
1157                         setup_IO_APIC();
1158 #endif
1159         setup_boot_clock();
1160
1161         return 0;
1162 }
1163
1164 /*
1165  * APIC command line parameters
1166  */
1167 static int __init parse_lapic(char *arg)
1168 {
1169         enable_local_apic = 1;
1170         return 0;
1171 }
1172 early_param("lapic", parse_lapic);
1173
1174 static int __init parse_nolapic(char *arg)
1175 {
1176         enable_local_apic = -1;
1177         clear_bit(X86_FEATURE_APIC, boot_cpu_data.x86_capability);
1178         return 0;
1179 }
1180 early_param("nolapic", parse_nolapic);
1181
1182 static int __init apic_set_verbosity(char *str)
1183 {
1184         if (strcmp("debug", str) == 0)
1185                 apic_verbosity = APIC_DEBUG;
1186         else if (strcmp("verbose", str) == 0)
1187                 apic_verbosity = APIC_VERBOSE;
1188         return 1;
1189 }
1190
1191 __setup("apic=", apic_set_verbosity);
1192
1193
1194 /*
1195  * Local APIC interrupts
1196  */
1197
1198 /*
1199  * This interrupt should _never_ happen with our APIC/SMP architecture
1200  */
1201 void smp_spurious_interrupt(struct pt_regs *regs)
1202 {
1203         unsigned long v;
1204
1205         irq_enter();
1206         /*
1207          * Check if this really is a spurious interrupt and ACK it
1208          * if it is a vectored one.  Just in case...
1209          * Spurious interrupts should not be ACKed.
1210          */
1211         v = apic_read(APIC_ISR + ((SPURIOUS_APIC_VECTOR & ~0x1f) >> 1));
1212         if (v & (1 << (SPURIOUS_APIC_VECTOR & 0x1f)))
1213                 ack_APIC_irq();
1214
1215         /* see sw-dev-man vol 3, chapter 7.4.13.5 */
1216         printk(KERN_INFO "spurious APIC interrupt on CPU#%d, "
1217                "should never happen.\n", smp_processor_id());
1218         irq_exit();
1219 }
1220
1221 /*
1222  * This interrupt should never happen with our APIC/SMP architecture
1223  */
1224 void smp_error_interrupt(struct pt_regs *regs)
1225 {
1226         unsigned long v, v1;
1227
1228         irq_enter();
1229         /* First tickle the hardware, only then report what went on. -- REW */
1230         v = apic_read(APIC_ESR);
1231         apic_write(APIC_ESR, 0);
1232         v1 = apic_read(APIC_ESR);
1233         ack_APIC_irq();
1234         atomic_inc(&irq_err_count);
1235
1236         /* Here is what the APIC error bits mean:
1237            0: Send CS error
1238            1: Receive CS error
1239            2: Send accept error
1240            3: Receive accept error
1241            4: Reserved
1242            5: Send illegal vector
1243            6: Received illegal vector
1244            7: Illegal register address
1245         */
1246         printk (KERN_DEBUG "APIC error on CPU%d: %02lx(%02lx)\n",
1247                 smp_processor_id(), v , v1);
1248         irq_exit();
1249 }
1250
1251 /*
1252  * Initialize APIC interrupts
1253  */
1254 void __init apic_intr_init(void)
1255 {
1256 #ifdef CONFIG_SMP
1257         smp_intr_init();
1258 #endif
1259         /* self generated IPI for local APIC timer */
1260         set_intr_gate(LOCAL_TIMER_VECTOR, apic_timer_interrupt);
1261
1262         /* IPI vectors for APIC spurious and error interrupts */
1263         set_intr_gate(SPURIOUS_APIC_VECTOR, spurious_interrupt);
1264         set_intr_gate(ERROR_APIC_VECTOR, error_interrupt);
1265
1266         /* thermal monitor LVT interrupt */
1267 #ifdef CONFIG_X86_MCE_P4THERMAL
1268         set_intr_gate(THERMAL_APIC_VECTOR, thermal_interrupt);
1269 #endif
1270 }
1271
1272 /**
1273  * connect_bsp_APIC - attach the APIC to the interrupt system
1274  */
1275 void __init connect_bsp_APIC(void)
1276 {
1277         if (pic_mode) {
1278                 /*
1279                  * Do not trust the local APIC being empty at bootup.
1280                  */
1281                 clear_local_APIC();
1282                 /*
1283                  * PIC mode, enable APIC mode in the IMCR, i.e.  connect BSP's
1284                  * local APIC to INT and NMI lines.
1285                  */
1286                 apic_printk(APIC_VERBOSE, "leaving PIC mode, "
1287                                 "enabling APIC mode.\n");
1288                 outb(0x70, 0x22);
1289                 outb(0x01, 0x23);
1290         }
1291         enable_apic_mode();
1292 }
1293
1294 /**
1295  * disconnect_bsp_APIC - detach the APIC from the interrupt system
1296  * @virt_wire_setup:    indicates, whether virtual wire mode is selected
1297  *
1298  * Virtual wire mode is necessary to deliver legacy interrupts even when the
1299  * APIC is disabled.
1300  */
1301 void disconnect_bsp_APIC(int virt_wire_setup)
1302 {
1303         if (pic_mode) {
1304                 /*
1305                  * Put the board back into PIC mode (has an effect only on
1306                  * certain older boards).  Note that APIC interrupts, including
1307                  * IPIs, won't work beyond this point!  The only exception are
1308                  * INIT IPIs.
1309                  */
1310                 apic_printk(APIC_VERBOSE, "disabling APIC mode, "
1311                                 "entering PIC mode.\n");
1312                 outb(0x70, 0x22);
1313                 outb(0x00, 0x23);
1314         } else {
1315                 /* Go back to Virtual Wire compatibility mode */
1316                 unsigned long value;
1317
1318                 /* For the spurious interrupt use vector F, and enable it */
1319                 value = apic_read(APIC_SPIV);
1320                 value &= ~APIC_VECTOR_MASK;
1321                 value |= APIC_SPIV_APIC_ENABLED;
1322                 value |= 0xf;
1323                 apic_write_around(APIC_SPIV, value);
1324
1325                 if (!virt_wire_setup) {
1326                         /*
1327                          * For LVT0 make it edge triggered, active high,
1328                          * external and enabled
1329                          */
1330                         value = apic_read(APIC_LVT0);
1331                         value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
1332                                 APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
1333                                 APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED );
1334                         value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
1335                         value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_EXTINT);
1336                         apic_write_around(APIC_LVT0, value);
1337                 } else {
1338                         /* Disable LVT0 */
1339                         apic_write_around(APIC_LVT0, APIC_LVT_MASKED);
1340                 }
1341
1342                 /*
1343                  * For LVT1 make it edge triggered, active high, nmi and
1344                  * enabled
1345                  */
1346                 value = apic_read(APIC_LVT1);
1347                 value &= ~(
1348                         APIC_MODE_MASK | APIC_SEND_PENDING |
1349                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
1350                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
1351                 value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
1352                 value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_NMI);
1353                 apic_write_around(APIC_LVT1, value);
1354         }
1355 }
1356
1357 /*
1358  * Power management
1359  */
1360 #ifdef CONFIG_PM
1361
1362 static struct {
1363         int active;
1364         /* r/w apic fields */
1365         unsigned int apic_id;
1366         unsigned int apic_taskpri;
1367         unsigned int apic_ldr;
1368         unsigned int apic_dfr;
1369         unsigned int apic_spiv;
1370         unsigned int apic_lvtt;
1371         unsigned int apic_lvtpc;
1372         unsigned int apic_lvt0;
1373         unsigned int apic_lvt1;
1374         unsigned int apic_lvterr;
1375         unsigned int apic_tmict;
1376         unsigned int apic_tdcr;
1377         unsigned int apic_thmr;
1378 } apic_pm_state;
1379
1380 static int lapic_suspend(struct sys_device *dev, pm_message_t state)
1381 {
1382         unsigned long flags;
1383         int maxlvt;
1384
1385         if (!apic_pm_state.active)
1386                 return 0;
1387
1388         maxlvt = lapic_get_maxlvt();
1389
1390         apic_pm_state.apic_id = apic_read(APIC_ID);
1391         apic_pm_state.apic_taskpri = apic_read(APIC_TASKPRI);
1392         apic_pm_state.apic_ldr = apic_read(APIC_LDR);
1393         apic_pm_state.apic_dfr = apic_read(APIC_DFR);
1394         apic_pm_state.apic_spiv = apic_read(APIC_SPIV);
1395         apic_pm_state.apic_lvtt = apic_read(APIC_LVTT);
1396         if (maxlvt >= 4)
1397                 apic_pm_state.apic_lvtpc = apic_read(APIC_LVTPC);
1398         apic_pm_state.apic_lvt0 = apic_read(APIC_LVT0);
1399         apic_pm_state.apic_lvt1 = apic_read(APIC_LVT1);
1400         apic_pm_state.apic_lvterr = apic_read(APIC_LVTERR);
1401         apic_pm_state.apic_tmict = apic_read(APIC_TMICT);
1402         apic_pm_state.apic_tdcr = apic_read(APIC_TDCR);
1403 #ifdef CONFIG_X86_MCE_P4THERMAL
1404         if (maxlvt >= 5)
1405                 apic_pm_state.apic_thmr = apic_read(APIC_LVTTHMR);
1406 #endif
1407
1408         local_irq_save(flags);
1409         disable_local_APIC();
1410         local_irq_restore(flags);
1411         return 0;
1412 }
1413
1414 static int lapic_resume(struct sys_device *dev)
1415 {
1416         unsigned int l, h;
1417         unsigned long flags;
1418         int maxlvt;
1419
1420         if (!apic_pm_state.active)
1421                 return 0;
1422
1423         maxlvt = lapic_get_maxlvt();
1424
1425         local_irq_save(flags);
1426
1427         /*
1428          * Make sure the APICBASE points to the right address
1429          *
1430          * FIXME! This will be wrong if we ever support suspend on
1431          * SMP! We'll need to do this as part of the CPU restore!
1432          */
1433         rdmsr(MSR_IA32_APICBASE, l, h);
1434         l &= ~MSR_IA32_APICBASE_BASE;
1435         l |= MSR_IA32_APICBASE_ENABLE | mp_lapic_addr;
1436         wrmsr(MSR_IA32_APICBASE, l, h);
1437
1438         apic_write(APIC_LVTERR, ERROR_APIC_VECTOR | APIC_LVT_MASKED);
1439         apic_write(APIC_ID, apic_pm_state.apic_id);
1440         apic_write(APIC_DFR, apic_pm_state.apic_dfr);
1441         apic_write(APIC_LDR, apic_pm_state.apic_ldr);
1442         apic_write(APIC_TASKPRI, apic_pm_state.apic_taskpri);
1443         apic_write(APIC_SPIV, apic_pm_state.apic_spiv);
1444         apic_write(APIC_LVT0, apic_pm_state.apic_lvt0);
1445         apic_write(APIC_LVT1, apic_pm_state.apic_lvt1);
1446 #ifdef CONFIG_X86_MCE_P4THERMAL
1447         if (maxlvt >= 5)
1448                 apic_write(APIC_LVTTHMR, apic_pm_state.apic_thmr);
1449 #endif
1450         if (maxlvt >= 4)
1451                 apic_write(APIC_LVTPC, apic_pm_state.apic_lvtpc);
1452         apic_write(APIC_LVTT, apic_pm_state.apic_lvtt);
1453         apic_write(APIC_TDCR, apic_pm_state.apic_tdcr);
1454         apic_write(APIC_TMICT, apic_pm_state.apic_tmict);
1455         apic_write(APIC_ESR, 0);
1456         apic_read(APIC_ESR);
1457         apic_write(APIC_LVTERR, apic_pm_state.apic_lvterr);
1458         apic_write(APIC_ESR, 0);
1459         apic_read(APIC_ESR);
1460         local_irq_restore(flags);
1461         return 0;
1462 }
1463
1464 /*
1465  * This device has no shutdown method - fully functioning local APICs
1466  * are needed on every CPU up until machine_halt/restart/poweroff.
1467  */
1468
1469 static struct sysdev_class lapic_sysclass = {
1470         set_kset_name("lapic"),
1471         .resume         = lapic_resume,
1472         .suspend        = lapic_suspend,
1473 };
1474
1475 static struct sys_device device_lapic = {
1476         .id     = 0,
1477         .cls    = &lapic_sysclass,
1478 };
1479
1480 static void __devinit apic_pm_activate(void)
1481 {
1482         apic_pm_state.active = 1;
1483 }
1484
1485 static int __init init_lapic_sysfs(void)
1486 {
1487         int error;
1488
1489         if (!cpu_has_apic)
1490                 return 0;
1491         /* XXX: remove suspend/resume procs if !apic_pm_state.active? */
1492
1493         error = sysdev_class_register(&lapic_sysclass);
1494         if (!error)
1495                 error = sysdev_register(&device_lapic);
1496         return error;
1497 }
1498 device_initcall(init_lapic_sysfs);
1499
1500 #else   /* CONFIG_PM */
1501
1502 static void apic_pm_activate(void) { }
1503
1504 #endif  /* CONFIG_PM */