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