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