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