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