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