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