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