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