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