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