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