]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/local_apic.c
Revert previous commit. The BIOS braindamage is even worse than I
[FreeBSD/FreeBSD.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
39 #include "opt_ddb.h"
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/bus.h>
44 #include <sys/kernel.h>
45 #include <sys/lock.h>
46 #include <sys/mutex.h>
47 #include <sys/pcpu.h>
48 #include <sys/smp.h>
49
50 #include <vm/vm.h>
51 #include <vm/pmap.h>
52
53 #include <machine/apicreg.h>
54 #include <machine/cputypes.h>
55 #include <machine/frame.h>
56 #include <machine/intr_machdep.h>
57 #include <machine/apicvar.h>
58 #include <machine/md_var.h>
59 #include <machine/smp.h>
60 #include <machine/specialreg.h>
61
62 #ifdef DDB
63 #include <sys/interrupt.h>
64 #include <ddb/ddb.h>
65 #endif
66
67 /*
68  * We can handle up to 60 APICs via our logical cluster IDs, but currently
69  * the physical IDs on Intel processors up to the Pentium 4 are limited to
70  * 16.
71  */
72 #define MAX_APICID      16
73
74 /* Sanity checks on IDT vectors. */
75 CTASSERT(APIC_IO_INTS + APIC_NUM_IOINTS == APIC_TIMER_INT);
76 CTASSERT(APIC_TIMER_INT < APIC_LOCAL_INTS);
77 CTASSERT(APIC_LOCAL_INTS == 240);
78 CTASSERT(IPI_STOP < APIC_SPURIOUS_INT);
79
80 #define LAPIC_TIMER_HZ_DIVIDER          2
81 #define LAPIC_TIMER_STATHZ_DIVIDER      15
82 #define LAPIC_TIMER_PROFHZ_DIVIDER      3
83
84 /* Magic IRQ values for the timer and syscalls. */
85 #define IRQ_TIMER       (NUM_IO_INTS + 1)
86 #define IRQ_SYSCALL     (NUM_IO_INTS + 2)
87
88 /*
89  * Support for local APICs.  Local APICs manage interrupts on each
90  * individual processor as opposed to I/O APICs which receive interrupts
91  * from I/O devices and then forward them on to the local APICs.
92  *
93  * Local APICs can also send interrupts to each other thus providing the
94  * mechanism for IPIs.
95  */
96
97 struct lvt {
98         u_int lvt_edgetrigger:1;
99         u_int lvt_activehi:1;
100         u_int lvt_masked:1;
101         u_int lvt_active:1;
102         u_int lvt_mode:16;
103         u_int lvt_vector:8;
104 };
105
106 struct lapic {
107         struct lvt la_lvts[LVT_MAX + 1];
108         u_int la_id:8;
109         u_int la_cluster:4;
110         u_int la_cluster_id:2;
111         u_int la_present:1;
112         u_long *la_timer_count;
113         u_long la_hard_ticks;
114         u_long la_stat_ticks;
115         u_long la_prof_ticks;
116 } static lapics[MAX_APICID];
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, 0, 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 /* Include IDT_SYSCALL to make indexing easier. */
142 static u_int ioint_irqs[APIC_NUM_IOINTS + 1];
143
144 static u_int32_t lapic_timer_divisors[] = { 
145         APIC_TDCR_1, APIC_TDCR_2, APIC_TDCR_4, APIC_TDCR_8, APIC_TDCR_16,
146         APIC_TDCR_32, APIC_TDCR_64, APIC_TDCR_128
147 };
148
149 volatile lapic_t *lapic;
150 static u_long lapic_timer_divisor, lapic_timer_period, lapic_timer_hz;
151
152 static void     lapic_enable(void);
153 static void     lapic_timer_enable_intr(void);
154 static void     lapic_timer_oneshot(u_int count);
155 static void     lapic_timer_periodic(u_int count);
156 static void     lapic_timer_set_divisor(u_int divisor);
157 static uint32_t lvt_mode(struct lapic *la, u_int pin, uint32_t value);
158
159 static uint32_t
160 lvt_mode(struct lapic *la, u_int pin, uint32_t value)
161 {
162         struct lvt *lvt;
163
164         KASSERT(pin <= LVT_MAX, ("%s: pin %u out of range", __func__, pin));
165         if (la->la_lvts[pin].lvt_active)
166                 lvt = &la->la_lvts[pin];
167         else
168                 lvt = &lvts[pin];
169
170         value &= ~(APIC_LVT_M | APIC_LVT_TM | APIC_LVT_IIPP | APIC_LVT_DM |
171             APIC_LVT_VECTOR);
172         if (lvt->lvt_edgetrigger == 0)
173                 value |= APIC_LVT_TM;
174         if (lvt->lvt_activehi == 0)
175                 value |= APIC_LVT_IIPP_INTALO;
176         if (lvt->lvt_masked)
177                 value |= APIC_LVT_M;
178         value |= lvt->lvt_mode;
179         switch (lvt->lvt_mode) {
180         case APIC_LVT_DM_NMI:
181         case APIC_LVT_DM_SMI:
182         case APIC_LVT_DM_INIT:
183         case APIC_LVT_DM_EXTINT:
184                 if (!lvt->lvt_edgetrigger) {
185                         printf("lapic%u: Forcing LINT%u to edge trigger\n",
186                             la->la_id, pin);
187                         value |= APIC_LVT_TM;
188                 }
189                 /* Use a vector of 0. */
190                 break;
191         case APIC_LVT_DM_FIXED:
192                 value |= lvt->lvt_vector;
193                 break;
194         default:
195                 panic("bad APIC LVT delivery mode: %#x\n", value);
196         }
197         return (value);
198 }
199
200 /*
201  * Map the local APIC and setup necessary interrupt vectors.
202  */
203 void
204 lapic_init(uintptr_t addr)
205 {
206
207         /* Map the local APIC and setup the spurious interrupt handler. */
208         KASSERT(trunc_page(addr) == addr,
209             ("local APIC not aligned on a page boundary"));
210         lapic = (lapic_t *)pmap_mapdev(addr, sizeof(lapic_t));
211         setidt(APIC_SPURIOUS_INT, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
212
213         /* Perform basic initialization of the BSP's local APIC. */
214         lapic_enable();
215         ioint_irqs[IDT_SYSCALL - APIC_IO_INTS] = IRQ_SYSCALL;
216
217         /* Set BSP's per-CPU local APIC ID. */
218         PCPU_SET(apic_id, lapic_id());
219
220         /* Local APIC timer interrupt. */
221         setidt(APIC_TIMER_INT, IDTVEC(timerint), SDT_SYSIGT, SEL_KPL, 0);
222         ioint_irqs[APIC_TIMER_INT - APIC_IO_INTS] = IRQ_TIMER;
223
224         /* XXX: error/thermal interrupts */
225 }
226
227 /*
228  * Create a local APIC instance.
229  */
230 void
231 lapic_create(u_int apic_id, int boot_cpu)
232 {
233         int i;
234
235         if (apic_id >= MAX_APICID) {
236                 printf("APIC: Ignoring local APIC with ID %d\n", apic_id);
237                 if (boot_cpu)
238                         panic("Can't ignore BSP");
239                 return;
240         }
241         KASSERT(!lapics[apic_id].la_present, ("duplicate local APIC %u",
242             apic_id));
243
244         /*
245          * Assume no local LVT overrides and a cluster of 0 and
246          * intra-cluster ID of 0.
247          */
248         lapics[apic_id].la_present = 1;
249         lapics[apic_id].la_id = apic_id;
250         for (i = 0; i < LVT_MAX; i++) {
251                 lapics[apic_id].la_lvts[i] = lvts[i];
252                 lapics[apic_id].la_lvts[i].lvt_active = 0;
253         }
254
255 #ifdef SMP
256         cpu_add(apic_id, boot_cpu);
257 #endif
258 }
259
260 /*
261  * Dump contents of local APIC registers
262  */
263 void
264 lapic_dump(const char* str)
265 {
266
267         printf("cpu%d %s:\n", PCPU_GET(cpuid), str);
268         printf("     ID: 0x%08x   VER: 0x%08x LDR: 0x%08x DFR: 0x%08x\n",
269             lapic->id, lapic->version, lapic->ldr, lapic->dfr);
270         printf("  lint0: 0x%08x lint1: 0x%08x TPR: 0x%08x SVR: 0x%08x\n",
271             lapic->lvt_lint0, lapic->lvt_lint1, lapic->tpr, lapic->svr);
272         printf("  timer: 0x%08x therm: 0x%08x err: 0x%08x pcm: 0x%08x\n",
273             lapic->lvt_timer, lapic->lvt_thermal, lapic->lvt_error,
274             lapic->lvt_pcint);
275 }
276
277 void
278 lapic_setup(void)
279 {
280         struct lapic *la;
281         u_int32_t value, maxlvt;
282         register_t eflags;
283         char buf[MAXCOMLEN + 1];
284
285         la = &lapics[lapic_id()];
286         KASSERT(la->la_present, ("missing APIC structure"));
287         eflags = intr_disable();
288         maxlvt = (lapic->version & APIC_VER_MAXLVT) >> MAXLVTSHIFT;
289
290         /* Initialize the TPR to allow all interrupts. */
291         lapic_set_tpr(0);
292
293         /* Use the cluster model for logical IDs. */
294         value = lapic->dfr;
295         value &= ~APIC_DFR_MODEL_MASK;
296         value |= APIC_DFR_MODEL_CLUSTER;
297         lapic->dfr = value;
298
299         /* Set this APIC's logical ID. */
300         value = lapic->ldr;
301         value &= ~APIC_ID_MASK;
302         value |= (la->la_cluster << APIC_ID_CLUSTER_SHIFT |
303             1 << la->la_cluster_id) << APIC_ID_SHIFT;
304         lapic->ldr = value;
305
306         /* Setup spurious vector and enable the local APIC. */
307         lapic_enable();
308
309         /* Program LINT[01] LVT entries. */
310         lapic->lvt_lint0 = lvt_mode(la, LVT_LINT0, lapic->lvt_lint0);
311         lapic->lvt_lint1 = lvt_mode(la, LVT_LINT1, lapic->lvt_lint1);
312 #ifdef  HWPMC_HOOKS
313         /* Program the PMC LVT entry if present. */
314         if (maxlvt >= LVT_PMC)
315                 lapic->lvt_pcint = lvt_mode(la, LVT_PMC, lapic->lvt_pcint);
316 #endif
317
318         /* Program timer LVT and setup handler. */
319         lapic->lvt_timer = lvt_mode(la, LVT_TIMER, lapic->lvt_timer);
320         snprintf(buf, sizeof(buf), "cpu%d: timer", PCPU_GET(cpuid));
321         intrcnt_add(buf, &la->la_timer_count);
322         if (PCPU_GET(cpuid) != 0) {
323                 KASSERT(lapic_timer_period != 0, ("lapic%u: zero divisor",
324                     lapic_id()));
325                 lapic_timer_set_divisor(lapic_timer_divisor);
326                 lapic_timer_periodic(lapic_timer_period);
327                 lapic_timer_enable_intr();
328         }
329
330         /* XXX: Error and thermal LVTs */
331
332         intr_restore(eflags);
333 }
334
335 /*
336  * Called by cpu_initclocks() on the BSP to setup the local APIC timer so
337  * that it can drive hardclock, statclock, and profclock.  This function
338  * returns true if it is able to use the local APIC timer to drive the
339  * clocks and false if it is not able.
340  */
341 int
342 lapic_setup_clock(void)
343 {
344         u_long value;
345
346         /* Can't drive the timer without a local APIC. */
347         if (lapic == NULL)
348                 return (0);
349
350         /* Start off with a divisor of 2 (power on reset default). */
351         lapic_timer_divisor = 2;
352
353         /* Try to calibrate the local APIC timer. */
354         do {
355                 lapic_timer_set_divisor(lapic_timer_divisor);
356                 lapic_timer_oneshot(APIC_TIMER_MAX_COUNT);
357                 DELAY(2000000);
358                 value = APIC_TIMER_MAX_COUNT - lapic->ccr_timer;
359                 if (value != APIC_TIMER_MAX_COUNT)
360                         break;
361                 lapic_timer_divisor <<= 1;
362         } while (lapic_timer_divisor <= 128);
363         if (lapic_timer_divisor > 128)
364                 panic("lapic: Divisor too big");
365         value /= 2;
366         if (bootverbose)
367                 printf("lapic: Divisor %lu, Frequency %lu hz\n",
368                     lapic_timer_divisor, value);
369
370         /*
371          * We will drive the timer at a small multiple of hz and drive
372          * both of the other timers with similarly small but relatively
373          * prime divisors.
374          */
375         lapic_timer_hz = hz * LAPIC_TIMER_HZ_DIVIDER;
376         stathz = lapic_timer_hz / LAPIC_TIMER_STATHZ_DIVIDER;
377         profhz = lapic_timer_hz / LAPIC_TIMER_PROFHZ_DIVIDER;
378         lapic_timer_period = value / lapic_timer_hz;
379
380         /*
381          * Start up the timer on the BSP.  The APs will kick off their
382          * timer during lapic_setup().
383          */
384         lapic_timer_periodic(lapic_timer_period);
385         lapic_timer_enable_intr();
386         return (1);
387 }
388
389 void
390 lapic_disable(void)
391 {
392         uint32_t value;
393
394         /* Software disable the local APIC. */
395         value = lapic->svr;
396         value &= ~APIC_SVR_SWEN;
397         lapic->svr = value;
398 }
399
400 static void
401 lapic_enable(void)
402 {
403         u_int32_t value;
404
405         /* Program the spurious vector to enable the local APIC. */
406         value = lapic->svr;
407         value &= ~(APIC_SVR_VECTOR | APIC_SVR_FOCUS);
408         value |= (APIC_SVR_FEN | APIC_SVR_SWEN | APIC_SPURIOUS_INT);
409         lapic->svr = value;
410 }
411
412 int
413 lapic_id(void)
414 {
415
416         KASSERT(lapic != NULL, ("local APIC is not mapped"));
417         return (lapic->id >> APIC_ID_SHIFT);
418 }
419
420 int
421 lapic_intr_pending(u_int vector)
422 {
423         volatile u_int32_t *irr;
424
425         /*
426          * The IRR registers are an array of 128-bit registers each of
427          * which only describes 32 interrupts in the low 32 bits..  Thus,
428          * we divide the vector by 32 to get the 128-bit index.  We then
429          * multiply that index by 4 to get the equivalent index from
430          * treating the IRR as an array of 32-bit registers.  Finally, we
431          * modulus the vector by 32 to determine the individual bit to
432          * test.
433          */
434         irr = &lapic->irr0;
435         return (irr[(vector / 32) * 4] & 1 << (vector % 32));
436 }
437
438 void
439 lapic_set_logical_id(u_int apic_id, u_int cluster, u_int cluster_id)
440 {
441         struct lapic *la;
442
443         KASSERT(lapics[apic_id].la_present, ("%s: APIC %u doesn't exist",
444             __func__, apic_id));
445         KASSERT(cluster <= APIC_MAX_CLUSTER, ("%s: cluster %u too big",
446             __func__, cluster));
447         KASSERT(cluster_id <= APIC_MAX_INTRACLUSTER_ID,
448             ("%s: intra cluster id %u too big", __func__, cluster_id));
449         la = &lapics[apic_id];
450         la->la_cluster = cluster;
451         la->la_cluster_id = cluster_id;
452 }
453
454 int
455 lapic_set_lvt_mask(u_int apic_id, u_int pin, u_char masked)
456 {
457
458         if (pin > LVT_MAX)
459                 return (EINVAL);
460         if (apic_id == APIC_ID_ALL) {
461                 lvts[pin].lvt_masked = masked;
462                 if (bootverbose)
463                         printf("lapic:");
464         } else {
465                 KASSERT(lapics[apic_id].la_present,
466                     ("%s: missing APIC %u", __func__, apic_id));
467                 lapics[apic_id].la_lvts[pin].lvt_masked = masked;
468                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
469                 if (bootverbose)
470                         printf("lapic%u:", apic_id);
471         }
472         if (bootverbose)
473                 printf(" LINT%u %s\n", pin, masked ? "masked" : "unmasked");
474         return (0);
475 }
476
477 int
478 lapic_set_lvt_mode(u_int apic_id, u_int pin, u_int32_t mode)
479 {
480         struct lvt *lvt;
481
482         if (pin > LVT_MAX)
483                 return (EINVAL);
484         if (apic_id == APIC_ID_ALL) {
485                 lvt = &lvts[pin];
486                 if (bootverbose)
487                         printf("lapic:");
488         } else {
489                 KASSERT(lapics[apic_id].la_present,
490                     ("%s: missing APIC %u", __func__, apic_id));
491                 lvt = &lapics[apic_id].la_lvts[pin];
492                 lvt->lvt_active = 1;
493                 if (bootverbose)
494                         printf("lapic%u:", apic_id);
495         }
496         lvt->lvt_mode = mode;
497         switch (mode) {
498         case APIC_LVT_DM_NMI:
499         case APIC_LVT_DM_SMI:
500         case APIC_LVT_DM_INIT:
501         case APIC_LVT_DM_EXTINT:
502                 lvt->lvt_edgetrigger = 1;
503                 lvt->lvt_activehi = 1;
504                 if (mode == APIC_LVT_DM_EXTINT)
505                         lvt->lvt_masked = 1;
506                 else
507                         lvt->lvt_masked = 0;
508                 break;
509         default:
510                 panic("Unsupported delivery mode: 0x%x\n", mode);
511         }
512         if (bootverbose) {
513                 printf(" Routing ");
514                 switch (mode) {
515                 case APIC_LVT_DM_NMI:
516                         printf("NMI");
517                         break;
518                 case APIC_LVT_DM_SMI:
519                         printf("SMI");
520                         break;
521                 case APIC_LVT_DM_INIT:
522                         printf("INIT");
523                         break;
524                 case APIC_LVT_DM_EXTINT:
525                         printf("ExtINT");
526                         break;
527                 }
528                 printf(" -> LINT%u\n", pin);
529         }
530         return (0);
531 }
532
533 int
534 lapic_set_lvt_polarity(u_int apic_id, u_int pin, enum intr_polarity pol)
535 {
536
537         if (pin > LVT_MAX || pol == INTR_POLARITY_CONFORM)
538                 return (EINVAL);
539         if (apic_id == APIC_ID_ALL) {
540                 lvts[pin].lvt_activehi = (pol == INTR_POLARITY_HIGH);
541                 if (bootverbose)
542                         printf("lapic:");
543         } else {
544                 KASSERT(lapics[apic_id].la_present,
545                     ("%s: missing APIC %u", __func__, apic_id));
546                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
547                 lapics[apic_id].la_lvts[pin].lvt_activehi =
548                     (pol == INTR_POLARITY_HIGH);
549                 if (bootverbose)
550                         printf("lapic%u:", apic_id);
551         }
552         if (bootverbose)
553                 printf(" LINT%u polarity: %s\n", pin,
554                     pol == INTR_POLARITY_HIGH ? "high" : "low");
555         return (0);
556 }
557
558 int
559 lapic_set_lvt_triggermode(u_int apic_id, u_int pin, enum intr_trigger trigger)
560 {
561
562         if (pin > LVT_MAX || trigger == INTR_TRIGGER_CONFORM)
563                 return (EINVAL);
564         if (apic_id == APIC_ID_ALL) {
565                 lvts[pin].lvt_edgetrigger = (trigger == INTR_TRIGGER_EDGE);
566                 if (bootverbose)
567                         printf("lapic:");
568         } else {
569                 KASSERT(lapics[apic_id].la_present,
570                     ("%s: missing APIC %u", __func__, apic_id));
571                 lapics[apic_id].la_lvts[pin].lvt_edgetrigger =
572                     (trigger == INTR_TRIGGER_EDGE);
573                 lapics[apic_id].la_lvts[pin].lvt_active = 1;
574                 if (bootverbose)
575                         printf("lapic%u:", apic_id);
576         }
577         if (bootverbose)
578                 printf(" LINT%u trigger: %s\n", pin,
579                     trigger == INTR_TRIGGER_EDGE ? "edge" : "level");
580         return (0);
581 }
582
583 /*
584  * Adjust the TPR of the current CPU so that it blocks all interrupts below
585  * the passed in vector.
586  */
587 void
588 lapic_set_tpr(u_int vector)
589 {
590 #ifdef CHEAP_TPR
591         lapic->tpr = vector;
592 #else
593         u_int32_t tpr;
594
595         tpr = lapic->tpr & ~APIC_TPR_PRIO;
596         tpr |= vector;
597         lapic->tpr = tpr;
598 #endif
599 }
600
601 void
602 lapic_eoi(void)
603 {
604
605         lapic->eoi = 0;
606 }
607
608 void
609 lapic_handle_intr(int vector, struct trapframe frame)
610 {
611         struct intsrc *isrc;
612
613         if (vector == -1)
614                 panic("Couldn't get vector from ISR!");
615         isrc = intr_lookup_source(apic_idt_to_irq(vector));
616         intr_execute_handlers(isrc, &frame);
617 }
618
619 void
620 lapic_handle_timer(struct clockframe frame)
621 {
622         struct lapic *la;
623
624         /* Send EOI first thing. */
625         lapic_eoi();
626
627         /* Look up our local APIC structure for the tick counters. */
628         la = &lapics[PCPU_GET(apic_id)];
629         (*la->la_timer_count)++;
630         critical_enter();
631
632         /* Fire hardclock at hz. */
633         la->la_hard_ticks += hz;
634         if (la->la_hard_ticks >= lapic_timer_hz) {
635                 la->la_hard_ticks -= lapic_timer_hz;
636                 if (PCPU_GET(cpuid) == 0)
637                         hardclock(&frame);
638                 else
639                         hardclock_process(&frame);
640         }
641
642         /* Fire statclock at stathz. */
643         la->la_stat_ticks += stathz;
644         if (la->la_stat_ticks >= lapic_timer_hz) {
645                 la->la_stat_ticks -= lapic_timer_hz;
646                 statclock(&frame);
647         }
648
649         /* Fire profclock at profhz, but only when needed. */
650         la->la_prof_ticks += profhz;
651         if (la->la_prof_ticks >= lapic_timer_hz) {
652                 la->la_prof_ticks -= lapic_timer_hz;
653                 if (profprocs != 0)
654                         profclock(&frame);
655         }
656         critical_exit();
657 }
658
659 static void
660 lapic_timer_set_divisor(u_int divisor)
661 {
662
663         KASSERT(powerof2(divisor), ("lapic: invalid divisor %u", divisor));
664         KASSERT(ffs(divisor) <= sizeof(lapic_timer_divisors) /
665             sizeof(u_int32_t), ("lapic: invalid divisor %u", divisor));
666         lapic->dcr_timer = lapic_timer_divisors[ffs(divisor) - 1];
667 }
668
669 static void
670 lapic_timer_oneshot(u_int count)
671 {
672         u_int32_t value;
673
674         value = lapic->lvt_timer;
675         value &= ~APIC_LVTT_TM;
676         value |= APIC_LVTT_TM_ONE_SHOT;
677         lapic->lvt_timer = value;
678         lapic->icr_timer = count;
679 }
680
681 static void
682 lapic_timer_periodic(u_int count)
683 {
684         u_int32_t value;
685
686         value = lapic->lvt_timer;
687         value &= ~APIC_LVTT_TM;
688         value |= APIC_LVTT_TM_PERIODIC;
689         lapic->lvt_timer = value;
690         lapic->icr_timer = count;
691 }
692
693 static void
694 lapic_timer_enable_intr(void)
695 {
696         u_int32_t value;
697
698         value = lapic->lvt_timer;
699         value &= ~APIC_LVT_M;
700         lapic->lvt_timer = value;
701 }
702
703 /* Request a free IDT vector to be used by the specified IRQ. */
704 u_int
705 apic_alloc_vector(u_int irq)
706 {
707         u_int vector;
708
709         KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
710
711         /*
712          * Search for a free vector.  Currently we just use a very simple
713          * algorithm to find the first free vector.
714          */
715         mtx_lock_spin(&icu_lock);
716         for (vector = 0; vector < APIC_NUM_IOINTS; vector++) {
717                 if (ioint_irqs[vector] != 0)
718                         continue;
719                 ioint_irqs[vector] = irq;
720                 mtx_unlock_spin(&icu_lock);
721                 return (vector + APIC_IO_INTS);
722         }
723         mtx_unlock_spin(&icu_lock);
724         panic("Couldn't find an APIC vector for IRQ %u", irq);
725 }
726
727 void
728 apic_enable_vector(u_int vector)
729 {
730
731         KASSERT(vector != IDT_SYSCALL, ("Attempt to overwrite syscall entry"));
732         KASSERT(ioint_handlers[vector / 32] != NULL,
733             ("No ISR handler for vector %u", vector));
734         setidt(vector, ioint_handlers[vector / 32], SDT_SYSIGT, SEL_KPL, 0);
735 }
736
737 /* Release an APIC vector when it's no longer in use. */
738 void
739 apic_free_vector(u_int vector, u_int irq)
740 {
741         KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
742             vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
743             ("Vector %u does not map to an IRQ line", vector));
744         KASSERT(irq < NUM_IO_INTS, ("Invalid IRQ %u", irq));
745         KASSERT(ioint_irqs[vector - APIC_IO_INTS] == irq, ("IRQ mismatch"));
746         mtx_lock_spin(&icu_lock);
747         ioint_irqs[vector - APIC_IO_INTS] = 0;
748         mtx_unlock_spin(&icu_lock);
749 }
750
751 /* Map an IDT vector (APIC) to an IRQ (interrupt source). */
752 u_int
753 apic_idt_to_irq(u_int vector)
754 {
755
756         KASSERT(vector >= APIC_IO_INTS && vector != IDT_SYSCALL &&
757             vector <= APIC_IO_INTS + APIC_NUM_IOINTS,
758             ("Vector %u does not map to an IRQ line", vector));
759         return (ioint_irqs[vector - APIC_IO_INTS]);
760 }
761
762 #ifdef DDB
763 /*
764  * Dump data about APIC IDT vector mappings.
765  */
766 DB_SHOW_COMMAND(apic, db_show_apic)
767 {
768         struct intsrc *isrc;
769         int quit, i, verbose;
770         u_int irq;
771
772         quit = 0;
773         if (strcmp(modif, "vv") == 0)
774                 verbose = 2;
775         else if (strcmp(modif, "v") == 0)
776                 verbose = 1;
777         else
778                 verbose = 0;
779         db_setup_paging(db_simple_pager, &quit, db_lines_per_page);
780         for (i = 0; i < APIC_NUM_IOINTS + 1 && !quit; i++) {
781                 irq = ioint_irqs[i];
782                 if (irq != 0 && irq != IRQ_SYSCALL) {
783                         db_printf("vec 0x%2x -> ", i + APIC_IO_INTS);
784                         if (irq == IRQ_TIMER)
785                                 db_printf("lapic timer\n");
786                         else if (irq < NUM_IO_INTS) {
787                                 isrc = intr_lookup_source(irq);
788                                 if (isrc == NULL || verbose == 0)
789                                         db_printf("IRQ %u\n", irq);
790                                 else
791                                         db_dump_intr_event(isrc->is_event,
792                                             verbose == 2);
793                         } else
794                                 db_printf("IRQ %u ???\n", irq);
795                 }
796         }
797 }
798 #endif
799
800 /*
801  * APIC probing support code.  This includes code to manage enumerators.
802  */
803
804 static SLIST_HEAD(, apic_enumerator) enumerators =
805         SLIST_HEAD_INITIALIZER(enumerators);
806 static struct apic_enumerator *best_enum;
807         
808 void
809 apic_register_enumerator(struct apic_enumerator *enumerator)
810 {
811 #ifdef INVARIANTS
812         struct apic_enumerator *apic_enum;
813
814         SLIST_FOREACH(apic_enum, &enumerators, apic_next) {
815                 if (apic_enum == enumerator)
816                         panic("%s: Duplicate register of %s", __func__,
817                             enumerator->apic_name);
818         }
819 #endif
820         SLIST_INSERT_HEAD(&enumerators, enumerator, apic_next);
821 }
822
823 /*
824  * We have to look for CPU's very, very early because certain subsystems
825  * want to know how many CPU's we have extremely early on in the boot
826  * process.
827  */
828 static void
829 apic_init(void *dummy __unused)
830 {
831         struct apic_enumerator *enumerator;
832         int retval, best;
833
834         /* We only support built in local APICs. */
835         if (!(cpu_feature & CPUID_APIC))
836                 return;
837
838         /* Don't probe if APIC mode is disabled. */
839         if (resource_disabled("apic", 0))
840                 return;
841
842         /* First, probe all the enumerators to find the best match. */
843         best_enum = NULL;
844         best = 0;
845         SLIST_FOREACH(enumerator, &enumerators, apic_next) {
846                 retval = enumerator->apic_probe();
847                 if (retval > 0)
848                         continue;
849                 if (best_enum == NULL || best < retval) {
850                         best_enum = enumerator;
851                         best = retval;
852                 }
853         }
854         if (best_enum == NULL) {
855                 if (bootverbose)
856                         printf("APIC: Could not find any APICs.\n");
857                 return;
858         }
859
860         if (bootverbose)
861                 printf("APIC: Using the %s enumerator.\n",
862                     best_enum->apic_name);
863
864         /* Second, probe the CPU's in the system. */
865         retval = best_enum->apic_probe_cpus();
866         if (retval != 0)
867                 printf("%s: Failed to probe CPUs: returned %d\n",
868                     best_enum->apic_name, retval);
869 }
870 SYSINIT(apic_init, SI_SUB_TUNABLES - 1, SI_ORDER_SECOND, apic_init, NULL)
871
872 /*
873  * Setup the local APIC.  We have to do this prior to starting up the APs
874  * in the SMP case.
875  */
876 static void
877 apic_setup_local(void *dummy __unused)
878 {
879         int retval;
880
881         if (best_enum == NULL)
882                 return;
883         retval = best_enum->apic_setup_local();
884         if (retval != 0)
885                 printf("%s: Failed to setup the local APIC: returned %d\n",
886                     best_enum->apic_name, retval);
887 #ifdef SMP
888         /* Last, setup the cpu topology now that we have probed CPUs */
889         mp_topology();
890 #endif
891 }
892 SYSINIT(apic_setup_local, SI_SUB_CPU, SI_ORDER_FIRST, apic_setup_local, NULL)
893
894 /*
895  * Setup the I/O APICs.
896  */
897 static void
898 apic_setup_io(void *dummy __unused)
899 {
900         int retval;
901
902         if (best_enum == NULL)
903                 return;
904         retval = best_enum->apic_setup_io();
905         if (retval != 0)
906                 printf("%s: Failed to setup I/O APICs: returned %d\n",
907                     best_enum->apic_name, retval);
908
909         /*
910          * Finish setting up the local APIC on the BSP once we know how to
911          * properly program the LINT pins.
912          */
913         lapic_setup();
914         if (bootverbose)
915                 lapic_dump("BSP");
916 }
917 SYSINIT(apic_setup_io, SI_SUB_INTR, SI_ORDER_SECOND, apic_setup_io, NULL)
918
919 #ifdef SMP
920 /*
921  * Inter Processor Interrupt functions.  The lapic_ipi_*() functions are
922  * private to the sys/amd64 code.  The public interface for the rest of the
923  * kernel is defined in mp_machdep.c.
924  */
925 int
926 lapic_ipi_wait(int delay)
927 {
928         int x, incr;
929
930         /*
931          * Wait delay loops for IPI to be sent.  This is highly bogus
932          * since this is sensitive to CPU clock speed.  If delay is
933          * -1, we wait forever.
934          */
935         if (delay == -1) {
936                 incr = 0;
937                 delay = 1;
938         } else
939                 incr = 1;
940         for (x = 0; x < delay; x += incr) {
941                 if ((lapic->icr_lo & APIC_DELSTAT_MASK) == APIC_DELSTAT_IDLE)
942                         return (1);
943                 ia32_pause();
944         }
945         return (0);
946 }
947
948 void
949 lapic_ipi_raw(register_t icrlo, u_int dest)
950 {
951         register_t value, eflags;
952
953         /* XXX: Need more sanity checking of icrlo? */
954         KASSERT(lapic != NULL, ("%s called too early", __func__));
955         KASSERT((dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
956             ("%s: invalid dest field", __func__));
957         KASSERT((icrlo & APIC_ICRLO_RESV_MASK) == 0,
958             ("%s: reserved bits set in ICR LO register", __func__));
959
960         /* Set destination in ICR HI register if it is being used. */
961         eflags = intr_disable();
962         if ((icrlo & APIC_DEST_MASK) == APIC_DEST_DESTFLD) {
963                 value = lapic->icr_hi;
964                 value &= ~APIC_ID_MASK;
965                 value |= dest << APIC_ID_SHIFT;
966                 lapic->icr_hi = value;
967         }
968
969         /* Program the contents of the IPI and dispatch it. */
970         value = lapic->icr_lo;
971         value &= APIC_ICRLO_RESV_MASK;
972         value |= icrlo;
973         lapic->icr_lo = value;
974         intr_restore(eflags);
975 }
976
977 #define BEFORE_SPIN     1000000
978 #ifdef DETECT_DEADLOCK
979 #define AFTER_SPIN      1000
980 #endif
981
982 void
983 lapic_ipi_vectored(u_int vector, int dest)
984 {
985         register_t icrlo, destfield;
986
987         KASSERT((vector & ~APIC_VECTOR_MASK) == 0,
988             ("%s: invalid vector %d", __func__, vector));
989
990         icrlo = vector | APIC_DELMODE_FIXED | APIC_DESTMODE_PHY |
991             APIC_LEVEL_DEASSERT | APIC_TRIGMOD_EDGE;
992         destfield = 0;
993         switch (dest) {
994         case APIC_IPI_DEST_SELF:
995                 icrlo |= APIC_DEST_SELF;
996                 break;
997         case APIC_IPI_DEST_ALL:
998                 icrlo |= APIC_DEST_ALLISELF;
999                 break;
1000         case APIC_IPI_DEST_OTHERS:
1001                 icrlo |= APIC_DEST_ALLESELF;
1002                 break;
1003         default:
1004                 KASSERT((dest & ~(APIC_ID_MASK >> APIC_ID_SHIFT)) == 0,
1005                     ("%s: invalid destination 0x%x", __func__, dest));
1006                 destfield = dest;
1007         }
1008
1009         /* Wait for an earlier IPI to finish. */
1010         if (!lapic_ipi_wait(BEFORE_SPIN)) {
1011                 if (panicstr != NULL)
1012                         return;
1013                 else
1014                         panic("APIC: Previous IPI is stuck");
1015         }
1016
1017         lapic_ipi_raw(icrlo, destfield);
1018
1019 #ifdef DETECT_DEADLOCK
1020         /* Wait for IPI to be delivered. */
1021         if (!lapic_ipi_wait(AFTER_SPIN)) {
1022 #ifdef needsattention
1023                 /*
1024                  * XXX FIXME:
1025                  *
1026                  * The above function waits for the message to actually be
1027                  * delivered.  It breaks out after an arbitrary timeout
1028                  * since the message should eventually be delivered (at
1029                  * least in theory) and that if it wasn't we would catch
1030                  * the failure with the check above when the next IPI is
1031                  * sent.
1032                  *
1033                  * We could skip this wait entirely, EXCEPT it probably
1034                  * protects us from other routines that assume that the
1035                  * message was delivered and acted upon when this function
1036                  * returns.
1037                  */
1038                 printf("APIC: IPI might be stuck\n");
1039 #else /* !needsattention */
1040                 /* Wait until mesage is sent without a timeout. */
1041                 while (lapic->icr_lo & APIC_DELSTAT_PEND)
1042                         ia32_pause();
1043 #endif /* needsattention */
1044         }
1045 #endif /* DETECT_DEADLOCK */
1046 }
1047 #endif /* SMP */