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