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