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