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