2 * Copyright (c) 2003 John Baldwin <jhb@FreeBSD.org>
3 * Copyright (c) 1996, by Steve Passe
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. The name of the developer may NOT be used to endorse or promote products
12 * derived from this software without specific prior written permission.
13 * 3. Neither the name of the author nor the names of any co-contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * Local APIC support on Pentium and later processors.
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
37 #include "opt_hwpmc_hooks.h"
38 #include "opt_kdtrace.h"
42 #include <sys/param.h>
43 #include <sys/systm.h>
45 #include <sys/kernel.h>
47 #include <sys/mutex.h>
50 #include <sys/sched.h>
52 #include <sys/timeet.h>
57 #include <x86/apicreg.h>
58 #include <machine/cpu.h>
59 #include <machine/cputypes.h>
60 #include <machine/frame.h>
61 #include <machine/intr_machdep.h>
62 #include <machine/apicvar.h>
64 #include <machine/md_var.h>
65 #include <machine/smp.h>
66 #include <machine/specialreg.h>
69 #include <sys/interrupt.h>
74 #define SDT_APIC SDT_SYSIGT
75 #define SDT_APICT SDT_SYSIGT
78 #define SDT_APIC SDT_SYS386IGT
79 #define SDT_APICT SDT_SYS386TGT
80 #define GSEL_APIC GSEL(GCODE_SEL, SEL_KPL)
83 /* Sanity checks on IDT vectors. */
84 CTASSERT(APIC_IO_INTS + APIC_NUM_IOINTS == APIC_TIMER_INT);
85 CTASSERT(APIC_TIMER_INT < APIC_LOCAL_INTS);
86 CTASSERT(APIC_LOCAL_INTS == 240);
87 CTASSERT(IPI_STOP < APIC_SPURIOUS_INT);
89 /* Magic IRQ values for the timer and syscalls. */
90 #define IRQ_TIMER (NUM_IO_INTS + 1)
91 #define IRQ_SYSCALL (NUM_IO_INTS + 2)
92 #define IRQ_DTRACE_RET (NUM_IO_INTS + 3)
95 * Support for local APICs. Local APICs manage interrupts on each
96 * individual processor as opposed to I/O APICs which receive interrupts
97 * from I/O devices and then forward them on to the local APICs.
99 * Local APICs can also send interrupts to each other thus providing the
100 * mechanism for IPIs.
104 u_int lvt_edgetrigger:1;
105 u_int lvt_activehi:1;
113 struct lvt la_lvts[LVT_MAX + 1];
116 u_int la_cluster_id:2;
118 u_long *la_timer_count;
119 u_long la_timer_period;
121 /* Include IDT_SYSCALL to make indexing easier. */
122 int la_ioint_irqs[APIC_NUM_IOINTS + 1];
123 } static lapics[MAX_APIC_ID + 1];
125 /* Global defaults for local APIC LVT entries. */
126 static struct lvt lvts[LVT_MAX + 1] = {
127 { 1, 1, 1, 1, APIC_LVT_DM_EXTINT, 0 }, /* LINT0: masked ExtINT */
128 { 1, 1, 0, 1, APIC_LVT_DM_NMI, 0 }, /* LINT1: NMI */
129 { 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_TIMER_INT }, /* Timer */
130 { 1, 1, 0, 1, APIC_LVT_DM_FIXED, APIC_ERROR_INT }, /* Error */
131 { 1, 1, 1, 1, APIC_LVT_DM_NMI, 0 }, /* PMC */
132 { 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_THERMAL_INT }, /* Thermal */
133 { 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_CMC_INT }, /* CMCI */
136 static inthand_t *ioint_handlers[] = {
138 IDTVEC(apic_isr1), /* 32 - 63 */
139 IDTVEC(apic_isr2), /* 64 - 95 */
140 IDTVEC(apic_isr3), /* 96 - 127 */
141 IDTVEC(apic_isr4), /* 128 - 159 */
142 IDTVEC(apic_isr5), /* 160 - 191 */
143 IDTVEC(apic_isr6), /* 192 - 223 */
144 IDTVEC(apic_isr7), /* 224 - 255 */
148 static u_int32_t lapic_timer_divisors[] = {
149 APIC_TDCR_1, APIC_TDCR_2, APIC_TDCR_4, APIC_TDCR_8, APIC_TDCR_16,
150 APIC_TDCR_32, APIC_TDCR_64, APIC_TDCR_128
153 extern inthand_t IDTVEC(rsvd);
155 volatile lapic_t *lapic;
156 vm_paddr_t lapic_paddr;
157 static u_long lapic_timer_divisor;
158 static struct eventtimer lapic_et;
160 static void lapic_enable(void);
161 static void lapic_resume(struct pic *pic);
162 static void lapic_timer_oneshot(u_int count, int enable_int);
163 static void lapic_timer_periodic(u_int count, int enable_int);
164 static void lapic_timer_stop(void);
165 static void lapic_timer_set_divisor(u_int divisor);
166 static uint32_t lvt_mode(struct lapic *la, u_int pin, uint32_t value);
167 static int lapic_et_start(struct eventtimer *et,
168 struct bintime *first, struct bintime *period);
169 static int lapic_et_stop(struct eventtimer *et);
171 struct pic lapic_pic = { .pic_resume = lapic_resume };
174 lvt_mode(struct lapic *la, u_int pin, uint32_t value)
178 KASSERT(pin <= LVT_MAX, ("%s: pin %u out of range", __func__, pin));
179 if (la->la_lvts[pin].lvt_active)
180 lvt = &la->la_lvts[pin];
184 value &= ~(APIC_LVT_M | APIC_LVT_TM | APIC_LVT_IIPP | APIC_LVT_DM |
186 if (lvt->lvt_edgetrigger == 0)
187 value |= APIC_LVT_TM;
188 if (lvt->lvt_activehi == 0)
189 value |= APIC_LVT_IIPP_INTALO;
192 value |= lvt->lvt_mode;
193 switch (lvt->lvt_mode) {
194 case APIC_LVT_DM_NMI:
195 case APIC_LVT_DM_SMI:
196 case APIC_LVT_DM_INIT:
197 case APIC_LVT_DM_EXTINT:
198 if (!lvt->lvt_edgetrigger) {
199 printf("lapic%u: Forcing LINT%u to edge trigger\n",
201 value |= APIC_LVT_TM;
203 /* Use a vector of 0. */
205 case APIC_LVT_DM_FIXED:
206 value |= lvt->lvt_vector;
209 panic("bad APIC LVT delivery mode: %#x\n", value);
215 * Map the local APIC and setup necessary interrupt vectors.
218 lapic_init(vm_paddr_t addr)
223 /* Map the local APIC and setup the spurious interrupt handler. */
224 KASSERT(trunc_page(addr) == addr,
225 ("local APIC not aligned on a page boundary"));
227 lapic = pmap_mapdev(addr, sizeof(lapic_t));
228 setidt(APIC_SPURIOUS_INT, IDTVEC(spuriousint), SDT_APIC, SEL_KPL,
231 /* Perform basic initialization of the BSP's local APIC. */
234 /* Set BSP's per-CPU local APIC ID. */
235 PCPU_SET(apic_id, lapic_id());
237 /* Local APIC timer interrupt. */
238 setidt(APIC_TIMER_INT, IDTVEC(timerint), SDT_APIC, SEL_KPL, GSEL_APIC);
240 /* Local APIC error interrupt. */
241 setidt(APIC_ERROR_INT, IDTVEC(errorint), SDT_APIC, SEL_KPL, GSEL_APIC);
243 /* XXX: Thermal interrupt */
245 /* Local APIC CMCI. */
246 setidt(APIC_CMC_INT, IDTVEC(cmcint), SDT_APICT, SEL_KPL, GSEL_APIC);
248 if ((resource_int_value("apic", 0, "clock", &i) != 0 || i != 0)) {
250 /* Intel CPUID 0x06 EAX[2] set if APIC timer runs in C3. */
251 if (cpu_vendor_id == CPU_VENDOR_INTEL && cpu_high >= 6) {
252 do_cpuid(0x06, regs);
253 if ((regs[0] & CPUTPM1_ARAT) != 0)
256 bzero(&lapic_et, sizeof(lapic_et));
257 lapic_et.et_name = "LAPIC";
258 lapic_et.et_flags = ET_FLAGS_PERIODIC | ET_FLAGS_ONESHOT |
260 lapic_et.et_quality = 600;
262 lapic_et.et_flags |= ET_FLAGS_C3STOP;
263 lapic_et.et_quality -= 200;
265 lapic_et.et_frequency = 0;
266 /* We don't know frequency yet, so trying to guess. */
267 lapic_et.et_min_period.sec = 0;
268 lapic_et.et_min_period.frac = 0x00001000LL << 32;
269 lapic_et.et_max_period.sec = 1;
270 lapic_et.et_max_period.frac = 0;
271 lapic_et.et_start = lapic_et_start;
272 lapic_et.et_stop = lapic_et_stop;
273 lapic_et.et_priv = NULL;
274 et_register(&lapic_et);
279 * Create a local APIC instance.
282 lapic_create(u_int apic_id, int boot_cpu)
286 if (apic_id > MAX_APIC_ID) {
287 printf("APIC: Ignoring local APIC with ID %d\n", apic_id);
289 panic("Can't ignore BSP");
292 KASSERT(!lapics[apic_id].la_present, ("duplicate local APIC %u",
296 * Assume no local LVT overrides and a cluster of 0 and
297 * intra-cluster ID of 0.
299 lapics[apic_id].la_present = 1;
300 lapics[apic_id].la_id = apic_id;
301 for (i = 0; i <= LVT_MAX; i++) {
302 lapics[apic_id].la_lvts[i] = lvts[i];
303 lapics[apic_id].la_lvts[i].lvt_active = 0;
305 for (i = 0; i <= APIC_NUM_IOINTS; i++)
306 lapics[apic_id].la_ioint_irqs[i] = -1;
307 lapics[apic_id].la_ioint_irqs[IDT_SYSCALL - APIC_IO_INTS] = IRQ_SYSCALL;
308 lapics[apic_id].la_ioint_irqs[APIC_TIMER_INT - APIC_IO_INTS] =
311 lapics[apic_id].la_ioint_irqs[IDT_DTRACE_RET - APIC_IO_INTS] = IRQ_DTRACE_RET;
316 cpu_add(apic_id, boot_cpu);
321 * Dump contents of local APIC registers
324 lapic_dump(const char* str)
328 maxlvt = (lapic->version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
329 printf("cpu%d %s:\n", PCPU_GET(cpuid), str);
330 printf(" ID: 0x%08x VER: 0x%08x LDR: 0x%08x DFR: 0x%08x\n",
331 lapic->id, lapic->version, lapic->ldr, lapic->dfr);
332 printf(" lint0: 0x%08x lint1: 0x%08x TPR: 0x%08x SVR: 0x%08x\n",
333 lapic->lvt_lint0, lapic->lvt_lint1, lapic->tpr, lapic->svr);
334 printf(" timer: 0x%08x therm: 0x%08x err: 0x%08x",
335 lapic->lvt_timer, lapic->lvt_thermal, lapic->lvt_error);
336 if (maxlvt >= LVT_PMC)
337 printf(" pmc: 0x%08x", lapic->lvt_pcint);
339 if (maxlvt >= LVT_CMCI)
340 printf(" cmci: 0x%08x\n", lapic->lvt_cmci);
344 lapic_setup(int boot)
349 char buf[MAXCOMLEN + 1];
351 la = &lapics[lapic_id()];
352 KASSERT(la->la_present, ("missing APIC structure"));
353 saveintr = intr_disable();
354 maxlvt = (lapic->version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
356 /* Initialize the TPR to allow all interrupts. */
359 /* Setup spurious vector and enable the local APIC. */
362 /* Program LINT[01] LVT entries. */
363 lapic->lvt_lint0 = lvt_mode(la, LVT_LINT0, lapic->lvt_lint0);
364 lapic->lvt_lint1 = lvt_mode(la, LVT_LINT1, lapic->lvt_lint1);
366 /* Program the PMC LVT entry if present. */
367 if (maxlvt >= LVT_PMC)
368 lapic->lvt_pcint = lvt_mode(la, LVT_PMC, lapic->lvt_pcint);
370 /* Program timer LVT and setup handler. */
371 lapic->lvt_timer = lvt_mode(la, LVT_TIMER, lapic->lvt_timer);
373 snprintf(buf, sizeof(buf), "cpu%d:timer", PCPU_GET(cpuid));
374 intrcnt_add(buf, &la->la_timer_count);
377 /* Setup the timer if configured. */
378 if (la->la_timer_mode != 0) {
379 KASSERT(la->la_timer_period != 0, ("lapic%u: zero divisor",
381 lapic_timer_set_divisor(lapic_timer_divisor);
382 if (la->la_timer_mode == 1)
383 lapic_timer_periodic(la->la_timer_period, 1);
385 lapic_timer_oneshot(la->la_timer_period, 1);
388 /* Program error LVT and clear any existing errors. */
389 lapic->lvt_error = lvt_mode(la, LVT_ERROR, lapic->lvt_error);
392 /* XXX: Thermal LVT */
394 /* Program the CMCI LVT entry if present. */
395 if (maxlvt >= LVT_CMCI)
396 lapic->lvt_cmci = lvt_mode(la, LVT_CMCI, lapic->lvt_cmci);
398 intr_restore(saveintr);
402 lapic_reenable_pmc(void)
407 value = lapic->lvt_pcint;
408 value &= ~APIC_LVT_M;
409 lapic->lvt_pcint = value;
415 lapic_update_pmc(void *dummy)
419 la = &lapics[lapic_id()];
420 lapic->lvt_pcint = lvt_mode(la, LVT_PMC, lapic->lvt_pcint);
425 lapic_enable_pmc(void)
430 /* Fail if the local APIC is not present. */
434 /* Fail if the PMC LVT is not present. */
435 maxlvt = (lapic->version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
436 if (maxlvt < LVT_PMC)
439 lvts[LVT_PMC].lvt_masked = 0;
443 * If hwpmc was loaded at boot time then the APs may not be
444 * started yet. In that case, don't forward the request to
445 * them as they will program the lvt when they start.
448 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
451 lapic_update_pmc(NULL);
459 lapic_disable_pmc(void)
464 /* Fail if the local APIC is not present. */
468 /* Fail if the PMC LVT is not present. */
469 maxlvt = (lapic->version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
470 if (maxlvt < LVT_PMC)
473 lvts[LVT_PMC].lvt_masked = 1;
476 /* The APs should always be started when hwpmc is unloaded. */
477 KASSERT(mp_ncpus == 1 || smp_started, ("hwpmc unloaded too early"));
479 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
484 lapic_et_start(struct eventtimer *et,
485 struct bintime *first, struct bintime *period)
490 if (et->et_frequency == 0) {
491 /* Start off with a divisor of 2 (power on reset default). */
492 lapic_timer_divisor = 2;
493 /* Try to calibrate the local APIC timer. */
495 lapic_timer_set_divisor(lapic_timer_divisor);
496 lapic_timer_oneshot(APIC_TIMER_MAX_COUNT, 0);
498 value = APIC_TIMER_MAX_COUNT - lapic->ccr_timer;
499 if (value != APIC_TIMER_MAX_COUNT)
501 lapic_timer_divisor <<= 1;
502 } while (lapic_timer_divisor <= 128);
503 if (lapic_timer_divisor > 128)
504 panic("lapic: Divisor too big");
506 printf("lapic: Divisor %lu, Frequency %lu Hz\n",
507 lapic_timer_divisor, value);
508 et->et_frequency = value;
509 et->et_min_period.sec = 0;
510 et->et_min_period.frac =
511 ((0x00000002LLU << 32) / et->et_frequency) << 32;
512 et->et_max_period.sec = 0xfffffffeLLU / et->et_frequency;
513 et->et_max_period.frac =
514 ((0xfffffffeLLU << 32) / et->et_frequency) << 32;
516 lapic_timer_set_divisor(lapic_timer_divisor);
517 la = &lapics[lapic_id()];
518 if (period != NULL) {
519 la->la_timer_mode = 1;
520 la->la_timer_period =
521 (et->et_frequency * (period->frac >> 32)) >> 32;
522 if (period->sec != 0)
523 la->la_timer_period += et->et_frequency * period->sec;
524 lapic_timer_periodic(la->la_timer_period, 1);
526 la->la_timer_mode = 2;
527 la->la_timer_period =
528 (et->et_frequency * (first->frac >> 32)) >> 32;
530 la->la_timer_period += et->et_frequency * first->sec;
531 lapic_timer_oneshot(la->la_timer_period, 1);
537 lapic_et_stop(struct eventtimer *et)
539 struct lapic *la = &lapics[lapic_id()];
541 la->la_timer_mode = 0;
551 /* Software disable the local APIC. */
553 value &= ~APIC_SVR_SWEN;
562 /* Program the spurious vector to enable the local APIC. */
564 value &= ~(APIC_SVR_VECTOR | APIC_SVR_FOCUS);
565 value |= (APIC_SVR_FEN | APIC_SVR_SWEN | APIC_SPURIOUS_INT);
569 /* Reset the local APIC on the BSP during resume. */
571 lapic_resume(struct pic *pic)
581 KASSERT(lapic != NULL, ("local APIC is not mapped"));
582 return (lapic->id >> APIC_ID_SHIFT);
586 lapic_intr_pending(u_int vector)
588 volatile u_int32_t *irr;
591 * The IRR registers are an array of 128-bit registers each of
592 * which only describes 32 interrupts in the low 32 bits.. Thus,
593 * we divide the vector by 32 to get the 128-bit index. We then
594 * multiply that index by 4 to get the equivalent index from
595 * treating the IRR as an array of 32-bit registers. Finally, we
596 * modulus the vector by 32 to determine the individual bit to
600 return (irr[(vector / 32) * 4] & 1 << (vector % 32));
604 lapic_set_logical_id(u_int apic_id, u_int cluster, u_int cluster_id)
608 KASSERT(lapics[apic_id].la_present, ("%s: APIC %u doesn't exist",
610 KASSERT(cluster <= APIC_MAX_CLUSTER, ("%s: cluster %u too big",
612 KASSERT(cluster_id <= APIC_MAX_INTRACLUSTER_ID,
613 ("%s: intra cluster id %u too big", __func__, cluster_id));
614 la = &lapics[apic_id];
615 la->la_cluster = cluster;
616 la->la_cluster_id = cluster_id;
620 lapic_set_lvt_mask(u_int apic_id, u_int pin, u_char masked)
625 if (apic_id == APIC_ID_ALL) {
626 lvts[pin].lvt_masked = masked;
630 KASSERT(lapics[apic_id].la_present,
631 ("%s: missing APIC %u", __func__, apic_id));
632 lapics[apic_id].la_lvts[pin].lvt_masked = masked;
633 lapics[apic_id].la_lvts[pin].lvt_active = 1;
635 printf("lapic%u:", apic_id);
638 printf(" LINT%u %s\n", pin, masked ? "masked" : "unmasked");
643 lapic_set_lvt_mode(u_int apic_id, u_int pin, u_int32_t mode)
649 if (apic_id == APIC_ID_ALL) {
654 KASSERT(lapics[apic_id].la_present,
655 ("%s: missing APIC %u", __func__, apic_id));
656 lvt = &lapics[apic_id].la_lvts[pin];
659 printf("lapic%u:", apic_id);
661 lvt->lvt_mode = mode;
663 case APIC_LVT_DM_NMI:
664 case APIC_LVT_DM_SMI:
665 case APIC_LVT_DM_INIT:
666 case APIC_LVT_DM_EXTINT:
667 lvt->lvt_edgetrigger = 1;
668 lvt->lvt_activehi = 1;
669 if (mode == APIC_LVT_DM_EXTINT)
675 panic("Unsupported delivery mode: 0x%x\n", mode);
680 case APIC_LVT_DM_NMI:
683 case APIC_LVT_DM_SMI:
686 case APIC_LVT_DM_INIT:
689 case APIC_LVT_DM_EXTINT:
693 printf(" -> LINT%u\n", pin);
699 lapic_set_lvt_polarity(u_int apic_id, u_int pin, enum intr_polarity pol)
702 if (pin > LVT_MAX || pol == INTR_POLARITY_CONFORM)
704 if (apic_id == APIC_ID_ALL) {
705 lvts[pin].lvt_activehi = (pol == INTR_POLARITY_HIGH);
709 KASSERT(lapics[apic_id].la_present,
710 ("%s: missing APIC %u", __func__, apic_id));
711 lapics[apic_id].la_lvts[pin].lvt_active = 1;
712 lapics[apic_id].la_lvts[pin].lvt_activehi =
713 (pol == INTR_POLARITY_HIGH);
715 printf("lapic%u:", apic_id);
718 printf(" LINT%u polarity: %s\n", pin,
719 pol == INTR_POLARITY_HIGH ? "high" : "low");
724 lapic_set_lvt_triggermode(u_int apic_id, u_int pin, enum intr_trigger trigger)
727 if (pin > LVT_MAX || trigger == INTR_TRIGGER_CONFORM)
729 if (apic_id == APIC_ID_ALL) {
730 lvts[pin].lvt_edgetrigger = (trigger == INTR_TRIGGER_EDGE);
734 KASSERT(lapics[apic_id].la_present,
735 ("%s: missing APIC %u", __func__, apic_id));
736 lapics[apic_id].la_lvts[pin].lvt_edgetrigger =
737 (trigger == INTR_TRIGGER_EDGE);
738 lapics[apic_id].la_lvts[pin].lvt_active = 1;
740 printf("lapic%u:", apic_id);
743 printf(" LINT%u trigger: %s\n", pin,
744 trigger == INTR_TRIGGER_EDGE ? "edge" : "level");
749 * Adjust the TPR of the current CPU so that it blocks all interrupts below
750 * the passed in vector.
753 lapic_set_tpr(u_int vector)
760 tpr = lapic->tpr & ~APIC_TPR_PRIO;
774 lapic_handle_intr(int vector, struct trapframe *frame)
778 isrc = intr_lookup_source(apic_idt_to_irq(PCPU_GET(apic_id),
780 intr_execute_handlers(isrc, frame);
784 lapic_handle_timer(struct trapframe *frame)
787 struct trapframe *oldframe;
790 /* Send EOI first thing. */
793 #if defined(SMP) && !defined(SCHED_ULE)
795 * Don't do any accounting for the disabled HTT cores, since it
796 * will provide misleading numbers for the userland.
798 * No locking is necessary here, since even if we lose the race
799 * when hlt_cpus_mask changes it is not a big deal, really.
801 * Don't do that for ULE, since ULE doesn't consider hlt_cpus_mask
802 * and unlike other schedulers it actually schedules threads to
805 if (CPU_ISSET(PCPU_GET(cpuid), &hlt_cpus_mask))
809 /* Look up our local APIC structure for the tick counters. */
810 la = &lapics[PCPU_GET(apic_id)];
811 (*la->la_timer_count)++;
813 if (lapic_et.et_active) {
815 td->td_intr_nesting_level++;
816 oldframe = td->td_intr_frame;
817 td->td_intr_frame = frame;
818 lapic_et.et_event_cb(&lapic_et, lapic_et.et_arg);
819 td->td_intr_frame = oldframe;
820 td->td_intr_nesting_level--;
826 lapic_timer_set_divisor(u_int divisor)
829 KASSERT(powerof2(divisor), ("lapic: invalid divisor %u", divisor));
830 KASSERT(ffs(divisor) <= sizeof(lapic_timer_divisors) /
831 sizeof(u_int32_t), ("lapic: invalid divisor %u", divisor));
832 lapic->dcr_timer = lapic_timer_divisors[ffs(divisor) - 1];
836 lapic_timer_oneshot(u_int count, int enable_int)
840 value = lapic->lvt_timer;
841 value &= ~APIC_LVTT_TM;
842 value |= APIC_LVTT_TM_ONE_SHOT;
844 value &= ~APIC_LVT_M;
845 lapic->lvt_timer = value;
846 lapic->icr_timer = count;
850 lapic_timer_periodic(u_int count, int enable_int)
854 value = lapic->lvt_timer;
855 value &= ~APIC_LVTT_TM;
856 value |= APIC_LVTT_TM_PERIODIC;
858 value &= ~APIC_LVT_M;
859 lapic->lvt_timer = value;
860 lapic->icr_timer = count;
864 lapic_timer_stop(void)
868 value = lapic->lvt_timer;
869 value &= ~APIC_LVTT_TM;
871 lapic->lvt_timer = value;
875 lapic_handle_cmc(void)
883 * Called from the mca_init() to activate the CMC interrupt if this CPU is
884 * responsible for monitoring any MC banks for CMC events. Since mca_init()
885 * is called prior to lapic_setup() during boot, this just needs to unmask
886 * this CPU's LVT_CMCI entry.
889 lapic_enable_cmc(void)
893 apic_id = PCPU_GET(apic_id);
894 KASSERT(lapics[apic_id].la_present,
895 ("%s: missing APIC %u", __func__, apic_id));
896 lapics[apic_id].la_lvts[LVT_CMCI].lvt_masked = 0;
897 lapics[apic_id].la_lvts[LVT_CMCI].lvt_active = 1;
899 printf("lapic%u: CMCI unmasked\n", apic_id);
903 lapic_handle_error(void)
908 * Read the contents of the error status register. Write to
909 * the register first before reading from it to force the APIC
910 * to update its value to indicate any errors that have
911 * occurred since the previous write to the register.
916 printf("CPU%d: local APIC error 0x%x\n", PCPU_GET(cpuid), esr);
921 apic_cpuid(u_int apic_id)
924 return apic_cpuids[apic_id];
930 /* Request a free IDT vector to be used by the specified IRQ. */
932 apic_alloc_vector(u_int apic_id, u_int irq)
936 KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
939 * Search for a free vector. Currently we just use a very simple
940 * algorithm to find the first free vector.
942 mtx_lock_spin(&icu_lock);
943 for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
944 if (lapics[apic_id].la_ioint_irqs[vector] != -1)
946 lapics[apic_id].la_ioint_irqs[vector] = irq;
947 mtx_unlock_spin(&icu_lock);
948 return (vector + APIC_IO_INTS);
950 mtx_unlock_spin(&icu_lock);
955 * Request 'count' free contiguous IDT vectors to be used by 'count'
956 * IRQs. 'count' must be a power of two and the vectors will be
957 * aligned on a boundary of 'align'. If the request cannot be
958 * satisfied, 0 is returned.
961 apic_alloc_vectors(u_int apic_id, u_int *irqs, u_int count, u_int align)
963 u_int first, run, vector;
965 KASSERT(powerof2(count), ("bad count"));
966 KASSERT(powerof2(align), ("bad align"));
967 KASSERT(align >= count, ("align < count"));
969 for (run = 0; run < count; run++)
970 KASSERT(irqs[run] < NUM_IO_INTS, ("Invalid IRQ %u at index %u",
975 * Search for 'count' free vectors. As with apic_alloc_vector(),
976 * this just uses a simple first fit algorithm.
980 mtx_lock_spin(&icu_lock);
981 for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
983 /* Vector is in use, end run. */
984 if (lapics[apic_id].la_ioint_irqs[vector] != -1) {
990 /* Start a new run if run == 0 and vector is aligned. */
992 if ((vector & (align - 1)) != 0)
998 /* Keep looping if the run isn't long enough yet. */
1002 /* Found a run, assign IRQs and return the first vector. */
1003 for (vector = 0; vector < count; vector++)
1004 lapics[apic_id].la_ioint_irqs[first + vector] =
1006 mtx_unlock_spin(&icu_lock);
1007 return (first + APIC_IO_INTS);
1009 mtx_unlock_spin(&icu_lock);
1010 printf("APIC: Couldn't find APIC vectors for %u IRQs\n", count);
1015 * Enable a vector for a particular apic_id. Since all lapics share idt
1016 * entries and ioint_handlers this enables the vector on all lapics. lapics
1017 * which do not have the vector configured would report spurious interrupts
1021 apic_enable_vector(u_int apic_id, u_int vector)
1024 KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1025 KASSERT(ioint_handlers[vector / 32] != NULL,
1026 ("No ISR handler for vector %u", vector));
1027 #ifdef KDTRACE_HOOKS
1028 KASSERT(vector != IDT_DTRACE_RET,
1029 ("Attempt to overwrite DTrace entry"));
1031 setidt(vector, ioint_handlers[vector / 32], SDT_APIC, SEL_KPL,
1036 apic_disable_vector(u_int apic_id, u_int vector)
1039 KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1040 #ifdef KDTRACE_HOOKS
1041 KASSERT(vector != IDT_DTRACE_RET,
1042 ("Attempt to overwrite DTrace entry"));
1044 KASSERT(ioint_handlers[vector / 32] != NULL,
1045 ("No ISR handler for vector %u", vector));
1048 * We can not currently clear the idt entry because other cpus
1049 * may have a valid vector at this offset.
1051 setidt(vector, &IDTVEC(rsvd), SDT_APICT, SEL_KPL, GSEL_APIC);
1055 /* Release an APIC vector when it's no longer in use. */
1057 apic_free_vector(u_int apic_id, u_int vector, u_int irq)
1061 KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1062 vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1063 ("Vector %u does not map to an IRQ line", vector));
1064 KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
1065 KASSERT(lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] ==
1066 irq, ("IRQ mismatch"));
1067 #ifdef KDTRACE_HOOKS
1068 KASSERT(vector != IDT_DTRACE_RET,
1069 ("Attempt to overwrite DTrace entry"));
1073 * Bind us to the cpu that owned the vector before freeing it so
1074 * we don't lose an interrupt delivery race.
1079 if (sched_is_bound(td))
1080 panic("apic_free_vector: Thread already bound.\n");
1081 sched_bind(td, apic_cpuid(apic_id));
1084 mtx_lock_spin(&icu_lock);
1085 lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] = -1;
1086 mtx_unlock_spin(&icu_lock);
1094 /* Map an IDT vector (APIC) to an IRQ (interrupt source). */
1096 apic_idt_to_irq(u_int apic_id, u_int vector)
1100 KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1101 vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1102 ("Vector %u does not map to an IRQ line", vector));
1103 #ifdef KDTRACE_HOOKS
1104 KASSERT(vector != IDT_DTRACE_RET,
1105 ("Attempt to overwrite DTrace entry"));
1107 irq = lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS];
1115 * Dump data about APIC IDT vector mappings.
1117 DB_SHOW_COMMAND(apic, db_show_apic)
1119 struct intsrc *isrc;
1124 if (strcmp(modif, "vv") == 0)
1126 else if (strcmp(modif, "v") == 0)
1130 for (apic_id = 0; apic_id <= MAX_APIC_ID; apic_id++) {
1131 if (lapics[apic_id].la_present == 0)
1133 db_printf("Interrupts bound to lapic %u\n", apic_id);
1134 for (i = 0; i < APIC_NUM_IOINTS + 1 && !db_pager_quit; i++) {
1135 irq = lapics[apic_id].la_ioint_irqs[i];
1136 if (irq == -1 || irq == IRQ_SYSCALL)
1138 #ifdef KDTRACE_HOOKS
1139 if (irq == IRQ_DTRACE_RET)
1142 db_printf("vec 0x%2x -> ", i + APIC_IO_INTS);
1143 if (irq == IRQ_TIMER)
1144 db_printf("lapic timer\n");
1145 else if (irq < NUM_IO_INTS) {
1146 isrc = intr_lookup_source(irq);
1147 if (isrc == NULL || verbose == 0)
1148 db_printf("IRQ %u\n", irq);
1150 db_dump_intr_event(isrc->is_event,
1153 db_printf("IRQ %u ???\n", irq);
1159 dump_mask(const char *prefix, uint32_t v, int base)
1164 for (i = 0; i < 32; i++)
1167 db_printf("%s:", prefix);
1170 db_printf(" %02x", base + i);
1176 /* Show info from the lapic regs for this CPU. */
1177 DB_SHOW_COMMAND(lapic, db_show_lapic)
1181 db_printf("lapic ID = %d\n", lapic_id());
1183 db_printf("version = %d.%d\n", (v & APIC_VER_VERSION) >> 4,
1185 db_printf("max LVT = %d\n", (v & APIC_VER_MAXLVT) >> MAXLVTSHIFT);
1187 db_printf("SVR = %02x (%s)\n", v & APIC_SVR_VECTOR,
1188 v & APIC_SVR_ENABLE ? "enabled" : "disabled");
1189 db_printf("TPR = %02x\n", lapic->tpr);
1191 #define dump_field(prefix, index) \
1192 dump_mask(__XSTRING(prefix ## index), lapic->prefix ## index, \
1195 db_printf("In-service Interrupts:\n");
1205 db_printf("TMR Interrupts:\n");
1215 db_printf("IRR Interrupts:\n");
1230 * APIC probing support code. This includes code to manage enumerators.
1233 static SLIST_HEAD(, apic_enumerator) enumerators =
1234 SLIST_HEAD_INITIALIZER(enumerators);
1235 static struct apic_enumerator *best_enum;
1238 apic_register_enumerator(struct apic_enumerator *enumerator)
1241 struct apic_enumerator *apic_enum;
1243 SLIST_FOREACH(apic_enum, &enumerators, apic_next) {
1244 if (apic_enum == enumerator)
1245 panic("%s: Duplicate register of %s", __func__,
1246 enumerator->apic_name);
1249 SLIST_INSERT_HEAD(&enumerators, enumerator, apic_next);
1253 * We have to look for CPU's very, very early because certain subsystems
1254 * want to know how many CPU's we have extremely early on in the boot
1258 apic_init(void *dummy __unused)
1260 struct apic_enumerator *enumerator;
1266 /* We only support built in local APICs. */
1267 if (!(cpu_feature & CPUID_APIC))
1270 /* Don't probe if APIC mode is disabled. */
1271 if (resource_disabled("apic", 0))
1274 /* Probe all the enumerators to find the best match. */
1277 SLIST_FOREACH(enumerator, &enumerators, apic_next) {
1278 retval = enumerator->apic_probe();
1281 if (best_enum == NULL || best < retval) {
1282 best_enum = enumerator;
1286 if (best_enum == NULL) {
1288 printf("APIC: Could not find any APICs.\n");
1293 printf("APIC: Using the %s enumerator.\n",
1294 best_enum->apic_name);
1298 * To work around an errata, we disable the local APIC on some
1299 * CPUs during early startup. We need to turn the local APIC back
1300 * on on such CPUs now.
1302 if (cpu == CPU_686 && cpu_vendor_id == CPU_VENDOR_INTEL &&
1303 (cpu_id & 0xff0) == 0x610) {
1304 apic_base = rdmsr(MSR_APICBASE);
1305 apic_base |= APICBASE_ENABLED;
1306 wrmsr(MSR_APICBASE, apic_base);
1310 /* Probe the CPU's in the system. */
1311 retval = best_enum->apic_probe_cpus();
1313 printf("%s: Failed to probe CPUs: returned %d\n",
1314 best_enum->apic_name, retval);
1317 SYSINIT(apic_init, SI_SUB_TUNABLES - 1, SI_ORDER_SECOND, apic_init, NULL);
1320 * Setup the local APIC. We have to do this prior to starting up the APs
1324 apic_setup_local(void *dummy __unused)
1328 if (best_enum == NULL)
1331 /* Initialize the local APIC. */
1332 retval = best_enum->apic_setup_local();
1334 printf("%s: Failed to setup the local APIC: returned %d\n",
1335 best_enum->apic_name, retval);
1337 SYSINIT(apic_setup_local, SI_SUB_CPU, SI_ORDER_SECOND, apic_setup_local, NULL);
1340 * Setup the I/O APICs.
1343 apic_setup_io(void *dummy __unused)
1347 if (best_enum == NULL)
1351 * Local APIC must be registered before other PICs and pseudo PICs
1352 * for proper suspend/resume order.
1355 intr_register_pic(&lapic_pic);
1358 retval = best_enum->apic_setup_io();
1360 printf("%s: Failed to setup I/O APICs: returned %d\n",
1361 best_enum->apic_name, retval);
1366 * Finish setting up the local APIC on the BSP once we know how to
1367 * properly program the LINT pins.
1373 /* Enable the MSI "pic". */
1376 SYSINIT(apic_setup_io, SI_SUB_INTR, SI_ORDER_SECOND, apic_setup_io, NULL);
1380 * Inter Processor Interrupt functions. The lapic_ipi_*() functions are
1381 * private to the MD code. The public interface for the rest of the
1382 * kernel is defined in mp_machdep.c.
1385 lapic_ipi_wait(int delay)
1390 * Wait delay loops for IPI to be sent. This is highly bogus
1391 * since this is sensitive to CPU clock speed. If delay is
1392 * -1, we wait forever.
1399 for (x = 0; x < delay; x += incr) {
1400 if ((lapic->icr_lo & APIC_DELSTAT_MASK) == APIC_DELSTAT_IDLE)
1408 lapic_ipi_raw(register_t icrlo, u_int dest)
1410 register_t value, saveintr;
1412 /* XXX: Need more sanity checking of icrlo? */
1413 KASSERT(lapic != NULL, ("%s called too early", __func__));
1414 KASSERT((dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
1415 ("%s: invalid dest field", __func__));
1416 KASSERT((icrlo & APIC_ICRLO_RESV_MASK) == 0,
1417 ("%s: reserved bits set in ICR LO register", __func__));
1419 /* Set destination in ICR HI register if it is being used. */
1420 saveintr = intr_disable();
1421 if ((icrlo & APIC_DEST_MASK) == APIC_DEST_DESTFLD) {
1422 value = lapic->icr_hi;
1423 value &= ~APIC_ID_MASK;
1424 value |= dest << APIC_ID_SHIFT;
1425 lapic->icr_hi = value;
1428 /* Program the contents of the IPI and dispatch it. */
1429 value = lapic->icr_lo;
1430 value &= APIC_ICRLO_RESV_MASK;
1432 lapic->icr_lo = value;
1433 intr_restore(saveintr);
1436 #define BEFORE_SPIN 1000000
1437 #ifdef DETECT_DEADLOCK
1438 #define AFTER_SPIN 1000
1442 lapic_ipi_vectored(u_int vector, int dest)
1444 register_t icrlo, destfield;
1446 KASSERT((vector & ~APIC_VECTOR_MASK) == 0,
1447 ("%s: invalid vector %d", __func__, vector));
1449 icrlo = APIC_DESTMODE_PHY | APIC_TRIGMOD_EDGE;
1452 * IPI_STOP_HARD is just a "fake" vector used to send a NMI.
1453 * Use special rules regard NMI if passed, otherwise specify
1456 if (vector == IPI_STOP_HARD)
1457 icrlo |= APIC_DELMODE_NMI | APIC_LEVEL_ASSERT;
1459 icrlo |= vector | APIC_DELMODE_FIXED | APIC_LEVEL_DEASSERT;
1462 case APIC_IPI_DEST_SELF:
1463 icrlo |= APIC_DEST_SELF;
1465 case APIC_IPI_DEST_ALL:
1466 icrlo |= APIC_DEST_ALLISELF;
1468 case APIC_IPI_DEST_OTHERS:
1469 icrlo |= APIC_DEST_ALLESELF;
1472 KASSERT((dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
1473 ("%s: invalid destination 0x%x", __func__, dest));
1477 /* Wait for an earlier IPI to finish. */
1478 if (!lapic_ipi_wait(BEFORE_SPIN)) {
1479 if (panicstr != NULL)
1482 panic("APIC: Previous IPI is stuck");
1485 lapic_ipi_raw(icrlo, destfield);
1487 #ifdef DETECT_DEADLOCK
1488 /* Wait for IPI to be delivered. */
1489 if (!lapic_ipi_wait(AFTER_SPIN)) {
1490 #ifdef needsattention
1494 * The above function waits for the message to actually be
1495 * delivered. It breaks out after an arbitrary timeout
1496 * since the message should eventually be delivered (at
1497 * least in theory) and that if it wasn't we would catch
1498 * the failure with the check above when the next IPI is
1501 * We could skip this wait entirely, EXCEPT it probably
1502 * protects us from other routines that assume that the
1503 * message was delivered and acted upon when this function
1506 printf("APIC: IPI might be stuck\n");
1507 #else /* !needsattention */
1508 /* Wait until mesage is sent without a timeout. */
1509 while (lapic->icr_lo & APIC_DELSTAT_PEND)
1511 #endif /* needsattention */
1513 #endif /* DETECT_DEADLOCK */