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