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