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