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