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