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