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/module.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 
38 #include <asm/perf_event.h>
39 #include <asm/x86_init.h>
40 #include <asm/pgalloc.h>
41 #include <linux/atomic.h>
42 #include <asm/mpspec.h>
43 #include <asm/i8259.h>
44 #include <asm/proto.h>
45 #include <asm/apic.h>
46 #include <asm/io_apic.h>
47 #include <asm/desc.h>
48 #include <asm/hpet.h>
49 #include <asm/idle.h>
50 #include <asm/mtrr.h>
51 #include <asm/time.h>
52 #include <asm/smp.h>
53 #include <asm/mce.h>
54 #include <asm/tsc.h>
55 #include <asm/hypervisor.h>
56 
57 unsigned int num_processors;
58 
59 unsigned disabled_cpus __cpuinitdata;
60 
61 /* Processor that is doing the boot up */
62 unsigned int boot_cpu_physical_apicid = -1U;
63 
64 /*
65  * The highest APIC ID seen during enumeration.
66  */
67 unsigned int max_physical_apicid;
68 
69 /*
70  * Bitmask of physically existing CPUs:
71  */
72 physid_mask_t phys_cpu_present_map;
73 
74 /*
75  * Map cpu index to physical APIC ID
76  */
77 DEFINE_EARLY_PER_CPU(u16, x86_cpu_to_apicid, BAD_APICID);
78 DEFINE_EARLY_PER_CPU(u16, x86_bios_cpu_apicid, BAD_APICID);
79 EXPORT_EARLY_PER_CPU_SYMBOL(x86_cpu_to_apicid);
80 EXPORT_EARLY_PER_CPU_SYMBOL(x86_bios_cpu_apicid);
81 
82 #ifdef CONFIG_X86_32
83 
84 /*
85  * On x86_32, the mapping between cpu and logical apicid may vary
86  * depending on apic in use.  The following early percpu variable is
87  * used for the mapping.  This is where the behaviors of x86_64 and 32
88  * actually diverge.  Let's keep it ugly for now.
89  */
90 DEFINE_EARLY_PER_CPU(int, x86_cpu_to_logical_apicid, BAD_APICID);
91 
92 /*
93  * Knob to control our willingness to enable the local APIC.
94  *
95  * +1=force-enable
96  */
97 static int force_enable_local_apic __initdata;
98 /*
99  * APIC command line parameters
100  */
parse_lapic(char * arg)101 static int __init parse_lapic(char *arg)
102 {
103 	force_enable_local_apic = 1;
104 	return 0;
105 }
106 early_param("lapic", parse_lapic);
107 /* Local APIC was disabled by the BIOS and enabled by the kernel */
108 static int enabled_via_apicbase;
109 
110 /*
111  * Handle interrupt mode configuration register (IMCR).
112  * This register controls whether the interrupt signals
113  * that reach the BSP come from the master PIC or from the
114  * local APIC. Before entering Symmetric I/O Mode, either
115  * the BIOS or the operating system must switch out of
116  * PIC Mode by changing the IMCR.
117  */
imcr_pic_to_apic(void)118 static inline void imcr_pic_to_apic(void)
119 {
120 	/* select IMCR register */
121 	outb(0x70, 0x22);
122 	/* NMI and 8259 INTR go through APIC */
123 	outb(0x01, 0x23);
124 }
125 
imcr_apic_to_pic(void)126 static inline void imcr_apic_to_pic(void)
127 {
128 	/* select IMCR register */
129 	outb(0x70, 0x22);
130 	/* NMI and 8259 INTR go directly to BSP */
131 	outb(0x00, 0x23);
132 }
133 #endif
134 
135 #ifdef CONFIG_X86_64
136 static int apic_calibrate_pmtmr __initdata;
setup_apicpmtimer(char * s)137 static __init int setup_apicpmtimer(char *s)
138 {
139 	apic_calibrate_pmtmr = 1;
140 	notsc_setup(NULL);
141 	return 0;
142 }
143 __setup("apicpmtimer", setup_apicpmtimer);
144 #endif
145 
146 int x2apic_mode;
147 #ifdef CONFIG_X86_X2APIC
148 /* x2apic enabled before OS handover */
149 int x2apic_preenabled;
150 static int x2apic_disabled;
151 static int nox2apic;
setup_nox2apic(char * str)152 static __init int setup_nox2apic(char *str)
153 {
154 	if (x2apic_enabled()) {
155 		int apicid = native_apic_msr_read(APIC_ID);
156 
157 		if (apicid >= 255) {
158 			pr_warning("Apicid: %08x, cannot enforce nox2apic\n",
159 				   apicid);
160 			return 0;
161 		}
162 
163 		pr_warning("x2apic already enabled. will disable it\n");
164 	} else
165 		setup_clear_cpu_cap(X86_FEATURE_X2APIC);
166 
167 	nox2apic = 1;
168 
169 	return 0;
170 }
171 early_param("nox2apic", setup_nox2apic);
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 int first_system_vector = 0xfe;
183 
184 /*
185  * Debug level, exported for io_apic.c
186  */
187 unsigned int apic_verbosity;
188 
189 int pic_mode;
190 
191 /* Have we found an MP table */
192 int smp_found_config;
193 
194 static struct resource lapic_resource = {
195 	.name = "Local APIC",
196 	.flags = IORESOURCE_MEM | IORESOURCE_BUSY,
197 };
198 
199 unsigned int lapic_timer_frequency = 0;
200 
201 static void apic_pm_activate(void);
202 
203 static unsigned long apic_phys;
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 #ifdef CONFIG_X86_64
219 	return 1;
220 #else
221 	return APIC_INTEGRATED(lapic_get_version());
222 #endif
223 }
224 
225 /*
226  * Check, whether this is a modern or a first generation APIC
227  */
modern_apic(void)228 static int modern_apic(void)
229 {
230 	/* AMD systems use old APIC versions, so check the CPU */
231 	if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD &&
232 	    boot_cpu_data.x86 >= 0xf)
233 		return 1;
234 	return lapic_get_version() >= 0x14;
235 }
236 
237 /*
238  * right after this call apic become NOOP driven
239  * so apic->write/read doesn't do anything
240  */
apic_disable(void)241 static void __init apic_disable(void)
242 {
243 	pr_info("APIC: switched to apic NOOP\n");
244 	apic = &apic_noop;
245 }
246 
native_apic_wait_icr_idle(void)247 void native_apic_wait_icr_idle(void)
248 {
249 	while (apic_read(APIC_ICR) & APIC_ICR_BUSY)
250 		cpu_relax();
251 }
252 
native_safe_apic_wait_icr_idle(void)253 u32 native_safe_apic_wait_icr_idle(void)
254 {
255 	u32 send_status;
256 	int timeout;
257 
258 	timeout = 0;
259 	do {
260 		send_status = apic_read(APIC_ICR) & APIC_ICR_BUSY;
261 		if (!send_status)
262 			break;
263 		inc_irq_stat(icr_read_retry_count);
264 		udelay(100);
265 	} while (timeout++ < 1000);
266 
267 	return send_status;
268 }
269 
native_apic_icr_write(u32 low,u32 id)270 void native_apic_icr_write(u32 low, u32 id)
271 {
272 	apic_write(APIC_ICR2, SET_APIC_DEST_FIELD(id));
273 	apic_write(APIC_ICR, low);
274 }
275 
native_apic_icr_read(void)276 u64 native_apic_icr_read(void)
277 {
278 	u32 icr1, icr2;
279 
280 	icr2 = apic_read(APIC_ICR2);
281 	icr1 = apic_read(APIC_ICR);
282 
283 	return icr1 | ((u64)icr2 << 32);
284 }
285 
286 #ifdef CONFIG_X86_32
287 /**
288  * get_physical_broadcast - Get number of physical broadcast IDs
289  */
get_physical_broadcast(void)290 int get_physical_broadcast(void)
291 {
292 	return modern_apic() ? 0xff : 0xf;
293 }
294 #endif
295 
296 /**
297  * lapic_get_maxlvt - get the maximum number of local vector table entries
298  */
lapic_get_maxlvt(void)299 int lapic_get_maxlvt(void)
300 {
301 	unsigned int v;
302 
303 	v = apic_read(APIC_LVR);
304 	/*
305 	 * - we always have APIC integrated on 64bit mode
306 	 * - 82489DXs do not report # of LVT entries
307 	 */
308 	return APIC_INTEGRATED(GET_APIC_VERSION(v)) ? GET_APIC_MAXLVT(v) : 2;
309 }
310 
311 /*
312  * Local APIC timer
313  */
314 
315 /* Clock divisor */
316 #define APIC_DIVISOR 16
317 
318 /*
319  * This function sets up the local APIC timer, with a timeout of
320  * 'clocks' APIC bus clock. During calibration we actually call
321  * this function twice on the boot CPU, once with a bogus timeout
322  * value, second time for real. The other (noncalibrating) CPUs
323  * call this function only once, with the real, calibrated value.
324  *
325  * We do reads before writes even if unnecessary, to get around the
326  * P5 APIC double write bug.
327  */
__setup_APIC_LVTT(unsigned int clocks,int oneshot,int irqen)328 static void __setup_APIC_LVTT(unsigned int clocks, int oneshot, int irqen)
329 {
330 	unsigned int lvtt_value, tmp_value;
331 
332 	lvtt_value = LOCAL_TIMER_VECTOR;
333 	if (!oneshot)
334 		lvtt_value |= APIC_LVT_TIMER_PERIODIC;
335 	if (!lapic_is_integrated())
336 		lvtt_value |= SET_APIC_TIMER_BASE(APIC_TIMER_BASE_DIV);
337 
338 	if (!irqen)
339 		lvtt_value |= APIC_LVT_MASKED;
340 
341 	apic_write(APIC_LVTT, lvtt_value);
342 
343 	/*
344 	 * Divide PICLK by 16
345 	 */
346 	tmp_value = apic_read(APIC_TDCR);
347 	apic_write(APIC_TDCR,
348 		(tmp_value & ~(APIC_TDR_DIV_1 | APIC_TDR_DIV_TMBASE)) |
349 		APIC_TDR_DIV_16);
350 
351 	if (!oneshot)
352 		apic_write(APIC_TMICT, clocks / APIC_DIVISOR);
353 }
354 
355 /*
356  * Setup extended LVT, AMD specific
357  *
358  * Software should use the LVT offsets the BIOS provides.  The offsets
359  * are determined by the subsystems using it like those for MCE
360  * threshold or IBS.  On K8 only offset 0 (APIC500) and MCE interrupts
361  * are supported. Beginning with family 10h at least 4 offsets are
362  * available.
363  *
364  * Since the offsets must be consistent for all cores, we keep track
365  * of the LVT offsets in software and reserve the offset for the same
366  * vector also to be used on other cores. An offset is freed by
367  * setting the entry to APIC_EILVT_MASKED.
368  *
369  * If the BIOS is right, there should be no conflicts. Otherwise a
370  * "[Firmware Bug]: ..." error message is generated. However, if
371  * software does not properly determines the offsets, it is not
372  * necessarily a BIOS bug.
373  */
374 
375 static atomic_t eilvt_offsets[APIC_EILVT_NR_MAX];
376 
eilvt_entry_is_changeable(unsigned int old,unsigned int new)377 static inline int eilvt_entry_is_changeable(unsigned int old, unsigned int new)
378 {
379 	return (old & APIC_EILVT_MASKED)
380 		|| (new == APIC_EILVT_MASKED)
381 		|| ((new & ~APIC_EILVT_MASKED) == old);
382 }
383 
reserve_eilvt_offset(int offset,unsigned int new)384 static unsigned int reserve_eilvt_offset(int offset, unsigned int new)
385 {
386 	unsigned int rsvd;			/* 0: uninitialized */
387 
388 	if (offset >= APIC_EILVT_NR_MAX)
389 		return ~0;
390 
391 	rsvd = atomic_read(&eilvt_offsets[offset]) & ~APIC_EILVT_MASKED;
392 	do {
393 		if (rsvd &&
394 		    !eilvt_entry_is_changeable(rsvd, new))
395 			/* may not change if vectors are different */
396 			return rsvd;
397 		rsvd = atomic_cmpxchg(&eilvt_offsets[offset], rsvd, new);
398 	} while (rsvd != new);
399 
400 	return new;
401 }
402 
403 /*
404  * If mask=1, the LVT entry does not generate interrupts while mask=0
405  * enables the vector. See also the BKDGs. Must be called with
406  * preemption disabled.
407  */
408 
setup_APIC_eilvt(u8 offset,u8 vector,u8 msg_type,u8 mask)409 int setup_APIC_eilvt(u8 offset, u8 vector, u8 msg_type, u8 mask)
410 {
411 	unsigned long reg = APIC_EILVTn(offset);
412 	unsigned int new, old, reserved;
413 
414 	new = (mask << 16) | (msg_type << 8) | vector;
415 	old = apic_read(reg);
416 	reserved = reserve_eilvt_offset(offset, new);
417 
418 	if (reserved != new) {
419 		pr_err(FW_BUG "cpu %d, try to use APIC%lX (LVT offset %d) for "
420 		       "vector 0x%x, but the register is already in use for "
421 		       "vector 0x%x on another cpu\n",
422 		       smp_processor_id(), reg, offset, new, reserved);
423 		return -EINVAL;
424 	}
425 
426 	if (!eilvt_entry_is_changeable(old, new)) {
427 		pr_err(FW_BUG "cpu %d, try to use APIC%lX (LVT offset %d) for "
428 		       "vector 0x%x, but the register is already in use for "
429 		       "vector 0x%x on this cpu\n",
430 		       smp_processor_id(), reg, offset, new, old);
431 		return -EBUSY;
432 	}
433 
434 	apic_write(reg, new);
435 
436 	return 0;
437 }
438 EXPORT_SYMBOL_GPL(setup_APIC_eilvt);
439 
440 /*
441  * Program the next event, relative to now
442  */
lapic_next_event(unsigned long delta,struct clock_event_device * evt)443 static int lapic_next_event(unsigned long delta,
444 			    struct clock_event_device *evt)
445 {
446 	apic_write(APIC_TMICT, delta);
447 	return 0;
448 }
449 
450 /*
451  * Setup the lapic timer in periodic or oneshot mode
452  */
lapic_timer_setup(enum clock_event_mode mode,struct clock_event_device * evt)453 static void lapic_timer_setup(enum clock_event_mode mode,
454 			      struct clock_event_device *evt)
455 {
456 	unsigned long flags;
457 	unsigned int v;
458 
459 	/* Lapic used as dummy for broadcast ? */
460 	if (evt->features & CLOCK_EVT_FEAT_DUMMY)
461 		return;
462 
463 	local_irq_save(flags);
464 
465 	switch (mode) {
466 	case CLOCK_EVT_MODE_PERIODIC:
467 	case CLOCK_EVT_MODE_ONESHOT:
468 		__setup_APIC_LVTT(lapic_timer_frequency,
469 				  mode != CLOCK_EVT_MODE_PERIODIC, 1);
470 		break;
471 	case CLOCK_EVT_MODE_UNUSED:
472 	case CLOCK_EVT_MODE_SHUTDOWN:
473 		v = apic_read(APIC_LVTT);
474 		v |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
475 		apic_write(APIC_LVTT, v);
476 		apic_write(APIC_TMICT, 0);
477 		break;
478 	case CLOCK_EVT_MODE_RESUME:
479 		/* Nothing to do here */
480 		break;
481 	}
482 
483 	local_irq_restore(flags);
484 }
485 
486 /*
487  * Local APIC timer broadcast function
488  */
lapic_timer_broadcast(const struct cpumask * mask)489 static void lapic_timer_broadcast(const struct cpumask *mask)
490 {
491 #ifdef CONFIG_SMP
492 	apic->send_IPI_mask(mask, LOCAL_TIMER_VECTOR);
493 #endif
494 }
495 
496 
497 /*
498  * The local apic timer can be used for any function which is CPU local.
499  */
500 static struct clock_event_device lapic_clockevent = {
501 	.name		= "lapic",
502 	.features	= CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT
503 			| CLOCK_EVT_FEAT_C3STOP | CLOCK_EVT_FEAT_DUMMY,
504 	.shift		= 32,
505 	.set_mode	= lapic_timer_setup,
506 	.set_next_event	= lapic_next_event,
507 	.broadcast	= lapic_timer_broadcast,
508 	.rating		= 100,
509 	.irq		= -1,
510 };
511 static DEFINE_PER_CPU(struct clock_event_device, lapic_events);
512 
513 /*
514  * Setup the local APIC timer for this CPU. Copy the initialized values
515  * of the boot CPU and register the clock event in the framework.
516  */
setup_APIC_timer(void)517 static void __cpuinit setup_APIC_timer(void)
518 {
519 	struct clock_event_device *levt = &__get_cpu_var(lapic_events);
520 
521 	if (this_cpu_has(X86_FEATURE_ARAT)) {
522 		lapic_clockevent.features &= ~CLOCK_EVT_FEAT_C3STOP;
523 		/* Make LAPIC timer preferrable over percpu HPET */
524 		lapic_clockevent.rating = 150;
525 	}
526 
527 	memcpy(levt, &lapic_clockevent, sizeof(*levt));
528 	levt->cpumask = cpumask_of(smp_processor_id());
529 
530 	clockevents_register_device(levt);
531 }
532 
533 /*
534  * In this functions we calibrate APIC bus clocks to the external timer.
535  *
536  * We want to do the calibration only once since we want to have local timer
537  * irqs syncron. CPUs connected by the same APIC bus have the very same bus
538  * frequency.
539  *
540  * This was previously done by reading the PIT/HPET and waiting for a wrap
541  * around to find out, that a tick has elapsed. I have a box, where the PIT
542  * readout is broken, so it never gets out of the wait loop again. This was
543  * also reported by others.
544  *
545  * Monitoring the jiffies value is inaccurate and the clockevents
546  * infrastructure allows us to do a simple substitution of the interrupt
547  * handler.
548  *
549  * The calibration routine also uses the pm_timer when possible, as the PIT
550  * happens to run way too slow (factor 2.3 on my VAIO CoreDuo, which goes
551  * back to normal later in the boot process).
552  */
553 
554 #define LAPIC_CAL_LOOPS		(HZ/10)
555 
556 static __initdata int lapic_cal_loops = -1;
557 static __initdata long lapic_cal_t1, lapic_cal_t2;
558 static __initdata unsigned long long lapic_cal_tsc1, lapic_cal_tsc2;
559 static __initdata unsigned long lapic_cal_pm1, lapic_cal_pm2;
560 static __initdata unsigned long lapic_cal_j1, lapic_cal_j2;
561 
562 /*
563  * Temporary interrupt handler.
564  */
lapic_cal_handler(struct clock_event_device * dev)565 static void __init lapic_cal_handler(struct clock_event_device *dev)
566 {
567 	unsigned long long tsc = 0;
568 	long tapic = apic_read(APIC_TMCCT);
569 	unsigned long pm = acpi_pm_read_early();
570 
571 	if (cpu_has_tsc)
572 		rdtscll(tsc);
573 
574 	switch (lapic_cal_loops++) {
575 	case 0:
576 		lapic_cal_t1 = tapic;
577 		lapic_cal_tsc1 = tsc;
578 		lapic_cal_pm1 = pm;
579 		lapic_cal_j1 = jiffies;
580 		break;
581 
582 	case LAPIC_CAL_LOOPS:
583 		lapic_cal_t2 = tapic;
584 		lapic_cal_tsc2 = tsc;
585 		if (pm < lapic_cal_pm1)
586 			pm += ACPI_PM_OVRRUN;
587 		lapic_cal_pm2 = pm;
588 		lapic_cal_j2 = jiffies;
589 		break;
590 	}
591 }
592 
593 static int __init
calibrate_by_pmtimer(long deltapm,long * delta,long * deltatsc)594 calibrate_by_pmtimer(long deltapm, long *delta, long *deltatsc)
595 {
596 	const long pm_100ms = PMTMR_TICKS_PER_SEC / 10;
597 	const long pm_thresh = pm_100ms / 100;
598 	unsigned long mult;
599 	u64 res;
600 
601 #ifndef CONFIG_X86_PM_TIMER
602 	return -1;
603 #endif
604 
605 	apic_printk(APIC_VERBOSE, "... PM-Timer delta = %ld\n", deltapm);
606 
607 	/* Check, if the PM timer is available */
608 	if (!deltapm)
609 		return -1;
610 
611 	mult = clocksource_hz2mult(PMTMR_TICKS_PER_SEC, 22);
612 
613 	if (deltapm > (pm_100ms - pm_thresh) &&
614 	    deltapm < (pm_100ms + pm_thresh)) {
615 		apic_printk(APIC_VERBOSE, "... PM-Timer result ok\n");
616 		return 0;
617 	}
618 
619 	res = (((u64)deltapm) *  mult) >> 22;
620 	do_div(res, 1000000);
621 	pr_warning("APIC calibration not consistent "
622 		   "with PM-Timer: %ldms instead of 100ms\n",(long)res);
623 
624 	/* Correct the lapic counter value */
625 	res = (((u64)(*delta)) * pm_100ms);
626 	do_div(res, deltapm);
627 	pr_info("APIC delta adjusted to PM-Timer: "
628 		"%lu (%ld)\n", (unsigned long)res, *delta);
629 	*delta = (long)res;
630 
631 	/* Correct the tsc counter value */
632 	if (cpu_has_tsc) {
633 		res = (((u64)(*deltatsc)) * pm_100ms);
634 		do_div(res, deltapm);
635 		apic_printk(APIC_VERBOSE, "TSC delta adjusted to "
636 					  "PM-Timer: %lu (%ld)\n",
637 					(unsigned long)res, *deltatsc);
638 		*deltatsc = (long)res;
639 	}
640 
641 	return 0;
642 }
643 
calibrate_APIC_clock(void)644 static int __init calibrate_APIC_clock(void)
645 {
646 	struct clock_event_device *levt = &__get_cpu_var(lapic_events);
647 	void (*real_handler)(struct clock_event_device *dev);
648 	unsigned long deltaj;
649 	long delta, deltatsc;
650 	int pm_referenced = 0;
651 
652 	/**
653 	 * check if lapic timer has already been calibrated by platform
654 	 * specific routine, such as tsc calibration code. if so, we just fill
655 	 * in the clockevent structure and return.
656 	 */
657 
658 	if (lapic_timer_frequency) {
659 		apic_printk(APIC_VERBOSE, "lapic timer already calibrated %d\n",
660 				lapic_timer_frequency);
661 		lapic_clockevent.mult = div_sc(lapic_timer_frequency/APIC_DIVISOR,
662 					TICK_NSEC, lapic_clockevent.shift);
663 		lapic_clockevent.max_delta_ns =
664 			clockevent_delta2ns(0x7FFFFF, &lapic_clockevent);
665 		lapic_clockevent.min_delta_ns =
666 			clockevent_delta2ns(0xF, &lapic_clockevent);
667 		lapic_clockevent.features &= ~CLOCK_EVT_FEAT_DUMMY;
668 		return 0;
669 	}
670 
671 	local_irq_disable();
672 
673 	/* Replace the global interrupt handler */
674 	real_handler = global_clock_event->event_handler;
675 	global_clock_event->event_handler = lapic_cal_handler;
676 
677 	/*
678 	 * Setup the APIC counter to maximum. There is no way the lapic
679 	 * can underflow in the 100ms detection time frame
680 	 */
681 	__setup_APIC_LVTT(0xffffffff, 0, 0);
682 
683 	/* Let the interrupts run */
684 	local_irq_enable();
685 
686 	while (lapic_cal_loops <= LAPIC_CAL_LOOPS)
687 		cpu_relax();
688 
689 	local_irq_disable();
690 
691 	/* Restore the real event handler */
692 	global_clock_event->event_handler = real_handler;
693 
694 	/* Build delta t1-t2 as apic timer counts down */
695 	delta = lapic_cal_t1 - lapic_cal_t2;
696 	apic_printk(APIC_VERBOSE, "... lapic delta = %ld\n", delta);
697 
698 	deltatsc = (long)(lapic_cal_tsc2 - lapic_cal_tsc1);
699 
700 	/* we trust the PM based calibration if possible */
701 	pm_referenced = !calibrate_by_pmtimer(lapic_cal_pm2 - lapic_cal_pm1,
702 					&delta, &deltatsc);
703 
704 	/* Calculate the scaled math multiplication factor */
705 	lapic_clockevent.mult = div_sc(delta, TICK_NSEC * LAPIC_CAL_LOOPS,
706 				       lapic_clockevent.shift);
707 	lapic_clockevent.max_delta_ns =
708 		clockevent_delta2ns(0x7FFFFFFF, &lapic_clockevent);
709 	lapic_clockevent.min_delta_ns =
710 		clockevent_delta2ns(0xF, &lapic_clockevent);
711 
712 	lapic_timer_frequency = (delta * APIC_DIVISOR) / LAPIC_CAL_LOOPS;
713 
714 	apic_printk(APIC_VERBOSE, "..... delta %ld\n", delta);
715 	apic_printk(APIC_VERBOSE, "..... mult: %u\n", lapic_clockevent.mult);
716 	apic_printk(APIC_VERBOSE, "..... calibration result: %u\n",
717 		    lapic_timer_frequency);
718 
719 	if (cpu_has_tsc) {
720 		apic_printk(APIC_VERBOSE, "..... CPU clock speed is "
721 			    "%ld.%04ld MHz.\n",
722 			    (deltatsc / LAPIC_CAL_LOOPS) / (1000000 / HZ),
723 			    (deltatsc / LAPIC_CAL_LOOPS) % (1000000 / HZ));
724 	}
725 
726 	apic_printk(APIC_VERBOSE, "..... host bus clock speed is "
727 		    "%u.%04u MHz.\n",
728 		    lapic_timer_frequency / (1000000 / HZ),
729 		    lapic_timer_frequency % (1000000 / HZ));
730 
731 	/*
732 	 * Do a sanity check on the APIC calibration result
733 	 */
734 	if (lapic_timer_frequency < (1000000 / HZ)) {
735 		local_irq_enable();
736 		pr_warning("APIC frequency too slow, disabling apic timer\n");
737 		return -1;
738 	}
739 
740 	levt->features &= ~CLOCK_EVT_FEAT_DUMMY;
741 
742 	/*
743 	 * PM timer calibration failed or not turned on
744 	 * so lets try APIC timer based calibration
745 	 */
746 	if (!pm_referenced) {
747 		apic_printk(APIC_VERBOSE, "... verify APIC timer\n");
748 
749 		/*
750 		 * Setup the apic timer manually
751 		 */
752 		levt->event_handler = lapic_cal_handler;
753 		lapic_timer_setup(CLOCK_EVT_MODE_PERIODIC, levt);
754 		lapic_cal_loops = -1;
755 
756 		/* Let the interrupts run */
757 		local_irq_enable();
758 
759 		while (lapic_cal_loops <= LAPIC_CAL_LOOPS)
760 			cpu_relax();
761 
762 		/* Stop the lapic timer */
763 		lapic_timer_setup(CLOCK_EVT_MODE_SHUTDOWN, levt);
764 
765 		/* Jiffies delta */
766 		deltaj = lapic_cal_j2 - lapic_cal_j1;
767 		apic_printk(APIC_VERBOSE, "... jiffies delta = %lu\n", deltaj);
768 
769 		/* Check, if the jiffies result is consistent */
770 		if (deltaj >= LAPIC_CAL_LOOPS-2 && deltaj <= LAPIC_CAL_LOOPS+2)
771 			apic_printk(APIC_VERBOSE, "... jiffies result ok\n");
772 		else
773 			levt->features |= CLOCK_EVT_FEAT_DUMMY;
774 	} else
775 		local_irq_enable();
776 
777 	if (levt->features & CLOCK_EVT_FEAT_DUMMY) {
778 		pr_warning("APIC timer disabled due to verification failure\n");
779 			return -1;
780 	}
781 
782 	return 0;
783 }
784 
785 /*
786  * Setup the boot APIC
787  *
788  * Calibrate and verify the result.
789  */
setup_boot_APIC_clock(void)790 void __init setup_boot_APIC_clock(void)
791 {
792 	/*
793 	 * The local apic timer can be disabled via the kernel
794 	 * commandline or from the CPU detection code. Register the lapic
795 	 * timer as a dummy clock event source on SMP systems, so the
796 	 * broadcast mechanism is used. On UP systems simply ignore it.
797 	 */
798 	if (disable_apic_timer) {
799 		pr_info("Disabling APIC timer\n");
800 		/* No broadcast on UP ! */
801 		if (num_possible_cpus() > 1) {
802 			lapic_clockevent.mult = 1;
803 			setup_APIC_timer();
804 		}
805 		return;
806 	}
807 
808 	apic_printk(APIC_VERBOSE, "Using local APIC timer interrupts.\n"
809 		    "calibrating APIC timer ...\n");
810 
811 	if (calibrate_APIC_clock()) {
812 		/* No broadcast on UP ! */
813 		if (num_possible_cpus() > 1)
814 			setup_APIC_timer();
815 		return;
816 	}
817 
818 	/*
819 	 * If nmi_watchdog is set to IO_APIC, we need the
820 	 * PIT/HPET going.  Otherwise register lapic as a dummy
821 	 * device.
822 	 */
823 	lapic_clockevent.features &= ~CLOCK_EVT_FEAT_DUMMY;
824 
825 	/* Setup the lapic or request the broadcast */
826 	setup_APIC_timer();
827 }
828 
setup_secondary_APIC_clock(void)829 void __cpuinit setup_secondary_APIC_clock(void)
830 {
831 	setup_APIC_timer();
832 }
833 
834 /*
835  * The guts of the apic timer interrupt
836  */
local_apic_timer_interrupt(void)837 static void local_apic_timer_interrupt(void)
838 {
839 	int cpu = smp_processor_id();
840 	struct clock_event_device *evt = &per_cpu(lapic_events, cpu);
841 
842 	/*
843 	 * Normally we should not be here till LAPIC has been initialized but
844 	 * in some cases like kdump, its possible that there is a pending LAPIC
845 	 * timer interrupt from previous kernel's context and is delivered in
846 	 * new kernel the moment interrupts are enabled.
847 	 *
848 	 * Interrupts are enabled early and LAPIC is setup much later, hence
849 	 * its possible that when we get here evt->event_handler is NULL.
850 	 * Check for event_handler being NULL and discard the interrupt as
851 	 * spurious.
852 	 */
853 	if (!evt->event_handler) {
854 		pr_warning("Spurious LAPIC timer interrupt on cpu %d\n", cpu);
855 		/* Switch it off */
856 		lapic_timer_setup(CLOCK_EVT_MODE_SHUTDOWN, evt);
857 		return;
858 	}
859 
860 	/*
861 	 * the NMI deadlock-detector uses this.
862 	 */
863 	inc_irq_stat(apic_timer_irqs);
864 
865 	evt->event_handler(evt);
866 }
867 
868 /*
869  * Local APIC timer interrupt. This is the most natural way for doing
870  * local interrupts, but local timer interrupts can be emulated by
871  * broadcast interrupts too. [in case the hw doesn't support APIC timers]
872  *
873  * [ if a single-CPU system runs an SMP kernel then we call the local
874  *   interrupt as well. Thus we cannot inline the local irq ... ]
875  */
smp_apic_timer_interrupt(struct pt_regs * regs)876 void __irq_entry smp_apic_timer_interrupt(struct pt_regs *regs)
877 {
878 	struct pt_regs *old_regs = set_irq_regs(regs);
879 
880 	/*
881 	 * NOTE! We'd better ACK the irq immediately,
882 	 * because timer handling can be slow.
883 	 */
884 	ack_APIC_irq();
885 	/*
886 	 * update_process_times() expects us to have done irq_enter().
887 	 * Besides, if we don't timer interrupts ignore the global
888 	 * interrupt lock, which is the WrongThing (tm) to do.
889 	 */
890 	irq_enter();
891 	exit_idle();
892 	local_apic_timer_interrupt();
893 	irq_exit();
894 
895 	set_irq_regs(old_regs);
896 }
897 
setup_profiling_timer(unsigned int multiplier)898 int setup_profiling_timer(unsigned int multiplier)
899 {
900 	return -EINVAL;
901 }
902 
903 /*
904  * Local APIC start and shutdown
905  */
906 
907 /**
908  * clear_local_APIC - shutdown the local APIC
909  *
910  * This is called, when a CPU is disabled and before rebooting, so the state of
911  * the local APIC has no dangling leftovers. Also used to cleanout any BIOS
912  * leftovers during boot.
913  */
clear_local_APIC(void)914 void clear_local_APIC(void)
915 {
916 	int maxlvt;
917 	u32 v;
918 
919 	/* APIC hasn't been mapped yet */
920 	if (!x2apic_mode && !apic_phys)
921 		return;
922 
923 	maxlvt = lapic_get_maxlvt();
924 	/*
925 	 * Masking an LVT entry can trigger a local APIC error
926 	 * if the vector is zero. Mask LVTERR first to prevent this.
927 	 */
928 	if (maxlvt >= 3) {
929 		v = ERROR_APIC_VECTOR; /* any non-zero vector will do */
930 		apic_write(APIC_LVTERR, v | APIC_LVT_MASKED);
931 	}
932 	/*
933 	 * Careful: we have to set masks only first to deassert
934 	 * any level-triggered sources.
935 	 */
936 	v = apic_read(APIC_LVTT);
937 	apic_write(APIC_LVTT, v | APIC_LVT_MASKED);
938 	v = apic_read(APIC_LVT0);
939 	apic_write(APIC_LVT0, v | APIC_LVT_MASKED);
940 	v = apic_read(APIC_LVT1);
941 	apic_write(APIC_LVT1, v | APIC_LVT_MASKED);
942 	if (maxlvt >= 4) {
943 		v = apic_read(APIC_LVTPC);
944 		apic_write(APIC_LVTPC, v | APIC_LVT_MASKED);
945 	}
946 
947 	/* lets not touch this if we didn't frob it */
948 #ifdef CONFIG_X86_THERMAL_VECTOR
949 	if (maxlvt >= 5) {
950 		v = apic_read(APIC_LVTTHMR);
951 		apic_write(APIC_LVTTHMR, v | APIC_LVT_MASKED);
952 	}
953 #endif
954 #ifdef CONFIG_X86_MCE_INTEL
955 	if (maxlvt >= 6) {
956 		v = apic_read(APIC_LVTCMCI);
957 		if (!(v & APIC_LVT_MASKED))
958 			apic_write(APIC_LVTCMCI, v | APIC_LVT_MASKED);
959 	}
960 #endif
961 
962 	/*
963 	 * Clean APIC state for other OSs:
964 	 */
965 	apic_write(APIC_LVTT, APIC_LVT_MASKED);
966 	apic_write(APIC_LVT0, APIC_LVT_MASKED);
967 	apic_write(APIC_LVT1, APIC_LVT_MASKED);
968 	if (maxlvt >= 3)
969 		apic_write(APIC_LVTERR, APIC_LVT_MASKED);
970 	if (maxlvt >= 4)
971 		apic_write(APIC_LVTPC, APIC_LVT_MASKED);
972 
973 	/* Integrated APIC (!82489DX) ? */
974 	if (lapic_is_integrated()) {
975 		if (maxlvt > 3)
976 			/* Clear ESR due to Pentium errata 3AP and 11AP */
977 			apic_write(APIC_ESR, 0);
978 		apic_read(APIC_ESR);
979 	}
980 }
981 
982 /**
983  * disable_local_APIC - clear and disable the local APIC
984  */
disable_local_APIC(void)985 void disable_local_APIC(void)
986 {
987 	unsigned int value;
988 
989 	/* APIC hasn't been mapped yet */
990 	if (!x2apic_mode && !apic_phys)
991 		return;
992 
993 	clear_local_APIC();
994 
995 	/*
996 	 * Disable APIC (implies clearing of registers
997 	 * for 82489DX!).
998 	 */
999 	value = apic_read(APIC_SPIV);
1000 	value &= ~APIC_SPIV_APIC_ENABLED;
1001 	apic_write(APIC_SPIV, value);
1002 
1003 #ifdef CONFIG_X86_32
1004 	/*
1005 	 * When LAPIC was disabled by the BIOS and enabled by the kernel,
1006 	 * restore the disabled state.
1007 	 */
1008 	if (enabled_via_apicbase) {
1009 		unsigned int l, h;
1010 
1011 		rdmsr(MSR_IA32_APICBASE, l, h);
1012 		l &= ~MSR_IA32_APICBASE_ENABLE;
1013 		wrmsr(MSR_IA32_APICBASE, l, h);
1014 	}
1015 #endif
1016 }
1017 
1018 /*
1019  * If Linux enabled the LAPIC against the BIOS default disable it down before
1020  * re-entering the BIOS on shutdown.  Otherwise the BIOS may get confused and
1021  * not power-off.  Additionally clear all LVT entries before disable_local_APIC
1022  * for the case where Linux didn't enable the LAPIC.
1023  */
lapic_shutdown(void)1024 void lapic_shutdown(void)
1025 {
1026 	unsigned long flags;
1027 
1028 	if (!cpu_has_apic && !apic_from_smp_config())
1029 		return;
1030 
1031 	local_irq_save(flags);
1032 
1033 #ifdef CONFIG_X86_32
1034 	if (!enabled_via_apicbase)
1035 		clear_local_APIC();
1036 	else
1037 #endif
1038 		disable_local_APIC();
1039 
1040 
1041 	local_irq_restore(flags);
1042 }
1043 
1044 /*
1045  * This is to verify that we're looking at a real local APIC.
1046  * Check these against your board if the CPUs aren't getting
1047  * started for no apparent reason.
1048  */
verify_local_APIC(void)1049 int __init verify_local_APIC(void)
1050 {
1051 	unsigned int reg0, reg1;
1052 
1053 	/*
1054 	 * The version register is read-only in a real APIC.
1055 	 */
1056 	reg0 = apic_read(APIC_LVR);
1057 	apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg0);
1058 	apic_write(APIC_LVR, reg0 ^ APIC_LVR_MASK);
1059 	reg1 = apic_read(APIC_LVR);
1060 	apic_printk(APIC_DEBUG, "Getting VERSION: %x\n", reg1);
1061 
1062 	/*
1063 	 * The two version reads above should print the same
1064 	 * numbers.  If the second one is different, then we
1065 	 * poke at a non-APIC.
1066 	 */
1067 	if (reg1 != reg0)
1068 		return 0;
1069 
1070 	/*
1071 	 * Check if the version looks reasonably.
1072 	 */
1073 	reg1 = GET_APIC_VERSION(reg0);
1074 	if (reg1 == 0x00 || reg1 == 0xff)
1075 		return 0;
1076 	reg1 = lapic_get_maxlvt();
1077 	if (reg1 < 0x02 || reg1 == 0xff)
1078 		return 0;
1079 
1080 	/*
1081 	 * The ID register is read/write in a real APIC.
1082 	 */
1083 	reg0 = apic_read(APIC_ID);
1084 	apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg0);
1085 	apic_write(APIC_ID, reg0 ^ apic->apic_id_mask);
1086 	reg1 = apic_read(APIC_ID);
1087 	apic_printk(APIC_DEBUG, "Getting ID: %x\n", reg1);
1088 	apic_write(APIC_ID, reg0);
1089 	if (reg1 != (reg0 ^ apic->apic_id_mask))
1090 		return 0;
1091 
1092 	/*
1093 	 * The next two are just to see if we have sane values.
1094 	 * They're only really relevant if we're in Virtual Wire
1095 	 * compatibility mode, but most boxes are anymore.
1096 	 */
1097 	reg0 = apic_read(APIC_LVT0);
1098 	apic_printk(APIC_DEBUG, "Getting LVT0: %x\n", reg0);
1099 	reg1 = apic_read(APIC_LVT1);
1100 	apic_printk(APIC_DEBUG, "Getting LVT1: %x\n", reg1);
1101 
1102 	return 1;
1103 }
1104 
1105 /**
1106  * sync_Arb_IDs - synchronize APIC bus arbitration IDs
1107  */
sync_Arb_IDs(void)1108 void __init sync_Arb_IDs(void)
1109 {
1110 	/*
1111 	 * Unsupported on P4 - see Intel Dev. Manual Vol. 3, Ch. 8.6.1 And not
1112 	 * needed on AMD.
1113 	 */
1114 	if (modern_apic() || boot_cpu_data.x86_vendor == X86_VENDOR_AMD)
1115 		return;
1116 
1117 	/*
1118 	 * Wait for idle.
1119 	 */
1120 	apic_wait_icr_idle();
1121 
1122 	apic_printk(APIC_DEBUG, "Synchronizing Arb IDs.\n");
1123 	apic_write(APIC_ICR, APIC_DEST_ALLINC |
1124 			APIC_INT_LEVELTRIG | APIC_DM_INIT);
1125 }
1126 
1127 /*
1128  * An initial setup of the virtual wire mode.
1129  */
init_bsp_APIC(void)1130 void __init init_bsp_APIC(void)
1131 {
1132 	unsigned int value;
1133 
1134 	/*
1135 	 * Don't do the setup now if we have a SMP BIOS as the
1136 	 * through-I/O-APIC virtual wire mode might be active.
1137 	 */
1138 	if (smp_found_config || !cpu_has_apic)
1139 		return;
1140 
1141 	/*
1142 	 * Do not trust the local APIC being empty at bootup.
1143 	 */
1144 	clear_local_APIC();
1145 
1146 	/*
1147 	 * Enable APIC.
1148 	 */
1149 	value = apic_read(APIC_SPIV);
1150 	value &= ~APIC_VECTOR_MASK;
1151 	value |= APIC_SPIV_APIC_ENABLED;
1152 
1153 #ifdef CONFIG_X86_32
1154 	/* This bit is reserved on P4/Xeon and should be cleared */
1155 	if ((boot_cpu_data.x86_vendor == X86_VENDOR_INTEL) &&
1156 	    (boot_cpu_data.x86 == 15))
1157 		value &= ~APIC_SPIV_FOCUS_DISABLED;
1158 	else
1159 #endif
1160 		value |= APIC_SPIV_FOCUS_DISABLED;
1161 	value |= SPURIOUS_APIC_VECTOR;
1162 	apic_write(APIC_SPIV, value);
1163 
1164 	/*
1165 	 * Set up the virtual wire mode.
1166 	 */
1167 	apic_write(APIC_LVT0, APIC_DM_EXTINT);
1168 	value = APIC_DM_NMI;
1169 	if (!lapic_is_integrated())		/* 82489DX */
1170 		value |= APIC_LVT_LEVEL_TRIGGER;
1171 	apic_write(APIC_LVT1, value);
1172 }
1173 
lapic_setup_esr(void)1174 static void __cpuinit lapic_setup_esr(void)
1175 {
1176 	unsigned int oldvalue, value, maxlvt;
1177 
1178 	if (!lapic_is_integrated()) {
1179 		pr_info("No ESR for 82489DX.\n");
1180 		return;
1181 	}
1182 
1183 	if (apic->disable_esr) {
1184 		/*
1185 		 * Something untraceable is creating bad interrupts on
1186 		 * secondary quads ... for the moment, just leave the
1187 		 * ESR disabled - we can't do anything useful with the
1188 		 * errors anyway - mbligh
1189 		 */
1190 		pr_info("Leaving ESR disabled.\n");
1191 		return;
1192 	}
1193 
1194 	maxlvt = lapic_get_maxlvt();
1195 	if (maxlvt > 3)		/* Due to the Pentium erratum 3AP. */
1196 		apic_write(APIC_ESR, 0);
1197 	oldvalue = apic_read(APIC_ESR);
1198 
1199 	/* enables sending errors */
1200 	value = ERROR_APIC_VECTOR;
1201 	apic_write(APIC_LVTERR, value);
1202 
1203 	/*
1204 	 * spec says clear errors after enabling vector.
1205 	 */
1206 	if (maxlvt > 3)
1207 		apic_write(APIC_ESR, 0);
1208 	value = apic_read(APIC_ESR);
1209 	if (value != oldvalue)
1210 		apic_printk(APIC_VERBOSE, "ESR value before enabling "
1211 			"vector: 0x%08x  after: 0x%08x\n",
1212 			oldvalue, value);
1213 }
1214 
1215 /**
1216  * setup_local_APIC - setup the local APIC
1217  *
1218  * Used to setup local APIC while initializing BSP or bringin up APs.
1219  * Always called with preemption disabled.
1220  */
setup_local_APIC(void)1221 void __cpuinit setup_local_APIC(void)
1222 {
1223 	int cpu = smp_processor_id();
1224 	unsigned int value, queued;
1225 	int i, j, acked = 0;
1226 	unsigned long long tsc = 0, ntsc;
1227 	long long max_loops = cpu_khz;
1228 
1229 	if (cpu_has_tsc)
1230 		rdtscll(tsc);
1231 
1232 	if (disable_apic) {
1233 		disable_ioapic_support();
1234 		return;
1235 	}
1236 
1237 #ifdef CONFIG_X86_32
1238 	/* Pound the ESR really hard over the head with a big hammer - mbligh */
1239 	if (lapic_is_integrated() && apic->disable_esr) {
1240 		apic_write(APIC_ESR, 0);
1241 		apic_write(APIC_ESR, 0);
1242 		apic_write(APIC_ESR, 0);
1243 		apic_write(APIC_ESR, 0);
1244 	}
1245 #endif
1246 	perf_events_lapic_init();
1247 
1248 	/*
1249 	 * Double-check whether this APIC is really registered.
1250 	 * This is meaningless in clustered apic mode, so we skip it.
1251 	 */
1252 	BUG_ON(!apic->apic_id_registered());
1253 
1254 	/*
1255 	 * Intel recommends to set DFR, LDR and TPR before enabling
1256 	 * an APIC.  See e.g. "AP-388 82489DX User's Manual" (Intel
1257 	 * document number 292116).  So here it goes...
1258 	 */
1259 	apic->init_apic_ldr();
1260 
1261 #ifdef CONFIG_X86_32
1262 	/*
1263 	 * APIC LDR is initialized.  If logical_apicid mapping was
1264 	 * initialized during get_smp_config(), make sure it matches the
1265 	 * actual value.
1266 	 */
1267 	i = early_per_cpu(x86_cpu_to_logical_apicid, cpu);
1268 	WARN_ON(i != BAD_APICID && i != logical_smp_processor_id());
1269 	/* always use the value from LDR */
1270 	early_per_cpu(x86_cpu_to_logical_apicid, cpu) =
1271 		logical_smp_processor_id();
1272 
1273 	/*
1274 	 * Some NUMA implementations (NUMAQ) don't initialize apicid to
1275 	 * node mapping during NUMA init.  Now that logical apicid is
1276 	 * guaranteed to be known, give it another chance.  This is already
1277 	 * a bit too late - percpu allocation has already happened without
1278 	 * proper NUMA affinity.
1279 	 */
1280 	if (apic->x86_32_numa_cpu_node)
1281 		set_apicid_to_node(early_per_cpu(x86_cpu_to_apicid, cpu),
1282 				   apic->x86_32_numa_cpu_node(cpu));
1283 #endif
1284 
1285 	/*
1286 	 * Set Task Priority to 'accept all'. We never change this
1287 	 * later on.
1288 	 */
1289 	value = apic_read(APIC_TASKPRI);
1290 	value &= ~APIC_TPRI_MASK;
1291 	apic_write(APIC_TASKPRI, value);
1292 
1293 	/*
1294 	 * After a crash, we no longer service the interrupts and a pending
1295 	 * interrupt from previous kernel might still have ISR bit set.
1296 	 *
1297 	 * Most probably by now CPU has serviced that pending interrupt and
1298 	 * it might not have done the ack_APIC_irq() because it thought,
1299 	 * interrupt came from i8259 as ExtInt. LAPIC did not get EOI so it
1300 	 * does not clear the ISR bit and cpu thinks it has already serivced
1301 	 * the interrupt. Hence a vector might get locked. It was noticed
1302 	 * for timer irq (vector 0x31). Issue an extra EOI to clear ISR.
1303 	 */
1304 	do {
1305 		queued = 0;
1306 		for (i = APIC_ISR_NR - 1; i >= 0; i--)
1307 			queued |= apic_read(APIC_IRR + i*0x10);
1308 
1309 		for (i = APIC_ISR_NR - 1; i >= 0; i--) {
1310 			value = apic_read(APIC_ISR + i*0x10);
1311 			for (j = 31; j >= 0; j--) {
1312 				if (value & (1<<j)) {
1313 					ack_APIC_irq();
1314 					acked++;
1315 				}
1316 			}
1317 		}
1318 		if (acked > 256) {
1319 			printk(KERN_ERR "LAPIC pending interrupts after %d EOI\n",
1320 			       acked);
1321 			break;
1322 		}
1323 		if (cpu_has_tsc) {
1324 			rdtscll(ntsc);
1325 			max_loops = (cpu_khz << 10) - (ntsc - tsc);
1326 		} else
1327 			max_loops--;
1328 	} while (queued && max_loops > 0);
1329 	WARN_ON(max_loops <= 0);
1330 
1331 	/*
1332 	 * Now that we are all set up, enable the APIC
1333 	 */
1334 	value = apic_read(APIC_SPIV);
1335 	value &= ~APIC_VECTOR_MASK;
1336 	/*
1337 	 * Enable APIC
1338 	 */
1339 	value |= APIC_SPIV_APIC_ENABLED;
1340 
1341 #ifdef CONFIG_X86_32
1342 	/*
1343 	 * Some unknown Intel IO/APIC (or APIC) errata is biting us with
1344 	 * certain networking cards. If high frequency interrupts are
1345 	 * happening on a particular IOAPIC pin, plus the IOAPIC routing
1346 	 * entry is masked/unmasked at a high rate as well then sooner or
1347 	 * later IOAPIC line gets 'stuck', no more interrupts are received
1348 	 * from the device. If focus CPU is disabled then the hang goes
1349 	 * away, oh well :-(
1350 	 *
1351 	 * [ This bug can be reproduced easily with a level-triggered
1352 	 *   PCI Ne2000 networking cards and PII/PIII processors, dual
1353 	 *   BX chipset. ]
1354 	 */
1355 	/*
1356 	 * Actually disabling the focus CPU check just makes the hang less
1357 	 * frequent as it makes the interrupt distributon model be more
1358 	 * like LRU than MRU (the short-term load is more even across CPUs).
1359 	 * See also the comment in end_level_ioapic_irq().  --macro
1360 	 */
1361 
1362 	/*
1363 	 * - enable focus processor (bit==0)
1364 	 * - 64bit mode always use processor focus
1365 	 *   so no need to set it
1366 	 */
1367 	value &= ~APIC_SPIV_FOCUS_DISABLED;
1368 #endif
1369 
1370 	/*
1371 	 * Set spurious IRQ vector
1372 	 */
1373 	value |= SPURIOUS_APIC_VECTOR;
1374 	apic_write(APIC_SPIV, value);
1375 
1376 	/*
1377 	 * Set up LVT0, LVT1:
1378 	 *
1379 	 * set up through-local-APIC on the BP's LINT0. This is not
1380 	 * strictly necessary in pure symmetric-IO mode, but sometimes
1381 	 * we delegate interrupts to the 8259A.
1382 	 */
1383 	/*
1384 	 * TODO: set up through-local-APIC from through-I/O-APIC? --macro
1385 	 */
1386 	value = apic_read(APIC_LVT0) & APIC_LVT_MASKED;
1387 	if (!cpu && (pic_mode || !value)) {
1388 		value = APIC_DM_EXTINT;
1389 		apic_printk(APIC_VERBOSE, "enabled ExtINT on CPU#%d\n", cpu);
1390 	} else {
1391 		value = APIC_DM_EXTINT | APIC_LVT_MASKED;
1392 		apic_printk(APIC_VERBOSE, "masked ExtINT on CPU#%d\n", cpu);
1393 	}
1394 	apic_write(APIC_LVT0, value);
1395 
1396 	/*
1397 	 * only the BP should see the LINT1 NMI signal, obviously.
1398 	 */
1399 	if (!cpu)
1400 		value = APIC_DM_NMI;
1401 	else
1402 		value = APIC_DM_NMI | APIC_LVT_MASKED;
1403 	if (!lapic_is_integrated())		/* 82489DX */
1404 		value |= APIC_LVT_LEVEL_TRIGGER;
1405 	apic_write(APIC_LVT1, value);
1406 
1407 #ifdef CONFIG_X86_MCE_INTEL
1408 	/* Recheck CMCI information after local APIC is up on CPU #0 */
1409 	if (!cpu)
1410 		cmci_recheck();
1411 #endif
1412 }
1413 
end_local_APIC_setup(void)1414 void __cpuinit end_local_APIC_setup(void)
1415 {
1416 	lapic_setup_esr();
1417 
1418 #ifdef CONFIG_X86_32
1419 	{
1420 		unsigned int value;
1421 		/* Disable the local apic timer */
1422 		value = apic_read(APIC_LVTT);
1423 		value |= (APIC_LVT_MASKED | LOCAL_TIMER_VECTOR);
1424 		apic_write(APIC_LVTT, value);
1425 	}
1426 #endif
1427 
1428 	apic_pm_activate();
1429 }
1430 
bsp_end_local_APIC_setup(void)1431 void __init bsp_end_local_APIC_setup(void)
1432 {
1433 	end_local_APIC_setup();
1434 
1435 	/*
1436 	 * Now that local APIC setup is completed for BP, configure the fault
1437 	 * handling for interrupt remapping.
1438 	 */
1439 	if (intr_remapping_enabled)
1440 		enable_drhd_fault_handling();
1441 
1442 }
1443 
1444 #ifdef CONFIG_X86_X2APIC
1445 /*
1446  * Need to disable xapic and x2apic at the same time and then enable xapic mode
1447  */
__disable_x2apic(u64 msr)1448 static inline void __disable_x2apic(u64 msr)
1449 {
1450 	wrmsrl(MSR_IA32_APICBASE,
1451 	       msr & ~(X2APIC_ENABLE | XAPIC_ENABLE));
1452 	wrmsrl(MSR_IA32_APICBASE, msr & ~X2APIC_ENABLE);
1453 }
1454 
disable_x2apic(void)1455 static __init void disable_x2apic(void)
1456 {
1457 	u64 msr;
1458 
1459 	if (!cpu_has_x2apic)
1460 		return;
1461 
1462 	rdmsrl(MSR_IA32_APICBASE, msr);
1463 	if (msr & X2APIC_ENABLE) {
1464 		u32 x2apic_id = read_apic_id();
1465 
1466 		if (x2apic_id >= 255)
1467 			panic("Cannot disable x2apic, id: %08x\n", x2apic_id);
1468 
1469 		pr_info("Disabling x2apic\n");
1470 		__disable_x2apic(msr);
1471 
1472 		if (nox2apic) {
1473 			clear_cpu_cap(&cpu_data(0), X86_FEATURE_X2APIC);
1474 			setup_clear_cpu_cap(X86_FEATURE_X2APIC);
1475 		}
1476 
1477 		x2apic_disabled = 1;
1478 		x2apic_mode = 0;
1479 
1480 		register_lapic_address(mp_lapic_addr);
1481 	}
1482 }
1483 
check_x2apic(void)1484 void check_x2apic(void)
1485 {
1486 	if (x2apic_enabled()) {
1487 		pr_info("x2apic enabled by BIOS, switching to x2apic ops\n");
1488 		x2apic_preenabled = x2apic_mode = 1;
1489 	}
1490 }
1491 
enable_x2apic(void)1492 void enable_x2apic(void)
1493 {
1494 	u64 msr;
1495 
1496 	rdmsrl(MSR_IA32_APICBASE, msr);
1497 	if (x2apic_disabled) {
1498 		__disable_x2apic(msr);
1499 		return;
1500 	}
1501 
1502 	if (!x2apic_mode)
1503 		return;
1504 
1505 	if (!(msr & X2APIC_ENABLE)) {
1506 		printk_once(KERN_INFO "Enabling x2apic\n");
1507 		wrmsrl(MSR_IA32_APICBASE, msr | X2APIC_ENABLE);
1508 	}
1509 }
1510 #endif /* CONFIG_X86_X2APIC */
1511 
enable_IR(void)1512 int __init enable_IR(void)
1513 {
1514 #ifdef CONFIG_IRQ_REMAP
1515 	if (!intr_remapping_supported()) {
1516 		pr_debug("intr-remapping not supported\n");
1517 		return -1;
1518 	}
1519 
1520 	if (!x2apic_preenabled && skip_ioapic_setup) {
1521 		pr_info("Skipped enabling intr-remap because of skipping "
1522 			"io-apic setup\n");
1523 		return -1;
1524 	}
1525 
1526 	return enable_intr_remapping();
1527 #endif
1528 	return -1;
1529 }
1530 
enable_IR_x2apic(void)1531 void __init enable_IR_x2apic(void)
1532 {
1533 	unsigned long flags;
1534 	int ret, x2apic_enabled = 0;
1535 	int dmar_table_init_ret;
1536 
1537 	dmar_table_init_ret = dmar_table_init();
1538 	if (dmar_table_init_ret && !x2apic_supported())
1539 		return;
1540 
1541 	ret = save_ioapic_entries();
1542 	if (ret) {
1543 		pr_info("Saving IO-APIC state failed: %d\n", ret);
1544 		return;
1545 	}
1546 
1547 	local_irq_save(flags);
1548 	legacy_pic->mask_all();
1549 	mask_ioapic_entries();
1550 
1551 	if (x2apic_preenabled && nox2apic)
1552 		disable_x2apic();
1553 
1554 	if (dmar_table_init_ret)
1555 		ret = -1;
1556 	else
1557 		ret = enable_IR();
1558 
1559 	if (!x2apic_supported())
1560 		goto skip_x2apic;
1561 
1562 	if (ret < 0) {
1563 		/* IR is required if there is APIC ID > 255 even when running
1564 		 * under KVM
1565 		 */
1566 		if (max_physical_apicid > 255 ||
1567 		    !hypervisor_x2apic_available()) {
1568 			if (x2apic_preenabled)
1569 				disable_x2apic();
1570 			goto skip_x2apic;
1571 		}
1572 		/*
1573 		 * without IR all CPUs can be addressed by IOAPIC/MSI
1574 		 * only in physical mode
1575 		 */
1576 		x2apic_force_phys();
1577 	}
1578 
1579 	if (ret == IRQ_REMAP_XAPIC_MODE) {
1580 		pr_info("x2apic not enabled, IRQ remapping is in xapic mode\n");
1581 		goto skip_x2apic;
1582 	}
1583 
1584 	x2apic_enabled = 1;
1585 
1586 	if (x2apic_supported() && !x2apic_mode) {
1587 		x2apic_mode = 1;
1588 		enable_x2apic();
1589 		pr_info("Enabled x2apic\n");
1590 	}
1591 
1592 skip_x2apic:
1593 	if (ret < 0) /* IR enabling failed */
1594 		restore_ioapic_entries();
1595 	legacy_pic->restore_mask();
1596 	local_irq_restore(flags);
1597 }
1598 
1599 #ifdef CONFIG_X86_64
1600 /*
1601  * Detect and enable local APICs on non-SMP boards.
1602  * Original code written by Keir Fraser.
1603  * On AMD64 we trust the BIOS - if it says no APIC it is likely
1604  * not correctly set up (usually the APIC timer won't work etc.)
1605  */
detect_init_APIC(void)1606 static int __init detect_init_APIC(void)
1607 {
1608 	if (!cpu_has_apic) {
1609 		pr_info("No local APIC present\n");
1610 		return -1;
1611 	}
1612 
1613 	mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
1614 	return 0;
1615 }
1616 #else
1617 
apic_verify(void)1618 static int __init apic_verify(void)
1619 {
1620 	u32 features, h, l;
1621 
1622 	/*
1623 	 * The APIC feature bit should now be enabled
1624 	 * in `cpuid'
1625 	 */
1626 	features = cpuid_edx(1);
1627 	if (!(features & (1 << X86_FEATURE_APIC))) {
1628 		pr_warning("Could not enable APIC!\n");
1629 		return -1;
1630 	}
1631 	set_cpu_cap(&boot_cpu_data, X86_FEATURE_APIC);
1632 	mp_lapic_addr = APIC_DEFAULT_PHYS_BASE;
1633 
1634 	/* The BIOS may have set up the APIC at some other address */
1635 	rdmsr(MSR_IA32_APICBASE, l, h);
1636 	if (l & MSR_IA32_APICBASE_ENABLE)
1637 		mp_lapic_addr = l & MSR_IA32_APICBASE_BASE;
1638 
1639 	pr_info("Found and enabled local APIC!\n");
1640 	return 0;
1641 }
1642 
apic_force_enable(unsigned long addr)1643 int __init apic_force_enable(unsigned long addr)
1644 {
1645 	u32 h, l;
1646 
1647 	if (disable_apic)
1648 		return -1;
1649 
1650 	/*
1651 	 * Some BIOSes disable the local APIC in the APIC_BASE
1652 	 * MSR. This can only be done in software for Intel P6 or later
1653 	 * and AMD K7 (Model > 1) or later.
1654 	 */
1655 	rdmsr(MSR_IA32_APICBASE, l, h);
1656 	if (!(l & MSR_IA32_APICBASE_ENABLE)) {
1657 		pr_info("Local APIC disabled by BIOS -- reenabling.\n");
1658 		l &= ~MSR_IA32_APICBASE_BASE;
1659 		l |= MSR_IA32_APICBASE_ENABLE | addr;
1660 		wrmsr(MSR_IA32_APICBASE, l, h);
1661 		enabled_via_apicbase = 1;
1662 	}
1663 	return apic_verify();
1664 }
1665 
1666 /*
1667  * Detect and initialize APIC
1668  */
detect_init_APIC(void)1669 static int __init detect_init_APIC(void)
1670 {
1671 	/* Disabled by kernel option? */
1672 	if (disable_apic)
1673 		return -1;
1674 
1675 	switch (boot_cpu_data.x86_vendor) {
1676 	case X86_VENDOR_AMD:
1677 		if ((boot_cpu_data.x86 == 6 && boot_cpu_data.x86_model > 1) ||
1678 		    (boot_cpu_data.x86 >= 15))
1679 			break;
1680 		goto no_apic;
1681 	case X86_VENDOR_INTEL:
1682 		if (boot_cpu_data.x86 == 6 || boot_cpu_data.x86 == 15 ||
1683 		    (boot_cpu_data.x86 == 5 && cpu_has_apic))
1684 			break;
1685 		goto no_apic;
1686 	default:
1687 		goto no_apic;
1688 	}
1689 
1690 	if (!cpu_has_apic) {
1691 		/*
1692 		 * Over-ride BIOS and try to enable the local APIC only if
1693 		 * "lapic" specified.
1694 		 */
1695 		if (!force_enable_local_apic) {
1696 			pr_info("Local APIC disabled by BIOS -- "
1697 				"you can enable it with \"lapic\"\n");
1698 			return -1;
1699 		}
1700 		if (apic_force_enable(APIC_DEFAULT_PHYS_BASE))
1701 			return -1;
1702 	} else {
1703 		if (apic_verify())
1704 			return -1;
1705 	}
1706 
1707 	apic_pm_activate();
1708 
1709 	return 0;
1710 
1711 no_apic:
1712 	pr_info("No local APIC present or hardware disabled\n");
1713 	return -1;
1714 }
1715 #endif
1716 
1717 /**
1718  * init_apic_mappings - initialize APIC mappings
1719  */
init_apic_mappings(void)1720 void __init init_apic_mappings(void)
1721 {
1722 	unsigned int new_apicid;
1723 
1724 	if (x2apic_mode) {
1725 		boot_cpu_physical_apicid = read_apic_id();
1726 		return;
1727 	}
1728 
1729 	/* If no local APIC can be found return early */
1730 	if (!smp_found_config && detect_init_APIC()) {
1731 		/* lets NOP'ify apic operations */
1732 		pr_info("APIC: disable apic facility\n");
1733 		apic_disable();
1734 	} else {
1735 		apic_phys = mp_lapic_addr;
1736 
1737 		/*
1738 		 * acpi lapic path already maps that address in
1739 		 * acpi_register_lapic_address()
1740 		 */
1741 		if (!acpi_lapic && !smp_found_config)
1742 			register_lapic_address(apic_phys);
1743 	}
1744 
1745 	/*
1746 	 * Fetch the APIC ID of the BSP in case we have a
1747 	 * default configuration (or the MP table is broken).
1748 	 */
1749 	new_apicid = read_apic_id();
1750 	if (boot_cpu_physical_apicid != new_apicid) {
1751 		boot_cpu_physical_apicid = new_apicid;
1752 		/*
1753 		 * yeah -- we lie about apic_version
1754 		 * in case if apic was disabled via boot option
1755 		 * but it's not a problem for SMP compiled kernel
1756 		 * since smp_sanity_check is prepared for such a case
1757 		 * and disable smp mode
1758 		 */
1759 		apic_version[new_apicid] =
1760 			 GET_APIC_VERSION(apic_read(APIC_LVR));
1761 	}
1762 }
1763 
register_lapic_address(unsigned long address)1764 void __init register_lapic_address(unsigned long address)
1765 {
1766 	mp_lapic_addr = address;
1767 
1768 	if (!x2apic_mode) {
1769 		set_fixmap_nocache(FIX_APIC_BASE, address);
1770 		apic_printk(APIC_VERBOSE, "mapped APIC to %16lx (%16lx)\n",
1771 			    APIC_BASE, mp_lapic_addr);
1772 	}
1773 	if (boot_cpu_physical_apicid == -1U) {
1774 		boot_cpu_physical_apicid  = read_apic_id();
1775 		apic_version[boot_cpu_physical_apicid] =
1776 			 GET_APIC_VERSION(apic_read(APIC_LVR));
1777 	}
1778 }
1779 
1780 /*
1781  * This initializes the IO-APIC and APIC hardware if this is
1782  * a UP kernel.
1783  */
1784 int apic_version[MAX_LOCAL_APIC];
1785 
APIC_init_uniprocessor(void)1786 int __init APIC_init_uniprocessor(void)
1787 {
1788 	if (disable_apic) {
1789 		pr_info("Apic disabled\n");
1790 		return -1;
1791 	}
1792 #ifdef CONFIG_X86_64
1793 	if (!cpu_has_apic) {
1794 		disable_apic = 1;
1795 		pr_info("Apic disabled by BIOS\n");
1796 		return -1;
1797 	}
1798 #else
1799 	if (!smp_found_config && !cpu_has_apic)
1800 		return -1;
1801 
1802 	/*
1803 	 * Complain if the BIOS pretends there is one.
1804 	 */
1805 	if (!cpu_has_apic &&
1806 	    APIC_INTEGRATED(apic_version[boot_cpu_physical_apicid])) {
1807 		pr_err("BIOS bug, local APIC 0x%x not detected!...\n",
1808 			boot_cpu_physical_apicid);
1809 		return -1;
1810 	}
1811 #endif
1812 
1813 	default_setup_apic_routing();
1814 
1815 	verify_local_APIC();
1816 	connect_bsp_APIC();
1817 
1818 #ifdef CONFIG_X86_64
1819 	apic_write(APIC_ID, SET_APIC_ID(boot_cpu_physical_apicid));
1820 #else
1821 	/*
1822 	 * Hack: In case of kdump, after a crash, kernel might be booting
1823 	 * on a cpu with non-zero lapic id. But boot_cpu_physical_apicid
1824 	 * might be zero if read from MP tables. Get it from LAPIC.
1825 	 */
1826 # ifdef CONFIG_CRASH_DUMP
1827 	boot_cpu_physical_apicid = read_apic_id();
1828 # endif
1829 #endif
1830 	physid_set_mask_of_physid(boot_cpu_physical_apicid, &phys_cpu_present_map);
1831 	setup_local_APIC();
1832 
1833 #ifdef CONFIG_X86_IO_APIC
1834 	/*
1835 	 * Now enable IO-APICs, actually call clear_IO_APIC
1836 	 * We need clear_IO_APIC before enabling error vector
1837 	 */
1838 	if (!skip_ioapic_setup && nr_ioapics)
1839 		enable_IO_APIC();
1840 #endif
1841 
1842 	bsp_end_local_APIC_setup();
1843 
1844 #ifdef CONFIG_X86_IO_APIC
1845 	if (smp_found_config && !skip_ioapic_setup && nr_ioapics)
1846 		setup_IO_APIC();
1847 	else {
1848 		nr_ioapics = 0;
1849 	}
1850 #endif
1851 
1852 	x86_init.timers.setup_percpu_clockev();
1853 	return 0;
1854 }
1855 
1856 /*
1857  * Local APIC interrupts
1858  */
1859 
1860 /*
1861  * This interrupt should _never_ happen with our APIC/SMP architecture
1862  */
smp_spurious_interrupt(struct pt_regs * regs)1863 void smp_spurious_interrupt(struct pt_regs *regs)
1864 {
1865 	u32 v;
1866 
1867 	irq_enter();
1868 	exit_idle();
1869 	/*
1870 	 * Check if this really is a spurious interrupt and ACK it
1871 	 * if it is a vectored one.  Just in case...
1872 	 * Spurious interrupts should not be ACKed.
1873 	 */
1874 	v = apic_read(APIC_ISR + ((SPURIOUS_APIC_VECTOR & ~0x1f) >> 1));
1875 	if (v & (1 << (SPURIOUS_APIC_VECTOR & 0x1f)))
1876 		ack_APIC_irq();
1877 
1878 	inc_irq_stat(irq_spurious_count);
1879 
1880 	/* see sw-dev-man vol 3, chapter 7.4.13.5 */
1881 	pr_info("spurious APIC interrupt on CPU#%d, "
1882 		"should never happen.\n", smp_processor_id());
1883 	irq_exit();
1884 }
1885 
1886 /*
1887  * This interrupt should never happen with our APIC/SMP architecture
1888  */
smp_error_interrupt(struct pt_regs * regs)1889 void smp_error_interrupt(struct pt_regs *regs)
1890 {
1891 	u32 v0, v1;
1892 	u32 i = 0;
1893 	static const char * const error_interrupt_reason[] = {
1894 		"Send CS error",		/* APIC Error Bit 0 */
1895 		"Receive CS error",		/* APIC Error Bit 1 */
1896 		"Send accept error",		/* APIC Error Bit 2 */
1897 		"Receive accept error",		/* APIC Error Bit 3 */
1898 		"Redirectable IPI",		/* APIC Error Bit 4 */
1899 		"Send illegal vector",		/* APIC Error Bit 5 */
1900 		"Received illegal vector",	/* APIC Error Bit 6 */
1901 		"Illegal register address",	/* APIC Error Bit 7 */
1902 	};
1903 
1904 	irq_enter();
1905 	exit_idle();
1906 	/* First tickle the hardware, only then report what went on. -- REW */
1907 	v0 = apic_read(APIC_ESR);
1908 	apic_write(APIC_ESR, 0);
1909 	v1 = apic_read(APIC_ESR);
1910 	ack_APIC_irq();
1911 	atomic_inc(&irq_err_count);
1912 
1913 	apic_printk(APIC_DEBUG, KERN_DEBUG "APIC error on CPU%d: %02x(%02x)",
1914 		    smp_processor_id(), v0 , v1);
1915 
1916 	v1 = v1 & 0xff;
1917 	while (v1) {
1918 		if (v1 & 0x1)
1919 			apic_printk(APIC_DEBUG, KERN_CONT " : %s", error_interrupt_reason[i]);
1920 		i++;
1921 		v1 >>= 1;
1922 	};
1923 
1924 	apic_printk(APIC_DEBUG, KERN_CONT "\n");
1925 
1926 	irq_exit();
1927 }
1928 
1929 /**
1930  * connect_bsp_APIC - attach the APIC to the interrupt system
1931  */
connect_bsp_APIC(void)1932 void __init connect_bsp_APIC(void)
1933 {
1934 #ifdef CONFIG_X86_32
1935 	if (pic_mode) {
1936 		/*
1937 		 * Do not trust the local APIC being empty at bootup.
1938 		 */
1939 		clear_local_APIC();
1940 		/*
1941 		 * PIC mode, enable APIC mode in the IMCR, i.e.  connect BSP's
1942 		 * local APIC to INT and NMI lines.
1943 		 */
1944 		apic_printk(APIC_VERBOSE, "leaving PIC mode, "
1945 				"enabling APIC mode.\n");
1946 		imcr_pic_to_apic();
1947 	}
1948 #endif
1949 	if (apic->enable_apic_mode)
1950 		apic->enable_apic_mode();
1951 }
1952 
1953 /**
1954  * disconnect_bsp_APIC - detach the APIC from the interrupt system
1955  * @virt_wire_setup:	indicates, whether virtual wire mode is selected
1956  *
1957  * Virtual wire mode is necessary to deliver legacy interrupts even when the
1958  * APIC is disabled.
1959  */
disconnect_bsp_APIC(int virt_wire_setup)1960 void disconnect_bsp_APIC(int virt_wire_setup)
1961 {
1962 	unsigned int value;
1963 
1964 #ifdef CONFIG_X86_32
1965 	if (pic_mode) {
1966 		/*
1967 		 * Put the board back into PIC mode (has an effect only on
1968 		 * certain older boards).  Note that APIC interrupts, including
1969 		 * IPIs, won't work beyond this point!  The only exception are
1970 		 * INIT IPIs.
1971 		 */
1972 		apic_printk(APIC_VERBOSE, "disabling APIC mode, "
1973 				"entering PIC mode.\n");
1974 		imcr_apic_to_pic();
1975 		return;
1976 	}
1977 #endif
1978 
1979 	/* Go back to Virtual Wire compatibility mode */
1980 
1981 	/* For the spurious interrupt use vector F, and enable it */
1982 	value = apic_read(APIC_SPIV);
1983 	value &= ~APIC_VECTOR_MASK;
1984 	value |= APIC_SPIV_APIC_ENABLED;
1985 	value |= 0xf;
1986 	apic_write(APIC_SPIV, value);
1987 
1988 	if (!virt_wire_setup) {
1989 		/*
1990 		 * For LVT0 make it edge triggered, active high,
1991 		 * external and enabled
1992 		 */
1993 		value = apic_read(APIC_LVT0);
1994 		value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
1995 			APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
1996 			APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
1997 		value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
1998 		value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_EXTINT);
1999 		apic_write(APIC_LVT0, value);
2000 	} else {
2001 		/* Disable LVT0 */
2002 		apic_write(APIC_LVT0, APIC_LVT_MASKED);
2003 	}
2004 
2005 	/*
2006 	 * For LVT1 make it edge triggered, active high,
2007 	 * nmi and enabled
2008 	 */
2009 	value = apic_read(APIC_LVT1);
2010 	value &= ~(APIC_MODE_MASK | APIC_SEND_PENDING |
2011 			APIC_INPUT_POLARITY | APIC_LVT_REMOTE_IRR |
2012 			APIC_LVT_LEVEL_TRIGGER | APIC_LVT_MASKED);
2013 	value |= APIC_LVT_REMOTE_IRR | APIC_SEND_PENDING;
2014 	value = SET_APIC_DELIVERY_MODE(value, APIC_MODE_NMI);
2015 	apic_write(APIC_LVT1, value);
2016 }
2017 
generic_processor_info(int apicid,int version)2018 void __cpuinit generic_processor_info(int apicid, int version)
2019 {
2020 	int cpu, max = nr_cpu_ids;
2021 	bool boot_cpu_detected = physid_isset(boot_cpu_physical_apicid,
2022 				phys_cpu_present_map);
2023 
2024 	/*
2025 	 * If boot cpu has not been detected yet, then only allow upto
2026 	 * nr_cpu_ids - 1 processors and keep one slot free for boot cpu
2027 	 */
2028 	if (!boot_cpu_detected && num_processors >= nr_cpu_ids - 1 &&
2029 	    apicid != boot_cpu_physical_apicid) {
2030 		int thiscpu = max + disabled_cpus - 1;
2031 
2032 		pr_warning(
2033 			"ACPI: NR_CPUS/possible_cpus limit of %i almost"
2034 			" reached. Keeping one slot for boot cpu."
2035 			"  Processor %d/0x%x ignored.\n", max, thiscpu, apicid);
2036 
2037 		disabled_cpus++;
2038 		return;
2039 	}
2040 
2041 	if (num_processors >= nr_cpu_ids) {
2042 		int thiscpu = max + disabled_cpus;
2043 
2044 		pr_warning(
2045 			"ACPI: NR_CPUS/possible_cpus limit of %i reached."
2046 			"  Processor %d/0x%x ignored.\n", max, thiscpu, apicid);
2047 
2048 		disabled_cpus++;
2049 		return;
2050 	}
2051 
2052 	num_processors++;
2053 	if (apicid == boot_cpu_physical_apicid) {
2054 		/*
2055 		 * x86_bios_cpu_apicid is required to have processors listed
2056 		 * in same order as logical cpu numbers. Hence the first
2057 		 * entry is BSP, and so on.
2058 		 * boot_cpu_init() already hold bit 0 in cpu_present_mask
2059 		 * for BSP.
2060 		 */
2061 		cpu = 0;
2062 	} else
2063 		cpu = cpumask_next_zero(-1, cpu_present_mask);
2064 
2065 	/*
2066 	 * Validate version
2067 	 */
2068 	if (version == 0x0) {
2069 		pr_warning("BIOS bug: APIC version is 0 for CPU %d/0x%x, fixing up to 0x10\n",
2070 			   cpu, apicid);
2071 		version = 0x10;
2072 	}
2073 	apic_version[apicid] = version;
2074 
2075 	if (version != apic_version[boot_cpu_physical_apicid]) {
2076 		pr_warning("BIOS bug: APIC version mismatch, boot CPU: %x, CPU %d: version %x\n",
2077 			apic_version[boot_cpu_physical_apicid], cpu, version);
2078 	}
2079 
2080 	physid_set(apicid, phys_cpu_present_map);
2081 	if (apicid > max_physical_apicid)
2082 		max_physical_apicid = apicid;
2083 
2084 #if defined(CONFIG_SMP) || defined(CONFIG_X86_64)
2085 	early_per_cpu(x86_cpu_to_apicid, cpu) = apicid;
2086 	early_per_cpu(x86_bios_cpu_apicid, cpu) = apicid;
2087 #endif
2088 #ifdef CONFIG_X86_32
2089 	early_per_cpu(x86_cpu_to_logical_apicid, cpu) =
2090 		apic->x86_32_early_logical_apicid(cpu);
2091 #endif
2092 	set_cpu_possible(cpu, true);
2093 	set_cpu_present(cpu, true);
2094 }
2095 
hard_smp_processor_id(void)2096 int hard_smp_processor_id(void)
2097 {
2098 	return read_apic_id();
2099 }
2100 
default_init_apic_ldr(void)2101 void default_init_apic_ldr(void)
2102 {
2103 	unsigned long val;
2104 
2105 	apic_write(APIC_DFR, APIC_DFR_VALUE);
2106 	val = apic_read(APIC_LDR) & ~APIC_LDR_MASK;
2107 	val |= SET_APIC_LOGICAL_ID(1UL << smp_processor_id());
2108 	apic_write(APIC_LDR, val);
2109 }
2110 
2111 /*
2112  * Power management
2113  */
2114 #ifdef CONFIG_PM
2115 
2116 static struct {
2117 	/*
2118 	 * 'active' is true if the local APIC was enabled by us and
2119 	 * not the BIOS; this signifies that we are also responsible
2120 	 * for disabling it before entering apm/acpi suspend
2121 	 */
2122 	int active;
2123 	/* r/w apic fields */
2124 	unsigned int apic_id;
2125 	unsigned int apic_taskpri;
2126 	unsigned int apic_ldr;
2127 	unsigned int apic_dfr;
2128 	unsigned int apic_spiv;
2129 	unsigned int apic_lvtt;
2130 	unsigned int apic_lvtpc;
2131 	unsigned int apic_lvt0;
2132 	unsigned int apic_lvt1;
2133 	unsigned int apic_lvterr;
2134 	unsigned int apic_tmict;
2135 	unsigned int apic_tdcr;
2136 	unsigned int apic_thmr;
2137 } apic_pm_state;
2138 
lapic_suspend(void)2139 static int lapic_suspend(void)
2140 {
2141 	unsigned long flags;
2142 	int maxlvt;
2143 
2144 	if (!apic_pm_state.active)
2145 		return 0;
2146 
2147 	maxlvt = lapic_get_maxlvt();
2148 
2149 	apic_pm_state.apic_id = apic_read(APIC_ID);
2150 	apic_pm_state.apic_taskpri = apic_read(APIC_TASKPRI);
2151 	apic_pm_state.apic_ldr = apic_read(APIC_LDR);
2152 	apic_pm_state.apic_dfr = apic_read(APIC_DFR);
2153 	apic_pm_state.apic_spiv = apic_read(APIC_SPIV);
2154 	apic_pm_state.apic_lvtt = apic_read(APIC_LVTT);
2155 	if (maxlvt >= 4)
2156 		apic_pm_state.apic_lvtpc = apic_read(APIC_LVTPC);
2157 	apic_pm_state.apic_lvt0 = apic_read(APIC_LVT0);
2158 	apic_pm_state.apic_lvt1 = apic_read(APIC_LVT1);
2159 	apic_pm_state.apic_lvterr = apic_read(APIC_LVTERR);
2160 	apic_pm_state.apic_tmict = apic_read(APIC_TMICT);
2161 	apic_pm_state.apic_tdcr = apic_read(APIC_TDCR);
2162 #ifdef CONFIG_X86_THERMAL_VECTOR
2163 	if (maxlvt >= 5)
2164 		apic_pm_state.apic_thmr = apic_read(APIC_LVTTHMR);
2165 #endif
2166 
2167 	local_irq_save(flags);
2168 	disable_local_APIC();
2169 
2170 	if (intr_remapping_enabled)
2171 		disable_intr_remapping();
2172 
2173 	local_irq_restore(flags);
2174 	return 0;
2175 }
2176 
lapic_resume(void)2177 static void lapic_resume(void)
2178 {
2179 	unsigned int l, h;
2180 	unsigned long flags;
2181 	int maxlvt;
2182 
2183 	if (!apic_pm_state.active)
2184 		return;
2185 
2186 	local_irq_save(flags);
2187 	if (intr_remapping_enabled) {
2188 		/*
2189 		 * IO-APIC and PIC have their own resume routines.
2190 		 * We just mask them here to make sure the interrupt
2191 		 * subsystem is completely quiet while we enable x2apic
2192 		 * and interrupt-remapping.
2193 		 */
2194 		mask_ioapic_entries();
2195 		legacy_pic->mask_all();
2196 	}
2197 
2198 	if (x2apic_mode)
2199 		enable_x2apic();
2200 	else {
2201 		/*
2202 		 * Make sure the APICBASE points to the right address
2203 		 *
2204 		 * FIXME! This will be wrong if we ever support suspend on
2205 		 * SMP! We'll need to do this as part of the CPU restore!
2206 		 */
2207 		rdmsr(MSR_IA32_APICBASE, l, h);
2208 		l &= ~MSR_IA32_APICBASE_BASE;
2209 		l |= MSR_IA32_APICBASE_ENABLE | mp_lapic_addr;
2210 		wrmsr(MSR_IA32_APICBASE, l, h);
2211 	}
2212 
2213 	maxlvt = lapic_get_maxlvt();
2214 	apic_write(APIC_LVTERR, ERROR_APIC_VECTOR | APIC_LVT_MASKED);
2215 	apic_write(APIC_ID, apic_pm_state.apic_id);
2216 	apic_write(APIC_DFR, apic_pm_state.apic_dfr);
2217 	apic_write(APIC_LDR, apic_pm_state.apic_ldr);
2218 	apic_write(APIC_TASKPRI, apic_pm_state.apic_taskpri);
2219 	apic_write(APIC_SPIV, apic_pm_state.apic_spiv);
2220 	apic_write(APIC_LVT0, apic_pm_state.apic_lvt0);
2221 	apic_write(APIC_LVT1, apic_pm_state.apic_lvt1);
2222 #if defined(CONFIG_X86_MCE_P4THERMAL) || defined(CONFIG_X86_MCE_INTEL)
2223 	if (maxlvt >= 5)
2224 		apic_write(APIC_LVTTHMR, apic_pm_state.apic_thmr);
2225 #endif
2226 	if (maxlvt >= 4)
2227 		apic_write(APIC_LVTPC, apic_pm_state.apic_lvtpc);
2228 	apic_write(APIC_LVTT, apic_pm_state.apic_lvtt);
2229 	apic_write(APIC_TDCR, apic_pm_state.apic_tdcr);
2230 	apic_write(APIC_TMICT, apic_pm_state.apic_tmict);
2231 	apic_write(APIC_ESR, 0);
2232 	apic_read(APIC_ESR);
2233 	apic_write(APIC_LVTERR, apic_pm_state.apic_lvterr);
2234 	apic_write(APIC_ESR, 0);
2235 	apic_read(APIC_ESR);
2236 
2237 	if (intr_remapping_enabled)
2238 		reenable_intr_remapping(x2apic_mode);
2239 
2240 	local_irq_restore(flags);
2241 }
2242 
2243 /*
2244  * This device has no shutdown method - fully functioning local APICs
2245  * are needed on every CPU up until machine_halt/restart/poweroff.
2246  */
2247 
2248 static struct syscore_ops lapic_syscore_ops = {
2249 	.resume		= lapic_resume,
2250 	.suspend	= lapic_suspend,
2251 };
2252 
apic_pm_activate(void)2253 static void __cpuinit apic_pm_activate(void)
2254 {
2255 	apic_pm_state.active = 1;
2256 }
2257 
init_lapic_sysfs(void)2258 static int __init init_lapic_sysfs(void)
2259 {
2260 	/* XXX: remove suspend/resume procs if !apic_pm_state.active? */
2261 	if (cpu_has_apic)
2262 		register_syscore_ops(&lapic_syscore_ops);
2263 
2264 	return 0;
2265 }
2266 
2267 /* local apic needs to resume before other devices access its registers. */
2268 core_initcall(init_lapic_sysfs);
2269 
2270 #else	/* CONFIG_PM */
2271 
apic_pm_activate(void)2272 static void apic_pm_activate(void) { }
2273 
2274 #endif	/* CONFIG_PM */
2275 
2276 #ifdef CONFIG_X86_64
2277 
apic_cluster_num(void)2278 static int __cpuinit apic_cluster_num(void)
2279 {
2280 	int i, clusters, zeros;
2281 	unsigned id;
2282 	u16 *bios_cpu_apicid;
2283 	DECLARE_BITMAP(clustermap, NUM_APIC_CLUSTERS);
2284 
2285 	bios_cpu_apicid = early_per_cpu_ptr(x86_bios_cpu_apicid);
2286 	bitmap_zero(clustermap, NUM_APIC_CLUSTERS);
2287 
2288 	for (i = 0; i < nr_cpu_ids; i++) {
2289 		/* are we being called early in kernel startup? */
2290 		if (bios_cpu_apicid) {
2291 			id = bios_cpu_apicid[i];
2292 		} else if (i < nr_cpu_ids) {
2293 			if (cpu_present(i))
2294 				id = per_cpu(x86_bios_cpu_apicid, i);
2295 			else
2296 				continue;
2297 		} else
2298 			break;
2299 
2300 		if (id != BAD_APICID)
2301 			__set_bit(APIC_CLUSTERID(id), clustermap);
2302 	}
2303 
2304 	/* Problem:  Partially populated chassis may not have CPUs in some of
2305 	 * the APIC clusters they have been allocated.  Only present CPUs have
2306 	 * x86_bios_cpu_apicid entries, thus causing zeroes in the bitmap.
2307 	 * Since clusters are allocated sequentially, count zeros only if
2308 	 * they are bounded by ones.
2309 	 */
2310 	clusters = 0;
2311 	zeros = 0;
2312 	for (i = 0; i < NUM_APIC_CLUSTERS; i++) {
2313 		if (test_bit(i, clustermap)) {
2314 			clusters += 1 + zeros;
2315 			zeros = 0;
2316 		} else
2317 			++zeros;
2318 	}
2319 
2320 	return clusters;
2321 }
2322 
2323 static int __cpuinitdata multi_checked;
2324 static int __cpuinitdata multi;
2325 
set_multi(const struct dmi_system_id * d)2326 static int __cpuinit set_multi(const struct dmi_system_id *d)
2327 {
2328 	if (multi)
2329 		return 0;
2330 	pr_info("APIC: %s detected, Multi Chassis\n", d->ident);
2331 	multi = 1;
2332 	return 0;
2333 }
2334 
2335 static const __cpuinitconst struct dmi_system_id multi_dmi_table[] = {
2336 	{
2337 		.callback = set_multi,
2338 		.ident = "IBM System Summit2",
2339 		.matches = {
2340 			DMI_MATCH(DMI_SYS_VENDOR, "IBM"),
2341 			DMI_MATCH(DMI_PRODUCT_NAME, "Summit2"),
2342 		},
2343 	},
2344 	{}
2345 };
2346 
dmi_check_multi(void)2347 static void __cpuinit dmi_check_multi(void)
2348 {
2349 	if (multi_checked)
2350 		return;
2351 
2352 	dmi_check_system(multi_dmi_table);
2353 	multi_checked = 1;
2354 }
2355 
2356 /*
2357  * apic_is_clustered_box() -- Check if we can expect good TSC
2358  *
2359  * Thus far, the major user of this is IBM's Summit2 series:
2360  * Clustered boxes may have unsynced TSC problems if they are
2361  * multi-chassis.
2362  * Use DMI to check them
2363  */
apic_is_clustered_box(void)2364 __cpuinit int apic_is_clustered_box(void)
2365 {
2366 	dmi_check_multi();
2367 	if (multi)
2368 		return 1;
2369 
2370 	if (!is_vsmp_box())
2371 		return 0;
2372 
2373 	/*
2374 	 * ScaleMP vSMPowered boxes have one cluster per board and TSCs are
2375 	 * not guaranteed to be synced between boards
2376 	 */
2377 	if (apic_cluster_num() > 1)
2378 		return 1;
2379 
2380 	return 0;
2381 }
2382 #endif
2383 
2384 /*
2385  * APIC command line parameters
2386  */
setup_disableapic(char * arg)2387 static int __init setup_disableapic(char *arg)
2388 {
2389 	disable_apic = 1;
2390 	setup_clear_cpu_cap(X86_FEATURE_APIC);
2391 	return 0;
2392 }
2393 early_param("disableapic", setup_disableapic);
2394 
2395 /* same as disableapic, for compatibility */
setup_nolapic(char * arg)2396 static int __init setup_nolapic(char *arg)
2397 {
2398 	return setup_disableapic(arg);
2399 }
2400 early_param("nolapic", setup_nolapic);
2401 
parse_lapic_timer_c2_ok(char * arg)2402 static int __init parse_lapic_timer_c2_ok(char *arg)
2403 {
2404 	local_apic_timer_c2_ok = 1;
2405 	return 0;
2406 }
2407 early_param("lapic_timer_c2_ok", parse_lapic_timer_c2_ok);
2408 
parse_disable_apic_timer(char * arg)2409 static int __init parse_disable_apic_timer(char *arg)
2410 {
2411 	disable_apic_timer = 1;
2412 	return 0;
2413 }
2414 early_param("noapictimer", parse_disable_apic_timer);
2415 
parse_nolapic_timer(char * arg)2416 static int __init parse_nolapic_timer(char *arg)
2417 {
2418 	disable_apic_timer = 1;
2419 	return 0;
2420 }
2421 early_param("nolapic_timer", parse_nolapic_timer);
2422 
apic_set_verbosity(char * arg)2423 static int __init apic_set_verbosity(char *arg)
2424 {
2425 	if (!arg)  {
2426 #ifdef CONFIG_X86_64
2427 		skip_ioapic_setup = 0;
2428 		return 0;
2429 #endif
2430 		return -EINVAL;
2431 	}
2432 
2433 	if (strcmp("debug", arg) == 0)
2434 		apic_verbosity = APIC_DEBUG;
2435 	else if (strcmp("verbose", arg) == 0)
2436 		apic_verbosity = APIC_VERBOSE;
2437 	else {
2438 		pr_warning("APIC Verbosity level %s not recognised"
2439 			" use apic=verbose or apic=debug\n", arg);
2440 		return -EINVAL;
2441 	}
2442 
2443 	return 0;
2444 }
2445 early_param("apic", apic_set_verbosity);
2446 
lapic_insert_resource(void)2447 static int __init lapic_insert_resource(void)
2448 {
2449 	if (!apic_phys)
2450 		return -1;
2451 
2452 	/* Put local APIC into the resource map. */
2453 	lapic_resource.start = apic_phys;
2454 	lapic_resource.end = lapic_resource.start + PAGE_SIZE - 1;
2455 	insert_resource(&iomem_resource, &lapic_resource);
2456 
2457 	return 0;
2458 }
2459 
2460 /*
2461  * need call insert after e820_reserve_resources()
2462  * that is using request_resource
2463  */
2464 late_initcall(lapic_insert_resource);
2465