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