xref: /freebsd/sys/x86/x86/local_apic.c (revision cf59dabe161f956ac7d36fbb91b7edeab9d0f6c3)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1996, by Steve Passe
5  * All rights reserved.
6  * Copyright (c) 2003 John Baldwin <jhb@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. The name of the developer may NOT be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  * 3. Neither the name of the author nor the names of any co-contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  * Local APIC support on Pentium and later processors.
34  */
35 
36 #include <sys/cdefs.h>
37 #include "opt_atpic.h"
38 
39 #include "opt_ddb.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/asan.h>
44 #include <sys/bus.h>
45 #include <sys/kernel.h>
46 #include <sys/lock.h>
47 #include <sys/malloc.h>
48 #include <sys/msan.h>
49 #include <sys/mutex.h>
50 #include <sys/pcpu.h>
51 #include <sys/proc.h>
52 #include <sys/refcount.h>
53 #include <sys/sched.h>
54 #include <sys/smp.h>
55 #include <sys/sysctl.h>
56 #include <sys/timeet.h>
57 #include <sys/timetc.h>
58 
59 #include <vm/vm.h>
60 #include <vm/pmap.h>
61 
62 #include <x86/apicreg.h>
63 #include <machine/clock.h>
64 #include <machine/cpufunc.h>
65 #include <machine/cputypes.h>
66 #include <machine/fpu.h>
67 #include <machine/frame.h>
68 #include <machine/intr_machdep.h>
69 #include <x86/apicvar.h>
70 #include <x86/mca.h>
71 #include <machine/md_var.h>
72 #include <machine/smp.h>
73 #include <machine/specialreg.h>
74 #include <x86/init.h>
75 
76 #ifdef DDB
77 #include <sys/interrupt.h>
78 #include <ddb/ddb.h>
79 #endif
80 
81 #ifdef __amd64__
82 #define	SDT_APIC	SDT_SYSIGT
83 #define	GSEL_APIC	0
84 #else
85 #define	SDT_APIC	SDT_SYS386IGT
86 #define	GSEL_APIC	GSEL(GCODE_SEL, SEL_KPL)
87 #endif
88 
89 static MALLOC_DEFINE(M_LAPIC, "local_apic", "Local APIC items");
90 
91 /* Sanity checks on IDT vectors. */
92 CTASSERT(APIC_IO_INTS + APIC_NUM_IOINTS == APIC_TIMER_INT);
93 CTASSERT(APIC_TIMER_INT < APIC_LOCAL_INTS);
94 CTASSERT(APIC_LOCAL_INTS == 240);
95 CTASSERT(IPI_STOP < APIC_SPURIOUS_INT);
96 
97 /*
98  * I/O interrupts use non-negative IRQ values.  These values are used
99  * to mark unused IDT entries or IDT entries reserved for a non-I/O
100  * interrupt.
101  */
102 #define	IRQ_FREE	-1
103 #define	IRQ_TIMER	-2
104 #define	IRQ_SYSCALL	-3
105 #define	IRQ_DTRACE_RET	-4
106 #define	IRQ_EVTCHN	-5
107 
108 enum lat_timer_mode {
109 	LAT_MODE_UNDEF =	0,
110 	LAT_MODE_PERIODIC =	1,
111 	LAT_MODE_ONESHOT =	2,
112 	LAT_MODE_DEADLINE =	3,
113 };
114 
115 /*
116  * Support for local APICs.  Local APICs manage interrupts on each
117  * individual processor as opposed to I/O APICs which receive interrupts
118  * from I/O devices and then forward them on to the local APICs.
119  *
120  * Local APICs can also send interrupts to each other thus providing the
121  * mechanism for IPIs.
122  */
123 
124 struct lvt {
125 	u_int lvt_edgetrigger:1;
126 	u_int lvt_activehi:1;
127 	u_int lvt_masked:1;
128 	u_int lvt_active:1;
129 	u_int lvt_mode:16;
130 	u_int lvt_vector:8;
131 };
132 
133 struct lapic {
134 	struct lvt la_lvts[APIC_LVT_MAX + 1];
135 	struct lvt la_elvts[APIC_ELVT_MAX + 1];
136 	u_int la_id:8;
137 	u_int la_cluster:4;
138 	u_int la_cluster_id:2;
139 	u_int la_present:1;
140 	u_long *la_timer_count;
141 	uint64_t la_timer_period;
142 	enum lat_timer_mode la_timer_mode;
143 	uint32_t lvt_timer_base;
144 	uint32_t lvt_timer_last;
145 	/* Include IDT_SYSCALL to make indexing easier. */
146 	int la_ioint_irqs[APIC_NUM_IOINTS + 1];
147 } static *lapics;
148 
149 /* Global defaults for local APIC LVT entries. */
150 static struct lvt lvts[APIC_LVT_MAX + 1] = {
151 	{ 1, 1, 1, 1, APIC_LVT_DM_EXTINT, 0 },	/* LINT0: masked ExtINT */
152 	{ 1, 1, 0, 1, APIC_LVT_DM_NMI, 0 },	/* LINT1: NMI */
153 	{ 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_TIMER_INT },	/* Timer */
154 	{ 1, 1, 0, 1, APIC_LVT_DM_FIXED, APIC_ERROR_INT },	/* Error */
155 	{ 1, 1, 1, 1, APIC_LVT_DM_NMI, 0 },	/* PMC */
156 	{ 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_THERMAL_INT },	/* Thermal */
157 	{ 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_CMC_INT },	/* CMCI */
158 };
159 
160 /* Global defaults for AMD local APIC ELVT entries. */
161 static struct lvt elvts[APIC_ELVT_MAX + 1] = {
162 	{ 1, 1, 1, 0, APIC_LVT_DM_FIXED, 0 },
163 	{ 1, 1, 1, 0, APIC_LVT_DM_FIXED, APIC_CMC_INT },
164 	{ 1, 1, 1, 0, APIC_LVT_DM_FIXED, 0 },
165 	{ 1, 1, 1, 0, APIC_LVT_DM_FIXED, 0 },
166 };
167 
168 static inthand_t *ioint_handlers[] = {
169 	NULL,			/* 0 - 31 */
170 	IDTVEC(apic_isr1),	/* 32 - 63 */
171 	IDTVEC(apic_isr2),	/* 64 - 95 */
172 	IDTVEC(apic_isr3),	/* 96 - 127 */
173 	IDTVEC(apic_isr4),	/* 128 - 159 */
174 	IDTVEC(apic_isr5),	/* 160 - 191 */
175 	IDTVEC(apic_isr6),	/* 192 - 223 */
176 	IDTVEC(apic_isr7),	/* 224 - 255 */
177 };
178 
179 static inthand_t *ioint_pti_handlers[] = {
180 	NULL,			/* 0 - 31 */
181 	IDTVEC(apic_isr1_pti),	/* 32 - 63 */
182 	IDTVEC(apic_isr2_pti),	/* 64 - 95 */
183 	IDTVEC(apic_isr3_pti),	/* 96 - 127 */
184 	IDTVEC(apic_isr4_pti),	/* 128 - 159 */
185 	IDTVEC(apic_isr5_pti),	/* 160 - 191 */
186 	IDTVEC(apic_isr6_pti),	/* 192 - 223 */
187 	IDTVEC(apic_isr7_pti),	/* 224 - 255 */
188 };
189 
190 static u_int32_t lapic_timer_divisors[] = {
191 	APIC_TDCR_1, APIC_TDCR_2, APIC_TDCR_4, APIC_TDCR_8, APIC_TDCR_16,
192 	APIC_TDCR_32, APIC_TDCR_64, APIC_TDCR_128
193 };
194 
195 extern inthand_t IDTVEC(rsvd_pti), IDTVEC(rsvd);
196 
197 volatile char *lapic_map;
198 vm_paddr_t lapic_paddr = DEFAULT_APIC_BASE;
199 int x2apic_mode;
200 int lapic_eoi_suppression;
201 static int lapic_timer_tsc_deadline;
202 static u_long lapic_timer_divisor, count_freq;
203 static struct eventtimer lapic_et;
204 #ifdef SMP
205 static uint64_t lapic_ipi_wait_mult;
206 static int __read_mostly lapic_ds_idle_timeout = 1000000;
207 #endif
208 unsigned int max_apic_id;
209 static int pcint_refcnt = 0;
210 
211 SYSCTL_NODE(_hw, OID_AUTO, apic, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
212     "APIC options");
213 SYSCTL_INT(_hw_apic, OID_AUTO, x2apic_mode, CTLFLAG_RD, &x2apic_mode, 0, "");
214 SYSCTL_INT(_hw_apic, OID_AUTO, eoi_suppression, CTLFLAG_RD,
215     &lapic_eoi_suppression, 0, "");
216 SYSCTL_INT(_hw_apic, OID_AUTO, timer_tsc_deadline, CTLFLAG_RD,
217     &lapic_timer_tsc_deadline, 0, "");
218 #ifdef SMP
219 SYSCTL_INT(_hw_apic, OID_AUTO, ds_idle_timeout, CTLFLAG_RWTUN,
220     &lapic_ds_idle_timeout, 0,
221     "timeout (in us) for APIC Delivery Status to become Idle (xAPIC only)");
222 #endif
223 
224 static void lapic_calibrate_initcount(struct lapic *la);
225 
226 /*
227  * Use __nosanitizethread to exempt the LAPIC I/O accessors from KCSan
228  * instrumentation.  Otherwise, if x2APIC is not available, use of the global
229  * lapic_map will generate a KCSan false positive.  While the mapping is
230  * shared among all CPUs, the physical access will always take place on the
231  * local CPU's APIC, so there isn't in fact a race here.  Furthermore, the
232  * KCSan warning printf can cause a panic if issued during LAPIC access,
233  * due to attempted recursive use of event timer resources.
234  */
235 
236 static uint32_t __nosanitizethread
lapic_read32(enum LAPIC_REGISTERS reg)237 lapic_read32(enum LAPIC_REGISTERS reg)
238 {
239 	uint32_t res;
240 
241 	if (x2apic_mode) {
242 		res = rdmsr32(MSR_APIC_000 + reg);
243 	} else {
244 		res = *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL);
245 	}
246 	return (res);
247 }
248 
249 static void __nosanitizethread
lapic_write32(enum LAPIC_REGISTERS reg,uint32_t val)250 lapic_write32(enum LAPIC_REGISTERS reg, uint32_t val)
251 {
252 
253 	if (x2apic_mode) {
254 		mfence();
255 		lfence();
256 		wrmsr(MSR_APIC_000 + reg, val);
257 	} else {
258 		*(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL) = val;
259 	}
260 }
261 
262 static void __nosanitizethread
lapic_write32_nofence(enum LAPIC_REGISTERS reg,uint32_t val)263 lapic_write32_nofence(enum LAPIC_REGISTERS reg, uint32_t val)
264 {
265 
266 	if (x2apic_mode) {
267 		wrmsr(MSR_APIC_000 + reg, val);
268 	} else {
269 		*(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL) = val;
270 	}
271 }
272 
273 #ifdef SMP
274 static uint64_t
lapic_read_icr_lo(void)275 lapic_read_icr_lo(void)
276 {
277 
278 	return (lapic_read32(LAPIC_ICR_LO));
279 }
280 
281 static void
lapic_write_icr(uint32_t vhi,uint32_t vlo)282 lapic_write_icr(uint32_t vhi, uint32_t vlo)
283 {
284 	register_t saveintr;
285 	uint64_t v;
286 
287 	if (x2apic_mode) {
288 		v = ((uint64_t)vhi << 32) | vlo;
289 		mfence();
290 		wrmsr(MSR_APIC_000 + LAPIC_ICR_LO, v);
291 	} else {
292 		saveintr = intr_disable();
293 		lapic_write32(LAPIC_ICR_HI, vhi);
294 		lapic_write32(LAPIC_ICR_LO, vlo);
295 		intr_restore(saveintr);
296 	}
297 }
298 
299 static void
lapic_write_icr_lo(uint32_t vlo)300 lapic_write_icr_lo(uint32_t vlo)
301 {
302 
303 	if (x2apic_mode) {
304 		mfence();
305 		wrmsr(MSR_APIC_000 + LAPIC_ICR_LO, vlo);
306 	} else {
307 		lapic_write32(LAPIC_ICR_LO, vlo);
308 	}
309 }
310 
311 static void
lapic_write_self_ipi(uint32_t vector)312 lapic_write_self_ipi(uint32_t vector)
313 {
314 
315 	KASSERT(x2apic_mode, ("SELF IPI write in xAPIC mode"));
316 	wrmsr(MSR_APIC_000 + LAPIC_SELF_IPI, vector);
317 }
318 #endif /* SMP */
319 
320 static void
lapic_enable_x2apic(void)321 lapic_enable_x2apic(void)
322 {
323 	uint64_t apic_base;
324 
325 	apic_base = rdmsr(MSR_APICBASE);
326 	apic_base |= APICBASE_X2APIC | APICBASE_ENABLED;
327 	wrmsr(MSR_APICBASE, apic_base);
328 }
329 
330 bool
lapic_is_x2apic(void)331 lapic_is_x2apic(void)
332 {
333 	uint64_t apic_base;
334 
335 	apic_base = rdmsr(MSR_APICBASE);
336 	return ((apic_base & (APICBASE_X2APIC | APICBASE_ENABLED)) ==
337 	    (APICBASE_X2APIC | APICBASE_ENABLED));
338 }
339 
340 static void	lapic_enable(void);
341 static void	lapic_resume(struct pic *pic, bool suspend_cancelled);
342 static void	lapic_timer_oneshot(struct lapic *);
343 static void	lapic_timer_oneshot_nointr(struct lapic *, uint32_t);
344 static void	lapic_timer_periodic(struct lapic *);
345 static void	lapic_timer_deadline(struct lapic *);
346 static void	lapic_timer_stop(struct lapic *);
347 static void	lapic_timer_set_divisor(u_int divisor);
348 static uint32_t	lvt_mode(struct lapic *la, u_int pin, uint32_t value);
349 static int	lapic_et_start(struct eventtimer *et,
350 		    sbintime_t first, sbintime_t period);
351 static int	lapic_et_stop(struct eventtimer *et);
352 static u_int	apic_idt_to_irq(u_int apic_id, u_int vector);
353 static void	lapic_set_tpr(u_int vector);
354 
355 struct pic lapic_pic = { .pic_resume = lapic_resume };
356 
357 static uint32_t
lvt_mode_impl(struct lapic * la,struct lvt * lvt,u_int pin,uint32_t value)358 lvt_mode_impl(struct lapic *la, struct lvt *lvt, u_int pin, uint32_t value)
359 {
360 
361 	value &= ~(APIC_LVT_M | APIC_LVT_TM | APIC_LVT_IIPP | APIC_LVT_DM |
362 	    APIC_LVT_VECTOR);
363 	if (lvt->lvt_edgetrigger == 0)
364 		value |= APIC_LVT_TM;
365 	if (lvt->lvt_activehi == 0)
366 		value |= APIC_LVT_IIPP_INTALO;
367 	if (lvt->lvt_masked)
368 		value |= APIC_LVT_M;
369 	value |= lvt->lvt_mode;
370 	switch (lvt->lvt_mode) {
371 	case APIC_LVT_DM_NMI:
372 	case APIC_LVT_DM_SMI:
373 	case APIC_LVT_DM_INIT:
374 	case APIC_LVT_DM_EXTINT:
375 		if (!lvt->lvt_edgetrigger) {
376 			if (bootverbose) {
377 				printf(
378 				    "lapic%u: Forcing LINT%u to edge trigger\n",
379 				    la->la_id, pin);
380 			}
381 			value &= ~APIC_LVT_TM;
382 		}
383 		/* Use a vector of 0. */
384 		break;
385 	case APIC_LVT_DM_FIXED:
386 		value |= lvt->lvt_vector;
387 		break;
388 	default:
389 		panic("bad APIC LVT delivery mode: %#x\n", value);
390 	}
391 	return (value);
392 }
393 
394 static uint32_t
lvt_mode(struct lapic * la,u_int pin,uint32_t value)395 lvt_mode(struct lapic *la, u_int pin, uint32_t value)
396 {
397 	struct lvt *lvt;
398 
399 	KASSERT(pin <= APIC_LVT_MAX,
400 	    ("%s: pin %u out of range", __func__, pin));
401 	if (la->la_lvts[pin].lvt_active)
402 		lvt = &la->la_lvts[pin];
403 	else
404 		lvt = &lvts[pin];
405 
406 	return (lvt_mode_impl(la, lvt, pin, value));
407 }
408 
409 static uint32_t
elvt_mode(struct lapic * la,u_int idx,uint32_t value)410 elvt_mode(struct lapic *la, u_int idx, uint32_t value)
411 {
412 	struct lvt *elvt;
413 
414 	KASSERT(idx <= APIC_ELVT_MAX,
415 	    ("%s: idx %u out of range", __func__, idx));
416 
417 	elvt = &la->la_elvts[idx];
418 	KASSERT(elvt->lvt_active, ("%s: ELVT%u is not active", __func__, idx));
419 	KASSERT(elvt->lvt_edgetrigger,
420 	    ("%s: ELVT%u is not edge triggered", __func__, idx));
421 	KASSERT(elvt->lvt_activehi,
422 	    ("%s: ELVT%u is not active high", __func__, idx));
423 	return (lvt_mode_impl(la, elvt, idx, value));
424 }
425 
426 /*
427  * Map the local APIC and setup necessary interrupt vectors.
428  */
429 void
lapic_init(vm_paddr_t addr)430 lapic_init(vm_paddr_t addr)
431 {
432 #ifdef SMP
433 	uint64_t r, r1, r2, rx;
434 #endif
435 	uint32_t ver;
436 	int i;
437 	bool arat;
438 
439 	TSENTER();
440 
441 	/*
442 	 * Enable x2APIC mode if possible. Map the local APIC
443 	 * registers page.
444 	 *
445 	 * Keep the LAPIC registers page mapped uncached for x2APIC
446 	 * mode too, to have direct map page attribute set to
447 	 * uncached.  This is needed to work around CPU errata present
448 	 * on all Intel processors.
449 	 */
450 	KASSERT(trunc_page(addr) == addr,
451 	    ("local APIC not aligned on a page boundary"));
452 	lapic_paddr = addr;
453 	lapic_map = pmap_mapdev(addr, PAGE_SIZE);
454 	if (x2apic_mode) {
455 		lapic_enable_x2apic();
456 		lapic_map = NULL;
457 	}
458 
459 	/* Setup the spurious interrupt handler. */
460 	setidt(APIC_SPURIOUS_INT, IDTVEC(spuriousint), SDT_APIC, SEL_KPL,
461 	    GSEL_APIC);
462 
463 	/* Perform basic initialization of the BSP's local APIC. */
464 	lapic_enable();
465 
466 	/* Set BSP's per-CPU local APIC ID. */
467 	PCPU_SET(apic_id, lapic_id());
468 
469 	/* Local APIC timer interrupt. */
470 	setidt(APIC_TIMER_INT, pti ? IDTVEC(timerint_pti) : IDTVEC(timerint),
471 	    SDT_APIC, SEL_KPL, GSEL_APIC);
472 
473 	/* Local APIC error interrupt. */
474 	setidt(APIC_ERROR_INT, pti ? IDTVEC(errorint_pti) : IDTVEC(errorint),
475 	    SDT_APIC, SEL_KPL, GSEL_APIC);
476 
477 	/* XXX: Thermal interrupt */
478 
479 	/* Local APIC CMCI. */
480 	setidt(APIC_CMC_INT, pti ? IDTVEC(cmcint_pti) : IDTVEC(cmcint),
481 	    SDT_APIC, SEL_KPL, GSEL_APIC);
482 
483 	if ((resource_int_value("apic", 0, "clock", &i) != 0 || i != 0)) {
484 		/* Set if APIC timer runs in C3. */
485 		arat = (cpu_power_eax & CPUTPM1_ARAT);
486 
487 		bzero(&lapic_et, sizeof(lapic_et));
488 		lapic_et.et_name = "LAPIC";
489 		lapic_et.et_flags = ET_FLAGS_PERIODIC | ET_FLAGS_ONESHOT |
490 		    ET_FLAGS_PERCPU;
491 		lapic_et.et_quality = 600;
492 		if (!arat) {
493 			lapic_et.et_flags |= ET_FLAGS_C3STOP;
494 			lapic_et.et_quality = 100;
495 		}
496 		if ((cpu_feature & CPUID_TSC) != 0 &&
497 		    (cpu_feature2 & CPUID2_TSCDLT) != 0 &&
498 		    tsc_is_invariant && tsc_freq != 0) {
499 			lapic_timer_tsc_deadline = 1;
500 			TUNABLE_INT_FETCH("hw.apic.timer_tsc_deadline",
501 			    &lapic_timer_tsc_deadline);
502 		}
503 
504 		lapic_et.et_frequency = 0;
505 		/* We don't know frequency yet, so trying to guess. */
506 		lapic_et.et_min_period = 0x00001000LL;
507 		lapic_et.et_max_period = SBT_1S;
508 		lapic_et.et_start = lapic_et_start;
509 		lapic_et.et_stop = lapic_et_stop;
510 		lapic_et.et_priv = NULL;
511 		et_register(&lapic_et);
512 	}
513 
514 	/*
515 	 * Set lapic_eoi_suppression after lapic_enable(), to not
516 	 * enable suppression in the hardware prematurely.  Note that
517 	 * we by default enable suppression even when system only has
518 	 * one IO-APIC, since EOI is broadcasted to all APIC agents,
519 	 * including CPUs, otherwise.
520 	 *
521 	 * It seems that at least some KVM versions report
522 	 * EOI_SUPPRESSION bit, but auto-EOI does not work.
523 	 */
524 	ver = lapic_read32(LAPIC_VERSION);
525 	if ((ver & APIC_VER_EOI_SUPPRESSION) != 0) {
526 		lapic_eoi_suppression = 1;
527 		if (vm_guest == VM_GUEST_KVM) {
528 			if (bootverbose)
529 				printf(
530 		       "KVM -- disabling lapic eoi suppression\n");
531 			lapic_eoi_suppression = 0;
532 		}
533 		TUNABLE_INT_FETCH("hw.apic.eoi_suppression",
534 		    &lapic_eoi_suppression);
535 	}
536 
537 #ifdef SMP
538 #define	LOOPS	1000
539 	/*
540 	 * Calibrate the busy loop waiting for IPI ack in xAPIC mode.
541 	 * lapic_ipi_wait_mult contains the number of iterations which
542 	 * approximately delay execution for 1 microsecond (the
543 	 * argument to lapic_ipi_wait() is in microseconds).
544 	 *
545 	 * We assume that TSC is present and already measured.
546 	 * Possible TSC frequency jumps are irrelevant to the
547 	 * calibration loop below, the CPU clock management code is
548 	 * not yet started, and we do not enter sleep states.
549 	 */
550 	KASSERT((cpu_feature & CPUID_TSC) != 0 && tsc_freq != 0,
551 	    ("TSC not initialized"));
552 	if (!x2apic_mode) {
553 		r = rdtsc();
554 		for (rx = 0; rx < LOOPS; rx++) {
555 			(void)lapic_read_icr_lo();
556 			ia32_pause();
557 		}
558 		r = rdtsc() - r;
559 		r1 = tsc_freq * LOOPS;
560 		r2 = r * 1000000;
561 		lapic_ipi_wait_mult = r1 >= r2 ? r1 / r2 : 1;
562 		if (bootverbose) {
563 			printf("LAPIC: ipi_wait() us multiplier %ju (r %ju "
564 			    "tsc %ju)\n", (uintmax_t)lapic_ipi_wait_mult,
565 			    (uintmax_t)r, (uintmax_t)tsc_freq);
566 		}
567 	}
568 #undef LOOPS
569 #endif /* SMP */
570 
571 	TSEXIT();
572 }
573 
574 /*
575  * Create a local APIC instance.
576  */
577 void
lapic_create(u_int apic_id,int boot_cpu)578 lapic_create(u_int apic_id, int boot_cpu)
579 {
580 	int i;
581 
582 	if (apic_id > max_apic_id) {
583 		printf("APIC: Ignoring local APIC with ID %d\n", apic_id);
584 		if (boot_cpu)
585 			panic("Can't ignore BSP");
586 		return;
587 	}
588 	KASSERT(!lapics[apic_id].la_present, ("duplicate local APIC %u",
589 	    apic_id));
590 
591 	/*
592 	 * Assume no local LVT overrides and a cluster of 0 and
593 	 * intra-cluster ID of 0.
594 	 */
595 	lapics[apic_id].la_present = 1;
596 	lapics[apic_id].la_id = apic_id;
597 	for (i = 0; i <= APIC_LVT_MAX; i++) {
598 		lapics[apic_id].la_lvts[i] = lvts[i];
599 		lapics[apic_id].la_lvts[i].lvt_active = 0;
600 	}
601 	for (i = 0; i <= APIC_ELVT_MAX; i++) {
602 		lapics[apic_id].la_elvts[i] = elvts[i];
603 		lapics[apic_id].la_elvts[i].lvt_active = 0;
604 	}
605 	for (i = 0; i <= APIC_NUM_IOINTS; i++)
606 	    lapics[apic_id].la_ioint_irqs[i] = IRQ_FREE;
607 	lapics[apic_id].la_ioint_irqs[IDT_SYSCALL - APIC_IO_INTS] = IRQ_SYSCALL;
608 	lapics[apic_id].la_ioint_irqs[APIC_TIMER_INT - APIC_IO_INTS] =
609 	    IRQ_TIMER;
610 #ifdef KDTRACE_HOOKS
611 	lapics[apic_id].la_ioint_irqs[IDT_DTRACE_RET - APIC_IO_INTS] =
612 	    IRQ_DTRACE_RET;
613 #endif
614 #ifdef XENHVM
615 	lapics[apic_id].la_ioint_irqs[IDT_EVTCHN - APIC_IO_INTS] = IRQ_EVTCHN;
616 #endif
617 
618 #ifdef SMP
619 	cpu_add(apic_id, boot_cpu);
620 #endif
621 }
622 
623 static inline uint32_t
amd_read_ext_features(void)624 amd_read_ext_features(void)
625 {
626 	uint32_t version;
627 
628 	if (cpu_vendor_id != CPU_VENDOR_AMD &&
629 	    cpu_vendor_id != CPU_VENDOR_HYGON)
630 		return (0);
631 	version = lapic_read32(LAPIC_VERSION);
632 	if ((version & APIC_VER_AMD_EXT_SPACE) != 0)
633 		return (lapic_read32(LAPIC_EXT_FEATURES));
634 	else
635 		return (0);
636 }
637 
638 static inline uint32_t
amd_read_elvt_count(void)639 amd_read_elvt_count(void)
640 {
641 	uint32_t extf;
642 	uint32_t count;
643 
644 	extf = amd_read_ext_features();
645 	count = (extf & APIC_EXTF_ELVT_MASK) >> APIC_EXTF_ELVT_SHIFT;
646 	count = min(count, APIC_ELVT_MAX + 1);
647 	return (count);
648 }
649 
650 /*
651  * Dump contents of local APIC registers
652  */
653 void
lapic_dump(const char * str)654 lapic_dump(const char* str)
655 {
656 	uint32_t version;
657 	uint32_t maxlvt;
658 	uint32_t extf;
659 	int elvt_count;
660 	int i;
661 
662 	version = lapic_read32(LAPIC_VERSION);
663 	maxlvt = (version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
664 	printf("cpu%d %s:\n", PCPU_GET(cpuid), str);
665 	printf("     ID: 0x%08x   VER: 0x%08x LDR: 0x%08x DFR: 0x%08x",
666 	    lapic_read32(LAPIC_ID), version,
667 	    lapic_read32(LAPIC_LDR), x2apic_mode ? 0 : lapic_read32(LAPIC_DFR));
668 	if ((cpu_feature2 & CPUID2_X2APIC) != 0)
669 		printf(" x2APIC: %d", x2apic_mode);
670 	printf("\n  lint0: 0x%08x lint1: 0x%08x TPR: 0x%08x SVR: 0x%08x\n",
671 	    lapic_read32(LAPIC_LVT_LINT0), lapic_read32(LAPIC_LVT_LINT1),
672 	    lapic_read32(LAPIC_TPR), lapic_read32(LAPIC_SVR));
673 	printf("  timer: 0x%08x therm: 0x%08x err: 0x%08x",
674 	    lapic_read32(LAPIC_LVT_TIMER), lapic_read32(LAPIC_LVT_THERMAL),
675 	    lapic_read32(LAPIC_LVT_ERROR));
676 	if (maxlvt >= APIC_LVT_PMC)
677 		printf(" pmc: 0x%08x", lapic_read32(LAPIC_LVT_PCINT));
678 	printf("\n");
679 	if (maxlvt >= APIC_LVT_CMCI)
680 		printf("   cmci: 0x%08x\n", lapic_read32(LAPIC_LVT_CMCI));
681 	extf = amd_read_ext_features();
682 	if (extf != 0) {
683 		printf("   AMD ext features: 0x%08x", extf);
684 		elvt_count = amd_read_elvt_count();
685 		for (i = 0; i < elvt_count; i++)
686 			printf("%s elvt%d: 0x%08x", (i % 4) ? "" : "\n ", i,
687 			    lapic_read32(LAPIC_EXT_LVT0 + i));
688 		printf("\n");
689 	}
690 }
691 
692 void
lapic_xapic_mode(void)693 lapic_xapic_mode(void)
694 {
695 	register_t saveintr;
696 
697 	saveintr = intr_disable();
698 	if (x2apic_mode)
699 		lapic_enable_x2apic();
700 	intr_restore(saveintr);
701 }
702 
703 void
lapic_setup(int boot)704 lapic_setup(int boot)
705 {
706 	struct lapic *la;
707 	uint32_t version;
708 	uint32_t maxlvt;
709 	register_t saveintr;
710 	int elvt_count;
711 	int i;
712 
713 	saveintr = intr_disable();
714 
715 	la = &lapics[lapic_id()];
716 	KASSERT(la->la_present, ("missing APIC structure"));
717 	version = lapic_read32(LAPIC_VERSION);
718 	maxlvt = (version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
719 
720 	/* Initialize the TPR to allow all interrupts. */
721 	lapic_set_tpr(0);
722 
723 	/* Setup spurious vector and enable the local APIC. */
724 	lapic_enable();
725 
726 	/* Program LINT[01] LVT entries. */
727 	lapic_write32(LAPIC_LVT_LINT0, lvt_mode(la, APIC_LVT_LINT0,
728 	    lapic_read32(LAPIC_LVT_LINT0)));
729 	lapic_write32(LAPIC_LVT_LINT1, lvt_mode(la, APIC_LVT_LINT1,
730 	    lapic_read32(LAPIC_LVT_LINT1)));
731 
732 	/* Program the PMC LVT entry if present. */
733 	if (maxlvt >= APIC_LVT_PMC) {
734 		lapic_write32(LAPIC_LVT_PCINT, lvt_mode(la, APIC_LVT_PMC,
735 		    LAPIC_LVT_PCINT));
736 	}
737 
738 	/*
739 	 * Program the timer LVT.  Calibration is deferred until it is certain
740 	 * that we have a reliable timecounter.
741 	 */
742 	la->lvt_timer_base = lvt_mode(la, APIC_LVT_TIMER,
743 	    lapic_read32(LAPIC_LVT_TIMER));
744 	la->lvt_timer_last = la->lvt_timer_base;
745 	lapic_write32(LAPIC_LVT_TIMER, la->lvt_timer_base);
746 
747 	if (boot)
748 		la->la_timer_mode = LAT_MODE_UNDEF;
749 	else if (la->la_timer_mode != LAT_MODE_UNDEF) {
750 		KASSERT(la->la_timer_period != 0, ("lapic%u: zero divisor",
751 		    lapic_id()));
752 		switch (la->la_timer_mode) {
753 		case LAT_MODE_PERIODIC:
754 			lapic_timer_set_divisor(lapic_timer_divisor);
755 			lapic_timer_periodic(la);
756 			break;
757 		case LAT_MODE_ONESHOT:
758 			lapic_timer_set_divisor(lapic_timer_divisor);
759 			lapic_timer_oneshot(la);
760 			break;
761 		case LAT_MODE_DEADLINE:
762 			lapic_timer_deadline(la);
763 			break;
764 		default:
765 			panic("corrupted la_timer_mode %p %d", la,
766 			    la->la_timer_mode);
767 		}
768 	}
769 
770 	/* Program error LVT and clear any existing errors. */
771 	lapic_write32(LAPIC_LVT_ERROR, lvt_mode(la, APIC_LVT_ERROR,
772 	    lapic_read32(LAPIC_LVT_ERROR)));
773 	lapic_write32(LAPIC_ESR, 0);
774 
775 	/* XXX: Thermal LVT */
776 
777 	/* Program the CMCI LVT entry if present. */
778 	if (maxlvt >= APIC_LVT_CMCI) {
779 		lapic_write32(LAPIC_LVT_CMCI, lvt_mode(la, APIC_LVT_CMCI,
780 		    lapic_read32(LAPIC_LVT_CMCI)));
781 	}
782 
783 	elvt_count = amd_read_elvt_count();
784 	for (i = 0; i < elvt_count; i++) {
785 		if (la->la_elvts[i].lvt_active)
786 			lapic_write32(LAPIC_EXT_LVT0 + i,
787 			    elvt_mode(la, i, lapic_read32(LAPIC_EXT_LVT0 + i)));
788 	}
789 
790 	intr_restore(saveintr);
791 }
792 
793 static void
lapic_intrcnt(void * dummy __unused)794 lapic_intrcnt(void *dummy __unused)
795 {
796 	struct pcpu *pc;
797 	struct lapic *la;
798 	char buf[MAXCOMLEN + 1];
799 
800 	/* If there are no APICs, skip this function. */
801 	if (lapics == NULL)
802 		return;
803 
804 	STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
805 		la = &lapics[pc->pc_apic_id];
806 		if (!la->la_present)
807 		    continue;
808 
809 		snprintf(buf, sizeof(buf), "cpu%d:timer", pc->pc_cpuid);
810 		intrcnt_add(buf, &la->la_timer_count);
811 	}
812 }
813 SYSINIT(lapic_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, lapic_intrcnt, NULL);
814 
815 void
lapic_reenable_pcint(void)816 lapic_reenable_pcint(void)
817 {
818 	uint32_t value;
819 
820 	if (refcount_load(&pcint_refcnt) == 0)
821 		return;
822 	value = lapic_read32(LAPIC_LVT_PCINT);
823 	value &= ~APIC_LVT_M;
824 	lapic_write32(LAPIC_LVT_PCINT, value);
825 }
826 
827 static void
lapic_update_pcint(void * dummy)828 lapic_update_pcint(void *dummy)
829 {
830 	struct lapic *la;
831 
832 	la = &lapics[lapic_id()];
833 	lapic_write32(LAPIC_LVT_PCINT, lvt_mode(la, APIC_LVT_PMC,
834 	    lapic_read32(LAPIC_LVT_PCINT)));
835 }
836 
837 void
lapic_calibrate_timer(void)838 lapic_calibrate_timer(void)
839 {
840 	struct lapic *la;
841 	register_t intr;
842 
843 #ifdef DEV_ATPIC
844 	/* Fail if the local APIC is not present. */
845 	if (!x2apic_mode && lapic_map == NULL)
846 		return;
847 #endif
848 
849 	intr = intr_disable();
850 	la = &lapics[lapic_id()];
851 
852 	lapic_calibrate_initcount(la);
853 
854 	intr_restore(intr);
855 
856 	if (lapic_timer_tsc_deadline && bootverbose) {
857 		printf("lapic: deadline tsc mode, Frequency %ju Hz\n",
858 		    (uintmax_t)tsc_freq);
859 	}
860 }
861 
862 int
lapic_enable_pcint(void)863 lapic_enable_pcint(void)
864 {
865 	u_int32_t maxlvt;
866 
867 #ifdef DEV_ATPIC
868 	/* Fail if the local APIC is not present. */
869 	if (!x2apic_mode && lapic_map == NULL)
870 		return (0);
871 #endif
872 
873 	/* Fail if the PMC LVT is not present. */
874 	maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
875 	if (maxlvt < APIC_LVT_PMC)
876 		return (0);
877 	if (refcount_acquire(&pcint_refcnt) > 0)
878 		return (1);
879 	lvts[APIC_LVT_PMC].lvt_masked = 0;
880 
881 	MPASS(mp_ncpus == 1 || smp_started);
882 	smp_rendezvous(NULL, lapic_update_pcint, NULL, NULL);
883 	return (1);
884 }
885 
886 void
lapic_disable_pcint(void)887 lapic_disable_pcint(void)
888 {
889 	u_int32_t maxlvt;
890 
891 #ifdef DEV_ATPIC
892 	/* Fail if the local APIC is not present. */
893 	if (!x2apic_mode && lapic_map == NULL)
894 		return;
895 #endif
896 
897 	/* Fail if the PMC LVT is not present. */
898 	maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
899 	if (maxlvt < APIC_LVT_PMC)
900 		return;
901 	if (!refcount_release(&pcint_refcnt))
902 		return;
903 	lvts[APIC_LVT_PMC].lvt_masked = 1;
904 
905 #ifdef SMP
906 	/* The APs should always be started when hwpmc is unloaded. */
907 	KASSERT(mp_ncpus == 1 || smp_started, ("hwpmc unloaded too early"));
908 #endif
909 	smp_rendezvous(NULL, lapic_update_pcint, NULL, NULL);
910 }
911 
912 static int
lapic_calibrate_initcount_cpuid_vm(void)913 lapic_calibrate_initcount_cpuid_vm(void)
914 {
915 	u_int regs[4];
916 	uint64_t freq;
917 
918 	/* Get value from CPUID leaf if possible. */
919 	if (vm_guest == VM_GUEST_NO)
920 		return (false);
921 	if (hv_high < 0x40000010)
922 		return (false);
923 	do_cpuid(0x40000010, regs);
924 	freq = (uint64_t)(regs[1]) * 1000;
925 
926 	/* Pick timer divisor. */
927 	lapic_timer_divisor = 2;
928 	do {
929 		if (freq / lapic_timer_divisor < APIC_TIMER_MAX_COUNT)
930 			break;
931 		lapic_timer_divisor <<= 1;
932 	} while (lapic_timer_divisor <= 128);
933 	if (lapic_timer_divisor > 128)
934 		return (false);
935 
936 	/* Record divided frequency. */
937 	count_freq = freq / lapic_timer_divisor;
938 	return (count_freq != 0);
939 }
940 
941 static uint64_t
cb_lapic_getcount(void)942 cb_lapic_getcount(void)
943 {
944 
945 	return (APIC_TIMER_MAX_COUNT - lapic_read32(LAPIC_CCR_TIMER));
946 }
947 
948 static void
lapic_calibrate_initcount(struct lapic * la)949 lapic_calibrate_initcount(struct lapic *la)
950 {
951 	uint64_t freq;
952 
953 	if (lapic_calibrate_initcount_cpuid_vm())
954 		goto done;
955 
956 	/* Calibrate the APIC timer frequency. */
957 	lapic_timer_set_divisor(2);
958 	lapic_timer_oneshot_nointr(la, APIC_TIMER_MAX_COUNT);
959 	fpu_kern_enter(curthread, NULL, FPU_KERN_NOCTX);
960 	freq = clockcalib(cb_lapic_getcount, "lapic");
961 	fpu_kern_leave(curthread, NULL);
962 
963 	/* Pick a different divisor if necessary. */
964 	lapic_timer_divisor = 2;
965 	do {
966 		if (freq * 2 / lapic_timer_divisor < APIC_TIMER_MAX_COUNT)
967 			break;
968 		lapic_timer_divisor <<= 1;
969 	} while (lapic_timer_divisor <= 128);
970 	if (lapic_timer_divisor > 128)
971 		panic("lapic: Divisor too big");
972 	count_freq = freq * 2 / lapic_timer_divisor;
973 done:
974 	if (bootverbose) {
975 		printf("lapic: Divisor %lu, Frequency %lu Hz\n",
976 		    lapic_timer_divisor, count_freq);
977 	}
978 }
979 
980 static void
lapic_change_mode(struct eventtimer * et,struct lapic * la,enum lat_timer_mode newmode)981 lapic_change_mode(struct eventtimer *et, struct lapic *la,
982     enum lat_timer_mode newmode)
983 {
984 	if (la->la_timer_mode == newmode)
985 		return;
986 	switch (newmode) {
987 	case LAT_MODE_PERIODIC:
988 		lapic_timer_set_divisor(lapic_timer_divisor);
989 		et->et_frequency = count_freq;
990 		break;
991 	case LAT_MODE_DEADLINE:
992 		et->et_frequency = tsc_freq;
993 		break;
994 	case LAT_MODE_ONESHOT:
995 		lapic_timer_set_divisor(lapic_timer_divisor);
996 		et->et_frequency = count_freq;
997 		break;
998 	default:
999 		panic("lapic_change_mode %d", newmode);
1000 	}
1001 	la->la_timer_mode = newmode;
1002 	et->et_min_period = (0x00000002LLU << 32) / et->et_frequency;
1003 	et->et_max_period = (0xfffffffeLLU << 32) / et->et_frequency;
1004 }
1005 
1006 static int
lapic_et_start(struct eventtimer * et,sbintime_t first,sbintime_t period)1007 lapic_et_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
1008 {
1009 	struct lapic *la;
1010 
1011 	la = &lapics[PCPU_GET(apic_id)];
1012 	if (period != 0) {
1013 		lapic_change_mode(et, la, LAT_MODE_PERIODIC);
1014 		la->la_timer_period = ((uint32_t)et->et_frequency * period) >>
1015 		    32;
1016 		lapic_timer_periodic(la);
1017 	} else if (lapic_timer_tsc_deadline) {
1018 		lapic_change_mode(et, la, LAT_MODE_DEADLINE);
1019 		la->la_timer_period = (et->et_frequency * first) >> 32;
1020 		lapic_timer_deadline(la);
1021 	} else {
1022 		lapic_change_mode(et, la, LAT_MODE_ONESHOT);
1023 		la->la_timer_period = ((uint32_t)et->et_frequency * first) >>
1024 		    32;
1025 		lapic_timer_oneshot(la);
1026 	}
1027 	return (0);
1028 }
1029 
1030 static int
lapic_et_stop(struct eventtimer * et)1031 lapic_et_stop(struct eventtimer *et)
1032 {
1033 	struct lapic *la;
1034 
1035 	la = &lapics[PCPU_GET(apic_id)];
1036 	lapic_timer_stop(la);
1037 	la->la_timer_mode = LAT_MODE_UNDEF;
1038 	return (0);
1039 }
1040 
1041 void
lapic_disable(void)1042 lapic_disable(void)
1043 {
1044 	uint32_t value;
1045 
1046 	/* Software disable the local APIC. */
1047 	value = lapic_read32(LAPIC_SVR);
1048 	value &= ~APIC_SVR_SWEN;
1049 	lapic_write32(LAPIC_SVR, value);
1050 }
1051 
1052 static void
lapic_enable(void)1053 lapic_enable(void)
1054 {
1055 	uint32_t value;
1056 
1057 	/* Program the spurious vector to enable the local APIC. */
1058 	value = lapic_read32(LAPIC_SVR);
1059 	value &= ~(APIC_SVR_VECTOR | APIC_SVR_FOCUS);
1060 	value |= APIC_SVR_FEN | APIC_SVR_SWEN | APIC_SPURIOUS_INT;
1061 	if (lapic_eoi_suppression)
1062 		value |= APIC_SVR_EOI_SUPPRESSION;
1063 	lapic_write32(LAPIC_SVR, value);
1064 }
1065 
1066 /* Reset the local APIC on the BSP during resume. */
1067 static void
lapic_resume(struct pic * pic,bool suspend_cancelled)1068 lapic_resume(struct pic *pic, bool suspend_cancelled)
1069 {
1070 
1071 	lapic_setup(0);
1072 }
1073 
1074 int
lapic_id(void)1075 lapic_id(void)
1076 {
1077 	uint32_t v;
1078 
1079 	KASSERT(x2apic_mode || lapic_map != NULL, ("local APIC is not mapped"));
1080 	v = lapic_read32(LAPIC_ID);
1081 	if (!x2apic_mode)
1082 		v >>= APIC_ID_SHIFT;
1083 	return (v);
1084 }
1085 
1086 int
lapic_intr_pending(u_int vector)1087 lapic_intr_pending(u_int vector)
1088 {
1089 	uint32_t irr;
1090 
1091 	/*
1092 	 * The IRR registers are an array of registers each of which
1093 	 * only describes 32 interrupts in the low 32 bits.  Thus, we
1094 	 * divide the vector by 32 to get the register index.
1095 	 * Finally, we modulus the vector by 32 to determine the
1096 	 * individual bit to test.
1097 	 */
1098 	irr = lapic_read32(LAPIC_IRR0 + vector / 32);
1099 	return (irr & 1 << (vector % 32));
1100 }
1101 
1102 void
lapic_set_logical_id(u_int apic_id,u_int cluster,u_int cluster_id)1103 lapic_set_logical_id(u_int apic_id, u_int cluster, u_int cluster_id)
1104 {
1105 	struct lapic *la;
1106 
1107 	KASSERT(lapics[apic_id].la_present, ("%s: APIC %u doesn't exist",
1108 	    __func__, apic_id));
1109 	KASSERT(cluster <= APIC_MAX_CLUSTER, ("%s: cluster %u too big",
1110 	    __func__, cluster));
1111 	KASSERT(cluster_id <= APIC_MAX_INTRACLUSTER_ID,
1112 	    ("%s: intra cluster id %u too big", __func__, cluster_id));
1113 	la = &lapics[apic_id];
1114 	la->la_cluster = cluster;
1115 	la->la_cluster_id = cluster_id;
1116 }
1117 
1118 int
lapic_set_lvt_mask(u_int apic_id,u_int pin,u_char masked)1119 lapic_set_lvt_mask(u_int apic_id, u_int pin, u_char masked)
1120 {
1121 
1122 	if (pin > APIC_LVT_MAX)
1123 		return (EINVAL);
1124 	if (apic_id == APIC_ID_ALL) {
1125 		lvts[pin].lvt_masked = masked;
1126 		if (bootverbose)
1127 			printf("lapic:");
1128 	} else {
1129 		KASSERT(lapics[apic_id].la_present,
1130 		    ("%s: missing APIC %u", __func__, apic_id));
1131 		lapics[apic_id].la_lvts[pin].lvt_masked = masked;
1132 		lapics[apic_id].la_lvts[pin].lvt_active = 1;
1133 		if (bootverbose)
1134 			printf("lapic%u:", apic_id);
1135 	}
1136 	if (bootverbose)
1137 		printf(" LINT%u %s\n", pin, masked ? "masked" : "unmasked");
1138 	return (0);
1139 }
1140 
1141 int
lapic_set_lvt_mode(u_int apic_id,u_int pin,u_int32_t mode)1142 lapic_set_lvt_mode(u_int apic_id, u_int pin, u_int32_t mode)
1143 {
1144 	struct lvt *lvt;
1145 
1146 	if (pin > APIC_LVT_MAX)
1147 		return (EINVAL);
1148 	if (apic_id == APIC_ID_ALL) {
1149 		lvt = &lvts[pin];
1150 		if (bootverbose)
1151 			printf("lapic:");
1152 	} else {
1153 		KASSERT(lapics[apic_id].la_present,
1154 		    ("%s: missing APIC %u", __func__, apic_id));
1155 		lvt = &lapics[apic_id].la_lvts[pin];
1156 		lvt->lvt_active = 1;
1157 		if (bootverbose)
1158 			printf("lapic%u:", apic_id);
1159 	}
1160 	lvt->lvt_mode = mode;
1161 	switch (mode) {
1162 	case APIC_LVT_DM_NMI:
1163 	case APIC_LVT_DM_SMI:
1164 	case APIC_LVT_DM_INIT:
1165 	case APIC_LVT_DM_EXTINT:
1166 		lvt->lvt_edgetrigger = 1;
1167 		lvt->lvt_activehi = 1;
1168 		if (mode == APIC_LVT_DM_EXTINT)
1169 			lvt->lvt_masked = 1;
1170 		else
1171 			lvt->lvt_masked = 0;
1172 		break;
1173 	default:
1174 		panic("Unsupported delivery mode: 0x%x\n", mode);
1175 	}
1176 	if (bootverbose) {
1177 		printf(" Routing ");
1178 		switch (mode) {
1179 		case APIC_LVT_DM_NMI:
1180 			printf("NMI");
1181 			break;
1182 		case APIC_LVT_DM_SMI:
1183 			printf("SMI");
1184 			break;
1185 		case APIC_LVT_DM_INIT:
1186 			printf("INIT");
1187 			break;
1188 		case APIC_LVT_DM_EXTINT:
1189 			printf("ExtINT");
1190 			break;
1191 		}
1192 		printf(" -> LINT%u\n", pin);
1193 	}
1194 	return (0);
1195 }
1196 
1197 int
lapic_set_lvt_polarity(u_int apic_id,u_int pin,enum intr_polarity pol)1198 lapic_set_lvt_polarity(u_int apic_id, u_int pin, enum intr_polarity pol)
1199 {
1200 
1201 	if (pin > APIC_LVT_MAX || pol == INTR_POLARITY_CONFORM)
1202 		return (EINVAL);
1203 	if (apic_id == APIC_ID_ALL) {
1204 		lvts[pin].lvt_activehi = (pol == INTR_POLARITY_HIGH);
1205 		if (bootverbose)
1206 			printf("lapic:");
1207 	} else {
1208 		KASSERT(lapics[apic_id].la_present,
1209 		    ("%s: missing APIC %u", __func__, apic_id));
1210 		lapics[apic_id].la_lvts[pin].lvt_active = 1;
1211 		lapics[apic_id].la_lvts[pin].lvt_activehi =
1212 		    (pol == INTR_POLARITY_HIGH);
1213 		if (bootverbose)
1214 			printf("lapic%u:", apic_id);
1215 	}
1216 	if (bootverbose)
1217 		printf(" LINT%u polarity: %s\n", pin,
1218 		    pol == INTR_POLARITY_HIGH ? "high" : "low");
1219 	return (0);
1220 }
1221 
1222 int
lapic_set_lvt_triggermode(u_int apic_id,u_int pin,enum intr_trigger trigger)1223 lapic_set_lvt_triggermode(u_int apic_id, u_int pin,
1224      enum intr_trigger trigger)
1225 {
1226 
1227 	if (pin > APIC_LVT_MAX || trigger == INTR_TRIGGER_CONFORM)
1228 		return (EINVAL);
1229 	if (apic_id == APIC_ID_ALL) {
1230 		lvts[pin].lvt_edgetrigger = (trigger == INTR_TRIGGER_EDGE);
1231 		if (bootverbose)
1232 			printf("lapic:");
1233 	} else {
1234 		KASSERT(lapics[apic_id].la_present,
1235 		    ("%s: missing APIC %u", __func__, apic_id));
1236 		lapics[apic_id].la_lvts[pin].lvt_edgetrigger =
1237 		    (trigger == INTR_TRIGGER_EDGE);
1238 		lapics[apic_id].la_lvts[pin].lvt_active = 1;
1239 		if (bootverbose)
1240 			printf("lapic%u:", apic_id);
1241 	}
1242 	if (bootverbose)
1243 		printf(" LINT%u trigger: %s\n", pin,
1244 		    trigger == INTR_TRIGGER_EDGE ? "edge" : "level");
1245 	return (0);
1246 }
1247 
1248 /*
1249  * Adjust the TPR of the current CPU so that it blocks all interrupts below
1250  * the passed in vector.
1251  */
1252 static void
lapic_set_tpr(u_int vector)1253 lapic_set_tpr(u_int vector)
1254 {
1255 #ifdef CHEAP_TPR
1256 	lapic_write32(LAPIC_TPR, vector);
1257 #else
1258 	uint32_t tpr;
1259 
1260 	tpr = lapic_read32(LAPIC_TPR) & ~APIC_TPR_PRIO;
1261 	tpr |= vector;
1262 	lapic_write32(LAPIC_TPR, tpr);
1263 #endif
1264 }
1265 
1266 void
lapic_eoi(void)1267 lapic_eoi(void)
1268 {
1269 
1270 	lapic_write32_nofence(LAPIC_EOI, 0);
1271 }
1272 
1273 void
lapic_handle_intr(int vector,struct trapframe * frame)1274 lapic_handle_intr(int vector, struct trapframe *frame)
1275 {
1276 	struct intsrc *isrc;
1277 
1278 	kasan_mark(frame, sizeof(*frame), sizeof(*frame), 0);
1279 	kmsan_mark(&vector, sizeof(vector), KMSAN_STATE_INITED);
1280 	kmsan_mark(frame, sizeof(*frame), KMSAN_STATE_INITED);
1281 	trap_check_kstack();
1282 
1283 	isrc = intr_lookup_source(apic_idt_to_irq(PCPU_GET(apic_id),
1284 	    vector));
1285 	intr_execute_handlers(isrc, frame);
1286 }
1287 
1288 void
lapic_handle_timer(struct trapframe * frame)1289 lapic_handle_timer(struct trapframe *frame)
1290 {
1291 	struct lapic *la;
1292 	struct trapframe *oldframe;
1293 	struct thread *td;
1294 
1295 	/* Send EOI first thing. */
1296 	lapic_eoi();
1297 
1298 	kasan_mark(frame, sizeof(*frame), sizeof(*frame), 0);
1299 	kmsan_mark(frame, sizeof(*frame), KMSAN_STATE_INITED);
1300 	trap_check_kstack();
1301 
1302 #if defined(SMP) && !defined(SCHED_ULE)
1303 	/*
1304 	 * Don't do any accounting for the disabled HTT cores, since it
1305 	 * will provide misleading numbers for the userland.
1306 	 *
1307 	 * No locking is necessary here, since even if we lose the race
1308 	 * when hlt_cpus_mask changes it is not a big deal, really.
1309 	 *
1310 	 * Don't do that for ULE, since ULE doesn't consider hlt_cpus_mask
1311 	 * and unlike other schedulers it actually schedules threads to
1312 	 * those CPUs.
1313 	 */
1314 	if (CPU_ISSET(PCPU_GET(cpuid), &hlt_cpus_mask))
1315 		return;
1316 #endif
1317 
1318 	/* Look up our local APIC structure for the tick counters. */
1319 	la = &lapics[PCPU_GET(apic_id)];
1320 	(*la->la_timer_count)++;
1321 	critical_enter();
1322 	if (lapic_et.et_active) {
1323 		td = curthread;
1324 		td->td_intr_nesting_level++;
1325 		oldframe = td->td_intr_frame;
1326 		td->td_intr_frame = frame;
1327 		lapic_et.et_event_cb(&lapic_et, lapic_et.et_arg);
1328 		td->td_intr_frame = oldframe;
1329 		td->td_intr_nesting_level--;
1330 	}
1331 	critical_exit();
1332 }
1333 
1334 static void
lapic_timer_set_divisor(u_int divisor)1335 lapic_timer_set_divisor(u_int divisor)
1336 {
1337 
1338 	KASSERT(powerof2(divisor), ("lapic: invalid divisor %u", divisor));
1339 	KASSERT(ffs(divisor) <= nitems(lapic_timer_divisors),
1340 		("lapic: invalid divisor %u", divisor));
1341 	lapic_write32(LAPIC_DCR_TIMER, lapic_timer_divisors[ffs(divisor) - 1]);
1342 }
1343 
1344 static void
lapic_timer_oneshot(struct lapic * la)1345 lapic_timer_oneshot(struct lapic *la)
1346 {
1347 	uint32_t value;
1348 
1349 	value = la->lvt_timer_base;
1350 	value &= ~(APIC_LVTT_TM | APIC_LVT_M);
1351 	value |= APIC_LVTT_TM_ONE_SHOT;
1352 	la->lvt_timer_last = value;
1353 	lapic_write32(LAPIC_LVT_TIMER, value);
1354 	lapic_write32(LAPIC_ICR_TIMER, la->la_timer_period);
1355 }
1356 
1357 static void
lapic_timer_oneshot_nointr(struct lapic * la,uint32_t count)1358 lapic_timer_oneshot_nointr(struct lapic *la, uint32_t count)
1359 {
1360 	uint32_t value;
1361 
1362 	value = la->lvt_timer_base;
1363 	value &= ~APIC_LVTT_TM;
1364 	value |= APIC_LVTT_TM_ONE_SHOT | APIC_LVT_M;
1365 	la->lvt_timer_last = value;
1366 	lapic_write32(LAPIC_LVT_TIMER, value);
1367 	lapic_write32(LAPIC_ICR_TIMER, count);
1368 }
1369 
1370 static void
lapic_timer_periodic(struct lapic * la)1371 lapic_timer_periodic(struct lapic *la)
1372 {
1373 	uint32_t value;
1374 
1375 	value = la->lvt_timer_base;
1376 	value &= ~(APIC_LVTT_TM | APIC_LVT_M);
1377 	value |= APIC_LVTT_TM_PERIODIC;
1378 	la->lvt_timer_last = value;
1379 	lapic_write32(LAPIC_LVT_TIMER, value);
1380 	lapic_write32(LAPIC_ICR_TIMER, la->la_timer_period);
1381 }
1382 
1383 static void
lapic_timer_deadline(struct lapic * la)1384 lapic_timer_deadline(struct lapic *la)
1385 {
1386 	uint32_t value;
1387 
1388 	value = la->lvt_timer_base;
1389 	value &= ~(APIC_LVTT_TM | APIC_LVT_M);
1390 	value |= APIC_LVTT_TM_TSCDLT;
1391 	if (value != la->lvt_timer_last) {
1392 		la->lvt_timer_last = value;
1393 		lapic_write32_nofence(LAPIC_LVT_TIMER, value);
1394 		if (!x2apic_mode)
1395 			mfence();
1396 	}
1397 	wrmsr(MSR_TSC_DEADLINE, la->la_timer_period + rdtsc());
1398 }
1399 
1400 static void
lapic_timer_stop(struct lapic * la)1401 lapic_timer_stop(struct lapic *la)
1402 {
1403 	uint32_t value;
1404 
1405 	if (la->la_timer_mode == LAT_MODE_DEADLINE) {
1406 		wrmsr(MSR_TSC_DEADLINE, 0);
1407 		mfence();
1408 	} else {
1409 		value = la->lvt_timer_base;
1410 		value &= ~APIC_LVTT_TM;
1411 		value |= APIC_LVT_M;
1412 		la->lvt_timer_last = value;
1413 		lapic_write32(LAPIC_LVT_TIMER, value);
1414 	}
1415 }
1416 
1417 void
lapic_handle_cmc(void)1418 lapic_handle_cmc(void)
1419 {
1420 	trap_check_kstack();
1421 
1422 	lapic_eoi();
1423 	cmc_intr();
1424 }
1425 
1426 /*
1427  * Called from the mca_init() to activate the CMC interrupt if this CPU is
1428  * responsible for monitoring any MC banks for CMC events.  Since mca_init()
1429  * is called prior to lapic_setup() during boot, this just needs to unmask
1430  * this CPU's LVT_CMCI entry.
1431  */
1432 void
lapic_enable_cmc(void)1433 lapic_enable_cmc(void)
1434 {
1435 	u_int apic_id;
1436 
1437 #ifdef DEV_ATPIC
1438 	if (!x2apic_mode && lapic_map == NULL)
1439 		return;
1440 #endif
1441 	apic_id = PCPU_GET(apic_id);
1442 	KASSERT(lapics[apic_id].la_present,
1443 	    ("%s: missing APIC %u", __func__, apic_id));
1444 	lapics[apic_id].la_lvts[APIC_LVT_CMCI].lvt_masked = 0;
1445 	lapics[apic_id].la_lvts[APIC_LVT_CMCI].lvt_active = 1;
1446 }
1447 
1448 int
lapic_enable_mca_elvt(void)1449 lapic_enable_mca_elvt(void)
1450 {
1451 	u_int apic_id;
1452 	uint32_t value;
1453 	int elvt_count;
1454 
1455 #ifdef DEV_ATPIC
1456 	if (lapic_map == NULL)
1457 		return (-1);
1458 #endif
1459 
1460 	apic_id = PCPU_GET(apic_id);
1461 	KASSERT(lapics[apic_id].la_present,
1462 	    ("%s: missing APIC %u", __func__, apic_id));
1463 	elvt_count = amd_read_elvt_count();
1464 	if (elvt_count <= APIC_ELVT_MCA)
1465 		return (-1);
1466 
1467 	value = lapic_read32(LAPIC_EXT_LVT0 + APIC_ELVT_MCA);
1468 	if ((value & APIC_LVT_M) == 0) {
1469 		if (bootverbose)
1470 			printf("AMD MCE Thresholding Extended LVT is already active\n");
1471 		return (APIC_ELVT_MCA);
1472 	}
1473 	lapics[apic_id].la_elvts[APIC_ELVT_MCA].lvt_masked = 0;
1474 	lapics[apic_id].la_elvts[APIC_ELVT_MCA].lvt_active = 1;
1475 	return (APIC_ELVT_MCA);
1476 }
1477 
1478 void
lapic_handle_error(void)1479 lapic_handle_error(void)
1480 {
1481 	uint32_t esr;
1482 
1483 	trap_check_kstack();
1484 
1485 	/*
1486 	 * Read the contents of the error status register.  Write to
1487 	 * the register first before reading from it to force the APIC
1488 	 * to update its value to indicate any errors that have
1489 	 * occurred since the previous write to the register.
1490 	 */
1491 	lapic_write32(LAPIC_ESR, 0);
1492 	esr = lapic_read32(LAPIC_ESR);
1493 
1494 	printf("CPU%d: local APIC error 0x%x\n", PCPU_GET(cpuid), esr);
1495 	lapic_eoi();
1496 }
1497 
1498 u_int
apic_cpuid(u_int apic_id)1499 apic_cpuid(u_int apic_id)
1500 {
1501 #ifdef SMP
1502 	return apic_cpuids[apic_id];
1503 #else
1504 	return 0;
1505 #endif
1506 }
1507 
1508 /* Request a free IDT vector to be used by the specified IRQ. */
1509 u_int
apic_alloc_vector(u_int apic_id,u_int irq)1510 apic_alloc_vector(u_int apic_id, u_int irq)
1511 {
1512 	u_int vector;
1513 
1514 	KASSERT(irq < num_io_irqs, ("Invalid IRQ %u", irq));
1515 
1516 	/*
1517 	 * Search for a free vector.  Currently we just use a very simple
1518 	 * algorithm to find the first free vector.
1519 	 */
1520 	mtx_lock_spin(&icu_lock);
1521 	for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
1522 		if (lapics[apic_id].la_ioint_irqs[vector] != IRQ_FREE)
1523 			continue;
1524 		lapics[apic_id].la_ioint_irqs[vector] = irq;
1525 		mtx_unlock_spin(&icu_lock);
1526 		return (vector + APIC_IO_INTS);
1527 	}
1528 	mtx_unlock_spin(&icu_lock);
1529 	return (0);
1530 }
1531 
1532 /*
1533  * Request 'count' free contiguous IDT vectors to be used by 'count'
1534  * IRQs.  'count' must be a power of two and the vectors will be
1535  * aligned on a boundary of 'align'.  If the request cannot be
1536  * satisfied, 0 is returned.
1537  */
1538 u_int
apic_alloc_vectors(u_int apic_id,u_int * irqs,u_int count,u_int align)1539 apic_alloc_vectors(u_int apic_id, u_int *irqs, u_int count, u_int align)
1540 {
1541 	u_int first, run, vector;
1542 
1543 	KASSERT(powerof2(count), ("bad count"));
1544 	KASSERT(powerof2(align), ("bad align"));
1545 	KASSERT(align >= count, ("align < count"));
1546 #ifdef INVARIANTS
1547 	for (run = 0; run < count; run++)
1548 		KASSERT(irqs[run] < num_io_irqs, ("Invalid IRQ %u at index %u",
1549 		    irqs[run], run));
1550 #endif
1551 
1552 	/*
1553 	 * Search for 'count' free vectors.  As with apic_alloc_vector(),
1554 	 * this just uses a simple first fit algorithm.
1555 	 */
1556 	run = 0;
1557 	first = 0;
1558 	mtx_lock_spin(&icu_lock);
1559 	for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
1560 		/* Vector is in use, end run. */
1561 		if (lapics[apic_id].la_ioint_irqs[vector] != IRQ_FREE) {
1562 			run = 0;
1563 			first = 0;
1564 			continue;
1565 		}
1566 
1567 		/* Start a new run if run == 0 and vector is aligned. */
1568 		if (run == 0) {
1569 			if (((vector + APIC_IO_INTS) & (align - 1)) != 0)
1570 				continue;
1571 			first = vector;
1572 		}
1573 		run++;
1574 
1575 		/* Keep looping if the run isn't long enough yet. */
1576 		if (run < count)
1577 			continue;
1578 
1579 		/* Found a run, assign IRQs and return the first vector. */
1580 		for (vector = 0; vector < count; vector++)
1581 			lapics[apic_id].la_ioint_irqs[first + vector] =
1582 			    irqs[vector];
1583 		mtx_unlock_spin(&icu_lock);
1584 		return (first + APIC_IO_INTS);
1585 	}
1586 	mtx_unlock_spin(&icu_lock);
1587 	printf("APIC: Couldn't find APIC vectors for %u IRQs\n", count);
1588 	return (0);
1589 }
1590 
1591 /*
1592  * Enable a vector for a particular apic_id.  Since all lapics share idt
1593  * entries and ioint_handlers this enables the vector on all lapics.  lapics
1594  * which do not have the vector configured would report spurious interrupts
1595  * should it fire.
1596  */
1597 void
apic_enable_vector(u_int apic_id,u_int vector)1598 apic_enable_vector(u_int apic_id, u_int vector)
1599 {
1600 
1601 	KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1602 	KASSERT(ioint_handlers[vector / 32] != NULL,
1603 	    ("No ISR handler for vector %u", vector));
1604 #ifdef KDTRACE_HOOKS
1605 	KASSERT(vector != IDT_DTRACE_RET,
1606 	    ("Attempt to overwrite DTrace entry"));
1607 #endif
1608 	setidt(vector, (pti ? ioint_pti_handlers : ioint_handlers)[vector / 32],
1609 	    SDT_APIC, SEL_KPL, GSEL_APIC);
1610 }
1611 
1612 void
apic_disable_vector(u_int apic_id,u_int vector)1613 apic_disable_vector(u_int apic_id, u_int vector)
1614 {
1615 
1616 	KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1617 #ifdef KDTRACE_HOOKS
1618 	KASSERT(vector != IDT_DTRACE_RET,
1619 	    ("Attempt to overwrite DTrace entry"));
1620 #endif
1621 	KASSERT(ioint_handlers[vector / 32] != NULL,
1622 	    ("No ISR handler for vector %u", vector));
1623 #ifdef notyet
1624 	/*
1625 	 * We can not currently clear the idt entry because other cpus
1626 	 * may have a valid vector at this offset.
1627 	 */
1628 	setidt(vector, pti ? &IDTVEC(rsvd_pti) : &IDTVEC(rsvd), SDT_APIC,
1629 	    SEL_KPL, GSEL_APIC);
1630 #endif
1631 }
1632 
1633 /* Release an APIC vector when it's no longer in use. */
1634 void
apic_free_vector(u_int apic_id,u_int vector,u_int irq)1635 apic_free_vector(u_int apic_id, u_int vector, u_int irq)
1636 {
1637 	struct thread *td;
1638 
1639 	KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1640 	    vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1641 	    ("Vector %u does not map to an IRQ line", vector));
1642 	KASSERT(irq < num_io_irqs, ("Invalid IRQ %u", irq));
1643 	KASSERT(lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] ==
1644 	    irq, ("IRQ mismatch"));
1645 #ifdef KDTRACE_HOOKS
1646 	KASSERT(vector != IDT_DTRACE_RET,
1647 	    ("Attempt to overwrite DTrace entry"));
1648 #endif
1649 
1650 	/*
1651 	 * Bind us to the cpu that owned the vector before freeing it so
1652 	 * we don't lose an interrupt delivery race.
1653 	 */
1654 	td = curthread;
1655 	if (!rebooting) {
1656 		thread_lock(td);
1657 		if (sched_is_bound(td))
1658 			panic("apic_free_vector: Thread already bound.\n");
1659 		sched_bind(td, apic_cpuid(apic_id));
1660 		thread_unlock(td);
1661 	}
1662 	mtx_lock_spin(&icu_lock);
1663 	lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] = IRQ_FREE;
1664 	mtx_unlock_spin(&icu_lock);
1665 	if (!rebooting) {
1666 		thread_lock(td);
1667 		sched_unbind(td);
1668 		thread_unlock(td);
1669 	}
1670 }
1671 
1672 /* Map an IDT vector (APIC) to an IRQ (interrupt source). */
1673 static u_int
apic_idt_to_irq(u_int apic_id,u_int vector)1674 apic_idt_to_irq(u_int apic_id, u_int vector)
1675 {
1676 	int irq;
1677 
1678 	KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1679 	    vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1680 	    ("Vector %u does not map to an IRQ line", vector));
1681 #ifdef KDTRACE_HOOKS
1682 	KASSERT(vector != IDT_DTRACE_RET,
1683 	    ("Attempt to overwrite DTrace entry"));
1684 #endif
1685 	irq = lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS];
1686 	if (irq < 0)
1687 		irq = 0;
1688 	return (irq);
1689 }
1690 
1691 #ifdef DDB
1692 /*
1693  * Dump data about APIC IDT vector mappings.
1694  */
DB_SHOW_COMMAND_FLAGS(apic,db_show_apic,DB_CMD_MEMSAFE)1695 DB_SHOW_COMMAND_FLAGS(apic, db_show_apic, DB_CMD_MEMSAFE)
1696 {
1697 	struct intsrc *isrc;
1698 	int i, verbose;
1699 	u_int apic_id;
1700 	u_int irq;
1701 
1702 	if (strcmp(modif, "vv") == 0)
1703 		verbose = 2;
1704 	else if (strcmp(modif, "v") == 0)
1705 		verbose = 1;
1706 	else
1707 		verbose = 0;
1708 	for (apic_id = 0; apic_id <= max_apic_id; apic_id++) {
1709 		if (lapics[apic_id].la_present == 0)
1710 			continue;
1711 		db_printf("Interrupts bound to lapic %u\n", apic_id);
1712 		for (i = 0; i < APIC_NUM_IOINTS + 1 && !db_pager_quit; i++) {
1713 			irq = lapics[apic_id].la_ioint_irqs[i];
1714 			if (irq == IRQ_FREE || irq == IRQ_SYSCALL)
1715 				continue;
1716 #ifdef KDTRACE_HOOKS
1717 			if (irq == IRQ_DTRACE_RET)
1718 				continue;
1719 #endif
1720 #ifdef XENHVM
1721 			if (irq == IRQ_EVTCHN)
1722 				continue;
1723 #endif
1724 			db_printf("vec 0x%2x -> ", i + APIC_IO_INTS);
1725 			if (irq == IRQ_TIMER)
1726 				db_printf("lapic timer\n");
1727 			else if (irq < num_io_irqs) {
1728 				isrc = intr_lookup_source(irq);
1729 				if (isrc == NULL || verbose == 0)
1730 					db_printf("IRQ %u\n", irq);
1731 				else
1732 					db_dump_intr_event(isrc->is_event,
1733 					    verbose == 2);
1734 			} else
1735 				db_printf("IRQ %u ???\n", irq);
1736 		}
1737 	}
1738 }
1739 
1740 static void
dump_mask(const char * prefix,uint32_t v,int base)1741 dump_mask(const char *prefix, uint32_t v, int base)
1742 {
1743 	int i, first;
1744 
1745 	first = 1;
1746 	for (i = 0; i < 32; i++)
1747 		if (v & (1 << i)) {
1748 			if (first) {
1749 				db_printf("%s:", prefix);
1750 				first = 0;
1751 			}
1752 			db_printf(" %02x", base + i);
1753 		}
1754 	if (!first)
1755 		db_printf("\n");
1756 }
1757 
1758 /* Show info from the lapic regs for this CPU. */
DB_SHOW_COMMAND_FLAGS(lapic,db_show_lapic,DB_CMD_MEMSAFE)1759 DB_SHOW_COMMAND_FLAGS(lapic, db_show_lapic, DB_CMD_MEMSAFE)
1760 {
1761 	uint32_t v;
1762 
1763 	db_printf("lapic ID = %d\n", lapic_id());
1764 	v = lapic_read32(LAPIC_VERSION);
1765 	db_printf("version  = %d.%d\n", (v & APIC_VER_VERSION) >> 4,
1766 	    v & 0xf);
1767 	db_printf("max LVT  = %d\n", (v & APIC_VER_MAXLVT) >> MAXLVTSHIFT);
1768 	v = lapic_read32(LAPIC_SVR);
1769 	db_printf("SVR      = %02x (%s)\n", v & APIC_SVR_VECTOR,
1770 	    v & APIC_SVR_ENABLE ? "enabled" : "disabled");
1771 	db_printf("TPR      = %02x\n", lapic_read32(LAPIC_TPR));
1772 
1773 #define dump_field(prefix, regn, index)					\
1774 	dump_mask(__XSTRING(prefix ## index), 				\
1775 	    lapic_read32(LAPIC_ ## regn ## index),			\
1776 	    index * 32)
1777 
1778 	db_printf("In-service Interrupts:\n");
1779 	dump_field(isr, ISR, 0);
1780 	dump_field(isr, ISR, 1);
1781 	dump_field(isr, ISR, 2);
1782 	dump_field(isr, ISR, 3);
1783 	dump_field(isr, ISR, 4);
1784 	dump_field(isr, ISR, 5);
1785 	dump_field(isr, ISR, 6);
1786 	dump_field(isr, ISR, 7);
1787 
1788 	db_printf("TMR Interrupts:\n");
1789 	dump_field(tmr, TMR, 0);
1790 	dump_field(tmr, TMR, 1);
1791 	dump_field(tmr, TMR, 2);
1792 	dump_field(tmr, TMR, 3);
1793 	dump_field(tmr, TMR, 4);
1794 	dump_field(tmr, TMR, 5);
1795 	dump_field(tmr, TMR, 6);
1796 	dump_field(tmr, TMR, 7);
1797 
1798 	db_printf("IRR Interrupts:\n");
1799 	dump_field(irr, IRR, 0);
1800 	dump_field(irr, IRR, 1);
1801 	dump_field(irr, IRR, 2);
1802 	dump_field(irr, IRR, 3);
1803 	dump_field(irr, IRR, 4);
1804 	dump_field(irr, IRR, 5);
1805 	dump_field(irr, IRR, 6);
1806 	dump_field(irr, IRR, 7);
1807 
1808 #undef dump_field
1809 }
1810 #endif
1811 
1812 /*
1813  * APIC probing support code.  This includes code to manage enumerators.
1814  */
1815 
1816 static SLIST_HEAD(, apic_enumerator) enumerators =
1817 	SLIST_HEAD_INITIALIZER(enumerators);
1818 static struct apic_enumerator *best_enum;
1819 
1820 void
apic_register_enumerator(struct apic_enumerator * enumerator)1821 apic_register_enumerator(struct apic_enumerator *enumerator)
1822 {
1823 #ifdef INVARIANTS
1824 	struct apic_enumerator *apic_enum;
1825 
1826 	SLIST_FOREACH(apic_enum, &enumerators, apic_next) {
1827 		if (apic_enum == enumerator)
1828 			panic("%s: Duplicate register of %s", __func__,
1829 			    enumerator->apic_name);
1830 	}
1831 #endif
1832 	SLIST_INSERT_HEAD(&enumerators, enumerator, apic_next);
1833 }
1834 
1835 /*
1836  * We have to look for CPU's very, very early because certain subsystems
1837  * want to know how many CPU's we have extremely early on in the boot
1838  * process.
1839  */
1840 static void
apic_init(void * dummy __unused)1841 apic_init(void *dummy __unused)
1842 {
1843 	struct apic_enumerator *enumerator;
1844 	int retval, best;
1845 
1846 	/* We only support built in local APICs. */
1847 	if (!(cpu_feature & CPUID_APIC))
1848 		return;
1849 
1850 	/* Don't probe if APIC mode is disabled. */
1851 	if (resource_disabled("apic", 0))
1852 		return;
1853 
1854 	/* Probe all the enumerators to find the best match. */
1855 	best_enum = NULL;
1856 	best = 0;
1857 	SLIST_FOREACH(enumerator, &enumerators, apic_next) {
1858 		retval = enumerator->apic_probe();
1859 		if (retval > 0)
1860 			continue;
1861 		if (best_enum == NULL || best < retval) {
1862 			best_enum = enumerator;
1863 			best = retval;
1864 		}
1865 	}
1866 	if (best_enum == NULL) {
1867 		if (bootverbose)
1868 			printf("APIC: Could not find any APICs.\n");
1869 #ifndef DEV_ATPIC
1870 		panic("running without device atpic requires a local APIC");
1871 #endif
1872 		return;
1873 	}
1874 
1875 	if (bootverbose)
1876 		printf("APIC: Using the %s enumerator.\n",
1877 		    best_enum->apic_name);
1878 
1879 #ifdef I686_CPU
1880 	/*
1881 	 * To work around an errata, we disable the local APIC on some
1882 	 * CPUs during early startup.  We need to turn the local APIC back
1883 	 * on on such CPUs now.
1884 	 */
1885 	ppro_reenable_apic();
1886 #endif
1887 
1888 	/* Probe the CPU's in the system. */
1889 	retval = best_enum->apic_probe_cpus();
1890 	if (retval != 0)
1891 		printf("%s: Failed to probe CPUs: returned %d\n",
1892 		    best_enum->apic_name, retval);
1893 
1894 }
1895 SYSINIT(apic_init, SI_SUB_TUNABLES - 1, SI_ORDER_SECOND, apic_init, NULL);
1896 
1897 /*
1898  * Setup the local APIC.  We have to do this prior to starting up the APs
1899  * in the SMP case.
1900  */
1901 static void
apic_setup_local(void * dummy __unused)1902 apic_setup_local(void *dummy __unused)
1903 {
1904 	int retval;
1905 
1906 	if (best_enum == NULL)
1907 		return;
1908 
1909 	lapics = malloc(sizeof(*lapics) * (max_apic_id + 1), M_LAPIC,
1910 	    M_WAITOK | M_ZERO);
1911 
1912 	/* Initialize the local APIC. */
1913 	retval = best_enum->apic_setup_local();
1914 	if (retval != 0)
1915 		printf("%s: Failed to setup the local APIC: returned %d\n",
1916 		    best_enum->apic_name, retval);
1917 }
1918 SYSINIT(apic_setup_local, SI_SUB_CPU, SI_ORDER_SECOND, apic_setup_local, NULL);
1919 
1920 /*
1921  * Setup the I/O APICs.
1922  */
1923 static void
apic_setup_io(void * dummy __unused)1924 apic_setup_io(void *dummy __unused)
1925 {
1926 	int retval;
1927 
1928 	if (best_enum == NULL)
1929 		return;
1930 
1931 	/*
1932 	 * Local APIC must be registered before other PICs and pseudo PICs
1933 	 * for proper suspend/resume order.
1934 	 */
1935 	intr_register_pic(&lapic_pic);
1936 
1937 	retval = best_enum->apic_setup_io();
1938 	if (retval != 0)
1939 		printf("%s: Failed to setup I/O APICs: returned %d\n",
1940 		    best_enum->apic_name, retval);
1941 
1942 	/*
1943 	 * Finish setting up the local APIC on the BSP once we know
1944 	 * how to properly program the LINT pins.  In particular, this
1945 	 * enables the EOI suppression mode, if LAPIC supports it and
1946 	 * user did not disable the mode.
1947 	 */
1948 	lapic_setup(1);
1949 	if (bootverbose)
1950 		lapic_dump("BSP");
1951 
1952 	/* Enable the MSI "pic". */
1953 	msi_init();
1954 
1955 #ifdef XENHVM
1956 	xen_intr_alloc_irqs();
1957 #endif
1958 }
1959 SYSINIT(apic_setup_io, SI_SUB_INTR, SI_ORDER_THIRD, apic_setup_io, NULL);
1960 
1961 #ifdef SMP
1962 /*
1963  * Inter Processor Interrupt functions.  The lapic_ipi_*() functions are
1964  * private to the MD code.  The public interface for the rest of the
1965  * kernel is defined in mp_machdep.c.
1966  */
1967 
1968 /*
1969  * Wait delay microseconds for IPI to be sent.  If delay is -1, we
1970  * wait forever.
1971  */
1972 int
lapic_ipi_wait(int delay)1973 lapic_ipi_wait(int delay)
1974 {
1975 	uint64_t rx;
1976 
1977 	/* LAPIC_ICR.APIC_DELSTAT_MASK is undefined in x2APIC mode */
1978 	if (x2apic_mode)
1979 		return (1);
1980 
1981 	for (rx = 0; delay == -1 || rx < lapic_ipi_wait_mult * delay; rx++) {
1982 		if ((lapic_read_icr_lo() & APIC_DELSTAT_MASK) ==
1983 		    APIC_DELSTAT_IDLE)
1984 			return (1);
1985 		ia32_pause();
1986 	}
1987 	return (0);
1988 }
1989 
1990 void
lapic_ipi_raw(register_t icrlo,u_int dest)1991 lapic_ipi_raw(register_t icrlo, u_int dest)
1992 {
1993 	uint32_t icrhi;
1994 
1995 	/* XXX: Need more sanity checking of icrlo? */
1996 	KASSERT(x2apic_mode || lapic_map != NULL,
1997 	    ("%s called too early", __func__));
1998 	KASSERT(x2apic_mode ||
1999 	    (dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
2000 	    ("%s: invalid dest field", __func__));
2001 	KASSERT((icrlo & APIC_ICRLO_RESV_MASK) == 0,
2002 	    ("%s: reserved bits set in ICR LO register", __func__));
2003 
2004 	if ((icrlo & APIC_DEST_MASK) == APIC_DEST_DESTFLD) {
2005 		if (x2apic_mode)
2006 			icrhi = dest;
2007 		else
2008 			icrhi = dest << APIC_ID_SHIFT;
2009 		lapic_write_icr(icrhi, icrlo);
2010 	} else {
2011 		lapic_write_icr_lo(icrlo);
2012 	}
2013 }
2014 
2015 #ifdef DETECT_DEADLOCK
2016 #define	AFTER_SPIN	50
2017 #endif
2018 
2019 static void
native_lapic_ipi_vectored(u_int vector,int dest)2020 native_lapic_ipi_vectored(u_int vector, int dest)
2021 {
2022 	register_t icrlo, destfield;
2023 
2024 	KASSERT((vector & ~APIC_VECTOR_MASK) == 0,
2025 	    ("%s: invalid vector %d", __func__, vector));
2026 
2027 	destfield = 0;
2028 	switch (dest) {
2029 	case APIC_IPI_DEST_SELF:
2030 		if (x2apic_mode && vector < IPI_NMI_FIRST) {
2031 			lapic_write_self_ipi(vector);
2032 			return;
2033 		}
2034 		icrlo = APIC_DEST_SELF;
2035 		break;
2036 	case APIC_IPI_DEST_ALL:
2037 		icrlo = APIC_DEST_ALLISELF;
2038 		break;
2039 	case APIC_IPI_DEST_OTHERS:
2040 		icrlo = APIC_DEST_ALLESELF;
2041 		break;
2042 	default:
2043 		icrlo = 0;
2044 		KASSERT(x2apic_mode ||
2045 		    (dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
2046 		    ("%s: invalid destination 0x%x", __func__, dest));
2047 		destfield = dest;
2048 	}
2049 
2050 	/*
2051 	 * NMI IPIs are just fake vectors used to send a NMI.  Use special rules
2052 	 * regarding NMIs if passed, otherwise specify the vector.
2053 	 */
2054 	if (vector >= IPI_NMI_FIRST)
2055 		icrlo |= APIC_DELMODE_NMI;
2056 	else
2057 		icrlo |= vector | APIC_DELMODE_FIXED;
2058 	icrlo |= APIC_DESTMODE_PHY | APIC_TRIGMOD_EDGE | APIC_LEVEL_ASSERT;
2059 
2060 	/* Wait for an earlier IPI to finish. */
2061 	if (!lapic_ipi_wait(lapic_ds_idle_timeout)) {
2062 		if (KERNEL_PANICKED())
2063 			return;
2064 		else
2065 			panic("APIC: Previous IPI is stuck");
2066 	}
2067 
2068 	lapic_ipi_raw(icrlo, destfield);
2069 
2070 #ifdef DETECT_DEADLOCK
2071 	/* Wait for IPI to be delivered. */
2072 	if (!lapic_ipi_wait(AFTER_SPIN)) {
2073 #ifdef needsattention
2074 		/*
2075 		 * XXX FIXME:
2076 		 *
2077 		 * The above function waits for the message to actually be
2078 		 * delivered.  It breaks out after an arbitrary timeout
2079 		 * since the message should eventually be delivered (at
2080 		 * least in theory) and that if it wasn't we would catch
2081 		 * the failure with the check above when the next IPI is
2082 		 * sent.
2083 		 *
2084 		 * We could skip this wait entirely, EXCEPT it probably
2085 		 * protects us from other routines that assume that the
2086 		 * message was delivered and acted upon when this function
2087 		 * returns.
2088 		 */
2089 		printf("APIC: IPI might be stuck\n");
2090 #else /* !needsattention */
2091 		/* Wait until mesage is sent without a timeout. */
2092 		while (lapic_read_icr_lo() & APIC_DELSTAT_PEND)
2093 			ia32_pause();
2094 #endif /* needsattention */
2095 	}
2096 #endif /* DETECT_DEADLOCK */
2097 }
2098 
2099 void (*ipi_vectored)(u_int, int) = &native_lapic_ipi_vectored;
2100 #endif /* SMP */
2101 
2102 /*
2103  * Since the IDT is shared by all CPUs the IPI slot update needs to be globally
2104  * visible.
2105  *
2106  * Consider the case where an IPI is generated immediately after allocation:
2107  *     vector = lapic_ipi_alloc(ipifunc);
2108  *     ipi_selected(other_cpus, vector);
2109  *
2110  * In xAPIC mode a write to ICR_LO has serializing semantics because the
2111  * APIC page is mapped as an uncached region. In x2APIC mode there is an
2112  * explicit 'mfence' before the ICR MSR is written. Therefore in both cases
2113  * the IDT slot update is globally visible before the IPI is delivered.
2114  */
2115 int
lapic_ipi_alloc(inthand_t * ipifunc)2116 lapic_ipi_alloc(inthand_t *ipifunc)
2117 {
2118 	struct gate_descriptor *ip;
2119 	long func;
2120 	int idx, vector;
2121 
2122 	KASSERT(ipifunc != &IDTVEC(rsvd) && ipifunc != &IDTVEC(rsvd_pti),
2123 	    ("invalid ipifunc %p", ipifunc));
2124 
2125 	vector = -1;
2126 	mtx_lock_spin(&icu_lock);
2127 	for (idx = IPI_DYN_FIRST; idx <= IPI_DYN_LAST; idx++) {
2128 		ip = &idt[idx];
2129 		func = (ip->gd_hioffset << 16) | ip->gd_looffset;
2130 #ifdef __i386__
2131 		func -= setidt_disp;
2132 #endif
2133 		if ((!pti && func == (uintptr_t)&IDTVEC(rsvd)) ||
2134 		    (pti && func == (uintptr_t)&IDTVEC(rsvd_pti))) {
2135 			vector = idx;
2136 			setidt(vector, ipifunc, SDT_APIC, SEL_KPL, GSEL_APIC);
2137 			break;
2138 		}
2139 	}
2140 	mtx_unlock_spin(&icu_lock);
2141 	return (vector);
2142 }
2143 
2144 void
lapic_ipi_free(int vector)2145 lapic_ipi_free(int vector)
2146 {
2147 	struct gate_descriptor *ip;
2148 	long func __diagused;
2149 
2150 	KASSERT(vector >= IPI_DYN_FIRST && vector <= IPI_DYN_LAST,
2151 	    ("%s: invalid vector %d", __func__, vector));
2152 
2153 	mtx_lock_spin(&icu_lock);
2154 	ip = &idt[vector];
2155 	func = (ip->gd_hioffset << 16) | ip->gd_looffset;
2156 #ifdef __i386__
2157 	func -= setidt_disp;
2158 #endif
2159 	KASSERT(func != (uintptr_t)&IDTVEC(rsvd) &&
2160 	    func != (uintptr_t)&IDTVEC(rsvd_pti),
2161 	    ("invalid idtfunc %#lx", func));
2162 	setidt(vector, pti ? &IDTVEC(rsvd_pti) : &IDTVEC(rsvd), SDT_APIC,
2163 	    SEL_KPL, GSEL_APIC);
2164 	mtx_unlock_spin(&icu_lock);
2165 }
2166