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