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