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