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