]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/x86/x86/local_apic.c
Update clang to trunk r256945.
[FreeBSD/FreeBSD.git] / sys / x86 / x86 / local_apic.c
1 /*-
2  * Copyright (c) 2003 John Baldwin <jhb@FreeBSD.org>
3  * Copyright (c) 1996, by Steve Passe
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. The name of the developer may NOT be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  * 3. Neither the name of the author nor the names of any co-contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 /*
31  * Local APIC support on Pentium and later processors.
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_atpic.h"
38 #include "opt_hwpmc_hooks.h"
39
40 #include "opt_ddb.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/bus.h>
45 #include <sys/kernel.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/pcpu.h>
49 #include <sys/proc.h>
50 #include <sys/sched.h>
51 #include <sys/smp.h>
52 #include <sys/sysctl.h>
53 #include <sys/timeet.h>
54
55 #include <vm/vm.h>
56 #include <vm/pmap.h>
57
58 #include <x86/apicreg.h>
59 #include <machine/cpufunc.h>
60 #include <machine/cputypes.h>
61 #include <machine/frame.h>
62 #include <machine/intr_machdep.h>
63 #include <x86/apicvar.h>
64 #include <x86/mca.h>
65 #include <machine/md_var.h>
66 #include <machine/smp.h>
67 #include <machine/specialreg.h>
68 #include <x86/init.h>
69
70 #ifdef DDB
71 #include <sys/interrupt.h>
72 #include <ddb/ddb.h>
73 #endif
74
75 #ifdef __amd64__
76 #define SDT_APIC        SDT_SYSIGT
77 #define SDT_APICT       SDT_SYSIGT
78 #define GSEL_APIC       0
79 #else
80 #define SDT_APIC        SDT_SYS386IGT
81 #define SDT_APICT       SDT_SYS386TGT
82 #define GSEL_APIC       GSEL(GCODE_SEL, SEL_KPL)
83 #endif
84
85 /* Sanity checks on IDT vectors. */
86 CTASSERT(APIC_IO_INTS + APIC_NUM_IOINTS == APIC_TIMER_INT);
87 CTASSERT(APIC_TIMER_INT < APIC_LOCAL_INTS);
88 CTASSERT(APIC_LOCAL_INTS == 240);
89 CTASSERT(IPI_STOP < APIC_SPURIOUS_INT);
90
91 /* Magic IRQ values for the timer and syscalls. */
92 #define IRQ_TIMER       (NUM_IO_INTS + 1)
93 #define IRQ_SYSCALL     (NUM_IO_INTS + 2)
94 #define IRQ_DTRACE_RET  (NUM_IO_INTS + 3)
95 #define IRQ_EVTCHN      (NUM_IO_INTS + 4)
96
97 /*
98  * Support for local APICs.  Local APICs manage interrupts on each
99  * individual processor as opposed to I/O APICs which receive interrupts
100  * from I/O devices and then forward them on to the local APICs.
101  *
102  * Local APICs can also send interrupts to each other thus providing the
103  * mechanism for IPIs.
104  */
105
106 struct lvt {
107         u_int lvt_edgetrigger:1;
108         u_int lvt_activehi:1;
109         u_int lvt_masked:1;
110         u_int lvt_active:1;
111         u_int lvt_mode:16;
112         u_int lvt_vector:8;
113 };
114
115 struct lapic {
116         struct lvt la_lvts[APIC_LVT_MAX + 1];
117         u_int la_id:8;
118         u_int la_cluster:4;
119         u_int la_cluster_id:2;
120         u_int la_present:1;
121         u_long *la_timer_count;
122         u_long la_timer_period;
123         u_int la_timer_mode;
124         uint32_t lvt_timer_cache;
125         /* Include IDT_SYSCALL to make indexing easier. */
126         int la_ioint_irqs[APIC_NUM_IOINTS + 1];
127 } static lapics[MAX_APIC_ID + 1];
128
129 /* Global defaults for local APIC LVT entries. */
130 static struct lvt lvts[APIC_LVT_MAX + 1] = {
131         { 1, 1, 1, 1, APIC_LVT_DM_EXTINT, 0 },  /* LINT0: masked ExtINT */
132         { 1, 1, 0, 1, APIC_LVT_DM_NMI, 0 },     /* LINT1: NMI */
133         { 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_TIMER_INT },      /* Timer */
134         { 1, 1, 0, 1, APIC_LVT_DM_FIXED, APIC_ERROR_INT },      /* Error */
135         { 1, 1, 1, 1, APIC_LVT_DM_NMI, 0 },     /* PMC */
136         { 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_THERMAL_INT },    /* Thermal */
137         { 1, 1, 1, 1, APIC_LVT_DM_FIXED, APIC_CMC_INT },        /* CMCI */
138 };
139
140 static inthand_t *ioint_handlers[] = {
141         NULL,                   /* 0 - 31 */
142         IDTVEC(apic_isr1),      /* 32 - 63 */
143         IDTVEC(apic_isr2),      /* 64 - 95 */
144         IDTVEC(apic_isr3),      /* 96 - 127 */
145         IDTVEC(apic_isr4),      /* 128 - 159 */
146         IDTVEC(apic_isr5),      /* 160 - 191 */
147         IDTVEC(apic_isr6),      /* 192 - 223 */
148         IDTVEC(apic_isr7),      /* 224 - 255 */
149 };
150
151
152 static u_int32_t lapic_timer_divisors[] = {
153         APIC_TDCR_1, APIC_TDCR_2, APIC_TDCR_4, APIC_TDCR_8, APIC_TDCR_16,
154         APIC_TDCR_32, APIC_TDCR_64, APIC_TDCR_128
155 };
156
157 extern inthand_t IDTVEC(rsvd);
158
159 volatile char *lapic_map;
160 vm_paddr_t lapic_paddr;
161 int x2apic_mode;
162 int lapic_eoi_suppression;
163 static u_long lapic_timer_divisor;
164 static struct eventtimer lapic_et;
165
166 SYSCTL_NODE(_hw, OID_AUTO, apic, CTLFLAG_RD, 0, "APIC options");
167 SYSCTL_INT(_hw_apic, OID_AUTO, x2apic_mode, CTLFLAG_RD, &x2apic_mode, 0, "");
168 SYSCTL_INT(_hw_apic, OID_AUTO, eoi_suppression, CTLFLAG_RD,
169     &lapic_eoi_suppression, 0, "");
170
171 static uint32_t
172 lapic_read32(enum LAPIC_REGISTERS reg)
173 {
174         uint32_t res;
175
176         if (x2apic_mode) {
177                 res = rdmsr32(MSR_APIC_000 + reg);
178         } else {
179                 res = *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL);
180         }
181         return (res);
182 }
183
184 static void
185 lapic_write32(enum LAPIC_REGISTERS reg, uint32_t val)
186 {
187
188         if (x2apic_mode) {
189                 mfence();
190                 wrmsr(MSR_APIC_000 + reg, val);
191         } else {
192                 *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL) = val;
193         }
194 }
195
196 static void
197 lapic_write32_nofence(enum LAPIC_REGISTERS reg, uint32_t val)
198 {
199
200         if (x2apic_mode) {
201                 wrmsr(MSR_APIC_000 + reg, val);
202         } else {
203                 *(volatile uint32_t *)(lapic_map + reg * LAPIC_MEM_MUL) = val;
204         }
205 }
206
207 #ifdef SMP
208 static uint64_t
209 lapic_read_icr(void)
210 {
211         uint64_t v;
212         uint32_t vhi, vlo;
213
214         if (x2apic_mode) {
215                 v = rdmsr(MSR_APIC_000 + LAPIC_ICR_LO);
216         } else {
217                 vhi = lapic_read32(LAPIC_ICR_HI);
218                 vlo = lapic_read32(LAPIC_ICR_LO);
219                 v = ((uint64_t)vhi << 32) | vlo;
220         }
221         return (v);
222 }
223
224 static uint64_t
225 lapic_read_icr_lo(void)
226 {
227
228         return (lapic_read32(LAPIC_ICR_LO));
229 }
230
231 static void
232 lapic_write_icr(uint32_t vhi, uint32_t vlo)
233 {
234         uint64_t v;
235
236         if (x2apic_mode) {
237                 v = ((uint64_t)vhi << 32) | vlo;
238                 mfence();
239                 wrmsr(MSR_APIC_000 + LAPIC_ICR_LO, v);
240         } else {
241                 lapic_write32(LAPIC_ICR_HI, vhi);
242                 lapic_write32(LAPIC_ICR_LO, vlo);
243         }
244 }
245 #endif /* SMP */
246
247 static void
248 native_lapic_enable_x2apic(void)
249 {
250         uint64_t apic_base;
251
252         apic_base = rdmsr(MSR_APICBASE);
253         apic_base |= APICBASE_X2APIC | APICBASE_ENABLED;
254         wrmsr(MSR_APICBASE, apic_base);
255 }
256
257 static void     lapic_enable(void);
258 static void     lapic_resume(struct pic *pic, bool suspend_cancelled);
259 static void     lapic_timer_oneshot(struct lapic *,
260                     u_int count, int enable_int);
261 static void     lapic_timer_periodic(struct lapic *,
262                     u_int count, int enable_int);
263 static void     lapic_timer_stop(struct lapic *);
264 static void     lapic_timer_set_divisor(u_int divisor);
265 static uint32_t lvt_mode(struct lapic *la, u_int pin, uint32_t value);
266 static int      lapic_et_start(struct eventtimer *et,
267                     sbintime_t first, sbintime_t period);
268 static int      lapic_et_stop(struct eventtimer *et);
269 static u_int    apic_idt_to_irq(u_int apic_id, u_int vector);
270 static void     lapic_set_tpr(u_int vector);
271
272 struct pic lapic_pic = { .pic_resume = lapic_resume };
273
274 /* Forward declarations for apic_ops */
275 static void     native_lapic_create(u_int apic_id, int boot_cpu);
276 static void     native_lapic_init(vm_paddr_t addr);
277 static void     native_lapic_xapic_mode(void);
278 static void     native_lapic_setup(int boot);
279 static void     native_lapic_dump(const char *str);
280 static void     native_lapic_disable(void);
281 static void     native_lapic_eoi(void);
282 static int      native_lapic_id(void);
283 static int      native_lapic_intr_pending(u_int vector);
284 static u_int    native_apic_cpuid(u_int apic_id);
285 static u_int    native_apic_alloc_vector(u_int apic_id, u_int irq);
286 static u_int    native_apic_alloc_vectors(u_int apic_id, u_int *irqs,
287                     u_int count, u_int align);
288 static void     native_apic_disable_vector(u_int apic_id, u_int vector);
289 static void     native_apic_enable_vector(u_int apic_id, u_int vector);
290 static void     native_apic_free_vector(u_int apic_id, u_int vector, u_int irq);
291 static void     native_lapic_set_logical_id(u_int apic_id, u_int cluster,
292                     u_int cluster_id);
293 static int      native_lapic_enable_pmc(void);
294 static void     native_lapic_disable_pmc(void);
295 static void     native_lapic_reenable_pmc(void);
296 static void     native_lapic_enable_cmc(void);
297 static int      native_lapic_set_lvt_mask(u_int apic_id, u_int lvt,
298                     u_char masked);
299 static int      native_lapic_set_lvt_mode(u_int apic_id, u_int lvt,
300                     uint32_t mode);
301 static int      native_lapic_set_lvt_polarity(u_int apic_id, u_int lvt,
302                     enum intr_polarity pol);
303 static int      native_lapic_set_lvt_triggermode(u_int apic_id, u_int lvt,
304                     enum intr_trigger trigger);
305 #ifdef SMP
306 static void     native_lapic_ipi_raw(register_t icrlo, u_int dest);
307 static void     native_lapic_ipi_vectored(u_int vector, int dest);
308 static int      native_lapic_ipi_wait(int delay);
309 static int      native_lapic_ipi_alloc(inthand_t *ipifunc);
310 static void     native_lapic_ipi_free(int vector);
311 #endif /* SMP */
312
313 struct apic_ops apic_ops = {
314         .create                 = native_lapic_create,
315         .init                   = native_lapic_init,
316         .xapic_mode             = native_lapic_xapic_mode,
317         .setup                  = native_lapic_setup,
318         .dump                   = native_lapic_dump,
319         .disable                = native_lapic_disable,
320         .eoi                    = native_lapic_eoi,
321         .id                     = native_lapic_id,
322         .intr_pending           = native_lapic_intr_pending,
323         .set_logical_id         = native_lapic_set_logical_id,
324         .cpuid                  = native_apic_cpuid,
325         .alloc_vector           = native_apic_alloc_vector,
326         .alloc_vectors          = native_apic_alloc_vectors,
327         .enable_vector          = native_apic_enable_vector,
328         .disable_vector         = native_apic_disable_vector,
329         .free_vector            = native_apic_free_vector,
330         .enable_pmc             = native_lapic_enable_pmc,
331         .disable_pmc            = native_lapic_disable_pmc,
332         .reenable_pmc           = native_lapic_reenable_pmc,
333         .enable_cmc             = native_lapic_enable_cmc,
334 #ifdef SMP
335         .ipi_raw                = native_lapic_ipi_raw,
336         .ipi_vectored           = native_lapic_ipi_vectored,
337         .ipi_wait               = native_lapic_ipi_wait,
338         .ipi_alloc              = native_lapic_ipi_alloc,
339         .ipi_free               = native_lapic_ipi_free,
340 #endif
341         .set_lvt_mask           = native_lapic_set_lvt_mask,
342         .set_lvt_mode           = native_lapic_set_lvt_mode,
343         .set_lvt_polarity       = native_lapic_set_lvt_polarity,
344         .set_lvt_triggermode    = native_lapic_set_lvt_triggermode,
345 };
346
347 static uint32_t
348 lvt_mode(struct lapic *la, u_int pin, uint32_t value)
349 {
350         struct lvt *lvt;
351
352         KASSERT(pin <= APIC_LVT_MAX, ("%s: pin %u out of range", __func__, pin));
353         if (la->la_lvts[pin].lvt_active)
354                 lvt = &la->la_lvts[pin];
355         else
356                 lvt = &lvts[pin];
357
358         value &= ~(APIC_LVT_M | APIC_LVT_TM | APIC_LVT_IIPP | APIC_LVT_DM |
359             APIC_LVT_VECTOR);
360         if (lvt->lvt_edgetrigger == 0)
361                 value |= APIC_LVT_TM;
362         if (lvt->lvt_activehi == 0)
363                 value |= APIC_LVT_IIPP_INTALO;
364         if (lvt->lvt_masked)
365                 value |= APIC_LVT_M;
366         value |= lvt->lvt_mode;
367         switch (lvt->lvt_mode) {
368         case APIC_LVT_DM_NMI:
369         case APIC_LVT_DM_SMI:
370         case APIC_LVT_DM_INIT:
371         case APIC_LVT_DM_EXTINT:
372                 if (!lvt->lvt_edgetrigger && bootverbose) {
373                         printf("lapic%u: Forcing LINT%u to edge trigger\n",
374                             la->la_id, pin);
375                         value |= APIC_LVT_TM;
376                 }
377                 /* Use a vector of 0. */
378                 break;
379         case APIC_LVT_DM_FIXED:
380                 value |= lvt->lvt_vector;
381                 break;
382         default:
383                 panic("bad APIC LVT delivery mode: %#x\n", value);
384         }
385         return (value);
386 }
387
388 /*
389  * Map the local APIC and setup necessary interrupt vectors.
390  */
391 static void
392 native_lapic_init(vm_paddr_t addr)
393 {
394         uint32_t ver;
395         u_int regs[4];
396         int i, arat;
397
398         /*
399          * Enable x2APIC mode if possible. Map the local APIC
400          * registers page.
401          *
402          * Keep the LAPIC registers page mapped uncached for x2APIC
403          * mode too, to have direct map page attribute set to
404          * uncached.  This is needed to work around CPU errata present
405          * on all Intel processors.
406          */
407         KASSERT(trunc_page(addr) == addr,
408             ("local APIC not aligned on a page boundary"));
409         lapic_paddr = addr;
410         lapic_map = pmap_mapdev(addr, PAGE_SIZE);
411         if (x2apic_mode) {
412                 native_lapic_enable_x2apic();
413                 lapic_map = NULL;
414         }
415
416         /* Setup the spurious interrupt handler. */
417         setidt(APIC_SPURIOUS_INT, IDTVEC(spuriousint), SDT_APIC, SEL_KPL,
418             GSEL_APIC);
419
420         /* Perform basic initialization of the BSP's local APIC. */
421         lapic_enable();
422
423         /* Set BSP's per-CPU local APIC ID. */
424         PCPU_SET(apic_id, lapic_id());
425
426         /* Local APIC timer interrupt. */
427         setidt(APIC_TIMER_INT, IDTVEC(timerint), SDT_APIC, SEL_KPL, GSEL_APIC);
428
429         /* Local APIC error interrupt. */
430         setidt(APIC_ERROR_INT, IDTVEC(errorint), SDT_APIC, SEL_KPL, GSEL_APIC);
431
432         /* XXX: Thermal interrupt */
433
434         /* Local APIC CMCI. */
435         setidt(APIC_CMC_INT, IDTVEC(cmcint), SDT_APICT, SEL_KPL, GSEL_APIC);
436
437         if ((resource_int_value("apic", 0, "clock", &i) != 0 || i != 0)) {
438                 arat = 0;
439                 /* Intel CPUID 0x06 EAX[2] set if APIC timer runs in C3. */
440                 if (cpu_vendor_id == CPU_VENDOR_INTEL && cpu_high >= 6) {
441                         do_cpuid(0x06, regs);
442                         if ((regs[0] & CPUTPM1_ARAT) != 0)
443                                 arat = 1;
444                 }
445                 bzero(&lapic_et, sizeof(lapic_et));
446                 lapic_et.et_name = "LAPIC";
447                 lapic_et.et_flags = ET_FLAGS_PERIODIC | ET_FLAGS_ONESHOT |
448                     ET_FLAGS_PERCPU;
449                 lapic_et.et_quality = 600;
450                 if (!arat) {
451                         lapic_et.et_flags |= ET_FLAGS_C3STOP;
452                         lapic_et.et_quality -= 200;
453                 }
454                 lapic_et.et_frequency = 0;
455                 /* We don't know frequency yet, so trying to guess. */
456                 lapic_et.et_min_period = 0x00001000LL;
457                 lapic_et.et_max_period = SBT_1S;
458                 lapic_et.et_start = lapic_et_start;
459                 lapic_et.et_stop = lapic_et_stop;
460                 lapic_et.et_priv = NULL;
461                 et_register(&lapic_et);
462         }
463
464         /*
465          * Set lapic_eoi_suppression after lapic_enable(), to not
466          * enable suppression in the hardware prematurely.  Note that
467          * we by default enable suppression even when system only has
468          * one IO-APIC, since EOI is broadcasted to all APIC agents,
469          * including CPUs, otherwise.
470          *
471          * It seems that at least some KVM versions report
472          * EOI_SUPPRESSION bit, but auto-EOI does not work.
473          */
474         ver = lapic_read32(LAPIC_VERSION);
475         if ((ver & APIC_VER_EOI_SUPPRESSION) != 0) {
476                 lapic_eoi_suppression = 1;
477                 if (vm_guest == VM_GUEST_VM &&
478                     !strcmp(hv_vendor, "KVMKVMKVM")) {
479                         if (bootverbose)
480                                 printf(
481                        "KVM -- disabling lapic eoi suppression\n");
482                         lapic_eoi_suppression = 0;
483                 }
484                 TUNABLE_INT_FETCH("hw.lapic_eoi_suppression",
485                     &lapic_eoi_suppression);
486         }
487 }
488
489 /*
490  * Create a local APIC instance.
491  */
492 static void
493 native_lapic_create(u_int apic_id, int boot_cpu)
494 {
495         int i;
496
497         if (apic_id > MAX_APIC_ID) {
498                 printf("APIC: Ignoring local APIC with ID %d\n", apic_id);
499                 if (boot_cpu)
500                         panic("Can't ignore BSP");
501                 return;
502         }
503         KASSERT(!lapics[apic_id].la_present, ("duplicate local APIC %u",
504             apic_id));
505
506         /*
507          * Assume no local LVT overrides and a cluster of 0 and
508          * intra-cluster ID of 0.
509          */
510         lapics[apic_id].la_present = 1;
511         lapics[apic_id].la_id = apic_id;
512         for (i = 0; i <= APIC_LVT_MAX; i++) {
513                 lapics[apic_id].la_lvts[i] = lvts[i];
514                 lapics[apic_id].la_lvts[i].lvt_active = 0;
515         }
516         for (i = 0; i <= APIC_NUM_IOINTS; i++)
517             lapics[apic_id].la_ioint_irqs[i] = -1;
518         lapics[apic_id].la_ioint_irqs[IDT_SYSCALL - APIC_IO_INTS] = IRQ_SYSCALL;
519         lapics[apic_id].la_ioint_irqs[APIC_TIMER_INT - APIC_IO_INTS] =
520             IRQ_TIMER;
521 #ifdef KDTRACE_HOOKS
522         lapics[apic_id].la_ioint_irqs[IDT_DTRACE_RET - APIC_IO_INTS] =
523             IRQ_DTRACE_RET;
524 #endif
525 #ifdef XENHVM
526         lapics[apic_id].la_ioint_irqs[IDT_EVTCHN - APIC_IO_INTS] = IRQ_EVTCHN;
527 #endif
528
529
530 #ifdef SMP
531         cpu_add(apic_id, boot_cpu);
532 #endif
533 }
534
535 /*
536  * Dump contents of local APIC registers
537  */
538 static void
539 native_lapic_dump(const char* str)
540 {
541         uint32_t maxlvt;
542
543         maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
544         printf("cpu%d %s:\n", PCPU_GET(cpuid), str);
545         printf("     ID: 0x%08x   VER: 0x%08x LDR: 0x%08x DFR: 0x%08x",
546             lapic_read32(LAPIC_ID), lapic_read32(LAPIC_VERSION),
547             lapic_read32(LAPIC_LDR), x2apic_mode ? 0 : lapic_read32(LAPIC_DFR));
548         if ((cpu_feature2 & CPUID2_X2APIC) != 0)
549                 printf(" x2APIC: %d", x2apic_mode);
550         printf("\n  lint0: 0x%08x lint1: 0x%08x TPR: 0x%08x SVR: 0x%08x\n",
551             lapic_read32(LAPIC_LVT_LINT0), lapic_read32(LAPIC_LVT_LINT1),
552             lapic_read32(LAPIC_TPR), lapic_read32(LAPIC_SVR));
553         printf("  timer: 0x%08x therm: 0x%08x err: 0x%08x",
554             lapic_read32(LAPIC_LVT_TIMER), lapic_read32(LAPIC_LVT_THERMAL),
555             lapic_read32(LAPIC_LVT_ERROR));
556         if (maxlvt >= APIC_LVT_PMC)
557                 printf(" pmc: 0x%08x", lapic_read32(LAPIC_LVT_PCINT));
558         printf("\n");
559         if (maxlvt >= APIC_LVT_CMCI)
560                 printf("   cmci: 0x%08x\n", lapic_read32(LAPIC_LVT_CMCI));
561 }
562
563 static void
564 native_lapic_xapic_mode(void)
565 {
566         register_t saveintr;
567
568         saveintr = intr_disable();
569         if (x2apic_mode)
570                 native_lapic_enable_x2apic();
571         intr_restore(saveintr);
572 }
573
574 static void
575 native_lapic_setup(int boot)
576 {
577         struct lapic *la;
578         uint32_t maxlvt;
579         register_t saveintr;
580         char buf[MAXCOMLEN + 1];
581
582         saveintr = intr_disable();
583
584         la = &lapics[lapic_id()];
585         KASSERT(la->la_present, ("missing APIC structure"));
586         maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
587
588         /* Initialize the TPR to allow all interrupts. */
589         lapic_set_tpr(0);
590
591         /* Setup spurious vector and enable the local APIC. */
592         lapic_enable();
593
594         /* Program LINT[01] LVT entries. */
595         lapic_write32(LAPIC_LVT_LINT0, lvt_mode(la, APIC_LVT_LINT0,
596             lapic_read32(LAPIC_LVT_LINT0)));
597         lapic_write32(LAPIC_LVT_LINT1, lvt_mode(la, APIC_LVT_LINT1,
598             lapic_read32(LAPIC_LVT_LINT1)));
599
600         /* Program the PMC LVT entry if present. */
601         if (maxlvt >= APIC_LVT_PMC) {
602                 lapic_write32(LAPIC_LVT_PCINT, lvt_mode(la, APIC_LVT_PMC,
603                     LAPIC_LVT_PCINT));
604         }
605
606         /* Program timer LVT and setup handler. */
607         la->lvt_timer_cache = lvt_mode(la, APIC_LVT_TIMER,
608             lapic_read32(LAPIC_LVT_TIMER));
609         lapic_write32(LAPIC_LVT_TIMER, la->lvt_timer_cache);
610         if (boot) {
611                 snprintf(buf, sizeof(buf), "cpu%d:timer", PCPU_GET(cpuid));
612                 intrcnt_add(buf, &la->la_timer_count);
613         }
614
615         /* Setup the timer if configured. */
616         if (la->la_timer_mode != 0) {
617                 KASSERT(la->la_timer_period != 0, ("lapic%u: zero divisor",
618                     lapic_id()));
619                 lapic_timer_set_divisor(lapic_timer_divisor);
620                 if (la->la_timer_mode == 1)
621                         lapic_timer_periodic(la, la->la_timer_period, 1);
622                 else
623                         lapic_timer_oneshot(la, la->la_timer_period, 1);
624         }
625
626         /* Program error LVT and clear any existing errors. */
627         lapic_write32(LAPIC_LVT_ERROR, lvt_mode(la, APIC_LVT_ERROR,
628             lapic_read32(LAPIC_LVT_ERROR)));
629         lapic_write32(LAPIC_ESR, 0);
630
631         /* XXX: Thermal LVT */
632
633         /* Program the CMCI LVT entry if present. */
634         if (maxlvt >= APIC_LVT_CMCI) {
635                 lapic_write32(LAPIC_LVT_CMCI, lvt_mode(la, APIC_LVT_CMCI,
636                     lapic_read32(LAPIC_LVT_CMCI)));
637         }
638             
639         intr_restore(saveintr);
640 }
641
642 static void
643 native_lapic_reenable_pmc(void)
644 {
645 #ifdef HWPMC_HOOKS
646         uint32_t value;
647
648         value = lapic_read32(LAPIC_LVT_PCINT);
649         value &= ~APIC_LVT_M;
650         lapic_write32(LAPIC_LVT_PCINT, value);
651 #endif
652 }
653
654 #ifdef HWPMC_HOOKS
655 static void
656 lapic_update_pmc(void *dummy)
657 {
658         struct lapic *la;
659
660         la = &lapics[lapic_id()];
661         lapic_write32(LAPIC_LVT_PCINT, lvt_mode(la, APIC_LVT_PMC,
662             lapic_read32(LAPIC_LVT_PCINT)));
663 }
664 #endif
665
666 static int
667 native_lapic_enable_pmc(void)
668 {
669 #ifdef HWPMC_HOOKS
670         u_int32_t maxlvt;
671
672         /* Fail if the local APIC is not present. */
673         if (!x2apic_mode && lapic_map == NULL)
674                 return (0);
675
676         /* Fail if the PMC LVT is not present. */
677         maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
678         if (maxlvt < APIC_LVT_PMC)
679                 return (0);
680
681         lvts[APIC_LVT_PMC].lvt_masked = 0;
682
683 #ifdef SMP
684         /*
685          * If hwpmc was loaded at boot time then the APs may not be
686          * started yet.  In that case, don't forward the request to
687          * them as they will program the lvt when they start.
688          */
689         if (smp_started)
690                 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
691         else
692 #endif
693                 lapic_update_pmc(NULL);
694         return (1);
695 #else
696         return (0);
697 #endif
698 }
699
700 static void
701 native_lapic_disable_pmc(void)
702 {
703 #ifdef HWPMC_HOOKS
704         u_int32_t maxlvt;
705
706         /* Fail if the local APIC is not present. */
707         if (!x2apic_mode && lapic_map == NULL)
708                 return;
709
710         /* Fail if the PMC LVT is not present. */
711         maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
712         if (maxlvt < APIC_LVT_PMC)
713                 return;
714
715         lvts[APIC_LVT_PMC].lvt_masked = 1;
716
717 #ifdef SMP
718         /* The APs should always be started when hwpmc is unloaded. */
719         KASSERT(mp_ncpus == 1 || smp_started, ("hwpmc unloaded too early"));
720 #endif
721         smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
722 #endif
723 }
724
725 static int
726 lapic_et_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
727 {
728         struct lapic *la;
729         u_long value;
730
731         la = &lapics[PCPU_GET(apic_id)];
732         if (et->et_frequency == 0) {
733                 /* Start off with a divisor of 2 (power on reset default). */
734                 lapic_timer_divisor = 2;
735                 /* Try to calibrate the local APIC timer. */
736                 do {
737                         lapic_timer_set_divisor(lapic_timer_divisor);
738                         lapic_timer_oneshot(la, APIC_TIMER_MAX_COUNT, 0);
739                         DELAY(1000000);
740                         value = APIC_TIMER_MAX_COUNT -
741                             lapic_read32(LAPIC_CCR_TIMER);
742                         if (value != APIC_TIMER_MAX_COUNT)
743                                 break;
744                         lapic_timer_divisor <<= 1;
745                 } while (lapic_timer_divisor <= 128);
746                 if (lapic_timer_divisor > 128)
747                         panic("lapic: Divisor too big");
748                 if (bootverbose)
749                         printf("lapic: Divisor %lu, Frequency %lu Hz\n",
750                             lapic_timer_divisor, value);
751                 et->et_frequency = value;
752                 et->et_min_period = (0x00000002LLU << 32) / et->et_frequency;
753                 et->et_max_period = (0xfffffffeLLU << 32) / et->et_frequency;
754         }
755         if (la->la_timer_mode == 0)
756                 lapic_timer_set_divisor(lapic_timer_divisor);
757         if (period != 0) {
758                 la->la_timer_mode = 1;
759                 la->la_timer_period = ((uint32_t)et->et_frequency * period) >> 32;
760                 lapic_timer_periodic(la, la->la_timer_period, 1);
761         } else {
762                 la->la_timer_mode = 2;
763                 la->la_timer_period = ((uint32_t)et->et_frequency * first) >> 32;
764                 lapic_timer_oneshot(la, la->la_timer_period, 1);
765         }
766         return (0);
767 }
768
769 static int
770 lapic_et_stop(struct eventtimer *et)
771 {
772         struct lapic *la = &lapics[PCPU_GET(apic_id)];
773
774         la->la_timer_mode = 0;
775         lapic_timer_stop(la);
776         return (0);
777 }
778
779 static void
780 native_lapic_disable(void)
781 {
782         uint32_t value;
783
784         /* Software disable the local APIC. */
785         value = lapic_read32(LAPIC_SVR);
786         value &= ~APIC_SVR_SWEN;
787         lapic_write32(LAPIC_SVR, value);
788 }
789
790 static void
791 lapic_enable(void)
792 {
793         uint32_t value;
794
795         /* Program the spurious vector to enable the local APIC. */
796         value = lapic_read32(LAPIC_SVR);
797         value &= ~(APIC_SVR_VECTOR | APIC_SVR_FOCUS);
798         value |= APIC_SVR_FEN | APIC_SVR_SWEN | APIC_SPURIOUS_INT;
799         if (lapic_eoi_suppression)
800                 value |= APIC_SVR_EOI_SUPPRESSION;
801         lapic_write32(LAPIC_SVR, value);
802 }
803
804 /* Reset the local APIC on the BSP during resume. */
805 static void
806 lapic_resume(struct pic *pic, bool suspend_cancelled)
807 {
808
809         lapic_setup(0);
810 }
811
812 static int
813 native_lapic_id(void)
814 {
815         uint32_t v;
816
817         KASSERT(x2apic_mode || lapic_map != NULL, ("local APIC is not mapped"));
818         v = lapic_read32(LAPIC_ID);
819         if (!x2apic_mode)
820                 v >>= APIC_ID_SHIFT;
821         return (v);
822 }
823
824 static int
825 native_lapic_intr_pending(u_int vector)
826 {
827         uint32_t irr;
828
829         /*
830          * The IRR registers are an array of registers each of which
831          * only describes 32 interrupts in the low 32 bits.  Thus, we
832          * divide the vector by 32 to get the register index.
833          * Finally, we modulus the vector by 32 to determine the
834          * individual bit to test.
835          */
836         irr = lapic_read32(LAPIC_IRR0 + vector / 32);
837         return (irr & 1 << (vector % 32));
838 }
839
840 static void
841 native_lapic_set_logical_id(u_int apic_id, u_int cluster, u_int cluster_id)
842 {
843         struct lapic *la;
844
845         KASSERT(lapics[apic_id].la_present, ("%s: APIC %u doesn't exist",
846             __func__, apic_id));
847         KASSERT(cluster <= APIC_MAX_CLUSTER, ("%s: cluster %u too big",
848             __func__, cluster));
849         KASSERT(cluster_id <= APIC_MAX_INTRACLUSTER_ID,
850             ("%s: intra cluster id %u too big", __func__, cluster_id));
851         la = &lapics[apic_id];
852         la->la_cluster = cluster;
853         la->la_cluster_id = cluster_id;
854 }
855
856 static int
857 native_lapic_set_lvt_mask(u_int apic_id, u_int pin, u_char masked)
858 {
859
860         if (pin > APIC_LVT_MAX)
861                 return (EINVAL);
862         if (apic_id == APIC_ID_ALL) {
863                 lvts[pin].lvt_masked = masked;
864                 if (bootverbose)
865                         printf("lapic:");
866         } else {
867                 KASSERT(lapics[apic_id].la_present,
868                     ("%s: missing APIC %u", __func__, apic_id));
869                 lapics[apic_id].la_lvts[pin].lvt_masked = masked;
870                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
871                 if (bootverbose)
872                         printf("lapic%u:", apic_id);
873         }
874         if (bootverbose)
875                 printf(" LINT%u %s\n", pin, masked ? "masked" : "unmasked");
876         return (0);
877 }
878
879 static int
880 native_lapic_set_lvt_mode(u_int apic_id, u_int pin, u_int32_t mode)
881 {
882         struct lvt *lvt;
883
884         if (pin > APIC_LVT_MAX)
885                 return (EINVAL);
886         if (apic_id == APIC_ID_ALL) {
887                 lvt = &lvts[pin];
888                 if (bootverbose)
889                         printf("lapic:");
890         } else {
891                 KASSERT(lapics[apic_id].la_present,
892                     ("%s: missing APIC %u", __func__, apic_id));
893                 lvt = &lapics[apic_id].la_lvts[pin];
894                 lvt->lvt_active = 1;
895                 if (bootverbose)
896                         printf("lapic%u:", apic_id);
897         }
898         lvt->lvt_mode = mode;
899         switch (mode) {
900         case APIC_LVT_DM_NMI:
901         case APIC_LVT_DM_SMI:
902         case APIC_LVT_DM_INIT:
903         case APIC_LVT_DM_EXTINT:
904                 lvt->lvt_edgetrigger = 1;
905                 lvt->lvt_activehi = 1;
906                 if (mode == APIC_LVT_DM_EXTINT)
907                         lvt->lvt_masked = 1;
908                 else
909                         lvt->lvt_masked = 0;
910                 break;
911         default:
912                 panic("Unsupported delivery mode: 0x%x\n", mode);
913         }
914         if (bootverbose) {
915                 printf(" Routing ");
916                 switch (mode) {
917                 case APIC_LVT_DM_NMI:
918                         printf("NMI");
919                         break;
920                 case APIC_LVT_DM_SMI:
921                         printf("SMI");
922                         break;
923                 case APIC_LVT_DM_INIT:
924                         printf("INIT");
925                         break;
926                 case APIC_LVT_DM_EXTINT:
927                         printf("ExtINT");
928                         break;
929                 }
930                 printf(" -> LINT%u\n", pin);
931         }
932         return (0);
933 }
934
935 static int
936 native_lapic_set_lvt_polarity(u_int apic_id, u_int pin, enum intr_polarity pol)
937 {
938
939         if (pin > APIC_LVT_MAX || pol == INTR_POLARITY_CONFORM)
940                 return (EINVAL);
941         if (apic_id == APIC_ID_ALL) {
942                 lvts[pin].lvt_activehi = (pol == INTR_POLARITY_HIGH);
943                 if (bootverbose)
944                         printf("lapic:");
945         } else {
946                 KASSERT(lapics[apic_id].la_present,
947                     ("%s: missing APIC %u", __func__, apic_id));
948                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
949                 lapics[apic_id].la_lvts[pin].lvt_activehi =
950                     (pol == INTR_POLARITY_HIGH);
951                 if (bootverbose)
952                         printf("lapic%u:", apic_id);
953         }
954         if (bootverbose)
955                 printf(" LINT%u polarity: %s\n", pin,
956                     pol == INTR_POLARITY_HIGH ? "high" : "low");
957         return (0);
958 }
959
960 static int
961 native_lapic_set_lvt_triggermode(u_int apic_id, u_int pin,
962      enum intr_trigger trigger)
963 {
964
965         if (pin > APIC_LVT_MAX || trigger == INTR_TRIGGER_CONFORM)
966                 return (EINVAL);
967         if (apic_id == APIC_ID_ALL) {
968                 lvts[pin].lvt_edgetrigger = (trigger == INTR_TRIGGER_EDGE);
969                 if (bootverbose)
970                         printf("lapic:");
971         } else {
972                 KASSERT(lapics[apic_id].la_present,
973                     ("%s: missing APIC %u", __func__, apic_id));
974                 lapics[apic_id].la_lvts[pin].lvt_edgetrigger =
975                     (trigger == INTR_TRIGGER_EDGE);
976                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
977                 if (bootverbose)
978                         printf("lapic%u:", apic_id);
979         }
980         if (bootverbose)
981                 printf(" LINT%u trigger: %s\n", pin,
982                     trigger == INTR_TRIGGER_EDGE ? "edge" : "level");
983         return (0);
984 }
985
986 /*
987  * Adjust the TPR of the current CPU so that it blocks all interrupts below
988  * the passed in vector.
989  */
990 static void
991 lapic_set_tpr(u_int vector)
992 {
993 #ifdef CHEAP_TPR
994         lapic_write32(LAPIC_TPR, vector);
995 #else
996         uint32_t tpr;
997
998         tpr = lapic_read32(LAPIC_TPR) & ~APIC_TPR_PRIO;
999         tpr |= vector;
1000         lapic_write32(LAPIC_TPR, tpr);
1001 #endif
1002 }
1003
1004 static void
1005 native_lapic_eoi(void)
1006 {
1007
1008         lapic_write32_nofence(LAPIC_EOI, 0);
1009 }
1010
1011 void
1012 lapic_handle_intr(int vector, struct trapframe *frame)
1013 {
1014         struct intsrc *isrc;
1015
1016         isrc = intr_lookup_source(apic_idt_to_irq(PCPU_GET(apic_id),
1017             vector));
1018         intr_execute_handlers(isrc, frame);
1019 }
1020
1021 void
1022 lapic_handle_timer(struct trapframe *frame)
1023 {
1024         struct lapic *la;
1025         struct trapframe *oldframe;
1026         struct thread *td;
1027
1028         /* Send EOI first thing. */
1029         lapic_eoi();
1030
1031 #if defined(SMP) && !defined(SCHED_ULE)
1032         /*
1033          * Don't do any accounting for the disabled HTT cores, since it
1034          * will provide misleading numbers for the userland.
1035          *
1036          * No locking is necessary here, since even if we lose the race
1037          * when hlt_cpus_mask changes it is not a big deal, really.
1038          *
1039          * Don't do that for ULE, since ULE doesn't consider hlt_cpus_mask
1040          * and unlike other schedulers it actually schedules threads to
1041          * those CPUs.
1042          */
1043         if (CPU_ISSET(PCPU_GET(cpuid), &hlt_cpus_mask))
1044                 return;
1045 #endif
1046
1047         /* Look up our local APIC structure for the tick counters. */
1048         la = &lapics[PCPU_GET(apic_id)];
1049         (*la->la_timer_count)++;
1050         critical_enter();
1051         if (lapic_et.et_active) {
1052                 td = curthread;
1053                 td->td_intr_nesting_level++;
1054                 oldframe = td->td_intr_frame;
1055                 td->td_intr_frame = frame;
1056                 lapic_et.et_event_cb(&lapic_et, lapic_et.et_arg);
1057                 td->td_intr_frame = oldframe;
1058                 td->td_intr_nesting_level--;
1059         }
1060         critical_exit();
1061 }
1062
1063 static void
1064 lapic_timer_set_divisor(u_int divisor)
1065 {
1066
1067         KASSERT(powerof2(divisor), ("lapic: invalid divisor %u", divisor));
1068         KASSERT(ffs(divisor) <= sizeof(lapic_timer_divisors) /
1069             sizeof(u_int32_t), ("lapic: invalid divisor %u", divisor));
1070         lapic_write32(LAPIC_DCR_TIMER, lapic_timer_divisors[ffs(divisor) - 1]);
1071 }
1072
1073 static void
1074 lapic_timer_oneshot(struct lapic *la, u_int count, int enable_int)
1075 {
1076         uint32_t value;
1077
1078         value = la->lvt_timer_cache;
1079         value &= ~APIC_LVTT_TM;
1080         value |= APIC_LVTT_TM_ONE_SHOT;
1081         if (enable_int)
1082                 value &= ~APIC_LVT_M;
1083         lapic_write32(LAPIC_LVT_TIMER, value);
1084         lapic_write32(LAPIC_ICR_TIMER, count);
1085 }
1086
1087 static void
1088 lapic_timer_periodic(struct lapic *la, u_int count, int enable_int)
1089 {
1090         uint32_t value;
1091
1092         value = la->lvt_timer_cache;
1093         value &= ~APIC_LVTT_TM;
1094         value |= APIC_LVTT_TM_PERIODIC;
1095         if (enable_int)
1096                 value &= ~APIC_LVT_M;
1097         lapic_write32(LAPIC_LVT_TIMER, value);
1098         lapic_write32(LAPIC_ICR_TIMER, count);
1099 }
1100
1101 static void
1102 lapic_timer_stop(struct lapic *la)
1103 {
1104         uint32_t value;
1105
1106         value = la->lvt_timer_cache;
1107         value &= ~APIC_LVTT_TM;
1108         value |= APIC_LVT_M;
1109         lapic_write32(LAPIC_LVT_TIMER, value);
1110 }
1111
1112 void
1113 lapic_handle_cmc(void)
1114 {
1115
1116         lapic_eoi();
1117         cmc_intr();
1118 }
1119
1120 /*
1121  * Called from the mca_init() to activate the CMC interrupt if this CPU is
1122  * responsible for monitoring any MC banks for CMC events.  Since mca_init()
1123  * is called prior to lapic_setup() during boot, this just needs to unmask
1124  * this CPU's LVT_CMCI entry.
1125  */
1126 static void
1127 native_lapic_enable_cmc(void)
1128 {
1129         u_int apic_id;
1130
1131 #ifdef DEV_ATPIC
1132         if (!x2apic_mode && lapic_map == NULL)
1133                 return;
1134 #endif
1135         apic_id = PCPU_GET(apic_id);
1136         KASSERT(lapics[apic_id].la_present,
1137             ("%s: missing APIC %u", __func__, apic_id));
1138         lapics[apic_id].la_lvts[APIC_LVT_CMCI].lvt_masked = 0;
1139         lapics[apic_id].la_lvts[APIC_LVT_CMCI].lvt_active = 1;
1140         if (bootverbose)
1141                 printf("lapic%u: CMCI unmasked\n", apic_id);
1142 }
1143
1144 void
1145 lapic_handle_error(void)
1146 {
1147         uint32_t esr;
1148
1149         /*
1150          * Read the contents of the error status register.  Write to
1151          * the register first before reading from it to force the APIC
1152          * to update its value to indicate any errors that have
1153          * occurred since the previous write to the register.
1154          */
1155         lapic_write32(LAPIC_ESR, 0);
1156         esr = lapic_read32(LAPIC_ESR);
1157
1158         printf("CPU%d: local APIC error 0x%x\n", PCPU_GET(cpuid), esr);
1159         lapic_eoi();
1160 }
1161
1162 static u_int
1163 native_apic_cpuid(u_int apic_id)
1164 {
1165 #ifdef SMP
1166         return apic_cpuids[apic_id];
1167 #else
1168         return 0;
1169 #endif
1170 }
1171
1172 /* Request a free IDT vector to be used by the specified IRQ. */
1173 static u_int
1174 native_apic_alloc_vector(u_int apic_id, u_int irq)
1175 {
1176         u_int vector;
1177
1178         KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
1179
1180         /*
1181          * Search for a free vector.  Currently we just use a very simple
1182          * algorithm to find the first free vector.
1183          */
1184         mtx_lock_spin(&icu_lock);
1185         for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
1186                 if (lapics[apic_id].la_ioint_irqs[vector] != -1)
1187                         continue;
1188                 lapics[apic_id].la_ioint_irqs[vector] = irq;
1189                 mtx_unlock_spin(&icu_lock);
1190                 return (vector + APIC_IO_INTS);
1191         }
1192         mtx_unlock_spin(&icu_lock);
1193         return (0);
1194 }
1195
1196 /*
1197  * Request 'count' free contiguous IDT vectors to be used by 'count'
1198  * IRQs.  'count' must be a power of two and the vectors will be
1199  * aligned on a boundary of 'align'.  If the request cannot be
1200  * satisfied, 0 is returned.
1201  */
1202 static u_int
1203 native_apic_alloc_vectors(u_int apic_id, u_int *irqs, u_int count, u_int align)
1204 {
1205         u_int first, run, vector;
1206
1207         KASSERT(powerof2(count), ("bad count"));
1208         KASSERT(powerof2(align), ("bad align"));
1209         KASSERT(align >= count, ("align < count"));
1210 #ifdef INVARIANTS
1211         for (run = 0; run < count; run++)
1212                 KASSERT(irqs[run] < NUM_IO_INTS, ("Invalid IRQ %u at index %u",
1213                     irqs[run], run));
1214 #endif
1215
1216         /*
1217          * Search for 'count' free vectors.  As with apic_alloc_vector(),
1218          * this just uses a simple first fit algorithm.
1219          */
1220         run = 0;
1221         first = 0;
1222         mtx_lock_spin(&icu_lock);
1223         for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
1224
1225                 /* Vector is in use, end run. */
1226                 if (lapics[apic_id].la_ioint_irqs[vector] != -1) {
1227                         run = 0;
1228                         first = 0;
1229                         continue;
1230                 }
1231
1232                 /* Start a new run if run == 0 and vector is aligned. */
1233                 if (run == 0) {
1234                         if ((vector & (align - 1)) != 0)
1235                                 continue;
1236                         first = vector;
1237                 }
1238                 run++;
1239
1240                 /* Keep looping if the run isn't long enough yet. */
1241                 if (run < count)
1242                         continue;
1243
1244                 /* Found a run, assign IRQs and return the first vector. */
1245                 for (vector = 0; vector < count; vector++)
1246                         lapics[apic_id].la_ioint_irqs[first + vector] =
1247                             irqs[vector];
1248                 mtx_unlock_spin(&icu_lock);
1249                 return (first + APIC_IO_INTS);
1250         }
1251         mtx_unlock_spin(&icu_lock);
1252         printf("APIC: Couldn't find APIC vectors for %u IRQs\n", count);
1253         return (0);
1254 }
1255
1256 /*
1257  * Enable a vector for a particular apic_id.  Since all lapics share idt
1258  * entries and ioint_handlers this enables the vector on all lapics.  lapics
1259  * which do not have the vector configured would report spurious interrupts
1260  * should it fire.
1261  */
1262 static void
1263 native_apic_enable_vector(u_int apic_id, u_int vector)
1264 {
1265
1266         KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1267         KASSERT(ioint_handlers[vector / 32] != NULL,
1268             ("No ISR handler for vector %u", vector));
1269 #ifdef KDTRACE_HOOKS
1270         KASSERT(vector != IDT_DTRACE_RET,
1271             ("Attempt to overwrite DTrace entry"));
1272 #endif
1273         setidt(vector, ioint_handlers[vector / 32], SDT_APIC, SEL_KPL,
1274             GSEL_APIC);
1275 }
1276
1277 static void
1278 native_apic_disable_vector(u_int apic_id, u_int vector)
1279 {
1280
1281         KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1282 #ifdef KDTRACE_HOOKS
1283         KASSERT(vector != IDT_DTRACE_RET,
1284             ("Attempt to overwrite DTrace entry"));
1285 #endif
1286         KASSERT(ioint_handlers[vector / 32] != NULL,
1287             ("No ISR handler for vector %u", vector));
1288 #ifdef notyet
1289         /*
1290          * We can not currently clear the idt entry because other cpus
1291          * may have a valid vector at this offset.
1292          */
1293         setidt(vector, &IDTVEC(rsvd), SDT_APICT, SEL_KPL, GSEL_APIC);
1294 #endif
1295 }
1296
1297 /* Release an APIC vector when it's no longer in use. */
1298 static void
1299 native_apic_free_vector(u_int apic_id, u_int vector, u_int irq)
1300 {
1301         struct thread *td;
1302
1303         KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1304             vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1305             ("Vector %u does not map to an IRQ line", vector));
1306         KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
1307         KASSERT(lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] ==
1308             irq, ("IRQ mismatch"));
1309 #ifdef KDTRACE_HOOKS
1310         KASSERT(vector != IDT_DTRACE_RET,
1311             ("Attempt to overwrite DTrace entry"));
1312 #endif
1313
1314         /*
1315          * Bind us to the cpu that owned the vector before freeing it so
1316          * we don't lose an interrupt delivery race.
1317          */
1318         td = curthread;
1319         if (!rebooting) {
1320                 thread_lock(td);
1321                 if (sched_is_bound(td))
1322                         panic("apic_free_vector: Thread already bound.\n");
1323                 sched_bind(td, apic_cpuid(apic_id));
1324                 thread_unlock(td);
1325         }
1326         mtx_lock_spin(&icu_lock);
1327         lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] = -1;
1328         mtx_unlock_spin(&icu_lock);
1329         if (!rebooting) {
1330                 thread_lock(td);
1331                 sched_unbind(td);
1332                 thread_unlock(td);
1333         }
1334 }
1335
1336 /* Map an IDT vector (APIC) to an IRQ (interrupt source). */
1337 static u_int
1338 apic_idt_to_irq(u_int apic_id, u_int vector)
1339 {
1340         int irq;
1341
1342         KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1343             vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1344             ("Vector %u does not map to an IRQ line", vector));
1345 #ifdef KDTRACE_HOOKS
1346         KASSERT(vector != IDT_DTRACE_RET,
1347             ("Attempt to overwrite DTrace entry"));
1348 #endif
1349         irq = lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS];
1350         if (irq < 0)
1351                 irq = 0;
1352         return (irq);
1353 }
1354
1355 #ifdef DDB
1356 /*
1357  * Dump data about APIC IDT vector mappings.
1358  */
1359 DB_SHOW_COMMAND(apic, db_show_apic)
1360 {
1361         struct intsrc *isrc;
1362         int i, verbose;
1363         u_int apic_id;
1364         u_int irq;
1365
1366         if (strcmp(modif, "vv") == 0)
1367                 verbose = 2;
1368         else if (strcmp(modif, "v") == 0)
1369                 verbose = 1;
1370         else
1371                 verbose = 0;
1372         for (apic_id = 0; apic_id <= MAX_APIC_ID; apic_id++) {
1373                 if (lapics[apic_id].la_present == 0)
1374                         continue;
1375                 db_printf("Interrupts bound to lapic %u\n", apic_id);
1376                 for (i = 0; i < APIC_NUM_IOINTS + 1 && !db_pager_quit; i++) {
1377                         irq = lapics[apic_id].la_ioint_irqs[i];
1378                         if (irq == -1 || irq == IRQ_SYSCALL)
1379                                 continue;
1380 #ifdef KDTRACE_HOOKS
1381                         if (irq == IRQ_DTRACE_RET)
1382                                 continue;
1383 #endif
1384 #ifdef XENHVM
1385                         if (irq == IRQ_EVTCHN)
1386                                 continue;
1387 #endif
1388                         db_printf("vec 0x%2x -> ", i + APIC_IO_INTS);
1389                         if (irq == IRQ_TIMER)
1390                                 db_printf("lapic timer\n");
1391                         else if (irq < NUM_IO_INTS) {
1392                                 isrc = intr_lookup_source(irq);
1393                                 if (isrc == NULL || verbose == 0)
1394                                         db_printf("IRQ %u\n", irq);
1395                                 else
1396                                         db_dump_intr_event(isrc->is_event,
1397                                             verbose == 2);
1398                         } else
1399                                 db_printf("IRQ %u ???\n", irq);
1400                 }
1401         }
1402 }
1403
1404 static void
1405 dump_mask(const char *prefix, uint32_t v, int base)
1406 {
1407         int i, first;
1408
1409         first = 1;
1410         for (i = 0; i < 32; i++)
1411                 if (v & (1 << i)) {
1412                         if (first) {
1413                                 db_printf("%s:", prefix);
1414                                 first = 0;
1415                         }
1416                         db_printf(" %02x", base + i);
1417                 }
1418         if (!first)
1419                 db_printf("\n");
1420 }
1421
1422 /* Show info from the lapic regs for this CPU. */
1423 DB_SHOW_COMMAND(lapic, db_show_lapic)
1424 {
1425         uint32_t v;
1426
1427         db_printf("lapic ID = %d\n", lapic_id());
1428         v = lapic_read32(LAPIC_VERSION);
1429         db_printf("version  = %d.%d\n", (v & APIC_VER_VERSION) >> 4,
1430             v & 0xf);
1431         db_printf("max LVT  = %d\n", (v & APIC_VER_MAXLVT) >> MAXLVTSHIFT);
1432         v = lapic_read32(LAPIC_SVR);
1433         db_printf("SVR      = %02x (%s)\n", v & APIC_SVR_VECTOR,
1434             v & APIC_SVR_ENABLE ? "enabled" : "disabled");
1435         db_printf("TPR      = %02x\n", lapic_read32(LAPIC_TPR));
1436
1437 #define dump_field(prefix, regn, index)                                 \
1438         dump_mask(__XSTRING(prefix ## index),                           \
1439             lapic_read32(LAPIC_ ## regn ## index),                      \
1440             index * 32)
1441
1442         db_printf("In-service Interrupts:\n");
1443         dump_field(isr, ISR, 0);
1444         dump_field(isr, ISR, 1);
1445         dump_field(isr, ISR, 2);
1446         dump_field(isr, ISR, 3);
1447         dump_field(isr, ISR, 4);
1448         dump_field(isr, ISR, 5);
1449         dump_field(isr, ISR, 6);
1450         dump_field(isr, ISR, 7);
1451
1452         db_printf("TMR Interrupts:\n");
1453         dump_field(tmr, TMR, 0);
1454         dump_field(tmr, TMR, 1);
1455         dump_field(tmr, TMR, 2);
1456         dump_field(tmr, TMR, 3);
1457         dump_field(tmr, TMR, 4);
1458         dump_field(tmr, TMR, 5);
1459         dump_field(tmr, TMR, 6);
1460         dump_field(tmr, TMR, 7);
1461
1462         db_printf("IRR Interrupts:\n");
1463         dump_field(irr, IRR, 0);
1464         dump_field(irr, IRR, 1);
1465         dump_field(irr, IRR, 2);
1466         dump_field(irr, IRR, 3);
1467         dump_field(irr, IRR, 4);
1468         dump_field(irr, IRR, 5);
1469         dump_field(irr, IRR, 6);
1470         dump_field(irr, IRR, 7);
1471
1472 #undef dump_field
1473 }
1474 #endif
1475
1476 /*
1477  * APIC probing support code.  This includes code to manage enumerators.
1478  */
1479
1480 static SLIST_HEAD(, apic_enumerator) enumerators =
1481         SLIST_HEAD_INITIALIZER(enumerators);
1482 static struct apic_enumerator *best_enum;
1483
1484 void
1485 apic_register_enumerator(struct apic_enumerator *enumerator)
1486 {
1487 #ifdef INVARIANTS
1488         struct apic_enumerator *apic_enum;
1489
1490         SLIST_FOREACH(apic_enum, &enumerators, apic_next) {
1491                 if (apic_enum == enumerator)
1492                         panic("%s: Duplicate register of %s", __func__,
1493                             enumerator->apic_name);
1494         }
1495 #endif
1496         SLIST_INSERT_HEAD(&enumerators, enumerator, apic_next);
1497 }
1498
1499 /*
1500  * We have to look for CPU's very, very early because certain subsystems
1501  * want to know how many CPU's we have extremely early on in the boot
1502  * process.
1503  */
1504 static void
1505 apic_init(void *dummy __unused)
1506 {
1507         struct apic_enumerator *enumerator;
1508         int retval, best;
1509
1510         /* We only support built in local APICs. */
1511         if (!(cpu_feature & CPUID_APIC))
1512                 return;
1513
1514         /* Don't probe if APIC mode is disabled. */
1515         if (resource_disabled("apic", 0))
1516                 return;
1517
1518         /* Probe all the enumerators to find the best match. */
1519         best_enum = NULL;
1520         best = 0;
1521         SLIST_FOREACH(enumerator, &enumerators, apic_next) {
1522                 retval = enumerator->apic_probe();
1523                 if (retval > 0)
1524                         continue;
1525                 if (best_enum == NULL || best < retval) {
1526                         best_enum = enumerator;
1527                         best = retval;
1528                 }
1529         }
1530         if (best_enum == NULL) {
1531                 if (bootverbose)
1532                         printf("APIC: Could not find any APICs.\n");
1533 #ifndef DEV_ATPIC
1534                 panic("running without device atpic requires a local APIC");
1535 #endif
1536                 return;
1537         }
1538
1539         if (bootverbose)
1540                 printf("APIC: Using the %s enumerator.\n",
1541                     best_enum->apic_name);
1542
1543 #ifdef I686_CPU
1544         /*
1545          * To work around an errata, we disable the local APIC on some
1546          * CPUs during early startup.  We need to turn the local APIC back
1547          * on on such CPUs now.
1548          */
1549         ppro_reenable_apic();
1550 #endif
1551
1552         /* Probe the CPU's in the system. */
1553         retval = best_enum->apic_probe_cpus();
1554         if (retval != 0)
1555                 printf("%s: Failed to probe CPUs: returned %d\n",
1556                     best_enum->apic_name, retval);
1557
1558 }
1559 SYSINIT(apic_init, SI_SUB_TUNABLES - 1, SI_ORDER_SECOND, apic_init, NULL);
1560
1561 /*
1562  * Setup the local APIC.  We have to do this prior to starting up the APs
1563  * in the SMP case.
1564  */
1565 static void
1566 apic_setup_local(void *dummy __unused)
1567 {
1568         int retval;
1569  
1570         if (best_enum == NULL)
1571                 return;
1572
1573         /* Initialize the local APIC. */
1574         retval = best_enum->apic_setup_local();
1575         if (retval != 0)
1576                 printf("%s: Failed to setup the local APIC: returned %d\n",
1577                     best_enum->apic_name, retval);
1578 }
1579 SYSINIT(apic_setup_local, SI_SUB_CPU, SI_ORDER_SECOND, apic_setup_local, NULL);
1580
1581 /*
1582  * Setup the I/O APICs.
1583  */
1584 static void
1585 apic_setup_io(void *dummy __unused)
1586 {
1587         int retval;
1588
1589         if (best_enum == NULL)
1590                 return;
1591
1592         /*
1593          * Local APIC must be registered before other PICs and pseudo PICs
1594          * for proper suspend/resume order.
1595          */
1596         intr_register_pic(&lapic_pic);
1597
1598         retval = best_enum->apic_setup_io();
1599         if (retval != 0)
1600                 printf("%s: Failed to setup I/O APICs: returned %d\n",
1601                     best_enum->apic_name, retval);
1602
1603         /*
1604          * Finish setting up the local APIC on the BSP once we know
1605          * how to properly program the LINT pins.  In particular, this
1606          * enables the EOI suppression mode, if LAPIC support it and
1607          * user did not disabled the mode.
1608          */
1609         lapic_setup(1);
1610         if (bootverbose)
1611                 lapic_dump("BSP");
1612
1613         /* Enable the MSI "pic". */
1614         init_ops.msi_init();
1615 }
1616 SYSINIT(apic_setup_io, SI_SUB_INTR, SI_ORDER_THIRD, apic_setup_io, NULL);
1617
1618 #ifdef SMP
1619 /*
1620  * Inter Processor Interrupt functions.  The lapic_ipi_*() functions are
1621  * private to the MD code.  The public interface for the rest of the
1622  * kernel is defined in mp_machdep.c.
1623  */
1624 static int
1625 native_lapic_ipi_wait(int delay)
1626 {
1627         int x;
1628
1629         /* LAPIC_ICR.APIC_DELSTAT_MASK is undefined in x2APIC mode */
1630         if (x2apic_mode)
1631                 return (1);
1632
1633         /*
1634          * Wait delay microseconds for IPI to be sent.  If delay is
1635          * -1, we wait forever.
1636          */
1637         if (delay == -1) {
1638                 while ((lapic_read_icr_lo() & APIC_DELSTAT_MASK) !=
1639                     APIC_DELSTAT_IDLE)
1640                         ia32_pause();
1641                 return (1);
1642         }
1643
1644         for (x = 0; x < delay; x += 5) {
1645                 if ((lapic_read_icr_lo() & APIC_DELSTAT_MASK) ==
1646                     APIC_DELSTAT_IDLE)
1647                         return (1);
1648                 DELAY(5);
1649         }
1650         return (0);
1651 }
1652
1653 static void
1654 native_lapic_ipi_raw(register_t icrlo, u_int dest)
1655 {
1656         uint64_t icr;
1657         uint32_t vhi, vlo;
1658         register_t saveintr;
1659
1660         /* XXX: Need more sanity checking of icrlo? */
1661         KASSERT(x2apic_mode || lapic_map != NULL,
1662             ("%s called too early", __func__));
1663         KASSERT(x2apic_mode ||
1664             (dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
1665             ("%s: invalid dest field", __func__));
1666         KASSERT((icrlo & APIC_ICRLO_RESV_MASK) == 0,
1667             ("%s: reserved bits set in ICR LO register", __func__));
1668
1669         /* Set destination in ICR HI register if it is being used. */
1670         if (!x2apic_mode) {
1671                 saveintr = intr_disable();
1672                 icr = lapic_read_icr();
1673         }
1674
1675         if ((icrlo & APIC_DEST_MASK) == APIC_DEST_DESTFLD) {
1676                 if (x2apic_mode) {
1677                         vhi = dest;
1678                 } else {
1679                         vhi = icr >> 32;
1680                         vhi &= ~APIC_ID_MASK;
1681                         vhi |= dest << APIC_ID_SHIFT;
1682                 }
1683         } else {
1684                 vhi = 0;
1685         }
1686
1687         /* Program the contents of the IPI and dispatch it. */
1688         if (x2apic_mode) {
1689                 vlo = icrlo;
1690         } else {
1691                 vlo = icr;
1692                 vlo &= APIC_ICRLO_RESV_MASK;
1693                 vlo |= icrlo;
1694         }
1695         lapic_write_icr(vhi, vlo);
1696         if (!x2apic_mode)
1697                 intr_restore(saveintr);
1698 }
1699
1700 #define BEFORE_SPIN     50000
1701 #ifdef DETECT_DEADLOCK
1702 #define AFTER_SPIN      50
1703 #endif
1704
1705 static void
1706 native_lapic_ipi_vectored(u_int vector, int dest)
1707 {
1708         register_t icrlo, destfield;
1709
1710         KASSERT((vector & ~APIC_VECTOR_MASK) == 0,
1711             ("%s: invalid vector %d", __func__, vector));
1712
1713         icrlo = APIC_DESTMODE_PHY | APIC_TRIGMOD_EDGE | APIC_LEVEL_ASSERT;
1714
1715         /*
1716          * NMI IPIs are just fake vectors used to send a NMI.  Use special rules
1717          * regarding NMIs if passed, otherwise specify the vector.
1718          */
1719         if (vector >= IPI_NMI_FIRST)
1720                 icrlo |= APIC_DELMODE_NMI;
1721         else
1722                 icrlo |= vector | APIC_DELMODE_FIXED;
1723         destfield = 0;
1724         switch (dest) {
1725         case APIC_IPI_DEST_SELF:
1726                 icrlo |= APIC_DEST_SELF;
1727                 break;
1728         case APIC_IPI_DEST_ALL:
1729                 icrlo |= APIC_DEST_ALLISELF;
1730                 break;
1731         case APIC_IPI_DEST_OTHERS:
1732                 icrlo |= APIC_DEST_ALLESELF;
1733                 break;
1734         default:
1735                 KASSERT(x2apic_mode ||
1736                     (dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
1737                     ("%s: invalid destination 0x%x", __func__, dest));
1738                 destfield = dest;
1739         }
1740
1741         /* Wait for an earlier IPI to finish. */
1742         if (!lapic_ipi_wait(BEFORE_SPIN)) {
1743                 if (panicstr != NULL)
1744                         return;
1745                 else
1746                         panic("APIC: Previous IPI is stuck");
1747         }
1748
1749         lapic_ipi_raw(icrlo, destfield);
1750
1751 #ifdef DETECT_DEADLOCK
1752         /* Wait for IPI to be delivered. */
1753         if (!lapic_ipi_wait(AFTER_SPIN)) {
1754 #ifdef needsattention
1755                 /*
1756                  * XXX FIXME:
1757                  *
1758                  * The above function waits for the message to actually be
1759                  * delivered.  It breaks out after an arbitrary timeout
1760                  * since the message should eventually be delivered (at
1761                  * least in theory) and that if it wasn't we would catch
1762                  * the failure with the check above when the next IPI is
1763                  * sent.
1764                  *
1765                  * We could skip this wait entirely, EXCEPT it probably
1766                  * protects us from other routines that assume that the
1767                  * message was delivered and acted upon when this function
1768                  * returns.
1769                  */
1770                 printf("APIC: IPI might be stuck\n");
1771 #else /* !needsattention */
1772                 /* Wait until mesage is sent without a timeout. */
1773                 while (lapic_read_icr_lo() & APIC_DELSTAT_PEND)
1774                         ia32_pause();
1775 #endif /* needsattention */
1776         }
1777 #endif /* DETECT_DEADLOCK */
1778 }
1779
1780 /*
1781  * Since the IDT is shared by all CPUs the IPI slot update needs to be globally
1782  * visible.
1783  *
1784  * Consider the case where an IPI is generated immediately after allocation:
1785  *     vector = lapic_ipi_alloc(ipifunc);
1786  *     ipi_selected(other_cpus, vector);
1787  *
1788  * In xAPIC mode a write to ICR_LO has serializing semantics because the
1789  * APIC page is mapped as an uncached region. In x2APIC mode there is an
1790  * explicit 'mfence' before the ICR MSR is written. Therefore in both cases
1791  * the IDT slot update is globally visible before the IPI is delivered.
1792  */
1793 static int
1794 native_lapic_ipi_alloc(inthand_t *ipifunc)
1795 {
1796         struct gate_descriptor *ip;
1797         long func;
1798         int idx, vector;
1799
1800         KASSERT(ipifunc != &IDTVEC(rsvd), ("invalid ipifunc %p", ipifunc));
1801
1802         vector = -1;
1803         mtx_lock_spin(&icu_lock);
1804         for (idx = IPI_DYN_FIRST; idx <= IPI_DYN_LAST; idx++) {
1805                 ip = &idt[idx];
1806                 func = (ip->gd_hioffset << 16) | ip->gd_looffset;
1807                 if (func == (uintptr_t)&IDTVEC(rsvd)) {
1808                         vector = idx;
1809                         setidt(vector, ipifunc, SDT_APIC, SEL_KPL, GSEL_APIC);
1810                         break;
1811                 }
1812         }
1813         mtx_unlock_spin(&icu_lock);
1814         return (vector);
1815 }
1816
1817 static void
1818 native_lapic_ipi_free(int vector)
1819 {
1820         struct gate_descriptor *ip;
1821         long func;
1822
1823         KASSERT(vector >= IPI_DYN_FIRST && vector <= IPI_DYN_LAST,
1824             ("%s: invalid vector %d", __func__, vector));
1825
1826         mtx_lock_spin(&icu_lock);
1827         ip = &idt[vector];
1828         func = (ip->gd_hioffset << 16) | ip->gd_looffset;
1829         KASSERT(func != (uintptr_t)&IDTVEC(rsvd),
1830             ("invalid idtfunc %#lx", func));
1831         setidt(vector, &IDTVEC(rsvd), SDT_APICT, SEL_KPL, GSEL_APIC);
1832         mtx_unlock_spin(&icu_lock);
1833 }
1834
1835 #endif /* SMP */