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