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