2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1996, by Steve Passe
6 * Copyright (c) 2003 John Baldwin <jhb@FreeBSD.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
33 * Local APIC support on Pentium and later processors.
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include "opt_atpic.h"
40 #include "opt_hwpmc_hooks.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
47 #include <sys/kernel.h>
49 #include <sys/malloc.h>
50 #include <sys/mutex.h>
53 #include <sys/sched.h>
55 #include <sys/sysctl.h>
56 #include <sys/timeet.h>
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>
69 #include <machine/md_var.h>
70 #include <machine/smp.h>
71 #include <machine/specialreg.h>
75 #include <sys/interrupt.h>
80 #define SDT_APIC SDT_SYSIGT
83 #define SDT_APIC SDT_SYS386IGT
84 #define GSEL_APIC GSEL(GCODE_SEL, SEL_KPL)
87 static MALLOC_DEFINE(M_LAPIC, "local_apic", "Local APIC items");
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);
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
102 #define IRQ_SYSCALL -3
103 #define IRQ_DTRACE_RET -4
104 #define IRQ_EVTCHN -5
106 enum lat_timer_mode {
108 LAT_MODE_PERIODIC = 1,
109 LAT_MODE_ONESHOT = 2,
110 LAT_MODE_DEADLINE = 3,
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.
118 * Local APICs can also send interrupts to each other thus providing the
119 * mechanism for IPIs.
123 u_int lvt_edgetrigger:1;
124 u_int lvt_activehi:1;
132 struct lvt la_lvts[APIC_LVT_MAX + 1];
133 struct lvt la_elvts[APIC_ELVT_MAX + 1];
136 u_int la_cluster_id:2;
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];
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 */
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 },
166 static inthand_t *ioint_handlers[] = {
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 */
177 static inthand_t *ioint_pti_handlers[] = {
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 */
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
193 extern inthand_t IDTVEC(rsvd_pti), IDTVEC(rsvd);
195 volatile char *lapic_map;
196 vm_paddr_t lapic_paddr;
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;
203 static uint64_t lapic_ipi_wait_mult;
205 unsigned int max_apic_id;
207 SYSCTL_NODE(_hw, OID_AUTO, apic, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
209 SYSCTL_INT(_hw_apic, OID_AUTO, x2apic_mode, CTLFLAG_RD, &x2apic_mode, 0, "");
210 SYSCTL_INT(_hw_apic, OID_AUTO, eoi_suppression, CTLFLAG_RD,
211 &lapic_eoi_suppression, 0, "");
212 SYSCTL_INT(_hw_apic, OID_AUTO, timer_tsc_deadline, CTLFLAG_RD,
213 &lapic_timer_tsc_deadline, 0, "");
215 static void lapic_calibrate_initcount(struct lapic *la);
216 static void lapic_calibrate_deadline(struct lapic *la);
219 lapic_read32(enum LAPIC_REGISTERS reg)
224 res = rdmsr32(MSR_APIC_000 + reg);
226 res = *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL);
232 lapic_write32(enum LAPIC_REGISTERS reg, uint32_t val)
238 wrmsr(MSR_APIC_000 + reg, val);
240 *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL) = val;
245 lapic_write32_nofence(enum LAPIC_REGISTERS reg, uint32_t val)
249 wrmsr(MSR_APIC_000 + reg, val);
251 *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL) = val;
257 lapic_read_icr_lo(void)
260 return (lapic_read32(LAPIC_ICR_LO));
264 lapic_write_icr(uint32_t vhi, uint32_t vlo)
270 v = ((uint64_t)vhi << 32) | vlo;
272 wrmsr(MSR_APIC_000 + LAPIC_ICR_LO, v);
274 saveintr = intr_disable();
275 lapic_write32(LAPIC_ICR_HI, vhi);
276 lapic_write32(LAPIC_ICR_LO, vlo);
277 intr_restore(saveintr);
282 lapic_write_icr_lo(uint32_t vlo)
287 wrmsr(MSR_APIC_000 + LAPIC_ICR_LO, vlo);
289 lapic_write32(LAPIC_ICR_LO, vlo);
294 lapic_write_self_ipi(uint32_t vector)
297 KASSERT(x2apic_mode, ("SELF IPI write in xAPIC mode"));
298 wrmsr(MSR_APIC_000 + LAPIC_SELF_IPI, vector);
303 native_lapic_enable_x2apic(void)
307 apic_base = rdmsr(MSR_APICBASE);
308 apic_base |= APICBASE_X2APIC | APICBASE_ENABLED;
309 wrmsr(MSR_APICBASE, apic_base);
313 native_lapic_is_x2apic(void)
317 apic_base = rdmsr(MSR_APICBASE);
318 return ((apic_base & (APICBASE_X2APIC | APICBASE_ENABLED)) ==
319 (APICBASE_X2APIC | APICBASE_ENABLED));
322 static void lapic_enable(void);
323 static void lapic_resume(struct pic *pic, bool suspend_cancelled);
324 static void lapic_timer_oneshot(struct lapic *);
325 static void lapic_timer_oneshot_nointr(struct lapic *, uint32_t);
326 static void lapic_timer_periodic(struct lapic *);
327 static void lapic_timer_deadline(struct lapic *);
328 static void lapic_timer_stop(struct lapic *);
329 static void lapic_timer_set_divisor(u_int divisor);
330 static uint32_t lvt_mode(struct lapic *la, u_int pin, uint32_t value);
331 static int lapic_et_start(struct eventtimer *et,
332 sbintime_t first, sbintime_t period);
333 static int lapic_et_stop(struct eventtimer *et);
334 static u_int apic_idt_to_irq(u_int apic_id, u_int vector);
335 static void lapic_set_tpr(u_int vector);
337 struct pic lapic_pic = { .pic_resume = lapic_resume };
339 /* Forward declarations for apic_ops */
340 static void native_lapic_create(u_int apic_id, int boot_cpu);
341 static void native_lapic_init(vm_paddr_t addr);
342 static void native_lapic_xapic_mode(void);
343 static void native_lapic_setup(int boot);
344 static void native_lapic_dump(const char *str);
345 static void native_lapic_disable(void);
346 static void native_lapic_eoi(void);
347 static int native_lapic_id(void);
348 static int native_lapic_intr_pending(u_int vector);
349 static u_int native_apic_cpuid(u_int apic_id);
350 static u_int native_apic_alloc_vector(u_int apic_id, u_int irq);
351 static u_int native_apic_alloc_vectors(u_int apic_id, u_int *irqs,
352 u_int count, u_int align);
353 static void native_apic_disable_vector(u_int apic_id, u_int vector);
354 static void native_apic_enable_vector(u_int apic_id, u_int vector);
355 static void native_apic_free_vector(u_int apic_id, u_int vector, u_int irq);
356 static void native_lapic_set_logical_id(u_int apic_id, u_int cluster,
358 static int native_lapic_enable_pmc(void);
359 static void native_lapic_disable_pmc(void);
360 static void native_lapic_reenable_pmc(void);
361 static void native_lapic_enable_cmc(void);
362 static int native_lapic_enable_mca_elvt(void);
363 static int native_lapic_set_lvt_mask(u_int apic_id, u_int lvt,
365 static int native_lapic_set_lvt_mode(u_int apic_id, u_int lvt,
367 static int native_lapic_set_lvt_polarity(u_int apic_id, u_int lvt,
368 enum intr_polarity pol);
369 static int native_lapic_set_lvt_triggermode(u_int apic_id, u_int lvt,
370 enum intr_trigger trigger);
372 static void native_lapic_ipi_raw(register_t icrlo, u_int dest);
373 static void native_lapic_ipi_vectored(u_int vector, int dest);
374 static int native_lapic_ipi_wait(int delay);
376 static int native_lapic_ipi_alloc(inthand_t *ipifunc);
377 static void native_lapic_ipi_free(int vector);
379 struct apic_ops apic_ops = {
380 .create = native_lapic_create,
381 .init = native_lapic_init,
382 .xapic_mode = native_lapic_xapic_mode,
383 .is_x2apic = native_lapic_is_x2apic,
384 .setup = native_lapic_setup,
385 .dump = native_lapic_dump,
386 .disable = native_lapic_disable,
387 .eoi = native_lapic_eoi,
388 .id = native_lapic_id,
389 .intr_pending = native_lapic_intr_pending,
390 .set_logical_id = native_lapic_set_logical_id,
391 .cpuid = native_apic_cpuid,
392 .alloc_vector = native_apic_alloc_vector,
393 .alloc_vectors = native_apic_alloc_vectors,
394 .enable_vector = native_apic_enable_vector,
395 .disable_vector = native_apic_disable_vector,
396 .free_vector = native_apic_free_vector,
397 .enable_pmc = native_lapic_enable_pmc,
398 .disable_pmc = native_lapic_disable_pmc,
399 .reenable_pmc = native_lapic_reenable_pmc,
400 .enable_cmc = native_lapic_enable_cmc,
401 .enable_mca_elvt = native_lapic_enable_mca_elvt,
403 .ipi_raw = native_lapic_ipi_raw,
404 .ipi_vectored = native_lapic_ipi_vectored,
405 .ipi_wait = native_lapic_ipi_wait,
407 .ipi_alloc = native_lapic_ipi_alloc,
408 .ipi_free = native_lapic_ipi_free,
409 .set_lvt_mask = native_lapic_set_lvt_mask,
410 .set_lvt_mode = native_lapic_set_lvt_mode,
411 .set_lvt_polarity = native_lapic_set_lvt_polarity,
412 .set_lvt_triggermode = native_lapic_set_lvt_triggermode,
416 lvt_mode_impl(struct lapic *la, struct lvt *lvt, u_int pin, uint32_t value)
419 value &= ~(APIC_LVT_M | APIC_LVT_TM | APIC_LVT_IIPP | APIC_LVT_DM |
421 if (lvt->lvt_edgetrigger == 0)
422 value |= APIC_LVT_TM;
423 if (lvt->lvt_activehi == 0)
424 value |= APIC_LVT_IIPP_INTALO;
427 value |= lvt->lvt_mode;
428 switch (lvt->lvt_mode) {
429 case APIC_LVT_DM_NMI:
430 case APIC_LVT_DM_SMI:
431 case APIC_LVT_DM_INIT:
432 case APIC_LVT_DM_EXTINT:
433 if (!lvt->lvt_edgetrigger && bootverbose) {
434 printf("lapic%u: Forcing LINT%u to edge trigger\n",
436 value &= ~APIC_LVT_TM;
438 /* Use a vector of 0. */
440 case APIC_LVT_DM_FIXED:
441 value |= lvt->lvt_vector;
444 panic("bad APIC LVT delivery mode: %#x\n", value);
450 lvt_mode(struct lapic *la, u_int pin, uint32_t value)
454 KASSERT(pin <= APIC_LVT_MAX,
455 ("%s: pin %u out of range", __func__, pin));
456 if (la->la_lvts[pin].lvt_active)
457 lvt = &la->la_lvts[pin];
461 return (lvt_mode_impl(la, lvt, pin, value));
465 elvt_mode(struct lapic *la, u_int idx, uint32_t value)
469 KASSERT(idx <= APIC_ELVT_MAX,
470 ("%s: idx %u out of range", __func__, idx));
472 elvt = &la->la_elvts[idx];
473 KASSERT(elvt->lvt_active, ("%s: ELVT%u is not active", __func__, idx));
474 KASSERT(elvt->lvt_edgetrigger,
475 ("%s: ELVT%u is not edge triggered", __func__, idx));
476 KASSERT(elvt->lvt_activehi,
477 ("%s: ELVT%u is not active high", __func__, idx));
478 return (lvt_mode_impl(la, elvt, idx, value));
482 * Map the local APIC and setup necessary interrupt vectors.
485 native_lapic_init(vm_paddr_t addr)
488 uint64_t r, r1, r2, rx;
495 * Enable x2APIC mode if possible. Map the local APIC
498 * Keep the LAPIC registers page mapped uncached for x2APIC
499 * mode too, to have direct map page attribute set to
500 * uncached. This is needed to work around CPU errata present
501 * on all Intel processors.
503 KASSERT(trunc_page(addr) == addr,
504 ("local APIC not aligned on a page boundary"));
506 lapic_map = pmap_mapdev(addr, PAGE_SIZE);
508 native_lapic_enable_x2apic();
512 /* Setup the spurious interrupt handler. */
513 setidt(APIC_SPURIOUS_INT, IDTVEC(spuriousint), SDT_APIC, SEL_KPL,
516 /* Perform basic initialization of the BSP's local APIC. */
519 /* Set BSP's per-CPU local APIC ID. */
520 PCPU_SET(apic_id, lapic_id());
522 /* Local APIC timer interrupt. */
523 setidt(APIC_TIMER_INT, pti ? IDTVEC(timerint_pti) : IDTVEC(timerint),
524 SDT_APIC, SEL_KPL, GSEL_APIC);
526 /* Local APIC error interrupt. */
527 setidt(APIC_ERROR_INT, pti ? IDTVEC(errorint_pti) : IDTVEC(errorint),
528 SDT_APIC, SEL_KPL, GSEL_APIC);
530 /* XXX: Thermal interrupt */
532 /* Local APIC CMCI. */
533 setidt(APIC_CMC_INT, pti ? IDTVEC(cmcint_pti) : IDTVEC(cmcint),
534 SDT_APIC, SEL_KPL, GSEL_APIC);
536 if ((resource_int_value("apic", 0, "clock", &i) != 0 || i != 0)) {
537 /* Set if APIC timer runs in C3. */
538 arat = (cpu_power_eax & CPUTPM1_ARAT);
540 bzero(&lapic_et, sizeof(lapic_et));
541 lapic_et.et_name = "LAPIC";
542 lapic_et.et_flags = ET_FLAGS_PERIODIC | ET_FLAGS_ONESHOT |
544 lapic_et.et_quality = 600;
546 lapic_et.et_flags |= ET_FLAGS_C3STOP;
547 lapic_et.et_quality = 100;
549 if ((cpu_feature & CPUID_TSC) != 0 &&
550 (cpu_feature2 & CPUID2_TSCDLT) != 0 &&
551 tsc_is_invariant && tsc_freq != 0) {
552 lapic_timer_tsc_deadline = 1;
553 TUNABLE_INT_FETCH("hw.lapic_tsc_deadline",
554 &lapic_timer_tsc_deadline);
557 lapic_et.et_frequency = 0;
558 /* We don't know frequency yet, so trying to guess. */
559 lapic_et.et_min_period = 0x00001000LL;
560 lapic_et.et_max_period = SBT_1S;
561 lapic_et.et_start = lapic_et_start;
562 lapic_et.et_stop = lapic_et_stop;
563 lapic_et.et_priv = NULL;
564 et_register(&lapic_et);
568 * Set lapic_eoi_suppression after lapic_enable(), to not
569 * enable suppression in the hardware prematurely. Note that
570 * we by default enable suppression even when system only has
571 * one IO-APIC, since EOI is broadcasted to all APIC agents,
572 * including CPUs, otherwise.
574 * It seems that at least some KVM versions report
575 * EOI_SUPPRESSION bit, but auto-EOI does not work.
577 ver = lapic_read32(LAPIC_VERSION);
578 if ((ver & APIC_VER_EOI_SUPPRESSION) != 0) {
579 lapic_eoi_suppression = 1;
580 if (vm_guest == VM_GUEST_KVM) {
583 "KVM -- disabling lapic eoi suppression\n");
584 lapic_eoi_suppression = 0;
586 TUNABLE_INT_FETCH("hw.lapic_eoi_suppression",
587 &lapic_eoi_suppression);
593 * Calibrate the busy loop waiting for IPI ack in xAPIC mode.
594 * lapic_ipi_wait_mult contains the number of iterations which
595 * approximately delay execution for 1 microsecond (the
596 * argument to native_lapic_ipi_wait() is in microseconds).
598 * We assume that TSC is present and already measured.
599 * Possible TSC frequency jumps are irrelevant to the
600 * calibration loop below, the CPU clock management code is
601 * not yet started, and we do not enter sleep states.
603 KASSERT((cpu_feature & CPUID_TSC) != 0 && tsc_freq != 0,
604 ("TSC not initialized"));
607 for (rx = 0; rx < LOOPS; rx++) {
608 (void)lapic_read_icr_lo();
612 r1 = tsc_freq * LOOPS;
614 lapic_ipi_wait_mult = r1 >= r2 ? r1 / r2 : 1;
616 printf("LAPIC: ipi_wait() us multiplier %ju (r %ju "
617 "tsc %ju)\n", (uintmax_t)lapic_ipi_wait_mult,
618 (uintmax_t)r, (uintmax_t)tsc_freq);
626 * Create a local APIC instance.
629 native_lapic_create(u_int apic_id, int boot_cpu)
633 if (apic_id > max_apic_id) {
634 printf("APIC: Ignoring local APIC with ID %d\n", apic_id);
636 panic("Can't ignore BSP");
639 KASSERT(!lapics[apic_id].la_present, ("duplicate local APIC %u",
643 * Assume no local LVT overrides and a cluster of 0 and
644 * intra-cluster ID of 0.
646 lapics[apic_id].la_present = 1;
647 lapics[apic_id].la_id = apic_id;
648 for (i = 0; i <= APIC_LVT_MAX; i++) {
649 lapics[apic_id].la_lvts[i] = lvts[i];
650 lapics[apic_id].la_lvts[i].lvt_active = 0;
652 for (i = 0; i <= APIC_ELVT_MAX; i++) {
653 lapics[apic_id].la_elvts[i] = elvts[i];
654 lapics[apic_id].la_elvts[i].lvt_active = 0;
656 for (i = 0; i <= APIC_NUM_IOINTS; i++)
657 lapics[apic_id].la_ioint_irqs[i] = IRQ_FREE;
658 lapics[apic_id].la_ioint_irqs[IDT_SYSCALL - APIC_IO_INTS] = IRQ_SYSCALL;
659 lapics[apic_id].la_ioint_irqs[APIC_TIMER_INT - APIC_IO_INTS] =
662 lapics[apic_id].la_ioint_irqs[IDT_DTRACE_RET - APIC_IO_INTS] =
666 lapics[apic_id].la_ioint_irqs[IDT_EVTCHN - APIC_IO_INTS] = IRQ_EVTCHN;
671 cpu_add(apic_id, boot_cpu);
675 static inline uint32_t
676 amd_read_ext_features(void)
680 if (cpu_vendor_id != CPU_VENDOR_AMD &&
681 cpu_vendor_id != CPU_VENDOR_HYGON)
683 version = lapic_read32(LAPIC_VERSION);
684 if ((version & APIC_VER_AMD_EXT_SPACE) != 0)
685 return (lapic_read32(LAPIC_EXT_FEATURES));
690 static inline uint32_t
691 amd_read_elvt_count(void)
696 extf = amd_read_ext_features();
697 count = (extf & APIC_EXTF_ELVT_MASK) >> APIC_EXTF_ELVT_SHIFT;
698 count = min(count, APIC_ELVT_MAX + 1);
703 * Dump contents of local APIC registers
706 native_lapic_dump(const char* str)
714 version = lapic_read32(LAPIC_VERSION);
715 maxlvt = (version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
716 printf("cpu%d %s:\n", PCPU_GET(cpuid), str);
717 printf(" ID: 0x%08x VER: 0x%08x LDR: 0x%08x DFR: 0x%08x",
718 lapic_read32(LAPIC_ID), version,
719 lapic_read32(LAPIC_LDR), x2apic_mode ? 0 : lapic_read32(LAPIC_DFR));
720 if ((cpu_feature2 & CPUID2_X2APIC) != 0)
721 printf(" x2APIC: %d", x2apic_mode);
722 printf("\n lint0: 0x%08x lint1: 0x%08x TPR: 0x%08x SVR: 0x%08x\n",
723 lapic_read32(LAPIC_LVT_LINT0), lapic_read32(LAPIC_LVT_LINT1),
724 lapic_read32(LAPIC_TPR), lapic_read32(LAPIC_SVR));
725 printf(" timer: 0x%08x therm: 0x%08x err: 0x%08x",
726 lapic_read32(LAPIC_LVT_TIMER), lapic_read32(LAPIC_LVT_THERMAL),
727 lapic_read32(LAPIC_LVT_ERROR));
728 if (maxlvt >= APIC_LVT_PMC)
729 printf(" pmc: 0x%08x", lapic_read32(LAPIC_LVT_PCINT));
731 if (maxlvt >= APIC_LVT_CMCI)
732 printf(" cmci: 0x%08x\n", lapic_read32(LAPIC_LVT_CMCI));
733 extf = amd_read_ext_features();
735 printf(" AMD ext features: 0x%08x\n", extf);
736 elvt_count = amd_read_elvt_count();
737 for (i = 0; i < elvt_count; i++)
738 printf(" AMD elvt%d: 0x%08x\n", i,
739 lapic_read32(LAPIC_EXT_LVT0 + i));
744 native_lapic_xapic_mode(void)
748 saveintr = intr_disable();
750 native_lapic_enable_x2apic();
751 intr_restore(saveintr);
755 native_lapic_setup(int boot)
764 saveintr = intr_disable();
766 la = &lapics[lapic_id()];
767 KASSERT(la->la_present, ("missing APIC structure"));
768 version = lapic_read32(LAPIC_VERSION);
769 maxlvt = (version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
771 /* Initialize the TPR to allow all interrupts. */
774 /* Setup spurious vector and enable the local APIC. */
777 /* Program LINT[01] LVT entries. */
778 lapic_write32(LAPIC_LVT_LINT0, lvt_mode(la, APIC_LVT_LINT0,
779 lapic_read32(LAPIC_LVT_LINT0)));
780 lapic_write32(LAPIC_LVT_LINT1, lvt_mode(la, APIC_LVT_LINT1,
781 lapic_read32(LAPIC_LVT_LINT1)));
783 /* Program the PMC LVT entry if present. */
784 if (maxlvt >= APIC_LVT_PMC) {
785 lapic_write32(LAPIC_LVT_PCINT, lvt_mode(la, APIC_LVT_PMC,
789 /* Program timer LVT. */
790 la->lvt_timer_base = lvt_mode(la, APIC_LVT_TIMER,
791 lapic_read32(LAPIC_LVT_TIMER));
792 la->lvt_timer_last = la->lvt_timer_base;
793 lapic_write32(LAPIC_LVT_TIMER, la->lvt_timer_base);
795 /* Calibrate the timer parameters using BSP. */
796 if (boot && IS_BSP()) {
797 lapic_calibrate_initcount(la);
798 if (lapic_timer_tsc_deadline)
799 lapic_calibrate_deadline(la);
802 /* Setup the timer if configured. */
803 if (la->la_timer_mode != LAT_MODE_UNDEF) {
804 KASSERT(la->la_timer_period != 0, ("lapic%u: zero divisor",
806 switch (la->la_timer_mode) {
807 case LAT_MODE_PERIODIC:
808 lapic_timer_set_divisor(lapic_timer_divisor);
809 lapic_timer_periodic(la);
811 case LAT_MODE_ONESHOT:
812 lapic_timer_set_divisor(lapic_timer_divisor);
813 lapic_timer_oneshot(la);
815 case LAT_MODE_DEADLINE:
816 lapic_timer_deadline(la);
819 panic("corrupted la_timer_mode %p %d", la,
824 /* Program error LVT and clear any existing errors. */
825 lapic_write32(LAPIC_LVT_ERROR, lvt_mode(la, APIC_LVT_ERROR,
826 lapic_read32(LAPIC_LVT_ERROR)));
827 lapic_write32(LAPIC_ESR, 0);
829 /* XXX: Thermal LVT */
831 /* Program the CMCI LVT entry if present. */
832 if (maxlvt >= APIC_LVT_CMCI) {
833 lapic_write32(LAPIC_LVT_CMCI, lvt_mode(la, APIC_LVT_CMCI,
834 lapic_read32(LAPIC_LVT_CMCI)));
837 elvt_count = amd_read_elvt_count();
838 for (i = 0; i < elvt_count; i++) {
839 if (la->la_elvts[i].lvt_active)
840 lapic_write32(LAPIC_EXT_LVT0 + i,
841 elvt_mode(la, i, lapic_read32(LAPIC_EXT_LVT0 + i)));
844 intr_restore(saveintr);
848 native_lapic_intrcnt(void *dummy __unused)
852 char buf[MAXCOMLEN + 1];
854 /* If there are no APICs, skip this function. */
858 STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
859 la = &lapics[pc->pc_apic_id];
863 snprintf(buf, sizeof(buf), "cpu%d:timer", pc->pc_cpuid);
864 intrcnt_add(buf, &la->la_timer_count);
867 SYSINIT(native_lapic_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, native_lapic_intrcnt,
871 native_lapic_reenable_pmc(void)
876 value = lapic_read32(LAPIC_LVT_PCINT);
877 value &= ~APIC_LVT_M;
878 lapic_write32(LAPIC_LVT_PCINT, value);
884 lapic_update_pmc(void *dummy)
888 la = &lapics[lapic_id()];
889 lapic_write32(LAPIC_LVT_PCINT, lvt_mode(la, APIC_LVT_PMC,
890 lapic_read32(LAPIC_LVT_PCINT)));
895 native_lapic_enable_pmc(void)
900 /* Fail if the local APIC is not present. */
901 if (!x2apic_mode && lapic_map == NULL)
904 /* Fail if the PMC LVT is not present. */
905 maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
906 if (maxlvt < APIC_LVT_PMC)
909 lvts[APIC_LVT_PMC].lvt_masked = 0;
911 #ifdef EARLY_AP_STARTUP
912 MPASS(mp_ncpus == 1 || smp_started);
913 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
917 * If hwpmc was loaded at boot time then the APs may not be
918 * started yet. In that case, don't forward the request to
919 * them as they will program the lvt when they start.
922 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
925 lapic_update_pmc(NULL);
934 native_lapic_disable_pmc(void)
939 /* Fail if the local APIC is not present. */
940 if (!x2apic_mode && lapic_map == NULL)
943 /* Fail if the PMC LVT is not present. */
944 maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
945 if (maxlvt < APIC_LVT_PMC)
948 lvts[APIC_LVT_PMC].lvt_masked = 1;
951 /* The APs should always be started when hwpmc is unloaded. */
952 KASSERT(mp_ncpus == 1 || smp_started, ("hwpmc unloaded too early"));
954 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
959 lapic_calibrate_initcount(struct lapic *la)
963 /* Start off with a divisor of 2 (power on reset default). */
964 lapic_timer_divisor = 2;
965 /* Try to calibrate the local APIC timer. */
967 lapic_timer_set_divisor(lapic_timer_divisor);
968 lapic_timer_oneshot_nointr(la, APIC_TIMER_MAX_COUNT);
970 value = APIC_TIMER_MAX_COUNT - lapic_read32(LAPIC_CCR_TIMER);
971 if (value != APIC_TIMER_MAX_COUNT)
973 lapic_timer_divisor <<= 1;
974 } while (lapic_timer_divisor <= 128);
975 if (lapic_timer_divisor > 128)
976 panic("lapic: Divisor too big");
978 printf("lapic: Divisor %lu, Frequency %lu Hz\n",
979 lapic_timer_divisor, value);
985 lapic_calibrate_deadline(struct lapic *la __unused)
989 printf("lapic: deadline tsc mode, Frequency %ju Hz\n",
990 (uintmax_t)tsc_freq);
995 lapic_change_mode(struct eventtimer *et, struct lapic *la,
996 enum lat_timer_mode newmode)
999 if (la->la_timer_mode == newmode)
1002 case LAT_MODE_PERIODIC:
1003 lapic_timer_set_divisor(lapic_timer_divisor);
1004 et->et_frequency = count_freq;
1006 case LAT_MODE_DEADLINE:
1007 et->et_frequency = tsc_freq;
1009 case LAT_MODE_ONESHOT:
1010 lapic_timer_set_divisor(lapic_timer_divisor);
1011 et->et_frequency = count_freq;
1014 panic("lapic_change_mode %d", newmode);
1016 la->la_timer_mode = newmode;
1017 et->et_min_period = (0x00000002LLU << 32) / et->et_frequency;
1018 et->et_max_period = (0xfffffffeLLU << 32) / et->et_frequency;
1022 lapic_et_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
1026 la = &lapics[PCPU_GET(apic_id)];
1028 lapic_change_mode(et, la, LAT_MODE_PERIODIC);
1029 la->la_timer_period = ((uint32_t)et->et_frequency * period) >>
1031 lapic_timer_periodic(la);
1032 } else if (lapic_timer_tsc_deadline) {
1033 lapic_change_mode(et, la, LAT_MODE_DEADLINE);
1034 la->la_timer_period = (et->et_frequency * first) >> 32;
1035 lapic_timer_deadline(la);
1037 lapic_change_mode(et, la, LAT_MODE_ONESHOT);
1038 la->la_timer_period = ((uint32_t)et->et_frequency * first) >>
1040 lapic_timer_oneshot(la);
1046 lapic_et_stop(struct eventtimer *et)
1050 la = &lapics[PCPU_GET(apic_id)];
1051 lapic_timer_stop(la);
1052 la->la_timer_mode = LAT_MODE_UNDEF;
1057 native_lapic_disable(void)
1061 /* Software disable the local APIC. */
1062 value = lapic_read32(LAPIC_SVR);
1063 value &= ~APIC_SVR_SWEN;
1064 lapic_write32(LAPIC_SVR, value);
1072 /* Program the spurious vector to enable the local APIC. */
1073 value = lapic_read32(LAPIC_SVR);
1074 value &= ~(APIC_SVR_VECTOR | APIC_SVR_FOCUS);
1075 value |= APIC_SVR_FEN | APIC_SVR_SWEN | APIC_SPURIOUS_INT;
1076 if (lapic_eoi_suppression)
1077 value |= APIC_SVR_EOI_SUPPRESSION;
1078 lapic_write32(LAPIC_SVR, value);
1081 /* Reset the local APIC on the BSP during resume. */
1083 lapic_resume(struct pic *pic, bool suspend_cancelled)
1090 native_lapic_id(void)
1094 KASSERT(x2apic_mode || lapic_map != NULL, ("local APIC is not mapped"));
1095 v = lapic_read32(LAPIC_ID);
1097 v >>= APIC_ID_SHIFT;
1102 native_lapic_intr_pending(u_int vector)
1107 * The IRR registers are an array of registers each of which
1108 * only describes 32 interrupts in the low 32 bits. Thus, we
1109 * divide the vector by 32 to get the register index.
1110 * Finally, we modulus the vector by 32 to determine the
1111 * individual bit to test.
1113 irr = lapic_read32(LAPIC_IRR0 + vector / 32);
1114 return (irr & 1 << (vector % 32));
1118 native_lapic_set_logical_id(u_int apic_id, u_int cluster, u_int cluster_id)
1122 KASSERT(lapics[apic_id].la_present, ("%s: APIC %u doesn't exist",
1123 __func__, apic_id));
1124 KASSERT(cluster <= APIC_MAX_CLUSTER, ("%s: cluster %u too big",
1125 __func__, cluster));
1126 KASSERT(cluster_id <= APIC_MAX_INTRACLUSTER_ID,
1127 ("%s: intra cluster id %u too big", __func__, cluster_id));
1128 la = &lapics[apic_id];
1129 la->la_cluster = cluster;
1130 la->la_cluster_id = cluster_id;
1134 native_lapic_set_lvt_mask(u_int apic_id, u_int pin, u_char masked)
1137 if (pin > APIC_LVT_MAX)
1139 if (apic_id == APIC_ID_ALL) {
1140 lvts[pin].lvt_masked = masked;
1144 KASSERT(lapics[apic_id].la_present,
1145 ("%s: missing APIC %u", __func__, apic_id));
1146 lapics[apic_id].la_lvts[pin].lvt_masked = masked;
1147 lapics[apic_id].la_lvts[pin].lvt_active = 1;
1149 printf("lapic%u:", apic_id);
1152 printf(" LINT%u %s\n", pin, masked ? "masked" : "unmasked");
1157 native_lapic_set_lvt_mode(u_int apic_id, u_int pin, u_int32_t mode)
1161 if (pin > APIC_LVT_MAX)
1163 if (apic_id == APIC_ID_ALL) {
1168 KASSERT(lapics[apic_id].la_present,
1169 ("%s: missing APIC %u", __func__, apic_id));
1170 lvt = &lapics[apic_id].la_lvts[pin];
1171 lvt->lvt_active = 1;
1173 printf("lapic%u:", apic_id);
1175 lvt->lvt_mode = mode;
1177 case APIC_LVT_DM_NMI:
1178 case APIC_LVT_DM_SMI:
1179 case APIC_LVT_DM_INIT:
1180 case APIC_LVT_DM_EXTINT:
1181 lvt->lvt_edgetrigger = 1;
1182 lvt->lvt_activehi = 1;
1183 if (mode == APIC_LVT_DM_EXTINT)
1184 lvt->lvt_masked = 1;
1186 lvt->lvt_masked = 0;
1189 panic("Unsupported delivery mode: 0x%x\n", mode);
1192 printf(" Routing ");
1194 case APIC_LVT_DM_NMI:
1197 case APIC_LVT_DM_SMI:
1200 case APIC_LVT_DM_INIT:
1203 case APIC_LVT_DM_EXTINT:
1207 printf(" -> LINT%u\n", pin);
1213 native_lapic_set_lvt_polarity(u_int apic_id, u_int pin, enum intr_polarity pol)
1216 if (pin > APIC_LVT_MAX || pol == INTR_POLARITY_CONFORM)
1218 if (apic_id == APIC_ID_ALL) {
1219 lvts[pin].lvt_activehi = (pol == INTR_POLARITY_HIGH);
1223 KASSERT(lapics[apic_id].la_present,
1224 ("%s: missing APIC %u", __func__, apic_id));
1225 lapics[apic_id].la_lvts[pin].lvt_active = 1;
1226 lapics[apic_id].la_lvts[pin].lvt_activehi =
1227 (pol == INTR_POLARITY_HIGH);
1229 printf("lapic%u:", apic_id);
1232 printf(" LINT%u polarity: %s\n", pin,
1233 pol == INTR_POLARITY_HIGH ? "high" : "low");
1238 native_lapic_set_lvt_triggermode(u_int apic_id, u_int pin,
1239 enum intr_trigger trigger)
1242 if (pin > APIC_LVT_MAX || trigger == INTR_TRIGGER_CONFORM)
1244 if (apic_id == APIC_ID_ALL) {
1245 lvts[pin].lvt_edgetrigger = (trigger == INTR_TRIGGER_EDGE);
1249 KASSERT(lapics[apic_id].la_present,
1250 ("%s: missing APIC %u", __func__, apic_id));
1251 lapics[apic_id].la_lvts[pin].lvt_edgetrigger =
1252 (trigger == INTR_TRIGGER_EDGE);
1253 lapics[apic_id].la_lvts[pin].lvt_active = 1;
1255 printf("lapic%u:", apic_id);
1258 printf(" LINT%u trigger: %s\n", pin,
1259 trigger == INTR_TRIGGER_EDGE ? "edge" : "level");
1264 * Adjust the TPR of the current CPU so that it blocks all interrupts below
1265 * the passed in vector.
1268 lapic_set_tpr(u_int vector)
1271 lapic_write32(LAPIC_TPR, vector);
1275 tpr = lapic_read32(LAPIC_TPR) & ~APIC_TPR_PRIO;
1277 lapic_write32(LAPIC_TPR, tpr);
1282 native_lapic_eoi(void)
1285 lapic_write32_nofence(LAPIC_EOI, 0);
1289 lapic_handle_intr(int vector, struct trapframe *frame)
1291 struct intsrc *isrc;
1293 isrc = intr_lookup_source(apic_idt_to_irq(PCPU_GET(apic_id),
1295 intr_execute_handlers(isrc, frame);
1299 lapic_handle_timer(struct trapframe *frame)
1302 struct trapframe *oldframe;
1305 /* Send EOI first thing. */
1308 #if defined(SMP) && !defined(SCHED_ULE)
1310 * Don't do any accounting for the disabled HTT cores, since it
1311 * will provide misleading numbers for the userland.
1313 * No locking is necessary here, since even if we lose the race
1314 * when hlt_cpus_mask changes it is not a big deal, really.
1316 * Don't do that for ULE, since ULE doesn't consider hlt_cpus_mask
1317 * and unlike other schedulers it actually schedules threads to
1320 if (CPU_ISSET(PCPU_GET(cpuid), &hlt_cpus_mask))
1324 /* Look up our local APIC structure for the tick counters. */
1325 la = &lapics[PCPU_GET(apic_id)];
1326 (*la->la_timer_count)++;
1328 if (lapic_et.et_active) {
1330 td->td_intr_nesting_level++;
1331 oldframe = td->td_intr_frame;
1332 td->td_intr_frame = frame;
1333 lapic_et.et_event_cb(&lapic_et, lapic_et.et_arg);
1334 td->td_intr_frame = oldframe;
1335 td->td_intr_nesting_level--;
1341 lapic_timer_set_divisor(u_int divisor)
1344 KASSERT(powerof2(divisor), ("lapic: invalid divisor %u", divisor));
1345 KASSERT(ffs(divisor) <= nitems(lapic_timer_divisors),
1346 ("lapic: invalid divisor %u", divisor));
1347 lapic_write32(LAPIC_DCR_TIMER, lapic_timer_divisors[ffs(divisor) - 1]);
1351 lapic_timer_oneshot(struct lapic *la)
1355 value = la->lvt_timer_base;
1356 value &= ~(APIC_LVTT_TM | APIC_LVT_M);
1357 value |= APIC_LVTT_TM_ONE_SHOT;
1358 la->lvt_timer_last = value;
1359 lapic_write32(LAPIC_LVT_TIMER, value);
1360 lapic_write32(LAPIC_ICR_TIMER, la->la_timer_period);
1364 lapic_timer_oneshot_nointr(struct lapic *la, uint32_t count)
1368 value = la->lvt_timer_base;
1369 value &= ~APIC_LVTT_TM;
1370 value |= APIC_LVTT_TM_ONE_SHOT | APIC_LVT_M;
1371 la->lvt_timer_last = value;
1372 lapic_write32(LAPIC_LVT_TIMER, value);
1373 lapic_write32(LAPIC_ICR_TIMER, count);
1377 lapic_timer_periodic(struct lapic *la)
1381 value = la->lvt_timer_base;
1382 value &= ~(APIC_LVTT_TM | APIC_LVT_M);
1383 value |= APIC_LVTT_TM_PERIODIC;
1384 la->lvt_timer_last = value;
1385 lapic_write32(LAPIC_LVT_TIMER, value);
1386 lapic_write32(LAPIC_ICR_TIMER, la->la_timer_period);
1390 lapic_timer_deadline(struct lapic *la)
1394 value = la->lvt_timer_base;
1395 value &= ~(APIC_LVTT_TM | APIC_LVT_M);
1396 value |= APIC_LVTT_TM_TSCDLT;
1397 if (value != la->lvt_timer_last) {
1398 la->lvt_timer_last = value;
1399 lapic_write32_nofence(LAPIC_LVT_TIMER, value);
1403 wrmsr(MSR_TSC_DEADLINE, la->la_timer_period + rdtsc());
1407 lapic_timer_stop(struct lapic *la)
1411 if (la->la_timer_mode == LAT_MODE_DEADLINE) {
1412 wrmsr(MSR_TSC_DEADLINE, 0);
1415 value = la->lvt_timer_base;
1416 value &= ~APIC_LVTT_TM;
1417 value |= APIC_LVT_M;
1418 la->lvt_timer_last = value;
1419 lapic_write32(LAPIC_LVT_TIMER, value);
1424 lapic_handle_cmc(void)
1432 * Called from the mca_init() to activate the CMC interrupt if this CPU is
1433 * responsible for monitoring any MC banks for CMC events. Since mca_init()
1434 * is called prior to lapic_setup() during boot, this just needs to unmask
1435 * this CPU's LVT_CMCI entry.
1438 native_lapic_enable_cmc(void)
1443 if (!x2apic_mode && lapic_map == NULL)
1446 apic_id = PCPU_GET(apic_id);
1447 KASSERT(lapics[apic_id].la_present,
1448 ("%s: missing APIC %u", __func__, apic_id));
1449 lapics[apic_id].la_lvts[APIC_LVT_CMCI].lvt_masked = 0;
1450 lapics[apic_id].la_lvts[APIC_LVT_CMCI].lvt_active = 1;
1452 printf("lapic%u: CMCI unmasked\n", apic_id);
1456 native_lapic_enable_mca_elvt(void)
1463 if (lapic_map == NULL)
1467 apic_id = PCPU_GET(apic_id);
1468 KASSERT(lapics[apic_id].la_present,
1469 ("%s: missing APIC %u", __func__, apic_id));
1470 elvt_count = amd_read_elvt_count();
1471 if (elvt_count <= APIC_ELVT_MCA)
1474 value = lapic_read32(LAPIC_EXT_LVT0 + APIC_ELVT_MCA);
1475 if ((value & APIC_LVT_M) == 0) {
1477 printf("AMD MCE Thresholding Extended LVT is already active\n");
1478 return (APIC_ELVT_MCA);
1480 lapics[apic_id].la_elvts[APIC_ELVT_MCA].lvt_masked = 0;
1481 lapics[apic_id].la_elvts[APIC_ELVT_MCA].lvt_active = 1;
1483 printf("lapic%u: MCE Thresholding ELVT unmasked\n", apic_id);
1484 return (APIC_ELVT_MCA);
1488 lapic_handle_error(void)
1493 * Read the contents of the error status register. Write to
1494 * the register first before reading from it to force the APIC
1495 * to update its value to indicate any errors that have
1496 * occurred since the previous write to the register.
1498 lapic_write32(LAPIC_ESR, 0);
1499 esr = lapic_read32(LAPIC_ESR);
1501 printf("CPU%d: local APIC error 0x%x\n", PCPU_GET(cpuid), esr);
1506 native_apic_cpuid(u_int apic_id)
1509 return apic_cpuids[apic_id];
1515 /* Request a free IDT vector to be used by the specified IRQ. */
1517 native_apic_alloc_vector(u_int apic_id, u_int irq)
1521 KASSERT(irq < num_io_irqs, ("Invalid IRQ %u", irq));
1524 * Search for a free vector. Currently we just use a very simple
1525 * algorithm to find the first free vector.
1527 mtx_lock_spin(&icu_lock);
1528 for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
1529 if (lapics[apic_id].la_ioint_irqs[vector] != IRQ_FREE)
1531 lapics[apic_id].la_ioint_irqs[vector] = irq;
1532 mtx_unlock_spin(&icu_lock);
1533 return (vector + APIC_IO_INTS);
1535 mtx_unlock_spin(&icu_lock);
1540 * Request 'count' free contiguous IDT vectors to be used by 'count'
1541 * IRQs. 'count' must be a power of two and the vectors will be
1542 * aligned on a boundary of 'align'. If the request cannot be
1543 * satisfied, 0 is returned.
1546 native_apic_alloc_vectors(u_int apic_id, u_int *irqs, u_int count, u_int align)
1548 u_int first, run, vector;
1550 KASSERT(powerof2(count), ("bad count"));
1551 KASSERT(powerof2(align), ("bad align"));
1552 KASSERT(align >= count, ("align < count"));
1554 for (run = 0; run < count; run++)
1555 KASSERT(irqs[run] < num_io_irqs, ("Invalid IRQ %u at index %u",
1560 * Search for 'count' free vectors. As with apic_alloc_vector(),
1561 * this just uses a simple first fit algorithm.
1565 mtx_lock_spin(&icu_lock);
1566 for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
1568 /* Vector is in use, end run. */
1569 if (lapics[apic_id].la_ioint_irqs[vector] != IRQ_FREE) {
1575 /* Start a new run if run == 0 and vector is aligned. */
1577 if ((vector & (align - 1)) != 0)
1583 /* Keep looping if the run isn't long enough yet. */
1587 /* Found a run, assign IRQs and return the first vector. */
1588 for (vector = 0; vector < count; vector++)
1589 lapics[apic_id].la_ioint_irqs[first + vector] =
1591 mtx_unlock_spin(&icu_lock);
1592 return (first + APIC_IO_INTS);
1594 mtx_unlock_spin(&icu_lock);
1595 printf("APIC: Couldn't find APIC vectors for %u IRQs\n", count);
1600 * Enable a vector for a particular apic_id. Since all lapics share idt
1601 * entries and ioint_handlers this enables the vector on all lapics. lapics
1602 * which do not have the vector configured would report spurious interrupts
1606 native_apic_enable_vector(u_int apic_id, u_int vector)
1609 KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1610 KASSERT(ioint_handlers[vector / 32] != NULL,
1611 ("No ISR handler for vector %u", vector));
1612 #ifdef KDTRACE_HOOKS
1613 KASSERT(vector != IDT_DTRACE_RET,
1614 ("Attempt to overwrite DTrace entry"));
1616 setidt(vector, (pti ? ioint_pti_handlers : ioint_handlers)[vector / 32],
1617 SDT_APIC, SEL_KPL, GSEL_APIC);
1621 native_apic_disable_vector(u_int apic_id, u_int vector)
1624 KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1625 #ifdef KDTRACE_HOOKS
1626 KASSERT(vector != IDT_DTRACE_RET,
1627 ("Attempt to overwrite DTrace entry"));
1629 KASSERT(ioint_handlers[vector / 32] != NULL,
1630 ("No ISR handler for vector %u", vector));
1633 * We can not currently clear the idt entry because other cpus
1634 * may have a valid vector at this offset.
1636 setidt(vector, pti ? &IDTVEC(rsvd_pti) : &IDTVEC(rsvd), SDT_APIC,
1637 SEL_KPL, GSEL_APIC);
1641 /* Release an APIC vector when it's no longer in use. */
1643 native_apic_free_vector(u_int apic_id, u_int vector, u_int irq)
1647 KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1648 vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1649 ("Vector %u does not map to an IRQ line", vector));
1650 KASSERT(irq < num_io_irqs, ("Invalid IRQ %u", irq));
1651 KASSERT(lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] ==
1652 irq, ("IRQ mismatch"));
1653 #ifdef KDTRACE_HOOKS
1654 KASSERT(vector != IDT_DTRACE_RET,
1655 ("Attempt to overwrite DTrace entry"));
1659 * Bind us to the cpu that owned the vector before freeing it so
1660 * we don't lose an interrupt delivery race.
1665 if (sched_is_bound(td))
1666 panic("apic_free_vector: Thread already bound.\n");
1667 sched_bind(td, apic_cpuid(apic_id));
1670 mtx_lock_spin(&icu_lock);
1671 lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] = IRQ_FREE;
1672 mtx_unlock_spin(&icu_lock);
1680 /* Map an IDT vector (APIC) to an IRQ (interrupt source). */
1682 apic_idt_to_irq(u_int apic_id, u_int vector)
1686 KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1687 vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1688 ("Vector %u does not map to an IRQ line", vector));
1689 #ifdef KDTRACE_HOOKS
1690 KASSERT(vector != IDT_DTRACE_RET,
1691 ("Attempt to overwrite DTrace entry"));
1693 irq = lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS];
1701 * Dump data about APIC IDT vector mappings.
1703 DB_SHOW_COMMAND(apic, db_show_apic)
1705 struct intsrc *isrc;
1710 if (strcmp(modif, "vv") == 0)
1712 else if (strcmp(modif, "v") == 0)
1716 for (apic_id = 0; apic_id <= max_apic_id; apic_id++) {
1717 if (lapics[apic_id].la_present == 0)
1719 db_printf("Interrupts bound to lapic %u\n", apic_id);
1720 for (i = 0; i < APIC_NUM_IOINTS + 1 && !db_pager_quit; i++) {
1721 irq = lapics[apic_id].la_ioint_irqs[i];
1722 if (irq == IRQ_FREE || irq == IRQ_SYSCALL)
1724 #ifdef KDTRACE_HOOKS
1725 if (irq == IRQ_DTRACE_RET)
1729 if (irq == IRQ_EVTCHN)
1732 db_printf("vec 0x%2x -> ", i + APIC_IO_INTS);
1733 if (irq == IRQ_TIMER)
1734 db_printf("lapic timer\n");
1735 else if (irq < num_io_irqs) {
1736 isrc = intr_lookup_source(irq);
1737 if (isrc == NULL || verbose == 0)
1738 db_printf("IRQ %u\n", irq);
1740 db_dump_intr_event(isrc->is_event,
1743 db_printf("IRQ %u ???\n", irq);
1749 dump_mask(const char *prefix, uint32_t v, int base)
1754 for (i = 0; i < 32; i++)
1757 db_printf("%s:", prefix);
1760 db_printf(" %02x", base + i);
1766 /* Show info from the lapic regs for this CPU. */
1767 DB_SHOW_COMMAND(lapic, db_show_lapic)
1771 db_printf("lapic ID = %d\n", lapic_id());
1772 v = lapic_read32(LAPIC_VERSION);
1773 db_printf("version = %d.%d\n", (v & APIC_VER_VERSION) >> 4,
1775 db_printf("max LVT = %d\n", (v & APIC_VER_MAXLVT) >> MAXLVTSHIFT);
1776 v = lapic_read32(LAPIC_SVR);
1777 db_printf("SVR = %02x (%s)\n", v & APIC_SVR_VECTOR,
1778 v & APIC_SVR_ENABLE ? "enabled" : "disabled");
1779 db_printf("TPR = %02x\n", lapic_read32(LAPIC_TPR));
1781 #define dump_field(prefix, regn, index) \
1782 dump_mask(__XSTRING(prefix ## index), \
1783 lapic_read32(LAPIC_ ## regn ## index), \
1786 db_printf("In-service Interrupts:\n");
1787 dump_field(isr, ISR, 0);
1788 dump_field(isr, ISR, 1);
1789 dump_field(isr, ISR, 2);
1790 dump_field(isr, ISR, 3);
1791 dump_field(isr, ISR, 4);
1792 dump_field(isr, ISR, 5);
1793 dump_field(isr, ISR, 6);
1794 dump_field(isr, ISR, 7);
1796 db_printf("TMR Interrupts:\n");
1797 dump_field(tmr, TMR, 0);
1798 dump_field(tmr, TMR, 1);
1799 dump_field(tmr, TMR, 2);
1800 dump_field(tmr, TMR, 3);
1801 dump_field(tmr, TMR, 4);
1802 dump_field(tmr, TMR, 5);
1803 dump_field(tmr, TMR, 6);
1804 dump_field(tmr, TMR, 7);
1806 db_printf("IRR Interrupts:\n");
1807 dump_field(irr, IRR, 0);
1808 dump_field(irr, IRR, 1);
1809 dump_field(irr, IRR, 2);
1810 dump_field(irr, IRR, 3);
1811 dump_field(irr, IRR, 4);
1812 dump_field(irr, IRR, 5);
1813 dump_field(irr, IRR, 6);
1814 dump_field(irr, IRR, 7);
1821 * APIC probing support code. This includes code to manage enumerators.
1824 static SLIST_HEAD(, apic_enumerator) enumerators =
1825 SLIST_HEAD_INITIALIZER(enumerators);
1826 static struct apic_enumerator *best_enum;
1829 apic_register_enumerator(struct apic_enumerator *enumerator)
1832 struct apic_enumerator *apic_enum;
1834 SLIST_FOREACH(apic_enum, &enumerators, apic_next) {
1835 if (apic_enum == enumerator)
1836 panic("%s: Duplicate register of %s", __func__,
1837 enumerator->apic_name);
1840 SLIST_INSERT_HEAD(&enumerators, enumerator, apic_next);
1844 * We have to look for CPU's very, very early because certain subsystems
1845 * want to know how many CPU's we have extremely early on in the boot
1849 apic_init(void *dummy __unused)
1851 struct apic_enumerator *enumerator;
1854 /* We only support built in local APICs. */
1855 if (!(cpu_feature & CPUID_APIC))
1858 /* Don't probe if APIC mode is disabled. */
1859 if (resource_disabled("apic", 0))
1862 /* Probe all the enumerators to find the best match. */
1865 SLIST_FOREACH(enumerator, &enumerators, apic_next) {
1866 retval = enumerator->apic_probe();
1869 if (best_enum == NULL || best < retval) {
1870 best_enum = enumerator;
1874 if (best_enum == NULL) {
1876 printf("APIC: Could not find any APICs.\n");
1878 panic("running without device atpic requires a local APIC");
1884 printf("APIC: Using the %s enumerator.\n",
1885 best_enum->apic_name);
1889 * To work around an errata, we disable the local APIC on some
1890 * CPUs during early startup. We need to turn the local APIC back
1891 * on on such CPUs now.
1893 ppro_reenable_apic();
1896 /* Probe the CPU's in the system. */
1897 retval = best_enum->apic_probe_cpus();
1899 printf("%s: Failed to probe CPUs: returned %d\n",
1900 best_enum->apic_name, retval);
1903 SYSINIT(apic_init, SI_SUB_TUNABLES - 1, SI_ORDER_SECOND, apic_init, NULL);
1906 * Setup the local APIC. We have to do this prior to starting up the APs
1910 apic_setup_local(void *dummy __unused)
1914 if (best_enum == NULL)
1917 lapics = malloc(sizeof(*lapics) * (max_apic_id + 1), M_LAPIC,
1920 /* Initialize the local APIC. */
1921 retval = best_enum->apic_setup_local();
1923 printf("%s: Failed to setup the local APIC: returned %d\n",
1924 best_enum->apic_name, retval);
1926 SYSINIT(apic_setup_local, SI_SUB_CPU, SI_ORDER_SECOND, apic_setup_local, NULL);
1929 * Setup the I/O APICs.
1932 apic_setup_io(void *dummy __unused)
1936 if (best_enum == NULL)
1940 * Local APIC must be registered before other PICs and pseudo PICs
1941 * for proper suspend/resume order.
1943 intr_register_pic(&lapic_pic);
1945 retval = best_enum->apic_setup_io();
1947 printf("%s: Failed to setup I/O APICs: returned %d\n",
1948 best_enum->apic_name, retval);
1951 * Finish setting up the local APIC on the BSP once we know
1952 * how to properly program the LINT pins. In particular, this
1953 * enables the EOI suppression mode, if LAPIC supports it and
1954 * user did not disable the mode.
1960 /* Enable the MSI "pic". */
1961 init_ops.msi_init();
1964 xen_intr_alloc_irqs();
1967 SYSINIT(apic_setup_io, SI_SUB_INTR, SI_ORDER_THIRD, apic_setup_io, NULL);
1971 * Inter Processor Interrupt functions. The lapic_ipi_*() functions are
1972 * private to the MD code. The public interface for the rest of the
1973 * kernel is defined in mp_machdep.c.
1977 * Wait delay microseconds for IPI to be sent. If delay is -1, we
1981 native_lapic_ipi_wait(int delay)
1985 /* LAPIC_ICR.APIC_DELSTAT_MASK is undefined in x2APIC mode */
1989 for (rx = 0; delay == -1 || rx < lapic_ipi_wait_mult * delay; rx++) {
1990 if ((lapic_read_icr_lo() & APIC_DELSTAT_MASK) ==
1999 native_lapic_ipi_raw(register_t icrlo, u_int dest)
2003 /* XXX: Need more sanity checking of icrlo? */
2004 KASSERT(x2apic_mode || lapic_map != NULL,
2005 ("%s called too early", __func__));
2006 KASSERT(x2apic_mode ||
2007 (dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
2008 ("%s: invalid dest field", __func__));
2009 KASSERT((icrlo & APIC_ICRLO_RESV_MASK) == 0,
2010 ("%s: reserved bits set in ICR LO register", __func__));
2012 if ((icrlo & APIC_DEST_MASK) == APIC_DEST_DESTFLD) {
2016 icrhi = dest << APIC_ID_SHIFT;
2017 lapic_write_icr(icrhi, icrlo);
2019 lapic_write_icr_lo(icrlo);
2023 #define BEFORE_SPIN 50000
2024 #ifdef DETECT_DEADLOCK
2025 #define AFTER_SPIN 50
2029 native_lapic_ipi_vectored(u_int vector, int dest)
2031 register_t icrlo, destfield;
2033 KASSERT((vector & ~APIC_VECTOR_MASK) == 0,
2034 ("%s: invalid vector %d", __func__, vector));
2038 case APIC_IPI_DEST_SELF:
2039 if (x2apic_mode && vector < IPI_NMI_FIRST) {
2040 lapic_write_self_ipi(vector);
2043 icrlo = APIC_DEST_SELF;
2045 case APIC_IPI_DEST_ALL:
2046 icrlo = APIC_DEST_ALLISELF;
2048 case APIC_IPI_DEST_OTHERS:
2049 icrlo = APIC_DEST_ALLESELF;
2053 KASSERT(x2apic_mode ||
2054 (dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
2055 ("%s: invalid destination 0x%x", __func__, dest));
2060 * NMI IPIs are just fake vectors used to send a NMI. Use special rules
2061 * regarding NMIs if passed, otherwise specify the vector.
2063 if (vector >= IPI_NMI_FIRST)
2064 icrlo |= APIC_DELMODE_NMI;
2066 icrlo |= vector | APIC_DELMODE_FIXED;
2067 icrlo |= APIC_DESTMODE_PHY | APIC_TRIGMOD_EDGE | APIC_LEVEL_ASSERT;
2069 /* Wait for an earlier IPI to finish. */
2070 if (!lapic_ipi_wait(BEFORE_SPIN)) {
2071 if (KERNEL_PANICKED())
2074 panic("APIC: Previous IPI is stuck");
2077 lapic_ipi_raw(icrlo, destfield);
2079 #ifdef DETECT_DEADLOCK
2080 /* Wait for IPI to be delivered. */
2081 if (!lapic_ipi_wait(AFTER_SPIN)) {
2082 #ifdef needsattention
2086 * The above function waits for the message to actually be
2087 * delivered. It breaks out after an arbitrary timeout
2088 * since the message should eventually be delivered (at
2089 * least in theory) and that if it wasn't we would catch
2090 * the failure with the check above when the next IPI is
2093 * We could skip this wait entirely, EXCEPT it probably
2094 * protects us from other routines that assume that the
2095 * message was delivered and acted upon when this function
2098 printf("APIC: IPI might be stuck\n");
2099 #else /* !needsattention */
2100 /* Wait until mesage is sent without a timeout. */
2101 while (lapic_read_icr_lo() & APIC_DELSTAT_PEND)
2103 #endif /* needsattention */
2105 #endif /* DETECT_DEADLOCK */
2111 * Since the IDT is shared by all CPUs the IPI slot update needs to be globally
2114 * Consider the case where an IPI is generated immediately after allocation:
2115 * vector = lapic_ipi_alloc(ipifunc);
2116 * ipi_selected(other_cpus, vector);
2118 * In xAPIC mode a write to ICR_LO has serializing semantics because the
2119 * APIC page is mapped as an uncached region. In x2APIC mode there is an
2120 * explicit 'mfence' before the ICR MSR is written. Therefore in both cases
2121 * the IDT slot update is globally visible before the IPI is delivered.
2124 native_lapic_ipi_alloc(inthand_t *ipifunc)
2126 struct gate_descriptor *ip;
2130 KASSERT(ipifunc != &IDTVEC(rsvd) && ipifunc != &IDTVEC(rsvd_pti),
2131 ("invalid ipifunc %p", ipifunc));
2134 mtx_lock_spin(&icu_lock);
2135 for (idx = IPI_DYN_FIRST; idx <= IPI_DYN_LAST; idx++) {
2137 func = (ip->gd_hioffset << 16) | ip->gd_looffset;
2138 if ((!pti && func == (uintptr_t)&IDTVEC(rsvd)) ||
2139 (pti && func == (uintptr_t)&IDTVEC(rsvd_pti))) {
2141 setidt(vector, ipifunc, SDT_APIC, SEL_KPL, GSEL_APIC);
2145 mtx_unlock_spin(&icu_lock);
2150 native_lapic_ipi_free(int vector)
2152 struct gate_descriptor *ip;
2155 KASSERT(vector >= IPI_DYN_FIRST && vector <= IPI_DYN_LAST,
2156 ("%s: invalid vector %d", __func__, vector));
2158 mtx_lock_spin(&icu_lock);
2160 func = (ip->gd_hioffset << 16) | ip->gd_looffset;
2161 KASSERT(func != (uintptr_t)&IDTVEC(rsvd) &&
2162 func != (uintptr_t)&IDTVEC(rsvd_pti),
2163 ("invalid idtfunc %#lx", func));
2164 setidt(vector, pti ? &IDTVEC(rsvd_pti) : &IDTVEC(rsvd), SDT_APIC,
2165 SEL_KPL, GSEL_APIC);
2166 mtx_unlock_spin(&icu_lock);