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