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