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