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