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