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