]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/x86/x86/local_apic.c
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / sys / x86 / x86 / local_apic.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1996, by Steve Passe
5  * All rights reserved.
6  * Copyright (c) 2003 John Baldwin <jhb@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. The name of the developer may NOT be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  * 3. Neither the name of the author nor the names of any co-contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31
32 /*
33  * Local APIC support on Pentium and later processors.
34  */
35
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38
39 #include "opt_atpic.h"
40 #include "opt_hwpmc_hooks.h"
41
42 #include "opt_ddb.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/bus.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/malloc.h>
50 #include <sys/mutex.h>
51 #include <sys/pcpu.h>
52 #include <sys/proc.h>
53 #include <sys/sched.h>
54 #include <sys/smp.h>
55 #include <sys/sysctl.h>
56 #include <sys/timeet.h>
57
58 #include <vm/vm.h>
59 #include <vm/pmap.h>
60
61 #include <x86/apicreg.h>
62 #include <machine/clock.h>
63 #include <machine/cpufunc.h>
64 #include <machine/cputypes.h>
65 #include <machine/frame.h>
66 #include <machine/intr_machdep.h>
67 #include <x86/apicvar.h>
68 #include <x86/mca.h>
69 #include <machine/md_var.h>
70 #include <machine/smp.h>
71 #include <machine/specialreg.h>
72 #include <x86/init.h>
73
74 #ifdef DDB
75 #include <sys/interrupt.h>
76 #include <ddb/ddb.h>
77 #endif
78
79 #ifdef __amd64__
80 #define SDT_APIC        SDT_SYSIGT
81 #define GSEL_APIC       0
82 #else
83 #define SDT_APIC        SDT_SYS386IGT
84 #define GSEL_APIC       GSEL(GCODE_SEL, SEL_KPL)
85 #endif
86
87 static MALLOC_DEFINE(M_LAPIC, "local_apic", "Local APIC items");
88
89 /* Sanity checks on IDT vectors. */
90 CTASSERT(APIC_IO_INTS + APIC_NUM_IOINTS == APIC_TIMER_INT);
91 CTASSERT(APIC_TIMER_INT < APIC_LOCAL_INTS);
92 CTASSERT(APIC_LOCAL_INTS == 240);
93 CTASSERT(IPI_STOP < APIC_SPURIOUS_INT);
94
95 /*
96  * I/O interrupts use non-negative IRQ values.  These values are used
97  * to mark unused IDT entries or IDT entries reserved for a non-I/O
98  * interrupt.
99  */
100 #define IRQ_FREE        -1
101 #define IRQ_TIMER       -2
102 #define IRQ_SYSCALL     -3
103 #define IRQ_DTRACE_RET  -4
104 #define IRQ_EVTCHN      -5
105
106 enum lat_timer_mode {
107         LAT_MODE_UNDEF =        0,
108         LAT_MODE_PERIODIC =     1,
109         LAT_MODE_ONESHOT =      2,
110         LAT_MODE_DEADLINE =     3,
111 };
112
113 /*
114  * Support for local APICs.  Local APICs manage interrupts on each
115  * individual processor as opposed to I/O APICs which receive interrupts
116  * from I/O devices and then forward them on to the local APICs.
117  *
118  * Local APICs can also send interrupts to each other thus providing the
119  * mechanism for IPIs.
120  */
121
122 struct lvt {
123         u_int lvt_edgetrigger:1;
124         u_int lvt_activehi:1;
125         u_int lvt_masked:1;
126         u_int lvt_active:1;
127         u_int lvt_mode:16;
128         u_int lvt_vector:8;
129 };
130
131 struct lapic {
132         struct lvt la_lvts[APIC_LVT_MAX + 1];
133         struct lvt la_elvts[APIC_ELVT_MAX + 1];
134         u_int la_id:8;
135         u_int la_cluster:4;
136         u_int la_cluster_id:2;
137         u_int la_present:1;
138         u_long *la_timer_count;
139         uint64_t la_timer_period;
140         enum lat_timer_mode la_timer_mode;
141         uint32_t lvt_timer_base;
142         uint32_t lvt_timer_last;
143         /* Include IDT_SYSCALL to make indexing easier. */
144         int la_ioint_irqs[APIC_NUM_IOINTS + 1];
145 } static *lapics;
146
147 /* Global defaults for local APIC LVT entries. */
148 static struct lvt lvts[APIC_LVT_MAX + 1] = {
149         { 1, 1, 1, 1, APIC_LVT_DM_EXTINT, 0 },  /* LINT0: masked ExtINT */
150         { 1, 1, 0, 1, APIC_LVT_DM_NMI, 0 },     /* LINT1: NMI */
151         { 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_TIMER_INT },      /* Timer */
152         { 1, 1, 0, 1, APIC_LVT_DM_FIXED, APIC_ERROR_INT },      /* Error */
153         { 1, 1, 1, 1, APIC_LVT_DM_NMI, 0 },     /* PMC */
154         { 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_THERMAL_INT },    /* Thermal */
155         { 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_CMC_INT },        /* CMCI */
156 };
157
158 /* Global defaults for AMD local APIC ELVT entries. */
159 static struct lvt elvts[APIC_ELVT_MAX + 1] = {
160         { 1, 1, 1, 0, APIC_LVT_DM_FIXED, 0 },
161         { 1, 1, 1, 0, APIC_LVT_DM_FIXED, APIC_CMC_INT },
162         { 1, 1, 1, 0, APIC_LVT_DM_FIXED, 0 },
163         { 1, 1, 1, 0, APIC_LVT_DM_FIXED, 0 },
164 };
165
166 static inthand_t *ioint_handlers[] = {
167         NULL,                   /* 0 - 31 */
168         IDTVEC(apic_isr1),      /* 32 - 63 */
169         IDTVEC(apic_isr2),      /* 64 - 95 */
170         IDTVEC(apic_isr3),      /* 96 - 127 */
171         IDTVEC(apic_isr4),      /* 128 - 159 */
172         IDTVEC(apic_isr5),      /* 160 - 191 */
173         IDTVEC(apic_isr6),      /* 192 - 223 */
174         IDTVEC(apic_isr7),      /* 224 - 255 */
175 };
176
177 static inthand_t *ioint_pti_handlers[] = {
178         NULL,                   /* 0 - 31 */
179         IDTVEC(apic_isr1_pti),  /* 32 - 63 */
180         IDTVEC(apic_isr2_pti),  /* 64 - 95 */
181         IDTVEC(apic_isr3_pti),  /* 96 - 127 */
182         IDTVEC(apic_isr4_pti),  /* 128 - 159 */
183         IDTVEC(apic_isr5_pti),  /* 160 - 191 */
184         IDTVEC(apic_isr6_pti),  /* 192 - 223 */
185         IDTVEC(apic_isr7_pti),  /* 224 - 255 */
186 };
187
188 static u_int32_t lapic_timer_divisors[] = {
189         APIC_TDCR_1, APIC_TDCR_2, APIC_TDCR_4, APIC_TDCR_8, APIC_TDCR_16,
190         APIC_TDCR_32, APIC_TDCR_64, APIC_TDCR_128
191 };
192
193 extern inthand_t IDTVEC(rsvd_pti), IDTVEC(rsvd);
194
195 volatile char *lapic_map;
196 vm_paddr_t lapic_paddr;
197 int x2apic_mode;
198 int lapic_eoi_suppression;
199 static int lapic_timer_tsc_deadline;
200 static u_long lapic_timer_divisor, count_freq;
201 static struct eventtimer lapic_et;
202 #ifdef SMP
203 static uint64_t lapic_ipi_wait_mult;
204 #endif
205 unsigned int max_apic_id;
206
207 SYSCTL_NODE(_hw, OID_AUTO, apic, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
208     "APIC options");
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, "");
214
215 static void lapic_calibrate_initcount(struct lapic *la);
216 static void lapic_calibrate_deadline(struct lapic *la);
217
218 static uint32_t
219 lapic_read32(enum LAPIC_REGISTERS reg)
220 {
221         uint32_t res;
222
223         if (x2apic_mode) {
224                 res = rdmsr32(MSR_APIC_000 + reg);
225         } else {
226                 res = *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL);
227         }
228         return (res);
229 }
230
231 static void
232 lapic_write32(enum LAPIC_REGISTERS reg, uint32_t val)
233 {
234
235         if (x2apic_mode) {
236                 mfence();
237                 lfence();
238                 wrmsr(MSR_APIC_000 + reg, val);
239         } else {
240                 *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL) = val;
241         }
242 }
243
244 static void
245 lapic_write32_nofence(enum LAPIC_REGISTERS reg, uint32_t val)
246 {
247
248         if (x2apic_mode) {
249                 wrmsr(MSR_APIC_000 + reg, val);
250         } else {
251                 *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL) = val;
252         }
253 }
254
255 #ifdef SMP
256 static uint64_t
257 lapic_read_icr_lo(void)
258 {
259
260         return (lapic_read32(LAPIC_ICR_LO));
261 }
262
263 static void
264 lapic_write_icr(uint32_t vhi, uint32_t vlo)
265 {
266         register_t saveintr;
267         uint64_t v;
268
269         if (x2apic_mode) {
270                 v = ((uint64_t)vhi << 32) | vlo;
271                 mfence();
272                 wrmsr(MSR_APIC_000 + LAPIC_ICR_LO, v);
273         } else {
274                 saveintr = intr_disable();
275                 lapic_write32(LAPIC_ICR_HI, vhi);
276                 lapic_write32(LAPIC_ICR_LO, vlo);
277                 intr_restore(saveintr);
278         }
279 }
280
281 static void
282 lapic_write_icr_lo(uint32_t vlo)
283 {
284
285         if (x2apic_mode) {
286                 mfence();
287                 wrmsr(MSR_APIC_000 + LAPIC_ICR_LO, vlo);
288         } else {
289                 lapic_write32(LAPIC_ICR_LO, vlo);
290         }
291 }
292
293 static void
294 lapic_write_self_ipi(uint32_t vector)
295 {
296
297         KASSERT(x2apic_mode, ("SELF IPI write in xAPIC mode"));
298         wrmsr(MSR_APIC_000 + LAPIC_SELF_IPI, vector);
299 }
300 #endif /* SMP */
301
302 static void
303 native_lapic_enable_x2apic(void)
304 {
305         uint64_t apic_base;
306
307         apic_base = rdmsr(MSR_APICBASE);
308         apic_base |= APICBASE_X2APIC | APICBASE_ENABLED;
309         wrmsr(MSR_APICBASE, apic_base);
310 }
311
312 static bool
313 native_lapic_is_x2apic(void)
314 {
315         uint64_t apic_base;
316
317         apic_base = rdmsr(MSR_APICBASE);
318         return ((apic_base & (APICBASE_X2APIC | APICBASE_ENABLED)) ==
319             (APICBASE_X2APIC | APICBASE_ENABLED));
320 }
321
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);
336
337 struct pic lapic_pic = { .pic_resume = lapic_resume };
338
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,
357                     u_int cluster_id);
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,
364                     u_char masked);
365 static int      native_lapic_set_lvt_mode(u_int apic_id, u_int lvt,
366                     uint32_t mode);
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);
371 #ifdef SMP
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);
375 #endif /* SMP */
376 static int      native_lapic_ipi_alloc(inthand_t *ipifunc);
377 static void     native_lapic_ipi_free(int vector);
378
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,
402 #ifdef SMP
403         .ipi_raw                = native_lapic_ipi_raw,
404         .ipi_vectored           = native_lapic_ipi_vectored,
405         .ipi_wait               = native_lapic_ipi_wait,
406 #endif
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,
413 };
414
415 static uint32_t
416 lvt_mode_impl(struct lapic *la, struct lvt *lvt, u_int pin, uint32_t value)
417 {
418
419         value &= ~(APIC_LVT_M | APIC_LVT_TM | APIC_LVT_IIPP | APIC_LVT_DM |
420             APIC_LVT_VECTOR);
421         if (lvt->lvt_edgetrigger == 0)
422                 value |= APIC_LVT_TM;
423         if (lvt->lvt_activehi == 0)
424                 value |= APIC_LVT_IIPP_INTALO;
425         if (lvt->lvt_masked)
426                 value |= APIC_LVT_M;
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",
435                             la->la_id, pin);
436                         value &= ~APIC_LVT_TM;
437                 }
438                 /* Use a vector of 0. */
439                 break;
440         case APIC_LVT_DM_FIXED:
441                 value |= lvt->lvt_vector;
442                 break;
443         default:
444                 panic("bad APIC LVT delivery mode: %#x\n", value);
445         }
446         return (value);
447 }
448
449 static uint32_t
450 lvt_mode(struct lapic *la, u_int pin, uint32_t value)
451 {
452         struct lvt *lvt;
453
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];
458         else
459                 lvt = &lvts[pin];
460
461         return (lvt_mode_impl(la, lvt, pin, value));
462 }
463
464 static uint32_t
465 elvt_mode(struct lapic *la, u_int idx, uint32_t value)
466 {
467         struct lvt *elvt;
468
469         KASSERT(idx <= APIC_ELVT_MAX,
470             ("%s: idx %u out of range", __func__, idx));
471
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));
479 }
480
481 /*
482  * Map the local APIC and setup necessary interrupt vectors.
483  */
484 static void
485 native_lapic_init(vm_paddr_t addr)
486 {
487 #ifdef SMP
488         uint64_t r, r1, r2, rx;
489 #endif
490         uint32_t ver;
491         int i;
492         bool arat;
493
494         /*
495          * Enable x2APIC mode if possible. Map the local APIC
496          * registers page.
497          *
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.
502          */
503         KASSERT(trunc_page(addr) == addr,
504             ("local APIC not aligned on a page boundary"));
505         lapic_paddr = addr;
506         lapic_map = pmap_mapdev(addr, PAGE_SIZE);
507         if (x2apic_mode) {
508                 native_lapic_enable_x2apic();
509                 lapic_map = NULL;
510         }
511
512         /* Setup the spurious interrupt handler. */
513         setidt(APIC_SPURIOUS_INT, IDTVEC(spuriousint), SDT_APIC, SEL_KPL,
514             GSEL_APIC);
515
516         /* Perform basic initialization of the BSP's local APIC. */
517         lapic_enable();
518
519         /* Set BSP's per-CPU local APIC ID. */
520         PCPU_SET(apic_id, lapic_id());
521
522         /* Local APIC timer interrupt. */
523         setidt(APIC_TIMER_INT, pti ? IDTVEC(timerint_pti) : IDTVEC(timerint),
524             SDT_APIC, SEL_KPL, GSEL_APIC);
525
526         /* Local APIC error interrupt. */
527         setidt(APIC_ERROR_INT, pti ? IDTVEC(errorint_pti) : IDTVEC(errorint),
528             SDT_APIC, SEL_KPL, GSEL_APIC);
529
530         /* XXX: Thermal interrupt */
531
532         /* Local APIC CMCI. */
533         setidt(APIC_CMC_INT, pti ? IDTVEC(cmcint_pti) : IDTVEC(cmcint),
534             SDT_APIC, SEL_KPL, GSEL_APIC);
535
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);
539
540                 bzero(&lapic_et, sizeof(lapic_et));
541                 lapic_et.et_name = "LAPIC";
542                 lapic_et.et_flags = ET_FLAGS_PERIODIC | ET_FLAGS_ONESHOT |
543                     ET_FLAGS_PERCPU;
544                 lapic_et.et_quality = 600;
545                 if (!arat) {
546                         lapic_et.et_flags |= ET_FLAGS_C3STOP;
547                         lapic_et.et_quality = 100;
548                 }
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);
555                 }
556
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);
565         }
566
567         /*
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.
573          *
574          * It seems that at least some KVM versions report
575          * EOI_SUPPRESSION bit, but auto-EOI does not work.
576          */
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) {
581                         if (bootverbose)
582                                 printf(
583                        "KVM -- disabling lapic eoi suppression\n");
584                         lapic_eoi_suppression = 0;
585                 }
586                 TUNABLE_INT_FETCH("hw.lapic_eoi_suppression",
587                     &lapic_eoi_suppression);
588         }
589
590 #ifdef SMP
591 #define LOOPS   100000
592         /*
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).
597          *
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.
602          */
603         KASSERT((cpu_feature & CPUID_TSC) != 0 && tsc_freq != 0,
604             ("TSC not initialized"));
605         if (!x2apic_mode) {
606                 r = rdtsc();
607                 for (rx = 0; rx < LOOPS; rx++) {
608                         (void)lapic_read_icr_lo();
609                         ia32_pause();
610                 }
611                 r = rdtsc() - r;
612                 r1 = tsc_freq * LOOPS;
613                 r2 = r * 1000000;
614                 lapic_ipi_wait_mult = r1 >= r2 ? r1 / r2 : 1;
615                 if (bootverbose) {
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);
619                 }
620         }
621 #undef LOOPS
622 #endif /* SMP */
623 }
624
625 /*
626  * Create a local APIC instance.
627  */
628 static void
629 native_lapic_create(u_int apic_id, int boot_cpu)
630 {
631         int i;
632
633         if (apic_id > max_apic_id) {
634                 printf("APIC: Ignoring local APIC with ID %d\n", apic_id);
635                 if (boot_cpu)
636                         panic("Can't ignore BSP");
637                 return;
638         }
639         KASSERT(!lapics[apic_id].la_present, ("duplicate local APIC %u",
640             apic_id));
641
642         /*
643          * Assume no local LVT overrides and a cluster of 0 and
644          * intra-cluster ID of 0.
645          */
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;
651         }
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;
655         }
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] =
660             IRQ_TIMER;
661 #ifdef KDTRACE_HOOKS
662         lapics[apic_id].la_ioint_irqs[IDT_DTRACE_RET - APIC_IO_INTS] =
663             IRQ_DTRACE_RET;
664 #endif
665 #ifdef XENHVM
666         lapics[apic_id].la_ioint_irqs[IDT_EVTCHN - APIC_IO_INTS] = IRQ_EVTCHN;
667 #endif
668
669
670 #ifdef SMP
671         cpu_add(apic_id, boot_cpu);
672 #endif
673 }
674
675 static inline uint32_t
676 amd_read_ext_features(void)
677 {
678         uint32_t version;
679
680         if (cpu_vendor_id != CPU_VENDOR_AMD &&
681             cpu_vendor_id != CPU_VENDOR_HYGON)
682                 return (0);
683         version = lapic_read32(LAPIC_VERSION);
684         if ((version & APIC_VER_AMD_EXT_SPACE) != 0)
685                 return (lapic_read32(LAPIC_EXT_FEATURES));
686         else
687                 return (0);
688 }
689
690 static inline uint32_t
691 amd_read_elvt_count(void)
692 {
693         uint32_t extf;
694         uint32_t count;
695
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);
699         return (count);
700 }
701
702 /*
703  * Dump contents of local APIC registers
704  */
705 static void
706 native_lapic_dump(const char* str)
707 {
708         uint32_t version;
709         uint32_t maxlvt;
710         uint32_t extf;
711         int elvt_count;
712         int i;
713
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));
730         printf("\n");
731         if (maxlvt >= APIC_LVT_CMCI)
732                 printf("   cmci: 0x%08x\n", lapic_read32(LAPIC_LVT_CMCI));
733         extf = amd_read_ext_features();
734         if (extf != 0) {
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));
740         }
741 }
742
743 static void
744 native_lapic_xapic_mode(void)
745 {
746         register_t saveintr;
747
748         saveintr = intr_disable();
749         if (x2apic_mode)
750                 native_lapic_enable_x2apic();
751         intr_restore(saveintr);
752 }
753
754 static void
755 native_lapic_setup(int boot)
756 {
757         struct lapic *la;
758         uint32_t version;
759         uint32_t maxlvt;
760         register_t saveintr;
761         int elvt_count;
762         int i;
763
764         saveintr = intr_disable();
765
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;
770
771         /* Initialize the TPR to allow all interrupts. */
772         lapic_set_tpr(0);
773
774         /* Setup spurious vector and enable the local APIC. */
775         lapic_enable();
776
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)));
782
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,
786                     LAPIC_LVT_PCINT));
787         }
788
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);
794
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);
800         }
801
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",
805                     lapic_id()));
806                 switch (la->la_timer_mode) {
807                 case LAT_MODE_PERIODIC:
808                         lapic_timer_set_divisor(lapic_timer_divisor);
809                         lapic_timer_periodic(la);
810                         break;
811                 case LAT_MODE_ONESHOT:
812                         lapic_timer_set_divisor(lapic_timer_divisor);
813                         lapic_timer_oneshot(la);
814                         break;
815                 case LAT_MODE_DEADLINE:
816                         lapic_timer_deadline(la);
817                         break;
818                 default:
819                         panic("corrupted la_timer_mode %p %d", la,
820                             la->la_timer_mode);
821                 }
822         }
823
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);
828
829         /* XXX: Thermal LVT */
830
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)));
835         }
836
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)));
842         }
843
844         intr_restore(saveintr);
845 }
846
847 static void
848 native_lapic_intrcnt(void *dummy __unused)
849 {
850         struct pcpu *pc;
851         struct lapic *la;
852         char buf[MAXCOMLEN + 1];
853
854         /* If there are no APICs, skip this function. */
855         if (lapics == NULL)
856                 return;
857
858         STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
859                 la = &lapics[pc->pc_apic_id];
860                 if (!la->la_present)
861                     continue;
862
863                 snprintf(buf, sizeof(buf), "cpu%d:timer", pc->pc_cpuid);
864                 intrcnt_add(buf, &la->la_timer_count);
865         }
866 }
867 SYSINIT(native_lapic_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, native_lapic_intrcnt,
868     NULL);
869
870 static void
871 native_lapic_reenable_pmc(void)
872 {
873 #ifdef HWPMC_HOOKS
874         uint32_t value;
875
876         value = lapic_read32(LAPIC_LVT_PCINT);
877         value &= ~APIC_LVT_M;
878         lapic_write32(LAPIC_LVT_PCINT, value);
879 #endif
880 }
881
882 #ifdef HWPMC_HOOKS
883 static void
884 lapic_update_pmc(void *dummy)
885 {
886         struct lapic *la;
887
888         la = &lapics[lapic_id()];
889         lapic_write32(LAPIC_LVT_PCINT, lvt_mode(la, APIC_LVT_PMC,
890             lapic_read32(LAPIC_LVT_PCINT)));
891 }
892 #endif
893
894 static int
895 native_lapic_enable_pmc(void)
896 {
897 #ifdef HWPMC_HOOKS
898         u_int32_t maxlvt;
899
900         /* Fail if the local APIC is not present. */
901         if (!x2apic_mode && lapic_map == NULL)
902                 return (0);
903
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)
907                 return (0);
908
909         lvts[APIC_LVT_PMC].lvt_masked = 0;
910
911 #ifdef EARLY_AP_STARTUP
912         MPASS(mp_ncpus == 1 || smp_started);
913         smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
914 #else
915 #ifdef SMP
916         /*
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.
920          */
921         if (smp_started)
922                 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
923         else
924 #endif
925                 lapic_update_pmc(NULL);
926 #endif
927         return (1);
928 #else
929         return (0);
930 #endif
931 }
932
933 static void
934 native_lapic_disable_pmc(void)
935 {
936 #ifdef HWPMC_HOOKS
937         u_int32_t maxlvt;
938
939         /* Fail if the local APIC is not present. */
940         if (!x2apic_mode && lapic_map == NULL)
941                 return;
942
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)
946                 return;
947
948         lvts[APIC_LVT_PMC].lvt_masked = 1;
949
950 #ifdef SMP
951         /* The APs should always be started when hwpmc is unloaded. */
952         KASSERT(mp_ncpus == 1 || smp_started, ("hwpmc unloaded too early"));
953 #endif
954         smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
955 #endif
956 }
957
958 static void
959 lapic_calibrate_initcount(struct lapic *la)
960 {
961         u_long value;
962
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. */
966         do {
967                 lapic_timer_set_divisor(lapic_timer_divisor);
968                 lapic_timer_oneshot_nointr(la, APIC_TIMER_MAX_COUNT);
969                 DELAY(1000000);
970                 value = APIC_TIMER_MAX_COUNT - lapic_read32(LAPIC_CCR_TIMER);
971                 if (value != APIC_TIMER_MAX_COUNT)
972                         break;
973                 lapic_timer_divisor <<= 1;
974         } while (lapic_timer_divisor <= 128);
975         if (lapic_timer_divisor > 128)
976                 panic("lapic: Divisor too big");
977         if (bootverbose) {
978                 printf("lapic: Divisor %lu, Frequency %lu Hz\n",
979                     lapic_timer_divisor, value);
980         }
981         count_freq = value;
982 }
983
984 static void
985 lapic_calibrate_deadline(struct lapic *la __unused)
986 {
987
988         if (bootverbose) {
989                 printf("lapic: deadline tsc mode, Frequency %ju Hz\n",
990                     (uintmax_t)tsc_freq);
991         }
992 }
993
994 static void
995 lapic_change_mode(struct eventtimer *et, struct lapic *la,
996     enum lat_timer_mode newmode)
997 {
998
999         if (la->la_timer_mode == newmode)
1000                 return;
1001         switch (newmode) {
1002         case LAT_MODE_PERIODIC:
1003                 lapic_timer_set_divisor(lapic_timer_divisor);
1004                 et->et_frequency = count_freq;
1005                 break;
1006         case LAT_MODE_DEADLINE:
1007                 et->et_frequency = tsc_freq;
1008                 break;
1009         case LAT_MODE_ONESHOT:
1010                 lapic_timer_set_divisor(lapic_timer_divisor);
1011                 et->et_frequency = count_freq;
1012                 break;
1013         default:
1014                 panic("lapic_change_mode %d", newmode);
1015         }
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;
1019 }
1020
1021 static int
1022 lapic_et_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
1023 {
1024         struct lapic *la;
1025
1026         la = &lapics[PCPU_GET(apic_id)];
1027         if (period != 0) {
1028                 lapic_change_mode(et, la, LAT_MODE_PERIODIC);
1029                 la->la_timer_period = ((uint32_t)et->et_frequency * period) >>
1030                     32;
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);
1036         } else {
1037                 lapic_change_mode(et, la, LAT_MODE_ONESHOT);
1038                 la->la_timer_period = ((uint32_t)et->et_frequency * first) >>
1039                     32;
1040                 lapic_timer_oneshot(la);
1041         }
1042         return (0);
1043 }
1044
1045 static int
1046 lapic_et_stop(struct eventtimer *et)
1047 {
1048         struct lapic *la;
1049
1050         la = &lapics[PCPU_GET(apic_id)];
1051         lapic_timer_stop(la);
1052         la->la_timer_mode = LAT_MODE_UNDEF;
1053         return (0);
1054 }
1055
1056 static void
1057 native_lapic_disable(void)
1058 {
1059         uint32_t value;
1060
1061         /* Software disable the local APIC. */
1062         value = lapic_read32(LAPIC_SVR);
1063         value &= ~APIC_SVR_SWEN;
1064         lapic_write32(LAPIC_SVR, value);
1065 }
1066
1067 static void
1068 lapic_enable(void)
1069 {
1070         uint32_t value;
1071
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);
1079 }
1080
1081 /* Reset the local APIC on the BSP during resume. */
1082 static void
1083 lapic_resume(struct pic *pic, bool suspend_cancelled)
1084 {
1085
1086         lapic_setup(0);
1087 }
1088
1089 static int
1090 native_lapic_id(void)
1091 {
1092         uint32_t v;
1093
1094         KASSERT(x2apic_mode || lapic_map != NULL, ("local APIC is not mapped"));
1095         v = lapic_read32(LAPIC_ID);
1096         if (!x2apic_mode)
1097                 v >>= APIC_ID_SHIFT;
1098         return (v);
1099 }
1100
1101 static int
1102 native_lapic_intr_pending(u_int vector)
1103 {
1104         uint32_t irr;
1105
1106         /*
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.
1112          */
1113         irr = lapic_read32(LAPIC_IRR0 + vector / 32);
1114         return (irr & 1 << (vector % 32));
1115 }
1116
1117 static void
1118 native_lapic_set_logical_id(u_int apic_id, u_int cluster, u_int cluster_id)
1119 {
1120         struct lapic *la;
1121
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;
1131 }
1132
1133 static int
1134 native_lapic_set_lvt_mask(u_int apic_id, u_int pin, u_char masked)
1135 {
1136
1137         if (pin > APIC_LVT_MAX)
1138                 return (EINVAL);
1139         if (apic_id == APIC_ID_ALL) {
1140                 lvts[pin].lvt_masked = masked;
1141                 if (bootverbose)
1142                         printf("lapic:");
1143         } else {
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;
1148                 if (bootverbose)
1149                         printf("lapic%u:", apic_id);
1150         }
1151         if (bootverbose)
1152                 printf(" LINT%u %s\n", pin, masked ? "masked" : "unmasked");
1153         return (0);
1154 }
1155
1156 static int
1157 native_lapic_set_lvt_mode(u_int apic_id, u_int pin, u_int32_t mode)
1158 {
1159         struct lvt *lvt;
1160
1161         if (pin > APIC_LVT_MAX)
1162                 return (EINVAL);
1163         if (apic_id == APIC_ID_ALL) {
1164                 lvt = &lvts[pin];
1165                 if (bootverbose)
1166                         printf("lapic:");
1167         } else {
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;
1172                 if (bootverbose)
1173                         printf("lapic%u:", apic_id);
1174         }
1175         lvt->lvt_mode = mode;
1176         switch (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;
1185                 else
1186                         lvt->lvt_masked = 0;
1187                 break;
1188         default:
1189                 panic("Unsupported delivery mode: 0x%x\n", mode);
1190         }
1191         if (bootverbose) {
1192                 printf(" Routing ");
1193                 switch (mode) {
1194                 case APIC_LVT_DM_NMI:
1195                         printf("NMI");
1196                         break;
1197                 case APIC_LVT_DM_SMI:
1198                         printf("SMI");
1199                         break;
1200                 case APIC_LVT_DM_INIT:
1201                         printf("INIT");
1202                         break;
1203                 case APIC_LVT_DM_EXTINT:
1204                         printf("ExtINT");
1205                         break;
1206                 }
1207                 printf(" -> LINT%u\n", pin);
1208         }
1209         return (0);
1210 }
1211
1212 static int
1213 native_lapic_set_lvt_polarity(u_int apic_id, u_int pin, enum intr_polarity pol)
1214 {
1215
1216         if (pin > APIC_LVT_MAX || pol == INTR_POLARITY_CONFORM)
1217                 return (EINVAL);
1218         if (apic_id == APIC_ID_ALL) {
1219                 lvts[pin].lvt_activehi = (pol == INTR_POLARITY_HIGH);
1220                 if (bootverbose)
1221                         printf("lapic:");
1222         } else {
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);
1228                 if (bootverbose)
1229                         printf("lapic%u:", apic_id);
1230         }
1231         if (bootverbose)
1232                 printf(" LINT%u polarity: %s\n", pin,
1233                     pol == INTR_POLARITY_HIGH ? "high" : "low");
1234         return (0);
1235 }
1236
1237 static int
1238 native_lapic_set_lvt_triggermode(u_int apic_id, u_int pin,
1239      enum intr_trigger trigger)
1240 {
1241
1242         if (pin > APIC_LVT_MAX || trigger == INTR_TRIGGER_CONFORM)
1243                 return (EINVAL);
1244         if (apic_id == APIC_ID_ALL) {
1245                 lvts[pin].lvt_edgetrigger = (trigger == INTR_TRIGGER_EDGE);
1246                 if (bootverbose)
1247                         printf("lapic:");
1248         } else {
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;
1254                 if (bootverbose)
1255                         printf("lapic%u:", apic_id);
1256         }
1257         if (bootverbose)
1258                 printf(" LINT%u trigger: %s\n", pin,
1259                     trigger == INTR_TRIGGER_EDGE ? "edge" : "level");
1260         return (0);
1261 }
1262
1263 /*
1264  * Adjust the TPR of the current CPU so that it blocks all interrupts below
1265  * the passed in vector.
1266  */
1267 static void
1268 lapic_set_tpr(u_int vector)
1269 {
1270 #ifdef CHEAP_TPR
1271         lapic_write32(LAPIC_TPR, vector);
1272 #else
1273         uint32_t tpr;
1274
1275         tpr = lapic_read32(LAPIC_TPR) & ~APIC_TPR_PRIO;
1276         tpr |= vector;
1277         lapic_write32(LAPIC_TPR, tpr);
1278 #endif
1279 }
1280
1281 static void
1282 native_lapic_eoi(void)
1283 {
1284
1285         lapic_write32_nofence(LAPIC_EOI, 0);
1286 }
1287
1288 void
1289 lapic_handle_intr(int vector, struct trapframe *frame)
1290 {
1291         struct intsrc *isrc;
1292
1293         isrc = intr_lookup_source(apic_idt_to_irq(PCPU_GET(apic_id),
1294             vector));
1295         intr_execute_handlers(isrc, frame);
1296 }
1297
1298 void
1299 lapic_handle_timer(struct trapframe *frame)
1300 {
1301         struct lapic *la;
1302         struct trapframe *oldframe;
1303         struct thread *td;
1304
1305         /* Send EOI first thing. */
1306         lapic_eoi();
1307
1308 #if defined(SMP) && !defined(SCHED_ULE)
1309         /*
1310          * Don't do any accounting for the disabled HTT cores, since it
1311          * will provide misleading numbers for the userland.
1312          *
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.
1315          *
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
1318          * those CPUs.
1319          */
1320         if (CPU_ISSET(PCPU_GET(cpuid), &hlt_cpus_mask))
1321                 return;
1322 #endif
1323
1324         /* Look up our local APIC structure for the tick counters. */
1325         la = &lapics[PCPU_GET(apic_id)];
1326         (*la->la_timer_count)++;
1327         critical_enter();
1328         if (lapic_et.et_active) {
1329                 td = curthread;
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--;
1336         }
1337         critical_exit();
1338 }
1339
1340 static void
1341 lapic_timer_set_divisor(u_int divisor)
1342 {
1343
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]);
1348 }
1349
1350 static void
1351 lapic_timer_oneshot(struct lapic *la)
1352 {
1353         uint32_t value;
1354
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);
1361 }
1362
1363 static void
1364 lapic_timer_oneshot_nointr(struct lapic *la, uint32_t count)
1365 {
1366         uint32_t value;
1367
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);
1374 }
1375
1376 static void
1377 lapic_timer_periodic(struct lapic *la)
1378 {
1379         uint32_t value;
1380
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);
1387 }
1388
1389 static void
1390 lapic_timer_deadline(struct lapic *la)
1391 {
1392         uint32_t value;
1393
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);
1400                 if (!x2apic_mode)
1401                         mfence();
1402         }
1403         wrmsr(MSR_TSC_DEADLINE, la->la_timer_period + rdtsc());
1404 }
1405
1406 static void
1407 lapic_timer_stop(struct lapic *la)
1408 {
1409         uint32_t value;
1410
1411         if (la->la_timer_mode == LAT_MODE_DEADLINE) {
1412                 wrmsr(MSR_TSC_DEADLINE, 0);
1413                 mfence();
1414         } else {
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);
1420         }
1421 }
1422
1423 void
1424 lapic_handle_cmc(void)
1425 {
1426
1427         lapic_eoi();
1428         cmc_intr();
1429 }
1430
1431 /*
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.
1436  */
1437 static void
1438 native_lapic_enable_cmc(void)
1439 {
1440         u_int apic_id;
1441
1442 #ifdef DEV_ATPIC
1443         if (!x2apic_mode && lapic_map == NULL)
1444                 return;
1445 #endif
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;
1451         if (bootverbose)
1452                 printf("lapic%u: CMCI unmasked\n", apic_id);
1453 }
1454
1455 static int
1456 native_lapic_enable_mca_elvt(void)
1457 {
1458         u_int apic_id;
1459         uint32_t value;
1460         int elvt_count;
1461
1462 #ifdef DEV_ATPIC
1463         if (lapic_map == NULL)
1464                 return (-1);
1465 #endif
1466
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)
1472                 return (-1);
1473
1474         value = lapic_read32(LAPIC_EXT_LVT0 + APIC_ELVT_MCA);
1475         if ((value & APIC_LVT_M) == 0) {
1476                 if (bootverbose)
1477                         printf("AMD MCE Thresholding Extended LVT is already active\n");
1478                 return (APIC_ELVT_MCA);
1479         }
1480         lapics[apic_id].la_elvts[APIC_ELVT_MCA].lvt_masked = 0;
1481         lapics[apic_id].la_elvts[APIC_ELVT_MCA].lvt_active = 1;
1482         if (bootverbose)
1483                 printf("lapic%u: MCE Thresholding ELVT unmasked\n", apic_id);
1484         return (APIC_ELVT_MCA);
1485 }
1486
1487 void
1488 lapic_handle_error(void)
1489 {
1490         uint32_t esr;
1491
1492         /*
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.
1497          */
1498         lapic_write32(LAPIC_ESR, 0);
1499         esr = lapic_read32(LAPIC_ESR);
1500
1501         printf("CPU%d: local APIC error 0x%x\n", PCPU_GET(cpuid), esr);
1502         lapic_eoi();
1503 }
1504
1505 static u_int
1506 native_apic_cpuid(u_int apic_id)
1507 {
1508 #ifdef SMP
1509         return apic_cpuids[apic_id];
1510 #else
1511         return 0;
1512 #endif
1513 }
1514
1515 /* Request a free IDT vector to be used by the specified IRQ. */
1516 static u_int
1517 native_apic_alloc_vector(u_int apic_id, u_int irq)
1518 {
1519         u_int vector;
1520
1521         KASSERT(irq < num_io_irqs, ("Invalid IRQ %u", irq));
1522
1523         /*
1524          * Search for a free vector.  Currently we just use a very simple
1525          * algorithm to find the first free vector.
1526          */
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)
1530                         continue;
1531                 lapics[apic_id].la_ioint_irqs[vector] = irq;
1532                 mtx_unlock_spin(&icu_lock);
1533                 return (vector + APIC_IO_INTS);
1534         }
1535         mtx_unlock_spin(&icu_lock);
1536         return (0);
1537 }
1538
1539 /*
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.
1544  */
1545 static u_int
1546 native_apic_alloc_vectors(u_int apic_id, u_int *irqs, u_int count, u_int align)
1547 {
1548         u_int first, run, vector;
1549
1550         KASSERT(powerof2(count), ("bad count"));
1551         KASSERT(powerof2(align), ("bad align"));
1552         KASSERT(align >= count, ("align < count"));
1553 #ifdef INVARIANTS
1554         for (run = 0; run < count; run++)
1555                 KASSERT(irqs[run] < num_io_irqs, ("Invalid IRQ %u at index %u",
1556                     irqs[run], run));
1557 #endif
1558
1559         /*
1560          * Search for 'count' free vectors.  As with apic_alloc_vector(),
1561          * this just uses a simple first fit algorithm.
1562          */
1563         run = 0;
1564         first = 0;
1565         mtx_lock_spin(&icu_lock);
1566         for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
1567
1568                 /* Vector is in use, end run. */
1569                 if (lapics[apic_id].la_ioint_irqs[vector] != IRQ_FREE) {
1570                         run = 0;
1571                         first = 0;
1572                         continue;
1573                 }
1574
1575                 /* Start a new run if run == 0 and vector is aligned. */
1576                 if (run == 0) {
1577                         if ((vector & (align - 1)) != 0)
1578                                 continue;
1579                         first = vector;
1580                 }
1581                 run++;
1582
1583                 /* Keep looping if the run isn't long enough yet. */
1584                 if (run < count)
1585                         continue;
1586
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] =
1590                             irqs[vector];
1591                 mtx_unlock_spin(&icu_lock);
1592                 return (first + APIC_IO_INTS);
1593         }
1594         mtx_unlock_spin(&icu_lock);
1595         printf("APIC: Couldn't find APIC vectors for %u IRQs\n", count);
1596         return (0);
1597 }
1598
1599 /*
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
1603  * should it fire.
1604  */
1605 static void
1606 native_apic_enable_vector(u_int apic_id, u_int vector)
1607 {
1608
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"));
1615 #endif
1616         setidt(vector, (pti ? ioint_pti_handlers : ioint_handlers)[vector / 32],
1617             SDT_APIC, SEL_KPL, GSEL_APIC);
1618 }
1619
1620 static void
1621 native_apic_disable_vector(u_int apic_id, u_int vector)
1622 {
1623
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"));
1628 #endif
1629         KASSERT(ioint_handlers[vector / 32] != NULL,
1630             ("No ISR handler for vector %u", vector));
1631 #ifdef notyet
1632         /*
1633          * We can not currently clear the idt entry because other cpus
1634          * may have a valid vector at this offset.
1635          */
1636         setidt(vector, pti ? &IDTVEC(rsvd_pti) : &IDTVEC(rsvd), SDT_APIC,
1637             SEL_KPL, GSEL_APIC);
1638 #endif
1639 }
1640
1641 /* Release an APIC vector when it's no longer in use. */
1642 static void
1643 native_apic_free_vector(u_int apic_id, u_int vector, u_int irq)
1644 {
1645         struct thread *td;
1646
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"));
1656 #endif
1657
1658         /*
1659          * Bind us to the cpu that owned the vector before freeing it so
1660          * we don't lose an interrupt delivery race.
1661          */
1662         td = curthread;
1663         if (!rebooting) {
1664                 thread_lock(td);
1665                 if (sched_is_bound(td))
1666                         panic("apic_free_vector: Thread already bound.\n");
1667                 sched_bind(td, apic_cpuid(apic_id));
1668                 thread_unlock(td);
1669         }
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);
1673         if (!rebooting) {
1674                 thread_lock(td);
1675                 sched_unbind(td);
1676                 thread_unlock(td);
1677         }
1678 }
1679
1680 /* Map an IDT vector (APIC) to an IRQ (interrupt source). */
1681 static u_int
1682 apic_idt_to_irq(u_int apic_id, u_int vector)
1683 {
1684         int irq;
1685
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"));
1692 #endif
1693         irq = lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS];
1694         if (irq < 0)
1695                 irq = 0;
1696         return (irq);
1697 }
1698
1699 #ifdef DDB
1700 /*
1701  * Dump data about APIC IDT vector mappings.
1702  */
1703 DB_SHOW_COMMAND(apic, db_show_apic)
1704 {
1705         struct intsrc *isrc;
1706         int i, verbose;
1707         u_int apic_id;
1708         u_int irq;
1709
1710         if (strcmp(modif, "vv") == 0)
1711                 verbose = 2;
1712         else if (strcmp(modif, "v") == 0)
1713                 verbose = 1;
1714         else
1715                 verbose = 0;
1716         for (apic_id = 0; apic_id <= max_apic_id; apic_id++) {
1717                 if (lapics[apic_id].la_present == 0)
1718                         continue;
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)
1723                                 continue;
1724 #ifdef KDTRACE_HOOKS
1725                         if (irq == IRQ_DTRACE_RET)
1726                                 continue;
1727 #endif
1728 #ifdef XENHVM
1729                         if (irq == IRQ_EVTCHN)
1730                                 continue;
1731 #endif
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);
1739                                 else
1740                                         db_dump_intr_event(isrc->is_event,
1741                                             verbose == 2);
1742                         } else
1743                                 db_printf("IRQ %u ???\n", irq);
1744                 }
1745         }
1746 }
1747
1748 static void
1749 dump_mask(const char *prefix, uint32_t v, int base)
1750 {
1751         int i, first;
1752
1753         first = 1;
1754         for (i = 0; i < 32; i++)
1755                 if (v & (1 << i)) {
1756                         if (first) {
1757                                 db_printf("%s:", prefix);
1758                                 first = 0;
1759                         }
1760                         db_printf(" %02x", base + i);
1761                 }
1762         if (!first)
1763                 db_printf("\n");
1764 }
1765
1766 /* Show info from the lapic regs for this CPU. */
1767 DB_SHOW_COMMAND(lapic, db_show_lapic)
1768 {
1769         uint32_t v;
1770
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,
1774             v & 0xf);
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));
1780
1781 #define dump_field(prefix, regn, index)                                 \
1782         dump_mask(__XSTRING(prefix ## index),                           \
1783             lapic_read32(LAPIC_ ## regn ## index),                      \
1784             index * 32)
1785
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);
1795
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);
1805
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);
1815
1816 #undef dump_field
1817 }
1818 #endif
1819
1820 /*
1821  * APIC probing support code.  This includes code to manage enumerators.
1822  */
1823
1824 static SLIST_HEAD(, apic_enumerator) enumerators =
1825         SLIST_HEAD_INITIALIZER(enumerators);
1826 static struct apic_enumerator *best_enum;
1827
1828 void
1829 apic_register_enumerator(struct apic_enumerator *enumerator)
1830 {
1831 #ifdef INVARIANTS
1832         struct apic_enumerator *apic_enum;
1833
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);
1838         }
1839 #endif
1840         SLIST_INSERT_HEAD(&enumerators, enumerator, apic_next);
1841 }
1842
1843 /*
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
1846  * process.
1847  */
1848 static void
1849 apic_init(void *dummy __unused)
1850 {
1851         struct apic_enumerator *enumerator;
1852         int retval, best;
1853
1854         /* We only support built in local APICs. */
1855         if (!(cpu_feature & CPUID_APIC))
1856                 return;
1857
1858         /* Don't probe if APIC mode is disabled. */
1859         if (resource_disabled("apic", 0))
1860                 return;
1861
1862         /* Probe all the enumerators to find the best match. */
1863         best_enum = NULL;
1864         best = 0;
1865         SLIST_FOREACH(enumerator, &enumerators, apic_next) {
1866                 retval = enumerator->apic_probe();
1867                 if (retval > 0)
1868                         continue;
1869                 if (best_enum == NULL || best < retval) {
1870                         best_enum = enumerator;
1871                         best = retval;
1872                 }
1873         }
1874         if (best_enum == NULL) {
1875                 if (bootverbose)
1876                         printf("APIC: Could not find any APICs.\n");
1877 #ifndef DEV_ATPIC
1878                 panic("running without device atpic requires a local APIC");
1879 #endif
1880                 return;
1881         }
1882
1883         if (bootverbose)
1884                 printf("APIC: Using the %s enumerator.\n",
1885                     best_enum->apic_name);
1886
1887 #ifdef I686_CPU
1888         /*
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.
1892          */
1893         ppro_reenable_apic();
1894 #endif
1895
1896         /* Probe the CPU's in the system. */
1897         retval = best_enum->apic_probe_cpus();
1898         if (retval != 0)
1899                 printf("%s: Failed to probe CPUs: returned %d\n",
1900                     best_enum->apic_name, retval);
1901
1902 }
1903 SYSINIT(apic_init, SI_SUB_TUNABLES - 1, SI_ORDER_SECOND, apic_init, NULL);
1904
1905 /*
1906  * Setup the local APIC.  We have to do this prior to starting up the APs
1907  * in the SMP case.
1908  */
1909 static void
1910 apic_setup_local(void *dummy __unused)
1911 {
1912         int retval;
1913
1914         if (best_enum == NULL)
1915                 return;
1916
1917         lapics = malloc(sizeof(*lapics) * (max_apic_id + 1), M_LAPIC,
1918             M_WAITOK | M_ZERO);
1919
1920         /* Initialize the local APIC. */
1921         retval = best_enum->apic_setup_local();
1922         if (retval != 0)
1923                 printf("%s: Failed to setup the local APIC: returned %d\n",
1924                     best_enum->apic_name, retval);
1925 }
1926 SYSINIT(apic_setup_local, SI_SUB_CPU, SI_ORDER_SECOND, apic_setup_local, NULL);
1927
1928 /*
1929  * Setup the I/O APICs.
1930  */
1931 static void
1932 apic_setup_io(void *dummy __unused)
1933 {
1934         int retval;
1935
1936         if (best_enum == NULL)
1937                 return;
1938
1939         /*
1940          * Local APIC must be registered before other PICs and pseudo PICs
1941          * for proper suspend/resume order.
1942          */
1943         intr_register_pic(&lapic_pic);
1944
1945         retval = best_enum->apic_setup_io();
1946         if (retval != 0)
1947                 printf("%s: Failed to setup I/O APICs: returned %d\n",
1948                     best_enum->apic_name, retval);
1949
1950         /*
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.
1955          */
1956         lapic_setup(1);
1957         if (bootverbose)
1958                 lapic_dump("BSP");
1959
1960         /* Enable the MSI "pic". */
1961         init_ops.msi_init();
1962
1963 #ifdef XENHVM
1964         xen_intr_alloc_irqs();
1965 #endif
1966 }
1967 SYSINIT(apic_setup_io, SI_SUB_INTR, SI_ORDER_THIRD, apic_setup_io, NULL);
1968
1969 #ifdef SMP
1970 /*
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.
1974  */
1975
1976 /*
1977  * Wait delay microseconds for IPI to be sent.  If delay is -1, we
1978  * wait forever.
1979  */
1980 static int
1981 native_lapic_ipi_wait(int delay)
1982 {
1983         uint64_t rx;
1984
1985         /* LAPIC_ICR.APIC_DELSTAT_MASK is undefined in x2APIC mode */
1986         if (x2apic_mode)
1987                 return (1);
1988
1989         for (rx = 0; delay == -1 || rx < lapic_ipi_wait_mult * delay; rx++) {
1990                 if ((lapic_read_icr_lo() & APIC_DELSTAT_MASK) ==
1991                     APIC_DELSTAT_IDLE)
1992                         return (1);
1993                 ia32_pause();
1994         }
1995         return (0);
1996 }
1997
1998 static void
1999 native_lapic_ipi_raw(register_t icrlo, u_int dest)
2000 {
2001         uint32_t icrhi;
2002
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__));
2011
2012         if ((icrlo & APIC_DEST_MASK) == APIC_DEST_DESTFLD) {
2013                 if (x2apic_mode)
2014                         icrhi = dest;
2015                 else
2016                         icrhi = dest << APIC_ID_SHIFT;
2017                 lapic_write_icr(icrhi, icrlo);
2018         } else {
2019                 lapic_write_icr_lo(icrlo);
2020         }
2021 }
2022
2023 #define BEFORE_SPIN     50000
2024 #ifdef DETECT_DEADLOCK
2025 #define AFTER_SPIN      50
2026 #endif
2027
2028 static void
2029 native_lapic_ipi_vectored(u_int vector, int dest)
2030 {
2031         register_t icrlo, destfield;
2032
2033         KASSERT((vector & ~APIC_VECTOR_MASK) == 0,
2034             ("%s: invalid vector %d", __func__, vector));
2035
2036         destfield = 0;
2037         switch (dest) {
2038         case APIC_IPI_DEST_SELF:
2039                 if (x2apic_mode && vector < IPI_NMI_FIRST) {
2040                         lapic_write_self_ipi(vector);
2041                         return;
2042                 }
2043                 icrlo = APIC_DEST_SELF;
2044                 break;
2045         case APIC_IPI_DEST_ALL:
2046                 icrlo = APIC_DEST_ALLISELF;
2047                 break;
2048         case APIC_IPI_DEST_OTHERS:
2049                 icrlo = APIC_DEST_ALLESELF;
2050                 break;
2051         default:
2052                 icrlo = 0;
2053                 KASSERT(x2apic_mode ||
2054                     (dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
2055                     ("%s: invalid destination 0x%x", __func__, dest));
2056                 destfield = dest;
2057         }
2058
2059         /*
2060          * NMI IPIs are just fake vectors used to send a NMI.  Use special rules
2061          * regarding NMIs if passed, otherwise specify the vector.
2062          */
2063         if (vector >= IPI_NMI_FIRST)
2064                 icrlo |= APIC_DELMODE_NMI;
2065         else
2066                 icrlo |= vector | APIC_DELMODE_FIXED;
2067         icrlo |= APIC_DESTMODE_PHY | APIC_TRIGMOD_EDGE | APIC_LEVEL_ASSERT;
2068
2069         /* Wait for an earlier IPI to finish. */
2070         if (!lapic_ipi_wait(BEFORE_SPIN)) {
2071                 if (KERNEL_PANICKED())
2072                         return;
2073                 else
2074                         panic("APIC: Previous IPI is stuck");
2075         }
2076
2077         lapic_ipi_raw(icrlo, destfield);
2078
2079 #ifdef DETECT_DEADLOCK
2080         /* Wait for IPI to be delivered. */
2081         if (!lapic_ipi_wait(AFTER_SPIN)) {
2082 #ifdef needsattention
2083                 /*
2084                  * XXX FIXME:
2085                  *
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
2091                  * sent.
2092                  *
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
2096                  * returns.
2097                  */
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)
2102                         ia32_pause();
2103 #endif /* needsattention */
2104         }
2105 #endif /* DETECT_DEADLOCK */
2106 }
2107
2108 #endif /* SMP */
2109
2110 /*
2111  * Since the IDT is shared by all CPUs the IPI slot update needs to be globally
2112  * visible.
2113  *
2114  * Consider the case where an IPI is generated immediately after allocation:
2115  *     vector = lapic_ipi_alloc(ipifunc);
2116  *     ipi_selected(other_cpus, vector);
2117  *
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.
2122  */
2123 static int
2124 native_lapic_ipi_alloc(inthand_t *ipifunc)
2125 {
2126         struct gate_descriptor *ip;
2127         long func;
2128         int idx, vector;
2129
2130         KASSERT(ipifunc != &IDTVEC(rsvd) && ipifunc != &IDTVEC(rsvd_pti),
2131             ("invalid ipifunc %p", ipifunc));
2132
2133         vector = -1;
2134         mtx_lock_spin(&icu_lock);
2135         for (idx = IPI_DYN_FIRST; idx <= IPI_DYN_LAST; idx++) {
2136                 ip = &idt[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))) {
2140                         vector = idx;
2141                         setidt(vector, ipifunc, SDT_APIC, SEL_KPL, GSEL_APIC);
2142                         break;
2143                 }
2144         }
2145         mtx_unlock_spin(&icu_lock);
2146         return (vector);
2147 }
2148
2149 static void
2150 native_lapic_ipi_free(int vector)
2151 {
2152         struct gate_descriptor *ip;
2153         long func;
2154
2155         KASSERT(vector >= IPI_DYN_FIRST && vector <= IPI_DYN_LAST,
2156             ("%s: invalid vector %d", __func__, vector));
2157
2158         mtx_lock_spin(&icu_lock);
2159         ip = &idt[vector];
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);
2167 }