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