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