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