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