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