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