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