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