]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/x86/x86/local_apic.c
Merge ACPICA 20150717.
[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         ver = lapic_read32(LAPIC_VERSION);
472         if ((ver & APIC_VER_EOI_SUPPRESSION) != 0) {
473                 lapic_eoi_suppression = 1;
474                 TUNABLE_INT_FETCH("hw.lapic_eoi_suppression",
475                     &lapic_eoi_suppression);
476         }
477 }
478
479 /*
480  * Create a local APIC instance.
481  */
482 static void
483 native_lapic_create(u_int apic_id, int boot_cpu)
484 {
485         int i;
486
487         if (apic_id > MAX_APIC_ID) {
488                 printf("APIC: Ignoring local APIC with ID %d\n", apic_id);
489                 if (boot_cpu)
490                         panic("Can't ignore BSP");
491                 return;
492         }
493         KASSERT(!lapics[apic_id].la_present, ("duplicate local APIC %u",
494             apic_id));
495
496         /*
497          * Assume no local LVT overrides and a cluster of 0 and
498          * intra-cluster ID of 0.
499          */
500         lapics[apic_id].la_present = 1;
501         lapics[apic_id].la_id = apic_id;
502         for (i = 0; i <= APIC_LVT_MAX; i++) {
503                 lapics[apic_id].la_lvts[i] = lvts[i];
504                 lapics[apic_id].la_lvts[i].lvt_active = 0;
505         }
506         for (i = 0; i <= APIC_NUM_IOINTS; i++)
507             lapics[apic_id].la_ioint_irqs[i] = -1;
508         lapics[apic_id].la_ioint_irqs[IDT_SYSCALL - APIC_IO_INTS] = IRQ_SYSCALL;
509         lapics[apic_id].la_ioint_irqs[APIC_TIMER_INT - APIC_IO_INTS] =
510             IRQ_TIMER;
511 #ifdef KDTRACE_HOOKS
512         lapics[apic_id].la_ioint_irqs[IDT_DTRACE_RET - APIC_IO_INTS] =
513             IRQ_DTRACE_RET;
514 #endif
515 #ifdef XENHVM
516         lapics[apic_id].la_ioint_irqs[IDT_EVTCHN - APIC_IO_INTS] = IRQ_EVTCHN;
517 #endif
518
519
520 #ifdef SMP
521         cpu_add(apic_id, boot_cpu);
522 #endif
523 }
524
525 /*
526  * Dump contents of local APIC registers
527  */
528 static void
529 native_lapic_dump(const char* str)
530 {
531         uint32_t maxlvt;
532
533         maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
534         printf("cpu%d %s:\n", PCPU_GET(cpuid), str);
535         printf("     ID: 0x%08x   VER: 0x%08x LDR: 0x%08x DFR: 0x%08x",
536             lapic_read32(LAPIC_ID), lapic_read32(LAPIC_VERSION),
537             lapic_read32(LAPIC_LDR), x2apic_mode ? 0 : lapic_read32(LAPIC_DFR));
538         if ((cpu_feature2 & CPUID2_X2APIC) != 0)
539                 printf(" x2APIC: %d", x2apic_mode);
540         printf("\n  lint0: 0x%08x lint1: 0x%08x TPR: 0x%08x SVR: 0x%08x\n",
541             lapic_read32(LAPIC_LVT_LINT0), lapic_read32(LAPIC_LVT_LINT1),
542             lapic_read32(LAPIC_TPR), lapic_read32(LAPIC_SVR));
543         printf("  timer: 0x%08x therm: 0x%08x err: 0x%08x",
544             lapic_read32(LAPIC_LVT_TIMER), lapic_read32(LAPIC_LVT_THERMAL),
545             lapic_read32(LAPIC_LVT_ERROR));
546         if (maxlvt >= APIC_LVT_PMC)
547                 printf(" pmc: 0x%08x", lapic_read32(LAPIC_LVT_PCINT));
548         printf("\n");
549         if (maxlvt >= APIC_LVT_CMCI)
550                 printf("   cmci: 0x%08x\n", lapic_read32(LAPIC_LVT_CMCI));
551 }
552
553 static void
554 native_lapic_xapic_mode(void)
555 {
556         register_t saveintr;
557
558         saveintr = intr_disable();
559         if (x2apic_mode)
560                 native_lapic_enable_x2apic();
561         intr_restore(saveintr);
562 }
563
564 static void
565 native_lapic_setup(int boot)
566 {
567         struct lapic *la;
568         uint32_t maxlvt;
569         register_t saveintr;
570         char buf[MAXCOMLEN + 1];
571
572         saveintr = intr_disable();
573
574         la = &lapics[lapic_id()];
575         KASSERT(la->la_present, ("missing APIC structure"));
576         maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
577
578         /* Initialize the TPR to allow all interrupts. */
579         lapic_set_tpr(0);
580
581         /* Setup spurious vector and enable the local APIC. */
582         lapic_enable();
583
584         /* Program LINT[01] LVT entries. */
585         lapic_write32(LAPIC_LVT_LINT0, lvt_mode(la, APIC_LVT_LINT0,
586             lapic_read32(LAPIC_LVT_LINT0)));
587         lapic_write32(LAPIC_LVT_LINT1, lvt_mode(la, APIC_LVT_LINT1,
588             lapic_read32(LAPIC_LVT_LINT1)));
589
590         /* Program the PMC LVT entry if present. */
591         if (maxlvt >= APIC_LVT_PMC) {
592                 lapic_write32(LAPIC_LVT_PCINT, lvt_mode(la, APIC_LVT_PMC,
593                     LAPIC_LVT_PCINT));
594         }
595
596         /* Program timer LVT and setup handler. */
597         la->lvt_timer_cache = lvt_mode(la, APIC_LVT_TIMER,
598             lapic_read32(LAPIC_LVT_TIMER));
599         lapic_write32(LAPIC_LVT_TIMER, la->lvt_timer_cache);
600         if (boot) {
601                 snprintf(buf, sizeof(buf), "cpu%d:timer", PCPU_GET(cpuid));
602                 intrcnt_add(buf, &la->la_timer_count);
603         }
604
605         /* Setup the timer if configured. */
606         if (la->la_timer_mode != 0) {
607                 KASSERT(la->la_timer_period != 0, ("lapic%u: zero divisor",
608                     lapic_id()));
609                 lapic_timer_set_divisor(lapic_timer_divisor);
610                 if (la->la_timer_mode == 1)
611                         lapic_timer_periodic(la, la->la_timer_period, 1);
612                 else
613                         lapic_timer_oneshot(la, la->la_timer_period, 1);
614         }
615
616         /* Program error LVT and clear any existing errors. */
617         lapic_write32(LAPIC_LVT_ERROR, lvt_mode(la, APIC_LVT_ERROR,
618             lapic_read32(LAPIC_LVT_ERROR)));
619         lapic_write32(LAPIC_ESR, 0);
620
621         /* XXX: Thermal LVT */
622
623         /* Program the CMCI LVT entry if present. */
624         if (maxlvt >= APIC_LVT_CMCI) {
625                 lapic_write32(LAPIC_LVT_CMCI, lvt_mode(la, APIC_LVT_CMCI,
626                     lapic_read32(LAPIC_LVT_CMCI)));
627         }
628             
629         intr_restore(saveintr);
630 }
631
632 static void
633 native_lapic_reenable_pmc(void)
634 {
635 #ifdef HWPMC_HOOKS
636         uint32_t value;
637
638         value = lapic_read32(LAPIC_LVT_PCINT);
639         value &= ~APIC_LVT_M;
640         lapic_write32(LAPIC_LVT_PCINT, value);
641 #endif
642 }
643
644 #ifdef HWPMC_HOOKS
645 static void
646 lapic_update_pmc(void *dummy)
647 {
648         struct lapic *la;
649
650         la = &lapics[lapic_id()];
651         lapic_write32(LAPIC_LVT_PCINT, lvt_mode(la, APIC_LVT_PMC,
652             lapic_read32(LAPIC_LVT_PCINT)));
653 }
654 #endif
655
656 static int
657 native_lapic_enable_pmc(void)
658 {
659 #ifdef HWPMC_HOOKS
660         u_int32_t maxlvt;
661
662         /* Fail if the local APIC is not present. */
663         if (!x2apic_mode && lapic_map == NULL)
664                 return (0);
665
666         /* Fail if the PMC LVT is not present. */
667         maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
668         if (maxlvt < APIC_LVT_PMC)
669                 return (0);
670
671         lvts[APIC_LVT_PMC].lvt_masked = 0;
672
673 #ifdef SMP
674         /*
675          * If hwpmc was loaded at boot time then the APs may not be
676          * started yet.  In that case, don't forward the request to
677          * them as they will program the lvt when they start.
678          */
679         if (smp_started)
680                 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
681         else
682 #endif
683                 lapic_update_pmc(NULL);
684         return (1);
685 #else
686         return (0);
687 #endif
688 }
689
690 static void
691 native_lapic_disable_pmc(void)
692 {
693 #ifdef HWPMC_HOOKS
694         u_int32_t maxlvt;
695
696         /* Fail if the local APIC is not present. */
697         if (!x2apic_mode && lapic_map == NULL)
698                 return;
699
700         /* Fail if the PMC LVT is not present. */
701         maxlvt = (lapic_read32(LAPIC_VERSION) & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
702         if (maxlvt < APIC_LVT_PMC)
703                 return;
704
705         lvts[APIC_LVT_PMC].lvt_masked = 1;
706
707 #ifdef SMP
708         /* The APs should always be started when hwpmc is unloaded. */
709         KASSERT(mp_ncpus == 1 || smp_started, ("hwpmc unloaded too early"));
710 #endif
711         smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
712 #endif
713 }
714
715 static int
716 lapic_et_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
717 {
718         struct lapic *la;
719         u_long value;
720
721         la = &lapics[PCPU_GET(apic_id)];
722         if (et->et_frequency == 0) {
723                 /* Start off with a divisor of 2 (power on reset default). */
724                 lapic_timer_divisor = 2;
725                 /* Try to calibrate the local APIC timer. */
726                 do {
727                         lapic_timer_set_divisor(lapic_timer_divisor);
728                         lapic_timer_oneshot(la, APIC_TIMER_MAX_COUNT, 0);
729                         DELAY(1000000);
730                         value = APIC_TIMER_MAX_COUNT -
731                             lapic_read32(LAPIC_CCR_TIMER);
732                         if (value != APIC_TIMER_MAX_COUNT)
733                                 break;
734                         lapic_timer_divisor <<= 1;
735                 } while (lapic_timer_divisor <= 128);
736                 if (lapic_timer_divisor > 128)
737                         panic("lapic: Divisor too big");
738                 if (bootverbose)
739                         printf("lapic: Divisor %lu, Frequency %lu Hz\n",
740                             lapic_timer_divisor, value);
741                 et->et_frequency = value;
742                 et->et_min_period = (0x00000002LLU << 32) / et->et_frequency;
743                 et->et_max_period = (0xfffffffeLLU << 32) / et->et_frequency;
744         }
745         if (la->la_timer_mode == 0)
746                 lapic_timer_set_divisor(lapic_timer_divisor);
747         if (period != 0) {
748                 la->la_timer_mode = 1;
749                 la->la_timer_period = ((uint32_t)et->et_frequency * period) >> 32;
750                 lapic_timer_periodic(la, la->la_timer_period, 1);
751         } else {
752                 la->la_timer_mode = 2;
753                 la->la_timer_period = ((uint32_t)et->et_frequency * first) >> 32;
754                 lapic_timer_oneshot(la, la->la_timer_period, 1);
755         }
756         return (0);
757 }
758
759 static int
760 lapic_et_stop(struct eventtimer *et)
761 {
762         struct lapic *la = &lapics[PCPU_GET(apic_id)];
763
764         la->la_timer_mode = 0;
765         lapic_timer_stop(la);
766         return (0);
767 }
768
769 static void
770 native_lapic_disable(void)
771 {
772         uint32_t value;
773
774         /* Software disable the local APIC. */
775         value = lapic_read32(LAPIC_SVR);
776         value &= ~APIC_SVR_SWEN;
777         lapic_write32(LAPIC_SVR, value);
778 }
779
780 static void
781 lapic_enable(void)
782 {
783         uint32_t value;
784
785         /* Program the spurious vector to enable the local APIC. */
786         value = lapic_read32(LAPIC_SVR);
787         value &= ~(APIC_SVR_VECTOR | APIC_SVR_FOCUS);
788         value |= APIC_SVR_FEN | APIC_SVR_SWEN | APIC_SPURIOUS_INT;
789         if (lapic_eoi_suppression)
790                 value |= APIC_SVR_EOI_SUPPRESSION;
791         lapic_write32(LAPIC_SVR, value);
792 }
793
794 /* Reset the local APIC on the BSP during resume. */
795 static void
796 lapic_resume(struct pic *pic, bool suspend_cancelled)
797 {
798
799         lapic_setup(0);
800 }
801
802 static int
803 native_lapic_id(void)
804 {
805         uint32_t v;
806
807         KASSERT(x2apic_mode || lapic_map != NULL, ("local APIC is not mapped"));
808         v = lapic_read32(LAPIC_ID);
809         if (!x2apic_mode)
810                 v >>= APIC_ID_SHIFT;
811         return (v);
812 }
813
814 static int
815 native_lapic_intr_pending(u_int vector)
816 {
817         uint32_t irr;
818
819         /*
820          * The IRR registers are an array of registers each of which
821          * only describes 32 interrupts in the low 32 bits.  Thus, we
822          * divide the vector by 32 to get the register index.
823          * Finally, we modulus the vector by 32 to determine the
824          * individual bit to test.
825          */
826         irr = lapic_read32(LAPIC_IRR0 + vector / 32);
827         return (irr & 1 << (vector % 32));
828 }
829
830 static void
831 native_lapic_set_logical_id(u_int apic_id, u_int cluster, u_int cluster_id)
832 {
833         struct lapic *la;
834
835         KASSERT(lapics[apic_id].la_present, ("%s: APIC %u doesn't exist",
836             __func__, apic_id));
837         KASSERT(cluster <= APIC_MAX_CLUSTER, ("%s: cluster %u too big",
838             __func__, cluster));
839         KASSERT(cluster_id <= APIC_MAX_INTRACLUSTER_ID,
840             ("%s: intra cluster id %u too big", __func__, cluster_id));
841         la = &lapics[apic_id];
842         la->la_cluster = cluster;
843         la->la_cluster_id = cluster_id;
844 }
845
846 static int
847 native_lapic_set_lvt_mask(u_int apic_id, u_int pin, u_char masked)
848 {
849
850         if (pin > APIC_LVT_MAX)
851                 return (EINVAL);
852         if (apic_id == APIC_ID_ALL) {
853                 lvts[pin].lvt_masked = masked;
854                 if (bootverbose)
855                         printf("lapic:");
856         } else {
857                 KASSERT(lapics[apic_id].la_present,
858                     ("%s: missing APIC %u", __func__, apic_id));
859                 lapics[apic_id].la_lvts[pin].lvt_masked = masked;
860                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
861                 if (bootverbose)
862                         printf("lapic%u:", apic_id);
863         }
864         if (bootverbose)
865                 printf(" LINT%u %s\n", pin, masked ? "masked" : "unmasked");
866         return (0);
867 }
868
869 static int
870 native_lapic_set_lvt_mode(u_int apic_id, u_int pin, u_int32_t mode)
871 {
872         struct lvt *lvt;
873
874         if (pin > APIC_LVT_MAX)
875                 return (EINVAL);
876         if (apic_id == APIC_ID_ALL) {
877                 lvt = &lvts[pin];
878                 if (bootverbose)
879                         printf("lapic:");
880         } else {
881                 KASSERT(lapics[apic_id].la_present,
882                     ("%s: missing APIC %u", __func__, apic_id));
883                 lvt = &lapics[apic_id].la_lvts[pin];
884                 lvt->lvt_active = 1;
885                 if (bootverbose)
886                         printf("lapic%u:", apic_id);
887         }
888         lvt->lvt_mode = mode;
889         switch (mode) {
890         case APIC_LVT_DM_NMI:
891         case APIC_LVT_DM_SMI:
892         case APIC_LVT_DM_INIT:
893         case APIC_LVT_DM_EXTINT:
894                 lvt->lvt_edgetrigger = 1;
895                 lvt->lvt_activehi = 1;
896                 if (mode == APIC_LVT_DM_EXTINT)
897                         lvt->lvt_masked = 1;
898                 else
899                         lvt->lvt_masked = 0;
900                 break;
901         default:
902                 panic("Unsupported delivery mode: 0x%x\n", mode);
903         }
904         if (bootverbose) {
905                 printf(" Routing ");
906                 switch (mode) {
907                 case APIC_LVT_DM_NMI:
908                         printf("NMI");
909                         break;
910                 case APIC_LVT_DM_SMI:
911                         printf("SMI");
912                         break;
913                 case APIC_LVT_DM_INIT:
914                         printf("INIT");
915                         break;
916                 case APIC_LVT_DM_EXTINT:
917                         printf("ExtINT");
918                         break;
919                 }
920                 printf(" -> LINT%u\n", pin);
921         }
922         return (0);
923 }
924
925 static int
926 native_lapic_set_lvt_polarity(u_int apic_id, u_int pin, enum intr_polarity pol)
927 {
928
929         if (pin > APIC_LVT_MAX || pol == INTR_POLARITY_CONFORM)
930                 return (EINVAL);
931         if (apic_id == APIC_ID_ALL) {
932                 lvts[pin].lvt_activehi = (pol == INTR_POLARITY_HIGH);
933                 if (bootverbose)
934                         printf("lapic:");
935         } else {
936                 KASSERT(lapics[apic_id].la_present,
937                     ("%s: missing APIC %u", __func__, apic_id));
938                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
939                 lapics[apic_id].la_lvts[pin].lvt_activehi =
940                     (pol == INTR_POLARITY_HIGH);
941                 if (bootverbose)
942                         printf("lapic%u:", apic_id);
943         }
944         if (bootverbose)
945                 printf(" LINT%u polarity: %s\n", pin,
946                     pol == INTR_POLARITY_HIGH ? "high" : "low");
947         return (0);
948 }
949
950 static int
951 native_lapic_set_lvt_triggermode(u_int apic_id, u_int pin,
952      enum intr_trigger trigger)
953 {
954
955         if (pin > APIC_LVT_MAX || trigger == INTR_TRIGGER_CONFORM)
956                 return (EINVAL);
957         if (apic_id == APIC_ID_ALL) {
958                 lvts[pin].lvt_edgetrigger = (trigger == INTR_TRIGGER_EDGE);
959                 if (bootverbose)
960                         printf("lapic:");
961         } else {
962                 KASSERT(lapics[apic_id].la_present,
963                     ("%s: missing APIC %u", __func__, apic_id));
964                 lapics[apic_id].la_lvts[pin].lvt_edgetrigger =
965                     (trigger == INTR_TRIGGER_EDGE);
966                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
967                 if (bootverbose)
968                         printf("lapic%u:", apic_id);
969         }
970         if (bootverbose)
971                 printf(" LINT%u trigger: %s\n", pin,
972                     trigger == INTR_TRIGGER_EDGE ? "edge" : "level");
973         return (0);
974 }
975
976 /*
977  * Adjust the TPR of the current CPU so that it blocks all interrupts below
978  * the passed in vector.
979  */
980 static void
981 lapic_set_tpr(u_int vector)
982 {
983 #ifdef CHEAP_TPR
984         lapic_write32(LAPIC_TPR, vector);
985 #else
986         uint32_t tpr;
987
988         tpr = lapic_read32(LAPIC_TPR) & ~APIC_TPR_PRIO;
989         tpr |= vector;
990         lapic_write32(LAPIC_TPR, tpr);
991 #endif
992 }
993
994 static void
995 native_lapic_eoi(void)
996 {
997
998         lapic_write32_nofence(LAPIC_EOI, 0);
999 }
1000
1001 void
1002 lapic_handle_intr(int vector, struct trapframe *frame)
1003 {
1004         struct intsrc *isrc;
1005
1006         isrc = intr_lookup_source(apic_idt_to_irq(PCPU_GET(apic_id),
1007             vector));
1008         intr_execute_handlers(isrc, frame);
1009 }
1010
1011 void
1012 lapic_handle_timer(struct trapframe *frame)
1013 {
1014         struct lapic *la;
1015         struct trapframe *oldframe;
1016         struct thread *td;
1017
1018         /* Send EOI first thing. */
1019         lapic_eoi();
1020
1021 #if defined(SMP) && !defined(SCHED_ULE)
1022         /*
1023          * Don't do any accounting for the disabled HTT cores, since it
1024          * will provide misleading numbers for the userland.
1025          *
1026          * No locking is necessary here, since even if we lose the race
1027          * when hlt_cpus_mask changes it is not a big deal, really.
1028          *
1029          * Don't do that for ULE, since ULE doesn't consider hlt_cpus_mask
1030          * and unlike other schedulers it actually schedules threads to
1031          * those CPUs.
1032          */
1033         if (CPU_ISSET(PCPU_GET(cpuid), &hlt_cpus_mask))
1034                 return;
1035 #endif
1036
1037         /* Look up our local APIC structure for the tick counters. */
1038         la = &lapics[PCPU_GET(apic_id)];
1039         (*la->la_timer_count)++;
1040         critical_enter();
1041         if (lapic_et.et_active) {
1042                 td = curthread;
1043                 td->td_intr_nesting_level++;
1044                 oldframe = td->td_intr_frame;
1045                 td->td_intr_frame = frame;
1046                 lapic_et.et_event_cb(&lapic_et, lapic_et.et_arg);
1047                 td->td_intr_frame = oldframe;
1048                 td->td_intr_nesting_level--;
1049         }
1050         critical_exit();
1051 }
1052
1053 static void
1054 lapic_timer_set_divisor(u_int divisor)
1055 {
1056
1057         KASSERT(powerof2(divisor), ("lapic: invalid divisor %u", divisor));
1058         KASSERT(ffs(divisor) <= sizeof(lapic_timer_divisors) /
1059             sizeof(u_int32_t), ("lapic: invalid divisor %u", divisor));
1060         lapic_write32(LAPIC_DCR_TIMER, lapic_timer_divisors[ffs(divisor) - 1]);
1061 }
1062
1063 static void
1064 lapic_timer_oneshot(struct lapic *la, u_int count, int enable_int)
1065 {
1066         uint32_t value;
1067
1068         value = la->lvt_timer_cache;
1069         value &= ~APIC_LVTT_TM;
1070         value |= APIC_LVTT_TM_ONE_SHOT;
1071         if (enable_int)
1072                 value &= ~APIC_LVT_M;
1073         lapic_write32(LAPIC_LVT_TIMER, value);
1074         lapic_write32(LAPIC_ICR_TIMER, count);
1075 }
1076
1077 static void
1078 lapic_timer_periodic(struct lapic *la, u_int count, int enable_int)
1079 {
1080         uint32_t value;
1081
1082         value = la->lvt_timer_cache;
1083         value &= ~APIC_LVTT_TM;
1084         value |= APIC_LVTT_TM_PERIODIC;
1085         if (enable_int)
1086                 value &= ~APIC_LVT_M;
1087         lapic_write32(LAPIC_LVT_TIMER, value);
1088         lapic_write32(LAPIC_ICR_TIMER, count);
1089 }
1090
1091 static void
1092 lapic_timer_stop(struct lapic *la)
1093 {
1094         uint32_t value;
1095
1096         value = la->lvt_timer_cache;
1097         value &= ~APIC_LVTT_TM;
1098         value |= APIC_LVT_M;
1099         lapic_write32(LAPIC_LVT_TIMER, value);
1100 }
1101
1102 void
1103 lapic_handle_cmc(void)
1104 {
1105
1106         lapic_eoi();
1107         cmc_intr();
1108 }
1109
1110 /*
1111  * Called from the mca_init() to activate the CMC interrupt if this CPU is
1112  * responsible for monitoring any MC banks for CMC events.  Since mca_init()
1113  * is called prior to lapic_setup() during boot, this just needs to unmask
1114  * this CPU's LVT_CMCI entry.
1115  */
1116 static void
1117 native_lapic_enable_cmc(void)
1118 {
1119         u_int apic_id;
1120
1121 #ifdef DEV_ATPIC
1122         if (!x2apic_mode && lapic_map == NULL)
1123                 return;
1124 #endif
1125         apic_id = PCPU_GET(apic_id);
1126         KASSERT(lapics[apic_id].la_present,
1127             ("%s: missing APIC %u", __func__, apic_id));
1128         lapics[apic_id].la_lvts[APIC_LVT_CMCI].lvt_masked = 0;
1129         lapics[apic_id].la_lvts[APIC_LVT_CMCI].lvt_active = 1;
1130         if (bootverbose)
1131                 printf("lapic%u: CMCI unmasked\n", apic_id);
1132 }
1133
1134 void
1135 lapic_handle_error(void)
1136 {
1137         uint32_t esr;
1138
1139         /*
1140          * Read the contents of the error status register.  Write to
1141          * the register first before reading from it to force the APIC
1142          * to update its value to indicate any errors that have
1143          * occurred since the previous write to the register.
1144          */
1145         lapic_write32(LAPIC_ESR, 0);
1146         esr = lapic_read32(LAPIC_ESR);
1147
1148         printf("CPU%d: local APIC error 0x%x\n", PCPU_GET(cpuid), esr);
1149         lapic_eoi();
1150 }
1151
1152 static u_int
1153 native_apic_cpuid(u_int apic_id)
1154 {
1155 #ifdef SMP
1156         return apic_cpuids[apic_id];
1157 #else
1158         return 0;
1159 #endif
1160 }
1161
1162 /* Request a free IDT vector to be used by the specified IRQ. */
1163 static u_int
1164 native_apic_alloc_vector(u_int apic_id, u_int irq)
1165 {
1166         u_int vector;
1167
1168         KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
1169
1170         /*
1171          * Search for a free vector.  Currently we just use a very simple
1172          * algorithm to find the first free vector.
1173          */
1174         mtx_lock_spin(&icu_lock);
1175         for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
1176                 if (lapics[apic_id].la_ioint_irqs[vector] != -1)
1177                         continue;
1178                 lapics[apic_id].la_ioint_irqs[vector] = irq;
1179                 mtx_unlock_spin(&icu_lock);
1180                 return (vector + APIC_IO_INTS);
1181         }
1182         mtx_unlock_spin(&icu_lock);
1183         return (0);
1184 }
1185
1186 /*
1187  * Request 'count' free contiguous IDT vectors to be used by 'count'
1188  * IRQs.  'count' must be a power of two and the vectors will be
1189  * aligned on a boundary of 'align'.  If the request cannot be
1190  * satisfied, 0 is returned.
1191  */
1192 static u_int
1193 native_apic_alloc_vectors(u_int apic_id, u_int *irqs, u_int count, u_int align)
1194 {
1195         u_int first, run, vector;
1196
1197         KASSERT(powerof2(count), ("bad count"));
1198         KASSERT(powerof2(align), ("bad align"));
1199         KASSERT(align >= count, ("align < count"));
1200 #ifdef INVARIANTS
1201         for (run = 0; run < count; run++)
1202                 KASSERT(irqs[run] < NUM_IO_INTS, ("Invalid IRQ %u at index %u",
1203                     irqs[run], run));
1204 #endif
1205
1206         /*
1207          * Search for 'count' free vectors.  As with apic_alloc_vector(),
1208          * this just uses a simple first fit algorithm.
1209          */
1210         run = 0;
1211         first = 0;
1212         mtx_lock_spin(&icu_lock);
1213         for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
1214
1215                 /* Vector is in use, end run. */
1216                 if (lapics[apic_id].la_ioint_irqs[vector] != -1) {
1217                         run = 0;
1218                         first = 0;
1219                         continue;
1220                 }
1221
1222                 /* Start a new run if run == 0 and vector is aligned. */
1223                 if (run == 0) {
1224                         if ((vector & (align - 1)) != 0)
1225                                 continue;
1226                         first = vector;
1227                 }
1228                 run++;
1229
1230                 /* Keep looping if the run isn't long enough yet. */
1231                 if (run < count)
1232                         continue;
1233
1234                 /* Found a run, assign IRQs and return the first vector. */
1235                 for (vector = 0; vector < count; vector++)
1236                         lapics[apic_id].la_ioint_irqs[first + vector] =
1237                             irqs[vector];
1238                 mtx_unlock_spin(&icu_lock);
1239                 return (first + APIC_IO_INTS);
1240         }
1241         mtx_unlock_spin(&icu_lock);
1242         printf("APIC: Couldn't find APIC vectors for %u IRQs\n", count);
1243         return (0);
1244 }
1245
1246 /*
1247  * Enable a vector for a particular apic_id.  Since all lapics share idt
1248  * entries and ioint_handlers this enables the vector on all lapics.  lapics
1249  * which do not have the vector configured would report spurious interrupts
1250  * should it fire.
1251  */
1252 static void
1253 native_apic_enable_vector(u_int apic_id, u_int vector)
1254 {
1255
1256         KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1257         KASSERT(ioint_handlers[vector / 32] != NULL,
1258             ("No ISR handler for vector %u", vector));
1259 #ifdef KDTRACE_HOOKS
1260         KASSERT(vector != IDT_DTRACE_RET,
1261             ("Attempt to overwrite DTrace entry"));
1262 #endif
1263         setidt(vector, ioint_handlers[vector / 32], SDT_APIC, SEL_KPL,
1264             GSEL_APIC);
1265 }
1266
1267 static void
1268 native_apic_disable_vector(u_int apic_id, u_int vector)
1269 {
1270
1271         KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1272 #ifdef KDTRACE_HOOKS
1273         KASSERT(vector != IDT_DTRACE_RET,
1274             ("Attempt to overwrite DTrace entry"));
1275 #endif
1276         KASSERT(ioint_handlers[vector / 32] != NULL,
1277             ("No ISR handler for vector %u", vector));
1278 #ifdef notyet
1279         /*
1280          * We can not currently clear the idt entry because other cpus
1281          * may have a valid vector at this offset.
1282          */
1283         setidt(vector, &IDTVEC(rsvd), SDT_APICT, SEL_KPL, GSEL_APIC);
1284 #endif
1285 }
1286
1287 /* Release an APIC vector when it's no longer in use. */
1288 static void
1289 native_apic_free_vector(u_int apic_id, u_int vector, u_int irq)
1290 {
1291         struct thread *td;
1292
1293         KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1294             vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1295             ("Vector %u does not map to an IRQ line", vector));
1296         KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
1297         KASSERT(lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] ==
1298             irq, ("IRQ mismatch"));
1299 #ifdef KDTRACE_HOOKS
1300         KASSERT(vector != IDT_DTRACE_RET,
1301             ("Attempt to overwrite DTrace entry"));
1302 #endif
1303
1304         /*
1305          * Bind us to the cpu that owned the vector before freeing it so
1306          * we don't lose an interrupt delivery race.
1307          */
1308         td = curthread;
1309         if (!rebooting) {
1310                 thread_lock(td);
1311                 if (sched_is_bound(td))
1312                         panic("apic_free_vector: Thread already bound.\n");
1313                 sched_bind(td, apic_cpuid(apic_id));
1314                 thread_unlock(td);
1315         }
1316         mtx_lock_spin(&icu_lock);
1317         lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] = -1;
1318         mtx_unlock_spin(&icu_lock);
1319         if (!rebooting) {
1320                 thread_lock(td);
1321                 sched_unbind(td);
1322                 thread_unlock(td);
1323         }
1324 }
1325
1326 /* Map an IDT vector (APIC) to an IRQ (interrupt source). */
1327 static u_int
1328 apic_idt_to_irq(u_int apic_id, u_int vector)
1329 {
1330         int irq;
1331
1332         KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1333             vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1334             ("Vector %u does not map to an IRQ line", vector));
1335 #ifdef KDTRACE_HOOKS
1336         KASSERT(vector != IDT_DTRACE_RET,
1337             ("Attempt to overwrite DTrace entry"));
1338 #endif
1339         irq = lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS];
1340         if (irq < 0)
1341                 irq = 0;
1342         return (irq);
1343 }
1344
1345 #ifdef DDB
1346 /*
1347  * Dump data about APIC IDT vector mappings.
1348  */
1349 DB_SHOW_COMMAND(apic, db_show_apic)
1350 {
1351         struct intsrc *isrc;
1352         int i, verbose;
1353         u_int apic_id;
1354         u_int irq;
1355
1356         if (strcmp(modif, "vv") == 0)
1357                 verbose = 2;
1358         else if (strcmp(modif, "v") == 0)
1359                 verbose = 1;
1360         else
1361                 verbose = 0;
1362         for (apic_id = 0; apic_id <= MAX_APIC_ID; apic_id++) {
1363                 if (lapics[apic_id].la_present == 0)
1364                         continue;
1365                 db_printf("Interrupts bound to lapic %u\n", apic_id);
1366                 for (i = 0; i < APIC_NUM_IOINTS + 1 && !db_pager_quit; i++) {
1367                         irq = lapics[apic_id].la_ioint_irqs[i];
1368                         if (irq == -1 || irq == IRQ_SYSCALL)
1369                                 continue;
1370 #ifdef KDTRACE_HOOKS
1371                         if (irq == IRQ_DTRACE_RET)
1372                                 continue;
1373 #endif
1374 #ifdef XENHVM
1375                         if (irq == IRQ_EVTCHN)
1376                                 continue;
1377 #endif
1378                         db_printf("vec 0x%2x -> ", i + APIC_IO_INTS);
1379                         if (irq == IRQ_TIMER)
1380                                 db_printf("lapic timer\n");
1381                         else if (irq < NUM_IO_INTS) {
1382                                 isrc = intr_lookup_source(irq);
1383                                 if (isrc == NULL || verbose == 0)
1384                                         db_printf("IRQ %u\n", irq);
1385                                 else
1386                                         db_dump_intr_event(isrc->is_event,
1387                                             verbose == 2);
1388                         } else
1389                                 db_printf("IRQ %u ???\n", irq);
1390                 }
1391         }
1392 }
1393
1394 static void
1395 dump_mask(const char *prefix, uint32_t v, int base)
1396 {
1397         int i, first;
1398
1399         first = 1;
1400         for (i = 0; i < 32; i++)
1401                 if (v & (1 << i)) {
1402                         if (first) {
1403                                 db_printf("%s:", prefix);
1404                                 first = 0;
1405                         }
1406                         db_printf(" %02x", base + i);
1407                 }
1408         if (!first)
1409                 db_printf("\n");
1410 }
1411
1412 /* Show info from the lapic regs for this CPU. */
1413 DB_SHOW_COMMAND(lapic, db_show_lapic)
1414 {
1415         uint32_t v;
1416
1417         db_printf("lapic ID = %d\n", lapic_id());
1418         v = lapic_read32(LAPIC_VERSION);
1419         db_printf("version  = %d.%d\n", (v & APIC_VER_VERSION) >> 4,
1420             v & 0xf);
1421         db_printf("max LVT  = %d\n", (v & APIC_VER_MAXLVT) >> MAXLVTSHIFT);
1422         v = lapic_read32(LAPIC_SVR);
1423         db_printf("SVR      = %02x (%s)\n", v & APIC_SVR_VECTOR,
1424             v & APIC_SVR_ENABLE ? "enabled" : "disabled");
1425         db_printf("TPR      = %02x\n", lapic_read32(LAPIC_TPR));
1426
1427 #define dump_field(prefix, regn, index)                                 \
1428         dump_mask(__XSTRING(prefix ## index),                           \
1429             lapic_read32(LAPIC_ ## regn ## index),                      \
1430             index * 32)
1431
1432         db_printf("In-service Interrupts:\n");
1433         dump_field(isr, ISR, 0);
1434         dump_field(isr, ISR, 1);
1435         dump_field(isr, ISR, 2);
1436         dump_field(isr, ISR, 3);
1437         dump_field(isr, ISR, 4);
1438         dump_field(isr, ISR, 5);
1439         dump_field(isr, ISR, 6);
1440         dump_field(isr, ISR, 7);
1441
1442         db_printf("TMR Interrupts:\n");
1443         dump_field(tmr, TMR, 0);
1444         dump_field(tmr, TMR, 1);
1445         dump_field(tmr, TMR, 2);
1446         dump_field(tmr, TMR, 3);
1447         dump_field(tmr, TMR, 4);
1448         dump_field(tmr, TMR, 5);
1449         dump_field(tmr, TMR, 6);
1450         dump_field(tmr, TMR, 7);
1451
1452         db_printf("IRR Interrupts:\n");
1453         dump_field(irr, IRR, 0);
1454         dump_field(irr, IRR, 1);
1455         dump_field(irr, IRR, 2);
1456         dump_field(irr, IRR, 3);
1457         dump_field(irr, IRR, 4);
1458         dump_field(irr, IRR, 5);
1459         dump_field(irr, IRR, 6);
1460         dump_field(irr, IRR, 7);
1461
1462 #undef dump_field
1463 }
1464 #endif
1465
1466 /*
1467  * APIC probing support code.  This includes code to manage enumerators.
1468  */
1469
1470 static SLIST_HEAD(, apic_enumerator) enumerators =
1471         SLIST_HEAD_INITIALIZER(enumerators);
1472 static struct apic_enumerator *best_enum;
1473
1474 void
1475 apic_register_enumerator(struct apic_enumerator *enumerator)
1476 {
1477 #ifdef INVARIANTS
1478         struct apic_enumerator *apic_enum;
1479
1480         SLIST_FOREACH(apic_enum, &enumerators, apic_next) {
1481                 if (apic_enum == enumerator)
1482                         panic("%s: Duplicate register of %s", __func__,
1483                             enumerator->apic_name);
1484         }
1485 #endif
1486         SLIST_INSERT_HEAD(&enumerators, enumerator, apic_next);
1487 }
1488
1489 /*
1490  * We have to look for CPU's very, very early because certain subsystems
1491  * want to know how many CPU's we have extremely early on in the boot
1492  * process.
1493  */
1494 static void
1495 apic_init(void *dummy __unused)
1496 {
1497         struct apic_enumerator *enumerator;
1498         int retval, best;
1499
1500         /* We only support built in local APICs. */
1501         if (!(cpu_feature & CPUID_APIC))
1502                 return;
1503
1504         /* Don't probe if APIC mode is disabled. */
1505         if (resource_disabled("apic", 0))
1506                 return;
1507
1508         /* Probe all the enumerators to find the best match. */
1509         best_enum = NULL;
1510         best = 0;
1511         SLIST_FOREACH(enumerator, &enumerators, apic_next) {
1512                 retval = enumerator->apic_probe();
1513                 if (retval > 0)
1514                         continue;
1515                 if (best_enum == NULL || best < retval) {
1516                         best_enum = enumerator;
1517                         best = retval;
1518                 }
1519         }
1520         if (best_enum == NULL) {
1521                 if (bootverbose)
1522                         printf("APIC: Could not find any APICs.\n");
1523 #ifndef DEV_ATPIC
1524                 panic("running without device atpic requires a local APIC");
1525 #endif
1526                 return;
1527         }
1528
1529         if (bootverbose)
1530                 printf("APIC: Using the %s enumerator.\n",
1531                     best_enum->apic_name);
1532
1533 #ifdef I686_CPU
1534         /*
1535          * To work around an errata, we disable the local APIC on some
1536          * CPUs during early startup.  We need to turn the local APIC back
1537          * on on such CPUs now.
1538          */
1539         ppro_reenable_apic();
1540 #endif
1541
1542         /* Probe the CPU's in the system. */
1543         retval = best_enum->apic_probe_cpus();
1544         if (retval != 0)
1545                 printf("%s: Failed to probe CPUs: returned %d\n",
1546                     best_enum->apic_name, retval);
1547
1548 }
1549 SYSINIT(apic_init, SI_SUB_TUNABLES - 1, SI_ORDER_SECOND, apic_init, NULL);
1550
1551 /*
1552  * Setup the local APIC.  We have to do this prior to starting up the APs
1553  * in the SMP case.
1554  */
1555 static void
1556 apic_setup_local(void *dummy __unused)
1557 {
1558         int retval;
1559  
1560         if (best_enum == NULL)
1561                 return;
1562
1563         /* Initialize the local APIC. */
1564         retval = best_enum->apic_setup_local();
1565         if (retval != 0)
1566                 printf("%s: Failed to setup the local APIC: returned %d\n",
1567                     best_enum->apic_name, retval);
1568 }
1569 SYSINIT(apic_setup_local, SI_SUB_CPU, SI_ORDER_SECOND, apic_setup_local, NULL);
1570
1571 /*
1572  * Setup the I/O APICs.
1573  */
1574 static void
1575 apic_setup_io(void *dummy __unused)
1576 {
1577         int retval;
1578
1579         if (best_enum == NULL)
1580                 return;
1581
1582         /*
1583          * Local APIC must be registered before other PICs and pseudo PICs
1584          * for proper suspend/resume order.
1585          */
1586         intr_register_pic(&lapic_pic);
1587
1588         retval = best_enum->apic_setup_io();
1589         if (retval != 0)
1590                 printf("%s: Failed to setup I/O APICs: returned %d\n",
1591                     best_enum->apic_name, retval);
1592
1593         /*
1594          * Finish setting up the local APIC on the BSP once we know
1595          * how to properly program the LINT pins.  In particular, this
1596          * enables the EOI suppression mode, if LAPIC support it and
1597          * user did not disabled the mode.
1598          */
1599         lapic_setup(1);
1600         if (bootverbose)
1601                 lapic_dump("BSP");
1602
1603         /* Enable the MSI "pic". */
1604         init_ops.msi_init();
1605 }
1606 SYSINIT(apic_setup_io, SI_SUB_INTR, SI_ORDER_THIRD, apic_setup_io, NULL);
1607
1608 #ifdef SMP
1609 /*
1610  * Inter Processor Interrupt functions.  The lapic_ipi_*() functions are
1611  * private to the MD code.  The public interface for the rest of the
1612  * kernel is defined in mp_machdep.c.
1613  */
1614 static int
1615 native_lapic_ipi_wait(int delay)
1616 {
1617         int x;
1618
1619         /* LAPIC_ICR.APIC_DELSTAT_MASK is undefined in x2APIC mode */
1620         if (x2apic_mode)
1621                 return (1);
1622
1623         /*
1624          * Wait delay microseconds for IPI to be sent.  If delay is
1625          * -1, we wait forever.
1626          */
1627         if (delay == -1) {
1628                 while ((lapic_read_icr_lo() & APIC_DELSTAT_MASK) !=
1629                     APIC_DELSTAT_IDLE)
1630                         ia32_pause();
1631                 return (1);
1632         }
1633
1634         for (x = 0; x < delay; x += 5) {
1635                 if ((lapic_read_icr_lo() & APIC_DELSTAT_MASK) ==
1636                     APIC_DELSTAT_IDLE)
1637                         return (1);
1638                 DELAY(5);
1639         }
1640         return (0);
1641 }
1642
1643 static void
1644 native_lapic_ipi_raw(register_t icrlo, u_int dest)
1645 {
1646         uint64_t icr;
1647         uint32_t vhi, vlo;
1648         register_t saveintr;
1649
1650         /* XXX: Need more sanity checking of icrlo? */
1651         KASSERT(x2apic_mode || lapic_map != NULL,
1652             ("%s called too early", __func__));
1653         KASSERT(x2apic_mode ||
1654             (dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
1655             ("%s: invalid dest field", __func__));
1656         KASSERT((icrlo & APIC_ICRLO_RESV_MASK) == 0,
1657             ("%s: reserved bits set in ICR LO register", __func__));
1658
1659         /* Set destination in ICR HI register if it is being used. */
1660         saveintr = intr_disable();
1661         if (!x2apic_mode)
1662                 icr = lapic_read_icr();
1663
1664         if ((icrlo & APIC_DEST_MASK) == APIC_DEST_DESTFLD) {
1665                 if (x2apic_mode) {
1666                         vhi = dest;
1667                 } else {
1668                         vhi = icr >> 32;
1669                         vhi &= ~APIC_ID_MASK;
1670                         vhi |= dest << APIC_ID_SHIFT;
1671                 }
1672         } else {
1673                 vhi = 0;
1674         }
1675
1676         /* Program the contents of the IPI and dispatch it. */
1677         if (x2apic_mode) {
1678                 vlo = icrlo;
1679         } else {
1680                 vlo = icr;
1681                 vlo &= APIC_ICRLO_RESV_MASK;
1682                 vlo |= icrlo;
1683         }
1684         lapic_write_icr(vhi, vlo);
1685         intr_restore(saveintr);
1686 }
1687
1688 #define BEFORE_SPIN     50000
1689 #ifdef DETECT_DEADLOCK
1690 #define AFTER_SPIN      50
1691 #endif
1692
1693 static void
1694 native_lapic_ipi_vectored(u_int vector, int dest)
1695 {
1696         register_t icrlo, destfield;
1697
1698         KASSERT((vector & ~APIC_VECTOR_MASK) == 0,
1699             ("%s: invalid vector %d", __func__, vector));
1700
1701         icrlo = APIC_DESTMODE_PHY | APIC_TRIGMOD_EDGE | APIC_LEVEL_ASSERT;
1702
1703         /*
1704          * IPI_STOP_HARD is just a "fake" vector used to send a NMI.
1705          * Use special rules regard NMI if passed, otherwise specify
1706          * the vector.
1707          */
1708         if (vector == IPI_STOP_HARD)
1709                 icrlo |= APIC_DELMODE_NMI;
1710         else
1711                 icrlo |= vector | APIC_DELMODE_FIXED;
1712         destfield = 0;
1713         switch (dest) {
1714         case APIC_IPI_DEST_SELF:
1715                 icrlo |= APIC_DEST_SELF;
1716                 break;
1717         case APIC_IPI_DEST_ALL:
1718                 icrlo |= APIC_DEST_ALLISELF;
1719                 break;
1720         case APIC_IPI_DEST_OTHERS:
1721                 icrlo |= APIC_DEST_ALLESELF;
1722                 break;
1723         default:
1724                 KASSERT(x2apic_mode ||
1725                     (dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
1726                     ("%s: invalid destination 0x%x", __func__, dest));
1727                 destfield = dest;
1728         }
1729
1730         /* Wait for an earlier IPI to finish. */
1731         if (!lapic_ipi_wait(BEFORE_SPIN)) {
1732                 if (panicstr != NULL)
1733                         return;
1734                 else
1735                         panic("APIC: Previous IPI is stuck");
1736         }
1737
1738         lapic_ipi_raw(icrlo, destfield);
1739
1740 #ifdef DETECT_DEADLOCK
1741         /* Wait for IPI to be delivered. */
1742         if (!lapic_ipi_wait(AFTER_SPIN)) {
1743 #ifdef needsattention
1744                 /*
1745                  * XXX FIXME:
1746                  *
1747                  * The above function waits for the message to actually be
1748                  * delivered.  It breaks out after an arbitrary timeout
1749                  * since the message should eventually be delivered (at
1750                  * least in theory) and that if it wasn't we would catch
1751                  * the failure with the check above when the next IPI is
1752                  * sent.
1753                  *
1754                  * We could skip this wait entirely, EXCEPT it probably
1755                  * protects us from other routines that assume that the
1756                  * message was delivered and acted upon when this function
1757                  * returns.
1758                  */
1759                 printf("APIC: IPI might be stuck\n");
1760 #else /* !needsattention */
1761                 /* Wait until mesage is sent without a timeout. */
1762                 while (lapic_read_icr_lo() & APIC_DELSTAT_PEND)
1763                         ia32_pause();
1764 #endif /* needsattention */
1765         }
1766 #endif /* DETECT_DEADLOCK */
1767 }
1768
1769 /*
1770  * Since the IDT is shared by all CPUs the IPI slot update needs to be globally
1771  * visible.
1772  *
1773  * Consider the case where an IPI is generated immediately after allocation:
1774  *     vector = lapic_ipi_alloc(ipifunc);
1775  *     ipi_selected(other_cpus, vector);
1776  *
1777  * In xAPIC mode a write to ICR_LO has serializing semantics because the
1778  * APIC page is mapped as an uncached region. In x2APIC mode there is an
1779  * explicit 'mfence' before the ICR MSR is written. Therefore in both cases
1780  * the IDT slot update is globally visible before the IPI is delivered.
1781  */
1782 static int
1783 native_lapic_ipi_alloc(inthand_t *ipifunc)
1784 {
1785         struct gate_descriptor *ip;
1786         long func;
1787         int idx, vector;
1788
1789         KASSERT(ipifunc != &IDTVEC(rsvd), ("invalid ipifunc %p", ipifunc));
1790
1791         vector = -1;
1792         mtx_lock_spin(&icu_lock);
1793         for (idx = IPI_DYN_FIRST; idx <= IPI_DYN_LAST; idx++) {
1794                 ip = &idt[idx];
1795                 func = (ip->gd_hioffset << 16) | ip->gd_looffset;
1796                 if (func == (uintptr_t)&IDTVEC(rsvd)) {
1797                         vector = idx;
1798                         setidt(vector, ipifunc, SDT_APIC, SEL_KPL, GSEL_APIC);
1799                         break;
1800                 }
1801         }
1802         mtx_unlock_spin(&icu_lock);
1803         return (vector);
1804 }
1805
1806 static void
1807 native_lapic_ipi_free(int vector)
1808 {
1809         struct gate_descriptor *ip;
1810         long func;
1811
1812         KASSERT(vector >= IPI_DYN_FIRST && vector <= IPI_DYN_LAST,
1813             ("%s: invalid vector %d", __func__, vector));
1814
1815         mtx_lock_spin(&icu_lock);
1816         ip = &idt[vector];
1817         func = (ip->gd_hioffset << 16) | ip->gd_looffset;
1818         KASSERT(func != (uintptr_t)&IDTVEC(rsvd),
1819             ("invalid idtfunc %#lx", func));
1820         setidt(vector, &IDTVEC(rsvd), SDT_APICT, SEL_KPL, GSEL_APIC);
1821         mtx_unlock_spin(&icu_lock);
1822 }
1823
1824 #endif /* SMP */