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