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