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