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