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];
172 * Local data and functions.
175 static u_int logical_cpus;
176 static volatile cpumask_t ipi_nmi_pending;
178 /* used to hold the AP's until we are ready to release them */
179 static struct mtx ap_boot_mtx;
181 /* Set to 1 once we're ready to let the APs out of the pen. */
182 static volatile int aps_ready = 0;
185 * Store data from cpu_add() until later in the boot when we actually setup
192 int cpu_hyperthread:1;
193 } static cpu_info[MAX_APIC_ID + 1];
194 int cpu_apic_ids[MAXCPU];
195 int apic_cpuids[MAX_APIC_ID + 1];
197 /* Holds pending bitmap based IPIs per CPU */
198 static volatile u_int cpu_ipi_pending[MAXCPU];
200 static u_int boot_address;
201 static int cpu_logical;
202 static int cpu_cores;
204 static void assign_cpu_ids(void);
205 static void install_ap_tramp(void);
206 static void set_interrupt_apic_ids(void);
207 static int start_all_aps(void);
208 static int start_ap(int apic_id);
209 static void release_aps(void *dummy);
211 static int hlt_logical_cpus;
212 static u_int hyperthreading_cpus;
213 static cpumask_t hyperthreading_cpus_mask;
214 static int hyperthreading_allowed = 1;
215 static struct sysctl_ctx_list logical_cpu_clist;
218 mem_range_AP_init(void)
220 if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
221 mem_range_softc.mr_op->initAP(&mem_range_softc);
235 /* We only support two levels for now. */
236 for (i = 0; i < 3; i++) {
237 cpuid_count(0x0B, i, p);
239 logical = p[1] &= 0xffff;
240 type = (p[2] >> 8) & 0xff;
241 if (type == 0 || logical == 0)
243 for (cnt = 0, x = 0; x <= MAX_APIC_ID; x++) {
244 if (!cpu_info[x].cpu_present ||
245 cpu_info[x].cpu_disabled)
247 if (x >> bits == boot_cpu_id >> bits)
250 if (type == CPUID_TYPE_SMT)
252 else if (type == CPUID_TYPE_CORE)
255 if (cpu_logical == 0)
257 cpu_cores /= cpu_logical;
263 u_int threads_per_cache, p[4];
269 * If this CPU supports HTT or CMP then mention the
270 * number of physical/logical cores it contains.
272 if (cpu_feature & CPUID_HTT)
273 htt = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
274 if (cpu_vendor_id == CPU_VENDOR_AMD && (amd_feature2 & AMDID2_CMP))
275 cmp = (cpu_procinfo2 & AMDID_CMP_CORES) + 1;
276 else if (cpu_vendor_id == CPU_VENDOR_INTEL && (cpu_high >= 4)) {
277 cpuid_count(4, 0, p);
278 if ((p[0] & 0x1f) != 0)
279 cmp = ((p[0] >> 26) & 0x3f) + 1;
282 cpu_logical = htt / cmp;
284 /* Setup the initial logical CPUs info. */
285 if (cpu_feature & CPUID_HTT)
286 logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
289 * Work out if hyperthreading is *really* enabled. This
290 * is made really ugly by the fact that processors lie: Dual
291 * core processors claim to be hyperthreaded even when they're
292 * not, presumably because they want to be treated the same
293 * way as HTT with respect to per-cpu software licensing.
294 * At the time of writing (May 12, 2005) the only hyperthreaded
295 * cpus are from Intel, and Intel's dual-core processors can be
296 * identified via the "deterministic cache parameters" cpuid
300 * First determine if this is an Intel processor which claims
301 * to have hyperthreading support.
303 if ((cpu_feature & CPUID_HTT) && cpu_vendor_id == CPU_VENDOR_INTEL) {
305 * If the "deterministic cache parameters" cpuid calls
306 * are available, use them.
309 /* Ask the processor about the L1 cache. */
310 for (i = 0; i < 1; i++) {
311 cpuid_count(4, i, p);
312 threads_per_cache = ((p[0] & 0x3ffc000) >> 14) + 1;
313 if (hyperthreading_cpus < threads_per_cache)
314 hyperthreading_cpus = threads_per_cache;
315 if ((p[0] & 0x1f) == 0)
321 * If the deterministic cache parameters are not
322 * available, or if no caches were reported to exist,
323 * just accept what the HTT flag indicated.
325 if (hyperthreading_cpus == 0)
326 hyperthreading_cpus = logical_cpus;
333 static int cpu_topo_probed = 0;
338 logical_cpus = logical_cpus_mask = 0;
344 cpu_cores = mp_ncpus > 0 ? mp_ncpus : 1;
345 if (cpu_logical == 0)
356 * Determine whether any threading flags are
360 if (cpu_logical > 1 && hyperthreading_cpus)
361 cg_flags = CG_FLAG_HTT;
362 else if (cpu_logical > 1)
363 cg_flags = CG_FLAG_SMT;
366 if (mp_ncpus % (cpu_cores * cpu_logical) != 0) {
367 printf("WARNING: Non-uniform processors.\n");
368 printf("WARNING: Using suboptimal topology.\n");
369 return (smp_topo_none());
372 * No multi-core or hyper-threaded.
374 if (cpu_logical * cpu_cores == 1)
375 return (smp_topo_none());
377 * Only HTT no multi-core.
379 if (cpu_logical > 1 && cpu_cores == 1)
380 return (smp_topo_1level(CG_SHARE_L1, cpu_logical, cg_flags));
382 * Only multi-core no HTT.
384 if (cpu_cores > 1 && cpu_logical == 1)
385 return (smp_topo_1level(CG_SHARE_L2, cpu_cores, cg_flags));
387 * Both HTT and multi-core.
389 return (smp_topo_2level(CG_SHARE_L2, cpu_cores,
390 CG_SHARE_L1, cpu_logical, cg_flags));
395 * Calculate usable address in base memory for AP trampoline code.
398 mp_bootaddress(u_int basemem)
401 boot_address = trunc_page(basemem); /* round down to 4k boundary */
402 if ((basemem - boot_address) < bootMP_size)
403 boot_address -= PAGE_SIZE; /* not enough, lower by 4k */
409 cpu_add(u_int apic_id, char boot_cpu)
412 if (apic_id > MAX_APIC_ID) {
413 panic("SMP: APIC ID %d too high", apic_id);
416 KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
418 cpu_info[apic_id].cpu_present = 1;
420 KASSERT(boot_cpu_id == -1,
421 ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
423 boot_cpu_id = apic_id;
424 cpu_info[apic_id].cpu_bsp = 1;
426 if (mp_ncpus < MAXCPU)
429 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
434 cpu_mp_setmaxid(void)
437 mp_maxid = MAXCPU - 1;
445 * Always record BSP in CPU map so that the mbuf init code works
451 * No CPUs were found, so this must be a UP system. Setup
452 * the variables to represent a system with a single CPU
459 /* At least one CPU was found. */
462 * One CPU was found, so this must be a UP system with
468 /* At least two CPUs were found. */
473 * Initialize the IPI handlers and start up the AP's.
480 /* Initialize the logical ID to APIC ID table. */
481 for (i = 0; i < MAXCPU; i++) {
482 cpu_apic_ids[i] = -1;
483 cpu_ipi_pending[i] = 0;
486 /* Install an inter-CPU IPI for TLB invalidation */
487 setidt(IPI_INVLTLB, IDTVEC(invltlb),
488 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
489 setidt(IPI_INVLPG, IDTVEC(invlpg),
490 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
491 setidt(IPI_INVLRNG, IDTVEC(invlrng),
492 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
494 /* Install an inter-CPU IPI for cache invalidation. */
495 setidt(IPI_INVLCACHE, IDTVEC(invlcache),
496 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
498 /* Install an inter-CPU IPI for lazy pmap release */
499 setidt(IPI_LAZYPMAP, IDTVEC(lazypmap),
500 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
502 /* Install an inter-CPU IPI for all-CPU rendezvous */
503 setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous),
504 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
506 /* Install generic inter-CPU IPI handler */
507 setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
508 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
510 /* Install an inter-CPU IPI for CPU stop/restart */
511 setidt(IPI_STOP, IDTVEC(cpustop),
512 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
515 /* Set boot_cpu_id if needed. */
516 if (boot_cpu_id == -1) {
517 boot_cpu_id = PCPU_GET(apic_id);
518 cpu_info[boot_cpu_id].cpu_bsp = 1;
520 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
521 ("BSP's APIC ID doesn't match boot_cpu_id"));
523 /* Probe logical/physical core configuration. */
528 /* Start each Application Processor */
531 set_interrupt_apic_ids();
536 * Print various information about the SMP system hardware and setup.
539 cpu_mp_announce(void)
541 const char *hyperthread;
544 printf("FreeBSD/SMP: %d package(s) x %d core(s)",
545 mp_ncpus / (cpu_cores * cpu_logical), cpu_cores);
546 if (hyperthreading_cpus > 1)
547 printf(" x %d HTT threads", cpu_logical);
548 else if (cpu_logical > 1)
549 printf(" x %d SMT threads", cpu_logical);
552 /* List active CPUs first. */
553 printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
554 for (i = 1; i < mp_ncpus; i++) {
555 if (cpu_info[cpu_apic_ids[i]].cpu_hyperthread)
559 printf(" cpu%d (AP%s): APIC ID: %2d\n", i, hyperthread,
563 /* List disabled CPUs last. */
564 for (i = 0; i <= MAX_APIC_ID; i++) {
565 if (!cpu_info[i].cpu_present || !cpu_info[i].cpu_disabled)
567 if (cpu_info[i].cpu_hyperthread)
571 printf(" cpu (AP%s): APIC ID: %2d (disabled)\n", hyperthread,
577 * AP CPU's call this to initialize themselves.
588 /* bootAP is set in start_ap() to our ID. */
591 /* Get per-cpu data */
594 /* prime data page for it to use */
595 pcpu_init(pc, myid, sizeof(struct pcpu));
596 dpcpu_init(dpcpu, myid);
597 pc->pc_apic_id = cpu_apic_ids[myid];
598 pc->pc_prvspace = pc;
599 pc->pc_curthread = 0;
601 gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
602 gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
604 for (x = 0; x < NGDT; x++) {
605 ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x].sd);
608 r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
609 r_gdt.rd_base = (int) &gdt[myid * NGDT];
610 lgdt(&r_gdt); /* does magic intra-segment return */
615 PCPU_SET(currentldt, _default_ldt);
617 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
618 gdt[myid * NGDT + GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;
619 PCPU_SET(common_tss.tss_esp0, 0); /* not used until after switch */
620 PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
621 PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
622 PCPU_SET(tss_gdt, &gdt[myid * NGDT + GPROC0_SEL].sd);
623 PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
626 PCPU_SET(fsgs_gdt, &gdt[myid * NGDT + GUFS_SEL].sd);
629 * Set to a known state:
630 * Set by mpboot.s: CR0_PG, CR0_PE
631 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
634 cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
636 CHECK_WRITE(0x38, 5);
638 /* Disable local APIC just to be sure. */
641 /* signal our startup to the BSP. */
643 CHECK_WRITE(0x39, 6);
645 /* Spin until the BSP releases the AP's. */
649 /* BSP may have changed PTD while we were waiting */
651 for (addr = 0; addr < NKPT * NBPDR - 1; addr += PAGE_SIZE)
654 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
658 /* Initialize the PAT MSR if present. */
661 /* set up CPU registers and state */
664 /* set up FPU state on the AP */
667 /* set up SSE registers */
671 /* Enable the PTE no-execute bit. */
672 if ((amd_feature & AMDID_NX) != 0) {
675 msr = rdmsr(MSR_EFER) | EFER_NXE;
676 wrmsr(MSR_EFER, msr);
680 /* A quick check from sanity claus */
681 if (PCPU_GET(apic_id) != lapic_id()) {
682 printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
683 printf("SMP: actual apic_id = %d\n", lapic_id());
684 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
685 panic("cpuid mismatch! boom!!");
688 /* Initialize curthread. */
689 KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
690 PCPU_SET(curthread, PCPU_GET(idlethread));
694 mtx_lock_spin(&ap_boot_mtx);
696 /* Init local apic for irq's */
699 /* Set memory range attributes for this CPU to match the BSP */
704 CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
705 printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
707 /* Determine if we are a logical CPU. */
708 if (logical_cpus > 1 && PCPU_GET(apic_id) % logical_cpus != 0)
709 logical_cpus_mask |= PCPU_GET(cpumask);
711 /* Determine if we are a hyperthread. */
712 if (hyperthreading_cpus > 1 &&
713 PCPU_GET(apic_id) % hyperthreading_cpus != 0)
714 hyperthreading_cpus_mask |= PCPU_GET(cpumask);
716 /* Build our map of 'other' CPUs. */
717 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
722 if (smp_cpus == mp_ncpus) {
723 /* enable IPI's, tlb shootdown, freezes etc */
724 atomic_store_rel_int(&smp_started, 1);
725 smp_active = 1; /* historic */
728 mtx_unlock_spin(&ap_boot_mtx);
730 /* wait until all the AP's are up */
731 while (smp_started == 0)
734 /* enter the scheduler */
737 panic("scheduler returned us to %s", __func__);
741 /*******************************************************************
742 * local functions and data
746 * We tell the I/O APIC code about all the CPUs we want to receive
747 * interrupts. If we don't want certain CPUs to receive IRQs we
748 * can simply not tell the I/O APIC code about them in this function.
749 * We also do not tell it about the BSP since it tells itself about
750 * the BSP internally to work with UP kernels and on UP machines.
753 set_interrupt_apic_ids(void)
757 for (i = 0; i < MAXCPU; i++) {
758 apic_id = cpu_apic_ids[i];
761 if (cpu_info[apic_id].cpu_bsp)
763 if (cpu_info[apic_id].cpu_disabled)
766 /* Don't let hyperthreads service interrupts. */
767 if (hyperthreading_cpus > 1 &&
768 apic_id % hyperthreading_cpus != 0)
776 * Assign logical CPU IDs to local APICs.
783 TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
784 &hyperthreading_allowed);
786 /* Check for explicitly disabled CPUs. */
787 for (i = 0; i <= MAX_APIC_ID; i++) {
788 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp)
791 if (hyperthreading_cpus > 1 && i % hyperthreading_cpus != 0) {
792 cpu_info[i].cpu_hyperthread = 1;
793 #if defined(SCHED_ULE)
795 * Don't use HT CPU if it has been disabled by a
798 if (hyperthreading_allowed == 0) {
799 cpu_info[i].cpu_disabled = 1;
805 /* Don't use this CPU if it has been disabled by a tunable. */
806 if (resource_disabled("lapic", i)) {
807 cpu_info[i].cpu_disabled = 1;
813 * Assign CPU IDs to local APIC IDs and disable any CPUs
814 * beyond MAXCPU. CPU 0 is always assigned to the BSP.
816 * To minimize confusion for userland, we attempt to number
817 * CPUs such that all threads and cores in a package are
818 * grouped together. For now we assume that the BSP is always
819 * the first thread in a package and just start adding APs
820 * starting with the BSP's APIC ID.
823 cpu_apic_ids[0] = boot_cpu_id;
824 apic_cpuids[boot_cpu_id] = 0;
825 for (i = boot_cpu_id + 1; i != boot_cpu_id;
826 i == MAX_APIC_ID ? i = 0 : i++) {
827 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp ||
828 cpu_info[i].cpu_disabled)
831 if (mp_ncpus < MAXCPU) {
832 cpu_apic_ids[mp_ncpus] = i;
833 apic_cpuids[i] = mp_ncpus;
836 cpu_info[i].cpu_disabled = 1;
838 KASSERT(mp_maxid >= mp_ncpus - 1,
839 ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
844 * start each AP in our list
846 /* Lowest 1MB is already mapped: don't touch*/
847 #define TMPMAP_START 1
855 u_int32_t mpbioswarmvec;
858 mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
860 /* install the AP 1st level boot code */
863 /* save the current value of the warm-start vector */
864 mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
866 outb(CMOS_REG, BIOS_RESET);
867 mpbiosreason = inb(CMOS_DATA);
870 /* set up temporary P==V mapping for AP boot */
871 /* XXX this is a hack, we should boot the AP on its own stack/PTD */
873 kptbase = (uintptr_t)(void *)KPTphys;
874 for (i = TMPMAP_START; i < NKPT; i++)
875 PTD[i] = (pd_entry_t)(PG_V | PG_RW |
876 ((kptbase + i * PAGE_SIZE) & PG_FRAME));
880 for (cpu = 1; cpu < mp_ncpus; cpu++) {
881 apic_id = cpu_apic_ids[cpu];
883 /* allocate and set up a boot stack data page */
885 (char *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
886 dpcpu = (void *)kmem_alloc(kernel_map, DPCPU_SIZE);
887 /* setup a vector to our boot code */
888 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
889 *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
891 outb(CMOS_REG, BIOS_RESET);
892 outb(CMOS_DATA, BIOS_WARM); /* 'warm-start' */
895 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 4;
898 /* attempt to start the Application Processor */
899 CHECK_INIT(99); /* setup checkpoints */
900 if (!start_ap(apic_id)) {
901 printf("AP #%d (PHY# %d) failed!\n", cpu, apic_id);
902 CHECK_PRINT("trace"); /* show checkpoints */
903 /* better panic as the AP may be running loose */
904 printf("panic y/n? [y] ");
908 CHECK_PRINT("trace"); /* show checkpoints */
910 all_cpus |= (1 << cpu); /* record AP in CPU map */
913 /* build our map of 'other' CPUs */
914 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
916 /* restore the warmstart vector */
917 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
920 outb(CMOS_REG, BIOS_RESET);
921 outb(CMOS_DATA, mpbiosreason);
924 /* Undo V==P hack from above */
925 for (i = TMPMAP_START; i < NKPT; i++)
927 pmap_invalidate_range(kernel_pmap, 0, NKPT * NBPDR - 1);
929 /* number of APs actually started */
934 * load the 1st level AP boot code into base memory.
937 /* targets for relocation */
938 extern void bigJump(void);
939 extern void bootCodeSeg(void);
940 extern void bootDataSeg(void);
941 extern void MPentry(void);
943 extern u_int mp_gdtbase;
946 install_ap_tramp(void)
949 int size = *(int *) ((u_long) & bootMP_size);
950 vm_offset_t va = boot_address + KERNBASE;
951 u_char *src = (u_char *) ((u_long) bootMP);
952 u_char *dst = (u_char *) va;
953 u_int boot_base = (u_int) bootMP;
958 KASSERT (size <= PAGE_SIZE,
959 ("'size' do not fit into PAGE_SIZE, as expected."));
960 pmap_kenter(va, boot_address);
961 pmap_invalidate_page (kernel_pmap, va);
962 for (x = 0; x < size; ++x)
966 * modify addresses in code we just moved to basemem. unfortunately we
967 * need fairly detailed info about mpboot.s for this to work. changes
968 * to mpboot.s might require changes here.
971 /* boot code is located in KERNEL space */
974 /* modify the lgdt arg */
975 dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
976 *dst32 = boot_address + ((u_int) & MP_GDT - boot_base);
978 /* modify the ljmp target for MPentry() */
979 dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
980 *dst32 = ((u_int) MPentry - KERNBASE);
982 /* modify the target for boot code segment */
983 dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
984 dst8 = (u_int8_t *) (dst16 + 1);
985 *dst16 = (u_int) boot_address & 0xffff;
986 *dst8 = ((u_int) boot_address >> 16) & 0xff;
988 /* modify the target for boot data segment */
989 dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
990 dst8 = (u_int8_t *) (dst16 + 1);
991 *dst16 = (u_int) boot_address & 0xffff;
992 *dst8 = ((u_int) boot_address >> 16) & 0xff;
996 * This function starts the AP (application processor) identified
997 * by the APIC ID 'physicalCpu'. It does quite a "song and dance"
998 * to accomplish this. This is necessary because of the nuances
999 * of the different hardware we might encounter. It isn't pretty,
1000 * but it seems to work.
1003 start_ap(int apic_id)
1008 /* calculate the vector */
1009 vector = (boot_address >> 12) & 0xff;
1011 /* used as a watchpoint to signal AP startup */
1015 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
1016 * and running the target CPU. OR this INIT IPI might be latched (P5
1017 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
1021 /* do an INIT IPI: assert RESET */
1022 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1023 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
1025 /* wait for pending status end */
1028 /* do an INIT IPI: deassert RESET */
1029 lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
1030 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
1032 /* wait for pending status end */
1033 DELAY(10000); /* wait ~10mS */
1037 * next we do a STARTUP IPI: the previous INIT IPI might still be
1038 * latched, (P5 bug) this 1st STARTUP would then terminate
1039 * immediately, and the previously started INIT IPI would continue. OR
1040 * the previous INIT IPI has already run. and this STARTUP IPI will
1041 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
1045 /* do a STARTUP IPI */
1046 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1047 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1050 DELAY(200); /* wait ~200uS */
1053 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
1054 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
1055 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
1056 * recognized after hardware RESET or INIT IPI.
1059 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
1060 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
1063 DELAY(200); /* wait ~200uS */
1065 /* Wait up to 5 seconds for it to start. */
1066 for (ms = 0; ms < 5000; ms++) {
1068 return 1; /* return SUCCESS */
1071 return 0; /* return FAILURE */
1074 #ifdef COUNT_XINVLTLB_HITS
1075 u_int xhits_gbl[MAXCPU];
1076 u_int xhits_pg[MAXCPU];
1077 u_int xhits_rng[MAXCPU];
1078 SYSCTL_NODE(_debug, OID_AUTO, xhits, CTLFLAG_RW, 0, "");
1079 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, global, CTLFLAG_RW, &xhits_gbl,
1080 sizeof(xhits_gbl), "IU", "");
1081 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, page, CTLFLAG_RW, &xhits_pg,
1082 sizeof(xhits_pg), "IU", "");
1083 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, range, CTLFLAG_RW, &xhits_rng,
1084 sizeof(xhits_rng), "IU", "");
1089 u_int ipi_range_size;
1090 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_global, CTLFLAG_RW, &ipi_global, 0, "");
1091 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_page, CTLFLAG_RW, &ipi_page, 0, "");
1092 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range, CTLFLAG_RW, &ipi_range, 0, "");
1093 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range_size, CTLFLAG_RW, &ipi_range_size,
1096 u_int ipi_masked_global;
1097 u_int ipi_masked_page;
1098 u_int ipi_masked_range;
1099 u_int ipi_masked_range_size;
1100 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_global, CTLFLAG_RW,
1101 &ipi_masked_global, 0, "");
1102 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_page, CTLFLAG_RW,
1103 &ipi_masked_page, 0, "");
1104 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range, CTLFLAG_RW,
1105 &ipi_masked_range, 0, "");
1106 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range_size, CTLFLAG_RW,
1107 &ipi_masked_range_size, 0, "");
1108 #endif /* COUNT_XINVLTLB_HITS */
1111 * Flush the TLB on all other CPU's
1114 smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1118 ncpu = mp_ncpus - 1; /* does not shootdown self */
1120 return; /* no other cpus */
1121 if (!(read_eflags() & PSL_I))
1122 panic("%s: interrupts disabled", __func__);
1123 mtx_lock_spin(&smp_ipi_mtx);
1124 smp_tlb_addr1 = addr1;
1125 smp_tlb_addr2 = addr2;
1126 atomic_store_rel_int(&smp_tlb_wait, 0);
1127 ipi_all_but_self(vector);
1128 while (smp_tlb_wait < ncpu)
1130 mtx_unlock_spin(&smp_ipi_mtx);
1134 smp_targeted_tlb_shootdown(cpumask_t mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1136 int ncpu, othercpus;
1138 othercpus = mp_ncpus - 1;
1139 if (mask == (u_int)-1) {
1144 mask &= ~PCPU_GET(cpumask);
1147 ncpu = bitcount32(mask);
1148 if (ncpu > othercpus) {
1149 /* XXX this should be a panic offence */
1150 printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
1154 /* XXX should be a panic, implied by mask == 0 above */
1158 if (!(read_eflags() & PSL_I))
1159 panic("%s: interrupts disabled", __func__);
1160 mtx_lock_spin(&smp_ipi_mtx);
1161 smp_tlb_addr1 = addr1;
1162 smp_tlb_addr2 = addr2;
1163 atomic_store_rel_int(&smp_tlb_wait, 0);
1164 if (mask == (u_int)-1)
1165 ipi_all_but_self(vector);
1167 ipi_selected(mask, vector);
1168 while (smp_tlb_wait < ncpu)
1170 mtx_unlock_spin(&smp_ipi_mtx);
1174 smp_cache_flush(void)
1178 smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
1186 smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
1187 #ifdef COUNT_XINVLTLB_HITS
1194 smp_invlpg(vm_offset_t addr)
1198 smp_tlb_shootdown(IPI_INVLPG, addr, 0);
1199 #ifdef COUNT_XINVLTLB_HITS
1206 smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
1210 smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
1211 #ifdef COUNT_XINVLTLB_HITS
1213 ipi_range_size += (addr2 - addr1) / PAGE_SIZE;
1219 smp_masked_invltlb(cpumask_t mask)
1223 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
1224 #ifdef COUNT_XINVLTLB_HITS
1225 ipi_masked_global++;
1231 smp_masked_invlpg(cpumask_t mask, vm_offset_t addr)
1235 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
1236 #ifdef COUNT_XINVLTLB_HITS
1243 smp_masked_invlpg_range(cpumask_t mask, vm_offset_t addr1, vm_offset_t addr2)
1247 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
1248 #ifdef COUNT_XINVLTLB_HITS
1250 ipi_masked_range_size += (addr2 - addr1) / PAGE_SIZE;
1256 ipi_bitmap_handler(struct trapframe frame)
1258 int cpu = PCPU_GET(cpuid);
1261 ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
1263 if (ipi_bitmap & (1 << IPI_PREEMPT)) {
1265 (*ipi_preempt_counts[cpu])++;
1267 sched_preempt(curthread);
1270 if (ipi_bitmap & (1 << IPI_AST)) {
1272 (*ipi_ast_counts[cpu])++;
1274 /* Nothing to do for AST */
1277 if (ipi_bitmap & (1 << IPI_HARDCLOCK))
1278 hardclockintr(&frame);
1280 if (ipi_bitmap & (1 << IPI_STATCLOCK))
1281 statclockintr(&frame);
1283 if (ipi_bitmap & (1 << IPI_PROFCLOCK))
1284 profclockintr(&frame);
1288 * send an IPI to a set of cpus.
1291 ipi_selected(cpumask_t cpus, u_int ipi)
1298 if (IPI_IS_BITMAPED(ipi)) {
1300 ipi = IPI_BITMAP_VECTOR;
1304 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1305 * of help in order to understand what is the source.
1306 * Set the mask of receiving CPUs for this purpose.
1308 if (ipi == IPI_STOP_HARD)
1309 atomic_set_int(&ipi_nmi_pending, cpus);
1311 CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
1312 while ((cpu = ffs(cpus)) != 0) {
1314 cpus &= ~(1 << cpu);
1316 KASSERT(cpu_apic_ids[cpu] != -1,
1317 ("IPI to non-existent CPU %d", cpu));
1321 old_pending = cpu_ipi_pending[cpu];
1322 new_pending = old_pending | bitmap;
1323 } while (!atomic_cmpset_int(&cpu_ipi_pending[cpu],old_pending, new_pending));
1329 lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1335 * send an IPI to all CPUs EXCEPT myself
1338 ipi_all_but_self(u_int ipi)
1341 if (IPI_IS_BITMAPED(ipi)) {
1342 ipi_selected(PCPU_GET(other_cpus), ipi);
1347 * IPI_STOP_HARD maps to a NMI and the trap handler needs a bit
1348 * of help in order to understand what is the source.
1349 * Set the mask of receiving CPUs for this purpose.
1351 if (ipi == IPI_STOP_HARD)
1352 atomic_set_int(&ipi_nmi_pending, PCPU_GET(other_cpus));
1353 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1354 lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1363 * As long as there is not a simple way to know about a NMI's
1364 * source, if the bitmask for the current CPU is present in
1365 * the global pending bitword an IPI_STOP_HARD has been issued
1366 * and should be handled.
1368 cpumask = PCPU_GET(cpumask);
1369 if ((ipi_nmi_pending & cpumask) == 0)
1372 atomic_clear_int(&ipi_nmi_pending, cpumask);
1378 * Handle an IPI_STOP by saving our current context and spinning until we
1382 cpustop_handler(void)
1384 int cpu = PCPU_GET(cpuid);
1385 int cpumask = PCPU_GET(cpumask);
1387 savectx(&stoppcbs[cpu]);
1389 /* Indicate that we are stopped */
1390 atomic_set_int(&stopped_cpus, cpumask);
1392 /* Wait for restart */
1393 while (!(started_cpus & cpumask))
1396 atomic_clear_int(&started_cpus, cpumask);
1397 atomic_clear_int(&stopped_cpus, cpumask);
1399 if (cpu == 0 && cpustop_restartfunc != NULL) {
1400 cpustop_restartfunc();
1401 cpustop_restartfunc = NULL;
1406 * This is called once the rest of the system is up and running and we're
1407 * ready to let the AP's out of the pen.
1410 release_aps(void *dummy __unused)
1415 atomic_store_rel_int(&aps_ready, 1);
1416 while (smp_started == 0)
1419 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1422 sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1427 mask = hlt_cpus_mask;
1428 error = sysctl_handle_int(oidp, &mask, 0, req);
1429 if (error || !req->newptr)
1432 if (logical_cpus_mask != 0 &&
1433 (mask & logical_cpus_mask) == logical_cpus_mask)
1434 hlt_logical_cpus = 1;
1436 hlt_logical_cpus = 0;
1438 if (! hyperthreading_allowed)
1439 mask |= hyperthreading_cpus_mask;
1441 if ((mask & all_cpus) == all_cpus)
1443 hlt_cpus_mask = mask;
1446 SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1447 0, 0, sysctl_hlt_cpus, "IU",
1448 "Bitmap of CPUs to halt. 101 (binary) will halt CPUs 0 and 2.");
1451 sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1455 disable = hlt_logical_cpus;
1456 error = sysctl_handle_int(oidp, &disable, 0, req);
1457 if (error || !req->newptr)
1461 hlt_cpus_mask |= logical_cpus_mask;
1463 hlt_cpus_mask &= ~logical_cpus_mask;
1465 if (! hyperthreading_allowed)
1466 hlt_cpus_mask |= hyperthreading_cpus_mask;
1468 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1469 hlt_cpus_mask &= ~(1<<0);
1471 hlt_logical_cpus = disable;
1476 sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1480 allowed = hyperthreading_allowed;
1481 error = sysctl_handle_int(oidp, &allowed, 0, req);
1482 if (error || !req->newptr)
1487 * SCHED_ULE doesn't allow enabling/disabling HT cores at
1490 if (allowed != hyperthreading_allowed)
1496 hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1498 hlt_cpus_mask |= hyperthreading_cpus_mask;
1500 if (logical_cpus_mask != 0 &&
1501 (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1502 hlt_logical_cpus = 1;
1504 hlt_logical_cpus = 0;
1506 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1507 hlt_cpus_mask &= ~(1<<0);
1509 hyperthreading_allowed = allowed;
1514 cpu_hlt_setup(void *dummy __unused)
1517 if (logical_cpus_mask != 0) {
1518 TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1520 sysctl_ctx_init(&logical_cpu_clist);
1521 SYSCTL_ADD_PROC(&logical_cpu_clist,
1522 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1523 "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1524 sysctl_hlt_logical_cpus, "IU", "");
1525 SYSCTL_ADD_UINT(&logical_cpu_clist,
1526 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1527 "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1528 &logical_cpus_mask, 0, "");
1530 if (hlt_logical_cpus)
1531 hlt_cpus_mask |= logical_cpus_mask;
1534 * If necessary for security purposes, force
1535 * hyperthreading off, regardless of the value
1536 * of hlt_logical_cpus.
1538 if (hyperthreading_cpus_mask) {
1539 SYSCTL_ADD_PROC(&logical_cpu_clist,
1540 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1541 "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1542 0, 0, sysctl_hyperthreading_allowed, "IU", "");
1543 if (! hyperthreading_allowed)
1544 hlt_cpus_mask |= hyperthreading_cpus_mask;
1548 SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1551 mp_grab_cpu_hlt(void)
1553 u_int mask = PCPU_GET(cpumask);
1555 u_int cpuid = PCPU_GET(cpuid);
1563 retval = mask & hlt_cpus_mask;
1564 while (mask & hlt_cpus_mask)
1565 __asm __volatile("sti; hlt" : : : "memory");
1571 * Setup interrupt counters for IPI handlers.
1574 mp_ipi_intrcnt(void *dummy)
1579 for (i = 0; i < mp_maxid; i++) {
1582 snprintf(buf, sizeof(buf), "cpu%d: invltlb", i);
1583 intrcnt_add(buf, &ipi_invltlb_counts[i]);
1584 snprintf(buf, sizeof(buf), "cpu%d: invlrng", i);
1585 intrcnt_add(buf, &ipi_invlrng_counts[i]);
1586 snprintf(buf, sizeof(buf), "cpu%d: invlpg", i);
1587 intrcnt_add(buf, &ipi_invlpg_counts[i]);
1588 snprintf(buf, sizeof(buf), "cpu%d: preempt", i);
1589 intrcnt_add(buf, &ipi_preempt_counts[i]);
1590 snprintf(buf, sizeof(buf), "cpu%d: ast", i);
1591 intrcnt_add(buf, &ipi_ast_counts[i]);
1592 snprintf(buf, sizeof(buf), "cpu%d: rendezvous", i);
1593 intrcnt_add(buf, &ipi_rendezvous_counts[i]);
1594 snprintf(buf, sizeof(buf), "cpu%d: lazypmap", i);
1595 intrcnt_add(buf, &ipi_lazypmap_counts[i]);
1598 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);