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