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