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