161995b465686be6ab46b273dfb12749968c5881
[dragonfly.git] / sys / platform / pc64 / x86_64 / mp_machdep.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/mp_machdep.c,v 1.115.2.15 2003/03/14 21:22:35 jhb Exp $
26  * $DragonFly: src/sys/platform/pc32/i386/mp_machdep.c,v 1.60 2008/06/07 12:03:52 mneumann Exp $
27  */
28
29 #include "opt_cpu.h"
30
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/sysctl.h>
35 #include <sys/malloc.h>
36 #include <sys/memrange.h>
37 #include <sys/cons.h>   /* cngetc() */
38 #include <sys/machintr.h>
39
40 #include <sys/mplock2.h>
41
42 #include <vm/vm.h>
43 #include <vm/vm_param.h>
44 #include <vm/pmap.h>
45 #include <vm/vm_kern.h>
46 #include <vm/vm_extern.h>
47 #include <sys/lock.h>
48 #include <vm/vm_map.h>
49 #include <sys/user.h>
50 #ifdef GPROF 
51 #include <sys/gmon.h>
52 #endif
53
54 #include <machine/smp.h>
55 #include <machine_base/apic/apicreg.h>
56 #include <machine/atomic.h>
57 #include <machine/cpufunc.h>
58 #include <machine_base/apic/mpapic.h>
59 #include <machine/psl.h>
60 #include <machine/segments.h>
61 #include <machine/tss.h>
62 #include <machine/specialreg.h>
63 #include <machine/globaldata.h>
64 #include <machine/pmap_inval.h>
65
66 #include <machine/md_var.h>             /* setidt() */
67 #include <machine_base/icu/icu.h>       /* IPIs */
68 #include <machine/intr_machdep.h>       /* IPIs */
69
70 #define FIXUP_EXTRA_APIC_INTS   8       /* additional entries we may create */
71
72 #define WARMBOOT_TARGET         0
73 #define WARMBOOT_OFF            (KERNBASE + 0x0467)
74 #define WARMBOOT_SEG            (KERNBASE + 0x0469)
75
76 #define BIOS_BASE               (0xf0000)
77 #define BIOS_BASE2              (0xe0000)
78 #define BIOS_SIZE               (0x10000)
79 #define BIOS_COUNT              (BIOS_SIZE/4)
80
81 #define CMOS_REG                (0x70)
82 #define CMOS_DATA               (0x71)
83 #define BIOS_RESET              (0x0f)
84 #define BIOS_WARM               (0x0a)
85
86 #define PROCENTRY_FLAG_EN       0x01
87 #define PROCENTRY_FLAG_BP       0x02
88 #define IOAPICENTRY_FLAG_EN     0x01
89
90
91 /* MP Floating Pointer Structure */
92 typedef struct MPFPS {
93         char    signature[4];
94         u_int32_t pap;
95         u_char  length;
96         u_char  spec_rev;
97         u_char  checksum;
98         u_char  mpfb1;
99         u_char  mpfb2;
100         u_char  mpfb3;
101         u_char  mpfb4;
102         u_char  mpfb5;
103 }      *mpfps_t;
104
105 /* MP Configuration Table Header */
106 typedef struct MPCTH {
107         char    signature[4];
108         u_short base_table_length;
109         u_char  spec_rev;
110         u_char  checksum;
111         u_char  oem_id[8];
112         u_char  product_id[12];
113         u_int32_t oem_table_pointer;
114         u_short oem_table_size;
115         u_short entry_count;
116         u_int32_t apic_address;
117         u_short extended_table_length;
118         u_char  extended_table_checksum;
119         u_char  reserved;
120 }      *mpcth_t;
121
122
123 typedef struct PROCENTRY {
124         u_char  type;
125         u_char  apic_id;
126         u_char  apic_version;
127         u_char  cpu_flags;
128         u_int32_t cpu_signature;
129         u_int32_t feature_flags;
130         u_int32_t reserved1;
131         u_int32_t reserved2;
132 }      *proc_entry_ptr;
133
134 typedef struct BUSENTRY {
135         u_char  type;
136         u_char  bus_id;
137         char    bus_type[6];
138 }      *bus_entry_ptr;
139
140 typedef struct IOAPICENTRY {
141         u_char  type;
142         u_char  apic_id;
143         u_char  apic_version;
144         u_char  apic_flags;
145         u_int32_t apic_address;
146 }      *io_apic_entry_ptr;
147
148 typedef struct INTENTRY {
149         u_char  type;
150         u_char  int_type;
151         u_short int_flags;
152         u_char  src_bus_id;
153         u_char  src_bus_irq;
154         u_char  dst_apic_id;
155         u_char  dst_apic_int;
156 }      *int_entry_ptr;
157
158 /* descriptions of MP basetable entries */
159 typedef struct BASETABLE_ENTRY {
160         u_char  type;
161         u_char  length;
162         char    name[16];
163 }       basetable_entry;
164
165 struct mptable_pos {
166         mpfps_t         mp_fps;
167         mpcth_t         mp_cth;
168         vm_size_t       mp_cth_mapsz;   
169 };
170
171 #define MPTABLE_POS_USE_DEFAULT(mpt) \
172         ((mpt)->mp_fps->mpfb1 != 0 || (mpt)->mp_cth == NULL)
173
174 struct mptable_bus {
175         int             mb_id;
176         int             mb_type;        /* MPTABLE_BUS_ */
177         TAILQ_ENTRY(mptable_bus) mb_link;
178 };
179
180 #define MPTABLE_BUS_ISA         0
181 #define MPTABLE_BUS_PCI         1
182
183 struct mptable_bus_info {
184         TAILQ_HEAD(, mptable_bus) mbi_list;
185 };
186
187 struct mptable_pci_int {
188         int             mpci_bus;
189         int             mpci_dev;
190         int             mpci_pin;
191
192         int             mpci_ioapic_idx;
193         int             mpci_ioapic_pin;
194         TAILQ_ENTRY(mptable_pci_int) mpci_link;
195 };
196
197 struct mptable_ioapic {
198         int             mio_idx;
199         int             mio_apic_id;
200         uint32_t        mio_addr;
201         TAILQ_ENTRY(mptable_ioapic) mio_link;
202 };
203
204 typedef int     (*mptable_iter_func)(void *, const void *, int);
205
206 /*
207  * this code MUST be enabled here and in mpboot.s.
208  * it follows the very early stages of AP boot by placing values in CMOS ram.
209  * it NORMALLY will never be needed and thus the primitive method for enabling.
210  *
211  */
212 #if defined(CHECK_POINTS)
213 #define CHECK_READ(A)    (outb(CMOS_REG, (A)), inb(CMOS_DATA))
214 #define CHECK_WRITE(A,D) (outb(CMOS_REG, (A)), outb(CMOS_DATA, (D)))
215
216 #define CHECK_INIT(D);                          \
217         CHECK_WRITE(0x34, (D));                 \
218         CHECK_WRITE(0x35, (D));                 \
219         CHECK_WRITE(0x36, (D));                 \
220         CHECK_WRITE(0x37, (D));                 \
221         CHECK_WRITE(0x38, (D));                 \
222         CHECK_WRITE(0x39, (D));
223
224 #define CHECK_PRINT(S);                         \
225         kprintf("%s: %d, %d, %d, %d, %d, %d\n", \
226            (S),                                 \
227            CHECK_READ(0x34),                    \
228            CHECK_READ(0x35),                    \
229            CHECK_READ(0x36),                    \
230            CHECK_READ(0x37),                    \
231            CHECK_READ(0x38),                    \
232            CHECK_READ(0x39));
233
234 #else                           /* CHECK_POINTS */
235
236 #define CHECK_INIT(D)
237 #define CHECK_PRINT(S)
238
239 #endif                          /* CHECK_POINTS */
240
241 /*
242  * Values to send to the POST hardware.
243  */
244 #define MP_BOOTADDRESS_POST     0x10
245 #define MP_PROBE_POST           0x11
246 #define MPTABLE_PASS1_POST      0x12
247
248 #define MP_START_POST           0x13
249 #define MP_ENABLE_POST          0x14
250 #define MPTABLE_PASS2_POST      0x15
251
252 #define START_ALL_APS_POST      0x16
253 #define INSTALL_AP_TRAMP_POST   0x17
254 #define START_AP_POST           0x18
255
256 #define MP_ANNOUNCE_POST        0x19
257
258 /** XXX FIXME: where does this really belong, isa.h/isa.c perhaps? */
259 int     current_postcode;
260
261 /** XXX FIXME: what system files declare these??? */
262 extern struct region_descriptor r_gdt, r_idt;
263
264 int     mp_naps;                /* # of Applications processors */
265 #ifdef SMP /* APIC-IO */
266 static int      mp_nbusses;     /* # of busses */
267 int     mp_napics;              /* # of IO APICs */
268 vm_offset_t io_apic_address[NAPICID];   /* NAPICID is more than enough */
269 u_int32_t *io_apic_versions;
270 #endif
271 extern  int nkpt;
272
273 u_int32_t cpu_apic_versions[NAPICID];   /* populated during mptable scan */
274 int64_t tsc0_offset;
275 extern int64_t tsc_offsets[];
276
277 extern u_long ebda_addr;
278
279 #ifdef SMP /* APIC-IO */
280 struct apic_intmapinfo  int_to_apicintpin[APIC_INTMAPSIZE];
281 #endif
282
283 /*
284  * APIC ID logical/physical mapping structures.
285  * We oversize these to simplify boot-time config.
286  */
287 int     cpu_num_to_apic_id[NAPICID];
288 #ifdef SMP /* APIC-IO */
289 int     io_num_to_apic_id[NAPICID];
290 #endif
291 int     apic_id_to_logical[NAPICID];
292
293 /* AP uses this during bootstrap.  Do not staticize.  */
294 char *bootSTK;
295 static int bootAP;
296
297 struct pcb stoppcbs[MAXCPU];
298
299 extern inthand_t IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
300
301 static basetable_entry basetable_entry_types[] =
302 {
303         {0, 20, "Processor"},
304         {1, 8, "Bus"},
305         {2, 8, "I/O APIC"},
306         {3, 8, "I/O INT"},
307         {4, 8, "Local INT"}
308 };
309
310 /*
311  * Local data and functions.
312  */
313
314 static u_int    boot_address;
315 static u_int    base_memory;
316 static int      mp_finish;
317
318 static void     mp_enable(u_int boot_addr);
319
320 static int      mptable_iterate_entries(const mpcth_t,
321                     mptable_iter_func, void *);
322 static int      mptable_search(void);
323 static long     mptable_search_sig(u_int32_t target, int count);
324 static int      mptable_hyperthread_fixup(cpumask_t, int);
325 #ifdef SMP /* APIC-IO */
326 static void     mptable_pass1(struct mptable_pos *);
327 static void     mptable_pass2(struct mptable_pos *);
328 static void     mptable_default(int type);
329 static void     mptable_fix(void);
330 #endif
331 static int      mptable_map(struct mptable_pos *);
332 static void     mptable_unmap(struct mptable_pos *);
333 static void     mptable_imcr(struct mptable_pos *);
334 static void     mptable_bus_info_alloc(const mpcth_t,
335                     struct mptable_bus_info *);
336 static void     mptable_bus_info_free(struct mptable_bus_info *);
337
338 static int      mptable_lapic_probe(struct lapic_enumerator *);
339 static void     mptable_lapic_enumerate(struct lapic_enumerator *);
340 static void     mptable_lapic_default(void);
341
342 static int      mptable_ioapic_probe(struct ioapic_enumerator *);
343 static void     mptable_ioapic_enumerate(struct ioapic_enumerator *);
344
345 #ifdef SMP /* APIC-IO */
346 static void     setup_apic_irq_mapping(void);
347 static int      apic_int_is_bus_type(int intr, int bus_type);
348 #endif
349 static int      start_all_aps(u_int boot_addr);
350 #if 0
351 static void     install_ap_tramp(u_int boot_addr);
352 #endif
353 static int      start_ap(struct mdglobaldata *gd, u_int boot_addr, int smibest);
354 static int      smitest(void);
355
356 static cpumask_t smp_startup_mask = 1;  /* which cpus have been started */
357 cpumask_t smp_active_mask = 1;  /* which cpus are ready for IPIs etc? */
358 SYSCTL_INT(_machdep, OID_AUTO, smp_active, CTLFLAG_RD, &smp_active_mask, 0, "");
359 static u_int    bootMP_size;
360
361 static vm_paddr_t       mptable_fps_phyaddr;
362 static int              mptable_use_default;
363 static TAILQ_HEAD(mptable_pci_int_list, mptable_pci_int) mptable_pci_int_list =
364         TAILQ_HEAD_INITIALIZER(mptable_pci_int_list);
365 static TAILQ_HEAD(mptable_ioapic_list, mptable_ioapic) mptable_ioapic_list =
366         TAILQ_HEAD_INITIALIZER(mptable_ioapic_list);
367
368 /*
369  * Calculate usable address in base memory for AP trampoline code.
370  */
371 u_int
372 mp_bootaddress(u_int basemem)
373 {
374         POSTCODE(MP_BOOTADDRESS_POST);
375
376         base_memory = basemem;
377
378         bootMP_size = mptramp_end - mptramp_start;
379         boot_address = trunc_page(basemem * 1024); /* round down to 4k boundary */
380         if (((basemem * 1024) - boot_address) < bootMP_size)
381                 boot_address -= PAGE_SIZE;      /* not enough, lower by 4k */
382         /* 3 levels of page table pages */
383         mptramp_pagetables = boot_address - (PAGE_SIZE * 3);
384
385         return mptramp_pagetables;
386 }
387
388
389 static void
390 mptable_probe(void)
391 {
392         struct mptable_pos mpt;
393         int error;
394
395         KKASSERT(mptable_fps_phyaddr == 0);
396
397         mptable_fps_phyaddr = mptable_search();
398         if (mptable_fps_phyaddr == 0)
399                 return;
400
401         error = mptable_map(&mpt);
402         if (error) {
403                 mptable_fps_phyaddr = 0;
404                 return;
405         }
406
407         if (MPTABLE_POS_USE_DEFAULT(&mpt)) {
408                 kprintf("MPTABLE: use default configuration\n");
409                 mptable_use_default = 1;
410         }
411
412         mptable_unmap(&mpt);
413 }
414 SYSINIT(mptable_probe, SI_BOOT2_PRESMP, SI_ORDER_FIRST, mptable_probe, 0);
415
416 /*
417  * Look for an Intel MP spec table (ie, SMP capable hardware).
418  */
419 static int
420 mptable_search(void)
421 {
422         long    x;
423         u_int32_t target;
424  
425         POSTCODE(MP_PROBE_POST);
426
427         /* see if EBDA exists */
428         if (ebda_addr != 0) {
429                 /* search first 1K of EBDA */
430                 target = (u_int32_t)ebda_addr;
431                 if ((x = mptable_search_sig(target, 1024 / 4)) > 0)
432                         return x;
433         } else {
434                 /* last 1K of base memory, effective 'top of base' passed in */
435                 target = (u_int32_t)(base_memory - 0x400);
436                 if ((x = mptable_search_sig(target, 1024 / 4)) > 0)
437                         return x;
438         }
439
440         /* search the BIOS */
441         target = (u_int32_t)BIOS_BASE;
442         if ((x = mptable_search_sig(target, BIOS_COUNT)) > 0)
443                 return x;
444
445         /* search the extended BIOS */
446         target = (u_int32_t)BIOS_BASE2;
447         if ((x = mptable_search_sig(target, BIOS_COUNT)) > 0)
448                 return x;
449
450         /* nothing found */
451         return 0;
452 }
453
454 static int
455 mptable_iterate_entries(const mpcth_t cth, mptable_iter_func func, void *arg)
456 {
457         int count, total_size;
458         const void *position;
459
460         KKASSERT(cth->base_table_length >= sizeof(struct MPCTH));
461         total_size = cth->base_table_length - sizeof(struct MPCTH);
462         position = (const uint8_t *)cth + sizeof(struct MPCTH);
463         count = cth->entry_count;
464
465         while (count--) {
466                 int type, error;
467
468                 KKASSERT(total_size >= 0);
469                 if (total_size == 0) {
470                         kprintf("invalid base MP table, "
471                                 "entry count and length mismatch\n");
472                         return EINVAL;
473                 }
474
475                 type = *(const uint8_t *)position;
476                 switch (type) {
477                 case 0: /* processor_entry */
478                 case 1: /* bus_entry */
479                 case 2: /* io_apic_entry */
480                 case 3: /* int_entry */
481                 case 4: /* int_entry */
482                         break;
483                 default:
484                         kprintf("unknown base MP table entry type %d\n", type);
485                         return EINVAL;
486                 }
487
488                 if (total_size < basetable_entry_types[type].length) {
489                         kprintf("invalid base MP table length, "
490                                 "does not contain all entries\n");
491                         return EINVAL;
492                 }
493                 total_size -= basetable_entry_types[type].length;
494
495                 error = func(arg, position, type);
496                 if (error)
497                         return error;
498
499                 position = (const uint8_t *)position +
500                     basetable_entry_types[type].length;
501         }
502         return 0;
503 }
504
505
506 /*
507  * Startup the SMP processors.
508  */
509 void
510 mp_start(void)
511 {
512         POSTCODE(MP_START_POST);
513         mp_enable(boot_address);
514 }
515
516
517 /*
518  * Print various information about the SMP system hardware and setup.
519  */
520 void
521 mp_announce(void)
522 {
523         int     x;
524
525         POSTCODE(MP_ANNOUNCE_POST);
526
527         kprintf("DragonFly/MP: Multiprocessor motherboard\n");
528         kprintf(" cpu0 (BSP): apic id: %2d", CPU_TO_ID(0));
529         kprintf(", version: 0x%08x\n", cpu_apic_versions[0]);
530         for (x = 1; x <= mp_naps; ++x) {
531                 kprintf(" cpu%d (AP):  apic id: %2d", x, CPU_TO_ID(x));
532                 kprintf(", version: 0x%08x\n", cpu_apic_versions[x]);
533         }
534
535 if (apic_io_enable) {
536         for (x = 0; x < mp_napics; ++x) {
537                 kprintf(" io%d (APIC): apic id: %2d", x, IO_TO_ID(x));
538                 kprintf(", version: 0x%08x", io_apic_versions[x]);
539                 kprintf(", at 0x%08lx\n", io_apic_address[x]);
540         }
541 } else {
542         kprintf(" Warning: APIC I/O disabled\n");
543 }
544 }
545
546 /*
547  * AP cpu's call this to sync up protected mode.
548  *
549  * WARNING! %gs is not set up on entry.  This routine sets up %gs.
550  */
551 void
552 init_secondary(void)
553 {
554         int     gsel_tss;
555         int     x, myid = bootAP;
556         u_int64_t msr, cr0;
557         struct mdglobaldata *md;
558         struct privatespace *ps;
559
560         ps = &CPU_prvspace[myid];
561
562         gdt_segs[GPROC0_SEL].ssd_base =
563                 (long) &ps->mdglobaldata.gd_common_tss;
564         ps->mdglobaldata.mi.gd_prvspace = ps;
565
566         /* We fill the 32-bit segment descriptors */
567         for (x = 0; x < NGDT; x++) {
568                 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1))
569                         ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x]);
570         }
571         /* And now a 64-bit one */
572         ssdtosyssd(&gdt_segs[GPROC0_SEL],
573             (struct system_segment_descriptor *)&gdt[myid * NGDT + GPROC0_SEL]);
574
575         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
576         r_gdt.rd_base = (long) &gdt[myid * NGDT];
577         lgdt(&r_gdt);                   /* does magic intra-segment return */
578
579         /* lgdt() destroys the GSBASE value, so we load GSBASE after lgdt() */
580         wrmsr(MSR_FSBASE, 0);           /* User value */
581         wrmsr(MSR_GSBASE, (u_int64_t)ps);
582         wrmsr(MSR_KGSBASE, 0);          /* XXX User value while we're in the kernel */
583
584         lidt(&r_idt);
585
586 #if 0
587         lldt(_default_ldt);
588         mdcpu->gd_currentldt = _default_ldt;
589 #endif
590
591         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
592         gdt[myid * NGDT + GPROC0_SEL].sd_type = SDT_SYSTSS;
593
594         md = mdcpu;     /* loaded through %gs:0 (mdglobaldata.mi.gd_prvspace)*/
595
596         md->gd_common_tss.tss_rsp0 = 0; /* not used until after switch */
597 #if 0 /* JG XXX */
598         md->gd_common_tss.tss_ioopt = (sizeof md->gd_common_tss) << 16;
599 #endif
600         md->gd_tss_gdt = &gdt[myid * NGDT + GPROC0_SEL];
601         md->gd_common_tssd = *md->gd_tss_gdt;
602
603         /* double fault stack */
604         md->gd_common_tss.tss_ist1 =
605                 (long)&md->mi.gd_prvspace->idlestack[
606                         sizeof(md->mi.gd_prvspace->idlestack)];
607
608         ltr(gsel_tss);
609
610         /*
611          * Set to a known state:
612          * Set by mpboot.s: CR0_PG, CR0_PE
613          * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
614          */
615         cr0 = rcr0();
616         cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
617         load_cr0(cr0);
618
619         /* Set up the fast syscall stuff */
620         msr = rdmsr(MSR_EFER) | EFER_SCE;
621         wrmsr(MSR_EFER, msr);
622         wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
623         wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
624         msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
625               ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
626         wrmsr(MSR_STAR, msr);
627         wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
628
629         pmap_set_opt();         /* PSE/4MB pages, etc */
630 #if JGXXX
631         /* Initialize the PAT MSR. */
632         pmap_init_pat();
633 #endif
634
635         /* set up CPU registers and state */
636         cpu_setregs();
637
638         /* set up SSE/NX registers */
639         initializecpu();
640
641         /* set up FPU state on the AP */
642         npxinit(__INITIAL_NPXCW__);
643
644         /* disable the APIC, just to be SURE */
645         lapic->svr &= ~APIC_SVR_ENABLE;
646
647         /* data returned to BSP */
648         cpu_apic_versions[0] = lapic->version;
649 }
650
651 /*******************************************************************
652  * local functions and data
653  */
654
655 /*
656  * start the SMP system
657  */
658 static void
659 mp_enable(u_int boot_addr)
660 {
661         int     apic;
662         u_int   ux;
663         struct mptable_pos mpt;
664
665         POSTCODE(MP_ENABLE_POST);
666
667         lapic_config();
668
669         if (apic_io_enable)
670                 ioapic_config();
671
672         if (mptable_fps_phyaddr) {
673                 mptable_map(&mpt);
674                 mptable_imcr(&mpt);
675                 mptable_unmap(&mpt);
676         }
677 if (apic_io_enable) {
678
679         if (!mptable_fps_phyaddr)
680                 panic("no MP table, disable APIC_IO! (set hw.apic_io_enable=0)\n");
681
682         mptable_map(&mpt);
683
684         /*
685          * Examine the MP table for needed info
686          */
687         mptable_pass1(&mpt);
688         mptable_pass2(&mpt);
689
690         mptable_unmap(&mpt);
691
692         /* Post scan cleanup */
693         mptable_fix();
694
695         setup_apic_irq_mapping();
696
697         /* fill the LOGICAL io_apic_versions table */
698         for (apic = 0; apic < mp_napics; ++apic) {
699                 ux = ioapic_read(ioapic[apic], IOAPIC_VER);
700                 io_apic_versions[apic] = ux;
701                 io_apic_set_id(apic, IO_TO_ID(apic));
702         }
703
704         /* program each IO APIC in the system */
705         for (apic = 0; apic < mp_napics; ++apic)
706                 if (io_apic_setup(apic) < 0)
707                         panic("IO APIC setup failure");
708
709 }
710
711         /*
712          * These are required for SMP operation
713          */
714
715         /* install a 'Spurious INTerrupt' vector */
716         setidt(XSPURIOUSINT_OFFSET, Xspuriousint,
717                SDT_SYSIGT, SEL_KPL, 0);
718
719         /* install an inter-CPU IPI for TLB invalidation */
720         setidt(XINVLTLB_OFFSET, Xinvltlb,
721                SDT_SYSIGT, SEL_KPL, 0);
722
723         /* install an inter-CPU IPI for IPIQ messaging */
724         setidt(XIPIQ_OFFSET, Xipiq,
725                SDT_SYSIGT, SEL_KPL, 0);
726
727         /* install a timer vector */
728         setidt(XTIMER_OFFSET, Xtimer,
729                SDT_SYSIGT, SEL_KPL, 0);
730         
731         /* install an inter-CPU IPI for CPU stop/restart */
732         setidt(XCPUSTOP_OFFSET, Xcpustop,
733                SDT_SYSIGT, SEL_KPL, 0);
734
735         /* start each Application Processor */
736         start_all_aps(boot_addr);
737 }
738
739
740 /*
741  * look for the MP spec signature
742  */
743
744 /* string defined by the Intel MP Spec as identifying the MP table */
745 #define MP_SIG          0x5f504d5f      /* _MP_ */
746 #define NEXT(X)         ((X) += 4)
747 static long
748 mptable_search_sig(u_int32_t target, int count)
749 {
750         vm_size_t map_size;
751         u_int32_t *addr;
752         int x, ret;
753
754         KKASSERT(target != 0);
755
756         map_size = count * sizeof(u_int32_t);
757         addr = pmap_mapdev((vm_paddr_t)target, map_size);
758
759         ret = 0;
760         for (x = 0; x < count; NEXT(x)) {
761                 if (addr[x] == MP_SIG) {
762                         /* make array index a byte index */
763                         ret = target + (x * sizeof(u_int32_t));
764                         break;
765                 }
766         }
767
768         pmap_unmapdev((vm_offset_t)addr, map_size);
769         return ret;
770 }
771
772
773 typedef struct BUSDATA {
774         u_char  bus_id;
775         enum busTypes bus_type;
776 }       bus_datum;
777
778 typedef struct INTDATA {
779         u_char  int_type;
780         u_short int_flags;
781         u_char  src_bus_id;
782         u_char  src_bus_irq;
783         u_char  dst_apic_id;
784         u_char  dst_apic_int;
785         u_char  int_vector;
786 }       io_int, local_int;
787
788 typedef struct BUSTYPENAME {
789         u_char  type;
790         char    name[7];
791 }       bus_type_name;
792
793 static bus_type_name bus_type_table[] =
794 {
795         {CBUS, "CBUS"},
796         {CBUSII, "CBUSII"},
797         {EISA, "EISA"},
798         {MCA, "MCA"},
799         {UNKNOWN_BUSTYPE, "---"},
800         {ISA, "ISA"},
801         {MCA, "MCA"},
802         {UNKNOWN_BUSTYPE, "---"},
803         {UNKNOWN_BUSTYPE, "---"},
804         {UNKNOWN_BUSTYPE, "---"},
805         {UNKNOWN_BUSTYPE, "---"},
806         {UNKNOWN_BUSTYPE, "---"},
807         {PCI, "PCI"},
808         {UNKNOWN_BUSTYPE, "---"},
809         {UNKNOWN_BUSTYPE, "---"},
810         {UNKNOWN_BUSTYPE, "---"},
811         {UNKNOWN_BUSTYPE, "---"},
812         {XPRESS, "XPRESS"},
813         {UNKNOWN_BUSTYPE, "---"}
814 };
815
816 /* from MP spec v1.4, table 5-1 */
817 static int default_data[7][5] =
818 {
819 /*   nbus, id0, type0, id1, type1 */
820         {1, 0, ISA, 255, 255},
821         {1, 0, EISA, 255, 255},
822         {1, 0, EISA, 255, 255},
823         {1, 0, MCA, 255, 255},
824         {2, 0, ISA, 1, PCI},
825         {2, 0, EISA, 1, PCI},
826         {2, 0, MCA, 1, PCI}
827 };
828
829 /* the bus data */
830 static bus_datum *bus_data;
831
832 /* the IO INT data, one entry per possible APIC INTerrupt */
833 static io_int  *io_apic_ints;
834 static int nintrs;
835
836 static int processor_entry      (const struct PROCENTRY *entry, int cpu);
837 static int bus_entry            (const struct BUSENTRY *entry, int bus);
838 static int io_apic_entry        (const struct IOAPICENTRY *entry, int apic);
839 static int int_entry            (const struct INTENTRY *entry, int intr);
840 static int lookup_bus_type      (char *name);
841
842 static int
843 mptable_ioapic_pass1_callback(void *xarg, const void *pos, int type)
844 {
845         const struct IOAPICENTRY *ioapic_ent;
846
847         switch (type) {
848         case 1: /* bus_entry */
849                 ++mp_nbusses;
850                 break;
851
852         case 2: /* io_apic_entry */
853                 ioapic_ent = pos;
854                 if (ioapic_ent->apic_flags & IOAPICENTRY_FLAG_EN) {
855                         io_apic_address[mp_napics++] =
856                             (vm_offset_t)ioapic_ent->apic_address;
857                 }
858                 break;
859
860         case 3: /* int_entry */
861                 ++nintrs;
862                 break;
863         }
864         return 0;
865 }
866
867 /*
868  * 1st pass on motherboard's Intel MP specification table.
869  *
870  * determines:
871  *      io_apic_address[N]
872  *      mp_nbusses
873  *      mp_napics
874  *      nintrs
875  */
876 static void
877 mptable_pass1(struct mptable_pos *mpt)
878 {
879         mpfps_t fps;
880         int x;
881
882         POSTCODE(MPTABLE_PASS1_POST);
883
884         fps = mpt->mp_fps;
885         KKASSERT(fps != NULL);
886
887         /* clear various tables */
888         for (x = 0; x < NAPICID; ++x)
889                 io_apic_address[x] = ~0;        /* IO APIC address table */
890
891         mp_nbusses = 0;
892         mp_napics = 0;
893         nintrs = 0;
894
895         /* check for use of 'default' configuration */
896         if (fps->mpfb1 != 0) {
897                 io_apic_address[0] = DEFAULT_IO_APIC_BASE;
898                 mp_nbusses = default_data[fps->mpfb1 - 1][0];
899                 mp_napics = 1;
900                 nintrs = 16;
901         } else {
902                 int error;
903
904                 error = mptable_iterate_entries(mpt->mp_cth,
905                             mptable_ioapic_pass1_callback, NULL);
906                 if (error)
907                         panic("mptable_iterate_entries(ioapic_pass1) failed\n");
908         }
909 }
910
911 struct mptable_ioapic2_cbarg {
912         int     bus;
913         int     apic;
914         int     intr;
915 };
916
917 static int
918 mptable_ioapic_pass2_callback(void *xarg, const void *pos, int type)
919 {
920         struct mptable_ioapic2_cbarg *arg = xarg;
921
922         switch (type) {
923         case 1:
924                 if (bus_entry(pos, arg->bus))
925                         ++arg->bus;
926                 break;
927
928         case 2:
929                 if (io_apic_entry(pos, arg->apic))
930                         ++arg->apic;
931                 break;
932
933         case 3:
934                 if (int_entry(pos, arg->intr))
935                         ++arg->intr;
936                 break;
937         }
938         return 0;
939 }
940
941 /*
942  * 2nd pass on motherboard's Intel MP specification table.
943  *
944  * sets:
945  *      ID_TO_IO(N), phy APIC ID to log CPU/IO table
946  *      IO_TO_ID(N), logical IO to APIC ID table
947  *      bus_data[N]
948  *      io_apic_ints[N]
949  */
950 static void
951 mptable_pass2(struct mptable_pos *mpt)
952 {
953         struct mptable_ioapic2_cbarg arg;
954         mpfps_t fps;
955         int error, x;
956
957         POSTCODE(MPTABLE_PASS2_POST);
958
959         fps = mpt->mp_fps;
960         KKASSERT(fps != NULL);
961
962         MALLOC(io_apic_versions, u_int32_t *, sizeof(u_int32_t) * mp_napics,
963             M_DEVBUF, M_WAITOK);
964         MALLOC(ioapic, volatile ioapic_t **, sizeof(ioapic_t *) * mp_napics,
965             M_DEVBUF, M_WAITOK | M_ZERO);
966         MALLOC(io_apic_ints, io_int *, sizeof(io_int) * (nintrs + FIXUP_EXTRA_APIC_INTS),
967             M_DEVBUF, M_WAITOK);
968         MALLOC(bus_data, bus_datum *, sizeof(bus_datum) * mp_nbusses,
969             M_DEVBUF, M_WAITOK);
970
971         for (x = 0; x < mp_napics; x++)
972                 ioapic[x] = permanent_io_mapping(io_apic_address[x]);
973
974         /* clear various tables */
975         for (x = 0; x < NAPICID; ++x) {
976                 ID_TO_IO(x) = -1;       /* phy APIC ID to log CPU/IO table */
977                 IO_TO_ID(x) = -1;       /* logical IO to APIC ID table */
978         }
979
980         /* clear bus data table */
981         for (x = 0; x < mp_nbusses; ++x)
982                 bus_data[x].bus_id = 0xff;
983
984         /* clear IO APIC INT table */
985         for (x = 0; x < nintrs + FIXUP_EXTRA_APIC_INTS; ++x) {
986                 io_apic_ints[x].int_type = 0xff;
987                 io_apic_ints[x].int_vector = 0xff;
988         }
989
990         /* check for use of 'default' configuration */
991         if (fps->mpfb1 != 0) {
992                 mptable_default(fps->mpfb1);
993                 return;
994         }
995
996         bzero(&arg, sizeof(arg));
997         error = mptable_iterate_entries(mpt->mp_cth,
998                     mptable_ioapic_pass2_callback, &arg);
999         if (error)
1000                 panic("mptable_iterate_entries(ioapic_pass2) failed\n");
1001 }
1002
1003 /*
1004  * Check if we should perform a hyperthreading "fix-up" to
1005  * enumerate any logical CPU's that aren't already listed
1006  * in the table.
1007  *
1008  * XXX: We assume that all of the physical CPUs in the
1009  * system have the same number of logical CPUs.
1010  *
1011  * XXX: We assume that APIC ID's are allocated such that
1012  * the APIC ID's for a physical processor are aligned
1013  * with the number of logical CPU's in the processor.
1014  */
1015 static int
1016 mptable_hyperthread_fixup(cpumask_t id_mask, int cpu_count)
1017 {
1018         int i, id, lcpus_max, logical_cpus;
1019
1020         if ((cpu_feature & CPUID_HTT) == 0)
1021                 return 0;
1022
1023         lcpus_max = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
1024         if (lcpus_max <= 1)
1025                 return 0;
1026
1027         if (strcmp(cpu_vendor, "GenuineIntel") == 0) {
1028                 /*
1029                  * INSTRUCTION SET REFERENCE, A-M (#253666)
1030                  * Page 3-181, Table 3-20
1031                  * "The nearest power-of-2 integer that is not smaller
1032                  *  than EBX[23:16] is the number of unique initial APIC
1033                  *  IDs reserved for addressing different logical
1034                  *  processors in a physical package."
1035                  */
1036                 for (i = 0; ; ++i) {
1037                         if ((1 << i) >= lcpus_max) {
1038                                 lcpus_max = 1 << i;
1039                                 break;
1040                         }
1041                 }
1042         }
1043
1044         KKASSERT(cpu_count != 0);
1045         if (cpu_count == lcpus_max) {
1046                 /* We have nothing to fix */
1047                 return 0;
1048         } else if (cpu_count == 1) {
1049                 /* XXX this may be incorrect */
1050                 logical_cpus = lcpus_max;
1051         } else {
1052                 int cur, prev, dist;
1053
1054                 /*
1055                  * Calculate the distances between two nearest
1056                  * APIC IDs.  If all such distances are same,
1057                  * then it is the number of missing cpus that
1058                  * we are going to fill later.
1059                  */
1060                 dist = cur = prev = -1;
1061                 for (id = 0; id < MAXCPU; ++id) {
1062                         if ((id_mask & CPUMASK(id)) == 0)
1063                                 continue;
1064
1065                         cur = id;
1066                         if (prev >= 0) {
1067                                 int new_dist = cur - prev;
1068
1069                                 if (dist < 0)
1070                                         dist = new_dist;
1071
1072                                 /*
1073                                  * Make sure that all distances
1074                                  * between two nearest APIC IDs
1075                                  * are same.
1076                                  */
1077                                 if (dist != new_dist)
1078                                         return 0;
1079                         }
1080                         prev = cur;
1081                 }
1082                 if (dist == 1)
1083                         return 0;
1084
1085                 /* Must be power of 2 */
1086                 if (dist & (dist - 1))
1087                         return 0;
1088
1089                 /* Can't exceed CPU package capacity */
1090                 if (dist > lcpus_max)
1091                         logical_cpus = lcpus_max;
1092                 else
1093                         logical_cpus = dist;
1094         }
1095
1096         /*
1097          * For each APIC ID of a CPU that is set in the mask,
1098          * scan the other candidate APIC ID's for this
1099          * physical processor.  If any of those ID's are
1100          * already in the table, then kill the fixup.
1101          */
1102         for (id = 0; id < MAXCPU; id++) {
1103                 if ((id_mask & CPUMASK(id)) == 0)
1104                         continue;
1105                 /* First, make sure we are on a logical_cpus boundary. */
1106                 if (id % logical_cpus != 0)
1107                         return 0;
1108                 for (i = id + 1; i < id + logical_cpus; i++)
1109                         if ((id_mask & CPUMASK(i)) != 0)
1110                                 return 0;
1111         }
1112         return logical_cpus;
1113 }
1114
1115 static int
1116 mptable_map(struct mptable_pos *mpt)
1117 {
1118         mpfps_t fps = NULL;
1119         mpcth_t cth = NULL;
1120         vm_size_t cth_mapsz = 0;
1121
1122         KKASSERT(mptable_fps_phyaddr != 0);
1123
1124         bzero(mpt, sizeof(*mpt));
1125
1126         fps = pmap_mapdev(mptable_fps_phyaddr, sizeof(*fps));
1127         if (fps->pap != 0) {
1128                 /*
1129                  * Map configuration table header to get
1130                  * the base table size
1131                  */
1132                 cth = pmap_mapdev(fps->pap, sizeof(*cth));
1133                 cth_mapsz = cth->base_table_length;
1134                 pmap_unmapdev((vm_offset_t)cth, sizeof(*cth));
1135
1136                 if (cth_mapsz < sizeof(*cth)) {
1137                         kprintf("invalid base MP table length %d\n",
1138                                 (int)cth_mapsz);
1139                         pmap_unmapdev((vm_offset_t)fps, sizeof(*fps));
1140                         return EINVAL;
1141                 }
1142
1143                 /*
1144                  * Map the base table
1145                  */
1146                 cth = pmap_mapdev(fps->pap, cth_mapsz);
1147         }
1148
1149         mpt->mp_fps = fps;
1150         mpt->mp_cth = cth;
1151         mpt->mp_cth_mapsz = cth_mapsz;
1152
1153         return 0;
1154 }
1155
1156 static void
1157 mptable_unmap(struct mptable_pos *mpt)
1158 {
1159         if (mpt->mp_cth != NULL) {
1160                 pmap_unmapdev((vm_offset_t)mpt->mp_cth, mpt->mp_cth_mapsz);
1161                 mpt->mp_cth = NULL;
1162                 mpt->mp_cth_mapsz = 0;
1163         }
1164         if (mpt->mp_fps != NULL) {
1165                 pmap_unmapdev((vm_offset_t)mpt->mp_fps, sizeof(*mpt->mp_fps));
1166                 mpt->mp_fps = NULL;
1167         }
1168 }
1169
1170 void
1171 assign_apic_irq(int apic, int intpin, int irq)
1172 {
1173         int x;
1174         
1175         if (int_to_apicintpin[irq].ioapic != -1)
1176                 panic("assign_apic_irq: inconsistent table");
1177         
1178         int_to_apicintpin[irq].ioapic = apic;
1179         int_to_apicintpin[irq].int_pin = intpin;
1180         int_to_apicintpin[irq].apic_address = ioapic[apic];
1181         int_to_apicintpin[irq].redirindex = IOAPIC_REDTBL + 2 * intpin;
1182         
1183         for (x = 0; x < nintrs; x++) {
1184                 if ((io_apic_ints[x].int_type == 0 || 
1185                      io_apic_ints[x].int_type == 3) &&
1186                     io_apic_ints[x].int_vector == 0xff &&
1187                     io_apic_ints[x].dst_apic_id == IO_TO_ID(apic) &&
1188                     io_apic_ints[x].dst_apic_int == intpin)
1189                         io_apic_ints[x].int_vector = irq;
1190         }
1191 }
1192
1193 void
1194 revoke_apic_irq(int irq)
1195 {
1196         int x;
1197         int oldapic;
1198         int oldintpin;
1199         
1200         if (int_to_apicintpin[irq].ioapic == -1)
1201                 panic("revoke_apic_irq: inconsistent table");
1202         
1203         oldapic = int_to_apicintpin[irq].ioapic;
1204         oldintpin = int_to_apicintpin[irq].int_pin;
1205
1206         int_to_apicintpin[irq].ioapic = -1;
1207         int_to_apicintpin[irq].int_pin = 0;
1208         int_to_apicintpin[irq].apic_address = NULL;
1209         int_to_apicintpin[irq].redirindex = 0;
1210         
1211         for (x = 0; x < nintrs; x++) {
1212                 if ((io_apic_ints[x].int_type == 0 || 
1213                      io_apic_ints[x].int_type == 3) &&
1214                     io_apic_ints[x].int_vector != 0xff &&
1215                     io_apic_ints[x].dst_apic_id == IO_TO_ID(oldapic) &&
1216                     io_apic_ints[x].dst_apic_int == oldintpin)
1217                         io_apic_ints[x].int_vector = 0xff;
1218         }
1219 }
1220
1221 /*
1222  * Allocate an IRQ 
1223  */
1224 static void
1225 allocate_apic_irq(int intr)
1226 {
1227         int apic;
1228         int intpin;
1229         int irq;
1230         
1231         if (io_apic_ints[intr].int_vector != 0xff)
1232                 return;         /* Interrupt handler already assigned */
1233         
1234         if (io_apic_ints[intr].int_type != 0 &&
1235             (io_apic_ints[intr].int_type != 3 ||
1236              (io_apic_ints[intr].dst_apic_id == IO_TO_ID(0) &&
1237               io_apic_ints[intr].dst_apic_int == 0)))
1238                 return;         /* Not INT or ExtInt on != (0, 0) */
1239         
1240         irq = 0;
1241         while (irq < APIC_INTMAPSIZE &&
1242                int_to_apicintpin[irq].ioapic != -1)
1243                 irq++;
1244         
1245         if (irq >= APIC_INTMAPSIZE)
1246                 return;         /* No free interrupt handlers */
1247         
1248         apic = ID_TO_IO(io_apic_ints[intr].dst_apic_id);
1249         intpin = io_apic_ints[intr].dst_apic_int;
1250         
1251         assign_apic_irq(apic, intpin, irq);
1252 }
1253
1254
1255 static void
1256 swap_apic_id(int apic, int oldid, int newid)
1257 {
1258         int x;
1259         int oapic;
1260         
1261
1262         if (oldid == newid)
1263                 return;                 /* Nothing to do */
1264         
1265         kprintf("Changing APIC ID for IO APIC #%d from %d to %d in MP table\n",
1266                apic, oldid, newid);
1267         
1268         /* Swap physical APIC IDs in interrupt entries */
1269         for (x = 0; x < nintrs; x++) {
1270                 if (io_apic_ints[x].dst_apic_id == oldid)
1271                         io_apic_ints[x].dst_apic_id = newid;
1272                 else if (io_apic_ints[x].dst_apic_id == newid)
1273                         io_apic_ints[x].dst_apic_id = oldid;
1274         }
1275         
1276         /* Swap physical APIC IDs in IO_TO_ID mappings */
1277         for (oapic = 0; oapic < mp_napics; oapic++)
1278                 if (IO_TO_ID(oapic) == newid)
1279                         break;
1280         
1281         if (oapic < mp_napics) {
1282                 kprintf("Changing APIC ID for IO APIC #%d from "
1283                        "%d to %d in MP table\n",
1284                        oapic, newid, oldid);
1285                 IO_TO_ID(oapic) = oldid;
1286         }
1287         IO_TO_ID(apic) = newid;
1288 }
1289
1290
1291 static void
1292 fix_id_to_io_mapping(void)
1293 {
1294         int x;
1295
1296         for (x = 0; x < NAPICID; x++)
1297                 ID_TO_IO(x) = -1;
1298         
1299         for (x = 0; x <= mp_naps; x++) {
1300                 if ((u_int)CPU_TO_ID(x) < NAPICID)
1301                         ID_TO_IO(CPU_TO_ID(x)) = x;
1302         }
1303         
1304         for (x = 0; x < mp_napics; x++) {
1305                 if ((u_int)IO_TO_ID(x) < NAPICID)
1306                         ID_TO_IO(IO_TO_ID(x)) = x;
1307         }
1308 }
1309
1310
1311 static int
1312 first_free_apic_id(void)
1313 {
1314         int freeid, x;
1315         
1316         for (freeid = 0; freeid < NAPICID; freeid++) {
1317                 for (x = 0; x <= mp_naps; x++)
1318                         if (CPU_TO_ID(x) == freeid)
1319                                 break;
1320                 if (x <= mp_naps)
1321                         continue;
1322                 for (x = 0; x < mp_napics; x++)
1323                         if (IO_TO_ID(x) == freeid)
1324                                 break;
1325                 if (x < mp_napics)
1326                         continue;
1327                 return freeid;
1328         }
1329         return freeid;
1330 }
1331
1332
1333 static int
1334 io_apic_id_acceptable(int apic, int id)
1335 {
1336         int cpu;                /* Logical CPU number */
1337         int oapic;              /* Logical IO APIC number for other IO APIC */
1338
1339         if ((u_int)id >= NAPICID)
1340                 return 0;       /* Out of range */
1341         
1342         for (cpu = 0; cpu <= mp_naps; cpu++) {
1343                 if (CPU_TO_ID(cpu) == id)
1344                         return 0;       /* Conflict with CPU */
1345         }
1346         
1347         for (oapic = 0; oapic < mp_napics && oapic < apic; oapic++) {
1348                 if (IO_TO_ID(oapic) == id)
1349                         return 0;       /* Conflict with other APIC */
1350         }
1351         
1352         return 1;               /* ID is acceptable for IO APIC */
1353 }
1354
1355 static
1356 io_int *
1357 io_apic_find_int_entry(int apic, int pin)
1358 {
1359         int     x;
1360
1361         /* search each of the possible INTerrupt sources */
1362         for (x = 0; x < nintrs; ++x) {
1363                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1364                     (pin == io_apic_ints[x].dst_apic_int))
1365                         return (&io_apic_ints[x]);
1366         }
1367         return NULL;
1368 }
1369
1370 /*
1371  * parse an Intel MP specification table
1372  */
1373 static void
1374 mptable_fix(void)
1375 {
1376         int     x;
1377         int     id;
1378         int     apic;           /* IO APIC unit number */
1379         int     freeid;         /* Free physical APIC ID */
1380         int     physid;         /* Current physical IO APIC ID */
1381         io_int *io14;
1382         int     bus_0 = 0;      /* Stop GCC warning */
1383         int     bus_pci = 0;    /* Stop GCC warning */
1384         int     num_pci_bus;
1385
1386         /*
1387          * Fix mis-numbering of the PCI bus and its INT entries if the BIOS
1388          * did it wrong.  The MP spec says that when more than 1 PCI bus
1389          * exists the BIOS must begin with bus entries for the PCI bus and use
1390          * actual PCI bus numbering.  This implies that when only 1 PCI bus
1391          * exists the BIOS can choose to ignore this ordering, and indeed many
1392          * MP motherboards do ignore it.  This causes a problem when the PCI
1393          * sub-system makes requests of the MP sub-system based on PCI bus
1394          * numbers.     So here we look for the situation and renumber the
1395          * busses and associated INTs in an effort to "make it right".
1396          */
1397
1398         /* find bus 0, PCI bus, count the number of PCI busses */
1399         for (num_pci_bus = 0, x = 0; x < mp_nbusses; ++x) {
1400                 if (bus_data[x].bus_id == 0) {
1401                         bus_0 = x;
1402                 }
1403                 if (bus_data[x].bus_type == PCI) {
1404                         ++num_pci_bus;
1405                         bus_pci = x;
1406                 }
1407         }
1408         /*
1409          * bus_0 == slot of bus with ID of 0
1410          * bus_pci == slot of last PCI bus encountered
1411          */
1412
1413         /* check the 1 PCI bus case for sanity */
1414         /* if it is number 0 all is well */
1415         if (num_pci_bus == 1 &&
1416             bus_data[bus_pci].bus_id != 0) {
1417                 
1418                 /* mis-numbered, swap with whichever bus uses slot 0 */
1419
1420                 /* swap the bus entry types */
1421                 bus_data[bus_pci].bus_type = bus_data[bus_0].bus_type;
1422                 bus_data[bus_0].bus_type = PCI;
1423
1424                 /* swap each relevant INTerrupt entry */
1425                 id = bus_data[bus_pci].bus_id;
1426                 for (x = 0; x < nintrs; ++x) {
1427                         if (io_apic_ints[x].src_bus_id == id) {
1428                                 io_apic_ints[x].src_bus_id = 0;
1429                         }
1430                         else if (io_apic_ints[x].src_bus_id == 0) {
1431                                 io_apic_ints[x].src_bus_id = id;
1432                         }
1433                 }
1434         }
1435
1436         /* Assign IO APIC IDs.
1437          * 
1438          * First try the existing ID. If a conflict is detected, try
1439          * the ID in the MP table.  If a conflict is still detected, find
1440          * a free id.
1441          *
1442          * We cannot use the ID_TO_IO table before all conflicts has been
1443          * resolved and the table has been corrected.
1444          */
1445         for (apic = 0; apic < mp_napics; ++apic) { /* For all IO APICs */
1446                 
1447                 /* First try to use the value set by the BIOS */
1448                 physid = io_apic_get_id(apic);
1449                 if (io_apic_id_acceptable(apic, physid)) {
1450                         if (IO_TO_ID(apic) != physid)
1451                                 swap_apic_id(apic, IO_TO_ID(apic), physid);
1452                         continue;
1453                 }
1454
1455                 /* Then check if the value in the MP table is acceptable */
1456                 if (io_apic_id_acceptable(apic, IO_TO_ID(apic)))
1457                         continue;
1458
1459                 /* Last resort, find a free APIC ID and use it */
1460                 freeid = first_free_apic_id();
1461                 if (freeid >= NAPICID)
1462                         panic("No free physical APIC IDs found");
1463                 
1464                 if (io_apic_id_acceptable(apic, freeid)) {
1465                         swap_apic_id(apic, IO_TO_ID(apic), freeid);
1466                         continue;
1467                 }
1468                 panic("Free physical APIC ID not usable");
1469         }
1470         fix_id_to_io_mapping();
1471
1472         /* detect and fix broken Compaq MP table */
1473         if (apic_int_type(0, 0) == -1) {
1474                 kprintf("APIC_IO: MP table broken: 8259->APIC entry missing!\n");
1475                 io_apic_ints[nintrs].int_type = 3;      /* ExtInt */
1476                 io_apic_ints[nintrs].int_vector = 0xff; /* Unassigned */
1477                 /* XXX fixme, set src bus id etc, but it doesn't seem to hurt */
1478                 io_apic_ints[nintrs].dst_apic_id = IO_TO_ID(0);
1479                 io_apic_ints[nintrs].dst_apic_int = 0;  /* Pin 0 */
1480                 nintrs++;
1481         } else if (apic_int_type(0, 0) == 0) {
1482                 kprintf("APIC_IO: MP table broken: ExtINT entry corrupt!\n");
1483                 for (x = 0; x < nintrs; ++x)
1484                         if ((ID_TO_IO(io_apic_ints[x].dst_apic_id) == 0) &&
1485                             (io_apic_ints[x].dst_apic_int) == 0) {
1486                                 io_apic_ints[x].int_type = 3;
1487                                 io_apic_ints[x].int_vector = 0xff;
1488                                 break;
1489                         }
1490         }
1491
1492         /*
1493          * Fix missing IRQ 15 when IRQ 14 is an ISA interrupt.  IDE
1494          * controllers universally come in pairs.  If IRQ 14 is specified
1495          * as an ISA interrupt, then IRQ 15 had better be too.
1496          *
1497          * [ Shuttle XPC / AMD Athlon X2 ]
1498          *      The MPTable is missing an entry for IRQ 15.  Note that the
1499          *      ACPI table has an entry for both 14 and 15.
1500          */
1501         if (apic_int_type(0, 14) == 0 && apic_int_type(0, 15) == -1) {
1502                 kprintf("APIC_IO: MP table broken: IRQ 15 not ISA when IRQ 14 is!\n");
1503                 io14 = io_apic_find_int_entry(0, 14);
1504                 io_apic_ints[nintrs] = *io14;
1505                 io_apic_ints[nintrs].src_bus_irq = 15;
1506                 io_apic_ints[nintrs].dst_apic_int = 15;
1507                 nintrs++;
1508         }
1509 }
1510
1511 /* Assign low level interrupt handlers */
1512 static void
1513 setup_apic_irq_mapping(void)
1514 {
1515         int     x;
1516         int     int_vector;
1517
1518         /* Clear array */
1519         for (x = 0; x < APIC_INTMAPSIZE; x++) {
1520                 int_to_apicintpin[x].ioapic = -1;
1521                 int_to_apicintpin[x].int_pin = 0;
1522                 int_to_apicintpin[x].apic_address = NULL;
1523                 int_to_apicintpin[x].redirindex = 0;
1524
1525                 /* Default to masked */
1526                 int_to_apicintpin[x].flags = IOAPIC_IM_FLAG_MASKED;
1527         }
1528
1529         /* First assign ISA/EISA interrupts */
1530         for (x = 0; x < nintrs; x++) {
1531                 int_vector = io_apic_ints[x].src_bus_irq;
1532                 if (int_vector < APIC_INTMAPSIZE &&
1533                     io_apic_ints[x].int_vector == 0xff && 
1534                     int_to_apicintpin[int_vector].ioapic == -1 &&
1535                     (apic_int_is_bus_type(x, ISA) ||
1536                      apic_int_is_bus_type(x, EISA)) &&
1537                     io_apic_ints[x].int_type == 0) {
1538                         assign_apic_irq(ID_TO_IO(io_apic_ints[x].dst_apic_id), 
1539                                         io_apic_ints[x].dst_apic_int,
1540                                         int_vector);
1541                 }
1542         }
1543
1544         /* Assign ExtInt entry if no ISA/EISA interrupt 0 entry */
1545         for (x = 0; x < nintrs; x++) {
1546                 if (io_apic_ints[x].dst_apic_int == 0 &&
1547                     io_apic_ints[x].dst_apic_id == IO_TO_ID(0) &&
1548                     io_apic_ints[x].int_vector == 0xff && 
1549                     int_to_apicintpin[0].ioapic == -1 &&
1550                     io_apic_ints[x].int_type == 3) {
1551                         assign_apic_irq(0, 0, 0);
1552                         break;
1553                 }
1554         }
1555
1556         /* Assign PCI interrupts */
1557         for (x = 0; x < nintrs; ++x) {
1558                 if (io_apic_ints[x].int_type == 0 &&
1559                     io_apic_ints[x].int_vector == 0xff && 
1560                     apic_int_is_bus_type(x, PCI))
1561                         allocate_apic_irq(x);
1562         }
1563 }
1564
1565 void
1566 mp_set_cpuids(int cpu_id, int apic_id)
1567 {
1568         CPU_TO_ID(cpu_id) = apic_id;
1569         ID_TO_CPU(apic_id) = cpu_id;
1570 }
1571
1572 static int
1573 processor_entry(const struct PROCENTRY *entry, int cpu)
1574 {
1575         KKASSERT(cpu > 0);
1576
1577         /* check for usability */
1578         if (!(entry->cpu_flags & PROCENTRY_FLAG_EN))
1579                 return 0;
1580
1581         /* check for BSP flag */
1582         if (entry->cpu_flags & PROCENTRY_FLAG_BP) {
1583                 mp_set_cpuids(0, entry->apic_id);
1584                 return 0;       /* its already been counted */
1585         }
1586
1587         /* add another AP to list, if less than max number of CPUs */
1588         else if (cpu < MAXCPU) {
1589                 mp_set_cpuids(cpu, entry->apic_id);
1590                 return 1;
1591         }
1592
1593         return 0;
1594 }
1595
1596 static int
1597 bus_entry(const struct BUSENTRY *entry, int bus)
1598 {
1599         int     x;
1600         char    c, name[8];
1601
1602         /* encode the name into an index */
1603         for (x = 0; x < 6; ++x) {
1604                 if ((c = entry->bus_type[x]) == ' ')
1605                         break;
1606                 name[x] = c;
1607         }
1608         name[x] = '\0';
1609
1610         if ((x = lookup_bus_type(name)) == UNKNOWN_BUSTYPE)
1611                 panic("unknown bus type: '%s'", name);
1612
1613         bus_data[bus].bus_id = entry->bus_id;
1614         bus_data[bus].bus_type = x;
1615
1616         return 1;
1617 }
1618
1619 static int
1620 io_apic_entry(const struct IOAPICENTRY *entry, int apic)
1621 {
1622         if (!(entry->apic_flags & IOAPICENTRY_FLAG_EN))
1623                 return 0;
1624
1625         IO_TO_ID(apic) = entry->apic_id;
1626         ID_TO_IO(entry->apic_id) = apic;
1627
1628         return 1;
1629 }
1630
1631 static int
1632 lookup_bus_type(char *name)
1633 {
1634         int     x;
1635
1636         for (x = 0; x < MAX_BUSTYPE; ++x)
1637                 if (strcmp(bus_type_table[x].name, name) == 0)
1638                         return bus_type_table[x].type;
1639
1640         return UNKNOWN_BUSTYPE;
1641 }
1642
1643 static int
1644 int_entry(const struct INTENTRY *entry, int intr)
1645 {
1646         int apic;
1647
1648         io_apic_ints[intr].int_type = entry->int_type;
1649         io_apic_ints[intr].int_flags = entry->int_flags;
1650         io_apic_ints[intr].src_bus_id = entry->src_bus_id;
1651         io_apic_ints[intr].src_bus_irq = entry->src_bus_irq;
1652         if (entry->dst_apic_id == 255) {
1653                 /* This signal goes to all IO APICS.  Select an IO APIC
1654                    with sufficient number of interrupt pins */
1655                 for (apic = 0; apic < mp_napics; apic++)
1656                         if (((ioapic_read(ioapic[apic], IOAPIC_VER) & 
1657                               IOART_VER_MAXREDIR) >> MAXREDIRSHIFT) >= 
1658                             entry->dst_apic_int)
1659                                 break;
1660                 if (apic < mp_napics)
1661                         io_apic_ints[intr].dst_apic_id = IO_TO_ID(apic);
1662                 else
1663                         io_apic_ints[intr].dst_apic_id = entry->dst_apic_id;
1664         } else
1665                 io_apic_ints[intr].dst_apic_id = entry->dst_apic_id;
1666         io_apic_ints[intr].dst_apic_int = entry->dst_apic_int;
1667
1668         return 1;
1669 }
1670
1671 static int
1672 apic_int_is_bus_type(int intr, int bus_type)
1673 {
1674         int     bus;
1675
1676         for (bus = 0; bus < mp_nbusses; ++bus)
1677                 if ((bus_data[bus].bus_id == io_apic_ints[intr].src_bus_id)
1678                     && ((int) bus_data[bus].bus_type == bus_type))
1679                         return 1;
1680
1681         return 0;
1682 }
1683
1684 /*
1685  * Given a traditional ISA INT mask, return an APIC mask.
1686  */
1687 u_int
1688 isa_apic_mask(u_int isa_mask)
1689 {
1690         int isa_irq;
1691         int apic_pin;
1692
1693 #if defined(SKIP_IRQ15_REDIRECT)
1694         if (isa_mask == (1 << 15)) {
1695                 kprintf("skipping ISA IRQ15 redirect\n");
1696                 return isa_mask;
1697         }
1698 #endif  /* SKIP_IRQ15_REDIRECT */
1699
1700         isa_irq = ffs(isa_mask);                /* find its bit position */
1701         if (isa_irq == 0)                       /* doesn't exist */
1702                 return 0;
1703         --isa_irq;                              /* make it zero based */
1704
1705         apic_pin = isa_apic_irq(isa_irq);       /* look for APIC connection */
1706         if (apic_pin == -1)
1707                 return 0;
1708
1709         return (1 << apic_pin);                 /* convert pin# to a mask */
1710 }
1711
1712 /*
1713  * Determine which APIC pin an ISA/EISA INT is attached to.
1714  */
1715 #define INTTYPE(I)      (io_apic_ints[(I)].int_type)
1716 #define INTPIN(I)       (io_apic_ints[(I)].dst_apic_int)
1717 #define INTIRQ(I)       (io_apic_ints[(I)].int_vector)
1718 #define INTAPIC(I)      (ID_TO_IO(io_apic_ints[(I)].dst_apic_id))
1719
1720 #define SRCBUSIRQ(I)    (io_apic_ints[(I)].src_bus_irq)
1721 int
1722 isa_apic_irq(int isa_irq)
1723 {
1724         int     intr;
1725
1726         for (intr = 0; intr < nintrs; ++intr) {         /* check each record */
1727                 if (INTTYPE(intr) == 0) {               /* standard INT */
1728                         if (SRCBUSIRQ(intr) == isa_irq) {
1729                                 if (apic_int_is_bus_type(intr, ISA) ||
1730                                     apic_int_is_bus_type(intr, EISA)) {
1731                                         if (INTIRQ(intr) == 0xff)
1732                                                 return -1; /* unassigned */
1733                                         return INTIRQ(intr);    /* found */
1734                                 }
1735                         }
1736                 }
1737         }
1738         return -1;                                      /* NOT found */
1739 }
1740
1741
1742 /*
1743  * Determine which APIC pin a PCI INT is attached to.
1744  */
1745 #define SRCBUSID(I)     (io_apic_ints[(I)].src_bus_id)
1746 #define SRCBUSDEVICE(I) ((io_apic_ints[(I)].src_bus_irq >> 2) & 0x1f)
1747 #define SRCBUSLINE(I)   (io_apic_ints[(I)].src_bus_irq & 0x03)
1748 int
1749 pci_apic_irq(int pciBus, int pciDevice, int pciInt)
1750 {
1751         int     intr;
1752
1753         --pciInt;                                       /* zero based */
1754
1755         for (intr = 0; intr < nintrs; ++intr) {         /* check each record */
1756                 if ((INTTYPE(intr) == 0)                /* standard INT */
1757                     && (SRCBUSID(intr) == pciBus)
1758                     && (SRCBUSDEVICE(intr) == pciDevice)
1759                     && (SRCBUSLINE(intr) == pciInt)) {  /* a candidate IRQ */
1760                         if (apic_int_is_bus_type(intr, PCI)) {
1761                                 if (INTIRQ(intr) == 0xff) {
1762                                         kprintf("IOAPIC: pci_apic_irq() "
1763                                                 "failed\n");
1764                                         return -1;      /* unassigned */
1765                                 }
1766                                 return INTIRQ(intr);    /* exact match */
1767                         }
1768                 }
1769         }
1770
1771         return -1;                                      /* NOT found */
1772 }
1773
1774 int
1775 next_apic_irq(int irq) 
1776 {
1777         int intr, ointr;
1778         int bus, bustype;
1779
1780         bus = 0;
1781         bustype = 0;
1782         for (intr = 0; intr < nintrs; intr++) {
1783                 if (INTIRQ(intr) != irq || INTTYPE(intr) != 0)
1784                         continue;
1785                 bus = SRCBUSID(intr);
1786                 bustype = apic_bus_type(bus);
1787                 if (bustype != ISA &&
1788                     bustype != EISA &&
1789                     bustype != PCI)
1790                         continue;
1791                 break;
1792         }
1793         if (intr >= nintrs) {
1794                 return -1;
1795         }
1796         for (ointr = intr + 1; ointr < nintrs; ointr++) {
1797                 if (INTTYPE(ointr) != 0)
1798                         continue;
1799                 if (bus != SRCBUSID(ointr))
1800                         continue;
1801                 if (bustype == PCI) {
1802                         if (SRCBUSDEVICE(intr) != SRCBUSDEVICE(ointr))
1803                                 continue;
1804                         if (SRCBUSLINE(intr) != SRCBUSLINE(ointr))
1805                                 continue;
1806                 }
1807                 if (bustype == ISA || bustype == EISA) {
1808                         if (SRCBUSIRQ(intr) != SRCBUSIRQ(ointr))
1809                                 continue;
1810                 }
1811                 if (INTPIN(intr) == INTPIN(ointr))
1812                         continue;
1813                 break;
1814         }
1815         if (ointr >= nintrs) {
1816                 return -1;
1817         }
1818         return INTIRQ(ointr);
1819 }
1820 #undef SRCBUSLINE
1821 #undef SRCBUSDEVICE
1822 #undef SRCBUSID
1823 #undef SRCBUSIRQ
1824
1825 #undef INTPIN
1826 #undef INTIRQ
1827 #undef INTAPIC
1828 #undef INTTYPE
1829
1830 /*
1831  * Reprogram the MB chipset to NOT redirect an ISA INTerrupt.
1832  *
1833  * XXX FIXME:
1834  *  Exactly what this means is unclear at this point.  It is a solution
1835  *  for motherboards that redirect the MBIRQ0 pin.  Generically a motherboard
1836  *  could route any of the ISA INTs to upper (>15) IRQ values.  But most would
1837  *  NOT be redirected via MBIRQ0, thus "undirect()ing" them would NOT be an
1838  *  option.
1839  */
1840 int
1841 undirect_isa_irq(int rirq)
1842 {
1843 #if defined(READY)
1844         if (bootverbose)
1845             kprintf("Freeing redirected ISA irq %d.\n", rirq);
1846         /** FIXME: tickle the MB redirector chip */
1847         return /* XXX */;
1848 #else
1849         if (bootverbose)
1850             kprintf("Freeing (NOT implemented) redirected ISA irq %d.\n", rirq);
1851         return 0;
1852 #endif  /* READY */
1853 }
1854
1855
1856 /*
1857  * Reprogram the MB chipset to NOT redirect a PCI INTerrupt
1858  */
1859 int
1860 undirect_pci_irq(int rirq)
1861 {
1862 #if defined(READY)
1863         if (bootverbose)
1864                 kprintf("Freeing redirected PCI irq %d.\n", rirq);
1865
1866         /** FIXME: tickle the MB redirector chip */
1867         return /* XXX */;
1868 #else
1869         if (bootverbose)
1870                 kprintf("Freeing (NOT implemented) redirected PCI irq %d.\n",
1871                        rirq);
1872         return 0;
1873 #endif  /* READY */
1874 }
1875
1876
1877 /*
1878  * given a bus ID, return:
1879  *  the bus type if found
1880  *  -1 if NOT found
1881  */
1882 int
1883 apic_bus_type(int id)
1884 {
1885         int     x;
1886
1887         for (x = 0; x < mp_nbusses; ++x)
1888                 if (bus_data[x].bus_id == id)
1889                         return bus_data[x].bus_type;
1890
1891         return -1;
1892 }
1893
1894 /*
1895  * given a LOGICAL APIC# and pin#, return:
1896  *  the associated src bus ID if found
1897  *  -1 if NOT found
1898  */
1899 int
1900 apic_src_bus_id(int apic, int pin)
1901 {
1902         int     x;
1903
1904         /* search each of the possible INTerrupt sources */
1905         for (x = 0; x < nintrs; ++x)
1906                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1907                     (pin == io_apic_ints[x].dst_apic_int))
1908                         return (io_apic_ints[x].src_bus_id);
1909
1910         return -1;              /* NOT found */
1911 }
1912
1913 /*
1914  * given a LOGICAL APIC# and pin#, return:
1915  *  the associated src bus IRQ if found
1916  *  -1 if NOT found
1917  */
1918 int
1919 apic_src_bus_irq(int apic, int pin)
1920 {
1921         int     x;
1922
1923         for (x = 0; x < nintrs; x++)
1924                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1925                     (pin == io_apic_ints[x].dst_apic_int))
1926                         return (io_apic_ints[x].src_bus_irq);
1927
1928         return -1;              /* NOT found */
1929 }
1930
1931
1932 /*
1933  * given a LOGICAL APIC# and pin#, return:
1934  *  the associated INTerrupt type if found
1935  *  -1 if NOT found
1936  */
1937 int
1938 apic_int_type(int apic, int pin)
1939 {
1940         int     x;
1941
1942         /* search each of the possible INTerrupt sources */
1943         for (x = 0; x < nintrs; ++x) {
1944                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1945                     (pin == io_apic_ints[x].dst_apic_int))
1946                         return (io_apic_ints[x].int_type);
1947         }
1948         return -1;              /* NOT found */
1949 }
1950
1951 /*
1952  * Return the IRQ associated with an APIC pin
1953  */
1954 int 
1955 apic_irq(int apic, int pin)
1956 {
1957         int x;
1958         int res;
1959
1960         for (x = 0; x < nintrs; ++x) {
1961                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1962                     (pin == io_apic_ints[x].dst_apic_int)) {
1963                         res = io_apic_ints[x].int_vector;
1964                         if (res == 0xff)
1965                                 return -1;
1966                         if (apic != int_to_apicintpin[res].ioapic)
1967                                 panic("apic_irq: inconsistent table %d/%d", apic, int_to_apicintpin[res].ioapic);
1968                         if (pin != int_to_apicintpin[res].int_pin)
1969                                 panic("apic_irq inconsistent table (2)");
1970                         return res;
1971                 }
1972         }
1973         return -1;
1974 }
1975
1976
1977 /*
1978  * given a LOGICAL APIC# and pin#, return:
1979  *  the associated trigger mode if found
1980  *  -1 if NOT found
1981  */
1982 int
1983 apic_trigger(int apic, int pin)
1984 {
1985         int     x;
1986
1987         /* search each of the possible INTerrupt sources */
1988         for (x = 0; x < nintrs; ++x)
1989                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
1990                     (pin == io_apic_ints[x].dst_apic_int))
1991                         return ((io_apic_ints[x].int_flags >> 2) & 0x03);
1992
1993         return -1;              /* NOT found */
1994 }
1995
1996
1997 /*
1998  * given a LOGICAL APIC# and pin#, return:
1999  *  the associated 'active' level if found
2000  *  -1 if NOT found
2001  */
2002 int
2003 apic_polarity(int apic, int pin)
2004 {
2005         int     x;
2006
2007         /* search each of the possible INTerrupt sources */
2008         for (x = 0; x < nintrs; ++x)
2009                 if ((apic == ID_TO_IO(io_apic_ints[x].dst_apic_id)) &&
2010                     (pin == io_apic_ints[x].dst_apic_int))
2011                         return (io_apic_ints[x].int_flags & 0x03);
2012
2013         return -1;              /* NOT found */
2014 }
2015
2016 /*
2017  * set data according to MP defaults
2018  * FIXME: probably not complete yet...
2019  */
2020 static void
2021 mptable_default(int type)
2022 {
2023         int     io_apic_id;
2024         int     pin;
2025
2026 #if 0
2027         kprintf("  MP default config type: %d\n", type);
2028         switch (type) {
2029         case 1:
2030                 kprintf("   bus: ISA, APIC: 82489DX\n");
2031                 break;
2032         case 2:
2033                 kprintf("   bus: EISA, APIC: 82489DX\n");
2034                 break;
2035         case 3:
2036                 kprintf("   bus: EISA, APIC: 82489DX\n");
2037                 break;
2038         case 4:
2039                 kprintf("   bus: MCA, APIC: 82489DX\n");
2040                 break;
2041         case 5:
2042                 kprintf("   bus: ISA+PCI, APIC: Integrated\n");
2043                 break;
2044         case 6:
2045                 kprintf("   bus: EISA+PCI, APIC: Integrated\n");
2046                 break;
2047         case 7:
2048                 kprintf("   bus: MCA+PCI, APIC: Integrated\n");
2049                 break;
2050         default:
2051                 kprintf("   future type\n");
2052                 break;
2053                 /* NOTREACHED */
2054         }
2055 #endif  /* 0 */
2056
2057         /* one and only IO APIC */
2058         io_apic_id = (ioapic_read(ioapic[0], IOAPIC_ID) & APIC_ID_MASK) >> 24;
2059
2060         /*
2061          * sanity check, refer to MP spec section 3.6.6, last paragraph
2062          * necessary as some hardware isn't properly setting up the IO APIC
2063          */
2064 #if defined(REALLY_ANAL_IOAPICID_VALUE)
2065         if (io_apic_id != 2) {
2066 #else
2067         if ((io_apic_id == 0) || (io_apic_id == 1) || (io_apic_id == 15)) {
2068 #endif  /* REALLY_ANAL_IOAPICID_VALUE */
2069                 io_apic_set_id(0, 2);
2070                 io_apic_id = 2;
2071         }
2072         IO_TO_ID(0) = io_apic_id;
2073         ID_TO_IO(io_apic_id) = 0;
2074
2075         /* fill out bus entries */
2076         switch (type) {
2077         case 1:
2078         case 2:
2079         case 3:
2080         case 4:
2081         case 5:
2082         case 6:
2083         case 7:
2084                 bus_data[0].bus_id = default_data[type - 1][1];
2085                 bus_data[0].bus_type = default_data[type - 1][2];
2086                 bus_data[1].bus_id = default_data[type - 1][3];
2087                 bus_data[1].bus_type = default_data[type - 1][4];
2088                 break;
2089
2090         /* case 4: case 7:                 MCA NOT supported */
2091         default:                /* illegal/reserved */
2092                 panic("BAD default MP config: %d", type);
2093                 /* NOTREACHED */
2094         }
2095
2096         /* general cases from MP v1.4, table 5-2 */
2097         for (pin = 0; pin < 16; ++pin) {
2098                 io_apic_ints[pin].int_type = 0;
2099                 io_apic_ints[pin].int_flags = 0x05;     /* edge/active-hi */
2100                 io_apic_ints[pin].src_bus_id = 0;
2101                 io_apic_ints[pin].src_bus_irq = pin;    /* IRQ2 caught below */
2102                 io_apic_ints[pin].dst_apic_id = io_apic_id;
2103                 io_apic_ints[pin].dst_apic_int = pin;   /* 1-to-1 */
2104         }
2105
2106         /* special cases from MP v1.4, table 5-2 */
2107         if (type == 2) {
2108                 io_apic_ints[2].int_type = 0xff;        /* N/C */
2109                 io_apic_ints[13].int_type = 0xff;       /* N/C */
2110 #if !defined(APIC_MIXED_MODE)
2111                 /** FIXME: ??? */
2112                 panic("sorry, can't support type 2 default yet");
2113 #endif  /* APIC_MIXED_MODE */
2114         }
2115         else
2116                 io_apic_ints[2].src_bus_irq = 0;        /* ISA IRQ0 is on APIC INT 2 */
2117
2118         if (type == 7)
2119                 io_apic_ints[0].int_type = 0xff;        /* N/C */
2120         else
2121                 io_apic_ints[0].int_type = 3;   /* vectored 8259 */
2122 }
2123
2124 /*
2125  * Map a physical memory address representing I/O into KVA.  The I/O
2126  * block is assumed not to cross a page boundary.
2127  */
2128 void *
2129 permanent_io_mapping(vm_paddr_t pa)
2130 {
2131         KKASSERT(pa < 0x100000000LL);
2132
2133         return pmap_mapdev_uncacheable(pa, PAGE_SIZE);
2134 }
2135
2136 /*
2137  * start each AP in our list
2138  */
2139 static int
2140 start_all_aps(u_int boot_addr)
2141 {
2142         vm_offset_t va = boot_address + KERNBASE;
2143         u_int64_t *pt4, *pt3, *pt2;
2144         int     x, i, pg;
2145         int     shift;
2146         int     smicount;
2147         int     smibest;
2148         int     smilast;
2149         u_char  mpbiosreason;
2150         u_long  mpbioswarmvec;
2151         struct mdglobaldata *gd;
2152         struct privatespace *ps;
2153
2154         POSTCODE(START_ALL_APS_POST);
2155
2156         /* Initialize BSP's local APIC */
2157         apic_initialize(TRUE);
2158
2159         /* Finalize PIC */
2160         MachIntrABI.finalize();
2161
2162         /* install the AP 1st level boot code */
2163         pmap_kenter(va, boot_address);
2164         cpu_invlpg((void *)va);         /* JG XXX */
2165         bcopy(mptramp_start, (void *)va, bootMP_size);
2166
2167         /* Locate the page tables, they'll be below the trampoline */
2168         pt4 = (u_int64_t *)(uintptr_t)(mptramp_pagetables + KERNBASE);
2169         pt3 = pt4 + (PAGE_SIZE) / sizeof(u_int64_t);
2170         pt2 = pt3 + (PAGE_SIZE) / sizeof(u_int64_t);
2171
2172         /* Create the initial 1GB replicated page tables */
2173         for (i = 0; i < 512; i++) {
2174                 /* Each slot of the level 4 pages points to the same level 3 page */
2175                 pt4[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + PAGE_SIZE);
2176                 pt4[i] |= PG_V | PG_RW | PG_U;
2177
2178                 /* Each slot of the level 3 pages points to the same level 2 page */
2179                 pt3[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + (2 * PAGE_SIZE));
2180                 pt3[i] |= PG_V | PG_RW | PG_U;
2181
2182                 /* The level 2 page slots are mapped with 2MB pages for 1GB. */
2183                 pt2[i] = i * (2 * 1024 * 1024);
2184                 pt2[i] |= PG_V | PG_RW | PG_PS | PG_U;
2185         }
2186
2187         /* save the current value of the warm-start vector */
2188         mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
2189         outb(CMOS_REG, BIOS_RESET);
2190         mpbiosreason = inb(CMOS_DATA);
2191
2192         /* setup a vector to our boot code */
2193         *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
2194         *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
2195         outb(CMOS_REG, BIOS_RESET);
2196         outb(CMOS_DATA, BIOS_WARM);     /* 'warm-start' */
2197
2198         /*
2199          * If we have a TSC we can figure out the SMI interrupt rate.
2200          * The SMI does not necessarily use a constant rate.  Spend
2201          * up to 250ms trying to figure it out.
2202          */
2203         smibest = 0;
2204         if (cpu_feature & CPUID_TSC) {
2205                 set_apic_timer(275000);
2206                 smilast = read_apic_timer();
2207                 for (x = 0; x < 20 && read_apic_timer(); ++x) {
2208                         smicount = smitest();
2209                         if (smibest == 0 || smilast - smicount < smibest)
2210                                 smibest = smilast - smicount;
2211                         smilast = smicount;
2212                 }
2213                 if (smibest > 250000)
2214                         smibest = 0;
2215                 if (smibest) {
2216                         smibest = smibest * (int64_t)1000000 /
2217                                   get_apic_timer_frequency();
2218                 }
2219         }
2220         if (smibest)
2221                 kprintf("SMI Frequency (worst case): %d Hz (%d us)\n",
2222                         1000000 / smibest, smibest);
2223
2224         kprintf("SMP: Starting %d APs: ", mp_naps);
2225         /* start each AP */
2226         for (x = 1; x <= mp_naps; ++x) {
2227
2228                 /* This is a bit verbose, it will go away soon.  */
2229
2230                 /* first page of AP's private space */
2231                 pg = x * x86_64_btop(sizeof(struct privatespace));
2232
2233                 /* allocate new private data page(s) */
2234                 gd = (struct mdglobaldata *)kmem_alloc(&kernel_map, 
2235                                 MDGLOBALDATA_BASEALLOC_SIZE);
2236
2237                 gd = &CPU_prvspace[x].mdglobaldata;     /* official location */
2238                 bzero(gd, sizeof(*gd));
2239                 gd->mi.gd_prvspace = ps = &CPU_prvspace[x];
2240
2241                 /* prime data page for it to use */
2242                 mi_gdinit(&gd->mi, x);
2243                 cpu_gdinit(gd, x);
2244                 gd->mi.gd_ipiq = (void *)kmem_alloc(&kernel_map, sizeof(lwkt_ipiq) * (mp_naps + 1));
2245                 bzero(gd->mi.gd_ipiq, sizeof(lwkt_ipiq) * (mp_naps + 1));
2246
2247                 /* setup a vector to our boot code */
2248                 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
2249                 *((volatile u_short *) WARMBOOT_SEG) = (boot_addr >> 4);
2250                 outb(CMOS_REG, BIOS_RESET);
2251                 outb(CMOS_DATA, BIOS_WARM);     /* 'warm-start' */
2252
2253                 /*
2254                  * Setup the AP boot stack
2255                  */
2256                 bootSTK = &ps->idlestack[UPAGES*PAGE_SIZE/2];
2257                 bootAP = x;
2258
2259                 /* attempt to start the Application Processor */
2260                 CHECK_INIT(99); /* setup checkpoints */
2261                 if (!start_ap(gd, boot_addr, smibest)) {
2262                         kprintf("\nAP #%d (PHY# %d) failed!\n",
2263                                 x, CPU_TO_ID(x));
2264                         CHECK_PRINT("trace");   /* show checkpoints */
2265                         /* better panic as the AP may be running loose */
2266                         kprintf("panic y/n? [y] ");
2267                         if (cngetc() != 'n')
2268                                 panic("bye-bye");
2269                 }
2270                 CHECK_PRINT("trace");           /* show checkpoints */
2271
2272                 /* record its version info */
2273                 cpu_apic_versions[x] = cpu_apic_versions[0];
2274         }
2275
2276         /* set ncpus to 1 + highest logical cpu.  Not all may have come up */
2277         ncpus = x;
2278
2279         /* ncpus2 -- ncpus rounded down to the nearest power of 2 */
2280         for (shift = 0; (1 << shift) <= ncpus; ++shift)
2281                 ;
2282         --shift;
2283         ncpus2_shift = shift;
2284         ncpus2 = 1 << shift;
2285         ncpus2_mask = ncpus2 - 1;
2286
2287         /* ncpus_fit -- ncpus rounded up to the nearest power of 2 */
2288         if ((1 << shift) < ncpus)
2289                 ++shift;
2290         ncpus_fit = 1 << shift;
2291         ncpus_fit_mask = ncpus_fit - 1;
2292
2293         /* build our map of 'other' CPUs */
2294         mycpu->gd_other_cpus = smp_startup_mask & ~CPUMASK(mycpu->gd_cpuid);
2295         mycpu->gd_ipiq = (void *)kmem_alloc(&kernel_map, sizeof(lwkt_ipiq) * ncpus);
2296         bzero(mycpu->gd_ipiq, sizeof(lwkt_ipiq) * ncpus);
2297
2298         /* fill in our (BSP) APIC version */
2299         cpu_apic_versions[0] = lapic->version;
2300
2301         /* restore the warmstart vector */
2302         *(u_long *) WARMBOOT_OFF = mpbioswarmvec;
2303         outb(CMOS_REG, BIOS_RESET);
2304         outb(CMOS_DATA, mpbiosreason);
2305
2306         /*
2307          * NOTE!  The idlestack for the BSP was setup by locore.  Finish
2308          * up, clean out the P==V mapping we did earlier.
2309          */
2310         pmap_set_opt();
2311
2312         /* number of APs actually started */
2313         return ncpus - 1;
2314 }
2315
2316
2317 /*
2318  * load the 1st level AP boot code into base memory.
2319  */
2320
2321 /* targets for relocation */
2322 extern void bigJump(void);
2323 extern void bootCodeSeg(void);
2324 extern void bootDataSeg(void);
2325 extern void MPentry(void);
2326 extern u_int MP_GDT;
2327 extern u_int mp_gdtbase;
2328
2329 #if 0
2330
2331 static void
2332 install_ap_tramp(u_int boot_addr)
2333 {
2334         int     x;
2335         int     size = *(int *) ((u_long) & bootMP_size);
2336         u_char *src = (u_char *) ((u_long) bootMP);
2337         u_char *dst = (u_char *) boot_addr + KERNBASE;
2338         u_int   boot_base = (u_int) bootMP;
2339         u_int8_t *dst8;
2340         u_int16_t *dst16;
2341         u_int32_t *dst32;
2342
2343         POSTCODE(INSTALL_AP_TRAMP_POST);
2344
2345         for (x = 0; x < size; ++x)
2346                 *dst++ = *src++;
2347
2348         /*
2349          * modify addresses in code we just moved to basemem. unfortunately we
2350          * need fairly detailed info about mpboot.s for this to work.  changes
2351          * to mpboot.s might require changes here.
2352          */
2353
2354         /* boot code is located in KERNEL space */
2355         dst = (u_char *) boot_addr + KERNBASE;
2356
2357         /* modify the lgdt arg */
2358         dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
2359         *dst32 = boot_addr + ((u_int) & MP_GDT - boot_base);
2360
2361         /* modify the ljmp target for MPentry() */
2362         dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
2363         *dst32 = ((u_int) MPentry - KERNBASE);
2364
2365         /* modify the target for boot code segment */
2366         dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
2367         dst8 = (u_int8_t *) (dst16 + 1);
2368         *dst16 = (u_int) boot_addr & 0xffff;
2369         *dst8 = ((u_int) boot_addr >> 16) & 0xff;
2370
2371         /* modify the target for boot data segment */
2372         dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
2373         dst8 = (u_int8_t *) (dst16 + 1);
2374         *dst16 = (u_int) boot_addr & 0xffff;
2375         *dst8 = ((u_int) boot_addr >> 16) & 0xff;
2376 }
2377
2378 #endif
2379
2380 /*
2381  * This function starts the AP (application processor) identified
2382  * by the APIC ID 'physicalCpu'.  It does quite a "song and dance"
2383  * to accomplish this.  This is necessary because of the nuances
2384  * of the different hardware we might encounter.  It ain't pretty,
2385  * but it seems to work.
2386  *
2387  * NOTE: eventually an AP gets to ap_init(), which is called just 
2388  * before the AP goes into the LWKT scheduler's idle loop.
2389  */
2390 static int
2391 start_ap(struct mdglobaldata *gd, u_int boot_addr, int smibest)
2392 {
2393         int     physical_cpu;
2394         int     vector;
2395         u_long  icr_lo, icr_hi;
2396
2397         POSTCODE(START_AP_POST);
2398
2399         /* get the PHYSICAL APIC ID# */
2400         physical_cpu = CPU_TO_ID(gd->mi.gd_cpuid);
2401
2402         /* calculate the vector */
2403         vector = (boot_addr >> 12) & 0xff;
2404
2405         /* We don't want anything interfering */
2406         cpu_disable_intr();
2407
2408         /* Make sure the target cpu sees everything */
2409         wbinvd();
2410
2411         /*
2412          * Try to detect when a SMI has occurred, wait up to 200ms.
2413          *
2414          * If a SMI occurs during an AP reset but before we issue
2415          * the STARTUP command, the AP may brick.  To work around
2416          * this problem we hold off doing the AP startup until
2417          * after we have detected the SMI.  Hopefully another SMI
2418          * will not occur before we finish the AP startup.
2419          *
2420          * Retries don't seem to help.  SMIs have a window of opportunity
2421          * and if USB->legacy keyboard emulation is enabled in the BIOS
2422          * the interrupt rate can be quite high.
2423          *
2424          * NOTE: Don't worry about the L1 cache load, it might bloat
2425          *       ldelta a little but ndelta will be so huge when the SMI
2426          *       occurs the detection logic will still work fine.
2427          */
2428         if (smibest) {
2429                 set_apic_timer(200000);
2430                 smitest();
2431         }
2432
2433         /*
2434          * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
2435          * and running the target CPU. OR this INIT IPI might be latched (P5
2436          * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
2437          * ignored.
2438          *
2439          * see apic/apicreg.h for icr bit definitions.
2440          *
2441          * TIME CRITICAL CODE, DO NOT DO ANY KPRINTFS IN THE HOT PATH.
2442          */
2443
2444         /*
2445          * Setup the address for the target AP.  We can setup
2446          * icr_hi once and then just trigger operations with
2447          * icr_lo.
2448          */
2449         icr_hi = lapic->icr_hi & ~APIC_ID_MASK;
2450         icr_hi |= (physical_cpu << 24);
2451         icr_lo = lapic->icr_lo & 0xfff00000;
2452         lapic->icr_hi = icr_hi;
2453
2454         /*
2455          * Do an INIT IPI: assert RESET
2456          *
2457          * Use edge triggered mode to assert INIT
2458          */
2459         lapic->icr_lo = icr_lo | 0x00004500;
2460         while (lapic->icr_lo & APIC_DELSTAT_MASK)
2461                  /* spin */ ;
2462
2463         /*
2464          * The spec calls for a 10ms delay but we may have to use a
2465          * MUCH lower delay to avoid bricking an AP due to a fast SMI
2466          * interrupt.  We have other loops here too and dividing by 2
2467          * doesn't seem to be enough even after subtracting 350us,
2468          * so we divide by 4.
2469          *
2470          * Our minimum delay is 150uS, maximum is 10ms.  If no SMI
2471          * interrupt was detected we use the full 10ms.
2472          */
2473         if (smibest == 0)
2474                 u_sleep(10000);
2475         else if (smibest < 150 * 4 + 350)
2476                 u_sleep(150);
2477         else if ((smibest - 350) / 4 < 10000)
2478                 u_sleep((smibest - 350) / 4);
2479         else
2480                 u_sleep(10000);
2481
2482         /*
2483          * Do an INIT IPI: deassert RESET
2484          *
2485          * Use level triggered mode to deassert.  It is unclear
2486          * why we need to do this.
2487          */
2488         lapic->icr_lo = icr_lo | 0x00008500;
2489         while (lapic->icr_lo & APIC_DELSTAT_MASK)
2490                  /* spin */ ;
2491         u_sleep(150);                           /* wait 150us */
2492
2493         /*
2494          * Next we do a STARTUP IPI: the previous INIT IPI might still be
2495          * latched, (P5 bug) this 1st STARTUP would then terminate
2496          * immediately, and the previously started INIT IPI would continue. OR
2497          * the previous INIT IPI has already run. and this STARTUP IPI will
2498          * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
2499          * will run.
2500          */
2501         lapic->icr_lo = icr_lo | 0x00000600 | vector;
2502         while (lapic->icr_lo & APIC_DELSTAT_MASK)
2503                  /* spin */ ;
2504         u_sleep(200);           /* wait ~200uS */
2505
2506         /*
2507          * Finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
2508          * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
2509          * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
2510          * recognized after hardware RESET or INIT IPI.
2511          */
2512         lapic->icr_lo = icr_lo | 0x00000600 | vector;
2513         while (lapic->icr_lo & APIC_DELSTAT_MASK)
2514                  /* spin */ ;
2515
2516         /* Resume normal operation */
2517         cpu_enable_intr();
2518
2519         /* wait for it to start, see ap_init() */
2520         set_apic_timer(5000000);/* == 5 seconds */
2521         while (read_apic_timer()) {
2522                 if (smp_startup_mask & CPUMASK(gd->mi.gd_cpuid))
2523                         return 1;       /* return SUCCESS */
2524         }
2525
2526         return 0;               /* return FAILURE */
2527 }
2528
2529 static
2530 int
2531 smitest(void)
2532 {
2533         int64_t ltsc;
2534         int64_t ntsc;
2535         int64_t ldelta;
2536         int64_t ndelta;
2537         int count;
2538
2539         ldelta = 0;
2540         ndelta = 0;
2541         while (read_apic_timer()) {
2542                 ltsc = rdtsc();
2543                 for (count = 0; count < 100; ++count)
2544                         ntsc = rdtsc(); /* force loop to occur */
2545                 if (ldelta) {
2546                         ndelta = ntsc - ltsc;
2547                         if (ldelta > ndelta)
2548                                 ldelta = ndelta;
2549                         if (ndelta > ldelta * 2)
2550                                 break;
2551                 } else {
2552                         ldelta = ntsc - ltsc;
2553                 }
2554         }
2555         return(read_apic_timer());
2556 }
2557
2558 /*
2559  * Synchronously flush the TLB on all other CPU's.  The current cpu's
2560  * TLB is not flushed.  If the caller wishes to flush the current cpu's
2561  * TLB the caller must call cpu_invltlb() in addition to smp_invltlb().
2562  *
2563  * NOTE: If for some reason we were unable to start all cpus we cannot
2564  *       safely use broadcast IPIs.
2565  */
2566
2567 static cpumask_t smp_invltlb_req;
2568
2569 #define SMP_INVLTLB_DEBUG
2570
2571 void
2572 smp_invltlb(void)
2573 {
2574 #ifdef SMP
2575         struct mdglobaldata *md = mdcpu;
2576 #ifdef SMP_INVLTLB_DEBUG
2577         long count = 0;
2578         long xcount = 0;
2579 #endif
2580
2581         crit_enter_gd(&md->mi);
2582         md->gd_invltlb_ret = 0;
2583         ++md->mi.gd_cnt.v_smpinvltlb;
2584         atomic_set_cpumask(&smp_invltlb_req, md->mi.gd_cpumask);
2585 #ifdef SMP_INVLTLB_DEBUG
2586 again:
2587 #endif
2588         if (smp_startup_mask == smp_active_mask) {
2589                 all_but_self_ipi(XINVLTLB_OFFSET);
2590         } else {
2591                 selected_apic_ipi(smp_active_mask & ~md->mi.gd_cpumask,
2592                                   XINVLTLB_OFFSET, APIC_DELMODE_FIXED);
2593         }
2594
2595 #ifdef SMP_INVLTLB_DEBUG
2596         if (xcount)
2597                 kprintf("smp_invltlb: ipi sent\n");
2598 #endif
2599         while ((md->gd_invltlb_ret & smp_active_mask & ~md->mi.gd_cpumask) !=
2600                (smp_active_mask & ~md->mi.gd_cpumask)) {
2601                 cpu_mfence();
2602                 cpu_pause();
2603 #ifdef SMP_INVLTLB_DEBUG
2604                 /* DEBUGGING */
2605                 if (++count == 400000000) {
2606                         print_backtrace(-1);
2607                         kprintf("smp_invltlb: endless loop %08lx %08lx, "
2608                                 "rflags %016jx retry",
2609                               (long)md->gd_invltlb_ret,
2610                               (long)smp_invltlb_req,
2611                               (intmax_t)read_rflags());
2612                         __asm __volatile ("sti");
2613                         ++xcount;
2614                         if (xcount > 2)
2615                                 lwkt_process_ipiq();
2616                         if (xcount > 3) {
2617                                 int bcpu = BSFCPUMASK(~md->gd_invltlb_ret &
2618                                                       ~md->mi.gd_cpumask &
2619                                                       smp_active_mask);
2620                                 globaldata_t xgd;
2621
2622                                 kprintf("bcpu %d\n", bcpu);
2623                                 xgd = globaldata_find(bcpu);
2624                                 kprintf("thread %p %s\n", xgd->gd_curthread, xgd->gd_curthread->td_comm);
2625                         }
2626                         if (xcount > 5)
2627                                 Debugger("giving up");
2628                         count = 0;
2629                         goto again;
2630                 }
2631 #endif
2632         }
2633         atomic_clear_cpumask(&smp_invltlb_req, md->mi.gd_cpumask);
2634         crit_exit_gd(&md->mi);
2635 #endif
2636 }
2637
2638 #ifdef SMP
2639
2640 /*
2641  * Called from Xinvltlb assembly with interrupts disabled.  We didn't
2642  * bother to bump the critical section count or nested interrupt count
2643  * so only do very low level operations here.
2644  */
2645 void
2646 smp_invltlb_intr(void)
2647 {
2648         struct mdglobaldata *md = mdcpu;
2649         struct mdglobaldata *omd;
2650         cpumask_t mask;
2651         int cpu;
2652
2653         cpu_mfence();
2654         mask = smp_invltlb_req;
2655         cpu_invltlb();
2656         while (mask) {
2657                 cpu = BSFCPUMASK(mask);
2658                 mask &= ~CPUMASK(cpu);
2659                 omd = (struct mdglobaldata *)globaldata_find(cpu);
2660                 atomic_set_cpumask(&omd->gd_invltlb_ret, md->mi.gd_cpumask);
2661         }
2662 }
2663
2664 #endif
2665
2666 /*
2667  * When called the executing CPU will send an IPI to all other CPUs
2668  *  requesting that they halt execution.
2669  *
2670  * Usually (but not necessarily) called with 'other_cpus' as its arg.
2671  *
2672  *  - Signals all CPUs in map to stop.
2673  *  - Waits for each to stop.
2674  *
2675  * Returns:
2676  *  -1: error
2677  *   0: NA
2678  *   1: ok
2679  *
2680  * XXX FIXME: this is not MP-safe, needs a lock to prevent multiple CPUs
2681  *            from executing at same time.
2682  */
2683 int
2684 stop_cpus(cpumask_t map)
2685 {
2686         map &= smp_active_mask;
2687
2688         /* send the Xcpustop IPI to all CPUs in map */
2689         selected_apic_ipi(map, XCPUSTOP_OFFSET, APIC_DELMODE_FIXED);
2690         
2691         while ((stopped_cpus & map) != map)
2692                 /* spin */ ;
2693
2694         return 1;
2695 }
2696
2697
2698 /*
2699  * Called by a CPU to restart stopped CPUs. 
2700  *
2701  * Usually (but not necessarily) called with 'stopped_cpus' as its arg.
2702  *
2703  *  - Signals all CPUs in map to restart.
2704  *  - Waits for each to restart.
2705  *
2706  * Returns:
2707  *  -1: error
2708  *   0: NA
2709  *   1: ok
2710  */
2711 int
2712 restart_cpus(cpumask_t map)
2713 {
2714         /* signal other cpus to restart */
2715         started_cpus = map & smp_active_mask;
2716
2717         while ((stopped_cpus & map) != 0) /* wait for each to clear its bit */
2718                 /* spin */ ;
2719
2720         return 1;
2721 }
2722
2723 /*
2724  * This is called once the mpboot code has gotten us properly relocated
2725  * and the MMU turned on, etc.   ap_init() is actually the idle thread,
2726  * and when it returns the scheduler will call the real cpu_idle() main
2727  * loop for the idlethread.  Interrupts are disabled on entry and should
2728  * remain disabled at return.
2729  */
2730 void
2731 ap_init(void)
2732 {
2733         u_int   apic_id;
2734
2735         /*
2736          * Adjust smp_startup_mask to signal the BSP that we have started
2737          * up successfully.  Note that we do not yet hold the BGL.  The BSP
2738          * is waiting for our signal.
2739          *
2740          * We can't set our bit in smp_active_mask yet because we are holding
2741          * interrupts physically disabled and remote cpus could deadlock
2742          * trying to send us an IPI.
2743          */
2744         smp_startup_mask |= CPUMASK(mycpu->gd_cpuid);
2745         cpu_mfence();
2746
2747         /*
2748          * Interlock for finalization.  Wait until mp_finish is non-zero,
2749          * then get the MP lock.
2750          *
2751          * Note: We are in a critical section.
2752          *
2753          * Note: we are the idle thread, we can only spin.
2754          *
2755          * Note: The load fence is memory volatile and prevents the compiler
2756          * from improperly caching mp_finish, and the cpu from improperly
2757          * caching it.
2758          */
2759         while (mp_finish == 0)
2760                 cpu_lfence();
2761         while (try_mplock() == 0)
2762                 ;
2763
2764         if (cpu_feature & CPUID_TSC) {
2765                 /*
2766                  * The BSP is constantly updating tsc0_offset, figure out
2767                  * the relative difference to synchronize ktrdump.
2768                  */
2769                 tsc_offsets[mycpu->gd_cpuid] = rdtsc() - tsc0_offset;
2770         }
2771
2772         /* BSP may have changed PTD while we're waiting for the lock */
2773         cpu_invltlb();
2774
2775 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
2776         lidt(&r_idt);
2777 #endif
2778
2779         /* Build our map of 'other' CPUs. */
2780         mycpu->gd_other_cpus = smp_startup_mask & ~CPUMASK(mycpu->gd_cpuid);
2781
2782         kprintf(" %d", mycpu->gd_cpuid);
2783
2784         /* A quick check from sanity claus */
2785         apic_id = (apic_id_to_logical[(lapic->id & 0xff000000) >> 24]);
2786         if (mycpu->gd_cpuid != apic_id) {
2787                 kprintf("SMP: cpuid = %d\n", mycpu->gd_cpuid);
2788                 kprintf("SMP: apic_id = %d lapicid %d\n",
2789                         apic_id, (lapic->id & 0xff000000) >> 24);
2790 #if JGXXX
2791                 kprintf("PTD[MPPTDI] = %p\n", (void *)PTD[MPPTDI]);
2792 #endif
2793                 panic("cpuid mismatch! boom!!");
2794         }
2795
2796         /* Initialize AP's local APIC for irq's */
2797         apic_initialize(FALSE);
2798
2799         /* Set memory range attributes for this CPU to match the BSP */
2800         mem_range_AP_init();
2801
2802         /*
2803          * Once we go active we must process any IPIQ messages that may
2804          * have been queued, because no actual IPI will occur until we
2805          * set our bit in the smp_active_mask.  If we don't the IPI
2806          * message interlock could be left set which would also prevent
2807          * further IPIs.
2808          *
2809          * The idle loop doesn't expect the BGL to be held and while
2810          * lwkt_switch() normally cleans things up this is a special case
2811          * because we returning almost directly into the idle loop.
2812          *
2813          * The idle thread is never placed on the runq, make sure
2814          * nothing we've done put it there.
2815          */
2816         KKASSERT(get_mplock_count(curthread) == 1);
2817         smp_active_mask |= CPUMASK(mycpu->gd_cpuid);
2818
2819         /*
2820          * Enable interrupts here.  idle_restore will also do it, but
2821          * doing it here lets us clean up any strays that got posted to
2822          * the CPU during the AP boot while we are still in a critical
2823          * section.
2824          */
2825         __asm __volatile("sti; pause; pause"::);
2826         bzero(mdcpu->gd_ipending, sizeof(mdcpu->gd_ipending));
2827
2828         initclocks_pcpu();      /* clock interrupts (via IPIs) */
2829         lwkt_process_ipiq();
2830
2831         /*
2832          * Releasing the mp lock lets the BSP finish up the SMP init
2833          */
2834         rel_mplock();
2835         KKASSERT((curthread->td_flags & TDF_RUNQ) == 0);
2836 }
2837
2838 /*
2839  * Get SMP fully working before we start initializing devices.
2840  */
2841 static
2842 void
2843 ap_finish(void)
2844 {
2845         mp_finish = 1;
2846         if (bootverbose)
2847                 kprintf("Finish MP startup\n");
2848         if (cpu_feature & CPUID_TSC)
2849                 tsc0_offset = rdtsc();
2850         tsc_offsets[0] = 0;
2851         rel_mplock();
2852         while (smp_active_mask != smp_startup_mask) {
2853                 cpu_lfence();
2854                 if (cpu_feature & CPUID_TSC)
2855                         tsc0_offset = rdtsc();
2856         }
2857         while (try_mplock() == 0)
2858                 ;
2859         kprintf("\n");
2860         if (bootverbose) {
2861                 kprintf("Active CPU Mask: %016jx\n",
2862                         (uintmax_t)smp_active_mask);
2863         }
2864 }
2865
2866 SYSINIT(finishsmp, SI_BOOT2_FINISH_SMP, SI_ORDER_FIRST, ap_finish, NULL)
2867
2868 void
2869 cpu_send_ipiq(int dcpu)
2870 {
2871         if (CPUMASK(dcpu) & smp_active_mask)
2872                 single_apic_ipi(dcpu, XIPIQ_OFFSET, APIC_DELMODE_FIXED);
2873 }
2874
2875 #if 0   /* single_apic_ipi_passive() not working yet */
2876 /*
2877  * Returns 0 on failure, 1 on success
2878  */
2879 int
2880 cpu_send_ipiq_passive(int dcpu)
2881 {
2882         int r = 0;
2883         if (CPUMASK(dcpu) & smp_active_mask) {
2884                 r = single_apic_ipi_passive(dcpu, XIPIQ_OFFSET,
2885                                         APIC_DELMODE_FIXED);
2886         }
2887         return(r);
2888 }
2889 #endif
2890
2891 static int
2892 mptable_bus_info_callback(void *xarg, const void *pos, int type)
2893 {
2894         struct mptable_bus_info *bus_info = xarg;
2895         const struct BUSENTRY *ent;
2896         struct mptable_bus *bus;
2897
2898         if (type != 1)
2899                 return 0;
2900
2901         ent = pos;
2902         TAILQ_FOREACH(bus, &bus_info->mbi_list, mb_link) {
2903                 if (bus->mb_id == ent->bus_id) {
2904                         kprintf("mptable_bus_info_alloc: duplicated bus id "
2905                                 "(%d)\n", bus->mb_id);
2906                         return EINVAL;
2907                 }
2908         }
2909
2910         bus = NULL;
2911         if (strncmp(ent->bus_type, "PCI", 3) == 0) {
2912                 bus = kmalloc(sizeof(*bus), M_TEMP, M_WAITOK | M_ZERO);
2913                 bus->mb_type = MPTABLE_BUS_PCI;
2914         } else if (strncmp(ent->bus_type, "ISA", 3) == 0) {
2915                 bus = kmalloc(sizeof(*bus), M_TEMP, M_WAITOK | M_ZERO);
2916                 bus->mb_type = MPTABLE_BUS_ISA;
2917         }
2918
2919         if (bus != NULL) {
2920                 bus->mb_id = ent->bus_id;
2921                 TAILQ_INSERT_TAIL(&bus_info->mbi_list, bus, mb_link);
2922         }
2923         return 0;
2924 }
2925
2926 static void
2927 mptable_bus_info_alloc(const mpcth_t cth, struct mptable_bus_info *bus_info)
2928 {
2929         int error;
2930
2931         bzero(bus_info, sizeof(*bus_info));
2932         TAILQ_INIT(&bus_info->mbi_list);
2933
2934         error = mptable_iterate_entries(cth, mptable_bus_info_callback, bus_info);
2935         if (error)
2936                 mptable_bus_info_free(bus_info);
2937 }
2938
2939 static void
2940 mptable_bus_info_free(struct mptable_bus_info *bus_info)
2941 {
2942         struct mptable_bus *bus;
2943
2944         while ((bus = TAILQ_FIRST(&bus_info->mbi_list)) != NULL) {
2945                 TAILQ_REMOVE(&bus_info->mbi_list, bus, mb_link);
2946                 kfree(bus, M_TEMP);
2947         }
2948 }
2949
2950 struct mptable_lapic_cbarg1 {
2951         int     cpu_count;
2952         int     ht_fixup;
2953         u_int   ht_apicid_mask;
2954 };
2955
2956 static int
2957 mptable_lapic_pass1_callback(void *xarg, const void *pos, int type)
2958 {
2959         const struct PROCENTRY *ent;
2960         struct mptable_lapic_cbarg1 *arg = xarg;
2961
2962         if (type != 0)
2963                 return 0;
2964         ent = pos;
2965
2966         if ((ent->cpu_flags & PROCENTRY_FLAG_EN) == 0)
2967                 return 0;
2968
2969         arg->cpu_count++;
2970         if (ent->apic_id < 32) {
2971                 arg->ht_apicid_mask |= 1 << ent->apic_id;
2972         } else if (arg->ht_fixup) {
2973                 kprintf("MPTABLE: lapic id > 32, disable HTT fixup\n");
2974                 arg->ht_fixup = 0;
2975         }
2976         return 0;
2977 }
2978
2979 struct mptable_lapic_cbarg2 {
2980         int     cpu;
2981         int     logical_cpus;
2982         int     found_bsp;
2983 };
2984
2985 static int
2986 mptable_lapic_pass2_callback(void *xarg, const void *pos, int type)
2987 {
2988         const struct PROCENTRY *ent;
2989         struct mptable_lapic_cbarg2 *arg = xarg;
2990
2991         if (type != 0)
2992                 return 0;
2993         ent = pos;
2994
2995         if (ent->cpu_flags & PROCENTRY_FLAG_BP) {
2996                 KKASSERT(!arg->found_bsp);
2997                 arg->found_bsp = 1;
2998         }
2999
3000         if (processor_entry(ent, arg->cpu))
3001                 arg->cpu++;
3002
3003         if (arg->logical_cpus) {
3004                 struct PROCENTRY proc;
3005                 int i;
3006
3007                 /*
3008                  * Create fake mptable processor entries
3009                  * and feed them to processor_entry() to
3010                  * enumerate the logical CPUs.
3011                  */
3012                 bzero(&proc, sizeof(proc));
3013                 proc.type = 0;
3014                 proc.cpu_flags = PROCENTRY_FLAG_EN;
3015                 proc.apic_id = ent->apic_id;
3016
3017                 for (i = 1; i < arg->logical_cpus; i++) {
3018                         proc.apic_id++;
3019                         processor_entry(&proc, arg->cpu);
3020                         arg->cpu++;
3021                 }
3022         }
3023         return 0;
3024 }
3025
3026 static void
3027 mptable_imcr(struct mptable_pos *mpt)
3028 {
3029         /* record whether PIC or virtual-wire mode */
3030         machintr_setvar_simple(MACHINTR_VAR_IMCR_PRESENT,
3031                                mpt->mp_fps->mpfb2 & 0x80);
3032 }
3033
3034 static void
3035 mptable_lapic_default(void)
3036 {
3037         int ap_apicid, bsp_apicid;
3038
3039         mp_naps = 1; /* exclude BSP */
3040
3041         /* Map local apic before the id field is accessed */
3042         lapic_map(DEFAULT_APIC_BASE);
3043
3044         bsp_apicid = APIC_ID(lapic->id);
3045         ap_apicid = (bsp_apicid == 0) ? 1 : 0;
3046
3047         /* BSP */
3048         mp_set_cpuids(0, bsp_apicid);
3049         /* one and only AP */
3050         mp_set_cpuids(1, ap_apicid);
3051 }
3052
3053 /*
3054  * Configure:
3055  *     mp_naps
3056  *     ID_TO_CPU(N), APIC ID to logical CPU table
3057  *     CPU_TO_ID(N), logical CPU to APIC ID table
3058  */
3059 static void
3060 mptable_lapic_enumerate(struct lapic_enumerator *e)
3061 {
3062         struct mptable_pos mpt;
3063         struct mptable_lapic_cbarg1 arg1;
3064         struct mptable_lapic_cbarg2 arg2;
3065         mpcth_t cth;
3066         int error, logical_cpus = 0;
3067         vm_offset_t lapic_addr;
3068
3069         if (mptable_use_default) {
3070                 mptable_lapic_default();
3071                 return;
3072         }
3073  
3074         error = mptable_map(&mpt);
3075         if (error)
3076                 panic("mptable_lapic_enumerate mptable_map failed\n");
3077         KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
3078
3079         cth = mpt.mp_cth;
3080  
3081         /* Save local apic address */
3082         lapic_addr = (vm_offset_t)cth->apic_address;
3083         KKASSERT(lapic_addr != 0);
3084  
3085         /*
3086          * Find out how many CPUs do we have
3087          */
3088         bzero(&arg1, sizeof(arg1));
3089         arg1.ht_fixup = 1; /* Apply ht fixup by default */
3090
3091         error = mptable_iterate_entries(cth,
3092                     mptable_lapic_pass1_callback, &arg1);
3093         if (error)
3094                 panic("mptable_iterate_entries(lapic_pass1) failed\n");
3095         KKASSERT(arg1.cpu_count != 0);
3096  
3097         /* See if we need to fixup HT logical CPUs. */
3098         if (arg1.ht_fixup) {
3099                 logical_cpus = mptable_hyperthread_fixup(arg1.ht_apicid_mask,
3100                                                          arg1.cpu_count);
3101                 if (logical_cpus != 0)
3102                         arg1.cpu_count *= logical_cpus;
3103         }
3104         mp_naps = arg1.cpu_count;
3105  
3106         /* Qualify the numbers again, after possible HT fixup */
3107         if (mp_naps > MAXCPU) {
3108                 kprintf("Warning: only using %d of %d available CPUs!\n",
3109                         MAXCPU, mp_naps);
3110                 DELAY(1000000);
3111                 mp_naps = MAXCPU;
3112         }
3113
3114         --mp_naps;      /* subtract the BSP */
3115
3116         /*
3117          * Link logical CPU id to local apic id
3118          */
3119         bzero(&arg2, sizeof(arg2));
3120         arg2.cpu = 1;
3121         arg2.logical_cpus = logical_cpus;
3122
3123         error = mptable_iterate_entries(cth,
3124                     mptable_lapic_pass2_callback, &arg2);
3125         if (error)
3126                 panic("mptable_iterate_entries(lapic_pass2) failed\n");
3127         KKASSERT(arg2.found_bsp);
3128
3129         /* Map local apic */
3130         lapic_map(lapic_addr);
3131
3132         mptable_unmap(&mpt);
3133 }
3134
3135 struct mptable_lapic_probe_cbarg {
3136         int     cpu_count;
3137         int     found_bsp;
3138 };
3139
3140 static int
3141 mptable_lapic_probe_callback(void *xarg, const void *pos, int type)
3142 {
3143         const struct PROCENTRY *ent;
3144         struct mptable_lapic_probe_cbarg *arg = xarg;
3145
3146         if (type != 0)
3147                 return 0;
3148         ent = pos;
3149
3150         if ((ent->cpu_flags & PROCENTRY_FLAG_EN) == 0)
3151                 return 0;
3152         arg->cpu_count++;
3153
3154         if (ent->cpu_flags & PROCENTRY_FLAG_BP) {
3155                 if (arg->found_bsp) {
3156                         kprintf("more than one BSP in base MP table\n");
3157                         return EINVAL;
3158                 }
3159                 arg->found_bsp = 1;
3160         }
3161         return 0;
3162 }
3163
3164 static int
3165 mptable_lapic_probe(struct lapic_enumerator *e)
3166 {
3167         struct mptable_pos mpt;
3168         struct mptable_lapic_probe_cbarg arg;
3169         mpcth_t cth;
3170         int error;
3171
3172         if (mptable_fps_phyaddr == 0)
3173                 return ENXIO;
3174
3175         if (mptable_use_default)
3176                 return 0;
3177
3178         error = mptable_map(&mpt);
3179         if (error)
3180                 return error;
3181         KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
3182
3183         error = EINVAL;
3184         cth = mpt.mp_cth;
3185
3186         if (cth->apic_address == 0)
3187                 goto done;
3188
3189         bzero(&arg, sizeof(arg));
3190         error = mptable_iterate_entries(cth,
3191                     mptable_lapic_probe_callback, &arg);
3192         if (!error) {
3193                 if (arg.cpu_count == 0) {
3194                         kprintf("MP table contains no processor entries\n");
3195                         error = EINVAL;
3196                 } else if (!arg.found_bsp) {
3197                         kprintf("MP table does not contains BSP entry\n");
3198                         error = EINVAL;
3199                 }
3200         }
3201 done:
3202         mptable_unmap(&mpt);
3203         return error;
3204 }
3205
3206 static struct lapic_enumerator  mptable_lapic_enumerator = {
3207         .lapic_prio = LAPIC_ENUM_PRIO_MPTABLE,
3208         .lapic_probe = mptable_lapic_probe,
3209         .lapic_enumerate = mptable_lapic_enumerate
3210 };
3211
3212 static void
3213 mptable_lapic_enum_register(void)
3214 {
3215         lapic_enumerator_register(&mptable_lapic_enumerator);
3216 }
3217 SYSINIT(mptable_lapic, SI_BOOT2_PRESMP, SI_ORDER_ANY,
3218         mptable_lapic_enum_register, 0);
3219
3220 static int
3221 mptable_ioapic_list_callback(void *xarg, const void *pos, int type)
3222 {
3223         const struct IOAPICENTRY *ent;
3224         struct mptable_ioapic *nioapic, *ioapic;
3225
3226         if (type != 2)
3227                 return 0;
3228         ent = pos;
3229
3230         if ((ent->apic_flags & IOAPICENTRY_FLAG_EN) == 0)
3231                 return 0;
3232
3233         if (ent->apic_address == 0) {
3234                 kprintf("mptable_ioapic_create_list: zero IOAPIC addr\n");
3235                 return EINVAL;
3236         }
3237
3238         TAILQ_FOREACH(ioapic, &mptable_ioapic_list, mio_link) {
3239                 if (ioapic->mio_apic_id == ent->apic_id) {
3240                         kprintf("mptable_ioapic_create_list: duplicated "
3241                                 "apic id %d\n", ioapic->mio_apic_id);
3242                         return EINVAL;
3243                 }
3244                 if (ioapic->mio_addr == ent->apic_address) {
3245                         kprintf("mptable_ioapic_create_list: overlapped "
3246                                 "IOAPIC addr 0x%08x", ioapic->mio_addr);
3247                         return EINVAL;
3248                 }
3249         }
3250
3251         nioapic = kmalloc(sizeof(*nioapic), M_DEVBUF, M_WAITOK | M_ZERO);
3252         nioapic->mio_apic_id = ent->apic_id;
3253         nioapic->mio_addr = ent->apic_address;
3254
3255         /*
3256          * Create IOAPIC list in ascending order of APIC ID
3257          */
3258         TAILQ_FOREACH_REVERSE(ioapic, &mptable_ioapic_list,
3259             mptable_ioapic_list, mio_link) {
3260                 if (nioapic->mio_apic_id > ioapic->mio_apic_id) {
3261                         TAILQ_INSERT_AFTER(&mptable_ioapic_list,
3262                             ioapic, nioapic, mio_link);
3263                         break;
3264                 }
3265         }
3266         if (ioapic == NULL)
3267                 TAILQ_INSERT_HEAD(&mptable_ioapic_list, nioapic, mio_link);
3268
3269         return 0;
3270 }
3271
3272 static void
3273 mptable_ioapic_create_list(void)
3274 {
3275         struct mptable_ioapic *ioapic;
3276         struct mptable_pos mpt;
3277         int idx, error;
3278
3279         if (mptable_fps_phyaddr == 0)
3280                 return;
3281
3282         if (mptable_use_default) {
3283                 ioapic = kmalloc(sizeof(*ioapic), M_DEVBUF, M_WAITOK | M_ZERO);
3284                 ioapic->mio_idx = 0;
3285                 ioapic->mio_apic_id = 0;        /* NOTE: any value is ok here */
3286                 ioapic->mio_addr = 0xfec00000;  /* XXX magic number */
3287
3288                 TAILQ_INSERT_HEAD(&mptable_ioapic_list, ioapic, mio_link);
3289                 return;
3290         }
3291
3292         error = mptable_map(&mpt);
3293         if (error)
3294                 panic("mptable_ioapic_create_list: mptable_map failed\n");
3295         KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
3296
3297         error = mptable_iterate_entries(mpt.mp_cth,
3298                     mptable_ioapic_list_callback, NULL);
3299         if (error) {
3300                 while ((ioapic = TAILQ_FIRST(&mptable_ioapic_list)) != NULL) {
3301                         TAILQ_REMOVE(&mptable_ioapic_list, ioapic, mio_link);
3302                         kfree(ioapic, M_DEVBUF);
3303                 }
3304                 goto done;
3305         }
3306
3307         /*
3308          * Assign index number for each IOAPIC
3309          */
3310         idx = 0;
3311         TAILQ_FOREACH(ioapic, &mptable_ioapic_list, mio_link) {
3312                 ioapic->mio_idx = idx;
3313                 ++idx;
3314         }
3315 done:
3316         mptable_unmap(&mpt);
3317 }
3318 SYSINIT(mptable_ioapic_list, SI_BOOT2_PRESMP, SI_ORDER_SECOND,
3319         mptable_ioapic_create_list, 0);
3320
3321 static int
3322 mptable_pci_int_callback(void *xarg, const void *pos, int type)
3323 {
3324         const struct mptable_bus_info *bus_info = xarg;
3325         const struct mptable_ioapic *ioapic;
3326         const struct mptable_bus *bus;
3327         struct mptable_pci_int *pci_int;
3328         const struct INTENTRY *ent;
3329         int pci_pin, pci_dev;
3330
3331         if (type != 3)
3332                 return 0;
3333         ent = pos;
3334
3335         if (ent->int_type != 0)
3336                 return 0;
3337
3338         TAILQ_FOREACH(bus, &bus_info->mbi_list, mb_link) {
3339                 if (bus->mb_type == MPTABLE_BUS_PCI &&
3340                     bus->mb_id == ent->src_bus_id)
3341                         break;
3342         }
3343         if (bus == NULL)
3344                 return 0;
3345
3346         TAILQ_FOREACH(ioapic, &mptable_ioapic_list, mio_link) {
3347                 if (ioapic->mio_apic_id == ent->dst_apic_id)
3348                         break;
3349         }
3350         if (ioapic == NULL) {
3351                 kprintf("MPTABLE: warning PCI int dst apic id %d "
3352                         "does not exist\n", ent->dst_apic_id);
3353                 return 0;
3354         }
3355
3356         pci_pin = ent->src_bus_irq & 0x3;
3357         pci_dev = (ent->src_bus_irq >> 2) & 0x1f;
3358
3359         TAILQ_FOREACH(pci_int, &mptable_pci_int_list, mpci_link) {
3360                 if (pci_int->mpci_bus == ent->src_bus_id &&
3361                     pci_int->mpci_dev == pci_dev &&
3362                     pci_int->mpci_pin == pci_pin) {
3363                         if (pci_int->mpci_ioapic_idx == ioapic->mio_idx &&
3364                             pci_int->mpci_ioapic_pin == ent->dst_apic_int) {
3365                                 kprintf("MPTABLE: warning duplicated "
3366                                         "PCI int entry for "
3367                                         "bus %d, dev %d, pin %d\n",
3368                                         pci_int->mpci_bus,
3369                                         pci_int->mpci_dev,
3370                                         pci_int->mpci_pin);
3371                                 return 0;
3372                         } else {
3373                                 kprintf("mptable_pci_int_register: "
3374                                         "conflict PCI int entry for "
3375                                         "bus %d, dev %d, pin %d, "
3376                                         "IOAPIC %d.%d -> %d.%d\n",
3377                                         pci_int->mpci_bus,
3378                                         pci_int->mpci_dev,
3379                                         pci_int->mpci_pin,
3380                                         pci_int->mpci_ioapic_idx,
3381                                         pci_int->mpci_ioapic_pin,
3382                                         ioapic->mio_idx,
3383                                         ent->dst_apic_int);
3384                                 return EINVAL;
3385                         }
3386                 }
3387         }
3388
3389         pci_int = kmalloc(sizeof(*pci_int), M_DEVBUF, M_WAITOK | M_ZERO);
3390
3391         pci_int->mpci_bus = ent->src_bus_id;
3392         pci_int->mpci_dev = pci_dev;
3393         pci_int->mpci_pin = pci_pin;
3394         pci_int->mpci_ioapic_idx = ioapic->mio_idx;
3395         pci_int->mpci_ioapic_pin = ent->dst_apic_int;
3396
3397         TAILQ_INSERT_TAIL(&mptable_pci_int_list, pci_int, mpci_link);
3398
3399         return 0;
3400 }
3401
3402 static void
3403 mptable_pci_int_register(void)
3404 {
3405         struct mptable_bus_info bus_info;
3406         const struct mptable_bus *bus;
3407         struct mptable_pci_int *pci_int;
3408         struct mptable_pos mpt;
3409         int error, force_pci0, npcibus;
3410         mpcth_t cth;
3411
3412         if (mptable_fps_phyaddr == 0)
3413                 return;
3414
3415         if (mptable_use_default)
3416                 return;
3417
3418         if (TAILQ_EMPTY(&mptable_ioapic_list))
3419                 return;
3420
3421         error = mptable_map(&mpt);
3422         if (error)
3423                 panic("mptable_pci_int_register: mptable_map failed\n");
3424         KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
3425
3426         cth = mpt.mp_cth;
3427
3428         mptable_bus_info_alloc(cth, &bus_info);
3429         if (TAILQ_EMPTY(&bus_info.mbi_list))
3430                 goto done;
3431
3432         npcibus = 0;
3433         TAILQ_FOREACH(bus, &bus_info.mbi_list, mb_link) {
3434                 if (bus->mb_type == MPTABLE_BUS_PCI)
3435                         ++npcibus;
3436         }
3437         if (npcibus == 0) {
3438                 mptable_bus_info_free(&bus_info);
3439                 goto done;
3440         } else if (npcibus == 1) {
3441                 force_pci0 = 1;
3442         }
3443
3444         error = mptable_iterate_entries(cth,
3445                     mptable_pci_int_callback, &bus_info);
3446
3447         mptable_bus_info_free(&bus_info);
3448
3449         if (error) {
3450                 while ((pci_int = TAILQ_FIRST(&mptable_pci_int_list)) != NULL) {
3451                         TAILQ_REMOVE(&mptable_pci_int_list, pci_int, mpci_link);
3452                         kfree(pci_int, M_DEVBUF);
3453                 }
3454                 goto done;
3455         }
3456
3457         if (force_pci0) {
3458                 TAILQ_FOREACH(pci_int, &mptable_pci_int_list, mpci_link)
3459                         pci_int->mpci_bus = 0;
3460         }
3461 done:
3462         mptable_unmap(&mpt);
3463 }
3464 SYSINIT(mptable_pci, SI_BOOT2_PRESMP, SI_ORDER_ANY,
3465         mptable_pci_int_register, 0);
3466
3467 struct mptable_ioapic_probe_cbarg {
3468         const struct mptable_bus_info *bus_info;
3469 };
3470
3471 static int
3472 mptable_ioapic_probe_callback(void *xarg, const void *pos, int type)
3473 {
3474         struct mptable_ioapic_probe_cbarg *arg = xarg;
3475         const struct mptable_ioapic *ioapic;
3476         const struct mptable_bus *bus;
3477         const struct INTENTRY *ent;
3478
3479         if (type != 3)
3480                 return 0;
3481         ent = pos;
3482
3483         if (ent->int_type != 0)
3484                 return 0;
3485
3486         TAILQ_FOREACH(bus, &arg->bus_info->mbi_list, mb_link) {
3487                 if (bus->mb_type == MPTABLE_BUS_ISA &&
3488                     bus->mb_id == ent->src_bus_id)
3489                         break;
3490         }
3491         if (bus == NULL)
3492                 return 0;
3493
3494         TAILQ_FOREACH(ioapic, &mptable_ioapic_list, mio_link) {
3495                 if (ioapic->mio_apic_id == ent->dst_apic_id)
3496                         break;
3497         }
3498         if (ioapic == NULL) {
3499                 kprintf("MPTABLE: warning ISA int dst apic id %d "
3500                         "does not exist\n", ent->dst_apic_id);
3501                 return 0;
3502         }
3503
3504         /* XXX magic number */
3505         if (ent->src_bus_irq >= 16) {
3506                 kprintf("mptable_ioapic_probe: invalid ISA irq (%d)\n",
3507                         ent->src_bus_irq);
3508                 return EINVAL;
3509         }
3510         return 0;
3511 }
3512
3513 static int
3514 mptable_ioapic_probe(struct ioapic_enumerator *e)
3515 {
3516         struct mptable_ioapic_probe_cbarg arg;
3517         struct mptable_bus_info bus_info;
3518         struct mptable_pos mpt;
3519         mpcth_t cth;
3520         int error;
3521
3522         if (mptable_fps_phyaddr == 0)
3523                 return ENXIO;
3524
3525         if (mptable_use_default)
3526                 return 0;
3527
3528         if (TAILQ_EMPTY(&mptable_ioapic_list))
3529                 return ENXIO;
3530
3531         error = mptable_map(&mpt);
3532         if (error)
3533                 panic("mptable_ioapic_probe: mptable_map failed\n");
3534         KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
3535
3536         cth = mpt.mp_cth;
3537
3538         mptable_bus_info_alloc(cth, &bus_info);
3539
3540         bzero(&arg, sizeof(arg));
3541         arg.bus_info = &bus_info;
3542
3543         error = mptable_iterate_entries(cth,
3544                     mptable_ioapic_probe_callback, &arg);
3545
3546         mptable_bus_info_free(&bus_info);
3547         mptable_unmap(&mpt);
3548
3549         return error;
3550 }
3551
3552 struct mptable_ioapic_int_cbarg {
3553         const struct mptable_bus_info *bus_info;
3554         int     ioapic_nint;
3555 };
3556
3557 static int
3558 mptable_ioapic_int_callback(void *xarg, const void *pos, int type)
3559 {
3560         struct mptable_ioapic_int_cbarg *arg = xarg;
3561         const struct mptable_bus *bus;
3562         const struct INTENTRY *ent;
3563
3564         if (type != 3)
3565                 return 0;
3566
3567         arg->ioapic_nint++;
3568
3569         ent = pos;
3570         if (ent->int_type != 0)
3571                 return 0;
3572
3573         TAILQ_FOREACH(bus, &arg->bus_info->mbi_list, mb_link) {
3574                 if (bus->mb_type == MPTABLE_BUS_ISA &&
3575                     bus->mb_id == ent->src_bus_id)
3576                         break;
3577         }
3578         if (bus == NULL)
3579                 return 0;
3580
3581         /* XXX rough estimation */
3582         if (ent->src_bus_irq != ent->dst_apic_int) {
3583                 if (bootverbose) {
3584                         kprintf("MPTABLE: INTSRC irq %d -> GSI %d\n",
3585                                 ent->src_bus_irq, ent->dst_apic_int);
3586                 }
3587         }
3588         return 0;
3589 }
3590
3591 static void
3592 mptable_ioapic_enumerate(struct ioapic_enumerator *e)
3593 {
3594         struct mptable_bus_info bus_info;
3595         const struct mptable_ioapic *ioapic;
3596         struct mptable_pos mpt;
3597         mpcth_t cth;
3598         int error;
3599
3600         KKASSERT(mptable_fps_phyaddr != 0);
3601         KKASSERT(!TAILQ_EMPTY(&mptable_ioapic_list));
3602
3603         TAILQ_FOREACH(ioapic, &mptable_ioapic_list, mio_link) {
3604                 if (bootverbose) {
3605                         kprintf("MPTABLE: IOAPIC addr 0x%08x, "
3606                                 "apic id %d, idx %d\n",
3607                                 ioapic->mio_addr,
3608                                 ioapic->mio_apic_id, ioapic->mio_idx);
3609                 }
3610                 /* TODO */
3611         }
3612
3613         if (mptable_use_default) {
3614                 if (bootverbose)
3615                         kprintf("MPTABLE: INTSRC irq 0 -> GSI 2 (default)\n");
3616                 /* TODO default intsrc */
3617                 return;
3618         }
3619
3620         error = mptable_map(&mpt);
3621         if (error)
3622                 panic("mptable_ioapic_probe: mptable_map failed\n");
3623         KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
3624
3625         cth = mpt.mp_cth;
3626
3627         mptable_bus_info_alloc(cth, &bus_info);
3628
3629         if (TAILQ_EMPTY(&bus_info.mbi_list)) {
3630                 if (bootverbose)
3631                         kprintf("MPTABLE: INTSRC irq 0 -> GSI 2 (no bus)\n");
3632                 /* TODO default intsrc */
3633         } else {
3634                 struct mptable_ioapic_int_cbarg arg;
3635
3636                 bzero(&arg, sizeof(arg));
3637                 arg.bus_info = &bus_info;
3638
3639                 error = mptable_iterate_entries(cth,
3640                             mptable_ioapic_int_callback, &arg);
3641                 if (error)
3642                         panic("mptable_ioapic_int failed\n");
3643
3644                 if (arg.ioapic_nint == 0) {
3645                         if (bootverbose) {
3646                                 kprintf("MPTABLE: INTSRC irq 0 -> GSI 2 "
3647                                         "(no int)\n");
3648                         }
3649                         /* TODO default intsrc */
3650                 }
3651         }
3652
3653         mptable_bus_info_free(&bus_info);
3654
3655         mptable_unmap(&mpt);
3656 }
3657
3658 static struct ioapic_enumerator mptable_ioapic_enumerator = {
3659         .ioapic_prio = IOAPIC_ENUM_PRIO_MPTABLE,
3660         .ioapic_probe = mptable_ioapic_probe,
3661         .ioapic_enumerate = mptable_ioapic_enumerate
3662 };
3663
3664 static void
3665 mptable_ioapic_enum_register(void)
3666 {
3667         ioapic_enumerator_register(&mptable_ioapic_enumerator);
3668 }
3669 SYSINIT(mptable_ioapic, SI_BOOT2_PRESMP, SI_ORDER_ANY,
3670         mptable_ioapic_enum_register, 0);