]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - sys/x86/x86/local_apic.c
Copy stable/8 to releng/8.2 in preparation for FreeBSD-8.2 release.
[FreeBSD/releng/8.2.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_hwpmc_hooks.h"
38 #include "opt_kdtrace.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
53 #include <vm/vm.h>
54 #include <vm/pmap.h>
55
56 #include <machine/apicreg.h>
57 #include <machine/cpu.h>
58 #include <machine/cputypes.h>
59 #include <machine/frame.h>
60 #include <machine/intr_machdep.h>
61 #include <machine/apicvar.h>
62 #include <machine/mca.h>
63 #include <machine/md_var.h>
64 #include <machine/smp.h>
65 #include <machine/specialreg.h>
66
67 #ifdef DDB
68 #include <sys/interrupt.h>
69 #include <ddb/ddb.h>
70 #endif
71
72 #ifdef __amd64__
73 #define SDT_APIC        SDT_SYSIGT
74 #define SDT_APICT       SDT_SYSIGT
75 #define GSEL_APIC       0
76 #else
77 #define SDT_APIC        SDT_SYS386IGT
78 #define SDT_APICT       SDT_SYS386TGT
79 #define GSEL_APIC       GSEL(GCODE_SEL, SEL_KPL)
80 #endif
81
82 #ifdef KDTRACE_HOOKS
83 #include <sys/dtrace_bsd.h>
84 cyclic_clock_func_t     cyclic_clock_func[MAXCPU];
85 #endif
86
87 /* Sanity checks on IDT vectors. */
88 CTASSERT(APIC_IO_INTS + APIC_NUM_IOINTS == APIC_TIMER_INT);
89 CTASSERT(APIC_TIMER_INT < APIC_LOCAL_INTS);
90 CTASSERT(APIC_LOCAL_INTS == 240);
91 CTASSERT(IPI_STOP < APIC_SPURIOUS_INT);
92
93 /* Magic IRQ values for the timer and syscalls. */
94 #define IRQ_TIMER       (NUM_IO_INTS + 1)
95 #define IRQ_SYSCALL     (NUM_IO_INTS + 2)
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[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_hard_ticks;
123         u_long la_stat_ticks;
124         u_long la_prof_ticks;
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[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 lapic_t *lapic;
160 vm_paddr_t lapic_paddr;
161 static u_long lapic_timer_divisor, lapic_timer_period, lapic_timer_hz;
162 static enum lapic_clock clockcoverage;
163
164 static void     lapic_enable(void);
165 static void     lapic_resume(struct pic *pic);
166 static void     lapic_timer_enable_intr(void);
167 static void     lapic_timer_oneshot(u_int count);
168 static void     lapic_timer_periodic(u_int count);
169 static void     lapic_timer_set_divisor(u_int divisor);
170 static uint32_t lvt_mode(struct lapic *la, u_int pin, uint32_t value);
171
172 struct pic lapic_pic = { .pic_resume = lapic_resume };
173
174 static uint32_t
175 lvt_mode(struct lapic *la, u_int pin, uint32_t value)
176 {
177         struct lvt *lvt;
178
179         KASSERT(pin <= LVT_MAX, ("%s: pin %u out of range", __func__, pin));
180         if (la->la_lvts[pin].lvt_active)
181                 lvt = &la->la_lvts[pin];
182         else
183                 lvt = &lvts[pin];
184
185         value &= ~(APIC_LVT_M | APIC_LVT_TM | APIC_LVT_IIPP | APIC_LVT_DM |
186             APIC_LVT_VECTOR);
187         if (lvt->lvt_edgetrigger == 0)
188                 value |= APIC_LVT_TM;
189         if (lvt->lvt_activehi == 0)
190                 value |= APIC_LVT_IIPP_INTALO;
191         if (lvt->lvt_masked)
192                 value |= APIC_LVT_M;
193         value |= lvt->lvt_mode;
194         switch (lvt->lvt_mode) {
195         case APIC_LVT_DM_NMI:
196         case APIC_LVT_DM_SMI:
197         case APIC_LVT_DM_INIT:
198         case APIC_LVT_DM_EXTINT:
199                 if (!lvt->lvt_edgetrigger) {
200                         printf("lapic%u: Forcing LINT%u to edge trigger\n",
201                             la->la_id, pin);
202                         value |= APIC_LVT_TM;
203                 }
204                 /* Use a vector of 0. */
205                 break;
206         case APIC_LVT_DM_FIXED:
207                 value |= lvt->lvt_vector;
208                 break;
209         default:
210                 panic("bad APIC LVT delivery mode: %#x\n", value);
211         }
212         return (value);
213 }
214
215 /*
216  * Map the local APIC and setup necessary interrupt vectors.
217  */
218 void
219 lapic_init(vm_paddr_t addr)
220 {
221
222         /* Map the local APIC and setup the spurious interrupt handler. */
223         KASSERT(trunc_page(addr) == addr,
224             ("local APIC not aligned on a page boundary"));
225         lapic = pmap_mapdev(addr, sizeof(lapic_t));
226         lapic_paddr = addr;
227         setidt(APIC_SPURIOUS_INT, IDTVEC(spuriousint), SDT_APIC, SEL_KPL,
228             GSEL_APIC);
229
230         /* Perform basic initialization of the BSP's local APIC. */
231         lapic_enable();
232
233         /* Set BSP's per-CPU local APIC ID. */
234         PCPU_SET(apic_id, lapic_id());
235
236         /* Local APIC timer interrupt. */
237         setidt(APIC_TIMER_INT, IDTVEC(timerint), SDT_APIC, SEL_KPL, GSEL_APIC);
238
239         /* Local APIC error interrupt. */
240         setidt(APIC_ERROR_INT, IDTVEC(errorint), SDT_APIC, SEL_KPL, GSEL_APIC);
241
242         /* XXX: Thermal interrupt */
243
244         /* Local APIC CMCI. */
245         setidt(APIC_CMC_INT, IDTVEC(cmcint), SDT_APICT, SEL_KPL,
246             GSEL(GCODE_SEL, SEL_KPL));
247 }
248
249 /*
250  * Create a local APIC instance.
251  */
252 void
253 lapic_create(u_int apic_id, int boot_cpu)
254 {
255         int i;
256
257         if (apic_id > MAX_APIC_ID) {
258                 printf("APIC: Ignoring local APIC with ID %d\n", apic_id);
259                 if (boot_cpu)
260                         panic("Can't ignore BSP");
261                 return;
262         }
263         KASSERT(!lapics[apic_id].la_present, ("duplicate local APIC %u",
264             apic_id));
265
266         /*
267          * Assume no local LVT overrides and a cluster of 0 and
268          * intra-cluster ID of 0.
269          */
270         lapics[apic_id].la_present = 1;
271         lapics[apic_id].la_id = apic_id;
272         for (i = 0; i <= LVT_MAX; i++) {
273                 lapics[apic_id].la_lvts[i] = lvts[i];
274                 lapics[apic_id].la_lvts[i].lvt_active = 0;
275         }
276         for (i = 0; i <= APIC_NUM_IOINTS; i++)
277             lapics[apic_id].la_ioint_irqs[i] = -1;
278         lapics[apic_id].la_ioint_irqs[IDT_SYSCALL - APIC_IO_INTS] = IRQ_SYSCALL;
279         lapics[apic_id].la_ioint_irqs[APIC_TIMER_INT - APIC_IO_INTS] =
280             IRQ_TIMER;
281
282 #ifdef SMP
283         cpu_add(apic_id, boot_cpu);
284 #endif
285 }
286
287 /*
288  * Dump contents of local APIC registers
289  */
290 void
291 lapic_dump(const char* str)
292 {
293         uint32_t maxlvt;
294
295         maxlvt = (lapic->version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
296         printf("cpu%d %s:\n", PCPU_GET(cpuid), str);
297         printf("     ID: 0x%08x   VER: 0x%08x LDR: 0x%08x DFR: 0x%08x\n",
298             lapic->id, lapic->version, lapic->ldr, lapic->dfr);
299         printf("  lint0: 0x%08x lint1: 0x%08x TPR: 0x%08x SVR: 0x%08x\n",
300             lapic->lvt_lint0, lapic->lvt_lint1, lapic->tpr, lapic->svr);
301         printf("  timer: 0x%08x therm: 0x%08x err: 0x%08x",
302             lapic->lvt_timer, lapic->lvt_thermal, lapic->lvt_error);
303         if (maxlvt >= LVT_PMC)
304                 printf(" pmc: 0x%08x", lapic->lvt_pcint);
305         printf("\n");
306         if (maxlvt >= LVT_CMCI)
307                 printf("   cmci: 0x%08x\n", lapic->lvt_cmci);
308 }
309
310 void
311 lapic_setup(int boot)
312 {
313         struct lapic *la;
314         u_int32_t maxlvt;
315         register_t saveintr;
316         char buf[MAXCOMLEN + 1];
317
318         la = &lapics[lapic_id()];
319         KASSERT(la->la_present, ("missing APIC structure"));
320         saveintr = intr_disable();
321         maxlvt = (lapic->version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
322
323         /* Initialize the TPR to allow all interrupts. */
324         lapic_set_tpr(0);
325
326         /* Setup spurious vector and enable the local APIC. */
327         lapic_enable();
328
329         /* Program LINT[01] LVT entries. */
330         lapic->lvt_lint0 = lvt_mode(la, LVT_LINT0, lapic->lvt_lint0);
331         lapic->lvt_lint1 = lvt_mode(la, LVT_LINT1, lapic->lvt_lint1);
332
333         /* Program the PMC LVT entry if present. */
334         if (maxlvt >= LVT_PMC)
335                 lapic->lvt_pcint = lvt_mode(la, LVT_PMC, lapic->lvt_pcint);
336
337         /* Program timer LVT and setup handler. */
338         lapic->lvt_timer = lvt_mode(la, LVT_TIMER, lapic->lvt_timer);
339         if (boot) {
340                 snprintf(buf, sizeof(buf), "cpu%d: timer", PCPU_GET(cpuid));
341                 intrcnt_add(buf, &la->la_timer_count);
342         }
343
344         /* We don't setup the timer during boot on the BSP until later. */
345         if (!(boot && PCPU_GET(cpuid) == 0) && lapic_timer_hz != 0) {
346                 KASSERT(lapic_timer_period != 0, ("lapic%u: zero divisor",
347                     lapic_id()));
348                 lapic_timer_set_divisor(lapic_timer_divisor);
349                 lapic_timer_periodic(lapic_timer_period);
350                 lapic_timer_enable_intr();
351         }
352
353         /* Program error LVT and clear any existing errors. */
354         lapic->lvt_error = lvt_mode(la, LVT_ERROR, lapic->lvt_error);
355         lapic->esr = 0;
356
357         /* XXX: Thermal LVT */
358
359         /* Program the CMCI LVT entry if present. */
360         if (maxlvt >= LVT_CMCI)
361                 lapic->lvt_cmci = lvt_mode(la, LVT_CMCI, lapic->lvt_cmci);
362             
363         intr_restore(saveintr);
364 }
365
366 void
367 lapic_reenable_pmc(void)
368 {
369 #ifdef HWPMC_HOOKS
370         uint32_t value;
371
372         value =  lapic->lvt_pcint;
373         value &= ~APIC_LVT_M;
374         lapic->lvt_pcint = value;
375 #endif
376 }
377
378 #ifdef HWPMC_HOOKS
379 static void
380 lapic_update_pmc(void *dummy)
381 {
382         struct lapic *la;
383
384         la = &lapics[lapic_id()];
385         lapic->lvt_pcint = lvt_mode(la, LVT_PMC, lapic->lvt_pcint);
386 }
387 #endif
388
389 int
390 lapic_enable_pmc(void)
391 {
392 #ifdef HWPMC_HOOKS
393         u_int32_t maxlvt;
394
395         /* Fail if the local APIC is not present. */
396         if (lapic == NULL)
397                 return (0);
398
399         /* Fail if the PMC LVT is not present. */
400         maxlvt = (lapic->version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
401         if (maxlvt < LVT_PMC)
402                 return (0);
403
404         lvts[LVT_PMC].lvt_masked = 0;
405
406 #ifdef SMP
407         /*
408          * If hwpmc was loaded at boot time then the APs may not be
409          * started yet.  In that case, don't forward the request to
410          * them as they will program the lvt when they start.
411          */
412         if (smp_started)
413                 smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
414         else
415 #endif
416                 lapic_update_pmc(NULL);
417         return (1);
418 #else
419         return (0);
420 #endif
421 }
422
423 void
424 lapic_disable_pmc(void)
425 {
426 #ifdef HWPMC_HOOKS
427         u_int32_t maxlvt;
428
429         /* Fail if the local APIC is not present. */
430         if (lapic == NULL)
431                 return;
432
433         /* Fail if the PMC LVT is not present. */
434         maxlvt = (lapic->version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
435         if (maxlvt < LVT_PMC)
436                 return;
437
438         lvts[LVT_PMC].lvt_masked = 1;
439
440 #ifdef SMP
441         /* The APs should always be started when hwpmc is unloaded. */
442         KASSERT(mp_ncpus == 1 || smp_started, ("hwpmc unloaded too early"));
443 #endif
444         smp_rendezvous(NULL, lapic_update_pmc, NULL, NULL);
445 #endif
446 }
447
448 /*
449  * Called by cpu_initclocks() on the BSP to setup the local APIC timer so
450  * that it can drive hardclock, statclock, and profclock. 
451  */
452 enum lapic_clock
453 lapic_setup_clock(enum lapic_clock srcsdes)
454 {
455         u_long value;
456         int i;
457
458         /* lapic_setup_clock() should not be called with LAPIC_CLOCK_NONE. */
459         MPASS(srcsdes != LAPIC_CLOCK_NONE);
460
461         /* Can't drive the timer without a local APIC. */
462         if (lapic == NULL ||
463             (resource_int_value("apic", 0, "clock", &i) == 0 && i == 0)) {
464                 clockcoverage = LAPIC_CLOCK_NONE;
465                 return (clockcoverage);
466         }
467
468         /* Start off with a divisor of 2 (power on reset default). */
469         lapic_timer_divisor = 2;
470
471         /* Try to calibrate the local APIC timer. */
472         do {
473                 lapic_timer_set_divisor(lapic_timer_divisor);
474                 lapic_timer_oneshot(APIC_TIMER_MAX_COUNT);
475                 DELAY(2000000);
476                 value = APIC_TIMER_MAX_COUNT - lapic->ccr_timer;
477                 if (value != APIC_TIMER_MAX_COUNT)
478                         break;
479                 lapic_timer_divisor <<= 1;
480         } while (lapic_timer_divisor <= 128);
481         if (lapic_timer_divisor > 128)
482                 panic("lapic: Divisor too big");
483         value /= 2;
484         if (bootverbose)
485                 printf("lapic: Divisor %lu, Frequency %lu Hz\n",
486                     lapic_timer_divisor, value);
487
488         /*
489          * We want to run stathz in the neighborhood of 128hz.  We would
490          * like profhz to run as often as possible, so we let it run on
491          * each clock tick.  We try to honor the requested 'hz' value as
492          * much as possible.
493          *
494          * If 'hz' is above 1500, then we just let the lapic timer
495          * (and profhz) run at hz.  If 'hz' is below 1500 but above
496          * 750, then we let the lapic timer run at 2 * 'hz'.  If 'hz'
497          * is below 750 then we let the lapic timer run at 4 * 'hz'.
498          *
499          * Please note that stathz and profhz are set only if all the
500          * clocks are handled through the local APIC.
501          */
502         if (srcsdes == LAPIC_CLOCK_ALL) {
503                 if (hz >= 1500)
504                         lapic_timer_hz = hz;
505                 else if (hz >= 750)
506                         lapic_timer_hz = hz * 2;
507                 else
508                         lapic_timer_hz = hz * 4;
509         } else
510                 lapic_timer_hz = hz;
511         lapic_timer_period = value / lapic_timer_hz;
512         if (srcsdes == LAPIC_CLOCK_ALL) {
513                 if (lapic_timer_hz < 128)
514                         stathz = lapic_timer_hz;
515                 else
516                         stathz = lapic_timer_hz / (lapic_timer_hz / 128);
517                 profhz = lapic_timer_hz;
518         }
519
520         /*
521          * Start up the timer on the BSP.  The APs will kick off their
522          * timer during lapic_setup().
523          */
524         lapic_timer_periodic(lapic_timer_period);
525         lapic_timer_enable_intr();
526         clockcoverage = srcsdes;
527         return (srcsdes);
528 }
529
530 void
531 lapic_disable(void)
532 {
533         uint32_t value;
534
535         /* Software disable the local APIC. */
536         value = lapic->svr;
537         value &= ~APIC_SVR_SWEN;
538         lapic->svr = value;
539 }
540
541 static void
542 lapic_enable(void)
543 {
544         u_int32_t value;
545
546         /* Program the spurious vector to enable the local APIC. */
547         value = lapic->svr;
548         value &= ~(APIC_SVR_VECTOR | APIC_SVR_FOCUS);
549         value |= (APIC_SVR_FEN | APIC_SVR_SWEN | APIC_SPURIOUS_INT);
550         lapic->svr = value;
551 }
552
553 /* Reset the local APIC on the BSP during resume. */
554 static void
555 lapic_resume(struct pic *pic)
556 {
557
558         lapic_setup(0);
559 }
560
561 int
562 lapic_id(void)
563 {
564
565         KASSERT(lapic != NULL, ("local APIC is not mapped"));
566         return (lapic->id >> APIC_ID_SHIFT);
567 }
568
569 int
570 lapic_intr_pending(u_int vector)
571 {
572         volatile u_int32_t *irr;
573
574         /*
575          * The IRR registers are an array of 128-bit registers each of
576          * which only describes 32 interrupts in the low 32 bits..  Thus,
577          * we divide the vector by 32 to get the 128-bit index.  We then
578          * multiply that index by 4 to get the equivalent index from
579          * treating the IRR as an array of 32-bit registers.  Finally, we
580          * modulus the vector by 32 to determine the individual bit to
581          * test.
582          */
583         irr = &lapic->irr0;
584         return (irr[(vector / 32) * 4] & 1 << (vector % 32));
585 }
586
587 void
588 lapic_set_logical_id(u_int apic_id, u_int cluster, u_int cluster_id)
589 {
590         struct lapic *la;
591
592         KASSERT(lapics[apic_id].la_present, ("%s: APIC %u doesn't exist",
593             __func__, apic_id));
594         KASSERT(cluster <= APIC_MAX_CLUSTER, ("%s: cluster %u too big",
595             __func__, cluster));
596         KASSERT(cluster_id <= APIC_MAX_INTRACLUSTER_ID,
597             ("%s: intra cluster id %u too big", __func__, cluster_id));
598         la = &lapics[apic_id];
599         la->la_cluster = cluster;
600         la->la_cluster_id = cluster_id;
601 }
602
603 int
604 lapic_set_lvt_mask(u_int apic_id, u_int pin, u_char masked)
605 {
606
607         if (pin > LVT_MAX)
608                 return (EINVAL);
609         if (apic_id == APIC_ID_ALL) {
610                 lvts[pin].lvt_masked = masked;
611                 if (bootverbose)
612                         printf("lapic:");
613         } else {
614                 KASSERT(lapics[apic_id].la_present,
615                     ("%s: missing APIC %u", __func__, apic_id));
616                 lapics[apic_id].la_lvts[pin].lvt_masked = masked;
617                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
618                 if (bootverbose)
619                         printf("lapic%u:", apic_id);
620         }
621         if (bootverbose)
622                 printf(" LINT%u %s\n", pin, masked ? "masked" : "unmasked");
623         return (0);
624 }
625
626 int
627 lapic_set_lvt_mode(u_int apic_id, u_int pin, u_int32_t mode)
628 {
629         struct lvt *lvt;
630
631         if (pin > LVT_MAX)
632                 return (EINVAL);
633         if (apic_id == APIC_ID_ALL) {
634                 lvt = &lvts[pin];
635                 if (bootverbose)
636                         printf("lapic:");
637         } else {
638                 KASSERT(lapics[apic_id].la_present,
639                     ("%s: missing APIC %u", __func__, apic_id));
640                 lvt = &lapics[apic_id].la_lvts[pin];
641                 lvt->lvt_active = 1;
642                 if (bootverbose)
643                         printf("lapic%u:", apic_id);
644         }
645         lvt->lvt_mode = mode;
646         switch (mode) {
647         case APIC_LVT_DM_NMI:
648         case APIC_LVT_DM_SMI:
649         case APIC_LVT_DM_INIT:
650         case APIC_LVT_DM_EXTINT:
651                 lvt->lvt_edgetrigger = 1;
652                 lvt->lvt_activehi = 1;
653                 if (mode == APIC_LVT_DM_EXTINT)
654                         lvt->lvt_masked = 1;
655                 else
656                         lvt->lvt_masked = 0;
657                 break;
658         default:
659                 panic("Unsupported delivery mode: 0x%x\n", mode);
660         }
661         if (bootverbose) {
662                 printf(" Routing ");
663                 switch (mode) {
664                 case APIC_LVT_DM_NMI:
665                         printf("NMI");
666                         break;
667                 case APIC_LVT_DM_SMI:
668                         printf("SMI");
669                         break;
670                 case APIC_LVT_DM_INIT:
671                         printf("INIT");
672                         break;
673                 case APIC_LVT_DM_EXTINT:
674                         printf("ExtINT");
675                         break;
676                 }
677                 printf(" -> LINT%u\n", pin);
678         }
679         return (0);
680 }
681
682 int
683 lapic_set_lvt_polarity(u_int apic_id, u_int pin, enum intr_polarity pol)
684 {
685
686         if (pin > LVT_MAX || pol == INTR_POLARITY_CONFORM)
687                 return (EINVAL);
688         if (apic_id == APIC_ID_ALL) {
689                 lvts[pin].lvt_activehi = (pol == INTR_POLARITY_HIGH);
690                 if (bootverbose)
691                         printf("lapic:");
692         } else {
693                 KASSERT(lapics[apic_id].la_present,
694                     ("%s: missing APIC %u", __func__, apic_id));
695                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
696                 lapics[apic_id].la_lvts[pin].lvt_activehi =
697                     (pol == INTR_POLARITY_HIGH);
698                 if (bootverbose)
699                         printf("lapic%u:", apic_id);
700         }
701         if (bootverbose)
702                 printf(" LINT%u polarity: %s\n", pin,
703                     pol == INTR_POLARITY_HIGH ? "high" : "low");
704         return (0);
705 }
706
707 int
708 lapic_set_lvt_triggermode(u_int apic_id, u_int pin, enum intr_trigger trigger)
709 {
710
711         if (pin > LVT_MAX || trigger == INTR_TRIGGER_CONFORM)
712                 return (EINVAL);
713         if (apic_id == APIC_ID_ALL) {
714                 lvts[pin].lvt_edgetrigger = (trigger == INTR_TRIGGER_EDGE);
715                 if (bootverbose)
716                         printf("lapic:");
717         } else {
718                 KASSERT(lapics[apic_id].la_present,
719                     ("%s: missing APIC %u", __func__, apic_id));
720                 lapics[apic_id].la_lvts[pin].lvt_edgetrigger =
721                     (trigger == INTR_TRIGGER_EDGE);
722                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
723                 if (bootverbose)
724                         printf("lapic%u:", apic_id);
725         }
726         if (bootverbose)
727                 printf(" LINT%u trigger: %s\n", pin,
728                     trigger == INTR_TRIGGER_EDGE ? "edge" : "level");
729         return (0);
730 }
731
732 /*
733  * Adjust the TPR of the current CPU so that it blocks all interrupts below
734  * the passed in vector.
735  */
736 void
737 lapic_set_tpr(u_int vector)
738 {
739 #ifdef CHEAP_TPR
740         lapic->tpr = vector;
741 #else
742         u_int32_t tpr;
743
744         tpr = lapic->tpr & ~APIC_TPR_PRIO;
745         tpr |= vector;
746         lapic->tpr = tpr;
747 #endif
748 }
749
750 void
751 lapic_eoi(void)
752 {
753
754         lapic->eoi = 0;
755 }
756
757 void
758 lapic_handle_intr(int vector, struct trapframe *frame)
759 {
760         struct intsrc *isrc;
761
762         if (vector == -1)
763                 panic("Couldn't get vector from ISR!");
764         isrc = intr_lookup_source(apic_idt_to_irq(PCPU_GET(apic_id),
765             vector));
766         intr_execute_handlers(isrc, frame);
767 }
768
769 void
770 lapic_handle_timer(struct trapframe *frame)
771 {
772         struct lapic *la;
773
774         /* Send EOI first thing. */
775         lapic_eoi();
776
777 #if defined(SMP) && !defined(SCHED_ULE)
778         /*
779          * Don't do any accounting for the disabled HTT cores, since it
780          * will provide misleading numbers for the userland.
781          *
782          * No locking is necessary here, since even if we loose the race
783          * when hlt_cpus_mask changes it is not a big deal, really.
784          *
785          * Don't do that for ULE, since ULE doesn't consider hlt_cpus_mask
786          * and unlike other schedulers it actually schedules threads to
787          * those CPUs.
788          */
789         if ((hlt_cpus_mask & (1 << PCPU_GET(cpuid))) != 0)
790                 return;
791 #endif
792
793         /* Look up our local APIC structure for the tick counters. */
794         la = &lapics[PCPU_GET(apic_id)];
795         (*la->la_timer_count)++;
796         critical_enter();
797
798 #ifdef KDTRACE_HOOKS
799         /*
800          * If the DTrace hooks are configured and a callback function
801          * has been registered, then call it to process the high speed
802          * timers.
803          */
804         int cpu = PCPU_GET(cpuid);
805         if (cyclic_clock_func[cpu] != NULL)
806                 (*cyclic_clock_func[cpu])(frame);
807 #endif
808
809         /* Fire hardclock at hz. */
810         la->la_hard_ticks += hz;
811         if (la->la_hard_ticks >= lapic_timer_hz) {
812                 la->la_hard_ticks -= lapic_timer_hz;
813                 if (PCPU_GET(cpuid) == 0)
814                         hardclock(TRAPF_USERMODE(frame), TRAPF_PC(frame));
815                 else
816                         hardclock_cpu(TRAPF_USERMODE(frame));
817         }
818         if (clockcoverage == LAPIC_CLOCK_ALL) {
819
820                 /* Fire statclock at stathz. */
821                 la->la_stat_ticks += stathz;
822                 if (la->la_stat_ticks >= lapic_timer_hz) {
823                         la->la_stat_ticks -= lapic_timer_hz;
824                         statclock(TRAPF_USERMODE(frame));
825                 }
826
827                 /* Fire profclock at profhz, but only when needed. */
828                 la->la_prof_ticks += profhz;
829                 if (la->la_prof_ticks >= lapic_timer_hz) {
830                         la->la_prof_ticks -= lapic_timer_hz;
831                         if (profprocs != 0)
832                                 profclock(TRAPF_USERMODE(frame),
833                                     TRAPF_PC(frame));
834                 }
835         }
836         critical_exit();
837 }
838
839 static void
840 lapic_timer_set_divisor(u_int divisor)
841 {
842
843         KASSERT(powerof2(divisor), ("lapic: invalid divisor %u", divisor));
844         KASSERT(ffs(divisor) <= sizeof(lapic_timer_divisors) /
845             sizeof(u_int32_t), ("lapic: invalid divisor %u", divisor));
846         lapic->dcr_timer = lapic_timer_divisors[ffs(divisor) - 1];
847 }
848
849 static void
850 lapic_timer_oneshot(u_int count)
851 {
852         u_int32_t value;
853
854         value = lapic->lvt_timer;
855         value &= ~APIC_LVTT_TM;
856         value |= APIC_LVTT_TM_ONE_SHOT;
857         lapic->lvt_timer = value;
858         lapic->icr_timer = count;
859 }
860
861 static void
862 lapic_timer_periodic(u_int count)
863 {
864         u_int32_t value;
865
866         value = lapic->lvt_timer;
867         value &= ~APIC_LVTT_TM;
868         value |= APIC_LVTT_TM_PERIODIC;
869         lapic->lvt_timer = value;
870         lapic->icr_timer = count;
871 }
872
873 static void
874 lapic_timer_enable_intr(void)
875 {
876         u_int32_t value;
877
878         value = lapic->lvt_timer;
879         value &= ~APIC_LVT_M;
880         lapic->lvt_timer = value;
881 }
882
883 void
884 lapic_handle_cmc(void)
885 {
886
887         lapic_eoi();
888         cmc_intr();
889 }
890
891 /*
892  * Called from the mca_init() to activate the CMC interrupt if this CPU is
893  * responsible for monitoring any MC banks for CMC events.  Since mca_init()
894  * is called prior to lapic_setup() during boot, this just needs to unmask
895  * this CPU's LVT_CMCI entry.
896  */
897 void
898 lapic_enable_cmc(void)
899 {
900         u_int apic_id;
901
902         apic_id = PCPU_GET(apic_id);
903         KASSERT(lapics[apic_id].la_present,
904             ("%s: missing APIC %u", __func__, apic_id));
905         lapics[apic_id].la_lvts[LVT_CMCI].lvt_masked = 0;
906         lapics[apic_id].la_lvts[LVT_CMCI].lvt_active = 1;
907         if (bootverbose)
908                 printf("lapic%u: CMCI unmasked\n", apic_id);
909 }
910
911 void
912 lapic_handle_error(void)
913 {
914         u_int32_t esr;
915
916         /*
917          * Read the contents of the error status register.  Write to
918          * the register first before reading from it to force the APIC
919          * to update its value to indicate any errors that have
920          * occurred since the previous write to the register.
921          */
922         lapic->esr = 0;
923         esr = lapic->esr;
924
925         printf("CPU%d: local APIC error 0x%x\n", PCPU_GET(cpuid), esr);
926         lapic_eoi();
927 }
928
929 u_int
930 apic_cpuid(u_int apic_id)
931 {
932 #ifdef SMP
933         return apic_cpuids[apic_id];
934 #else
935         return 0;
936 #endif
937 }
938
939 /* Request a free IDT vector to be used by the specified IRQ. */
940 u_int
941 apic_alloc_vector(u_int apic_id, u_int irq)
942 {
943         u_int vector;
944
945         KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
946
947         /*
948          * Search for a free vector.  Currently we just use a very simple
949          * algorithm to find the first free vector.
950          */
951         mtx_lock_spin(&icu_lock);
952         for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
953                 if (lapics[apic_id].la_ioint_irqs[vector] != -1)
954                         continue;
955                 lapics[apic_id].la_ioint_irqs[vector] = irq;
956                 mtx_unlock_spin(&icu_lock);
957                 return (vector + APIC_IO_INTS);
958         }
959         mtx_unlock_spin(&icu_lock);
960         return (0);
961 }
962
963 /*
964  * Request 'count' free contiguous IDT vectors to be used by 'count'
965  * IRQs.  'count' must be a power of two and the vectors will be
966  * aligned on a boundary of 'align'.  If the request cannot be
967  * satisfied, 0 is returned.
968  */
969 u_int
970 apic_alloc_vectors(u_int apic_id, u_int *irqs, u_int count, u_int align)
971 {
972         u_int first, run, vector;
973
974         KASSERT(powerof2(count), ("bad count"));
975         KASSERT(powerof2(align), ("bad align"));
976         KASSERT(align >= count, ("align < count"));
977 #ifdef INVARIANTS
978         for (run = 0; run < count; run++)
979                 KASSERT(irqs[run] < NUM_IO_INTS, ("Invalid IRQ %u at index %u",
980                     irqs[run], run));
981 #endif
982
983         /*
984          * Search for 'count' free vectors.  As with apic_alloc_vector(),
985          * this just uses a simple first fit algorithm.
986          */
987         run = 0;
988         first = 0;
989         mtx_lock_spin(&icu_lock);
990         for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
991
992                 /* Vector is in use, end run. */
993                 if (lapics[apic_id].la_ioint_irqs[vector] != -1) {
994                         run = 0;
995                         first = 0;
996                         continue;
997                 }
998
999                 /* Start a new run if run == 0 and vector is aligned. */
1000                 if (run == 0) {
1001                         if ((vector & (align - 1)) != 0)
1002                                 continue;
1003                         first = vector;
1004                 }
1005                 run++;
1006
1007                 /* Keep looping if the run isn't long enough yet. */
1008                 if (run < count)
1009                         continue;
1010
1011                 /* Found a run, assign IRQs and return the first vector. */
1012                 for (vector = 0; vector < count; vector++)
1013                         lapics[apic_id].la_ioint_irqs[first + vector] =
1014                             irqs[vector];
1015                 mtx_unlock_spin(&icu_lock);
1016                 return (first + APIC_IO_INTS);
1017         }
1018         mtx_unlock_spin(&icu_lock);
1019         printf("APIC: Couldn't find APIC vectors for %u IRQs\n", count);
1020         return (0);
1021 }
1022
1023 /*
1024  * Enable a vector for a particular apic_id.  Since all lapics share idt
1025  * entries and ioint_handlers this enables the vector on all lapics.  lapics
1026  * which do not have the vector configured would report spurious interrupts
1027  * should it fire.
1028  */
1029 void
1030 apic_enable_vector(u_int apic_id, u_int vector)
1031 {
1032
1033         KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1034         KASSERT(ioint_handlers[vector / 32] != NULL,
1035             ("No ISR handler for vector %u", vector));
1036         setidt(vector, ioint_handlers[vector / 32], SDT_APIC, SEL_KPL,
1037             GSEL_APIC);
1038 }
1039
1040 void
1041 apic_disable_vector(u_int apic_id, u_int vector)
1042 {
1043
1044         KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
1045         KASSERT(ioint_handlers[vector / 32] != NULL,
1046             ("No ISR handler for vector %u", vector));
1047 #ifdef notyet
1048         /*
1049          * We can not currently clear the idt entry because other cpus
1050          * may have a valid vector at this offset.
1051          */
1052         setidt(vector, &IDTVEC(rsvd), SDT_APICT, SEL_KPL, GSEL_APIC);
1053 #endif
1054 }
1055
1056 /* Release an APIC vector when it's no longer in use. */
1057 void
1058 apic_free_vector(u_int apic_id, u_int vector, u_int irq)
1059 {
1060         struct thread *td;
1061
1062         KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1063             vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1064             ("Vector %u does not map to an IRQ line", vector));
1065         KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
1066         KASSERT(lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] ==
1067             irq, ("IRQ mismatch"));
1068
1069         /*
1070          * Bind us to the cpu that owned the vector before freeing it so
1071          * we don't lose an interrupt delivery race.
1072          */
1073         td = curthread;
1074         if (!rebooting) {
1075                 thread_lock(td);
1076                 if (sched_is_bound(td))
1077                         panic("apic_free_vector: Thread already bound.\n");
1078                 sched_bind(td, apic_cpuid(apic_id));
1079                 thread_unlock(td);
1080         }
1081         mtx_lock_spin(&icu_lock);
1082         lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS] = -1;
1083         mtx_unlock_spin(&icu_lock);
1084         if (!rebooting) {
1085                 thread_lock(td);
1086                 sched_unbind(td);
1087                 thread_unlock(td);
1088         }
1089 }
1090
1091 /* Map an IDT vector (APIC) to an IRQ (interrupt source). */
1092 u_int
1093 apic_idt_to_irq(u_int apic_id, u_int vector)
1094 {
1095         int irq;
1096
1097         KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
1098             vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
1099             ("Vector %u does not map to an IRQ line", vector));
1100         irq = lapics[apic_id].la_ioint_irqs[vector - APIC_IO_INTS];
1101         if (irq < 0)
1102                 irq = 0;
1103         return (irq);
1104 }
1105
1106 #ifdef DDB
1107 /*
1108  * Dump data about APIC IDT vector mappings.
1109  */
1110 DB_SHOW_COMMAND(apic, db_show_apic)
1111 {
1112         struct intsrc *isrc;
1113         int i, verbose;
1114         u_int apic_id;
1115         u_int irq;
1116
1117         if (strcmp(modif, "vv") == 0)
1118                 verbose = 2;
1119         else if (strcmp(modif, "v") == 0)
1120                 verbose = 1;
1121         else
1122                 verbose = 0;
1123         for (apic_id = 0; apic_id <= MAX_APIC_ID; apic_id++) {
1124                 if (lapics[apic_id].la_present == 0)
1125                         continue;
1126                 db_printf("Interrupts bound to lapic %u\n", apic_id);
1127                 for (i = 0; i < APIC_NUM_IOINTS + 1 && !db_pager_quit; i++) {
1128                         irq = lapics[apic_id].la_ioint_irqs[i];
1129                         if (irq == -1 || irq == IRQ_SYSCALL)
1130                                 continue;
1131                         db_printf("vec 0x%2x -> ", i + APIC_IO_INTS);
1132                         if (irq == IRQ_TIMER)
1133                                 db_printf("lapic timer\n");
1134                         else if (irq < NUM_IO_INTS) {
1135                                 isrc = intr_lookup_source(irq);
1136                                 if (isrc == NULL || verbose == 0)
1137                                         db_printf("IRQ %u\n", irq);
1138                                 else
1139                                         db_dump_intr_event(isrc->is_event,
1140                                             verbose == 2);
1141                         } else
1142                                 db_printf("IRQ %u ???\n", irq);
1143                 }
1144         }
1145 }
1146
1147 static void
1148 dump_mask(const char *prefix, uint32_t v, int base)
1149 {
1150         int i, first;
1151
1152         first = 1;
1153         for (i = 0; i < 32; i++)
1154                 if (v & (1 << i)) {
1155                         if (first) {
1156                                 db_printf("%s:", prefix);
1157                                 first = 0;
1158                         }
1159                         db_printf(" %02x", base + i);
1160                 }
1161         if (!first)
1162                 db_printf("\n");
1163 }
1164
1165 /* Show info from the lapic regs for this CPU. */
1166 DB_SHOW_COMMAND(lapic, db_show_lapic)
1167 {
1168         uint32_t v;
1169
1170         db_printf("lapic ID = %d\n", lapic_id());
1171         v = lapic->version;
1172         db_printf("version  = %d.%d\n", (v & APIC_VER_VERSION) >> 4,
1173             v & 0xf);
1174         db_printf("max LVT  = %d\n", (v & APIC_VER_MAXLVT) >> MAXLVTSHIFT);
1175         v = lapic->svr;
1176         db_printf("SVR      = %02x (%s)\n", v & APIC_SVR_VECTOR,
1177             v & APIC_SVR_ENABLE ? "enabled" : "disabled");
1178         db_printf("TPR      = %02x\n", lapic->tpr);
1179
1180 #define dump_field(prefix, index)                                       \
1181         dump_mask(__XSTRING(prefix ## index), lapic->prefix ## index,   \
1182             index * 32)
1183
1184         db_printf("In-service Interrupts:\n");
1185         dump_field(isr, 0);
1186         dump_field(isr, 1);
1187         dump_field(isr, 2);
1188         dump_field(isr, 3);
1189         dump_field(isr, 4);
1190         dump_field(isr, 5);
1191         dump_field(isr, 6);
1192         dump_field(isr, 7);
1193
1194         db_printf("TMR Interrupts:\n");
1195         dump_field(tmr, 0);
1196         dump_field(tmr, 1);
1197         dump_field(tmr, 2);
1198         dump_field(tmr, 3);
1199         dump_field(tmr, 4);
1200         dump_field(tmr, 5);
1201         dump_field(tmr, 6);
1202         dump_field(tmr, 7);
1203
1204         db_printf("IRR Interrupts:\n");
1205         dump_field(irr, 0);
1206         dump_field(irr, 1);
1207         dump_field(irr, 2);
1208         dump_field(irr, 3);
1209         dump_field(irr, 4);
1210         dump_field(irr, 5);
1211         dump_field(irr, 6);
1212         dump_field(irr, 7);
1213
1214 #undef dump_field
1215 }
1216 #endif
1217
1218 /*
1219  * APIC probing support code.  This includes code to manage enumerators.
1220  */
1221
1222 static SLIST_HEAD(, apic_enumerator) enumerators =
1223         SLIST_HEAD_INITIALIZER(enumerators);
1224 static struct apic_enumerator *best_enum;
1225
1226 void
1227 apic_register_enumerator(struct apic_enumerator *enumerator)
1228 {
1229 #ifdef INVARIANTS
1230         struct apic_enumerator *apic_enum;
1231
1232         SLIST_FOREACH(apic_enum, &enumerators, apic_next) {
1233                 if (apic_enum == enumerator)
1234                         panic("%s: Duplicate register of %s", __func__,
1235                             enumerator->apic_name);
1236         }
1237 #endif
1238         SLIST_INSERT_HEAD(&enumerators, enumerator, apic_next);
1239 }
1240
1241 /*
1242  * We have to look for CPU's very, very early because certain subsystems
1243  * want to know how many CPU's we have extremely early on in the boot
1244  * process.
1245  */
1246 static void
1247 apic_init(void *dummy __unused)
1248 {
1249         struct apic_enumerator *enumerator;
1250 #ifndef __amd64__
1251         uint64_t apic_base;
1252 #endif
1253         int retval, best;
1254
1255         /* We only support built in local APICs. */
1256         if (!(cpu_feature & CPUID_APIC))
1257                 return;
1258
1259         /* Don't probe if APIC mode is disabled. */
1260         if (resource_disabled("apic", 0))
1261                 return;
1262
1263         /* First, probe all the enumerators to find the best match. */
1264         best_enum = NULL;
1265         best = 0;
1266         SLIST_FOREACH(enumerator, &enumerators, apic_next) {
1267                 retval = enumerator->apic_probe();
1268                 if (retval > 0)
1269                         continue;
1270                 if (best_enum == NULL || best < retval) {
1271                         best_enum = enumerator;
1272                         best = retval;
1273                 }
1274         }
1275         if (best_enum == NULL) {
1276                 if (bootverbose)
1277                         printf("APIC: Could not find any APICs.\n");
1278                 return;
1279         }
1280
1281         if (bootverbose)
1282                 printf("APIC: Using the %s enumerator.\n",
1283                     best_enum->apic_name);
1284
1285 #ifndef __amd64__
1286         /*
1287          * To work around an errata, we disable the local APIC on some
1288          * CPUs during early startup.  We need to turn the local APIC back
1289          * on on such CPUs now.
1290          */
1291         if (cpu == CPU_686 && cpu_vendor_id == CPU_VENDOR_INTEL &&
1292             (cpu_id & 0xff0) == 0x610) {
1293                 apic_base = rdmsr(MSR_APICBASE);
1294                 apic_base |= APICBASE_ENABLED;
1295                 wrmsr(MSR_APICBASE, apic_base);
1296         }
1297 #endif
1298
1299         /* Second, probe the CPU's in the system. */
1300         retval = best_enum->apic_probe_cpus();
1301         if (retval != 0)
1302                 printf("%s: Failed to probe CPUs: returned %d\n",
1303                     best_enum->apic_name, retval);
1304
1305 #ifdef __amd64__
1306 }
1307 SYSINIT(apic_init, SI_SUB_TUNABLES - 1, SI_ORDER_SECOND, apic_init, NULL);
1308
1309 /*
1310  * Setup the local APIC.  We have to do this prior to starting up the APs
1311  * in the SMP case.
1312  */
1313 static void
1314 apic_setup_local(void *dummy __unused)
1315 {
1316         int retval;
1317  
1318         if (best_enum == NULL)
1319                 return;
1320 #endif
1321         /* Third, initialize the local APIC. */
1322         retval = best_enum->apic_setup_local();
1323         if (retval != 0)
1324                 printf("%s: Failed to setup the local APIC: returned %d\n",
1325                     best_enum->apic_name, retval);
1326 }
1327 #ifdef __amd64__
1328 SYSINIT(apic_setup_local, SI_SUB_CPU, SI_ORDER_SECOND, apic_setup_local,
1329     NULL);
1330 #else
1331 SYSINIT(apic_init, SI_SUB_CPU, SI_ORDER_SECOND, apic_init, NULL);
1332 #endif
1333
1334 /*
1335  * Setup the I/O APICs.
1336  */
1337 static void
1338 apic_setup_io(void *dummy __unused)
1339 {
1340         int retval;
1341
1342         if (best_enum == NULL)
1343                 return;
1344         retval = best_enum->apic_setup_io();
1345         if (retval != 0)
1346                 printf("%s: Failed to setup I/O APICs: returned %d\n",
1347                     best_enum->apic_name, retval);
1348
1349 #ifdef XEN
1350         return;
1351 #endif
1352         /*
1353          * Finish setting up the local APIC on the BSP once we know how to
1354          * properly program the LINT pins.
1355          */
1356         lapic_setup(1);
1357         intr_register_pic(&lapic_pic);
1358         if (bootverbose)
1359                 lapic_dump("BSP");
1360
1361         /* Enable the MSI "pic". */
1362         msi_init();
1363 }
1364 SYSINIT(apic_setup_io, SI_SUB_INTR, SI_ORDER_SECOND, apic_setup_io, NULL);
1365
1366 #ifdef SMP
1367 /*
1368  * Inter Processor Interrupt functions.  The lapic_ipi_*() functions are
1369  * private to the MD code.  The public interface for the rest of the
1370  * kernel is defined in mp_machdep.c.
1371  */
1372 int
1373 lapic_ipi_wait(int delay)
1374 {
1375         int x, incr;
1376
1377         /*
1378          * Wait delay loops for IPI to be sent.  This is highly bogus
1379          * since this is sensitive to CPU clock speed.  If delay is
1380          * -1, we wait forever.
1381          */
1382         if (delay == -1) {
1383                 incr = 0;
1384                 delay = 1;
1385         } else
1386                 incr = 1;
1387         for (x = 0; x < delay; x += incr) {
1388                 if ((lapic->icr_lo & APIC_DELSTAT_MASK) == APIC_DELSTAT_IDLE)
1389                         return (1);
1390                 ia32_pause();
1391         }
1392         return (0);
1393 }
1394
1395 void
1396 lapic_ipi_raw(register_t icrlo, u_int dest)
1397 {
1398         register_t value, saveintr;
1399
1400         /* XXX: Need more sanity checking of icrlo? */
1401         KASSERT(lapic != NULL, ("%s called too early", __func__));
1402         KASSERT((dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
1403             ("%s: invalid dest field", __func__));
1404         KASSERT((icrlo & APIC_ICRLO_RESV_MASK) == 0,
1405             ("%s: reserved bits set in ICR LO register", __func__));
1406
1407         /* Set destination in ICR HI register if it is being used. */
1408         saveintr = intr_disable();
1409         if ((icrlo & APIC_DEST_MASK) == APIC_DEST_DESTFLD) {
1410                 value = lapic->icr_hi;
1411                 value &= ~APIC_ID_MASK;
1412                 value |= dest << APIC_ID_SHIFT;
1413                 lapic->icr_hi = value;
1414         }
1415
1416         /* Program the contents of the IPI and dispatch it. */
1417         value = lapic->icr_lo;
1418         value &= APIC_ICRLO_RESV_MASK;
1419         value |= icrlo;
1420         lapic->icr_lo = value;
1421         intr_restore(saveintr);
1422 }
1423
1424 #define BEFORE_SPIN     1000000
1425 #ifdef DETECT_DEADLOCK
1426 #define AFTER_SPIN      1000
1427 #endif
1428
1429 void
1430 lapic_ipi_vectored(u_int vector, int dest)
1431 {
1432         register_t icrlo, destfield;
1433
1434         KASSERT((vector & ~APIC_VECTOR_MASK) == 0,
1435             ("%s: invalid vector %d", __func__, vector));
1436
1437         icrlo = APIC_DESTMODE_PHY | APIC_TRIGMOD_EDGE;
1438
1439         /*
1440          * IPI_STOP_HARD is just a "fake" vector used to send a NMI.
1441          * Use special rules regard NMI if passed, otherwise specify
1442          * the vector.
1443          */
1444         if (vector == IPI_STOP_HARD)
1445                 icrlo |= APIC_DELMODE_NMI | APIC_LEVEL_ASSERT;
1446         else
1447                 icrlo |= vector | APIC_DELMODE_FIXED | APIC_LEVEL_DEASSERT;
1448         destfield = 0;
1449         switch (dest) {
1450         case APIC_IPI_DEST_SELF:
1451                 icrlo |= APIC_DEST_SELF;
1452                 break;
1453         case APIC_IPI_DEST_ALL:
1454                 icrlo |= APIC_DEST_ALLISELF;
1455                 break;
1456         case APIC_IPI_DEST_OTHERS:
1457                 icrlo |= APIC_DEST_ALLESELF;
1458                 break;
1459         default:
1460                 KASSERT((dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
1461                     ("%s: invalid destination 0x%x", __func__, dest));
1462                 destfield = dest;
1463         }
1464
1465         /* Wait for an earlier IPI to finish. */
1466         if (!lapic_ipi_wait(BEFORE_SPIN)) {
1467                 if (panicstr != NULL)
1468                         return;
1469                 else
1470                         panic("APIC: Previous IPI is stuck");
1471         }
1472
1473         lapic_ipi_raw(icrlo, destfield);
1474
1475 #ifdef DETECT_DEADLOCK
1476         /* Wait for IPI to be delivered. */
1477         if (!lapic_ipi_wait(AFTER_SPIN)) {
1478 #ifdef needsattention
1479                 /*
1480                  * XXX FIXME:
1481                  *
1482                  * The above function waits for the message to actually be
1483                  * delivered.  It breaks out after an arbitrary timeout
1484                  * since the message should eventually be delivered (at
1485                  * least in theory) and that if it wasn't we would catch
1486                  * the failure with the check above when the next IPI is
1487                  * sent.
1488                  *
1489                  * We could skip this wait entirely, EXCEPT it probably
1490                  * protects us from other routines that assume that the
1491                  * message was delivered and acted upon when this function
1492                  * returns.
1493                  */
1494                 printf("APIC: IPI might be stuck\n");
1495 #else /* !needsattention */
1496                 /* Wait until mesage is sent without a timeout. */
1497                 while (lapic->icr_lo & APIC_DELSTAT_PEND)
1498                         ia32_pause();
1499 #endif /* needsattention */
1500         }
1501 #endif /* DETECT_DEADLOCK */
1502 }
1503 #endif /* SMP */