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