708bf857171ad6178bc1f2f5a9e13171059dcfa8
[dragonfly.git] / sys / platform / pc32 / apic / mpapic.c
1 /*
2  * Copyright (c) 1996, by Steve Passe
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. The name of the developer may NOT be used to endorse or promote products
11  *    derived from this software without specific prior written permission.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  * $FreeBSD: src/sys/i386/i386/mpapic.c,v 1.37.2.7 2003/01/25 02:31:47 peter Exp $
26  */
27
28 #include <sys/param.h>
29 #include <sys/systm.h>
30 #include <sys/kernel.h>
31 #include <sys/bus.h>
32 #include <machine/globaldata.h>
33 #include <machine/smp.h>
34 #include <machine/cputypes.h>
35 #include <machine/md_var.h>
36 #include <machine/pmap.h>
37 #include <machine_base/apic/mpapic.h>
38 #include <machine/segments.h>
39 #include <sys/thread2.h>
40
41 #include <machine/intr_machdep.h>
42
43 /* XXX */
44 extern pt_entry_t *SMPpt;
45
46 /* EISA Edge/Level trigger control registers */
47 #define ELCR0   0x4d0                   /* eisa irq 0-7 */
48 #define ELCR1   0x4d1                   /* eisa irq 8-15 */
49
50 struct ioapic_info {
51         int             io_idx;
52         int             io_apic_id;
53         void            *io_addr;
54         int             io_npin;
55         int             io_gsi_base;
56
57         TAILQ_ENTRY(ioapic_info) io_link;
58 };
59 TAILQ_HEAD(ioapic_info_list, ioapic_info);
60
61 struct ioapic_conf {
62         struct ioapic_info_list ioc_list;
63         int             ioc_intsrc[16]; /* XXX magic number */
64 };
65
66 static void     lapic_timer_calibrate(void);
67 static void     lapic_timer_set_divisor(int);
68 static void     lapic_timer_fixup_handler(void *);
69 static void     lapic_timer_restart_handler(void *);
70
71 void            lapic_timer_process(void);
72 void            lapic_timer_process_frame(struct intrframe *);
73
74 static int      lapic_timer_enable = 1;
75 TUNABLE_INT("hw.lapic_timer_enable", &lapic_timer_enable);
76
77 static void     lapic_timer_intr_reload(struct cputimer_intr *, sysclock_t);
78 static void     lapic_timer_intr_enable(struct cputimer_intr *);
79 static void     lapic_timer_intr_restart(struct cputimer_intr *);
80 static void     lapic_timer_intr_pmfixup(struct cputimer_intr *);
81
82 static void     ioapic_setup(const struct ioapic_info *);
83 static void     ioapic_set_apic_id(const struct ioapic_info *);
84 static void     ioapic_gsi_setup(int);
85 static const struct ioapic_info *
86                 ioapic_gsi_search(int);
87
88 static struct cputimer_intr lapic_cputimer_intr = {
89         .freq = 0,
90         .reload = lapic_timer_intr_reload,
91         .enable = lapic_timer_intr_enable,
92         .config = cputimer_intr_default_config,
93         .restart = lapic_timer_intr_restart,
94         .pmfixup = lapic_timer_intr_pmfixup,
95         .initclock = cputimer_intr_default_initclock,
96         .next = SLIST_ENTRY_INITIALIZER,
97         .name = "lapic",
98         .type = CPUTIMER_INTR_LAPIC,
99         .prio = CPUTIMER_INTR_PRIO_LAPIC,
100         .caps = CPUTIMER_INTR_CAP_NONE
101 };
102
103 /*
104  * pointers to pmapped apic hardware.
105  */
106
107 volatile ioapic_t       **ioapic;
108
109 static int              lapic_timer_divisor_idx = -1;
110 static const uint32_t   lapic_timer_divisors[] = {
111         APIC_TDCR_2,    APIC_TDCR_4,    APIC_TDCR_8,    APIC_TDCR_16,
112         APIC_TDCR_32,   APIC_TDCR_64,   APIC_TDCR_128,  APIC_TDCR_1
113 };
114 #define APIC_TIMER_NDIVISORS (int)(NELEM(lapic_timer_divisors))
115
116 int                     lapic_id_max;
117
118 static struct ioapic_conf       ioapic_conf;
119
120 /*
121  * Enable LAPIC, configure interrupts.
122  */
123 void
124 apic_initialize(boolean_t bsp)
125 {
126         uint32_t timer;
127         u_int   temp;
128
129         /*
130          * Setup LINT0 as ExtINT on the BSP.  This is theoretically an
131          * aggregate interrupt input from the 8259.  The INTA cycle
132          * will be routed to the external controller (the 8259) which
133          * is expected to supply the vector.
134          *
135          * Must be setup edge triggered, active high.
136          *
137          * Disable LINT0 on the APs.  It doesn't matter what delivery
138          * mode we use because we leave it masked.
139          */
140         temp = lapic.lvt_lint0;
141         temp &= ~(APIC_LVT_MASKED | APIC_LVT_TRIG_MASK | 
142                   APIC_LVT_POLARITY_MASK | APIC_LVT_DM_MASK);
143         if (mycpu->gd_cpuid == 0)
144                 temp |= APIC_LVT_DM_EXTINT;
145         else
146                 temp |= APIC_LVT_DM_FIXED | APIC_LVT_MASKED;
147         lapic.lvt_lint0 = temp;
148
149         /*
150          * Setup LINT1 as NMI, masked till later.
151          * Edge trigger, active high.
152          */
153         temp = lapic.lvt_lint1;
154         temp &= ~(APIC_LVT_MASKED | APIC_LVT_TRIG_MASK | 
155                   APIC_LVT_POLARITY_MASK | APIC_LVT_DM_MASK);
156         temp |= APIC_LVT_MASKED | APIC_LVT_DM_NMI;
157         lapic.lvt_lint1 = temp;
158
159         /*
160          * Mask the LAPIC error interrupt, LAPIC performance counter
161          * interrupt.
162          */
163         lapic.lvt_error = lapic.lvt_error | APIC_LVT_MASKED;
164         lapic.lvt_pcint = lapic.lvt_pcint | APIC_LVT_MASKED;
165
166         /*
167          * Set LAPIC timer vector and mask the LAPIC timer interrupt.
168          */
169         timer = lapic.lvt_timer;
170         timer &= ~APIC_LVTT_VECTOR;
171         timer |= XTIMER_OFFSET;
172         timer |= APIC_LVTT_MASKED;
173         lapic.lvt_timer = timer;
174
175         /*
176          * Set the Task Priority Register as needed.   At the moment allow
177          * interrupts on all cpus (the APs will remain CLId until they are
178          * ready to deal).  We could disable all but IPIs by setting
179          * temp |= TPR_IPI for cpu != 0.
180          */
181         temp = lapic.tpr;
182         temp &= ~APIC_TPR_PRIO;         /* clear priority field */
183 #ifdef SMP /* APIC-IO */
184 if (!apic_io_enable) {
185 #endif
186         /*
187          * If we are NOT running the IO APICs, the LAPIC will only be used
188          * for IPIs.  Set the TPR to prevent any unintentional interrupts.
189          */
190         temp |= TPR_IPI;
191 #ifdef SMP /* APIC-IO */
192 }
193 #endif
194
195         lapic.tpr = temp;
196
197         /* 
198          * Enable the LAPIC 
199          */
200         temp = lapic.svr;
201         temp |= APIC_SVR_ENABLE;        /* enable the LAPIC */
202         temp &= ~APIC_SVR_FOCUS_DISABLE; /* enable lopri focus processor */
203
204         /*
205          * Set the spurious interrupt vector.  The low 4 bits of the vector
206          * must be 1111.
207          */
208         if ((XSPURIOUSINT_OFFSET & 0x0F) != 0x0F)
209                 panic("bad XSPURIOUSINT_OFFSET: 0x%08x", XSPURIOUSINT_OFFSET);
210         temp &= ~APIC_SVR_VECTOR;
211         temp |= XSPURIOUSINT_OFFSET;
212
213         lapic.svr = temp;
214
215         /*
216          * Pump out a few EOIs to clean out interrupts that got through
217          * before we were able to set the TPR.
218          */
219         lapic.eoi = 0;
220         lapic.eoi = 0;
221         lapic.eoi = 0;
222
223         if (bsp) {
224                 lapic_timer_calibrate();
225                 if (lapic_timer_enable) {
226                         cputimer_intr_register(&lapic_cputimer_intr);
227                         cputimer_intr_select(&lapic_cputimer_intr, 0);
228                 }
229         } else {
230                 lapic_timer_set_divisor(lapic_timer_divisor_idx);
231         }
232
233         if (bootverbose)
234                 apic_dump("apic_initialize()");
235 }
236
237 static void
238 lapic_timer_set_divisor(int divisor_idx)
239 {
240         KKASSERT(divisor_idx >= 0 && divisor_idx < APIC_TIMER_NDIVISORS);
241         lapic.dcr_timer = lapic_timer_divisors[divisor_idx];
242 }
243
244 static void
245 lapic_timer_oneshot(u_int count)
246 {
247         uint32_t value;
248
249         value = lapic.lvt_timer;
250         value &= ~APIC_LVTT_PERIODIC;
251         lapic.lvt_timer = value;
252         lapic.icr_timer = count;
253 }
254
255 static void
256 lapic_timer_oneshot_quick(u_int count)
257 {
258         lapic.icr_timer = count;
259 }
260
261 static void
262 lapic_timer_calibrate(void)
263 {
264         sysclock_t value;
265
266         /* Try to calibrate the local APIC timer. */
267         for (lapic_timer_divisor_idx = 0;
268              lapic_timer_divisor_idx < APIC_TIMER_NDIVISORS;
269              lapic_timer_divisor_idx++) {
270                 lapic_timer_set_divisor(lapic_timer_divisor_idx);
271                 lapic_timer_oneshot(APIC_TIMER_MAX_COUNT);
272                 DELAY(2000000);
273                 value = APIC_TIMER_MAX_COUNT - lapic.ccr_timer;
274                 if (value != APIC_TIMER_MAX_COUNT)
275                         break;
276         }
277         if (lapic_timer_divisor_idx >= APIC_TIMER_NDIVISORS)
278                 panic("lapic: no proper timer divisor?!\n");
279         lapic_cputimer_intr.freq = value / 2;
280
281         kprintf("lapic: divisor index %d, frequency %u Hz\n",
282                 lapic_timer_divisor_idx, lapic_cputimer_intr.freq);
283 }
284
285 static void
286 lapic_timer_process_oncpu(struct globaldata *gd, struct intrframe *frame)
287 {
288         sysclock_t count;
289
290         gd->gd_timer_running = 0;
291
292         count = sys_cputimer->count();
293         if (TAILQ_FIRST(&gd->gd_systimerq) != NULL)
294                 systimer_intr(&count, 0, frame);
295 }
296
297 void
298 lapic_timer_process(void)
299 {
300         lapic_timer_process_oncpu(mycpu, NULL);
301 }
302
303 void
304 lapic_timer_process_frame(struct intrframe *frame)
305 {
306         lapic_timer_process_oncpu(mycpu, frame);
307 }
308
309 static void
310 lapic_timer_intr_reload(struct cputimer_intr *cti, sysclock_t reload)
311 {
312         struct globaldata *gd = mycpu;
313
314         reload = (int64_t)reload * cti->freq / sys_cputimer->freq;
315         if (reload < 2)
316                 reload = 2;
317
318         if (gd->gd_timer_running) {
319                 if (reload < lapic.ccr_timer)
320                         lapic_timer_oneshot_quick(reload);
321         } else {
322                 gd->gd_timer_running = 1;
323                 lapic_timer_oneshot_quick(reload);
324         }
325 }
326
327 static void
328 lapic_timer_intr_enable(struct cputimer_intr *cti __unused)
329 {
330         uint32_t timer;
331
332         timer = lapic.lvt_timer;
333         timer &= ~(APIC_LVTT_MASKED | APIC_LVTT_PERIODIC);
334         lapic.lvt_timer = timer;
335
336         lapic_timer_fixup_handler(NULL);
337 }
338
339 static void
340 lapic_timer_fixup_handler(void *arg)
341 {
342         int *started = arg;
343
344         if (started != NULL)
345                 *started = 0;
346
347         if (cpu_vendor_id == CPU_VENDOR_AMD) {
348                 /*
349                  * Detect the presence of C1E capability mostly on latest
350                  * dual-cores (or future) k8 family.  This feature renders
351                  * the local APIC timer dead, so we disable it by reading
352                  * the Interrupt Pending Message register and clearing both
353                  * C1eOnCmpHalt (bit 28) and SmiOnCmpHalt (bit 27).
354                  * 
355                  * Reference:
356                  *   "BIOS and Kernel Developer's Guide for AMD NPT
357                  *    Family 0Fh Processors"
358                  *   #32559 revision 3.00
359                  */
360                 if ((cpu_id & 0x00000f00) == 0x00000f00 &&
361                     (cpu_id & 0x0fff0000) >= 0x00040000) {
362                         uint64_t msr;
363
364                         msr = rdmsr(0xc0010055);
365                         if (msr & 0x18000000) {
366                                 struct globaldata *gd = mycpu;
367
368                                 kprintf("cpu%d: AMD C1E detected\n",
369                                         gd->gd_cpuid);
370                                 wrmsr(0xc0010055, msr & ~0x18000000ULL);
371
372                                 /*
373                                  * We are kinda stalled;
374                                  * kick start again.
375                                  */
376                                 gd->gd_timer_running = 1;
377                                 lapic_timer_oneshot_quick(2);
378
379                                 if (started != NULL)
380                                         *started = 1;
381                         }
382                 }
383         }
384 }
385
386 static void
387 lapic_timer_restart_handler(void *dummy __unused)
388 {
389         int started;
390
391         lapic_timer_fixup_handler(&started);
392         if (!started) {
393                 struct globaldata *gd = mycpu;
394
395                 gd->gd_timer_running = 1;
396                 lapic_timer_oneshot_quick(2);
397         }
398 }
399
400 /*
401  * This function is called only by ACPI-CA code currently:
402  * - AMD C1E fixup.  AMD C1E only seems to happen after ACPI
403  *   module controls PM.  So once ACPI-CA is attached, we try
404  *   to apply the fixup to prevent LAPIC timer from hanging.
405  */
406 static void
407 lapic_timer_intr_pmfixup(struct cputimer_intr *cti __unused)
408 {
409         lwkt_send_ipiq_mask(smp_active_mask,
410                             lapic_timer_fixup_handler, NULL);
411 }
412
413 static void
414 lapic_timer_intr_restart(struct cputimer_intr *cti __unused)
415 {
416         lwkt_send_ipiq_mask(smp_active_mask, lapic_timer_restart_handler, NULL);
417 }
418
419
420 /*
421  * dump contents of local APIC registers
422  */
423 void
424 apic_dump(char* str)
425 {
426         kprintf("SMP: CPU%d %s:\n", mycpu->gd_cpuid, str);
427         kprintf("     lint0: 0x%08x lint1: 0x%08x TPR: 0x%08x SVR: 0x%08x\n",
428                 lapic.lvt_lint0, lapic.lvt_lint1, lapic.tpr, lapic.svr);
429 }
430
431
432 #ifdef SMP /* APIC-IO */
433
434 /*
435  * IO APIC code,
436  */
437
438 #define IOAPIC_ISA_INTS         16
439 #define REDIRCNT_IOAPIC(A) \
440             ((int)((io_apic_versions[(A)] & IOART_VER_MAXREDIR) >> MAXREDIRSHIFT) + 1)
441
442 static int trigger (int apic, int pin, u_int32_t * flags);
443 static void polarity (int apic, int pin, u_int32_t * flags, int level);
444
445 #define DEFAULT_FLAGS           \
446         ((u_int32_t)            \
447          (IOART_INTMSET |       \
448           IOART_DESTPHY |       \
449           IOART_DELLOPRI))
450
451 #define DEFAULT_ISA_FLAGS       \
452         ((u_int32_t)            \
453          (IOART_INTMSET |       \
454           IOART_TRGREDG |       \
455           IOART_INTAHI |        \
456           IOART_DESTPHY |       \
457           IOART_DELLOPRI))
458
459 void
460 io_apic_set_id(int apic, int id)
461 {
462         u_int32_t ux;
463         
464         ux = ioapic_read(ioapic[apic], IOAPIC_ID);      /* get current contents */
465         if (((ux & APIC_ID_MASK) >> 24) != id) {
466                 kprintf("Changing APIC ID for IO APIC #%d"
467                        " from %d to %d on chip\n",
468                        apic, ((ux & APIC_ID_MASK) >> 24), id);
469                 ux &= ~APIC_ID_MASK;    /* clear the ID field */
470                 ux |= (id << 24);
471                 ioapic_write(ioapic[apic], IOAPIC_ID, ux);      /* write new value */
472                 ux = ioapic_read(ioapic[apic], IOAPIC_ID);      /* re-read && test */
473                 if (((ux & APIC_ID_MASK) >> 24) != id)
474                         panic("can't control IO APIC #%d ID, reg: 0x%08x",
475                               apic, ux);
476         }
477 }
478
479
480 int
481 io_apic_get_id(int apic)
482 {
483   return (ioapic_read(ioapic[apic], IOAPIC_ID) & APIC_ID_MASK) >> 24;
484 }
485   
486
487
488 /*
489  * Setup the IO APIC.
490  */
491 void
492 io_apic_setup_intpin(int apic, int pin)
493 {
494         int bus, bustype, irq;
495         u_char          select;         /* the select register is 8 bits */
496         u_int32_t       flags;          /* the window register is 32 bits */
497         u_int32_t       target;         /* the window register is 32 bits */
498         u_int32_t       vector;         /* the window register is 32 bits */
499         int             level;
500         int             cpuid;
501         char            envpath[32];
502
503         select = pin * 2 + IOAPIC_REDTBL0;      /* register */
504
505         /*
506          * Always clear an IO APIC pin before [re]programming it.  This is
507          * particularly important if the pin is set up for a level interrupt
508          * as the IOART_REM_IRR bit might be set.   When we reprogram the
509          * vector any EOI from pending ints on this pin could be lost and
510          * IRR might never get reset.
511          *
512          * To fix this problem, clear the vector and make sure it is 
513          * programmed as an edge interrupt.  This should theoretically
514          * clear IRR so we can later, safely program it as a level 
515          * interrupt.
516          */
517         imen_lock();
518
519         flags = ioapic_read(ioapic[apic], select) & IOART_RESV;
520         flags |= IOART_INTMSET | IOART_TRGREDG | IOART_INTAHI;
521         flags |= IOART_DESTPHY | IOART_DELFIXED;
522
523         target = ioapic_read(ioapic[apic], select + 1) & IOART_HI_DEST_RESV;
524         target |= 0;    /* fixed mode cpu mask of 0 - don't deliver anywhere */
525
526         vector = 0;
527
528         ioapic_write(ioapic[apic], select, flags | vector);
529         ioapic_write(ioapic[apic], select + 1, target);
530
531         imen_unlock();
532
533         /*
534          * We only deal with vectored interrupts here.  ? documentation is
535          * lacking, I'm guessing an interrupt type of 0 is the 'INT' type,
536          * vs ExTINT, etc.
537          *
538          * This test also catches unconfigured pins.
539          */
540         if (apic_int_type(apic, pin) != 0)
541                 return;
542
543         /*
544          * Leave the pin unprogrammed if it does not correspond to
545          * an IRQ.
546          */
547         irq = apic_irq(apic, pin);
548         if (irq < 0)
549                 return;
550         
551         /* determine the bus type for this pin */
552         bus = apic_src_bus_id(apic, pin);
553         if (bus < 0)
554                 return;
555         bustype = apic_bus_type(bus);
556         
557         if ((bustype == ISA) &&
558             (pin < IOAPIC_ISA_INTS) && 
559             (irq == pin) &&
560             (apic_polarity(apic, pin) == 0x1) &&
561             (apic_trigger(apic, pin) == 0x3)) {
562                 /* 
563                  * A broken BIOS might describe some ISA 
564                  * interrupts as active-high level-triggered.
565                  * Use default ISA flags for those interrupts.
566                  */
567                 flags = DEFAULT_ISA_FLAGS;
568         } else {
569                 /* 
570                  * Program polarity and trigger mode according to 
571                  * interrupt entry.
572                  */
573                 flags = DEFAULT_FLAGS;
574                 level = trigger(apic, pin, &flags);
575                 if (level == 1)
576                         int_to_apicintpin[irq].flags |= IOAPIC_IM_FLAG_LEVEL;
577                 polarity(apic, pin, &flags, level);
578         }
579
580         cpuid = 0;
581         ksnprintf(envpath, sizeof(envpath), "hw.irq.%d.dest", irq);
582         kgetenv_int(envpath, &cpuid);
583
584         /* ncpus may not be available yet */
585         if (cpuid > mp_naps)
586                 cpuid = 0;
587
588         if (bootverbose) {
589                 kprintf("IOAPIC #%d intpin %d -> irq %d (CPU%d)\n",
590                        apic, pin, irq, cpuid);
591         }
592
593         /*
594          * Program the appropriate registers.  This routing may be 
595          * overridden when an interrupt handler for a device is
596          * actually added (see register_int(), which calls through
597          * the MACHINTR ABI to set up an interrupt handler/vector).
598          *
599          * The order in which we must program the two registers for
600          * safety is unclear! XXX
601          */
602         imen_lock();
603
604         vector = IDT_OFFSET + irq;                      /* IDT vec */
605         target = ioapic_read(ioapic[apic], select + 1) & IOART_HI_DEST_RESV;
606         /* Deliver all interrupts to CPU0 (BSP) */
607         target |= (CPU_TO_ID(cpuid) << IOART_HI_DEST_SHIFT) &
608                   IOART_HI_DEST_MASK;
609         flags |= ioapic_read(ioapic[apic], select) & IOART_RESV;
610         ioapic_write(ioapic[apic], select, flags | vector);
611         ioapic_write(ioapic[apic], select + 1, target);
612
613         imen_unlock();
614 }
615
616 int
617 io_apic_setup(int apic)
618 {
619         int             maxpin;
620         int             pin;
621
622         maxpin = REDIRCNT_IOAPIC(apic);         /* pins in APIC */
623         kprintf("Programming %d pins in IOAPIC #%d\n", maxpin, apic);
624         
625         for (pin = 0; pin < maxpin; ++pin) {
626                 io_apic_setup_intpin(apic, pin);
627         }
628         while (pin < 32) {
629                 if (apic_int_type(apic, pin) >= 0) {
630                         kprintf("Warning: IOAPIC #%d pin %d does not exist,"
631                                 " cannot program!\n", apic, pin);
632                 }
633                 ++pin;
634         }
635
636         /* return GOOD status */
637         return 0;
638 }
639 #undef DEFAULT_ISA_FLAGS
640 #undef DEFAULT_FLAGS
641
642
643 #define DEFAULT_EXTINT_FLAGS    \
644         ((u_int32_t)            \
645          (IOART_INTMSET |       \
646           IOART_TRGREDG |       \
647           IOART_INTAHI |        \
648           IOART_DESTPHY |       \
649           IOART_DELLOPRI))
650
651 /*
652  * XXX this function is only used by 8254 setup
653  * Setup the source of External INTerrupts.
654  */
655 int
656 ext_int_setup(int apic, int intr)
657 {
658         u_char  select;         /* the select register is 8 bits */
659         u_int32_t flags;        /* the window register is 32 bits */
660         u_int32_t target;       /* the window register is 32 bits */
661         u_int32_t vector;       /* the window register is 32 bits */
662         int cpuid;
663         char envpath[32];
664
665         if (apic_int_type(apic, intr) != 3)
666                 return -1;
667
668         cpuid = 0;
669         ksnprintf(envpath, sizeof(envpath), "hw.irq.%d.dest", intr);
670         kgetenv_int(envpath, &cpuid);
671
672         /* ncpus may not be available yet */
673         if (cpuid > mp_naps)
674                 cpuid = 0;
675
676         /* Deliver interrupts to CPU0 (BSP) */
677         target = (CPU_TO_ID(cpuid) << IOART_HI_DEST_SHIFT) &
678                  IOART_HI_DEST_MASK;
679         select = IOAPIC_REDTBL0 + (2 * intr);
680         vector = IDT_OFFSET + intr;
681         flags = DEFAULT_EXTINT_FLAGS;
682
683         ioapic_write(ioapic[apic], select, flags | vector);
684         ioapic_write(ioapic[apic], select + 1, target);
685
686         return 0;
687 }
688 #undef DEFAULT_EXTINT_FLAGS
689
690
691 /*
692  * Set the trigger level for an IO APIC pin.
693  */
694 static int
695 trigger(int apic, int pin, u_int32_t * flags)
696 {
697         int     id;
698         int     eirq;
699         int     level;
700         static int intcontrol = -1;
701
702         switch (apic_trigger(apic, pin)) {
703
704         case 0x00:
705                 break;
706
707         case 0x01:
708                 *flags &= ~IOART_TRGRLVL;       /* *flags |= IOART_TRGREDG */
709                 return 0;
710
711         case 0x03:
712                 *flags |= IOART_TRGRLVL;
713                 return 1;
714
715         case -1:
716         default:
717                 goto bad;
718         }
719
720         if ((id = apic_src_bus_id(apic, pin)) == -1)
721                 goto bad;
722
723         switch (apic_bus_type(id)) {
724         case ISA:
725                 *flags &= ~IOART_TRGRLVL;       /* *flags |= IOART_TRGREDG; */
726                 return 0;
727
728         case EISA:
729                 eirq = apic_src_bus_irq(apic, pin);
730
731                 if (eirq < 0 || eirq > 15) {
732                         kprintf("EISA IRQ %d?!?!\n", eirq);
733                         goto bad;
734                 }
735
736                 if (intcontrol == -1) {
737                         intcontrol = inb(ELCR1) << 8;
738                         intcontrol |= inb(ELCR0);
739                         kprintf("EISA INTCONTROL = %08x\n", intcontrol);
740                 }
741
742                 /* Use ELCR settings to determine level or edge mode */
743                 level = (intcontrol >> eirq) & 1;
744
745                 /*
746                  * Note that on older Neptune chipset based systems, any
747                  * pci interrupts often show up here and in the ELCR as well
748                  * as level sensitive interrupts attributed to the EISA bus.
749                  */
750
751                 if (level)
752                         *flags |= IOART_TRGRLVL;
753                 else
754                         *flags &= ~IOART_TRGRLVL;
755
756                 return level;
757
758         case PCI:
759                 *flags |= IOART_TRGRLVL;
760                 return 1;
761
762         case -1:
763         default:
764                 goto bad;
765         }
766
767 bad:
768         panic("bad APIC IO INT flags");
769 }
770
771
772 /*
773  * Set the polarity value for an IO APIC pin.
774  */
775 static void
776 polarity(int apic, int pin, u_int32_t * flags, int level)
777 {
778         int     id;
779
780         switch (apic_polarity(apic, pin)) {
781
782         case 0x00:
783                 break;
784
785         case 0x01:
786                 *flags &= ~IOART_INTALO;        /* *flags |= IOART_INTAHI */
787                 return;
788
789         case 0x03:
790                 *flags |= IOART_INTALO;
791                 return;
792
793         case -1:
794         default:
795                 goto bad;
796         }
797
798         if ((id = apic_src_bus_id(apic, pin)) == -1)
799                 goto bad;
800
801         switch (apic_bus_type(id)) {
802         case ISA:
803                 *flags &= ~IOART_INTALO;        /* *flags |= IOART_INTAHI */
804                 return;
805
806         case EISA:
807                 /* polarity converter always gives active high */
808                 *flags &= ~IOART_INTALO;
809                 return;
810
811         case PCI:
812                 *flags |= IOART_INTALO;
813                 return;
814
815         case -1:
816         default:
817                 goto bad;
818         }
819
820 bad:
821         panic("bad APIC IO INT flags");
822 }
823
824
825 /*
826  * Print contents of unmasked IRQs.
827  */
828 void
829 imen_dump(void)
830 {
831         int x;
832
833         kprintf("SMP: enabled INTs: ");
834         for (x = 0; x < APIC_INTMAPSIZE; ++x) {
835                 if ((int_to_apicintpin[x].flags & IOAPIC_IM_FLAG_MASKED) == 0)
836                         kprintf("%d ", x);
837         }
838         kprintf("\n");
839 }
840
841
842 /*
843  * Inter Processor Interrupt functions.
844  */
845
846 #endif  /* SMP APIC-IO */
847
848 /*
849  * Send APIC IPI 'vector' to 'destType' via 'deliveryMode'.
850  *
851  *  destType is 1 of: APIC_DEST_SELF, APIC_DEST_ALLISELF, APIC_DEST_ALLESELF
852  *  vector is any valid SYSTEM INT vector
853  *  delivery_mode is 1 of: APIC_DELMODE_FIXED, APIC_DELMODE_LOWPRIO
854  *
855  * A backlog of requests can create a deadlock between cpus.  To avoid this
856  * we have to be able to accept IPIs at the same time we are trying to send
857  * them.  The critical section prevents us from attempting to send additional
858  * IPIs reentrantly, but also prevents IPIQ processing so we have to call
859  * lwkt_process_ipiq() manually.  It's rather messy and expensive for this
860  * to occur but fortunately it does not happen too often.
861  */
862 int
863 apic_ipi(int dest_type, int vector, int delivery_mode)
864 {
865         u_long  icr_lo;
866
867         crit_enter();
868         if ((lapic.icr_lo & APIC_DELSTAT_MASK) != 0) {
869             unsigned int eflags = read_eflags();
870             cpu_enable_intr();
871             DEBUG_PUSH_INFO("apic_ipi");
872             while ((lapic.icr_lo & APIC_DELSTAT_MASK) != 0) {
873                 lwkt_process_ipiq();
874             }
875             DEBUG_POP_INFO();
876             write_eflags(eflags);
877         }
878
879         icr_lo = (lapic.icr_lo & APIC_ICRLO_RESV_MASK) | dest_type | 
880                 delivery_mode | vector;
881         lapic.icr_lo = icr_lo;
882         crit_exit();
883         return 0;
884 }
885
886 void
887 single_apic_ipi(int cpu, int vector, int delivery_mode)
888 {
889         u_long  icr_lo;
890         u_long  icr_hi;
891
892         crit_enter();
893         if ((lapic.icr_lo & APIC_DELSTAT_MASK) != 0) {
894             unsigned int eflags = read_eflags();
895             cpu_enable_intr();
896             DEBUG_PUSH_INFO("single_apic_ipi");
897             while ((lapic.icr_lo & APIC_DELSTAT_MASK) != 0) {
898                 lwkt_process_ipiq();
899             }
900             DEBUG_POP_INFO();
901             write_eflags(eflags);
902         }
903         icr_hi = lapic.icr_hi & ~APIC_ID_MASK;
904         icr_hi |= (CPU_TO_ID(cpu) << 24);
905         lapic.icr_hi = icr_hi;
906
907         /* build ICR_LOW */
908         icr_lo = (lapic.icr_lo & APIC_ICRLO_RESV_MASK)
909             | APIC_DEST_DESTFLD | delivery_mode | vector;
910
911         /* write APIC ICR */
912         lapic.icr_lo = icr_lo;
913         crit_exit();
914 }
915
916 #if 0   
917
918 /*
919  * Returns 0 if the apic is busy, 1 if we were able to queue the request.
920  *
921  * NOT WORKING YET!  The code as-is may end up not queueing an IPI at all
922  * to the target, and the scheduler does not 'poll' for IPI messages.
923  */
924 int
925 single_apic_ipi_passive(int cpu, int vector, int delivery_mode)
926 {
927         u_long  icr_lo;
928         u_long  icr_hi;
929
930         crit_enter();
931         if ((lapic.icr_lo & APIC_DELSTAT_MASK) != 0) {
932             crit_exit();
933             return(0);
934         }
935         icr_hi = lapic.icr_hi & ~APIC_ID_MASK;
936         icr_hi |= (CPU_TO_ID(cpu) << 24);
937         lapic.icr_hi = icr_hi;
938
939         /* build IRC_LOW */
940         icr_lo = (lapic.icr_lo & APIC_RESV2_MASK)
941             | APIC_DEST_DESTFLD | delivery_mode | vector;
942
943         /* write APIC ICR */
944         lapic.icr_lo = icr_lo;
945         crit_exit();
946         return(1);
947 }
948
949 #endif
950
951 /*
952  * Send APIC IPI 'vector' to 'target's via 'delivery_mode'.
953  *
954  * target is a bitmask of destination cpus.  Vector is any
955  * valid system INT vector.  Delivery mode may be either
956  * APIC_DELMODE_FIXED or APIC_DELMODE_LOWPRIO.
957  */
958 void
959 selected_apic_ipi(cpumask_t target, int vector, int delivery_mode)
960 {
961         crit_enter();
962         while (target) {
963                 int n = BSFCPUMASK(target);
964                 target &= ~CPUMASK(n);
965                 single_apic_ipi(n, vector, delivery_mode);
966         }
967         crit_exit();
968 }
969
970 /*
971  * Timer code, in development...
972  *  - suggested by rgrimes@gndrsh.aac.dev.com
973  */
974 int
975 get_apic_timer_frequency(void)
976 {
977         return(lapic_cputimer_intr.freq);
978 }
979
980 /*
981  * Load a 'downcount time' in uSeconds.
982  */
983 void
984 set_apic_timer(int us)
985 {
986         u_int count;
987
988         /*
989          * When we reach here, lapic timer's frequency
990          * must have been calculated as well as the
991          * divisor (lapic.dcr_timer is setup during the
992          * divisor calculation).
993          */
994         KKASSERT(lapic_cputimer_intr.freq != 0 &&
995                  lapic_timer_divisor_idx >= 0);
996
997         count = ((us * (int64_t)lapic_cputimer_intr.freq) + 999999) / 1000000;
998         lapic_timer_oneshot(count);
999 }
1000
1001
1002 /*
1003  * Read remaining time in timer.
1004  */
1005 int
1006 read_apic_timer(void)
1007 {
1008 #if 0
1009         /** XXX FIXME: we need to return the actual remaining time,
1010          *         for now we just return the remaining count.
1011          */
1012 #else
1013         return lapic.ccr_timer;
1014 #endif
1015 }
1016
1017
1018 /*
1019  * Spin-style delay, set delay time in uS, spin till it drains.
1020  */
1021 void
1022 u_sleep(int count)
1023 {
1024         set_apic_timer(count);
1025         while (read_apic_timer())
1026                  /* spin */ ;
1027 }
1028
1029 void
1030 lapic_map(vm_offset_t lapic_addr)
1031 {
1032         /* Local apic is mapped on last page */
1033         SMPpt[NPTEPG - 1] = (pt_entry_t)(PG_V | PG_RW | PG_N |
1034             pmap_get_pgeflag() | (lapic_addr & PG_FRAME));
1035
1036         kprintf("lapic: at %p\n", (void *)lapic_addr);
1037 }
1038
1039 static TAILQ_HEAD(, lapic_enumerator) lapic_enumerators =
1040         TAILQ_HEAD_INITIALIZER(lapic_enumerators);
1041
1042 void
1043 lapic_config(void)
1044 {
1045         struct lapic_enumerator *e;
1046         int error;
1047
1048         TAILQ_FOREACH(e, &lapic_enumerators, lapic_link) {
1049                 error = e->lapic_probe(e);
1050                 if (!error)
1051                         break;
1052         }
1053         if (e == NULL)
1054                 panic("can't config lapic\n");
1055
1056         e->lapic_enumerate(e);
1057 }
1058
1059 void
1060 lapic_enumerator_register(struct lapic_enumerator *ne)
1061 {
1062         struct lapic_enumerator *e;
1063
1064         TAILQ_FOREACH(e, &lapic_enumerators, lapic_link) {
1065                 if (e->lapic_prio < ne->lapic_prio) {
1066                         TAILQ_INSERT_BEFORE(e, ne, lapic_link);
1067                         return;
1068                 }
1069         }
1070         TAILQ_INSERT_TAIL(&lapic_enumerators, ne, lapic_link);
1071 }
1072
1073 static TAILQ_HEAD(, ioapic_enumerator) ioapic_enumerators =
1074         TAILQ_HEAD_INITIALIZER(ioapic_enumerators);
1075
1076 void
1077 ioapic_config(void)
1078 {
1079         struct ioapic_enumerator *e;
1080         int error, i;
1081
1082         TAILQ_INIT(&ioapic_conf.ioc_list);
1083         /* XXX magic number */
1084         for (i = 0; i < 16; ++i)
1085                 ioapic_conf.ioc_intsrc[i] = -1;
1086
1087         TAILQ_FOREACH(e, &ioapic_enumerators, ioapic_link) {
1088                 error = e->ioapic_probe(e);
1089                 if (!error)
1090                         break;
1091         }
1092         if (e == NULL) {
1093 #ifdef notyet
1094                 panic("can't config I/O APIC\n");
1095 #else
1096                 kprintf("no I/O APIC\n");
1097                 return;
1098 #endif
1099         }
1100
1101         e->ioapic_enumerate(e);
1102
1103         if (!ioapic_use_old) {
1104                 struct ioapic_info *info;
1105
1106                 /*
1107                  * Fixup the rest of the fields of ioapic_info
1108                  */
1109                 i = 0;
1110                 TAILQ_FOREACH(info, &ioapic_conf.ioc_list, io_link) {
1111                         const struct ioapic_info *prev_info;
1112
1113                         info->io_idx = i++;
1114                         info->io_apic_id = info->io_idx + lapic_id_max + 1;
1115
1116                         if (bootverbose) {
1117                                 kprintf("IOAPIC: idx %d, apic id %d, "
1118                                         "gsi base %d, npin %d\n",
1119                                         info->io_idx,
1120                                         info->io_apic_id,
1121                                         info->io_gsi_base,
1122                                         info->io_npin);
1123                         }
1124
1125                         /* Warning about possible GSI hole */
1126                         prev_info = TAILQ_PREV(info, ioapic_info_list, io_link);
1127                         if (prev_info != NULL) {
1128                                 if (info->io_gsi_base !=
1129                                 prev_info->io_gsi_base + prev_info->io_npin) {
1130                                         kprintf("IOAPIC: warning gsi hole "
1131                                                 "[%d, %d]\n",
1132                                                 prev_info->io_gsi_base +
1133                                                 prev_info->io_npin,
1134                                                 info->io_gsi_base - 1);
1135                                 }
1136                         }
1137                 }
1138
1139                 /*
1140                  * Setup all I/O APIC
1141                  */
1142                 TAILQ_FOREACH(info, &ioapic_conf.ioc_list, io_link)
1143                         ioapic_setup(info);
1144
1145                 panic("ioapic_config: new ioapic not working yet\n");
1146         }
1147 }
1148
1149 void
1150 ioapic_enumerator_register(struct ioapic_enumerator *ne)
1151 {
1152         struct ioapic_enumerator *e;
1153
1154         TAILQ_FOREACH(e, &ioapic_enumerators, ioapic_link) {
1155                 if (e->ioapic_prio < ne->ioapic_prio) {
1156                         TAILQ_INSERT_BEFORE(e, ne, ioapic_link);
1157                         return;
1158                 }
1159         }
1160         TAILQ_INSERT_TAIL(&ioapic_enumerators, ne, ioapic_link);
1161 }
1162
1163 void
1164 ioapic_add(void *addr, int gsi_base, int npin)
1165 {
1166         struct ioapic_info *info, *ninfo;
1167         int gsi_end;
1168
1169         gsi_end = gsi_base + npin - 1;
1170         TAILQ_FOREACH(info, &ioapic_conf.ioc_list, io_link) {
1171                 if ((gsi_base >= info->io_gsi_base &&
1172                      gsi_base < info->io_gsi_base + info->io_npin) ||
1173                     (gsi_end >= info->io_gsi_base &&
1174                      gsi_end < info->io_gsi_base + info->io_npin)) {
1175                         panic("ioapic_add: overlapped gsi, base %d npin %d, "
1176                               "hit base %d, npin %d\n", gsi_base, npin,
1177                               info->io_gsi_base, info->io_npin);
1178                 }
1179                 if (info->io_addr == addr)
1180                         panic("ioapic_add: duplicated addr %p\n", addr);
1181         }
1182
1183         ninfo = kmalloc(sizeof(*ninfo), M_DEVBUF, M_WAITOK | M_ZERO);
1184         ninfo->io_addr = addr;
1185         ninfo->io_npin = npin;
1186         ninfo->io_gsi_base = gsi_base;
1187
1188         /*
1189          * Create IOAPIC list in ascending order of GSI base
1190          */
1191         TAILQ_FOREACH_REVERSE(info, &ioapic_conf.ioc_list,
1192             ioapic_info_list, io_link) {
1193                 if (ninfo->io_gsi_base > info->io_gsi_base) {
1194                         TAILQ_INSERT_AFTER(&ioapic_conf.ioc_list,
1195                             info, ninfo, io_link);
1196                         break;
1197                 }
1198         }
1199         if (info == NULL)
1200                 TAILQ_INSERT_HEAD(&ioapic_conf.ioc_list, ninfo, io_link);
1201 }
1202
1203 void
1204 ioapic_intsrc(int irq, int gsi)
1205 {
1206         KKASSERT(irq < 16);
1207         if (ioapic_conf.ioc_intsrc[irq] != -1 &&
1208             ioapic_conf.ioc_intsrc[irq] != gsi) {
1209                 kprintf("IOAPIC: warning intsrc irq %d, gsi %d -> gsi %d\n",
1210                         irq, ioapic_conf.ioc_intsrc[irq], gsi);
1211         }
1212         ioapic_conf.ioc_intsrc[irq] = gsi;
1213 }
1214
1215 static void
1216 ioapic_set_apic_id(const struct ioapic_info *info)
1217 {
1218         uint32_t id;
1219
1220         id = ioapic_read(info->io_addr, IOAPIC_ID);
1221
1222         id &= ~APIC_ID_MASK;
1223         id |= (info->io_apic_id << 24);
1224
1225         ioapic_write(info->io_addr, IOAPIC_ID, id);
1226
1227         /*
1228          * Re-read && test
1229          */
1230         id = ioapic_read(info->io_addr, IOAPIC_ID);
1231         if (((id & APIC_ID_MASK) >> 24) != info->io_apic_id) {
1232                 panic("ioapic_set_apic_id: can't set apic id to %d\n",
1233                       info->io_apic_id);
1234         }
1235 }
1236
1237 static void
1238 ioapic_gsi_setup(int gsi)
1239 {
1240         enum intr_trigger trig;
1241         enum intr_polarity pola;
1242         int irq;
1243
1244         for (irq = 0; irq < 16; ++irq) {
1245                 if (gsi == ioapic_conf.ioc_intsrc[irq]) {
1246                         trig = INTR_TRIGGER_EDGE;
1247                         pola = INTR_POLARITY_HIGH;
1248                         break;
1249                 }
1250         }
1251
1252         if (irq == 16) {
1253                 if (gsi == 0) {
1254                         /* TODO Program EXTINT */
1255                         return;
1256                 } else if (gsi < 16) {
1257                         trig = INTR_TRIGGER_EDGE;
1258                         pola = INTR_POLARITY_HIGH;
1259                 } else {
1260                         trig = INTR_TRIGGER_LEVEL;
1261                         pola = INTR_POLARITY_LOW;
1262                 }
1263                 irq = gsi;
1264         }
1265
1266 #if 0
1267         ioapic_abi_set_irqmap(irq, gsi, trig, pola);
1268 #endif
1269 }
1270
1271 void *
1272 ioapic_gsi_ioaddr(int gsi)
1273 {
1274         const struct ioapic_info *info;
1275
1276         info = ioapic_gsi_search(gsi);
1277         return info->io_addr;
1278 }
1279
1280 int
1281 ioapic_gsi_pin(int gsi)
1282 {
1283         const struct ioapic_info *info;
1284
1285         info = ioapic_gsi_search(gsi);
1286         return gsi - info->io_gsi_base;
1287 }
1288
1289 static const struct ioapic_info *
1290 ioapic_gsi_search(int gsi)
1291 {
1292         const struct ioapic_info *info;
1293
1294         TAILQ_FOREACH(info, &ioapic_conf.ioc_list, io_link) {
1295                 if (gsi >= info->io_gsi_base &&
1296                     gsi < info->io_gsi_base + info->io_npin)
1297                         return info;
1298         }
1299         panic("ioapic_gsi_search: no I/O APIC\n");
1300 }
1301
1302 static void
1303 ioapic_setup(const struct ioapic_info *info)
1304 {
1305         int i;
1306
1307         ioapic_set_apic_id(info);
1308
1309         for (i = 0; i < info->io_npin; ++i)
1310                 ioapic_gsi_setup(info->io_gsi_base + i);
1311 }