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
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
31 #include "opt_kstack_pages.h"
32 #include "opt_mp_watchdog.h"
34 #include "opt_sched.h"
39 #error How did you get here?
43 #error The apic device is required for SMP, add "device apic" to your config file.
45 #if defined(CPU_DISABLE_CMPXCHG) && !defined(COMPILING_LINT)
46 #error SMP not supported with CPU_DISABLE_CMPXCHG
50 #include <sys/param.h>
51 #include <sys/systm.h>
53 #include <sys/cons.h> /* cngetc() */
57 #include <sys/kernel.h>
60 #include <sys/malloc.h>
61 #include <sys/memrange.h>
62 #include <sys/mutex.h>
65 #include <sys/sched.h>
67 #include <sys/sysctl.h>
70 #include <vm/vm_param.h>
72 #include <vm/vm_kern.h>
73 #include <vm/vm_extern.h>
75 #include <machine/apicreg.h>
76 #include <machine/clock.h>
77 #include <machine/cputypes.h>
78 #include <machine/mca.h>
79 #include <machine/md_var.h>
80 #include <machine/mp_watchdog.h>
81 #include <machine/pcb.h>
82 #include <machine/psl.h>
83 #include <machine/smp.h>
84 #include <machine/specialreg.h>
86 #define WARMBOOT_TARGET 0
87 #define WARMBOOT_OFF (KERNBASE + 0x0467)
88 #define WARMBOOT_SEG (KERNBASE + 0x0469)
90 #define CMOS_REG (0x70)
91 #define CMOS_DATA (0x71)
92 #define BIOS_RESET (0x0f)
93 #define BIOS_WARM (0x0a)
96 * this code MUST be enabled here and in mpboot.s.
97 * it follows the very early stages of AP boot by placing values in CMOS ram.
98 * it NORMALLY will never be needed and thus the primitive method for enabling.
103 #if defined(CHECK_POINTS) && !defined(PC98)
104 #define CHECK_READ(A) (outb(CMOS_REG, (A)), inb(CMOS_DATA))
105 #define CHECK_WRITE(A,D) (outb(CMOS_REG, (A)), outb(CMOS_DATA, (D)))
107 #define CHECK_INIT(D); \
108 CHECK_WRITE(0x34, (D)); \
109 CHECK_WRITE(0x35, (D)); \
110 CHECK_WRITE(0x36, (D)); \
111 CHECK_WRITE(0x37, (D)); \
112 CHECK_WRITE(0x38, (D)); \
113 CHECK_WRITE(0x39, (D));
115 #define CHECK_PRINT(S); \
116 printf("%s: %d, %d, %d, %d, %d, %d\n", \
125 #else /* CHECK_POINTS */
127 #define CHECK_INIT(D)
128 #define CHECK_PRINT(S)
129 #define CHECK_WRITE(A, D)
131 #endif /* CHECK_POINTS */
133 /* lock region used by kernel profiling */
136 int mp_naps; /* # of Applications processors */
137 int boot_cpu_id = -1; /* designated BSP */
139 extern struct pcpu __pcpu[];
141 /* AP uses this during bootstrap. Do not staticize. */
145 /* Free these after use */
146 void *bootstacks[MAXCPU];
149 /* Hotwire a 0->4MB V==P mapping */
150 extern pt_entry_t *KPTphys;
152 struct pcb stoppcbs[MAXCPU];
154 /* Variables needed for SMP tlb shootdown. */
155 vm_offset_t smp_tlb_addr1;
156 vm_offset_t smp_tlb_addr2;
157 volatile int smp_tlb_wait;
160 /* Interrupt counts. */
161 static u_long *ipi_preempt_counts[MAXCPU];
162 static u_long *ipi_ast_counts[MAXCPU];
163 u_long *ipi_invltlb_counts[MAXCPU];
164 u_long *ipi_invlrng_counts[MAXCPU];
165 u_long *ipi_invlpg_counts[MAXCPU];
166 u_long *ipi_invlcache_counts[MAXCPU];
167 u_long *ipi_rendezvous_counts[MAXCPU];
168 u_long *ipi_lazypmap_counts[MAXCPU];
169 static u_long *ipi_hardclock_counts[MAXCPU];
170 static u_long *ipi_statclock_counts[MAXCPU];
174 * Local data and functions.
177 static u_int logical_cpus;
178 static volatile cpumask_t ipi_nmi_pending;
180 /* used to hold the AP's until we are ready to release them */
181 static struct mtx ap_boot_mtx;
183 /* Set to 1 once we're ready to let the APs out of the pen. */
184 static volatile int aps_ready = 0;
187 * Store data from cpu_add() until later in the boot when we actually setup
194 int cpu_hyperthread:1;
195 } static cpu_info[MAX_APIC_ID + 1];
196 int cpu_apic_ids[MAXCPU];
197 int apic_cpuids[MAX_APIC_ID + 1];
199 /* Holds pending bitmap based IPIs per CPU */
200 static volatile u_int cpu_ipi_pending[MAXCPU];
202 static u_int boot_address;
203 static int cpu_logical;
204 static int cpu_cores;
206 static void assign_cpu_ids(void);
207 static void install_ap_tramp(void);
208 static void set_interrupt_apic_ids(void);
209 static int start_all_aps(void);
210 static int start_ap(int apic_id);
211 static void release_aps(void *dummy);
213 static int hlt_logical_cpus;
214 static u_int hyperthreading_cpus;
215 static cpumask_t hyperthreading_cpus_mask;
216 static int hyperthreading_allowed = 1;
217 static struct sysctl_ctx_list logical_cpu_clist;
220 mem_range_AP_init(void)
222 if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
223 mem_range_softc.mr_op->initAP(&mem_range_softc);
237 /* We only support two levels for now. */
238 for (i = 0; i < 3; i++) {
239 cpuid_count(0x0B, i, p);
241 logical = p[1] &= 0xffff;
242 type = (p[2] >> 8) & 0xff;
243 if (type == 0 || logical == 0)
245 for (cnt = 0, x = 0; x <= MAX_APIC_ID; x++) {
246 if (!cpu_info[x].cpu_present ||
247 cpu_info[x].cpu_disabled)
249 if (x >> bits == boot_cpu_id >> bits)
252 if (type == CPUID_TYPE_SMT)
254 else if (type == CPUID_TYPE_CORE)
257 if (cpu_logical == 0)
259 cpu_cores /= cpu_logical;
265 u_int threads_per_cache, p[4];
271 * If this CPU supports HTT or CMP then mention the
272 * number of physical/logical cores it contains.
274 if (cpu_feature & CPUID_HTT)
275 htt = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
276 if (cpu_vendor_id == CPU_VENDOR_AMD && (amd_feature2 & AMDID2_CMP))
277 cmp = (cpu_procinfo2 & AMDID_CMP_CORES) + 1;
278 else if (cpu_vendor_id == CPU_VENDOR_INTEL && (cpu_high >= 4)) {
279 cpuid_count(4, 0, p);
280 if ((p[0] & 0x1f) != 0)
281 cmp = ((p[0] >> 26) & 0x3f) + 1;
284 cpu_logical = htt / cmp;
286 /* Setup the initial logical CPUs info. */
287 if (cpu_feature & CPUID_HTT)
288 logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
291 * Work out if hyperthreading is *really* enabled. This
292 * is made really ugly by the fact that processors lie: Dual
293 * core processors claim to be hyperthreaded even when they're
294 * not, presumably because they want to be treated the same
295 * way as HTT with respect to per-cpu software licensing.
296 * At the time of writing (May 12, 2005) the only hyperthreaded
297 * cpus are from Intel, and Intel's dual-core processors can be
298 * identified via the "deterministic cache parameters" cpuid
302 * First determine if this is an Intel processor which claims
303 * to have hyperthreading support.
305 if ((cpu_feature & CPUID_HTT) && cpu_vendor_id == CPU_VENDOR_INTEL) {
307 * If the "deterministic cache parameters" cpuid calls
308 * are available, use them.
311 /* Ask the processor about the L1 cache. */
312 for (i = 0; i < 1; i++) {
313 cpuid_count(4, i, p);
314 threads_per_cache = ((p[0] & 0x3ffc000) >> 14) + 1;
315 if (hyperthreading_cpus < threads_per_cache)
316 hyperthreading_cpus = threads_per_cache;
317 if ((p[0] & 0x1f) == 0)
323 * If the deterministic cache parameters are not
324 * available, or if no caches were reported to exist,
325 * just accept what the HTT flag indicated.
327 if (hyperthreading_cpus == 0)
328 hyperthreading_cpus = logical_cpus;
335 static int cpu_topo_probed = 0;
340 logical_cpus = logical_cpus_mask = 0;
346 cpu_cores = mp_ncpus > 0 ? mp_ncpus : 1;
347 if (cpu_logical == 0)
358 * Determine whether any threading flags are
362 if (cpu_logical > 1 && hyperthreading_cpus)
363 cg_flags = CG_FLAG_HTT;
364 else if (cpu_logical > 1)
365 cg_flags = CG_FLAG_SMT;
368 if (mp_ncpus % (cpu_cores * cpu_logical) != 0) {
369 printf("WARNING: Non-uniform processors.\n");
370 printf("WARNING: Using suboptimal topology.\n");
371 return (smp_topo_none());
374 * No multi-core or hyper-threaded.
376 if (cpu_logical * cpu_cores == 1)
377 return (smp_topo_none());
379 * Only HTT no multi-core.
381 if (cpu_logical > 1 && cpu_cores == 1)
382 return (smp_topo_1level(CG_SHARE_L1, cpu_logical, cg_flags));
384 * Only multi-core no HTT.
386 if (cpu_cores > 1 && cpu_logical == 1)
387 return (smp_topo_1level(CG_SHARE_L2, cpu_cores, cg_flags));
389 * Both HTT and multi-core.
391 return (smp_topo_2level(CG_SHARE_L2, cpu_cores,
392 CG_SHARE_L1, cpu_logical, cg_flags));
397 * Calculate usable address in base memory for AP trampoline code.
400 mp_bootaddress(u_int basemem)
403 boot_address = trunc_page(basemem); /* round down to 4k boundary */
404 if ((basemem - boot_address) < bootMP_size)
405 boot_address -= PAGE_SIZE; /* not enough, lower by 4k */
411 cpu_add(u_int apic_id, char boot_cpu)
414 if (apic_id > MAX_APIC_ID) {
415 panic("SMP: APIC ID %d too high", apic_id);
418 KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
420 cpu_info[apic_id].cpu_present = 1;
422 KASSERT(boot_cpu_id == -1,
423 ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
425 boot_cpu_id = apic_id;
426 cpu_info[apic_id].cpu_bsp = 1;
428 if (mp_ncpus < MAXCPU)
431 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
436 cpu_mp_setmaxid(void)
439 mp_maxid = MAXCPU - 1;
447 * Always record BSP in CPU map so that the mbuf init code works
453 * No CPUs were found, so this must be a UP system. Setup
454 * the variables to represent a system with a single CPU
461 /* At least one CPU was found. */
464 * One CPU was found, so this must be a UP system with
470 /* At least two CPUs were found. */
475 * Initialize the IPI handlers and start up the AP's.
482 /* Initialize the logical ID to APIC ID table. */
483 for (i = 0; i < MAXCPU; i++) {
484 cpu_apic_ids[i] = -1;
485 cpu_ipi_pending[i] = 0;
488 /* Install an inter-CPU IPI for TLB invalidation */
489 setidt(IPI_INVLTLB, IDTVEC(invltlb),
490 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
491 setidt(IPI_INVLPG, IDTVEC(invlpg),
492 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
493 setidt(IPI_INVLRNG, IDTVEC(invlrng),
494 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
496 /* Install an inter-CPU IPI for cache invalidation. */
497 setidt(IPI_INVLCACHE, IDTVEC(invlcache),
498 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
500 /* Install an inter-CPU IPI for lazy pmap release */
501 setidt(IPI_LAZYPMAP, IDTVEC(lazypmap),
502 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
504 /* Install an inter-CPU IPI for all-CPU rendezvous */
505 setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous),
506 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
508 /* Install generic inter-CPU IPI handler */
509 setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
510 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
512 /* Install an inter-CPU IPI for CPU stop/restart */
513 setidt(IPI_STOP, IDTVEC(cpustop),
514 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
517 /* Set boot_cpu_id if needed. */
518 if (boot_cpu_id == -1) {
519 boot_cpu_id = PCPU_GET(apic_id);
520 cpu_info[boot_cpu_id].cpu_bsp = 1;
522 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
523 ("BSP's APIC ID doesn't match boot_cpu_id"));
525 /* Probe logical/physical core configuration. */
530 /* Start each Application Processor */
533 set_interrupt_apic_ids();
538 * Print various information about the SMP system hardware and setup.
541 cpu_mp_announce(void)
543 const char *hyperthread;
546 printf("FreeBSD/SMP: %d package(s) x %d core(s)",
547 mp_ncpus / (cpu_cores * cpu_logical), cpu_cores);
548 if (hyperthreading_cpus > 1)
549 printf(" x %d HTT threads", cpu_logical);
550 else if (cpu_logical > 1)
551 printf(" x %d SMT threads", cpu_logical);
554 /* List active CPUs first. */
555 printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
556 for (i = 1; i < mp_ncpus; i++) {
557 if (cpu_info[cpu_apic_ids[i]].cpu_hyperthread)
561 printf(" cpu%d (AP%s): APIC ID: %2d\n", i, hyperthread,
565 /* List disabled CPUs last. */
566 for (i = 0; i <= MAX_APIC_ID; i++) {
567 if (!cpu_info[i].cpu_present || !cpu_info[i].cpu_disabled)
569 if (cpu_info[i].cpu_hyperthread)
573 printf(" cpu (AP%s): APIC ID: %2d (disabled)\n", hyperthread,
579 * AP CPU's call this to initialize themselves.
590 /* bootAP is set in start_ap() to our ID. */
593 /* Get per-cpu data */
596 /* prime data page for it to use */
597 pcpu_init(pc, myid, sizeof(struct pcpu));
598 dpcpu_init(dpcpu, myid);
599 pc->pc_apic_id = cpu_apic_ids[myid];
600 pc->pc_prvspace = pc;
601 pc->pc_curthread = 0;
603 gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
604 gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
606 for (x = 0; x < NGDT; x++) {
607 ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x].sd);
610 r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
611 r_gdt.rd_base = (int) &gdt[myid * NGDT];
612 lgdt(&r_gdt); /* does magic intra-segment return */
617 PCPU_SET(currentldt, _default_ldt);
619 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
620 gdt[myid * NGDT + GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;
621 PCPU_SET(common_tss.tss_esp0, 0); /* not used until after switch */
622 PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
623 PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
624 PCPU_SET(tss_gdt, &gdt[myid * NGDT + GPROC0_SEL].sd);
625 PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
628 PCPU_SET(fsgs_gdt, &gdt[myid * NGDT + GUFS_SEL].sd);
631 * Set to a known state:
632 * Set by mpboot.s: CR0_PG, CR0_PE
633 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
636 cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
638 CHECK_WRITE(0x38, 5);
640 /* Disable local APIC just to be sure. */
643 /* signal our startup to the BSP. */
645 CHECK_WRITE(0x39, 6);
647 /* Spin until the BSP releases the AP's. */
651 /* BSP may have changed PTD while we were waiting */
653 for (addr = 0; addr < NKPT * NBPDR - 1; addr += PAGE_SIZE)
656 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
660 /* Initialize the PAT MSR if present. */
663 /* set up CPU registers and state */
666 /* set up FPU state on the AP */
669 /* set up SSE registers */
673 /* Enable the PTE no-execute bit. */
674 if ((amd_feature & AMDID_NX) != 0) {
677 msr = rdmsr(MSR_EFER) | EFER_NXE;
678 wrmsr(MSR_EFER, msr);
682 /* A quick check from sanity claus */
683 if (PCPU_GET(apic_id) != lapic_id()) {
684 printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
685 printf("SMP: actual apic_id = %d\n", lapic_id());
686 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
687 panic("cpuid mismatch! boom!!");
690 /* Initialize curthread. */
691 KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
692 PCPU_SET(curthread, PCPU_GET(idlethread));
696 mtx_lock_spin(&ap_boot_mtx);
698 /* Init local apic for irq's */
701 /* Set memory range attributes for this CPU to match the BSP */
706 CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
707 printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
709 /* Determine if we are a logical CPU. */
710 if (logical_cpus > 1 && PCPU_GET(apic_id) % logical_cpus != 0)
711 logical_cpus_mask |= PCPU_GET(cpumask);
713 /* Determine if we are a hyperthread. */
714 if (hyperthreading_cpus > 1 &&
715 PCPU_GET(apic_id) % hyperthreading_cpus != 0)
716 hyperthreading_cpus_mask |= PCPU_GET(cpumask);
718 /* Build our map of 'other' CPUs. */
719 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
724 if (smp_cpus == mp_ncpus) {
725 /* enable IPI's, tlb shootdown, freezes etc */
726 atomic_store_rel_int(&smp_started, 1);
727 smp_active = 1; /* historic */
730 mtx_unlock_spin(&ap_boot_mtx);
732 /* Wait until all the AP's are up. */
733 while (smp_started == 0)
736 /* Start per-CPU event timers. */
739 /* Enter the scheduler. */
742 panic("scheduler returned us to %s", __func__);
746 /*******************************************************************
747 * local functions and data
751 * We tell the I/O APIC code about all the CPUs we want to receive
752 * interrupts. If we don't want certain CPUs to receive IRQs we
753 * can simply not tell the I/O APIC code about them in this function.
754 * We also do not tell it about the BSP since it tells itself about
755 * the BSP internally to work with UP kernels and on UP machines.
758 set_interrupt_apic_ids(void)
762 for (i = 0; i < MAXCPU; i++) {
763 apic_id = cpu_apic_ids[i];
766 if (cpu_info[apic_id].cpu_bsp)
768 if (cpu_info[apic_id].cpu_disabled)
771 /* Don't let hyperthreads service interrupts. */
772 if (hyperthreading_cpus > 1 &&
773 apic_id % hyperthreading_cpus != 0)
781 * Assign logical CPU IDs to local APICs.
788 TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
789 &hyperthreading_allowed);
791 /* Check for explicitly disabled CPUs. */
792 for (i = 0; i <= MAX_APIC_ID; i++) {
793 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp)
796 if (hyperthreading_cpus > 1 && i % hyperthreading_cpus != 0) {
797 cpu_info[i].cpu_hyperthread = 1;
798 #if defined(SCHED_ULE)
800 * Don't use HT CPU if it has been disabled by a
803 if (hyperthreading_allowed == 0) {
804 cpu_info[i].cpu_disabled = 1;
810 /* Don't use this CPU if it has been disabled by a tunable. */
811 if (resource_disabled("lapic", i)) {
812 cpu_info[i].cpu_disabled = 1;
818 * Assign CPU IDs to local APIC IDs and disable any CPUs
819 * beyond MAXCPU. CPU 0 is always assigned to the BSP.
821 * To minimize confusion for userland, we attempt to number
822 * CPUs such that all threads and cores in a package are
823 * grouped together. For now we assume that the BSP is always
824 * the first thread in a package and just start adding APs
825 * starting with the BSP's APIC ID.
828 cpu_apic_ids[0] = boot_cpu_id;
829 apic_cpuids[boot_cpu_id] = 0;
830 for (i = boot_cpu_id + 1; i != boot_cpu_id;
831 i == MAX_APIC_ID ? i = 0 : i++) {
832 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp ||
833 cpu_info[i].cpu_disabled)
836 if (mp_ncpus < MAXCPU) {
837 cpu_apic_ids[mp_ncpus] = i;
838 apic_cpuids[i] = mp_ncpus;
841 cpu_info[i].cpu_disabled = 1;
843 KASSERT(mp_maxid >= mp_ncpus - 1,
844 ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
849 * start each AP in our list
851 /* Lowest 1MB is already mapped: don't touch*/
852 #define TMPMAP_START 1
860 u_int32_t mpbioswarmvec;
863 mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
865 /* install the AP 1st level boot code */
868 /* save the current value of the warm-start vector */
869 mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
871 outb(CMOS_REG, BIOS_RESET);
872 mpbiosreason = inb(CMOS_DATA);
875 /* set up temporary P==V mapping for AP boot */
876 /* XXX this is a hack, we should boot the AP on its own stack/PTD */
878 kptbase = (uintptr_t)(void *)KPTphys;
879 for (i = TMPMAP_START; i < NKPT; i++)
880 PTD[i] = (pd_entry_t)(PG_V | PG_RW |
881 ((kptbase + i * PAGE_SIZE) & PG_FRAME));
885 for (cpu = 1; cpu < mp_ncpus; cpu++) {
886 apic_id = cpu_apic_ids[cpu];
888 /* allocate and set up a boot stack data page */
890 (char *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
891 dpcpu = (void *)kmem_alloc(kernel_map, DPCPU_SIZE);
892 /* setup a vector to our boot code */
893 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
894 *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
896 outb(CMOS_REG, BIOS_RESET);
897 outb(CMOS_DATA, BIOS_WARM); /* 'warm-start' */
900 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 4;
903 /* attempt to start the Application Processor */
904 CHECK_INIT(99); /* setup checkpoints */
905 if (!start_ap(apic_id)) {
906 printf("AP #%d (PHY# %d) failed!\n", cpu, apic_id);
907 CHECK_PRINT("trace"); /* show checkpoints */
908 /* better panic as the AP may be running loose */
909 printf("panic y/n? [y] ");
913 CHECK_PRINT("trace"); /* show checkpoints */
915 all_cpus |= (1 << cpu); /* record AP in CPU map */
918 /* build our map of 'other' CPUs */
919 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
921 /* restore the warmstart vector */
922 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
925 outb(CMOS_REG, BIOS_RESET);
926 outb(CMOS_DATA, mpbiosreason);
929 /* Undo V==P hack from above */
930 for (i = TMPMAP_START; i < NKPT; i++)
932 pmap_invalidate_range(kernel_pmap, 0, NKPT * NBPDR - 1);
934 /* number of APs actually started */
939 * load the 1st level AP boot code into base memory.
942 /* targets for relocation */
943 extern void bigJump(void);
944 extern void bootCodeSeg(void);
945 extern void bootDataSeg(void);
946 extern void MPentry(void);
948 extern u_int mp_gdtbase;
951 install_ap_tramp(void)
954 int size = *(int *) ((u_long) & bootMP_size);
955 vm_offset_t va = boot_address + KERNBASE;
956 u_char *src = (u_char *) ((u_long) bootMP);
957 u_char *dst = (u_char *) va;
958 u_int boot_base = (u_int) bootMP;
963 KASSERT (size <= PAGE_SIZE,
964 ("'size' do not fit into PAGE_SIZE, as expected."));
965 pmap_kenter(va, boot_address);
966 pmap_invalidate_page (kernel_pmap, va);
967 for (x = 0; x < size; ++x)
971 * modify addresses in code we just moved to basemem. unfortunately we
972 * need fairly detailed info about mpboot.s for this to work. changes
973 * to mpboot.s might require changes here.
976 /* boot code is located in KERNEL space */
979 /* modify the lgdt arg */
980 dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
981 *dst32 = boot_address + ((u_int) & MP_GDT - boot_base);
983 /* modify the ljmp target for MPentry() */
984 dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
985 *dst32 = ((u_int) MPentry - KERNBASE);
987 /* modify the target for boot code segment */
988 dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
989 dst8 = (u_int8_t *) (dst16 + 1);
990 *dst16 = (u_int) boot_address & 0xffff;
991 *dst8 = ((u_int) boot_address >> 16) & 0xff;
993 /* modify the target for boot data segment */
994 dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
995 dst8 = (u_int8_t *) (dst16 + 1);
996 *dst16 = (u_int) boot_address & 0xffff;
997 *dst8 = ((u_int) boot_address >> 16) & 0xff;
1001 * This function starts the AP (application processor) identified
1002 * by the APIC ID 'physicalCpu'. It does quite a "song and dance"
1003 * to accomplish this. This is necessary because of the nuances
1004 * of the different hardware we might encounter. It isn't pretty,
1005 * but it seems to work.
1008 start_ap(int apic_id)
1013 /* calculate the vector */
1014 vector = (boot_address >> 12) & 0xff;
1016 /* used as a watchpoint to signal AP startup */
1020 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
1021 * and running the target CPU. OR this INIT IPI might be latched (P5
1022 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
1026 /* do an INIT IPI: assert RESET */
1027 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1028 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
1030 /* wait for pending status end */
1033 /* do an INIT IPI: deassert RESET */
1034 lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
1035 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
1037 /* wait for pending status end */
1038 DELAY(10000); /* wait ~10mS */
1042 * next we do a STARTUP IPI: the previous INIT IPI might still be
1043 * latched, (P5 bug) this 1st STARTUP would then terminate
1044 * immediately, and the previously started INIT IPI would continue. OR
1045 * the previous INIT IPI has already run. and this STARTUP IPI will
1046 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1050 /* do a STARTUP IPI */
1051 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1052 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1055 DELAY(200); /* wait ~200uS */
1058 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1059 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1060 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1061 * recognized after hardware RESET or INIT IPI.
1064 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1065 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1068 DELAY(200); /* wait ~200uS */
1070 /* Wait up to 5 seconds for it to start. */
1071 for (ms = 0; ms < 5000; ms++) {
1073 return 1; /* return SUCCESS */
1076 return 0; /* return FAILURE */
1079 #ifdef COUNT_XINVLTLB_HITS
1080 u_int xhits_gbl[MAXCPU];
1081 u_int xhits_pg[MAXCPU];
1082 u_int xhits_rng[MAXCPU];
1083 SYSCTL_NODE(_debug, OID_AUTO, xhits, CTLFLAG_RW, 0, "");
1084 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, global, CTLFLAG_RW, &xhits_gbl,
1085 sizeof(xhits_gbl), "IU", "");
1086 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, page, CTLFLAG_RW, &xhits_pg,
1087 sizeof(xhits_pg), "IU", "");
1088 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, range, CTLFLAG_RW, &xhits_rng,
1089 sizeof(xhits_rng), "IU", "");
1094 u_int ipi_range_size;
1095 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_global, CTLFLAG_RW, &ipi_global, 0, "");
1096 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_page, CTLFLAG_RW, &ipi_page, 0, "");
1097 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range, CTLFLAG_RW, &ipi_range, 0, "");
1098 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range_size, CTLFLAG_RW, &ipi_range_size,
1101 u_int ipi_masked_global;
1102 u_int ipi_masked_page;
1103 u_int ipi_masked_range;
1104 u_int ipi_masked_range_size;
1105 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_global, CTLFLAG_RW,
1106 &ipi_masked_global, 0, "");
1107 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_page, CTLFLAG_RW,
1108 &ipi_masked_page, 0, "");
1109 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range, CTLFLAG_RW,
1110 &ipi_masked_range, 0, "");
1111 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range_size, CTLFLAG_RW,
1112 &ipi_masked_range_size, 0, "");
1113 #endif /* COUNT_XINVLTLB_HITS */
1116 * Flush the TLB on all other CPU's
1119 smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1123 ncpu = mp_ncpus - 1; /* does not shootdown self */
1125 return; /* no other cpus */
1126 if (!(read_eflags() & PSL_I))
1127 panic("%s: interrupts disabled", __func__);
1128 mtx_lock_spin(&smp_ipi_mtx);
1129 smp_tlb_addr1 = addr1;
1130 smp_tlb_addr2 = addr2;
1131 atomic_store_rel_int(&smp_tlb_wait, 0);
1132 ipi_all_but_self(vector);
1133 while (smp_tlb_wait < ncpu)
1135 mtx_unlock_spin(&smp_ipi_mtx);
1139 smp_targeted_tlb_shootdown(cpumask_t mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1141 int ncpu, othercpus;
1143 othercpus = mp_ncpus - 1;
1144 if (mask == (u_int)-1) {
1149 mask &= ~PCPU_GET(cpumask);
1152 ncpu = bitcount32(mask);
1153 if (ncpu > othercpus) {
1154 /* XXX this should be a panic offence */
1155 printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
1159 /* XXX should be a panic, implied by mask == 0 above */
1163 if (!(read_eflags() & PSL_I))
1164 panic("%s: interrupts disabled", __func__);
1165 mtx_lock_spin(&smp_ipi_mtx);
1166 smp_tlb_addr1 = addr1;
1167 smp_tlb_addr2 = addr2;
1168 atomic_store_rel_int(&smp_tlb_wait, 0);
1169 if (mask == (u_int)-1)
1170 ipi_all_but_self(vector);
1172 ipi_selected(mask, vector);
1173 while (smp_tlb_wait < ncpu)
1175 mtx_unlock_spin(&smp_ipi_mtx);
1179 smp_cache_flush(void)
1183 smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
1191 smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
1192 #ifdef COUNT_XINVLTLB_HITS
1199 smp_invlpg(vm_offset_t addr)
1203 smp_tlb_shootdown(IPI_INVLPG, addr, 0);
1204 #ifdef COUNT_XINVLTLB_HITS
1211 smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
1215 smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
1216 #ifdef COUNT_XINVLTLB_HITS
1218 ipi_range_size += (addr2 - addr1) / PAGE_SIZE;
1224 smp_masked_invltlb(cpumask_t mask)
1228 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
1229 #ifdef COUNT_XINVLTLB_HITS
1230 ipi_masked_global++;
1236 smp_masked_invlpg(cpumask_t mask, vm_offset_t addr)
1240 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
1241 #ifdef COUNT_XINVLTLB_HITS
1248 smp_masked_invlpg_range(cpumask_t mask, vm_offset_t addr1, vm_offset_t addr2)
1252 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
1253 #ifdef COUNT_XINVLTLB_HITS
1255 ipi_masked_range_size += (addr2 - addr1) / PAGE_SIZE;
1261 ipi_bitmap_handler(struct trapframe frame)
1263 int cpu = PCPU_GET(cpuid);
1266 ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
1268 if (ipi_bitmap & (1 << IPI_PREEMPT)) {
1270 (*ipi_preempt_counts[cpu])++;
1272 sched_preempt(curthread);
1274 if (ipi_bitmap & (1 << IPI_AST)) {
1276 (*ipi_ast_counts[cpu])++;
1278 /* Nothing to do for AST */
1280 if (ipi_bitmap & (1 << IPI_HARDCLOCK)) {
1282 (*ipi_hardclock_counts[cpu])++;
1284 hardclockintr(&frame);
1286 if (ipi_bitmap & (1 << IPI_STATCLOCK)) {
1288 (*ipi_statclock_counts[cpu])++;
1290 statclockintr(&frame);
1295 * send an IPI to a set of cpus.
1298 ipi_selected(cpumask_t cpus, u_int ipi)
1305 if (IPI_IS_BITMAPED(ipi)) {
1307 ipi = IPI_BITMAP_VECTOR;
1311 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1312 * of help in order to understand what is the source.
1313 * Set the mask of receiving CPUs for this purpose.
1315 if (ipi == IPI_STOP_HARD)
1316 atomic_set_int(&ipi_nmi_pending, cpus);
1318 CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
1319 while ((cpu = ffs(cpus)) != 0) {
1321 cpus &= ~(1 << cpu);
1323 KASSERT(cpu_apic_ids[cpu] != -1,
1324 ("IPI to non-existent CPU %d", cpu));
1328 old_pending = cpu_ipi_pending[cpu];
1329 new_pending = old_pending | bitmap;
1330 } while (!atomic_cmpset_int(&cpu_ipi_pending[cpu],old_pending, new_pending));
1336 lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1342 * send an IPI to all CPUs EXCEPT myself
1345 ipi_all_but_self(u_int ipi)
1348 if (IPI_IS_BITMAPED(ipi)) {
1349 ipi_selected(PCPU_GET(other_cpus), ipi);
1354 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1355 * of help in order to understand what is the source.
1356 * Set the mask of receiving CPUs for this purpose.
1358 if (ipi == IPI_STOP_HARD)
1359 atomic_set_int(&ipi_nmi_pending, PCPU_GET(other_cpus));
1360 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1361 lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1370 * As long as there is not a simple way to know about a NMI's
1371 * source, if the bitmask for the current CPU is present in
1372 * the global pending bitword an IPI_STOP_HARD has been issued
1373 * and should be handled.
1375 cpumask = PCPU_GET(cpumask);
1376 if ((ipi_nmi_pending & cpumask) == 0)
1379 atomic_clear_int(&ipi_nmi_pending, cpumask);
1385 * Handle an IPI_STOP by saving our current context and spinning until we
1389 cpustop_handler(void)
1391 int cpu = PCPU_GET(cpuid);
1392 int cpumask = PCPU_GET(cpumask);
1394 savectx(&stoppcbs[cpu]);
1396 /* Indicate that we are stopped */
1397 atomic_set_int(&stopped_cpus, cpumask);
1399 /* Wait for restart */
1400 while (!(started_cpus & cpumask))
1403 atomic_clear_int(&started_cpus, cpumask);
1404 atomic_clear_int(&stopped_cpus, cpumask);
1406 if (cpu == 0 && cpustop_restartfunc != NULL) {
1407 cpustop_restartfunc();
1408 cpustop_restartfunc = NULL;
1413 * This is called once the rest of the system is up and running and we're
1414 * ready to let the AP's out of the pen.
1417 release_aps(void *dummy __unused)
1422 atomic_store_rel_int(&aps_ready, 1);
1423 while (smp_started == 0)
1426 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1429 sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1434 mask = hlt_cpus_mask;
1435 error = sysctl_handle_int(oidp, &mask, 0, req);
1436 if (error || !req->newptr)
1439 if (logical_cpus_mask != 0 &&
1440 (mask & logical_cpus_mask) == logical_cpus_mask)
1441 hlt_logical_cpus = 1;
1443 hlt_logical_cpus = 0;
1445 if (! hyperthreading_allowed)
1446 mask |= hyperthreading_cpus_mask;
1448 if ((mask & all_cpus) == all_cpus)
1450 hlt_cpus_mask = mask;
1453 SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1454 0, 0, sysctl_hlt_cpus, "IU",
1455 "Bitmap of CPUs to halt. 101 (binary) will halt CPUs 0 and 2.");
1458 sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1462 disable = hlt_logical_cpus;
1463 error = sysctl_handle_int(oidp, &disable, 0, req);
1464 if (error || !req->newptr)
1468 hlt_cpus_mask |= logical_cpus_mask;
1470 hlt_cpus_mask &= ~logical_cpus_mask;
1472 if (! hyperthreading_allowed)
1473 hlt_cpus_mask |= hyperthreading_cpus_mask;
1475 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1476 hlt_cpus_mask &= ~(1<<0);
1478 hlt_logical_cpus = disable;
1483 sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1487 allowed = hyperthreading_allowed;
1488 error = sysctl_handle_int(oidp, &allowed, 0, req);
1489 if (error || !req->newptr)
1494 * SCHED_ULE doesn't allow enabling/disabling HT cores at
1497 if (allowed != hyperthreading_allowed)
1503 hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1505 hlt_cpus_mask |= hyperthreading_cpus_mask;
1507 if (logical_cpus_mask != 0 &&
1508 (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1509 hlt_logical_cpus = 1;
1511 hlt_logical_cpus = 0;
1513 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1514 hlt_cpus_mask &= ~(1<<0);
1516 hyperthreading_allowed = allowed;
1521 cpu_hlt_setup(void *dummy __unused)
1524 if (logical_cpus_mask != 0) {
1525 TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1527 sysctl_ctx_init(&logical_cpu_clist);
1528 SYSCTL_ADD_PROC(&logical_cpu_clist,
1529 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1530 "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1531 sysctl_hlt_logical_cpus, "IU", "");
1532 SYSCTL_ADD_UINT(&logical_cpu_clist,
1533 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1534 "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1535 &logical_cpus_mask, 0, "");
1537 if (hlt_logical_cpus)
1538 hlt_cpus_mask |= logical_cpus_mask;
1541 * If necessary for security purposes, force
1542 * hyperthreading off, regardless of the value
1543 * of hlt_logical_cpus.
1545 if (hyperthreading_cpus_mask) {
1546 SYSCTL_ADD_PROC(&logical_cpu_clist,
1547 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1548 "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1549 0, 0, sysctl_hyperthreading_allowed, "IU", "");
1550 if (! hyperthreading_allowed)
1551 hlt_cpus_mask |= hyperthreading_cpus_mask;
1555 SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1558 mp_grab_cpu_hlt(void)
1560 u_int mask = PCPU_GET(cpumask);
1562 u_int cpuid = PCPU_GET(cpuid);
1570 retval = mask & hlt_cpus_mask;
1571 while (mask & hlt_cpus_mask)
1572 __asm __volatile("sti; hlt" : : : "memory");
1578 * Setup interrupt counters for IPI handlers.
1581 mp_ipi_intrcnt(void *dummy)
1587 snprintf(buf, sizeof(buf), "cpu%d:invltlb", i);
1588 intrcnt_add(buf, &ipi_invltlb_counts[i]);
1589 snprintf(buf, sizeof(buf), "cpu%d:invlrng", i);
1590 intrcnt_add(buf, &ipi_invlrng_counts[i]);
1591 snprintf(buf, sizeof(buf), "cpu%d:invlpg", i);
1592 intrcnt_add(buf, &ipi_invlpg_counts[i]);
1593 snprintf(buf, sizeof(buf), "cpu%d:preempt", i);
1594 intrcnt_add(buf, &ipi_preempt_counts[i]);
1595 snprintf(buf, sizeof(buf), "cpu%d:ast", i);
1596 intrcnt_add(buf, &ipi_ast_counts[i]);
1597 snprintf(buf, sizeof(buf), "cpu%d:rendezvous", i);
1598 intrcnt_add(buf, &ipi_rendezvous_counts[i]);
1599 snprintf(buf, sizeof(buf), "cpu%d:lazypmap", i);
1600 intrcnt_add(buf, &ipi_lazypmap_counts[i]);
1601 snprintf(buf, sizeof(buf), "cpu%d:hardclock", i);
1602 intrcnt_add(buf, &ipi_hardclock_counts[i]);
1603 snprintf(buf, sizeof(buf), "cpu%d:statclock", i);
1604 intrcnt_add(buf, &ipi_statclock_counts[i]);
1607 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);