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