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