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