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