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