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