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