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