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