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