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