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, 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, "");
214 static void lapic_calibrate_initcount(struct lapic *la);
215 static void lapic_calibrate_deadline(struct lapic *la);
218 lapic_read32(enum LAPIC_REGISTERS reg)
223 res = rdmsr32(MSR_APIC_000 + reg);
225 res = *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL);
231 lapic_write32(enum LAPIC_REGISTERS reg, uint32_t val)
237 wrmsr(MSR_APIC_000 + reg, val);
239 *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL) = val;
244 lapic_write32_nofence(enum LAPIC_REGISTERS reg, uint32_t val)
248 wrmsr(MSR_APIC_000 + reg, val);
250 *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL) = val;
256 lapic_read_icr_lo(void)
259 return (lapic_read32(LAPIC_ICR_LO));
263 lapic_write_icr(uint32_t vhi, uint32_t vlo)
269 v = ((uint64_t)vhi << 32) | vlo;
271 wrmsr(MSR_APIC_000 + LAPIC_ICR_LO, v);
273 saveintr = intr_disable();
274 lapic_write32(LAPIC_ICR_HI, vhi);
275 lapic_write32(LAPIC_ICR_LO, vlo);
276 intr_restore(saveintr);
281 lapic_write_icr_lo(uint32_t vlo)
286 wrmsr(MSR_APIC_000 + LAPIC_ICR_LO, vlo);
288 lapic_write32(LAPIC_ICR_LO, vlo);
293 lapic_write_self_ipi(uint32_t vector)
296 KASSERT(x2apic_mode, ("SELF IPI write in xAPIC mode"));
297 wrmsr(MSR_APIC_000 + LAPIC_SELF_IPI, vector);
302 native_lapic_enable_x2apic(void)
306 apic_base = rdmsr(MSR_APICBASE);
307 apic_base |= APICBASE_X2APIC | APICBASE_ENABLED;
308 wrmsr(MSR_APICBASE, apic_base);
312 native_lapic_is_x2apic(void)
316 apic_base = rdmsr(MSR_APICBASE);
317 return ((apic_base & (APICBASE_X2APIC | APICBASE_ENABLED)) ==
318 (APICBASE_X2APIC | APICBASE_ENABLED));
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);
336 struct pic lapic_pic = { .pic_resume = lapic_resume };
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,
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,
364 static int native_lapic_set_lvt_mode(u_int apic_id, u_int lvt,
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);
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);
375 static int native_lapic_ipi_alloc(inthand_t *ipifunc);
376 static void native_lapic_ipi_free(int vector);
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,
402 .ipi_raw = native_lapic_ipi_raw,
403 .ipi_vectored = native_lapic_ipi_vectored,
404 .ipi_wait = native_lapic_ipi_wait,
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,
415 lvt_mode_impl(struct lapic *la, struct lvt *lvt, u_int pin, uint32_t value)
418 value &= ~(APIC_LVT_M | APIC_LVT_TM | APIC_LVT_IIPP | APIC_LVT_DM |
420 if (lvt->lvt_edgetrigger == 0)
421 value |= APIC_LVT_TM;
422 if (lvt->lvt_activehi == 0)
423 value |= APIC_LVT_IIPP_INTALO;
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",
435 value &= ~APIC_LVT_TM;
437 /* Use a vector of 0. */
439 case APIC_LVT_DM_FIXED:
440 value |= lvt->lvt_vector;
443 panic("bad APIC LVT delivery mode: %#x\n", value);
449 lvt_mode(struct lapic *la, u_int pin, uint32_t value)
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];
460 return (lvt_mode_impl(la, lvt, pin, value));
464 elvt_mode(struct lapic *la, u_int idx, uint32_t value)
468 KASSERT(idx <= APIC_ELVT_MAX,
469 ("%s: idx %u out of range", __func__, idx));
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));
481 * Map the local APIC and setup necessary interrupt vectors.
484 native_lapic_init(vm_paddr_t addr)
487 uint64_t r, r1, r2, rx;
494 * Enable x2APIC mode if possible. Map the local APIC
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.
502 KASSERT(trunc_page(addr) == addr,
503 ("local APIC not aligned on a page boundary"));
505 lapic_map = pmap_mapdev(addr, PAGE_SIZE);
507 native_lapic_enable_x2apic();
511 /* Setup the spurious interrupt handler. */
512 setidt(APIC_SPURIOUS_INT, IDTVEC(spuriousint), SDT_APIC, SEL_KPL,
515 /* Perform basic initialization of the BSP's local APIC. */
518 /* Set BSP's per-CPU local APIC ID. */
519 PCPU_SET(apic_id, lapic_id());
521 /* Local APIC timer interrupt. */
522 setidt(APIC_TIMER_INT, pti ? IDTVEC(timerint_pti) : IDTVEC(timerint),
523 SDT_APIC, SEL_KPL, GSEL_APIC);
525 /* Local APIC error interrupt. */
526 setidt(APIC_ERROR_INT, pti ? IDTVEC(errorint_pti) : IDTVEC(errorint),
527 SDT_APIC, SEL_KPL, GSEL_APIC);
529 /* XXX: Thermal interrupt */
531 /* Local APIC CMCI. */
532 setidt(APIC_CMC_INT, pti ? IDTVEC(cmcint_pti) : IDTVEC(cmcint),
533 SDT_APIC, SEL_KPL, GSEL_APIC);
535 if ((resource_int_value("apic", 0, "clock", &i) != 0 || i != 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)
542 } else if (cpu_vendor_id == CPU_VENDOR_AMD &&
543 CPUID_TO_FAMILY(cpu_id) >= 0x12) {
546 bzero(&lapic_et, sizeof(lapic_et));
547 lapic_et.et_name = "LAPIC";
548 lapic_et.et_flags = ET_FLAGS_PERIODIC | ET_FLAGS_ONESHOT |
550 lapic_et.et_quality = 600;
552 lapic_et.et_flags |= ET_FLAGS_C3STOP;
553 lapic_et.et_quality = 100;
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.lapic_tsc_deadline",
560 &lapic_timer_tsc_deadline);
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);
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.
580 * It seems that at least some KVM versions report
581 * EOI_SUPPRESSION bit, but auto-EOI does not work.
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) {
589 "KVM -- disabling lapic eoi suppression\n");
590 lapic_eoi_suppression = 0;
592 TUNABLE_INT_FETCH("hw.lapic_eoi_suppression",
593 &lapic_eoi_suppression);
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).
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.
609 KASSERT((cpu_feature & CPUID_TSC) != 0 && tsc_freq != 0,
610 ("TSC not initialized"));
613 for (rx = 0; rx < LOOPS; rx++) {
614 (void)lapic_read_icr_lo();
618 r1 = tsc_freq * LOOPS;
620 lapic_ipi_wait_mult = r1 >= r2 ? r1 / r2 : 1;
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);
632 * Create a local APIC instance.
635 native_lapic_create(u_int apic_id, int boot_cpu)
639 if (apic_id > max_apic_id) {
640 printf("APIC: Ignoring local APIC with ID %d\n", apic_id);
642 panic("Can't ignore BSP");
645 KASSERT(!lapics[apic_id].la_present, ("duplicate local APIC %u",
649 * Assume no local LVT overrides and a cluster of 0 and
650 * intra-cluster ID of 0.
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;
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;
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] =
668 lapics[apic_id].la_ioint_irqs[IDT_DTRACE_RET - APIC_IO_INTS] =
672 lapics[apic_id].la_ioint_irqs[IDT_EVTCHN - APIC_IO_INTS] = IRQ_EVTCHN;
677 cpu_add(apic_id, boot_cpu);
681 static inline uint32_t
682 amd_read_ext_features(void)
686 if (cpu_vendor_id != CPU_VENDOR_AMD &&
687 cpu_vendor_id != CPU_VENDOR_HYGON)
689 version = lapic_read32(LAPIC_VERSION);
690 if ((version & APIC_VER_AMD_EXT_SPACE) != 0)
691 return (lapic_read32(LAPIC_EXT_FEATURES));
696 static inline uint32_t
697 amd_read_elvt_count(void)
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);
709 * Dump contents of local APIC registers
712 native_lapic_dump(const char* str)
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));
737 if (maxlvt >= APIC_LVT_CMCI)
738 printf(" cmci: 0x%08x\n", lapic_read32(LAPIC_LVT_CMCI));
739 extf = amd_read_ext_features();
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));
750 native_lapic_xapic_mode(void)
754 saveintr = intr_disable();
756 native_lapic_enable_x2apic();
757 intr_restore(saveintr);
761 native_lapic_setup(int boot)
770 saveintr = intr_disable();
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;
777 /* Initialize the TPR to allow all interrupts. */
780 /* Setup spurious vector and enable the local APIC. */
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)));
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,
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);
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);
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",
812 switch (la->la_timer_mode) {
813 case LAT_MODE_PERIODIC:
814 lapic_timer_set_divisor(lapic_timer_divisor);
815 lapic_timer_periodic(la);
817 case LAT_MODE_ONESHOT:
818 lapic_timer_set_divisor(lapic_timer_divisor);
819 lapic_timer_oneshot(la);
821 case LAT_MODE_DEADLINE:
822 lapic_timer_deadline(la);
825 panic("corrupted la_timer_mode %p %d", la,
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);
835 /* XXX: Thermal LVT */
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)));
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)));
850 intr_restore(saveintr);
854 native_lapic_intrcnt(void *dummy __unused)
858 char buf[MAXCOMLEN + 1];
860 /* If there are no APICs, skip this function. */
864 STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
865 la = &lapics[pc->pc_apic_id];
869 snprintf(buf, sizeof(buf), "cpu%d:timer", pc->pc_cpuid);
870 intrcnt_add(buf, &la->la_timer_count);
873 SYSINIT(native_lapic_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, native_lapic_intrcnt,
877 native_lapic_reenable_pmc(void)
882 value = lapic_read32(LAPIC_LVT_PCINT);
883 value &= ~APIC_LVT_M;
884 lapic_write32(LAPIC_LVT_PCINT, value);
890 lapic_update_pmc(void *dummy)
894 la = &lapics[lapic_id()];
895 lapic_write32(LAPIC_LVT_PCINT, lvt_mode(la, APIC_LVT_PMC,
896 lapic_read32(LAPIC_LVT_PCINT)));
901 native_lapic_enable_pmc(void)
906 /* Fail if the local APIC is not present. */
907 if (!x2apic_mode && lapic_map == NULL)
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)
915 lvts[APIC_LVT_PMC].lvt_masked = 0;
917 #ifdef EARLY_AP_STARTUP
918 MPASS(mp_ncpus == 1 || smp_started);
919 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
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.
928 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
931 lapic_update_pmc(NULL);
940 native_lapic_disable_pmc(void)
945 /* Fail if the local APIC is not present. */
946 if (!x2apic_mode && lapic_map == NULL)
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)
954 lvts[APIC_LVT_PMC].lvt_masked = 1;
957 /* The APs should always be started when hwpmc is unloaded. */
958 KASSERT(mp_ncpus == 1 || smp_started, ("hwpmc unloaded too early"));
960 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
965 lapic_calibrate_initcount(struct lapic *la)
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. */
973 lapic_timer_set_divisor(lapic_timer_divisor);
974 lapic_timer_oneshot_nointr(la, APIC_TIMER_MAX_COUNT);
976 value = APIC_TIMER_MAX_COUNT - lapic_read32(LAPIC_CCR_TIMER);
977 if (value != APIC_TIMER_MAX_COUNT)
979 lapic_timer_divisor <<= 1;
980 } while (lapic_timer_divisor <= 128);
981 if (lapic_timer_divisor > 128)
982 panic("lapic: Divisor too big");
984 printf("lapic: Divisor %lu, Frequency %lu Hz\n",
985 lapic_timer_divisor, value);
991 lapic_calibrate_deadline(struct lapic *la __unused)
995 printf("lapic: deadline tsc mode, Frequency %ju Hz\n",
996 (uintmax_t)tsc_freq);
1001 lapic_change_mode(struct eventtimer *et, struct lapic *la,
1002 enum lat_timer_mode newmode)
1005 if (la->la_timer_mode == newmode)
1008 case LAT_MODE_PERIODIC:
1009 lapic_timer_set_divisor(lapic_timer_divisor);
1010 et->et_frequency = count_freq;
1012 case LAT_MODE_DEADLINE:
1013 et->et_frequency = tsc_freq;
1015 case LAT_MODE_ONESHOT:
1016 lapic_timer_set_divisor(lapic_timer_divisor);
1017 et->et_frequency = count_freq;
1020 panic("lapic_change_mode %d", newmode);
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;
1028 lapic_et_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
1032 la = &lapics[PCPU_GET(apic_id)];
1034 lapic_change_mode(et, la, LAT_MODE_PERIODIC);
1035 la->la_timer_period = ((uint32_t)et->et_frequency * period) >>
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);
1043 lapic_change_mode(et, la, LAT_MODE_ONESHOT);
1044 la->la_timer_period = ((uint32_t)et->et_frequency * first) >>
1046 lapic_timer_oneshot(la);
1052 lapic_et_stop(struct eventtimer *et)
1056 la = &lapics[PCPU_GET(apic_id)];
1057 lapic_timer_stop(la);
1058 la->la_timer_mode = LAT_MODE_UNDEF;
1063 native_lapic_disable(void)
1067 /* Software disable the local APIC. */
1068 value = lapic_read32(LAPIC_SVR);
1069 value &= ~APIC_SVR_SWEN;
1070 lapic_write32(LAPIC_SVR, value);
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);
1087 /* Reset the local APIC on the BSP during resume. */
1089 lapic_resume(struct pic *pic, bool suspend_cancelled)
1096 native_lapic_id(void)
1100 KASSERT(x2apic_mode || lapic_map != NULL, ("local APIC is not mapped"));
1101 v = lapic_read32(LAPIC_ID);
1103 v >>= APIC_ID_SHIFT;
1108 native_lapic_intr_pending(u_int vector)
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.
1119 irr = lapic_read32(LAPIC_IRR0 + vector / 32);
1120 return (irr & 1 << (vector % 32));
1124 native_lapic_set_logical_id(u_int apic_id, u_int cluster, u_int cluster_id)
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;
1140 native_lapic_set_lvt_mask(u_int apic_id, u_int pin, u_char masked)
1143 if (pin > APIC_LVT_MAX)
1145 if (apic_id == APIC_ID_ALL) {
1146 lvts[pin].lvt_masked = masked;
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;
1155 printf("lapic%u:", apic_id);
1158 printf(" LINT%u %s\n", pin, masked ? "masked" : "unmasked");
1163 native_lapic_set_lvt_mode(u_int apic_id, u_int pin, u_int32_t mode)
1167 if (pin > APIC_LVT_MAX)
1169 if (apic_id == APIC_ID_ALL) {
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;
1179 printf("lapic%u:", apic_id);
1181 lvt->lvt_mode = 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;
1192 lvt->lvt_masked = 0;
1195 panic("Unsupported delivery mode: 0x%x\n", mode);
1198 printf(" Routing ");
1200 case APIC_LVT_DM_NMI:
1203 case APIC_LVT_DM_SMI:
1206 case APIC_LVT_DM_INIT:
1209 case APIC_LVT_DM_EXTINT:
1213 printf(" -> LINT%u\n", pin);
1219 native_lapic_set_lvt_polarity(u_int apic_id, u_int pin, enum intr_polarity pol)
1222 if (pin > APIC_LVT_MAX || pol == INTR_POLARITY_CONFORM)
1224 if (apic_id == APIC_ID_ALL) {
1225 lvts[pin].lvt_activehi = (pol == INTR_POLARITY_HIGH);
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);
1235 printf("lapic%u:", apic_id);
1238 printf(" LINT%u polarity: %s\n", pin,
1239 pol == INTR_POLARITY_HIGH ? "high" : "low");
1244 native_lapic_set_lvt_triggermode(u_int apic_id, u_int pin,
1245 enum intr_trigger trigger)
1248 if (pin > APIC_LVT_MAX || trigger == INTR_TRIGGER_CONFORM)
1250 if (apic_id == APIC_ID_ALL) {
1251 lvts[pin].lvt_edgetrigger = (trigger == INTR_TRIGGER_EDGE);
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;
1261 printf("lapic%u:", apic_id);
1264 printf(" LINT%u trigger: %s\n", pin,
1265 trigger == INTR_TRIGGER_EDGE ? "edge" : "level");
1270 * Adjust the TPR of the current CPU so that it blocks all interrupts below
1271 * the passed in vector.
1274 lapic_set_tpr(u_int vector)
1277 lapic_write32(LAPIC_TPR, vector);
1281 tpr = lapic_read32(LAPIC_TPR) & ~APIC_TPR_PRIO;
1283 lapic_write32(LAPIC_TPR, tpr);
1288 native_lapic_eoi(void)
1291 lapic_write32_nofence(LAPIC_EOI, 0);
1295 lapic_handle_intr(int vector, struct trapframe *frame)
1297 struct intsrc *isrc;
1299 isrc = intr_lookup_source(apic_idt_to_irq(PCPU_GET(apic_id),
1301 intr_execute_handlers(isrc, frame);
1305 lapic_handle_timer(struct trapframe *frame)
1308 struct trapframe *oldframe;
1311 /* Send EOI first thing. */
1314 #if defined(SMP) && !defined(SCHED_ULE)
1316 * Don't do any accounting for the disabled HTT cores, since it
1317 * will provide misleading numbers for the userland.
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.
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
1326 if (CPU_ISSET(PCPU_GET(cpuid), &hlt_cpus_mask))
1330 /* Look up our local APIC structure for the tick counters. */
1331 la = &lapics[PCPU_GET(apic_id)];
1332 (*la->la_timer_count)++;
1334 if (lapic_et.et_active) {
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--;
1347 lapic_timer_set_divisor(u_int divisor)
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]);
1357 lapic_timer_oneshot(struct lapic *la)
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);
1370 lapic_timer_oneshot_nointr(struct lapic *la, uint32_t count)
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);
1383 lapic_timer_periodic(struct lapic *la)
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);
1396 lapic_timer_deadline(struct lapic *la)
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);
1409 wrmsr(MSR_TSC_DEADLINE, la->la_timer_period + rdtsc());
1413 lapic_timer_stop(struct lapic *la)
1417 if (la->la_timer_mode == LAT_MODE_DEADLINE) {
1418 wrmsr(MSR_TSC_DEADLINE, 0);
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);
1430 lapic_handle_cmc(void)
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.
1444 native_lapic_enable_cmc(void)
1449 if (!x2apic_mode && lapic_map == NULL)
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;
1458 printf("lapic%u: CMCI unmasked\n", apic_id);
1462 native_lapic_enable_mca_elvt(void)
1469 if (lapic_map == NULL)
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)
1480 value = lapic_read32(LAPIC_EXT_LVT0 + APIC_ELVT_MCA);
1481 if ((value & APIC_LVT_M) == 0) {
1483 printf("AMD MCE Thresholding Extended LVT is already active\n");
1484 return (APIC_ELVT_MCA);
1486 lapics[apic_id].la_elvts[APIC_ELVT_MCA].lvt_masked = 0;
1487 lapics[apic_id].la_elvts[APIC_ELVT_MCA].lvt_active = 1;
1489 printf("lapic%u: MCE Thresholding ELVT unmasked\n", apic_id);
1490 return (APIC_ELVT_MCA);
1494 lapic_handle_error(void)
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.
1504 lapic_write32(LAPIC_ESR, 0);
1505 esr = lapic_read32(LAPIC_ESR);
1507 printf("CPU%d: local APIC error 0x%x\n", PCPU_GET(cpuid), esr);
1512 native_apic_cpuid(u_int apic_id)
1515 return apic_cpuids[apic_id];
1521 /* Request a free IDT vector to be used by the specified IRQ. */
1523 native_apic_alloc_vector(u_int apic_id, u_int irq)
1527 KASSERT(irq < num_io_irqs, ("Invalid IRQ %u", irq));
1530 * Search for a free vector. Currently we just use a very simple
1531 * algorithm to find the first free vector.
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)
1537 lapics[apic_id].la_ioint_irqs[vector] = irq;
1538 mtx_unlock_spin(&icu_lock);
1539 return (vector + APIC_IO_INTS);
1541 mtx_unlock_spin(&icu_lock);
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.
1552 native_apic_alloc_vectors(u_int apic_id, u_int *irqs, u_int count, u_int align)
1554 u_int first, run, vector;
1556 KASSERT(powerof2(count), ("bad count"));
1557 KASSERT(powerof2(align), ("bad align"));
1558 KASSERT(align >= count, ("align < count"));
1560 for (run = 0; run < count; run++)
1561 KASSERT(irqs[run] < num_io_irqs, ("Invalid IRQ %u at index %u",
1566 * Search for 'count' free vectors. As with apic_alloc_vector(),
1567 * this just uses a simple first fit algorithm.
1571 mtx_lock_spin(&icu_lock);
1572 for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
1574 /* Vector is in use, end run. */
1575 if (lapics[apic_id].la_ioint_irqs[vector] != IRQ_FREE) {
1581 /* Start a new run if run == 0 and vector is aligned. */
1583 if ((vector & (align - 1)) != 0)
1589 /* Keep looping if the run isn't long enough yet. */
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] =
1597 mtx_unlock_spin(&icu_lock);
1598 return (first + APIC_IO_INTS);
1600 mtx_unlock_spin(&icu_lock);
1601 printf("APIC: Couldn't find APIC vectors for %u IRQs\n", count);
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
1612 native_apic_enable_vector(u_int apic_id, u_int vector)
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"));
1622 setidt(vector, (pti ? ioint_pti_handlers : ioint_handlers)[vector / 32],
1623 SDT_APIC, SEL_KPL, GSEL_APIC);
1627 native_apic_disable_vector(u_int apic_id, u_int vector)
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"));
1635 KASSERT(ioint_handlers[vector / 32] != NULL,
1636 ("No ISR handler for vector %u", vector));
1639 * We can not currently clear the idt entry because other cpus
1640 * may have a valid vector at this offset.
1642 setidt(vector, pti ? &IDTVEC(rsvd_pti) : &IDTVEC(rsvd), SDT_APIC,
1643 SEL_KPL, GSEL_APIC);
1647 /* Release an APIC vector when it's no longer in use. */
1649 native_apic_free_vector(u_int apic_id, u_int vector, u_int irq)
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"));
1665 * Bind us to the cpu that owned the vector before freeing it so
1666 * we don't lose an interrupt delivery race.
1671 if (sched_is_bound(td))
1672 panic("apic_free_vector: Thread already bound.\n");
1673 sched_bind(td, apic_cpuid(apic_id));
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);
1686 /* Map an IDT vector (APIC) to an IRQ (interrupt source). */
1688 apic_idt_to_irq(u_int apic_id, u_int vector)
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"));
1699 irq = lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS];
1707 * Dump data about APIC IDT vector mappings.
1709 DB_SHOW_COMMAND(apic, db_show_apic)
1711 struct intsrc *isrc;
1716 if (strcmp(modif, "vv") == 0)
1718 else if (strcmp(modif, "v") == 0)
1722 for (apic_id = 0; apic_id <= max_apic_id; apic_id++) {
1723 if (lapics[apic_id].la_present == 0)
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)
1730 #ifdef KDTRACE_HOOKS
1731 if (irq == IRQ_DTRACE_RET)
1735 if (irq == IRQ_EVTCHN)
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);
1746 db_dump_intr_event(isrc->is_event,
1749 db_printf("IRQ %u ???\n", irq);
1755 dump_mask(const char *prefix, uint32_t v, int base)
1760 for (i = 0; i < 32; i++)
1763 db_printf("%s:", prefix);
1766 db_printf(" %02x", base + i);
1772 /* Show info from the lapic regs for this CPU. */
1773 DB_SHOW_COMMAND(lapic, db_show_lapic)
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,
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));
1787 #define dump_field(prefix, regn, index) \
1788 dump_mask(__XSTRING(prefix ## index), \
1789 lapic_read32(LAPIC_ ## regn ## index), \
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);
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);
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);
1827 * APIC probing support code. This includes code to manage enumerators.
1830 static SLIST_HEAD(, apic_enumerator) enumerators =
1831 SLIST_HEAD_INITIALIZER(enumerators);
1832 static struct apic_enumerator *best_enum;
1835 apic_register_enumerator(struct apic_enumerator *enumerator)
1838 struct apic_enumerator *apic_enum;
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);
1846 SLIST_INSERT_HEAD(&enumerators, enumerator, apic_next);
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
1855 apic_init(void *dummy __unused)
1857 struct apic_enumerator *enumerator;
1860 /* We only support built in local APICs. */
1861 if (!(cpu_feature & CPUID_APIC))
1864 /* Don't probe if APIC mode is disabled. */
1865 if (resource_disabled("apic", 0))
1868 /* Probe all the enumerators to find the best match. */
1871 SLIST_FOREACH(enumerator, &enumerators, apic_next) {
1872 retval = enumerator->apic_probe();
1875 if (best_enum == NULL || best < retval) {
1876 best_enum = enumerator;
1880 if (best_enum == NULL) {
1882 printf("APIC: Could not find any APICs.\n");
1884 panic("running without device atpic requires a local APIC");
1890 printf("APIC: Using the %s enumerator.\n",
1891 best_enum->apic_name);
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.
1899 ppro_reenable_apic();
1902 /* Probe the CPU's in the system. */
1903 retval = best_enum->apic_probe_cpus();
1905 printf("%s: Failed to probe CPUs: returned %d\n",
1906 best_enum->apic_name, retval);
1909 SYSINIT(apic_init, SI_SUB_TUNABLES - 1, SI_ORDER_SECOND, apic_init, NULL);
1912 * Setup the local APIC. We have to do this prior to starting up the APs
1916 apic_setup_local(void *dummy __unused)
1920 if (best_enum == NULL)
1923 lapics = malloc(sizeof(*lapics) * (max_apic_id + 1), M_LAPIC,
1926 /* Initialize the local APIC. */
1927 retval = best_enum->apic_setup_local();
1929 printf("%s: Failed to setup the local APIC: returned %d\n",
1930 best_enum->apic_name, retval);
1932 SYSINIT(apic_setup_local, SI_SUB_CPU, SI_ORDER_SECOND, apic_setup_local, NULL);
1935 * Setup the I/O APICs.
1938 apic_setup_io(void *dummy __unused)
1942 if (best_enum == NULL)
1946 * Local APIC must be registered before other PICs and pseudo PICs
1947 * for proper suspend/resume order.
1949 intr_register_pic(&lapic_pic);
1951 retval = best_enum->apic_setup_io();
1953 printf("%s: Failed to setup I/O APICs: returned %d\n",
1954 best_enum->apic_name, retval);
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.
1966 /* Enable the MSI "pic". */
1967 init_ops.msi_init();
1970 xen_intr_alloc_irqs();
1973 SYSINIT(apic_setup_io, SI_SUB_INTR, SI_ORDER_THIRD, apic_setup_io, NULL);
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.
1983 * Wait delay microseconds for IPI to be sent. If delay is -1, we
1987 native_lapic_ipi_wait(int delay)
1991 /* LAPIC_ICR.APIC_DELSTAT_MASK is undefined in x2APIC mode */
1995 for (rx = 0; delay == -1 || rx < lapic_ipi_wait_mult * delay; rx++) {
1996 if ((lapic_read_icr_lo() & APIC_DELSTAT_MASK) ==
2005 native_lapic_ipi_raw(register_t icrlo, u_int dest)
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__));
2018 if ((icrlo & APIC_DEST_MASK) == APIC_DEST_DESTFLD) {
2022 icrhi = dest << APIC_ID_SHIFT;
2023 lapic_write_icr(icrhi, icrlo);
2025 lapic_write_icr_lo(icrlo);
2029 #define BEFORE_SPIN 50000
2030 #ifdef DETECT_DEADLOCK
2031 #define AFTER_SPIN 50
2035 native_lapic_ipi_vectored(u_int vector, int dest)
2037 register_t icrlo, destfield;
2039 KASSERT((vector & ~APIC_VECTOR_MASK) == 0,
2040 ("%s: invalid vector %d", __func__, vector));
2044 case APIC_IPI_DEST_SELF:
2045 if (x2apic_mode && vector < IPI_NMI_FIRST) {
2046 lapic_write_self_ipi(vector);
2049 icrlo = APIC_DEST_SELF;
2051 case APIC_IPI_DEST_ALL:
2052 icrlo = APIC_DEST_ALLISELF;
2054 case APIC_IPI_DEST_OTHERS:
2055 icrlo = APIC_DEST_ALLESELF;
2059 KASSERT(x2apic_mode ||
2060 (dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
2061 ("%s: invalid destination 0x%x", __func__, dest));
2066 * NMI IPIs are just fake vectors used to send a NMI. Use special rules
2067 * regarding NMIs if passed, otherwise specify the vector.
2069 if (vector >= IPI_NMI_FIRST)
2070 icrlo |= APIC_DELMODE_NMI;
2072 icrlo |= vector | APIC_DELMODE_FIXED;
2073 icrlo |= APIC_DESTMODE_PHY | APIC_TRIGMOD_EDGE | APIC_LEVEL_ASSERT;
2075 /* Wait for an earlier IPI to finish. */
2076 if (!lapic_ipi_wait(BEFORE_SPIN)) {
2077 if (panicstr != NULL)
2080 panic("APIC: Previous IPI is stuck");
2083 lapic_ipi_raw(icrlo, destfield);
2085 #ifdef DETECT_DEADLOCK
2086 /* Wait for IPI to be delivered. */
2087 if (!lapic_ipi_wait(AFTER_SPIN)) {
2088 #ifdef needsattention
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
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
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)
2109 #endif /* needsattention */
2111 #endif /* DETECT_DEADLOCK */
2117 * Since the IDT is shared by all CPUs the IPI slot update needs to be globally
2120 * Consider the case where an IPI is generated immediately after allocation:
2121 * vector = lapic_ipi_alloc(ipifunc);
2122 * ipi_selected(other_cpus, vector);
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.
2130 native_lapic_ipi_alloc(inthand_t *ipifunc)
2132 struct gate_descriptor *ip;
2136 KASSERT(ipifunc != &IDTVEC(rsvd) && ipifunc != &IDTVEC(rsvd_pti),
2137 ("invalid ipifunc %p", ipifunc));
2140 mtx_lock_spin(&icu_lock);
2141 for (idx = IPI_DYN_FIRST; idx <= IPI_DYN_LAST; idx++) {
2143 func = (ip->gd_hioffset << 16) | ip->gd_looffset;
2145 func -= setidt_disp;
2147 if ((!pti && func == (uintptr_t)&IDTVEC(rsvd)) ||
2148 (pti && func == (uintptr_t)&IDTVEC(rsvd_pti))) {
2150 setidt(vector, ipifunc, SDT_APIC, SEL_KPL, GSEL_APIC);
2154 mtx_unlock_spin(&icu_lock);
2159 native_lapic_ipi_free(int vector)
2161 struct gate_descriptor *ip;
2164 KASSERT(vector >= IPI_DYN_FIRST && vector <= IPI_DYN_LAST,
2165 ("%s: invalid vector %d", __func__, vector));
2167 mtx_lock_spin(&icu_lock);
2169 func = (ip->gd_hioffset << 16) | ip->gd_looffset;
2171 func -= setidt_disp;
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);