x86: move ipi definitions to mach_ipi.h
[safe/jmp/linux-2.6] / arch / x86 / kernel / apic_64.c
1 /*
2  *      Local APIC handling, local APIC timers
3  *
4  *      (c) 1999, 2000 Ingo Molnar <mingo@redhat.com>
5  *
6  *      Fixes
7  *      Maciej W. Rozycki       :       Bits for genuine 82489DX APICs;
8  *                                      thanks to Eric Gilmore
9  *                                      and Rolf G. Tews
10  *                                      for testing these extensively.
11  *      Maciej W. Rozycki       :       Various updates and fixes.
12  *      Mikael Pettersson       :       Power Management for UP-APIC.
13  *      Pavel Machek and
14  *      Mikael Pettersson       :       PM converted to driver model.
15  */
16
17 #include <linux/init.h>
18
19 #include <linux/mm.h>
20 #include <linux/delay.h>
21 #include <linux/bootmem.h>
22 #include <linux/interrupt.h>
23 #include <linux/mc146818rtc.h>
24 #include <linux/kernel_stat.h>
25 #include <linux/sysdev.h>
26 #include <linux/ioport.h>
27 #include <linux/clockchips.h>
28 #include <linux/acpi_pmtmr.h>
29 #include <linux/module.h>
30
31 #include <asm/atomic.h>
32 #include <asm/smp.h>
33 #include <asm/mtrr.h>
34 #include <asm/mpspec.h>
35 #include <asm/hpet.h>
36 #include <asm/pgalloc.h>
37 #include <asm/mach_apic.h>
38 #include <asm/nmi.h>
39 #include <asm/idle.h>
40 #include <asm/proto.h>
41 #include <asm/timex.h>
42 #include <asm/apic.h>
43
44 #include <mach_ipi.h>
45
46 int disable_apic_timer __cpuinitdata;
47 static int apic_calibrate_pmtmr __initdata;
48 int disable_apic;
49
50 /* Local APIC timer works in C2 */
51 int local_apic_timer_c2_ok;
52 EXPORT_SYMBOL_GPL(local_apic_timer_c2_ok);
53
54 /*
55  * Debug level, exported for io_apic.c
56  */
57 int apic_verbosity;
58
59 static struct resource lapic_resource = {
60         .name = "Local APIC",
61         .flags = IORESOURCE_MEM | IORESOURCE_BUSY,
62 };
63
64 static unsigned int calibration_result;
65
66 static int lapic_next_event(unsigned long delta,
67                             struct clock_event_device *evt);
68 static void lapic_timer_setup(enum clock_event_mode mode,
69                               struct clock_event_device *evt);
70 static void lapic_timer_broadcast(cpumask_t mask);
71 static void apic_pm_activate(void);
72
73 static struct clock_event_device lapic_clockevent = {
74         .name           = "lapic",
75         .features       = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT
76                         | CLOCK_EVT_FEAT_C3STOP | CLOCK_EVT_FEAT_DUMMY,
77         .shift          = 32,
78         .set_mode       = lapic_timer_setup,
79         .set_next_event = lapic_next_event,
80         .broadcast      = lapic_timer_broadcast,
81         .rating         = 100,
82         .irq            = -1,
83 };
84 static DEFINE_PER_CPU(struct clock_event_device, lapic_events);
85
86 static unsigned long apic_phys;
87
88 /*
89  * Get the LAPIC version
90  */
91 static inline int lapic_get_version(void)
92 {
93         return GET_APIC_VERSION(apic_read(APIC_LVR));
94 }
95
96 /*
97  * Check, if the APIC is integrated or a seperate chip
98  */
99 static inline int lapic_is_integrated(void)
100 {
101         return 1;
102 }
103
104 /*
105  * Check, whether this is a modern or a first generation APIC
106  */
107 static int modern_apic(void)
108 {
109         /* AMD systems use old APIC versions, so check the CPU */
110         if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD &&
111             boot_cpu_data.x86 >= 0xf)
112                 return 1;
113         return lapic_get_version() >= 0x14;
114 }
115
116 void apic_wait_icr_idle(void)
117 {
118         while (apic_read(APIC_ICR) & APIC_ICR_BUSY)
119                 cpu_relax();
120 }
121
122 u32 safe_apic_wait_icr_idle(void)
123 {
124         u32 send_status;
125         int timeout;
126
127         timeout = 0;
128         do {
129                 send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
130                 if (!send_status)
131                         break;
132                 udelay(100);
133         } while (timeout++ < 1000);
134
135         return send_status;
136 }
137
138 /**
139  * enable_NMI_through_LVT0 - enable NMI through local vector table 0
140  */
141 void __cpuinit enable_NMI_through_LVT0(void)
142 {
143         unsigned int v;
144
145         /* unmask and set to NMI */
146         v = APIC_DM_NMI;
147         apic_write(APIC_LVT0, v);
148 }
149
150 /**
151  * lapic_get_maxlvt - get the maximum number of local vector table entries
152  */
153 int lapic_get_maxlvt(void)
154 {
155         unsigned int v, maxlvt;
156
157         v = apic_read(APIC_LVR);
158         maxlvt = GET_APIC_MAXLVT(v);
159         return maxlvt;
160 }
161
162 /*
163  * This function sets up the local APIC timer, with a timeout of
164  * 'clocks' APIC bus clock. During calibration we actually call
165  * this function twice on the boot CPU, once with a bogus timeout
166  * value, second time for real. The other (noncalibrating) CPUs
167  * call this function only once, with the real, calibrated value.
168  *
169  * We do reads before writes even if unnecessary, to get around the
170  * P5 APIC double write bug.
171  */
172
173 static void __setup_APIC_LVTT(unsigned int clocks, int oneshot, int irqen)
174 {
175         unsigned int lvtt_value, tmp_value;
176
177         lvtt_value = LOCAL_TIMER_VECTOR;
178         if (!oneshot)
179                 lvtt_value |= APIC_LVT_TIMER_PERIODIC;
180         if (!irqen)
181                 lvtt_value |= APIC_LVT_MASKED;
182
183         apic_write(APIC_LVTT, lvtt_value);
184
185         /*
186          * Divide PICLK by 16
187          */
188         tmp_value = apic_read(APIC_TDCR);
189         apic_write(APIC_TDCR, (tmp_value
190                                 & ~(APIC_TDR_DIV_1 | APIC_TDR_DIV_TMBASE))
191                                 | APIC_TDR_DIV_16);
192
193         if (!oneshot)
194                 apic_write(APIC_TMICT, clocks);
195 }
196
197 /*
198  * Setup extended LVT, AMD specific (K8, family 10h)
199  *
200  * Vector mappings are hard coded. On K8 only offset 0 (APIC500) and
201  * MCE interrupts are supported. Thus MCE offset must be set to 0.
202  */
203
204 #define APIC_EILVT_LVTOFF_MCE 0
205 #define APIC_EILVT_LVTOFF_IBS 1
206
207 static void setup_APIC_eilvt(u8 lvt_off, u8 vector, u8 msg_type, u8 mask)
208 {
209         unsigned long reg = (lvt_off << 4) + APIC_EILVT0;
210         unsigned int  v   = (mask << 16) | (msg_type << 8) | vector;
211
212         apic_write(reg, v);
213 }
214
215 u8 setup_APIC_eilvt_mce(u8 vector, u8 msg_type, u8 mask)
216 {
217         setup_APIC_eilvt(APIC_EILVT_LVTOFF_MCE, vector, msg_type, mask);
218         return APIC_EILVT_LVTOFF_MCE;
219 }
220
221 u8 setup_APIC_eilvt_ibs(u8 vector, u8 msg_type, u8 mask)
222 {
223         setup_APIC_eilvt(APIC_EILVT_LVTOFF_IBS, vector, msg_type, mask);
224         return APIC_EILVT_LVTOFF_IBS;
225 }
226
227 /*
228  * Program the next event, relative to now
229  */
230 static int lapic_next_event(unsigned long delta,
231                             struct clock_event_device *evt)
232 {
233         apic_write(APIC_TMICT, delta);
234         return 0;
235 }
236
237 /*
238  * Setup the lapic timer in periodic or oneshot mode
239  */
240 static void lapic_timer_setup(enum clock_event_mode mode,
241                               struct clock_event_device *evt)
242 {
243         unsigned long flags;
244         unsigned int v;
245
246         /* Lapic used as dummy for broadcast ? */
247         if (evt->features & CLOCK_EVT_FEAT_DUMMY)
248                 return;
249
250         local_irq_save(flags);
251
252         switch (mode) {
253         case CLOCK_EVT_MODE_PERIODIC:
254         case CLOCK_EVT_MODE_ONESHOT:
255                 __setup_APIC_LVTT(calibration_result,
256                                   mode != CLOCK_EVT_MODE_PERIODIC, 1);
257                 break;
258         case CLOCK_EVT_MODE_UNUSED:
259         case CLOCK_EVT_MODE_SHUTDOWN:
260                 v = apic_read(APIC_LVTT);
261                 v |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
262                 apic_write(APIC_LVTT, v);
263                 break;
264         case CLOCK_EVT_MODE_RESUME:
265                 /* Nothing to do here */
266                 break;
267         }
268
269         local_irq_restore(flags);
270 }
271
272 /*
273  * Local APIC timer broadcast function
274  */
275 static void lapic_timer_broadcast(cpumask_t mask)
276 {
277 #ifdef CONFIG_SMP
278         send_IPI_mask(mask, LOCAL_TIMER_VECTOR);
279 #endif
280 }
281
282 /*
283  * Setup the local APIC timer for this CPU. Copy the initilized values
284  * of the boot CPU and register the clock event in the framework.
285  */
286 static void setup_APIC_timer(void)
287 {
288         struct clock_event_device *levt = &__get_cpu_var(lapic_events);
289
290         memcpy(levt, &lapic_clockevent, sizeof(*levt));
291         levt->cpumask = cpumask_of_cpu(smp_processor_id());
292
293         clockevents_register_device(levt);
294 }
295
296 /*
297  * In this function we calibrate APIC bus clocks to the external
298  * timer. Unfortunately we cannot use jiffies and the timer irq
299  * to calibrate, since some later bootup code depends on getting
300  * the first irq? Ugh.
301  *
302  * We want to do the calibration only once since we
303  * want to have local timer irqs syncron. CPUs connected
304  * by the same APIC bus have the very same bus frequency.
305  * And we want to have irqs off anyways, no accidental
306  * APIC irq that way.
307  */
308
309 #define TICK_COUNT 100000000
310
311 static void __init calibrate_APIC_clock(void)
312 {
313         unsigned apic, apic_start;
314         unsigned long tsc, tsc_start;
315         int result;
316
317         local_irq_disable();
318
319         /*
320          * Put whatever arbitrary (but long enough) timeout
321          * value into the APIC clock, we just want to get the
322          * counter running for calibration.
323          *
324          * No interrupt enable !
325          */
326         __setup_APIC_LVTT(250000000, 0, 0);
327
328         apic_start = apic_read(APIC_TMCCT);
329 #ifdef CONFIG_X86_PM_TIMER
330         if (apic_calibrate_pmtmr && pmtmr_ioport) {
331                 pmtimer_wait(5000);  /* 5ms wait */
332                 apic = apic_read(APIC_TMCCT);
333                 result = (apic_start - apic) * 1000L / 5;
334         } else
335 #endif
336         {
337                 rdtscll(tsc_start);
338
339                 do {
340                         apic = apic_read(APIC_TMCCT);
341                         rdtscll(tsc);
342                 } while ((tsc - tsc_start) < TICK_COUNT &&
343                                 (apic_start - apic) < TICK_COUNT);
344
345                 result = (apic_start - apic) * 1000L * tsc_khz /
346                                         (tsc - tsc_start);
347         }
348
349         local_irq_enable();
350
351         printk(KERN_DEBUG "APIC timer calibration result %d\n", result);
352
353         printk(KERN_INFO "Detected %d.%03d MHz APIC timer.\n",
354                 result / 1000 / 1000, result / 1000 % 1000);
355
356         /* Calculate the scaled math multiplication factor */
357         lapic_clockevent.mult = div_sc(result, NSEC_PER_SEC, 32);
358         lapic_clockevent.max_delta_ns =
359                 clockevent_delta2ns(0x7FFFFF, &lapic_clockevent);
360         lapic_clockevent.min_delta_ns =
361                 clockevent_delta2ns(0xF, &lapic_clockevent);
362
363         calibration_result = result / HZ;
364 }
365
366 /*
367  * Setup the boot APIC
368  *
369  * Calibrate and verify the result.
370  */
371 void __init setup_boot_APIC_clock(void)
372 {
373         /*
374          * The local apic timer can be disabled via the kernel commandline.
375          * Register the lapic timer as a dummy clock event source on SMP
376          * systems, so the broadcast mechanism is used. On UP systems simply
377          * ignore it.
378          */
379         if (disable_apic_timer) {
380                 printk(KERN_INFO "Disabling APIC timer\n");
381                 /* No broadcast on UP ! */
382                 if (num_possible_cpus() > 1) {
383                         lapic_clockevent.mult = 1;
384                         setup_APIC_timer();
385                 }
386                 return;
387         }
388
389         printk(KERN_INFO "Using local APIC timer interrupts.\n");
390         calibrate_APIC_clock();
391
392         /*
393          * Do a sanity check on the APIC calibration result
394          */
395         if (calibration_result < (1000000 / HZ)) {
396                 printk(KERN_WARNING
397                        "APIC frequency too slow, disabling apic timer\n");
398                 /* No broadcast on UP ! */
399                 if (num_possible_cpus() > 1)
400                         setup_APIC_timer();
401                 return;
402         }
403
404         /*
405          * If nmi_watchdog is set to IO_APIC, we need the
406          * PIT/HPET going.  Otherwise register lapic as a dummy
407          * device.
408          */
409         if (nmi_watchdog != NMI_IO_APIC)
410                 lapic_clockevent.features &= ~CLOCK_EVT_FEAT_DUMMY;
411         else
412                 printk(KERN_WARNING "APIC timer registered as dummy,"
413                        " due to nmi_watchdog=1!\n");
414
415         setup_APIC_timer();
416 }
417
418 /*
419  * AMD C1E enabled CPUs have a real nasty problem: Some BIOSes set the
420  * C1E flag only in the secondary CPU, so when we detect the wreckage
421  * we already have enabled the boot CPU local apic timer. Check, if
422  * disable_apic_timer is set and the DUMMY flag is cleared. If yes,
423  * set the DUMMY flag again and force the broadcast mode in the
424  * clockevents layer.
425  */
426 void __cpuinit check_boot_apic_timer_broadcast(void)
427 {
428         if (!disable_apic_timer ||
429             (lapic_clockevent.features & CLOCK_EVT_FEAT_DUMMY))
430                 return;
431
432         printk(KERN_INFO "AMD C1E detected late. Force timer broadcast.\n");
433         lapic_clockevent.features |= CLOCK_EVT_FEAT_DUMMY;
434
435         local_irq_enable();
436         clockevents_notify(CLOCK_EVT_NOTIFY_BROADCAST_FORCE,
437                            &boot_cpu_physical_apicid);
438         local_irq_disable();
439 }
440
441 void __cpuinit setup_secondary_APIC_clock(void)
442 {
443         check_boot_apic_timer_broadcast();
444         setup_APIC_timer();
445 }
446
447 /*
448  * The guts of the apic timer interrupt
449  */
450 static void local_apic_timer_interrupt(void)
451 {
452         int cpu = smp_processor_id();
453         struct clock_event_device *evt = &per_cpu(lapic_events, cpu);
454
455         /*
456          * Normally we should not be here till LAPIC has been initialized but
457          * in some cases like kdump, its possible that there is a pending LAPIC
458          * timer interrupt from previous kernel's context and is delivered in
459          * new kernel the moment interrupts are enabled.
460          *
461          * Interrupts are enabled early and LAPIC is setup much later, hence
462          * its possible that when we get here evt->event_handler is NULL.
463          * Check for event_handler being NULL and discard the interrupt as
464          * spurious.
465          */
466         if (!evt->event_handler) {
467                 printk(KERN_WARNING
468                        "Spurious LAPIC timer interrupt on cpu %d\n", cpu);
469                 /* Switch it off */
470                 lapic_timer_setup(CLOCK_EVT_MODE_SHUTDOWN, evt);
471                 return;
472         }
473
474         /*
475          * the NMI deadlock-detector uses this.
476          */
477         add_pda(apic_timer_irqs, 1);
478
479         evt->event_handler(evt);
480 }
481
482 /*
483  * Local APIC timer interrupt. This is the most natural way for doing
484  * local interrupts, but local timer interrupts can be emulated by
485  * broadcast interrupts too. [in case the hw doesn't support APIC timers]
486  *
487  * [ if a single-CPU system runs an SMP kernel then we call the local
488  *   interrupt as well. Thus we cannot inline the local irq ... ]
489  */
490 void smp_apic_timer_interrupt(struct pt_regs *regs)
491 {
492         struct pt_regs *old_regs = set_irq_regs(regs);
493
494         /*
495          * NOTE! We'd better ACK the irq immediately,
496          * because timer handling can be slow.
497          */
498         ack_APIC_irq();
499         /*
500          * update_process_times() expects us to have done irq_enter().
501          * Besides, if we don't timer interrupts ignore the global
502          * interrupt lock, which is the WrongThing (tm) to do.
503          */
504         exit_idle();
505         irq_enter();
506         local_apic_timer_interrupt();
507         irq_exit();
508         set_irq_regs(old_regs);
509 }
510
511 int setup_profiling_timer(unsigned int multiplier)
512 {
513         return -EINVAL;
514 }
515
516
517 /*
518  * Local APIC start and shutdown
519  */
520
521 /**
522  * clear_local_APIC - shutdown the local APIC
523  *
524  * This is called, when a CPU is disabled and before rebooting, so the state of
525  * the local APIC has no dangling leftovers. Also used to cleanout any BIOS
526  * leftovers during boot.
527  */
528 void clear_local_APIC(void)
529 {
530         int maxlvt = lapic_get_maxlvt();
531         u32 v;
532
533         /* APIC hasn't been mapped yet */
534         if (!apic_phys)
535                 return;
536
537         maxlvt = lapic_get_maxlvt();
538         /*
539          * Masking an LVT entry can trigger a local APIC error
540          * if the vector is zero. Mask LVTERR first to prevent this.
541          */
542         if (maxlvt >= 3) {
543                 v = ERROR_APIC_VECTOR; /* any non-zero vector will do */
544                 apic_write(APIC_LVTERR, v | APIC_LVT_MASKED);
545         }
546         /*
547          * Careful: we have to set masks only first to deassert
548          * any level-triggered sources.
549          */
550         v = apic_read(APIC_LVTT);
551         apic_write(APIC_LVTT, v | APIC_LVT_MASKED);
552         v = apic_read(APIC_LVT0);
553         apic_write(APIC_LVT0, v | APIC_LVT_MASKED);
554         v = apic_read(APIC_LVT1);
555         apic_write(APIC_LVT1, v | APIC_LVT_MASKED);
556         if (maxlvt >= 4) {
557                 v = apic_read(APIC_LVTPC);
558                 apic_write(APIC_LVTPC, v | APIC_LVT_MASKED);
559         }
560
561         /*
562          * Clean APIC state for other OSs:
563          */
564         apic_write(APIC_LVTT, APIC_LVT_MASKED);
565         apic_write(APIC_LVT0, APIC_LVT_MASKED);
566         apic_write(APIC_LVT1, APIC_LVT_MASKED);
567         if (maxlvt >= 3)
568                 apic_write(APIC_LVTERR, APIC_LVT_MASKED);
569         if (maxlvt >= 4)
570                 apic_write(APIC_LVTPC, APIC_LVT_MASKED);
571         apic_write(APIC_ESR, 0);
572         apic_read(APIC_ESR);
573 }
574
575 /**
576  * disable_local_APIC - clear and disable the local APIC
577  */
578 void disable_local_APIC(void)
579 {
580         unsigned int value;
581
582         clear_local_APIC();
583
584         /*
585          * Disable APIC (implies clearing of registers
586          * for 82489DX!).
587          */
588         value = apic_read(APIC_SPIV);
589         value &= ~APIC_SPIV_APIC_ENABLED;
590         apic_write(APIC_SPIV, value);
591 }
592
593 void lapic_shutdown(void)
594 {
595         unsigned long flags;
596
597         if (!cpu_has_apic)
598                 return;
599
600         local_irq_save(flags);
601
602         disable_local_APIC();
603
604         local_irq_restore(flags);
605 }
606
607 /*
608  * This is to verify that we're looking at a real local APIC.
609  * Check these against your board if the CPUs aren't getting
610  * started for no apparent reason.
611  */
612 int __init verify_local_APIC(void)
613 {
614         unsigned int reg0, reg1;
615
616         /*
617          * The version register is read-only in a real APIC.
618          */
619         reg0 = apic_read(APIC_LVR);
620         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg0);
621         apic_write(APIC_LVR, reg0 ^ APIC_LVR_MASK);
622         reg1 = apic_read(APIC_LVR);
623         apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg1);
624
625         /*
626          * The two version reads above should print the same
627          * numbers.  If the second one is different, then we
628          * poke at a non-APIC.
629          */
630         if (reg1 != reg0)
631                 return 0;
632
633         /*
634          * Check if the version looks reasonably.
635          */
636         reg1 = GET_APIC_VERSION(reg0);
637         if (reg1 == 0x00 || reg1 == 0xff)
638                 return 0;
639         reg1 = lapic_get_maxlvt();
640         if (reg1 < 0x02 || reg1 == 0xff)
641                 return 0;
642
643         /*
644          * The ID register is read/write in a real APIC.
645          */
646         reg0 = apic_read(APIC_ID);
647         apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg0);
648         apic_write(APIC_ID, reg0 ^ APIC_ID_MASK);
649         reg1 = apic_read(APIC_ID);
650         apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg1);
651         apic_write(APIC_ID, reg0);
652         if (reg1 != (reg0 ^ APIC_ID_MASK))
653                 return 0;
654
655         /*
656          * The next two are just to see if we have sane values.
657          * They're only really relevant if we're in Virtual Wire
658          * compatibility mode, but most boxes are anymore.
659          */
660         reg0 = apic_read(APIC_LVT0);
661         apic_printk(APIC_DEBUG, "Getting LVT0: %x\n", reg0);
662         reg1 = apic_read(APIC_LVT1);
663         apic_printk(APIC_DEBUG, "Getting LVT1: %x\n", reg1);
664
665         return 1;
666 }
667
668 /**
669  * sync_Arb_IDs - synchronize APIC bus arbitration IDs
670  */
671 void __init sync_Arb_IDs(void)
672 {
673         /* Unsupported on P4 - see Intel Dev. Manual Vol. 3, Ch. 8.6.1 */
674         if (modern_apic())
675                 return;
676
677         /*
678          * Wait for idle.
679          */
680         apic_wait_icr_idle();
681
682         apic_printk(APIC_DEBUG, "Synchronizing Arb IDs.\n");
683         apic_write(APIC_ICR, APIC_DEST_ALLINC | APIC_INT_LEVELTRIG
684                                 | APIC_DM_INIT);
685 }
686
687 /*
688  * An initial setup of the virtual wire mode.
689  */
690 void __init init_bsp_APIC(void)
691 {
692         unsigned int value;
693
694         /*
695          * Don't do the setup now if we have a SMP BIOS as the
696          * through-I/O-APIC virtual wire mode might be active.
697          */
698         if (smp_found_config || !cpu_has_apic)
699                 return;
700
701         value = apic_read(APIC_LVR);
702
703         /*
704          * Do not trust the local APIC being empty at bootup.
705          */
706         clear_local_APIC();
707
708         /*
709          * Enable APIC.
710          */
711         value = apic_read(APIC_SPIV);
712         value &= ~APIC_VECTOR_MASK;
713         value |= APIC_SPIV_APIC_ENABLED;
714         value |= APIC_SPIV_FOCUS_DISABLED;
715         value |= SPURIOUS_APIC_VECTOR;
716         apic_write(APIC_SPIV, value);
717
718         /*
719          * Set up the virtual wire mode.
720          */
721         apic_write(APIC_LVT0, APIC_DM_EXTINT);
722         value = APIC_DM_NMI;
723         apic_write(APIC_LVT1, value);
724 }
725
726 /**
727  * setup_local_APIC - setup the local APIC
728  */
729 void __cpuinit setup_local_APIC(void)
730 {
731         unsigned int value;
732         int i, j;
733
734         value = apic_read(APIC_LVR);
735
736         BUILD_BUG_ON((SPURIOUS_APIC_VECTOR & 0x0f) != 0x0f);
737
738         /*
739          * Double-check whether this APIC is really registered.
740          * This is meaningless in clustered apic mode, so we skip it.
741          */
742         if (!apic_id_registered())
743                 BUG();
744
745         /*
746          * Intel recommends to set DFR, LDR and TPR before enabling
747          * an APIC.  See e.g. "AP-388 82489DX User's Manual" (Intel
748          * document number 292116).  So here it goes...
749          */
750         init_apic_ldr();
751
752         /*
753          * Set Task Priority to 'accept all'. We never change this
754          * later on.
755          */
756         value = apic_read(APIC_TASKPRI);
757         value &= ~APIC_TPRI_MASK;
758         apic_write(APIC_TASKPRI, value);
759
760         /*
761          * After a crash, we no longer service the interrupts and a pending
762          * interrupt from previous kernel might still have ISR bit set.
763          *
764          * Most probably by now CPU has serviced that pending interrupt and
765          * it might not have done the ack_APIC_irq() because it thought,
766          * interrupt came from i8259 as ExtInt. LAPIC did not get EOI so it
767          * does not clear the ISR bit and cpu thinks it has already serivced
768          * the interrupt. Hence a vector might get locked. It was noticed
769          * for timer irq (vector 0x31). Issue an extra EOI to clear ISR.
770          */
771         for (i = APIC_ISR_NR - 1; i >= 0; i--) {
772                 value = apic_read(APIC_ISR + i*0x10);
773                 for (j = 31; j >= 0; j--) {
774                         if (value & (1<<j))
775                                 ack_APIC_irq();
776                 }
777         }
778
779         /*
780          * Now that we are all set up, enable the APIC
781          */
782         value = apic_read(APIC_SPIV);
783         value &= ~APIC_VECTOR_MASK;
784         /*
785          * Enable APIC
786          */
787         value |= APIC_SPIV_APIC_ENABLED;
788
789         /* We always use processor focus */
790
791         /*
792          * Set spurious IRQ vector
793          */
794         value |= SPURIOUS_APIC_VECTOR;
795         apic_write(APIC_SPIV, value);
796
797         /*
798          * Set up LVT0, LVT1:
799          *
800          * set up through-local-APIC on the BP's LINT0. This is not
801          * strictly necessary in pure symmetric-IO mode, but sometimes
802          * we delegate interrupts to the 8259A.
803          */
804         /*
805          * TODO: set up through-local-APIC from through-I/O-APIC? --macro
806          */
807         value = apic_read(APIC_LVT0) & APIC_LVT_MASKED;
808         if (!smp_processor_id() && !value) {
809                 value = APIC_DM_EXTINT;
810                 apic_printk(APIC_VERBOSE, "enabled ExtINT on CPU#%d\n",
811                             smp_processor_id());
812         } else {
813                 value = APIC_DM_EXTINT | APIC_LVT_MASKED;
814                 apic_printk(APIC_VERBOSE, "masked ExtINT on CPU#%d\n",
815                             smp_processor_id());
816         }
817         apic_write(APIC_LVT0, value);
818
819         /*
820          * only the BP should see the LINT1 NMI signal, obviously.
821          */
822         if (!smp_processor_id())
823                 value = APIC_DM_NMI;
824         else
825                 value = APIC_DM_NMI | APIC_LVT_MASKED;
826         apic_write(APIC_LVT1, value);
827 }
828
829 void __cpuinit lapic_setup_esr(void)
830 {
831         unsigned maxlvt = lapic_get_maxlvt();
832
833         apic_write(APIC_LVTERR, ERROR_APIC_VECTOR);
834         /*
835          * spec says clear errors after enabling vector.
836          */
837         if (maxlvt > 3)
838                 apic_write(APIC_ESR, 0);
839 }
840
841 void __cpuinit end_local_APIC_setup(void)
842 {
843         lapic_setup_esr();
844         nmi_watchdog_default();
845         setup_apic_nmi_watchdog(NULL);
846         apic_pm_activate();
847 }
848
849 /*
850  * Detect and enable local APICs on non-SMP boards.
851  * Original code written by Keir Fraser.
852  * On AMD64 we trust the BIOS - if it says no APIC it is likely
853  * not correctly set up (usually the APIC timer won't work etc.)
854  */
855 static int __init detect_init_APIC(void)
856 {
857         if (!cpu_has_apic) {
858                 printk(KERN_INFO "No local APIC present\n");
859                 return -1;
860         }
861
862         mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
863         boot_cpu_physical_apicid = 0;
864         return 0;
865 }
866
867 void __init early_init_lapic_mapping(void)
868 {
869         unsigned long apic_phys;
870
871         /*
872          * If no local APIC can be found then go out
873          * : it means there is no mpatable and MADT
874          */
875         if (!smp_found_config)
876                 return;
877
878         apic_phys = mp_lapic_addr;
879
880         set_fixmap_nocache(FIX_APIC_BASE, apic_phys);
881         apic_printk(APIC_VERBOSE, "mapped APIC to %16lx (%16lx)\n",
882                                  APIC_BASE, apic_phys);
883
884         /*
885          * Fetch the APIC ID of the BSP in case we have a
886          * default configuration (or the MP table is broken).
887          */
888         boot_cpu_physical_apicid = GET_APIC_ID(apic_read(APIC_ID));
889 }
890
891 /**
892  * init_apic_mappings - initialize APIC mappings
893  */
894 void __init init_apic_mappings(void)
895 {
896         /*
897          * If no local APIC can be found then set up a fake all
898          * zeroes page to simulate the local APIC and another
899          * one for the IO-APIC.
900          */
901         if (!smp_found_config && detect_init_APIC()) {
902                 apic_phys = (unsigned long) alloc_bootmem_pages(PAGE_SIZE);
903                 apic_phys = __pa(apic_phys);
904         } else
905                 apic_phys = mp_lapic_addr;
906
907         set_fixmap_nocache(FIX_APIC_BASE, apic_phys);
908         apic_printk(APIC_VERBOSE, "mapped APIC to %16lx (%16lx)\n",
909                                 APIC_BASE, apic_phys);
910
911         /*
912          * Fetch the APIC ID of the BSP in case we have a
913          * default configuration (or the MP table is broken).
914          */
915         boot_cpu_physical_apicid = GET_APIC_ID(apic_read(APIC_ID));
916 }
917
918 /*
919  * This initializes the IO-APIC and APIC hardware if this is
920  * a UP kernel.
921  */
922 int __init APIC_init_uniprocessor(void)
923 {
924         if (disable_apic) {
925                 printk(KERN_INFO "Apic disabled\n");
926                 return -1;
927         }
928         if (!cpu_has_apic) {
929                 disable_apic = 1;
930                 printk(KERN_INFO "Apic disabled by BIOS\n");
931                 return -1;
932         }
933
934         verify_local_APIC();
935
936         phys_cpu_present_map = physid_mask_of_physid(boot_cpu_physical_apicid);
937         apic_write(APIC_ID, SET_APIC_ID(boot_cpu_physical_apicid));
938
939         setup_local_APIC();
940
941         /*
942          * Now enable IO-APICs, actually call clear_IO_APIC
943          * We need clear_IO_APIC before enabling vector on BP
944          */
945         if (!skip_ioapic_setup && nr_ioapics)
946                 enable_IO_APIC();
947
948         end_local_APIC_setup();
949
950         if (smp_found_config && !skip_ioapic_setup && nr_ioapics)
951                 setup_IO_APIC();
952         else
953                 nr_ioapics = 0;
954         setup_boot_APIC_clock();
955         check_nmi_watchdog();
956         return 0;
957 }
958
959 /*
960  * Local APIC interrupts
961  */
962
963 /*
964  * This interrupt should _never_ happen with our APIC/SMP architecture
965  */
966 asmlinkage void smp_spurious_interrupt(void)
967 {
968         unsigned int v;
969         exit_idle();
970         irq_enter();
971         /*
972          * Check if this really is a spurious interrupt and ACK it
973          * if it is a vectored one.  Just in case...
974          * Spurious interrupts should not be ACKed.
975          */
976         v = apic_read(APIC_ISR + ((SPURIOUS_APIC_VECTOR & ~0x1f) >> 1));
977         if (v & (1 << (SPURIOUS_APIC_VECTOR & 0x1f)))
978                 ack_APIC_irq();
979
980         add_pda(irq_spurious_count, 1);
981         irq_exit();
982 }
983
984 /*
985  * This interrupt should never happen with our APIC/SMP architecture
986  */
987 asmlinkage void smp_error_interrupt(void)
988 {
989         unsigned int v, v1;
990
991         exit_idle();
992         irq_enter();
993         /* First tickle the hardware, only then report what went on. -- REW */
994         v = apic_read(APIC_ESR);
995         apic_write(APIC_ESR, 0);
996         v1 = apic_read(APIC_ESR);
997         ack_APIC_irq();
998         atomic_inc(&irq_err_count);
999
1000         /* Here is what the APIC error bits mean:
1001            0: Send CS error
1002            1: Receive CS error
1003            2: Send accept error
1004            3: Receive accept error
1005            4: Reserved
1006            5: Send illegal vector
1007            6: Received illegal vector
1008            7: Illegal register address
1009         */
1010         printk(KERN_DEBUG "APIC error on CPU%d: %02x(%02x)\n",
1011                 smp_processor_id(), v , v1);
1012         irq_exit();
1013 }
1014
1015 void disconnect_bsp_APIC(int virt_wire_setup)
1016 {
1017         /* Go back to Virtual Wire compatibility mode */
1018         unsigned long value;
1019
1020         /* For the spurious interrupt use vector F, and enable it */
1021         value = apic_read(APIC_SPIV);
1022         value &= ~APIC_VECTOR_MASK;
1023         value |= APIC_SPIV_APIC_ENABLED;
1024         value |= 0xf;
1025         apic_write(APIC_SPIV, value);
1026
1027         if (!virt_wire_setup) {
1028                 /*
1029                  * For LVT0 make it edge triggered, active high,
1030                  * external and enabled
1031                  */
1032                 value = apic_read(APIC_LVT0);
1033                 value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
1034                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
1035                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
1036                 value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
1037                 value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_EXTINT);
1038                 apic_write(APIC_LVT0, value);
1039         } else {
1040                 /* Disable LVT0 */
1041                 apic_write(APIC_LVT0, APIC_LVT_MASKED);
1042         }
1043
1044         /* For LVT1 make it edge triggered, active high, nmi and enabled */
1045         value = apic_read(APIC_LVT1);
1046         value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
1047                         APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
1048                         APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
1049         value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
1050         value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_NMI);
1051         apic_write(APIC_LVT1, value);
1052 }
1053
1054 /*
1055  * Power management
1056  */
1057 #ifdef CONFIG_PM
1058
1059 static struct {
1060         /* 'active' is true if the local APIC was enabled by us and
1061            not the BIOS; this signifies that we are also responsible
1062            for disabling it before entering apm/acpi suspend */
1063         int active;
1064         /* r/w apic fields */
1065         unsigned int apic_id;
1066         unsigned int apic_taskpri;
1067         unsigned int apic_ldr;
1068         unsigned int apic_dfr;
1069         unsigned int apic_spiv;
1070         unsigned int apic_lvtt;
1071         unsigned int apic_lvtpc;
1072         unsigned int apic_lvt0;
1073         unsigned int apic_lvt1;
1074         unsigned int apic_lvterr;
1075         unsigned int apic_tmict;
1076         unsigned int apic_tdcr;
1077         unsigned int apic_thmr;
1078 } apic_pm_state;
1079
1080 static int lapic_suspend(struct sys_device *dev, pm_message_t state)
1081 {
1082         unsigned long flags;
1083         int maxlvt;
1084
1085         if (!apic_pm_state.active)
1086                 return 0;
1087
1088         maxlvt = lapic_get_maxlvt();
1089
1090         apic_pm_state.apic_id = apic_read(APIC_ID);
1091         apic_pm_state.apic_taskpri = apic_read(APIC_TASKPRI);
1092         apic_pm_state.apic_ldr = apic_read(APIC_LDR);
1093         apic_pm_state.apic_dfr = apic_read(APIC_DFR);
1094         apic_pm_state.apic_spiv = apic_read(APIC_SPIV);
1095         apic_pm_state.apic_lvtt = apic_read(APIC_LVTT);
1096         if (maxlvt >= 4)
1097                 apic_pm_state.apic_lvtpc = apic_read(APIC_LVTPC);
1098         apic_pm_state.apic_lvt0 = apic_read(APIC_LVT0);
1099         apic_pm_state.apic_lvt1 = apic_read(APIC_LVT1);
1100         apic_pm_state.apic_lvterr = apic_read(APIC_LVTERR);
1101         apic_pm_state.apic_tmict = apic_read(APIC_TMICT);
1102         apic_pm_state.apic_tdcr = apic_read(APIC_TDCR);
1103 #ifdef CONFIG_X86_MCE_INTEL
1104         if (maxlvt >= 5)
1105                 apic_pm_state.apic_thmr = apic_read(APIC_LVTTHMR);
1106 #endif
1107         local_irq_save(flags);
1108         disable_local_APIC();
1109         local_irq_restore(flags);
1110         return 0;
1111 }
1112
1113 static int lapic_resume(struct sys_device *dev)
1114 {
1115         unsigned int l, h;
1116         unsigned long flags;
1117         int maxlvt;
1118
1119         if (!apic_pm_state.active)
1120                 return 0;
1121
1122         maxlvt = lapic_get_maxlvt();
1123
1124         local_irq_save(flags);
1125         rdmsr(MSR_IA32_APICBASE, l, h);
1126         l &= ~MSR_IA32_APICBASE_BASE;
1127         l |= MSR_IA32_APICBASE_ENABLE | mp_lapic_addr;
1128         wrmsr(MSR_IA32_APICBASE, l, h);
1129         apic_write(APIC_LVTERR, ERROR_APIC_VECTOR | APIC_LVT_MASKED);
1130         apic_write(APIC_ID, apic_pm_state.apic_id);
1131         apic_write(APIC_DFR, apic_pm_state.apic_dfr);
1132         apic_write(APIC_LDR, apic_pm_state.apic_ldr);
1133         apic_write(APIC_TASKPRI, apic_pm_state.apic_taskpri);
1134         apic_write(APIC_SPIV, apic_pm_state.apic_spiv);
1135         apic_write(APIC_LVT0, apic_pm_state.apic_lvt0);
1136         apic_write(APIC_LVT1, apic_pm_state.apic_lvt1);
1137 #ifdef CONFIG_X86_MCE_INTEL
1138         if (maxlvt >= 5)
1139                 apic_write(APIC_LVTTHMR, apic_pm_state.apic_thmr);
1140 #endif
1141         if (maxlvt >= 4)
1142                 apic_write(APIC_LVTPC, apic_pm_state.apic_lvtpc);
1143         apic_write(APIC_LVTT, apic_pm_state.apic_lvtt);
1144         apic_write(APIC_TDCR, apic_pm_state.apic_tdcr);
1145         apic_write(APIC_TMICT, apic_pm_state.apic_tmict);
1146         apic_write(APIC_ESR, 0);
1147         apic_read(APIC_ESR);
1148         apic_write(APIC_LVTERR, apic_pm_state.apic_lvterr);
1149         apic_write(APIC_ESR, 0);
1150         apic_read(APIC_ESR);
1151         local_irq_restore(flags);
1152         return 0;
1153 }
1154
1155 static struct sysdev_class lapic_sysclass = {
1156         .name           = "lapic",
1157         .resume         = lapic_resume,
1158         .suspend        = lapic_suspend,
1159 };
1160
1161 static struct sys_device device_lapic = {
1162         .id     = 0,
1163         .cls    = &lapic_sysclass,
1164 };
1165
1166 static void __cpuinit apic_pm_activate(void)
1167 {
1168         apic_pm_state.active = 1;
1169 }
1170
1171 static int __init init_lapic_sysfs(void)
1172 {
1173         int error;
1174
1175         if (!cpu_has_apic)
1176                 return 0;
1177         /* XXX: remove suspend/resume procs if !apic_pm_state.active? */
1178
1179         error = sysdev_class_register(&lapic_sysclass);
1180         if (!error)
1181                 error = sysdev_register(&device_lapic);
1182         return error;
1183 }
1184 device_initcall(init_lapic_sysfs);
1185
1186 #else   /* CONFIG_PM */
1187
1188 static void apic_pm_activate(void) { }
1189
1190 #endif  /* CONFIG_PM */
1191
1192 /*
1193  * apic_is_clustered_box() -- Check if we can expect good TSC
1194  *
1195  * Thus far, the major user of this is IBM's Summit2 series:
1196  *
1197  * Clustered boxes may have unsynced TSC problems if they are
1198  * multi-chassis. Use available data to take a good guess.
1199  * If in doubt, go HPET.
1200  */
1201 __cpuinit int apic_is_clustered_box(void)
1202 {
1203         int i, clusters, zeros;
1204         unsigned id;
1205         u16 *bios_cpu_apicid;
1206         DECLARE_BITMAP(clustermap, NUM_APIC_CLUSTERS);
1207
1208         /*
1209          * there is not this kind of box with AMD CPU yet.
1210          * Some AMD box with quadcore cpu and 8 sockets apicid
1211          * will be [4, 0x23] or [8, 0x27] could be thought to
1212          * vsmp box still need checking...
1213          */
1214         if ((boot_cpu_data.x86_vendor == X86_VENDOR_AMD) && !is_vsmp_box())
1215                 return 0;
1216
1217         bios_cpu_apicid = x86_bios_cpu_apicid_early_ptr;
1218         bitmap_zero(clustermap, NUM_APIC_CLUSTERS);
1219
1220         for (i = 0; i < NR_CPUS; i++) {
1221                 /* are we being called early in kernel startup? */
1222                 if (bios_cpu_apicid) {
1223                         id = bios_cpu_apicid[i];
1224                 }
1225                 else if (i < nr_cpu_ids) {
1226                         if (cpu_present(i))
1227                                 id = per_cpu(x86_bios_cpu_apicid, i);
1228                         else
1229                                 continue;
1230                 }
1231                 else
1232                         break;
1233
1234                 if (id != BAD_APICID)
1235                         __set_bit(APIC_CLUSTERID(id), clustermap);
1236         }
1237
1238         /* Problem:  Partially populated chassis may not have CPUs in some of
1239          * the APIC clusters they have been allocated.  Only present CPUs have
1240          * x86_bios_cpu_apicid entries, thus causing zeroes in the bitmap.
1241          * Since clusters are allocated sequentially, count zeros only if
1242          * they are bounded by ones.
1243          */
1244         clusters = 0;
1245         zeros = 0;
1246         for (i = 0; i < NUM_APIC_CLUSTERS; i++) {
1247                 if (test_bit(i, clustermap)) {
1248                         clusters += 1 + zeros;
1249                         zeros = 0;
1250                 } else
1251                         ++zeros;
1252         }
1253
1254         /* ScaleMP vSMPowered boxes have one cluster per board and TSCs are
1255          * not guaranteed to be synced between boards
1256          */
1257         if (is_vsmp_box() && clusters > 1)
1258                 return 1;
1259
1260         /*
1261          * If clusters > 2, then should be multi-chassis.
1262          * May have to revisit this when multi-core + hyperthreaded CPUs come
1263          * out, but AFAIK this will work even for them.
1264          */
1265         return (clusters > 2);
1266 }
1267
1268 /*
1269  * APIC command line parameters
1270  */
1271 static int __init apic_set_verbosity(char *str)
1272 {
1273         if (str == NULL)  {
1274                 skip_ioapic_setup = 0;
1275                 ioapic_force = 1;
1276                 return 0;
1277         }
1278         if (strcmp("debug", str) == 0)
1279                 apic_verbosity = APIC_DEBUG;
1280         else if (strcmp("verbose", str) == 0)
1281                 apic_verbosity = APIC_VERBOSE;
1282         else {
1283                 printk(KERN_WARNING "APIC Verbosity level %s not recognised"
1284                                 " use apic=verbose or apic=debug\n", str);
1285                 return -EINVAL;
1286         }
1287
1288         return 0;
1289 }
1290 early_param("apic", apic_set_verbosity);
1291
1292 static __init int setup_disableapic(char *str)
1293 {
1294         disable_apic = 1;
1295         clear_cpu_cap(&boot_cpu_data, X86_FEATURE_APIC);
1296         return 0;
1297 }
1298 early_param("disableapic", setup_disableapic);
1299
1300 /* same as disableapic, for compatibility */
1301 static __init int setup_nolapic(char *str)
1302 {
1303         return setup_disableapic(str);
1304 }
1305 early_param("nolapic", setup_nolapic);
1306
1307 static int __init parse_lapic_timer_c2_ok(char *arg)
1308 {
1309         local_apic_timer_c2_ok = 1;
1310         return 0;
1311 }
1312 early_param("lapic_timer_c2_ok", parse_lapic_timer_c2_ok);
1313
1314 static __init int setup_noapictimer(char *str)
1315 {
1316         if (str[0] != ' ' && str[0] != 0)
1317                 return 0;
1318         disable_apic_timer = 1;
1319         return 1;
1320 }
1321 __setup("noapictimer", setup_noapictimer);
1322
1323 static __init int setup_apicpmtimer(char *s)
1324 {
1325         apic_calibrate_pmtmr = 1;
1326         notsc_setup(NULL);
1327         return 0;
1328 }
1329 __setup("apicpmtimer", setup_apicpmtimer);
1330
1331 static int __init lapic_insert_resource(void)
1332 {
1333         if (!apic_phys)
1334                 return -1;
1335
1336         /* Put local APIC into the resource map. */
1337         lapic_resource.start = apic_phys;
1338         lapic_resource.end = lapic_resource.start + PAGE_SIZE - 1;
1339         insert_resource(&iomem_resource, &lapic_resource);
1340
1341         return 0;
1342 }
1343
1344 /*
1345  * need call insert after e820_reserve_resources()
1346  * that is using request_resource
1347  */
1348 late_initcall(lapic_insert_resource);