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