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