2 * Copyright (c) 1996, by Steve Passe
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
25 * $FreeBSD: src/sys/i386/i386/mp_machdep.c,v 1.115.2.15 2003/03/14 21:22:35 jhb Exp $
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/sysctl.h>
34 #include <sys/malloc.h>
35 #include <sys/memrange.h>
36 #include <sys/cons.h> /* cngetc() */
37 #include <sys/machintr.h>
39 #include <sys/mplock2.h>
42 #include <vm/vm_param.h>
44 #include <vm/vm_kern.h>
45 #include <vm/vm_extern.h>
47 #include <vm/vm_map.h>
53 #include <machine/smp.h>
54 #include <machine_base/apic/apicreg.h>
55 #include <machine/atomic.h>
56 #include <machine/cpufunc.h>
57 #include <machine_base/apic/mpapic.h>
58 #include <machine/psl.h>
59 #include <machine/segments.h>
60 #include <machine/tss.h>
61 #include <machine/specialreg.h>
62 #include <machine/globaldata.h>
63 #include <machine/pmap_inval.h>
65 #include <machine/md_var.h> /* setidt() */
66 #include <machine_base/icu/icu.h> /* IPIs */
67 #include <machine_base/apic/ioapic_abi.h>
68 #include <machine/intr_machdep.h> /* IPIs */
70 #define FIXUP_EXTRA_APIC_INTS 8 /* additional entries we may create */
72 #define WARMBOOT_TARGET 0
73 #define WARMBOOT_OFF (KERNBASE + 0x0467)
74 #define WARMBOOT_SEG (KERNBASE + 0x0469)
76 #define BIOS_BASE (0xf0000)
77 #define BIOS_BASE2 (0xe0000)
78 #define BIOS_SIZE (0x10000)
79 #define BIOS_COUNT (BIOS_SIZE/4)
81 #define CMOS_REG (0x70)
82 #define CMOS_DATA (0x71)
83 #define BIOS_RESET (0x0f)
84 #define BIOS_WARM (0x0a)
86 #define PROCENTRY_FLAG_EN 0x01
87 #define PROCENTRY_FLAG_BP 0x02
88 #define IOAPICENTRY_FLAG_EN 0x01
91 /* MP Floating Pointer Structure */
92 typedef struct MPFPS {
105 /* MP Configuration Table Header */
106 typedef struct MPCTH {
108 u_short base_table_length;
112 u_char product_id[12];
113 u_int32_t oem_table_pointer;
114 u_short oem_table_size;
116 u_int32_t apic_address;
117 u_short extended_table_length;
118 u_char extended_table_checksum;
123 typedef struct PROCENTRY {
128 u_int32_t cpu_signature;
129 u_int32_t feature_flags;
134 typedef struct BUSENTRY {
140 typedef struct IOAPICENTRY {
145 u_int32_t apic_address;
146 } *io_apic_entry_ptr;
148 typedef struct INTENTRY {
158 /* descriptions of MP basetable entries */
159 typedef struct BASETABLE_ENTRY {
168 vm_size_t mp_cth_mapsz;
171 #define MPTABLE_POS_USE_DEFAULT(mpt) \
172 ((mpt)->mp_fps->mpfb1 != 0 || (mpt)->mp_cth == NULL)
176 int mb_type; /* MPTABLE_BUS_ */
177 TAILQ_ENTRY(mptable_bus) mb_link;
180 #define MPTABLE_BUS_ISA 0
181 #define MPTABLE_BUS_PCI 1
183 struct mptable_bus_info {
184 TAILQ_HEAD(, mptable_bus) mbi_list;
187 struct mptable_pci_int {
194 TAILQ_ENTRY(mptable_pci_int) mpci_link;
197 struct mptable_ioapic {
203 TAILQ_ENTRY(mptable_ioapic) mio_link;
206 typedef int (*mptable_iter_func)(void *, const void *, int);
209 * this code MUST be enabled here and in mpboot.s.
210 * it follows the very early stages of AP boot by placing values in CMOS ram.
211 * it NORMALLY will never be needed and thus the primitive method for enabling.
214 #if defined(CHECK_POINTS)
215 #define CHECK_READ(A) (outb(CMOS_REG, (A)), inb(CMOS_DATA))
216 #define CHECK_WRITE(A,D) (outb(CMOS_REG, (A)), outb(CMOS_DATA, (D)))
218 #define CHECK_INIT(D); \
219 CHECK_WRITE(0x34, (D)); \
220 CHECK_WRITE(0x35, (D)); \
221 CHECK_WRITE(0x36, (D)); \
222 CHECK_WRITE(0x37, (D)); \
223 CHECK_WRITE(0x38, (D)); \
224 CHECK_WRITE(0x39, (D));
226 #define CHECK_PRINT(S); \
227 kprintf("%s: %d, %d, %d, %d, %d, %d\n", \
236 #else /* CHECK_POINTS */
238 #define CHECK_INIT(D)
239 #define CHECK_PRINT(S)
241 #endif /* CHECK_POINTS */
244 * Values to send to the POST hardware.
246 #define MP_BOOTADDRESS_POST 0x10
247 #define MP_PROBE_POST 0x11
248 #define MPTABLE_PASS1_POST 0x12
250 #define MP_START_POST 0x13
251 #define MP_ENABLE_POST 0x14
252 #define MPTABLE_PASS2_POST 0x15
254 #define START_ALL_APS_POST 0x16
255 #define INSTALL_AP_TRAMP_POST 0x17
256 #define START_AP_POST 0x18
258 #define MP_ANNOUNCE_POST 0x19
260 /** XXX FIXME: where does this really belong, isa.h/isa.c perhaps? */
261 int current_postcode;
263 /** XXX FIXME: what system files declare these??? */
264 extern struct region_descriptor r_gdt, r_idt;
266 int mp_naps; /* # of Applications processors */
269 u_int32_t cpu_apic_versions[NAPICID]; /* populated during mptable scan */
271 extern int64_t tsc_offsets[];
273 extern u_long ebda_addr;
275 #ifdef SMP /* APIC-IO */
276 struct apic_intmapinfo int_to_apicintpin[APIC_INTMAPSIZE];
280 * APIC ID logical/physical mapping structures.
281 * We oversize these to simplify boot-time config.
283 int cpu_num_to_apic_id[NAPICID];
284 int apic_id_to_logical[NAPICID];
286 /* AP uses this during bootstrap. Do not staticize. */
290 struct pcb stoppcbs[MAXCPU];
292 extern inthand_t IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
294 static basetable_entry basetable_entry_types[] =
296 {0, 20, "Processor"},
304 * Local data and functions.
307 static u_int boot_address;
308 static u_int base_memory;
309 static int mp_finish;
310 static int mp_finish_lapic;
312 static void mp_enable(u_int boot_addr);
314 static int mptable_iterate_entries(const mpcth_t,
315 mptable_iter_func, void *);
316 static int mptable_search(void);
317 static long mptable_search_sig(u_int32_t target, int count);
318 static int mptable_hyperthread_fixup(cpumask_t, int);
319 static int mptable_map(struct mptable_pos *);
320 static void mptable_unmap(struct mptable_pos *);
321 static void mptable_bus_info_alloc(const mpcth_t,
322 struct mptable_bus_info *);
323 static void mptable_bus_info_free(struct mptable_bus_info *);
325 static int mptable_lapic_probe(struct lapic_enumerator *);
326 static void mptable_lapic_enumerate(struct lapic_enumerator *);
327 static void mptable_lapic_default(void);
329 static int mptable_ioapic_probe(struct ioapic_enumerator *);
330 static void mptable_ioapic_enumerate(struct ioapic_enumerator *);
332 static int start_all_aps(u_int boot_addr);
334 static void install_ap_tramp(u_int boot_addr);
336 static int start_ap(struct mdglobaldata *gd, u_int boot_addr, int smibest);
337 static int smitest(void);
339 static cpumask_t smp_startup_mask = 1; /* which cpus have been started */
340 static cpumask_t smp_lapic_mask = 1; /* which cpus have lapic been inited */
341 cpumask_t smp_active_mask = 1; /* which cpus are ready for IPIs etc? */
342 SYSCTL_INT(_machdep, OID_AUTO, smp_active, CTLFLAG_RD, &smp_active_mask, 0, "");
343 static u_int bootMP_size;
347 static vm_paddr_t mptable_fps_phyaddr;
348 static int mptable_use_default;
349 static TAILQ_HEAD(mptable_pci_int_list, mptable_pci_int) mptable_pci_int_list =
350 TAILQ_HEAD_INITIALIZER(mptable_pci_int_list);
351 static TAILQ_HEAD(mptable_ioapic_list, mptable_ioapic) mptable_ioapic_list =
352 TAILQ_HEAD_INITIALIZER(mptable_ioapic_list);
355 * Calculate usable address in base memory for AP trampoline code.
358 mp_bootaddress(u_int basemem)
360 POSTCODE(MP_BOOTADDRESS_POST);
362 base_memory = basemem;
364 bootMP_size = mptramp_end - mptramp_start;
365 boot_address = trunc_page(basemem * 1024); /* round down to 4k boundary */
366 if (((basemem * 1024) - boot_address) < bootMP_size)
367 boot_address -= PAGE_SIZE; /* not enough, lower by 4k */
368 /* 3 levels of page table pages */
369 mptramp_pagetables = boot_address - (PAGE_SIZE * 3);
371 return mptramp_pagetables;
378 struct mptable_pos mpt;
381 KKASSERT(mptable_fps_phyaddr == 0);
383 mptable_fps_phyaddr = mptable_search();
384 if (mptable_fps_phyaddr == 0)
387 error = mptable_map(&mpt);
389 mptable_fps_phyaddr = 0;
393 if (MPTABLE_POS_USE_DEFAULT(&mpt)) {
394 kprintf("MPTABLE: use default configuration\n");
395 mptable_use_default = 1;
397 if (mpt.mp_fps->mpfb2 & 0x80)
402 SYSINIT(mptable_probe, SI_BOOT2_PRESMP, SI_ORDER_FIRST, mptable_probe, 0);
405 * Look for an Intel MP spec table (ie, SMP capable hardware).
413 POSTCODE(MP_PROBE_POST);
415 /* see if EBDA exists */
416 if (ebda_addr != 0) {
417 /* search first 1K of EBDA */
418 target = (u_int32_t)ebda_addr;
419 if ((x = mptable_search_sig(target, 1024 / 4)) > 0)
422 /* last 1K of base memory, effective 'top of base' passed in */
423 target = (u_int32_t)(base_memory - 0x400);
424 if ((x = mptable_search_sig(target, 1024 / 4)) > 0)
428 /* search the BIOS */
429 target = (u_int32_t)BIOS_BASE;
430 if ((x = mptable_search_sig(target, BIOS_COUNT)) > 0)
433 /* search the extended BIOS */
434 target = (u_int32_t)BIOS_BASE2;
435 if ((x = mptable_search_sig(target, BIOS_COUNT)) > 0)
443 mptable_iterate_entries(const mpcth_t cth, mptable_iter_func func, void *arg)
445 int count, total_size;
446 const void *position;
448 KKASSERT(cth->base_table_length >= sizeof(struct MPCTH));
449 total_size = cth->base_table_length - sizeof(struct MPCTH);
450 position = (const uint8_t *)cth + sizeof(struct MPCTH);
451 count = cth->entry_count;
456 KKASSERT(total_size >= 0);
457 if (total_size == 0) {
458 kprintf("invalid base MP table, "
459 "entry count and length mismatch\n");
463 type = *(const uint8_t *)position;
465 case 0: /* processor_entry */
466 case 1: /* bus_entry */
467 case 2: /* io_apic_entry */
468 case 3: /* int_entry */
469 case 4: /* int_entry */
472 kprintf("unknown base MP table entry type %d\n", type);
476 if (total_size < basetable_entry_types[type].length) {
477 kprintf("invalid base MP table length, "
478 "does not contain all entries\n");
481 total_size -= basetable_entry_types[type].length;
483 error = func(arg, position, type);
487 position = (const uint8_t *)position +
488 basetable_entry_types[type].length;
495 * Startup the SMP processors.
500 POSTCODE(MP_START_POST);
501 mp_enable(boot_address);
506 * Print various information about the SMP system hardware and setup.
513 POSTCODE(MP_ANNOUNCE_POST);
515 kprintf("DragonFly/MP: Multiprocessor motherboard\n");
516 kprintf(" cpu0 (BSP): apic id: %2d", CPU_TO_ID(0));
517 kprintf(", version: 0x%08x\n", cpu_apic_versions[0]);
518 for (x = 1; x <= mp_naps; ++x) {
519 kprintf(" cpu%d (AP): apic id: %2d", x, CPU_TO_ID(x));
520 kprintf(", version: 0x%08x\n", cpu_apic_versions[x]);
524 kprintf(" Warning: APIC I/O disabled\n");
528 * AP cpu's call this to sync up protected mode.
530 * WARNING! %gs is not set up on entry. This routine sets up %gs.
536 int x, myid = bootAP;
538 struct mdglobaldata *md;
539 struct privatespace *ps;
541 ps = &CPU_prvspace[myid];
543 gdt_segs[GPROC0_SEL].ssd_base =
544 (long) &ps->mdglobaldata.gd_common_tss;
545 ps->mdglobaldata.mi.gd_prvspace = ps;
547 /* We fill the 32-bit segment descriptors */
548 for (x = 0; x < NGDT; x++) {
549 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1))
550 ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x]);
552 /* And now a 64-bit one */
553 ssdtosyssd(&gdt_segs[GPROC0_SEL],
554 (struct system_segment_descriptor *)&gdt[myid * NGDT + GPROC0_SEL]);
556 r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
557 r_gdt.rd_base = (long) &gdt[myid * NGDT];
558 lgdt(&r_gdt); /* does magic intra-segment return */
560 /* lgdt() destroys the GSBASE value, so we load GSBASE after lgdt() */
561 wrmsr(MSR_FSBASE, 0); /* User value */
562 wrmsr(MSR_GSBASE, (u_int64_t)ps);
563 wrmsr(MSR_KGSBASE, 0); /* XXX User value while we're in the kernel */
569 mdcpu->gd_currentldt = _default_ldt;
572 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
573 gdt[myid * NGDT + GPROC0_SEL].sd_type = SDT_SYSTSS;
575 md = mdcpu; /* loaded through %gs:0 (mdglobaldata.mi.gd_prvspace)*/
577 md->gd_common_tss.tss_rsp0 = 0; /* not used until after switch */
579 md->gd_common_tss.tss_ioopt = (sizeof md->gd_common_tss) << 16;
581 md->gd_tss_gdt = &gdt[myid * NGDT + GPROC0_SEL];
582 md->gd_common_tssd = *md->gd_tss_gdt;
584 /* double fault stack */
585 md->gd_common_tss.tss_ist1 =
586 (long)&md->mi.gd_prvspace->idlestack[
587 sizeof(md->mi.gd_prvspace->idlestack)];
592 * Set to a known state:
593 * Set by mpboot.s: CR0_PG, CR0_PE
594 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
597 cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
600 /* Set up the fast syscall stuff */
601 msr = rdmsr(MSR_EFER) | EFER_SCE;
602 wrmsr(MSR_EFER, msr);
603 wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
604 wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
605 msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
606 ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
607 wrmsr(MSR_STAR, msr);
608 wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
610 pmap_set_opt(); /* PSE/4MB pages, etc */
612 /* Initialize the PAT MSR. */
616 /* set up CPU registers and state */
619 /* set up SSE/NX registers */
622 /* set up FPU state on the AP */
623 npxinit(__INITIAL_NPXCW__);
625 /* disable the APIC, just to be SURE */
626 lapic->svr &= ~APIC_SVR_ENABLE;
628 /* data returned to BSP */
629 cpu_apic_versions[0] = lapic->version;
632 /*******************************************************************
633 * local functions and data
637 * start the SMP system
640 mp_enable(u_int boot_addr)
642 POSTCODE(MP_ENABLE_POST);
646 /* Initialize BSP's local APIC */
649 /* start each Application Processor */
650 start_all_aps(boot_addr);
656 MachIntrABI.finalize();
661 * look for the MP spec signature
664 /* string defined by the Intel MP Spec as identifying the MP table */
665 #define MP_SIG 0x5f504d5f /* _MP_ */
666 #define NEXT(X) ((X) += 4)
668 mptable_search_sig(u_int32_t target, int count)
674 KKASSERT(target != 0);
676 map_size = count * sizeof(u_int32_t);
677 addr = pmap_mapdev((vm_paddr_t)target, map_size);
680 for (x = 0; x < count; NEXT(x)) {
681 if (addr[x] == MP_SIG) {
682 /* make array index a byte index */
683 ret = target + (x * sizeof(u_int32_t));
688 pmap_unmapdev((vm_offset_t)addr, map_size);
693 typedef struct BUSDATA {
695 enum busTypes bus_type;
698 typedef struct INTDATA {
708 typedef struct BUSTYPENAME {
713 static int processor_entry (const struct PROCENTRY *entry, int cpu);
716 * Check if we should perform a hyperthreading "fix-up" to
717 * enumerate any logical CPU's that aren't already listed
720 * XXX: We assume that all of the physical CPUs in the
721 * system have the same number of logical CPUs.
723 * XXX: We assume that APIC ID's are allocated such that
724 * the APIC ID's for a physical processor are aligned
725 * with the number of logical CPU's in the processor.
728 mptable_hyperthread_fixup(cpumask_t id_mask, int cpu_count)
730 int i, id, lcpus_max, logical_cpus;
732 if ((cpu_feature & CPUID_HTT) == 0)
735 lcpus_max = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
739 if (strcmp(cpu_vendor, "GenuineIntel") == 0) {
741 * INSTRUCTION SET REFERENCE, A-M (#253666)
742 * Page 3-181, Table 3-20
743 * "The nearest power-of-2 integer that is not smaller
744 * than EBX[23:16] is the number of unique initial APIC
745 * IDs reserved for addressing different logical
746 * processors in a physical package."
749 if ((1 << i) >= lcpus_max) {
756 KKASSERT(cpu_count != 0);
757 if (cpu_count == lcpus_max) {
758 /* We have nothing to fix */
760 } else if (cpu_count == 1) {
761 /* XXX this may be incorrect */
762 logical_cpus = lcpus_max;
767 * Calculate the distances between two nearest
768 * APIC IDs. If all such distances are same,
769 * then it is the number of missing cpus that
770 * we are going to fill later.
772 dist = cur = prev = -1;
773 for (id = 0; id < MAXCPU; ++id) {
774 if ((id_mask & CPUMASK(id)) == 0)
779 int new_dist = cur - prev;
785 * Make sure that all distances
786 * between two nearest APIC IDs
789 if (dist != new_dist)
797 /* Must be power of 2 */
798 if (dist & (dist - 1))
801 /* Can't exceed CPU package capacity */
802 if (dist > lcpus_max)
803 logical_cpus = lcpus_max;
809 * For each APIC ID of a CPU that is set in the mask,
810 * scan the other candidate APIC ID's for this
811 * physical processor. If any of those ID's are
812 * already in the table, then kill the fixup.
814 for (id = 0; id < MAXCPU; id++) {
815 if ((id_mask & CPUMASK(id)) == 0)
817 /* First, make sure we are on a logical_cpus boundary. */
818 if (id % logical_cpus != 0)
820 for (i = id + 1; i < id + logical_cpus; i++)
821 if ((id_mask & CPUMASK(i)) != 0)
828 mptable_map(struct mptable_pos *mpt)
832 vm_size_t cth_mapsz = 0;
834 KKASSERT(mptable_fps_phyaddr != 0);
836 bzero(mpt, sizeof(*mpt));
838 fps = pmap_mapdev(mptable_fps_phyaddr, sizeof(*fps));
841 * Map configuration table header to get
842 * the base table size
844 cth = pmap_mapdev(fps->pap, sizeof(*cth));
845 cth_mapsz = cth->base_table_length;
846 pmap_unmapdev((vm_offset_t)cth, sizeof(*cth));
848 if (cth_mapsz < sizeof(*cth)) {
849 kprintf("invalid base MP table length %d\n",
851 pmap_unmapdev((vm_offset_t)fps, sizeof(*fps));
858 cth = pmap_mapdev(fps->pap, cth_mapsz);
863 mpt->mp_cth_mapsz = cth_mapsz;
869 mptable_unmap(struct mptable_pos *mpt)
871 if (mpt->mp_cth != NULL) {
872 pmap_unmapdev((vm_offset_t)mpt->mp_cth, mpt->mp_cth_mapsz);
874 mpt->mp_cth_mapsz = 0;
876 if (mpt->mp_fps != NULL) {
877 pmap_unmapdev((vm_offset_t)mpt->mp_fps, sizeof(*mpt->mp_fps));
883 mp_set_cpuids(int cpu_id, int apic_id)
885 CPU_TO_ID(cpu_id) = apic_id;
886 ID_TO_CPU(apic_id) = cpu_id;
890 processor_entry(const struct PROCENTRY *entry, int cpu)
894 /* check for usability */
895 if (!(entry->cpu_flags & PROCENTRY_FLAG_EN))
898 /* check for BSP flag */
899 if (entry->cpu_flags & PROCENTRY_FLAG_BP) {
900 mp_set_cpuids(0, entry->apic_id);
901 return 0; /* its already been counted */
904 /* add another AP to list, if less than max number of CPUs */
905 else if (cpu < MAXCPU) {
906 mp_set_cpuids(cpu, entry->apic_id);
914 * Map a physical memory address representing I/O into KVA. The I/O
915 * block is assumed not to cross a page boundary.
918 ioapic_map(vm_paddr_t pa)
920 KKASSERT(pa < 0x100000000LL);
922 return pmap_mapdev_uncacheable(pa, PAGE_SIZE);
926 * start each AP in our list
929 start_all_aps(u_int boot_addr)
931 vm_offset_t va = boot_address + KERNBASE;
932 u_int64_t *pt4, *pt3, *pt2;
939 u_long mpbioswarmvec;
940 struct mdglobaldata *gd;
941 struct privatespace *ps;
943 POSTCODE(START_ALL_APS_POST);
945 /* install the AP 1st level boot code */
946 pmap_kenter(va, boot_address);
947 cpu_invlpg((void *)va); /* JG XXX */
948 bcopy(mptramp_start, (void *)va, bootMP_size);
950 /* Locate the page tables, they'll be below the trampoline */
951 pt4 = (u_int64_t *)(uintptr_t)(mptramp_pagetables + KERNBASE);
952 pt3 = pt4 + (PAGE_SIZE) / sizeof(u_int64_t);
953 pt2 = pt3 + (PAGE_SIZE) / sizeof(u_int64_t);
955 /* Create the initial 1GB replicated page tables */
956 for (i = 0; i < 512; i++) {
957 /* Each slot of the level 4 pages points to the same level 3 page */
958 pt4[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + PAGE_SIZE);
959 pt4[i] |= PG_V | PG_RW | PG_U;
961 /* Each slot of the level 3 pages points to the same level 2 page */
962 pt3[i] = (u_int64_t)(uintptr_t)(mptramp_pagetables + (2 * PAGE_SIZE));
963 pt3[i] |= PG_V | PG_RW | PG_U;
965 /* The level 2 page slots are mapped with 2MB pages for 1GB. */
966 pt2[i] = i * (2 * 1024 * 1024);
967 pt2[i] |= PG_V | PG_RW | PG_PS | PG_U;
970 /* save the current value of the warm-start vector */
971 mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
972 outb(CMOS_REG, BIOS_RESET);
973 mpbiosreason = inb(CMOS_DATA);
975 /* setup a vector to our boot code */
976 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
977 *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
978 outb(CMOS_REG, BIOS_RESET);
979 outb(CMOS_DATA, BIOS_WARM); /* 'warm-start' */
982 * If we have a TSC we can figure out the SMI interrupt rate.
983 * The SMI does not necessarily use a constant rate. Spend
984 * up to 250ms trying to figure it out.
987 if (cpu_feature & CPUID_TSC) {
988 set_apic_timer(275000);
989 smilast = read_apic_timer();
990 for (x = 0; x < 20 && read_apic_timer(); ++x) {
991 smicount = smitest();
992 if (smibest == 0 || smilast - smicount < smibest)
993 smibest = smilast - smicount;
996 if (smibest > 250000)
999 smibest = smibest * (int64_t)1000000 /
1000 get_apic_timer_frequency();
1004 kprintf("SMI Frequency (worst case): %d Hz (%d us)\n",
1005 1000000 / smibest, smibest);
1008 for (x = 1; x <= mp_naps; ++x) {
1010 /* This is a bit verbose, it will go away soon. */
1012 /* first page of AP's private space */
1013 pg = x * x86_64_btop(sizeof(struct privatespace));
1015 /* allocate new private data page(s) */
1016 gd = (struct mdglobaldata *)kmem_alloc(&kernel_map,
1017 MDGLOBALDATA_BASEALLOC_SIZE);
1019 gd = &CPU_prvspace[x].mdglobaldata; /* official location */
1020 bzero(gd, sizeof(*gd));
1021 gd->mi.gd_prvspace = ps = &CPU_prvspace[x];
1023 /* prime data page for it to use */
1024 mi_gdinit(&gd->mi, x);
1026 gd->mi.gd_ipiq = (void *)kmem_alloc(&kernel_map, sizeof(lwkt_ipiq) * (mp_naps + 1));
1027 bzero(gd->mi.gd_ipiq, sizeof(lwkt_ipiq) * (mp_naps + 1));
1029 /* setup a vector to our boot code */
1030 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
1031 *((volatile u_short *) WARMBOOT_SEG) = (boot_addr >> 4);
1032 outb(CMOS_REG, BIOS_RESET);
1033 outb(CMOS_DATA, BIOS_WARM); /* 'warm-start' */
1036 * Setup the AP boot stack
1038 bootSTK = &ps->idlestack[UPAGES*PAGE_SIZE/2];
1041 /* attempt to start the Application Processor */
1042 CHECK_INIT(99); /* setup checkpoints */
1043 if (!start_ap(gd, boot_addr, smibest)) {
1044 kprintf("\nAP #%d (PHY# %d) failed!\n",
1046 CHECK_PRINT("trace"); /* show checkpoints */
1047 /* better panic as the AP may be running loose */
1048 kprintf("panic y/n? [y] ");
1049 if (cngetc() != 'n')
1052 CHECK_PRINT("trace"); /* show checkpoints */
1054 /* record its version info */
1055 cpu_apic_versions[x] = cpu_apic_versions[0];
1058 /* set ncpus to 1 + highest logical cpu. Not all may have come up */
1061 /* ncpus2 -- ncpus rounded down to the nearest power of 2 */
1062 for (shift = 0; (1 << shift) <= ncpus; ++shift)
1065 ncpus2_shift = shift;
1066 ncpus2 = 1 << shift;
1067 ncpus2_mask = ncpus2 - 1;
1069 /* ncpus_fit -- ncpus rounded up to the nearest power of 2 */
1070 if ((1 << shift) < ncpus)
1072 ncpus_fit = 1 << shift;
1073 ncpus_fit_mask = ncpus_fit - 1;
1075 /* build our map of 'other' CPUs */
1076 mycpu->gd_other_cpus = smp_startup_mask & ~CPUMASK(mycpu->gd_cpuid);
1077 mycpu->gd_ipiq = (void *)kmem_alloc(&kernel_map, sizeof(lwkt_ipiq) * ncpus);
1078 bzero(mycpu->gd_ipiq, sizeof(lwkt_ipiq) * ncpus);
1080 /* fill in our (BSP) APIC version */
1081 cpu_apic_versions[0] = lapic->version;
1083 /* restore the warmstart vector */
1084 *(u_long *) WARMBOOT_OFF = mpbioswarmvec;
1085 outb(CMOS_REG, BIOS_RESET);
1086 outb(CMOS_DATA, mpbiosreason);
1089 * NOTE! The idlestack for the BSP was setup by locore. Finish
1090 * up, clean out the P==V mapping we did earlier.
1095 * Wait all APs to finish initializing LAPIC
1097 mp_finish_lapic = 1;
1099 kprintf("SMP: Waiting APs LAPIC initialization\n");
1100 if (cpu_feature & CPUID_TSC)
1101 tsc0_offset = rdtsc();
1104 while (smp_lapic_mask != smp_startup_mask) {
1106 if (cpu_feature & CPUID_TSC)
1107 tsc0_offset = rdtsc();
1109 while (try_mplock() == 0)
1112 /* number of APs actually started */
1118 * load the 1st level AP boot code into base memory.
1121 /* targets for relocation */
1122 extern void bigJump(void);
1123 extern void bootCodeSeg(void);
1124 extern void bootDataSeg(void);
1125 extern void MPentry(void);
1126 extern u_int MP_GDT;
1127 extern u_int mp_gdtbase;
1132 install_ap_tramp(u_int boot_addr)
1135 int size = *(int *) ((u_long) & bootMP_size);
1136 u_char *src = (u_char *) ((u_long) bootMP);
1137 u_char *dst = (u_char *) boot_addr + KERNBASE;
1138 u_int boot_base = (u_int) bootMP;
1143 POSTCODE(INSTALL_AP_TRAMP_POST);
1145 for (x = 0; x < size; ++x)
1149 * modify addresses in code we just moved to basemem. unfortunately we
1150 * need fairly detailed info about mpboot.s for this to work. changes
1151 * to mpboot.s might require changes here.
1154 /* boot code is located in KERNEL space */
1155 dst = (u_char *) boot_addr + KERNBASE;
1157 /* modify the lgdt arg */
1158 dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
1159 *dst32 = boot_addr + ((u_int) & MP_GDT - boot_base);
1161 /* modify the ljmp target for MPentry() */
1162 dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
1163 *dst32 = ((u_int) MPentry - KERNBASE);
1165 /* modify the target for boot code segment */
1166 dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
1167 dst8 = (u_int8_t *) (dst16 + 1);
1168 *dst16 = (u_int) boot_addr & 0xffff;
1169 *dst8 = ((u_int) boot_addr >> 16) & 0xff;
1171 /* modify the target for boot data segment */
1172 dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
1173 dst8 = (u_int8_t *) (dst16 + 1);
1174 *dst16 = (u_int) boot_addr & 0xffff;
1175 *dst8 = ((u_int) boot_addr >> 16) & 0xff;
1181 * This function starts the AP (application processor) identified
1182 * by the APIC ID 'physicalCpu'. It does quite a "song and dance"
1183 * to accomplish this. This is necessary because of the nuances
1184 * of the different hardware we might encounter. It ain't pretty,
1185 * but it seems to work.
1187 * NOTE: eventually an AP gets to ap_init(), which is called just
1188 * before the AP goes into the LWKT scheduler's idle loop.
1191 start_ap(struct mdglobaldata *gd, u_int boot_addr, int smibest)
1195 u_long icr_lo, icr_hi;
1197 POSTCODE(START_AP_POST);
1199 /* get the PHYSICAL APIC ID# */
1200 physical_cpu = CPU_TO_ID(gd->mi.gd_cpuid);
1202 /* calculate the vector */
1203 vector = (boot_addr >> 12) & 0xff;
1205 /* We don't want anything interfering */
1208 /* Make sure the target cpu sees everything */
1212 * Try to detect when a SMI has occurred, wait up to 200ms.
1214 * If a SMI occurs during an AP reset but before we issue
1215 * the STARTUP command, the AP may brick. To work around
1216 * this problem we hold off doing the AP startup until
1217 * after we have detected the SMI. Hopefully another SMI
1218 * will not occur before we finish the AP startup.
1220 * Retries don't seem to help. SMIs have a window of opportunity
1221 * and if USB->legacy keyboard emulation is enabled in the BIOS
1222 * the interrupt rate can be quite high.
1224 * NOTE: Don't worry about the L1 cache load, it might bloat
1225 * ldelta a little but ndelta will be so huge when the SMI
1226 * occurs the detection logic will still work fine.
1229 set_apic_timer(200000);
1234 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
1235 * and running the target CPU. OR this INIT IPI might be latched (P5
1236 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
1239 * see apic/apicreg.h for icr bit definitions.
1241 * TIME CRITICAL CODE, DO NOT DO ANY KPRINTFS IN THE HOT PATH.
1245 * Setup the address for the target AP. We can setup
1246 * icr_hi once and then just trigger operations with
1249 icr_hi = lapic->icr_hi & ~APIC_ID_MASK;
1250 icr_hi |= (physical_cpu << 24);
1251 icr_lo = lapic->icr_lo & 0xfff00000;
1252 lapic->icr_hi = icr_hi;
1255 * Do an INIT IPI: assert RESET
1257 * Use edge triggered mode to assert INIT
1259 lapic->icr_lo = icr_lo | 0x00004500;
1260 while (lapic->icr_lo & APIC_DELSTAT_MASK)
1264 * The spec calls for a 10ms delay but we may have to use a
1265 * MUCH lower delay to avoid bricking an AP due to a fast SMI
1266 * interrupt. We have other loops here too and dividing by 2
1267 * doesn't seem to be enough even after subtracting 350us,
1268 * so we divide by 4.
1270 * Our minimum delay is 150uS, maximum is 10ms. If no SMI
1271 * interrupt was detected we use the full 10ms.
1275 else if (smibest < 150 * 4 + 350)
1277 else if ((smibest - 350) / 4 < 10000)
1278 u_sleep((smibest - 350) / 4);
1283 * Do an INIT IPI: deassert RESET
1285 * Use level triggered mode to deassert. It is unclear
1286 * why we need to do this.
1288 lapic->icr_lo = icr_lo | 0x00008500;
1289 while (lapic->icr_lo & APIC_DELSTAT_MASK)
1291 u_sleep(150); /* wait 150us */
1294 * Next we do a STARTUP IPI: the previous INIT IPI might still be
1295 * latched, (P5 bug) this 1st STARTUP would then terminate
1296 * immediately, and the previously started INIT IPI would continue. OR
1297 * the previous INIT IPI has already run. and this STARTUP IPI will
1298 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1301 lapic->icr_lo = icr_lo | 0x00000600 | vector;
1302 while (lapic->icr_lo & APIC_DELSTAT_MASK)
1304 u_sleep(200); /* wait ~200uS */
1307 * Finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1308 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1309 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1310 * recognized after hardware RESET or INIT IPI.
1312 lapic->icr_lo = icr_lo | 0x00000600 | vector;
1313 while (lapic->icr_lo & APIC_DELSTAT_MASK)
1316 /* Resume normal operation */
1319 /* wait for it to start, see ap_init() */
1320 set_apic_timer(5000000);/* == 5 seconds */
1321 while (read_apic_timer()) {
1322 if (smp_startup_mask & CPUMASK(gd->mi.gd_cpuid))
1323 return 1; /* return SUCCESS */
1326 return 0; /* return FAILURE */
1341 while (read_apic_timer()) {
1343 for (count = 0; count < 100; ++count)
1344 ntsc = rdtsc(); /* force loop to occur */
1346 ndelta = ntsc - ltsc;
1347 if (ldelta > ndelta)
1349 if (ndelta > ldelta * 2)
1352 ldelta = ntsc - ltsc;
1355 return(read_apic_timer());
1359 * Synchronously flush the TLB on all other CPU's. The current cpu's
1360 * TLB is not flushed. If the caller wishes to flush the current cpu's
1361 * TLB the caller must call cpu_invltlb() in addition to smp_invltlb().
1363 * NOTE: If for some reason we were unable to start all cpus we cannot
1364 * safely use broadcast IPIs.
1367 static cpumask_t smp_invltlb_req;
1369 #define SMP_INVLTLB_DEBUG
1375 struct mdglobaldata *md = mdcpu;
1376 #ifdef SMP_INVLTLB_DEBUG
1381 crit_enter_gd(&md->mi);
1382 md->gd_invltlb_ret = 0;
1383 ++md->mi.gd_cnt.v_smpinvltlb;
1384 atomic_set_cpumask(&smp_invltlb_req, md->mi.gd_cpumask);
1385 #ifdef SMP_INVLTLB_DEBUG
1388 if (smp_startup_mask == smp_active_mask) {
1389 all_but_self_ipi(XINVLTLB_OFFSET);
1391 selected_apic_ipi(smp_active_mask & ~md->mi.gd_cpumask,
1392 XINVLTLB_OFFSET, APIC_DELMODE_FIXED);
1395 #ifdef SMP_INVLTLB_DEBUG
1397 kprintf("smp_invltlb: ipi sent\n");
1399 while ((md->gd_invltlb_ret & smp_active_mask & ~md->mi.gd_cpumask) !=
1400 (smp_active_mask & ~md->mi.gd_cpumask)) {
1403 #ifdef SMP_INVLTLB_DEBUG
1405 if (++count == 400000000) {
1406 print_backtrace(-1);
1407 kprintf("smp_invltlb: endless loop %08lx %08lx, "
1408 "rflags %016jx retry",
1409 (long)md->gd_invltlb_ret,
1410 (long)smp_invltlb_req,
1411 (intmax_t)read_rflags());
1412 __asm __volatile ("sti");
1415 lwkt_process_ipiq();
1417 int bcpu = BSFCPUMASK(~md->gd_invltlb_ret &
1418 ~md->mi.gd_cpumask &
1422 kprintf("bcpu %d\n", bcpu);
1423 xgd = globaldata_find(bcpu);
1424 kprintf("thread %p %s\n", xgd->gd_curthread, xgd->gd_curthread->td_comm);
1427 Debugger("giving up");
1433 atomic_clear_cpumask(&smp_invltlb_req, md->mi.gd_cpumask);
1434 crit_exit_gd(&md->mi);
1441 * Called from Xinvltlb assembly with interrupts disabled. We didn't
1442 * bother to bump the critical section count or nested interrupt count
1443 * so only do very low level operations here.
1446 smp_invltlb_intr(void)
1448 struct mdglobaldata *md = mdcpu;
1449 struct mdglobaldata *omd;
1454 mask = smp_invltlb_req;
1457 cpu = BSFCPUMASK(mask);
1458 mask &= ~CPUMASK(cpu);
1459 omd = (struct mdglobaldata *)globaldata_find(cpu);
1460 atomic_set_cpumask(&omd->gd_invltlb_ret, md->mi.gd_cpumask);
1467 * When called the executing CPU will send an IPI to all other CPUs
1468 * requesting that they halt execution.
1470 * Usually (but not necessarily) called with 'other_cpus' as its arg.
1472 * - Signals all CPUs in map to stop.
1473 * - Waits for each to stop.
1480 * XXX FIXME: this is not MP-safe, needs a lock to prevent multiple CPUs
1481 * from executing at same time.
1484 stop_cpus(cpumask_t map)
1486 map &= smp_active_mask;
1488 /* send the Xcpustop IPI to all CPUs in map */
1489 selected_apic_ipi(map, XCPUSTOP_OFFSET, APIC_DELMODE_FIXED);
1491 while ((stopped_cpus & map) != map)
1499 * Called by a CPU to restart stopped CPUs.
1501 * Usually (but not necessarily) called with 'stopped_cpus' as its arg.
1503 * - Signals all CPUs in map to restart.
1504 * - Waits for each to restart.
1512 restart_cpus(cpumask_t map)
1514 /* signal other cpus to restart */
1515 started_cpus = map & smp_active_mask;
1517 while ((stopped_cpus & map) != 0) /* wait for each to clear its bit */
1524 * This is called once the mpboot code has gotten us properly relocated
1525 * and the MMU turned on, etc. ap_init() is actually the idle thread,
1526 * and when it returns the scheduler will call the real cpu_idle() main
1527 * loop for the idlethread. Interrupts are disabled on entry and should
1528 * remain disabled at return.
1536 * Adjust smp_startup_mask to signal the BSP that we have started
1537 * up successfully. Note that we do not yet hold the BGL. The BSP
1538 * is waiting for our signal.
1540 * We can't set our bit in smp_active_mask yet because we are holding
1541 * interrupts physically disabled and remote cpus could deadlock
1542 * trying to send us an IPI.
1544 smp_startup_mask |= CPUMASK(mycpu->gd_cpuid);
1548 * Interlock for LAPIC initialization. Wait until mp_finish_lapic is
1549 * non-zero, then get the MP lock.
1551 * Note: We are in a critical section.
1553 * Note: we are the idle thread, we can only spin.
1555 * Note: The load fence is memory volatile and prevents the compiler
1556 * from improperly caching mp_finish_lapic, and the cpu from improperly
1559 while (mp_finish_lapic == 0)
1561 while (try_mplock() == 0)
1564 if (cpu_feature & CPUID_TSC) {
1566 * The BSP is constantly updating tsc0_offset, figure out
1567 * the relative difference to synchronize ktrdump.
1569 tsc_offsets[mycpu->gd_cpuid] = rdtsc() - tsc0_offset;
1572 /* BSP may have changed PTD while we're waiting for the lock */
1575 /* Build our map of 'other' CPUs. */
1576 mycpu->gd_other_cpus = smp_startup_mask & ~CPUMASK(mycpu->gd_cpuid);
1578 /* A quick check from sanity claus */
1579 apic_id = (apic_id_to_logical[(lapic->id & 0xff000000) >> 24]);
1580 if (mycpu->gd_cpuid != apic_id) {
1581 kprintf("SMP: cpuid = %d\n", mycpu->gd_cpuid);
1582 kprintf("SMP: apic_id = %d lapicid %d\n",
1583 apic_id, (lapic->id & 0xff000000) >> 24);
1585 kprintf("PTD[MPPTDI] = %p\n", (void *)PTD[MPPTDI]);
1587 panic("cpuid mismatch! boom!!");
1590 /* Initialize AP's local APIC for irq's */
1593 /* LAPIC initialization is done */
1594 smp_lapic_mask |= CPUMASK(mycpu->gd_cpuid);
1597 /* Let BSP move onto the next initialization stage */
1601 * Interlock for finalization. Wait until mp_finish is non-zero,
1602 * then get the MP lock.
1604 * Note: We are in a critical section.
1606 * Note: we are the idle thread, we can only spin.
1608 * Note: The load fence is memory volatile and prevents the compiler
1609 * from improperly caching mp_finish, and the cpu from improperly
1612 while (mp_finish == 0)
1614 while (try_mplock() == 0)
1617 /* BSP may have changed PTD while we're waiting for the lock */
1620 /* Set memory range attributes for this CPU to match the BSP */
1621 mem_range_AP_init();
1624 * Once we go active we must process any IPIQ messages that may
1625 * have been queued, because no actual IPI will occur until we
1626 * set our bit in the smp_active_mask. If we don't the IPI
1627 * message interlock could be left set which would also prevent
1630 * The idle loop doesn't expect the BGL to be held and while
1631 * lwkt_switch() normally cleans things up this is a special case
1632 * because we returning almost directly into the idle loop.
1634 * The idle thread is never placed on the runq, make sure
1635 * nothing we've done put it there.
1637 KKASSERT(get_mplock_count(curthread) == 1);
1638 smp_active_mask |= CPUMASK(mycpu->gd_cpuid);
1641 * Enable interrupts here. idle_restore will also do it, but
1642 * doing it here lets us clean up any strays that got posted to
1643 * the CPU during the AP boot while we are still in a critical
1646 __asm __volatile("sti; pause; pause"::);
1647 bzero(mdcpu->gd_ipending, sizeof(mdcpu->gd_ipending));
1649 initclocks_pcpu(); /* clock interrupts (via IPIs) */
1650 lwkt_process_ipiq();
1653 * Releasing the mp lock lets the BSP finish up the SMP init
1656 KKASSERT((curthread->td_flags & TDF_RUNQ) == 0);
1660 * Get SMP fully working before we start initializing devices.
1668 kprintf("Finish MP startup\n");
1670 while (smp_active_mask != smp_startup_mask)
1672 while (try_mplock() == 0)
1675 kprintf("Active CPU Mask: %016jx\n",
1676 (uintmax_t)smp_active_mask);
1680 SYSINIT(finishsmp, SI_BOOT2_FINISH_SMP, SI_ORDER_FIRST, ap_finish, NULL)
1683 cpu_send_ipiq(int dcpu)
1685 if (CPUMASK(dcpu) & smp_active_mask)
1686 single_apic_ipi(dcpu, XIPIQ_OFFSET, APIC_DELMODE_FIXED);
1689 #if 0 /* single_apic_ipi_passive() not working yet */
1691 * Returns 0 on failure, 1 on success
1694 cpu_send_ipiq_passive(int dcpu)
1697 if (CPUMASK(dcpu) & smp_active_mask) {
1698 r = single_apic_ipi_passive(dcpu, XIPIQ_OFFSET,
1699 APIC_DELMODE_FIXED);
1706 mptable_bus_info_callback(void *xarg, const void *pos, int type)
1708 struct mptable_bus_info *bus_info = xarg;
1709 const struct BUSENTRY *ent;
1710 struct mptable_bus *bus;
1716 TAILQ_FOREACH(bus, &bus_info->mbi_list, mb_link) {
1717 if (bus->mb_id == ent->bus_id) {
1718 kprintf("mptable_bus_info_alloc: duplicated bus id "
1719 "(%d)\n", bus->mb_id);
1725 if (strncmp(ent->bus_type, "PCI", 3) == 0) {
1726 bus = kmalloc(sizeof(*bus), M_TEMP, M_WAITOK | M_ZERO);
1727 bus->mb_type = MPTABLE_BUS_PCI;
1728 } else if (strncmp(ent->bus_type, "ISA", 3) == 0) {
1729 bus = kmalloc(sizeof(*bus), M_TEMP, M_WAITOK | M_ZERO);
1730 bus->mb_type = MPTABLE_BUS_ISA;
1734 bus->mb_id = ent->bus_id;
1735 TAILQ_INSERT_TAIL(&bus_info->mbi_list, bus, mb_link);
1741 mptable_bus_info_alloc(const mpcth_t cth, struct mptable_bus_info *bus_info)
1745 bzero(bus_info, sizeof(*bus_info));
1746 TAILQ_INIT(&bus_info->mbi_list);
1748 error = mptable_iterate_entries(cth, mptable_bus_info_callback, bus_info);
1750 mptable_bus_info_free(bus_info);
1754 mptable_bus_info_free(struct mptable_bus_info *bus_info)
1756 struct mptable_bus *bus;
1758 while ((bus = TAILQ_FIRST(&bus_info->mbi_list)) != NULL) {
1759 TAILQ_REMOVE(&bus_info->mbi_list, bus, mb_link);
1764 struct mptable_lapic_cbarg1 {
1767 u_int ht_apicid_mask;
1771 mptable_lapic_pass1_callback(void *xarg, const void *pos, int type)
1773 const struct PROCENTRY *ent;
1774 struct mptable_lapic_cbarg1 *arg = xarg;
1780 if ((ent->cpu_flags & PROCENTRY_FLAG_EN) == 0)
1784 if (ent->apic_id < 32) {
1785 arg->ht_apicid_mask |= 1 << ent->apic_id;
1786 } else if (arg->ht_fixup) {
1787 kprintf("MPTABLE: lapic id > 32, disable HTT fixup\n");
1793 struct mptable_lapic_cbarg2 {
1800 mptable_lapic_pass2_callback(void *xarg, const void *pos, int type)
1802 const struct PROCENTRY *ent;
1803 struct mptable_lapic_cbarg2 *arg = xarg;
1809 if (ent->cpu_flags & PROCENTRY_FLAG_BP) {
1810 KKASSERT(!arg->found_bsp);
1814 if (processor_entry(ent, arg->cpu))
1817 if (arg->logical_cpus) {
1818 struct PROCENTRY proc;
1822 * Create fake mptable processor entries
1823 * and feed them to processor_entry() to
1824 * enumerate the logical CPUs.
1826 bzero(&proc, sizeof(proc));
1828 proc.cpu_flags = PROCENTRY_FLAG_EN;
1829 proc.apic_id = ent->apic_id;
1831 for (i = 1; i < arg->logical_cpus; i++) {
1833 processor_entry(&proc, arg->cpu);
1841 mptable_lapic_default(void)
1843 int ap_apicid, bsp_apicid;
1845 mp_naps = 1; /* exclude BSP */
1847 /* Map local apic before the id field is accessed */
1848 lapic_map(DEFAULT_APIC_BASE);
1850 bsp_apicid = APIC_ID(lapic->id);
1851 ap_apicid = (bsp_apicid == 0) ? 1 : 0;
1854 mp_set_cpuids(0, bsp_apicid);
1855 /* one and only AP */
1856 mp_set_cpuids(1, ap_apicid);
1862 * ID_TO_CPU(N), APIC ID to logical CPU table
1863 * CPU_TO_ID(N), logical CPU to APIC ID table
1866 mptable_lapic_enumerate(struct lapic_enumerator *e)
1868 struct mptable_pos mpt;
1869 struct mptable_lapic_cbarg1 arg1;
1870 struct mptable_lapic_cbarg2 arg2;
1872 int error, logical_cpus = 0;
1873 vm_offset_t lapic_addr;
1875 if (mptable_use_default) {
1876 mptable_lapic_default();
1880 error = mptable_map(&mpt);
1882 panic("mptable_lapic_enumerate mptable_map failed\n");
1883 KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
1887 /* Save local apic address */
1888 lapic_addr = (vm_offset_t)cth->apic_address;
1889 KKASSERT(lapic_addr != 0);
1892 * Find out how many CPUs do we have
1894 bzero(&arg1, sizeof(arg1));
1895 arg1.ht_fixup = 1; /* Apply ht fixup by default */
1897 error = mptable_iterate_entries(cth,
1898 mptable_lapic_pass1_callback, &arg1);
1900 panic("mptable_iterate_entries(lapic_pass1) failed\n");
1901 KKASSERT(arg1.cpu_count != 0);
1903 /* See if we need to fixup HT logical CPUs. */
1904 if (arg1.ht_fixup) {
1905 logical_cpus = mptable_hyperthread_fixup(arg1.ht_apicid_mask,
1907 if (logical_cpus != 0)
1908 arg1.cpu_count *= logical_cpus;
1910 mp_naps = arg1.cpu_count;
1912 /* Qualify the numbers again, after possible HT fixup */
1913 if (mp_naps > MAXCPU) {
1914 kprintf("Warning: only using %d of %d available CPUs!\n",
1920 --mp_naps; /* subtract the BSP */
1923 * Link logical CPU id to local apic id
1925 bzero(&arg2, sizeof(arg2));
1927 arg2.logical_cpus = logical_cpus;
1929 error = mptable_iterate_entries(cth,
1930 mptable_lapic_pass2_callback, &arg2);
1932 panic("mptable_iterate_entries(lapic_pass2) failed\n");
1933 KKASSERT(arg2.found_bsp);
1935 /* Map local apic */
1936 lapic_map(lapic_addr);
1938 mptable_unmap(&mpt);
1941 struct mptable_lapic_probe_cbarg {
1947 mptable_lapic_probe_callback(void *xarg, const void *pos, int type)
1949 const struct PROCENTRY *ent;
1950 struct mptable_lapic_probe_cbarg *arg = xarg;
1956 if ((ent->cpu_flags & PROCENTRY_FLAG_EN) == 0)
1960 if (ent->cpu_flags & PROCENTRY_FLAG_BP) {
1961 if (arg->found_bsp) {
1962 kprintf("more than one BSP in base MP table\n");
1971 mptable_lapic_probe(struct lapic_enumerator *e)
1973 struct mptable_pos mpt;
1974 struct mptable_lapic_probe_cbarg arg;
1978 if (mptable_fps_phyaddr == 0)
1981 if (mptable_use_default)
1984 error = mptable_map(&mpt);
1987 KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
1992 if (cth->apic_address == 0)
1995 bzero(&arg, sizeof(arg));
1996 error = mptable_iterate_entries(cth,
1997 mptable_lapic_probe_callback, &arg);
1999 if (arg.cpu_count == 0) {
2000 kprintf("MP table contains no processor entries\n");
2002 } else if (!arg.found_bsp) {
2003 kprintf("MP table does not contains BSP entry\n");
2008 mptable_unmap(&mpt);
2012 static struct lapic_enumerator mptable_lapic_enumerator = {
2013 .lapic_prio = LAPIC_ENUM_PRIO_MPTABLE,
2014 .lapic_probe = mptable_lapic_probe,
2015 .lapic_enumerate = mptable_lapic_enumerate
2019 mptable_lapic_enum_register(void)
2021 lapic_enumerator_register(&mptable_lapic_enumerator);
2023 SYSINIT(mptable_lapic, SI_BOOT2_PRESMP, SI_ORDER_ANY,
2024 mptable_lapic_enum_register, 0);
2027 mptable_ioapic_list_callback(void *xarg, const void *pos, int type)
2029 const struct IOAPICENTRY *ent;
2030 struct mptable_ioapic *nioapic, *ioapic;
2036 if ((ent->apic_flags & IOAPICENTRY_FLAG_EN) == 0)
2039 if (ent->apic_address == 0) {
2040 kprintf("mptable_ioapic_create_list: zero IOAPIC addr\n");
2044 TAILQ_FOREACH(ioapic, &mptable_ioapic_list, mio_link) {
2045 if (ioapic->mio_apic_id == ent->apic_id) {
2046 kprintf("mptable_ioapic_create_list: duplicated "
2047 "apic id %d\n", ioapic->mio_apic_id);
2050 if (ioapic->mio_addr == ent->apic_address) {
2051 kprintf("mptable_ioapic_create_list: overlapped "
2052 "IOAPIC addr 0x%08x", ioapic->mio_addr);
2057 nioapic = kmalloc(sizeof(*nioapic), M_DEVBUF, M_WAITOK | M_ZERO);
2058 nioapic->mio_apic_id = ent->apic_id;
2059 nioapic->mio_addr = ent->apic_address;
2062 * Create IOAPIC list in ascending order of APIC ID
2064 TAILQ_FOREACH_REVERSE(ioapic, &mptable_ioapic_list,
2065 mptable_ioapic_list, mio_link) {
2066 if (nioapic->mio_apic_id > ioapic->mio_apic_id) {
2067 TAILQ_INSERT_AFTER(&mptable_ioapic_list,
2068 ioapic, nioapic, mio_link);
2073 TAILQ_INSERT_HEAD(&mptable_ioapic_list, nioapic, mio_link);
2079 mptable_ioapic_create_list(void)
2081 struct mptable_ioapic *ioapic;
2082 struct mptable_pos mpt;
2085 if (mptable_fps_phyaddr == 0)
2088 if (mptable_use_default) {
2089 ioapic = kmalloc(sizeof(*ioapic), M_DEVBUF, M_WAITOK | M_ZERO);
2090 ioapic->mio_idx = 0;
2091 ioapic->mio_apic_id = 0; /* NOTE: any value is ok here */
2092 ioapic->mio_addr = 0xfec00000; /* XXX magic number */
2094 TAILQ_INSERT_HEAD(&mptable_ioapic_list, ioapic, mio_link);
2098 error = mptable_map(&mpt);
2100 panic("mptable_ioapic_create_list: mptable_map failed\n");
2101 KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
2103 error = mptable_iterate_entries(mpt.mp_cth,
2104 mptable_ioapic_list_callback, NULL);
2106 while ((ioapic = TAILQ_FIRST(&mptable_ioapic_list)) != NULL) {
2107 TAILQ_REMOVE(&mptable_ioapic_list, ioapic, mio_link);
2108 kfree(ioapic, M_DEVBUF);
2114 * Assign index number for each IOAPIC
2117 TAILQ_FOREACH(ioapic, &mptable_ioapic_list, mio_link) {
2118 ioapic->mio_idx = idx;
2122 mptable_unmap(&mpt);
2124 SYSINIT(mptable_ioapic_list, SI_BOOT2_PRESMP, SI_ORDER_SECOND,
2125 mptable_ioapic_create_list, 0);
2128 mptable_pci_int_callback(void *xarg, const void *pos, int type)
2130 const struct mptable_bus_info *bus_info = xarg;
2131 const struct mptable_ioapic *ioapic;
2132 const struct mptable_bus *bus;
2133 struct mptable_pci_int *pci_int;
2134 const struct INTENTRY *ent;
2135 int pci_pin, pci_dev;
2141 if (ent->int_type != 0)
2144 TAILQ_FOREACH(bus, &bus_info->mbi_list, mb_link) {
2145 if (bus->mb_type == MPTABLE_BUS_PCI &&
2146 bus->mb_id == ent->src_bus_id)
2152 TAILQ_FOREACH(ioapic, &mptable_ioapic_list, mio_link) {
2153 if (ioapic->mio_apic_id == ent->dst_apic_id)
2156 if (ioapic == NULL) {
2157 kprintf("MPTABLE: warning PCI int dst apic id %d "
2158 "does not exist\n", ent->dst_apic_id);
2162 pci_pin = ent->src_bus_irq & 0x3;
2163 pci_dev = (ent->src_bus_irq >> 2) & 0x1f;
2165 TAILQ_FOREACH(pci_int, &mptable_pci_int_list, mpci_link) {
2166 if (pci_int->mpci_bus == ent->src_bus_id &&
2167 pci_int->mpci_dev == pci_dev &&
2168 pci_int->mpci_pin == pci_pin) {
2169 if (pci_int->mpci_ioapic_idx == ioapic->mio_idx &&
2170 pci_int->mpci_ioapic_pin == ent->dst_apic_int) {
2171 kprintf("MPTABLE: warning duplicated "
2172 "PCI int entry for "
2173 "bus %d, dev %d, pin %d\n",
2179 kprintf("mptable_pci_int_register: "
2180 "conflict PCI int entry for "
2181 "bus %d, dev %d, pin %d, "
2182 "IOAPIC %d.%d -> %d.%d\n",
2186 pci_int->mpci_ioapic_idx,
2187 pci_int->mpci_ioapic_pin,
2195 pci_int = kmalloc(sizeof(*pci_int), M_DEVBUF, M_WAITOK | M_ZERO);
2197 pci_int->mpci_bus = ent->src_bus_id;
2198 pci_int->mpci_dev = pci_dev;
2199 pci_int->mpci_pin = pci_pin;
2200 pci_int->mpci_ioapic_idx = ioapic->mio_idx;
2201 pci_int->mpci_ioapic_pin = ent->dst_apic_int;
2203 TAILQ_INSERT_TAIL(&mptable_pci_int_list, pci_int, mpci_link);
2209 mptable_pci_int_register(void)
2211 struct mptable_bus_info bus_info;
2212 const struct mptable_bus *bus;
2213 struct mptable_pci_int *pci_int;
2214 struct mptable_pos mpt;
2215 int error, force_pci0, npcibus;
2218 if (mptable_fps_phyaddr == 0)
2221 if (mptable_use_default)
2224 if (TAILQ_EMPTY(&mptable_ioapic_list))
2227 error = mptable_map(&mpt);
2229 panic("mptable_pci_int_register: mptable_map failed\n");
2230 KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
2234 mptable_bus_info_alloc(cth, &bus_info);
2235 if (TAILQ_EMPTY(&bus_info.mbi_list))
2240 TAILQ_FOREACH(bus, &bus_info.mbi_list, mb_link) {
2241 if (bus->mb_type == MPTABLE_BUS_PCI)
2245 mptable_bus_info_free(&bus_info);
2247 } else if (npcibus == 1) {
2251 error = mptable_iterate_entries(cth,
2252 mptable_pci_int_callback, &bus_info);
2254 mptable_bus_info_free(&bus_info);
2257 while ((pci_int = TAILQ_FIRST(&mptable_pci_int_list)) != NULL) {
2258 TAILQ_REMOVE(&mptable_pci_int_list, pci_int, mpci_link);
2259 kfree(pci_int, M_DEVBUF);
2265 TAILQ_FOREACH(pci_int, &mptable_pci_int_list, mpci_link)
2266 pci_int->mpci_bus = 0;
2269 mptable_unmap(&mpt);
2271 SYSINIT(mptable_pci, SI_BOOT2_PRESMP, SI_ORDER_ANY,
2272 mptable_pci_int_register, 0);
2274 struct mptable_ioapic_probe_cbarg {
2275 const struct mptable_bus_info *bus_info;
2279 mptable_ioapic_probe_callback(void *xarg, const void *pos, int type)
2281 struct mptable_ioapic_probe_cbarg *arg = xarg;
2282 const struct mptable_ioapic *ioapic;
2283 const struct mptable_bus *bus;
2284 const struct INTENTRY *ent;
2290 if (ent->int_type != 0)
2293 TAILQ_FOREACH(bus, &arg->bus_info->mbi_list, mb_link) {
2294 if (bus->mb_type == MPTABLE_BUS_ISA &&
2295 bus->mb_id == ent->src_bus_id)
2301 TAILQ_FOREACH(ioapic, &mptable_ioapic_list, mio_link) {
2302 if (ioapic->mio_apic_id == ent->dst_apic_id)
2305 if (ioapic == NULL) {
2306 kprintf("MPTABLE: warning ISA int dst apic id %d "
2307 "does not exist\n", ent->dst_apic_id);
2311 /* XXX magic number */
2312 if (ent->src_bus_irq >= 16) {
2313 kprintf("mptable_ioapic_probe: invalid ISA irq (%d)\n",
2321 mptable_ioapic_probe(struct ioapic_enumerator *e)
2323 struct mptable_ioapic_probe_cbarg arg;
2324 struct mptable_bus_info bus_info;
2325 struct mptable_pos mpt;
2329 if (mptable_fps_phyaddr == 0)
2332 if (mptable_use_default)
2335 if (TAILQ_EMPTY(&mptable_ioapic_list))
2338 error = mptable_map(&mpt);
2340 panic("mptable_ioapic_probe: mptable_map failed\n");
2341 KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
2345 mptable_bus_info_alloc(cth, &bus_info);
2347 bzero(&arg, sizeof(arg));
2348 arg.bus_info = &bus_info;
2350 error = mptable_iterate_entries(cth,
2351 mptable_ioapic_probe_callback, &arg);
2353 mptable_bus_info_free(&bus_info);
2354 mptable_unmap(&mpt);
2359 struct mptable_ioapic_int_cbarg {
2360 const struct mptable_bus_info *bus_info;
2365 mptable_ioapic_int_callback(void *xarg, const void *pos, int type)
2367 struct mptable_ioapic_int_cbarg *arg = xarg;
2368 const struct mptable_ioapic *ioapic;
2369 const struct mptable_bus *bus;
2370 const struct INTENTRY *ent;
2379 if (ent->int_type != 0)
2382 TAILQ_FOREACH(bus, &arg->bus_info->mbi_list, mb_link) {
2383 if (bus->mb_type == MPTABLE_BUS_ISA &&
2384 bus->mb_id == ent->src_bus_id)
2390 TAILQ_FOREACH(ioapic, &mptable_ioapic_list, mio_link) {
2391 if (ioapic->mio_apic_id == ent->dst_apic_id)
2394 if (ioapic == NULL) {
2395 kprintf("MPTABLE: warning ISA int dst apic id %d "
2396 "does not exist\n", ent->dst_apic_id);
2400 if (ent->dst_apic_int >= ioapic->mio_npin) {
2401 panic("mptable_ioapic_enumerate: invalid I/O APIC "
2402 "pin %d, should be < %d",
2403 ent->dst_apic_int, ioapic->mio_npin);
2405 gsi = ioapic->mio_gsi_base + ent->dst_apic_int;
2407 if (ent->src_bus_irq != gsi) {
2409 kprintf("MPTABLE: INTSRC irq %d -> GSI %d\n",
2410 ent->src_bus_irq, gsi);
2412 ioapic_intsrc(ent->src_bus_irq, gsi,
2413 INTR_TRIGGER_EDGE, INTR_POLARITY_HIGH);
2419 mptable_ioapic_enumerate(struct ioapic_enumerator *e)
2421 struct mptable_bus_info bus_info;
2422 struct mptable_ioapic *ioapic;
2423 struct mptable_pos mpt;
2427 KKASSERT(mptable_fps_phyaddr != 0);
2428 KKASSERT(!TAILQ_EMPTY(&mptable_ioapic_list));
2430 TAILQ_FOREACH(ioapic, &mptable_ioapic_list, mio_link) {
2431 const struct mptable_ioapic *prev_ioapic;
2435 addr = ioapic_map(ioapic->mio_addr);
2437 ver = ioapic_read(addr, IOAPIC_VER);
2438 ioapic->mio_npin = ((ver & IOART_VER_MAXREDIR)
2439 >> MAXREDIRSHIFT) + 1;
2441 prev_ioapic = TAILQ_PREV(ioapic,
2442 mptable_ioapic_list, mio_link);
2443 if (prev_ioapic == NULL) {
2444 ioapic->mio_gsi_base = 0;
2446 ioapic->mio_gsi_base =
2447 prev_ioapic->mio_gsi_base +
2448 prev_ioapic->mio_npin;
2450 ioapic_add(addr, ioapic->mio_gsi_base, ioapic->mio_npin);
2453 kprintf("MPTABLE: IOAPIC addr 0x%08x, "
2454 "apic id %d, idx %d, gsi base %d, npin %d\n",
2456 ioapic->mio_apic_id,
2458 ioapic->mio_gsi_base,
2463 if (mptable_use_default) {
2465 kprintf("MPTABLE: INTSRC irq 0 -> GSI 2 (default)\n");
2466 ioapic_intsrc(0, 2, INTR_TRIGGER_EDGE, INTR_POLARITY_HIGH);
2470 error = mptable_map(&mpt);
2472 panic("mptable_ioapic_probe: mptable_map failed\n");
2473 KKASSERT(!MPTABLE_POS_USE_DEFAULT(&mpt));
2477 mptable_bus_info_alloc(cth, &bus_info);
2479 if (TAILQ_EMPTY(&bus_info.mbi_list)) {
2481 kprintf("MPTABLE: INTSRC irq 0 -> GSI 2 (no bus)\n");
2482 ioapic_intsrc(0, 2, INTR_TRIGGER_EDGE, INTR_POLARITY_HIGH);
2484 struct mptable_ioapic_int_cbarg arg;
2486 bzero(&arg, sizeof(arg));
2487 arg.bus_info = &bus_info;
2489 error = mptable_iterate_entries(cth,
2490 mptable_ioapic_int_callback, &arg);
2492 panic("mptable_ioapic_int failed\n");
2494 if (arg.ioapic_nint == 0) {
2496 kprintf("MPTABLE: INTSRC irq 0 -> GSI 2 "
2499 ioapic_intsrc(0, 2, INTR_TRIGGER_EDGE,
2500 INTR_POLARITY_HIGH);
2504 mptable_bus_info_free(&bus_info);
2506 mptable_unmap(&mpt);
2509 static struct ioapic_enumerator mptable_ioapic_enumerator = {
2510 .ioapic_prio = IOAPIC_ENUM_PRIO_MPTABLE,
2511 .ioapic_probe = mptable_ioapic_probe,
2512 .ioapic_enumerate = mptable_ioapic_enumerate
2516 mptable_ioapic_enum_register(void)
2518 ioapic_enumerator_register(&mptable_ioapic_enumerator);
2520 SYSINIT(mptable_ioapic, SI_BOOT2_PRESMP, SI_ORDER_ANY,
2521 mptable_ioapic_enum_register, 0);
2524 mptable_pci_int_dump(void)
2526 const struct mptable_pci_int *pci_int;
2528 TAILQ_FOREACH(pci_int, &mptable_pci_int_list, mpci_link) {
2529 kprintf("MPTABLE: %d:%d INT%c -> IOAPIC %d.%d\n",
2532 pci_int->mpci_pin + 'A',
2533 pci_int->mpci_ioapic_idx,
2534 pci_int->mpci_ioapic_pin);
2539 mptable_pci_int_route(int bus, int dev, int pin, int intline)
2541 const struct mptable_pci_int *pci_int;
2545 --pin; /* zero based */
2547 TAILQ_FOREACH(pci_int, &mptable_pci_int_list, mpci_link) {
2548 if (pci_int->mpci_bus == bus &&
2549 pci_int->mpci_dev == dev &&
2550 pci_int->mpci_pin == pin)
2553 if (pci_int != NULL) {
2556 gsi = ioapic_gsi(pci_int->mpci_ioapic_idx,
2557 pci_int->mpci_ioapic_pin);
2559 irq = ioapic_abi_find_gsi(gsi,
2560 INTR_TRIGGER_LEVEL, INTR_POLARITY_LOW);
2566 kprintf("MPTABLE: fixed interrupt routing "
2567 "for %d:%d INT%c\n", bus, dev, pin + 'A');
2570 irq = ioapic_abi_find_irq(intline,
2571 INTR_TRIGGER_LEVEL, INTR_POLARITY_LOW);
2574 if (irq >= 0 && bootverbose) {
2575 kprintf("MPTABLE: %d:%d INT%c routed to irq %d\n",
2576 bus, dev, pin + 'A', irq);