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"
33 #include "opt_sched.h"
38 #error How did you get here?
42 #error The apic device is required for SMP, add "device apic" to your config file.
44 #if defined(CPU_DISABLE_CMPXCHG) && !defined(COMPILING_LINT)
45 #error SMP not supported with CPU_DISABLE_CMPXCHG
49 #include <sys/param.h>
50 #include <sys/systm.h>
52 #include <sys/cons.h> /* cngetc() */
56 #include <sys/kernel.h>
59 #include <sys/malloc.h>
60 #include <sys/memrange.h>
61 #include <sys/mutex.h>
64 #include <sys/sched.h>
66 #include <sys/sysctl.h>
69 #include <vm/vm_param.h>
71 #include <vm/vm_kern.h>
72 #include <vm/vm_extern.h>
74 #include <machine/apicreg.h>
75 #include <machine/md_var.h>
76 #include <machine/mp_watchdog.h>
77 #include <machine/pcb.h>
78 #include <machine/psl.h>
79 #include <machine/smp.h>
80 #include <machine/specialreg.h>
82 #define WARMBOOT_TARGET 0
83 #define WARMBOOT_OFF (KERNBASE + 0x0467)
84 #define WARMBOOT_SEG (KERNBASE + 0x0469)
86 #define CMOS_REG (0x70)
87 #define CMOS_DATA (0x71)
88 #define BIOS_RESET (0x0f)
89 #define BIOS_WARM (0x0a)
92 * this code MUST be enabled here and in mpboot.s.
93 * it follows the very early stages of AP boot by placing values in CMOS ram.
94 * it NORMALLY will never be needed and thus the primitive method for enabling.
99 #if defined(CHECK_POINTS) && !defined(PC98)
100 #define CHECK_READ(A) (outb(CMOS_REG, (A)), inb(CMOS_DATA))
101 #define CHECK_WRITE(A,D) (outb(CMOS_REG, (A)), outb(CMOS_DATA, (D)))
103 #define CHECK_INIT(D); \
104 CHECK_WRITE(0x34, (D)); \
105 CHECK_WRITE(0x35, (D)); \
106 CHECK_WRITE(0x36, (D)); \
107 CHECK_WRITE(0x37, (D)); \
108 CHECK_WRITE(0x38, (D)); \
109 CHECK_WRITE(0x39, (D));
111 #define CHECK_PRINT(S); \
112 printf("%s: %d, %d, %d, %d, %d, %d\n", \
121 #else /* CHECK_POINTS */
123 #define CHECK_INIT(D)
124 #define CHECK_PRINT(S)
125 #define CHECK_WRITE(A, D)
127 #endif /* CHECK_POINTS */
129 /* lock region used by kernel profiling */
132 int mp_naps; /* # of Applications processors */
133 int boot_cpu_id = -1; /* designated BSP */
135 extern struct pcpu __pcpu[];
137 /* AP uses this during bootstrap. Do not staticize. */
141 /* Free these after use */
142 void *bootstacks[MAXCPU];
144 /* Hotwire a 0->4MB V==P mapping */
145 extern pt_entry_t *KPTphys;
147 struct pcb stoppcbs[MAXCPU];
149 /* Variables needed for SMP tlb shootdown. */
150 vm_offset_t smp_tlb_addr1;
151 vm_offset_t smp_tlb_addr2;
152 volatile int smp_tlb_wait;
155 volatile cpumask_t ipi_nmi_pending;
157 static void ipi_nmi_selected(u_int32_t cpus);
161 /* Interrupt counts. */
162 static u_long *ipi_preempt_counts[MAXCPU];
163 static u_long *ipi_ast_counts[MAXCPU];
164 u_long *ipi_invltlb_counts[MAXCPU];
165 u_long *ipi_invlrng_counts[MAXCPU];
166 u_long *ipi_invlpg_counts[MAXCPU];
167 u_long *ipi_invlcache_counts[MAXCPU];
168 u_long *ipi_rendezvous_counts[MAXCPU];
169 u_long *ipi_lazypmap_counts[MAXCPU];
173 * Local data and functions.
178 * Provide an alternate method of stopping other CPUs. If another CPU has
179 * disabled interrupts the conventional STOP IPI will be blocked. This
180 * NMI-based stop should get through in that case.
182 static int stop_cpus_with_nmi = 1;
183 SYSCTL_INT(_debug, OID_AUTO, stop_cpus_with_nmi, CTLTYPE_INT | CTLFLAG_RW,
184 &stop_cpus_with_nmi, 0, "");
185 TUNABLE_INT("debug.stop_cpus_with_nmi", &stop_cpus_with_nmi);
187 #define stop_cpus_with_nmi 0
190 static u_int logical_cpus;
192 /* used to hold the AP's until we are ready to release them */
193 static struct mtx ap_boot_mtx;
195 /* Set to 1 once we're ready to let the APs out of the pen. */
196 static volatile int aps_ready = 0;
199 * Store data from cpu_add() until later in the boot when we actually setup
206 } static cpu_info[MAX_APIC_ID + 1];
207 int cpu_apic_ids[MAXCPU];
209 /* Holds pending bitmap based IPIs per CPU */
210 static volatile u_int cpu_ipi_pending[MAXCPU];
212 static u_int boot_address;
214 static void assign_cpu_ids(void);
215 static void install_ap_tramp(void);
216 static void set_interrupt_apic_ids(void);
217 static int start_all_aps(void);
218 static int start_ap(int apic_id);
219 static void release_aps(void *dummy);
221 static int hlt_logical_cpus;
222 static u_int hyperthreading_cpus;
223 static cpumask_t hyperthreading_cpus_mask;
224 static int hyperthreading_allowed = 1;
225 static struct sysctl_ctx_list logical_cpu_clist;
228 mem_range_AP_init(void)
230 if (mem_range_softc.mr_op && mem_range_softc.mr_op->initAP)
231 mem_range_softc.mr_op->initAP(&mem_range_softc);
239 if (cpu_logical == 0)
241 if (mp_ncpus % (cpu_cores * cpu_logical) != 0) {
242 printf("WARNING: Non-uniform processors.\n");
243 printf("WARNING: Using suboptimal topology.\n");
244 return (smp_topo_none());
247 * No multi-core or hyper-threaded.
249 if (cpu_logical * cpu_cores == 1)
250 return (smp_topo_none());
252 * Only HTT no multi-core.
254 if (cpu_logical > 1 && cpu_cores == 1)
255 return (smp_topo_1level(CG_SHARE_L1, cpu_logical, CG_FLAG_HTT));
257 * Only multi-core no HTT.
259 if (cpu_cores > 1 && cpu_logical == 1)
260 return (smp_topo_1level(CG_SHARE_NONE, cpu_cores, 0));
262 * Both HTT and multi-core.
264 return (smp_topo_2level(CG_SHARE_NONE, cpu_cores,
265 CG_SHARE_L1, cpu_logical, CG_FLAG_HTT));
270 * Calculate usable address in base memory for AP trampoline code.
273 mp_bootaddress(u_int basemem)
276 boot_address = trunc_page(basemem); /* round down to 4k boundary */
277 if ((basemem - boot_address) < bootMP_size)
278 boot_address -= PAGE_SIZE; /* not enough, lower by 4k */
284 cpu_add(u_int apic_id, char boot_cpu)
287 if (apic_id > MAX_APIC_ID) {
288 panic("SMP: APIC ID %d too high", apic_id);
291 KASSERT(cpu_info[apic_id].cpu_present == 0, ("CPU %d added twice",
293 cpu_info[apic_id].cpu_present = 1;
295 KASSERT(boot_cpu_id == -1,
296 ("CPU %d claims to be BSP, but CPU %d already is", apic_id,
298 boot_cpu_id = apic_id;
299 cpu_info[apic_id].cpu_bsp = 1;
301 if (mp_ncpus < MAXCPU)
304 printf("SMP: Added CPU %d (%s)\n", apic_id, boot_cpu ? "BSP" :
309 cpu_mp_setmaxid(void)
312 mp_maxid = MAXCPU - 1;
320 * Always record BSP in CPU map so that the mbuf init code works
326 * No CPUs were found, so this must be a UP system. Setup
327 * the variables to represent a system with a single CPU
334 /* At least one CPU was found. */
337 * One CPU was found, so this must be a UP system with
343 /* At least two CPUs were found. */
348 * Initialize the IPI handlers and start up the AP's.
354 u_int threads_per_cache, p[4];
356 /* Initialize the logical ID to APIC ID table. */
357 for (i = 0; i < MAXCPU; i++) {
358 cpu_apic_ids[i] = -1;
359 cpu_ipi_pending[i] = 0;
362 /* Install an inter-CPU IPI for TLB invalidation */
363 setidt(IPI_INVLTLB, IDTVEC(invltlb),
364 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
365 setidt(IPI_INVLPG, IDTVEC(invlpg),
366 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
367 setidt(IPI_INVLRNG, IDTVEC(invlrng),
368 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
370 /* Install an inter-CPU IPI for cache invalidation. */
371 setidt(IPI_INVLCACHE, IDTVEC(invlcache),
372 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
374 /* Install an inter-CPU IPI for lazy pmap release */
375 setidt(IPI_LAZYPMAP, IDTVEC(lazypmap),
376 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
378 /* Install an inter-CPU IPI for all-CPU rendezvous */
379 setidt(IPI_RENDEZVOUS, IDTVEC(rendezvous),
380 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
382 /* Install generic inter-CPU IPI handler */
383 setidt(IPI_BITMAP_VECTOR, IDTVEC(ipi_intr_bitmap_handler),
384 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
386 /* Install an inter-CPU IPI for CPU stop/restart */
387 setidt(IPI_STOP, IDTVEC(cpustop),
388 SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
391 /* Set boot_cpu_id if needed. */
392 if (boot_cpu_id == -1) {
393 boot_cpu_id = PCPU_GET(apic_id);
394 cpu_info[boot_cpu_id].cpu_bsp = 1;
396 KASSERT(boot_cpu_id == PCPU_GET(apic_id),
397 ("BSP's APIC ID doesn't match boot_cpu_id"));
398 cpu_apic_ids[0] = boot_cpu_id;
402 /* Start each Application Processor */
405 /* Setup the initial logical CPUs info. */
406 logical_cpus = logical_cpus_mask = 0;
407 if (cpu_feature & CPUID_HTT)
408 logical_cpus = (cpu_procinfo & CPUID_HTT_CORES) >> 16;
411 * Work out if hyperthreading is *really* enabled. This
412 * is made really ugly by the fact that processors lie: Dual
413 * core processors claim to be hyperthreaded even when they're
414 * not, presumably because they want to be treated the same
415 * way as HTT with respect to per-cpu software licensing.
416 * At the time of writing (May 12, 2005) the only hyperthreaded
417 * cpus are from Intel, and Intel's dual-core processors can be
418 * identified via the "deterministic cache parameters" cpuid
422 * First determine if this is an Intel processor which claims
423 * to have hyperthreading support.
425 if ((cpu_feature & CPUID_HTT) &&
426 (strcmp(cpu_vendor, "GenuineIntel") == 0)) {
428 * If the "deterministic cache parameters" cpuid calls
429 * are available, use them.
432 /* Ask the processor about the L1 cache. */
433 for (i = 0; i < 1; i++) {
434 cpuid_count(4, i, p);
435 threads_per_cache = ((p[0] & 0x3ffc000) >> 14) + 1;
436 if (hyperthreading_cpus < threads_per_cache)
437 hyperthreading_cpus = threads_per_cache;
438 if ((p[0] & 0x1f) == 0)
444 * If the deterministic cache parameters are not
445 * available, or if no caches were reported to exist,
446 * just accept what the HTT flag indicated.
448 if (hyperthreading_cpus == 0)
449 hyperthreading_cpus = logical_cpus;
452 set_interrupt_apic_ids();
457 * Print various information about the SMP system hardware and setup.
460 cpu_mp_announce(void)
465 printf(" cpu0 (BSP): APIC ID: %2d\n", boot_cpu_id);
466 for (i = 1, x = 0; x <= MAX_APIC_ID; x++) {
467 if (!cpu_info[x].cpu_present || cpu_info[x].cpu_bsp)
469 if (cpu_info[x].cpu_disabled)
470 printf(" cpu (AP): APIC ID: %2d (disabled)\n", x);
472 KASSERT(i < mp_ncpus,
473 ("mp_ncpus and actual cpus are out of whack"));
474 printf(" cpu%d (AP): APIC ID: %2d\n", i++, x);
480 * AP CPU's call this to initialize themselves.
491 /* bootAP is set in start_ap() to our ID. */
494 /* Get per-cpu data */
497 /* prime data page for it to use */
498 pcpu_init(pc, myid, sizeof(struct pcpu));
499 pc->pc_apic_id = cpu_apic_ids[myid];
500 pc->pc_prvspace = pc;
501 pc->pc_curthread = 0;
503 gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
504 gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
506 for (x = 0; x < NGDT; x++) {
507 ssdtosd(&gdt_segs[x], &gdt[myid * NGDT + x].sd);
510 r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
511 r_gdt.rd_base = (int) &gdt[myid * NGDT];
512 lgdt(&r_gdt); /* does magic intra-segment return */
517 PCPU_SET(currentldt, _default_ldt);
519 gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
520 gdt[myid * NGDT + GPROC0_SEL].sd.sd_type = SDT_SYS386TSS;
521 PCPU_SET(common_tss.tss_esp0, 0); /* not used until after switch */
522 PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
523 PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
524 PCPU_SET(tss_gdt, &gdt[myid * NGDT + GPROC0_SEL].sd);
525 PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
528 PCPU_SET(fsgs_gdt, &gdt[myid * NGDT + GUFS_SEL].sd);
531 * Set to a known state:
532 * Set by mpboot.s: CR0_PG, CR0_PE
533 * Set by cpu_setregs: CR0_NE, CR0_MP, CR0_TS, CR0_WP, CR0_AM
536 cr0 &= ~(CR0_CD | CR0_NW | CR0_EM);
538 CHECK_WRITE(0x38, 5);
540 /* Disable local APIC just to be sure. */
543 /* signal our startup to the BSP. */
545 CHECK_WRITE(0x39, 6);
547 /* Spin until the BSP releases the AP's. */
551 /* BSP may have changed PTD while we were waiting */
553 for (addr = 0; addr < NKPT * NBPDR - 1; addr += PAGE_SIZE)
556 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
560 /* Initialize the PAT MSR if present. */
563 /* set up CPU registers and state */
566 /* set up FPU state on the AP */
567 npxinit(__INITIAL_NPXCW__);
569 /* set up SSE registers */
573 /* Enable the PTE no-execute bit. */
574 if ((amd_feature & AMDID_NX) != 0) {
577 msr = rdmsr(MSR_EFER) | EFER_NXE;
578 wrmsr(MSR_EFER, msr);
582 /* A quick check from sanity claus */
583 if (PCPU_GET(apic_id) != lapic_id()) {
584 printf("SMP: cpuid = %d\n", PCPU_GET(cpuid));
585 printf("SMP: actual apic_id = %d\n", lapic_id());
586 printf("SMP: correct apic_id = %d\n", PCPU_GET(apic_id));
587 panic("cpuid mismatch! boom!!");
590 /* Initialize curthread. */
591 KASSERT(PCPU_GET(idlethread) != NULL, ("no idle thread"));
592 PCPU_SET(curthread, PCPU_GET(idlethread));
594 mtx_lock_spin(&ap_boot_mtx);
596 /* Init local apic for irq's */
599 /* Set memory range attributes for this CPU to match the BSP */
604 CTR1(KTR_SMP, "SMP: AP CPU #%d Launched", PCPU_GET(cpuid));
605 printf("SMP: AP CPU #%d Launched!\n", PCPU_GET(cpuid));
607 /* Determine if we are a logical CPU. */
608 if (logical_cpus > 1 && PCPU_GET(apic_id) % logical_cpus != 0)
609 logical_cpus_mask |= PCPU_GET(cpumask);
611 /* Determine if we are a hyperthread. */
612 if (hyperthreading_cpus > 1 &&
613 PCPU_GET(apic_id) % hyperthreading_cpus != 0)
614 hyperthreading_cpus_mask |= PCPU_GET(cpumask);
616 /* Build our map of 'other' CPUs. */
617 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
622 if (smp_cpus == mp_ncpus) {
623 /* enable IPI's, tlb shootdown, freezes etc */
624 atomic_store_rel_int(&smp_started, 1);
625 smp_active = 1; /* historic */
628 mtx_unlock_spin(&ap_boot_mtx);
630 /* wait until all the AP's are up */
631 while (smp_started == 0)
634 /* enter the scheduler */
637 panic("scheduler returned us to %s", __func__);
641 /*******************************************************************
642 * local functions and data
646 * We tell the I/O APIC code about all the CPUs we want to receive
647 * interrupts. If we don't want certain CPUs to receive IRQs we
648 * can simply not tell the I/O APIC code about them in this function.
649 * We also do not tell it about the BSP since it tells itself about
650 * the BSP internally to work with UP kernels and on UP machines.
653 set_interrupt_apic_ids(void)
657 for (i = 0; i < MAXCPU; i++) {
658 apic_id = cpu_apic_ids[i];
661 if (cpu_info[apic_id].cpu_bsp)
663 if (cpu_info[apic_id].cpu_disabled)
666 /* Don't let hyperthreads service interrupts. */
667 if (hyperthreading_cpus > 1 &&
668 apic_id % hyperthreading_cpus != 0)
676 * Assign logical CPU IDs to local APICs.
683 /* Check for explicitly disabled CPUs. */
684 for (i = 0; i <= MAX_APIC_ID; i++) {
685 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp)
688 /* Don't use this CPU if it has been disabled by a tunable. */
689 if (resource_disabled("lapic", i)) {
690 cpu_info[i].cpu_disabled = 1;
696 * Assign CPU IDs to local APIC IDs and disable any CPUs
697 * beyond MAXCPU. CPU 0 has already been assigned to the BSP,
698 * so we only have to assign IDs for APs.
701 for (i = 0; i <= MAX_APIC_ID; i++) {
702 if (!cpu_info[i].cpu_present || cpu_info[i].cpu_bsp ||
703 cpu_info[i].cpu_disabled)
706 if (mp_ncpus < MAXCPU) {
707 cpu_apic_ids[mp_ncpus] = i;
710 cpu_info[i].cpu_disabled = 1;
712 KASSERT(mp_maxid >= mp_ncpus - 1,
713 ("%s: counters out of sync: max %d, count %d", __func__, mp_maxid,
718 * start each AP in our list
720 /* Lowest 1MB is already mapped: don't touch*/
721 #define TMPMAP_START 1
729 u_int32_t mpbioswarmvec;
732 mtx_init(&ap_boot_mtx, "ap boot", NULL, MTX_SPIN);
734 /* install the AP 1st level boot code */
737 /* save the current value of the warm-start vector */
738 mpbioswarmvec = *((u_int32_t *) WARMBOOT_OFF);
740 outb(CMOS_REG, BIOS_RESET);
741 mpbiosreason = inb(CMOS_DATA);
744 /* set up temporary P==V mapping for AP boot */
745 /* XXX this is a hack, we should boot the AP on its own stack/PTD */
747 kptbase = (uintptr_t)(void *)KPTphys;
748 for (i = TMPMAP_START; i < NKPT; i++)
749 PTD[i] = (pd_entry_t)(PG_V | PG_RW |
750 ((kptbase + i * PAGE_SIZE) & PG_FRAME));
754 for (cpu = 1; cpu < mp_ncpus; cpu++) {
755 apic_id = cpu_apic_ids[cpu];
757 /* allocate and set up a boot stack data page */
758 bootstacks[cpu] = (char *)kmem_alloc(kernel_map, KSTACK_PAGES * PAGE_SIZE);
760 /* setup a vector to our boot code */
761 *((volatile u_short *) WARMBOOT_OFF) = WARMBOOT_TARGET;
762 *((volatile u_short *) WARMBOOT_SEG) = (boot_address >> 4);
764 outb(CMOS_REG, BIOS_RESET);
765 outb(CMOS_DATA, BIOS_WARM); /* 'warm-start' */
768 bootSTK = (char *)bootstacks[cpu] + KSTACK_PAGES * PAGE_SIZE - 4;
771 /* attempt to start the Application Processor */
772 CHECK_INIT(99); /* setup checkpoints */
773 if (!start_ap(apic_id)) {
774 printf("AP #%d (PHY# %d) failed!\n", cpu, apic_id);
775 CHECK_PRINT("trace"); /* show checkpoints */
776 /* better panic as the AP may be running loose */
777 printf("panic y/n? [y] ");
781 CHECK_PRINT("trace"); /* show checkpoints */
783 all_cpus |= (1 << cpu); /* record AP in CPU map */
786 /* build our map of 'other' CPUs */
787 PCPU_SET(other_cpus, all_cpus & ~PCPU_GET(cpumask));
789 /* restore the warmstart vector */
790 *(u_int32_t *) WARMBOOT_OFF = mpbioswarmvec;
793 outb(CMOS_REG, BIOS_RESET);
794 outb(CMOS_DATA, mpbiosreason);
797 /* Undo V==P hack from above */
798 for (i = TMPMAP_START; i < NKPT; i++)
800 pmap_invalidate_range(kernel_pmap, 0, NKPT * NBPDR - 1);
802 /* number of APs actually started */
807 * load the 1st level AP boot code into base memory.
810 /* targets for relocation */
811 extern void bigJump(void);
812 extern void bootCodeSeg(void);
813 extern void bootDataSeg(void);
814 extern void MPentry(void);
816 extern u_int mp_gdtbase;
819 install_ap_tramp(void)
822 int size = *(int *) ((u_long) & bootMP_size);
823 vm_offset_t va = boot_address + KERNBASE;
824 u_char *src = (u_char *) ((u_long) bootMP);
825 u_char *dst = (u_char *) va;
826 u_int boot_base = (u_int) bootMP;
831 KASSERT (size <= PAGE_SIZE,
832 ("'size' do not fit into PAGE_SIZE, as expected."));
833 pmap_kenter(va, boot_address);
834 pmap_invalidate_page (kernel_pmap, va);
835 for (x = 0; x < size; ++x)
839 * modify addresses in code we just moved to basemem. unfortunately we
840 * need fairly detailed info about mpboot.s for this to work. changes
841 * to mpboot.s might require changes here.
844 /* boot code is located in KERNEL space */
847 /* modify the lgdt arg */
848 dst32 = (u_int32_t *) (dst + ((u_int) & mp_gdtbase - boot_base));
849 *dst32 = boot_address + ((u_int) & MP_GDT - boot_base);
851 /* modify the ljmp target for MPentry() */
852 dst32 = (u_int32_t *) (dst + ((u_int) bigJump - boot_base) + 1);
853 *dst32 = ((u_int) MPentry - KERNBASE);
855 /* modify the target for boot code segment */
856 dst16 = (u_int16_t *) (dst + ((u_int) bootCodeSeg - boot_base));
857 dst8 = (u_int8_t *) (dst16 + 1);
858 *dst16 = (u_int) boot_address & 0xffff;
859 *dst8 = ((u_int) boot_address >> 16) & 0xff;
861 /* modify the target for boot data segment */
862 dst16 = (u_int16_t *) (dst + ((u_int) bootDataSeg - boot_base));
863 dst8 = (u_int8_t *) (dst16 + 1);
864 *dst16 = (u_int) boot_address & 0xffff;
865 *dst8 = ((u_int) boot_address >> 16) & 0xff;
869 * This function starts the AP (application processor) identified
870 * by the APIC ID 'physicalCpu'. It does quite a "song and dance"
871 * to accomplish this. This is necessary because of the nuances
872 * of the different hardware we might encounter. It isn't pretty,
873 * but it seems to work.
876 start_ap(int apic_id)
881 /* calculate the vector */
882 vector = (boot_address >> 12) & 0xff;
884 /* used as a watchpoint to signal AP startup */
888 * first we do an INIT/RESET IPI this INIT IPI might be run, reseting
889 * and running the target CPU. OR this INIT IPI might be latched (P5
890 * bug), CPU waiting for STARTUP IPI. OR this INIT IPI might be
894 /* do an INIT IPI: assert RESET */
895 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
896 APIC_LEVEL_ASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, apic_id);
898 /* wait for pending status end */
901 /* do an INIT IPI: deassert RESET */
902 lapic_ipi_raw(APIC_DEST_ALLESELF | APIC_TRIGMOD_LEVEL |
903 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_INIT, 0);
905 /* wait for pending status end */
906 DELAY(10000); /* wait ~10mS */
910 * next we do a STARTUP IPI: the previous INIT IPI might still be
911 * latched, (P5 bug) this 1st STARTUP would then terminate
912 * immediately, and the previously started INIT IPI would continue. OR
913 * the previous INIT IPI has already run. and this STARTUP IPI will
914 * run. OR the previous INIT IPI was ignored. and this STARTUP IPI
918 /* do a STARTUP IPI */
919 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
920 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
923 DELAY(200); /* wait ~200uS */
926 * finally we do a 2nd STARTUP IPI: this 2nd STARTUP IPI should run IF
927 * the previous STARTUP IPI was cancelled by a latched INIT IPI. OR
928 * this STARTUP IPI will be ignored, as only ONE STARTUP IPI is
929 * recognized after hardware RESET or INIT IPI.
932 lapic_ipi_raw(APIC_DEST_DESTFLD | APIC_TRIGMOD_EDGE |
933 APIC_LEVEL_DEASSERT | APIC_DESTMODE_PHY | APIC_DELMODE_STARTUP |
936 DELAY(200); /* wait ~200uS */
938 /* Wait up to 5 seconds for it to start. */
939 for (ms = 0; ms < 5000; ms++) {
941 return 1; /* return SUCCESS */
944 return 0; /* return FAILURE */
947 #ifdef COUNT_XINVLTLB_HITS
948 u_int xhits_gbl[MAXCPU];
949 u_int xhits_pg[MAXCPU];
950 u_int xhits_rng[MAXCPU];
951 SYSCTL_NODE(_debug, OID_AUTO, xhits, CTLFLAG_RW, 0, "");
952 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, global, CTLFLAG_RW, &xhits_gbl,
953 sizeof(xhits_gbl), "IU", "");
954 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, page, CTLFLAG_RW, &xhits_pg,
955 sizeof(xhits_pg), "IU", "");
956 SYSCTL_OPAQUE(_debug_xhits, OID_AUTO, range, CTLFLAG_RW, &xhits_rng,
957 sizeof(xhits_rng), "IU", "");
962 u_int ipi_range_size;
963 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_global, CTLFLAG_RW, &ipi_global, 0, "");
964 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_page, CTLFLAG_RW, &ipi_page, 0, "");
965 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range, CTLFLAG_RW, &ipi_range, 0, "");
966 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_range_size, CTLFLAG_RW, &ipi_range_size,
969 u_int ipi_masked_global;
970 u_int ipi_masked_page;
971 u_int ipi_masked_range;
972 u_int ipi_masked_range_size;
973 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_global, CTLFLAG_RW,
974 &ipi_masked_global, 0, "");
975 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_page, CTLFLAG_RW,
976 &ipi_masked_page, 0, "");
977 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range, CTLFLAG_RW,
978 &ipi_masked_range, 0, "");
979 SYSCTL_INT(_debug_xhits, OID_AUTO, ipi_masked_range_size, CTLFLAG_RW,
980 &ipi_masked_range_size, 0, "");
981 #endif /* COUNT_XINVLTLB_HITS */
984 * Flush the TLB on all other CPU's
987 smp_tlb_shootdown(u_int vector, vm_offset_t addr1, vm_offset_t addr2)
991 ncpu = mp_ncpus - 1; /* does not shootdown self */
993 return; /* no other cpus */
994 if (!(read_eflags() & PSL_I))
995 panic("%s: interrupts disabled", __func__);
996 mtx_lock_spin(&smp_ipi_mtx);
997 smp_tlb_addr1 = addr1;
998 smp_tlb_addr2 = addr2;
999 atomic_store_rel_int(&smp_tlb_wait, 0);
1000 ipi_all_but_self(vector);
1001 while (smp_tlb_wait < ncpu)
1003 mtx_unlock_spin(&smp_ipi_mtx);
1007 smp_targeted_tlb_shootdown(u_int mask, u_int vector, vm_offset_t addr1, vm_offset_t addr2)
1009 int ncpu, othercpus;
1011 othercpus = mp_ncpus - 1;
1012 if (mask == (u_int)-1) {
1017 mask &= ~PCPU_GET(cpumask);
1020 ncpu = bitcount32(mask);
1021 if (ncpu > othercpus) {
1022 /* XXX this should be a panic offence */
1023 printf("SMP: tlb shootdown to %d other cpus (only have %d)\n",
1027 /* XXX should be a panic, implied by mask == 0 above */
1031 if (!(read_eflags() & PSL_I))
1032 panic("%s: interrupts disabled", __func__);
1033 mtx_lock_spin(&smp_ipi_mtx);
1034 smp_tlb_addr1 = addr1;
1035 smp_tlb_addr2 = addr2;
1036 atomic_store_rel_int(&smp_tlb_wait, 0);
1037 if (mask == (u_int)-1)
1038 ipi_all_but_self(vector);
1040 ipi_selected(mask, vector);
1041 while (smp_tlb_wait < ncpu)
1043 mtx_unlock_spin(&smp_ipi_mtx);
1047 smp_cache_flush(void)
1051 smp_tlb_shootdown(IPI_INVLCACHE, 0, 0);
1059 smp_tlb_shootdown(IPI_INVLTLB, 0, 0);
1060 #ifdef COUNT_XINVLTLB_HITS
1067 smp_invlpg(vm_offset_t addr)
1071 smp_tlb_shootdown(IPI_INVLPG, addr, 0);
1072 #ifdef COUNT_XINVLTLB_HITS
1079 smp_invlpg_range(vm_offset_t addr1, vm_offset_t addr2)
1083 smp_tlb_shootdown(IPI_INVLRNG, addr1, addr2);
1084 #ifdef COUNT_XINVLTLB_HITS
1086 ipi_range_size += (addr2 - addr1) / PAGE_SIZE;
1092 smp_masked_invltlb(u_int mask)
1096 smp_targeted_tlb_shootdown(mask, IPI_INVLTLB, 0, 0);
1097 #ifdef COUNT_XINVLTLB_HITS
1098 ipi_masked_global++;
1104 smp_masked_invlpg(u_int mask, vm_offset_t addr)
1108 smp_targeted_tlb_shootdown(mask, IPI_INVLPG, addr, 0);
1109 #ifdef COUNT_XINVLTLB_HITS
1116 smp_masked_invlpg_range(u_int mask, vm_offset_t addr1, vm_offset_t addr2)
1120 smp_targeted_tlb_shootdown(mask, IPI_INVLRNG, addr1, addr2);
1121 #ifdef COUNT_XINVLTLB_HITS
1123 ipi_masked_range_size += (addr2 - addr1) / PAGE_SIZE;
1129 ipi_bitmap_handler(struct trapframe frame)
1131 int cpu = PCPU_GET(cpuid);
1134 ipi_bitmap = atomic_readandclear_int(&cpu_ipi_pending[cpu]);
1136 if (ipi_bitmap & (1 << IPI_PREEMPT)) {
1138 (*ipi_preempt_counts[cpu])++;
1140 sched_preempt(curthread);
1143 if (ipi_bitmap & (1 << IPI_AST)) {
1145 (*ipi_ast_counts[cpu])++;
1147 /* Nothing to do for AST */
1152 * send an IPI to a set of cpus.
1155 ipi_selected(u_int32_t cpus, u_int ipi)
1162 if (IPI_IS_BITMAPED(ipi)) {
1164 ipi = IPI_BITMAP_VECTOR;
1168 if (ipi == IPI_STOP && stop_cpus_with_nmi) {
1169 ipi_nmi_selected(cpus);
1173 CTR3(KTR_SMP, "%s: cpus: %x ipi: %x", __func__, cpus, ipi);
1174 while ((cpu = ffs(cpus)) != 0) {
1176 cpus &= ~(1 << cpu);
1178 KASSERT(cpu_apic_ids[cpu] != -1,
1179 ("IPI to non-existent CPU %d", cpu));
1183 old_pending = cpu_ipi_pending[cpu];
1184 new_pending = old_pending | bitmap;
1185 } while (!atomic_cmpset_int(&cpu_ipi_pending[cpu],old_pending, new_pending));
1191 lapic_ipi_vectored(ipi, cpu_apic_ids[cpu]);
1197 * send an IPI to all CPUs EXCEPT myself
1200 ipi_all_but_self(u_int ipi)
1203 if (IPI_IS_BITMAPED(ipi) || (ipi == IPI_STOP && stop_cpus_with_nmi)) {
1204 ipi_selected(PCPU_GET(other_cpus), ipi);
1207 CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi);
1208 lapic_ipi_vectored(ipi, APIC_IPI_DEST_OTHERS);
1213 * send NMI IPI to selected CPUs
1216 #define BEFORE_SPIN 1000000
1219 ipi_nmi_selected(u_int32_t cpus)
1224 icrlo = APIC_DELMODE_NMI | APIC_DESTMODE_PHY | APIC_LEVEL_ASSERT
1225 | APIC_TRIGMOD_EDGE;
1227 CTR2(KTR_SMP, "%s: cpus: %x nmi", __func__, cpus);
1229 atomic_set_int(&ipi_nmi_pending, cpus);
1231 while ((cpu = ffs(cpus)) != 0) {
1233 cpus &= ~(1 << cpu);
1235 KASSERT(cpu_apic_ids[cpu] != -1,
1236 ("IPI NMI to non-existent CPU %d", cpu));
1238 /* Wait for an earlier IPI to finish. */
1239 if (!lapic_ipi_wait(BEFORE_SPIN))
1240 panic("ipi_nmi_selected: previous IPI has not cleared");
1242 lapic_ipi_raw(icrlo, cpu_apic_ids[cpu]);
1247 ipi_nmi_handler(void)
1249 int cpumask = PCPU_GET(cpumask);
1251 if (!(ipi_nmi_pending & cpumask))
1254 atomic_clear_int(&ipi_nmi_pending, cpumask);
1259 #endif /* STOP_NMI */
1262 * Handle an IPI_STOP by saving our current context and spinning until we
1266 cpustop_handler(void)
1268 int cpu = PCPU_GET(cpuid);
1269 int cpumask = PCPU_GET(cpumask);
1271 savectx(&stoppcbs[cpu]);
1273 /* Indicate that we are stopped */
1274 atomic_set_int(&stopped_cpus, cpumask);
1276 /* Wait for restart */
1277 while (!(started_cpus & cpumask))
1280 atomic_clear_int(&started_cpus, cpumask);
1281 atomic_clear_int(&stopped_cpus, cpumask);
1283 if (cpu == 0 && cpustop_restartfunc != NULL) {
1284 cpustop_restartfunc();
1285 cpustop_restartfunc = NULL;
1290 * This is called once the rest of the system is up and running and we're
1291 * ready to let the AP's out of the pen.
1294 release_aps(void *dummy __unused)
1299 atomic_store_rel_int(&aps_ready, 1);
1300 while (smp_started == 0)
1303 SYSINIT(start_aps, SI_SUB_SMP, SI_ORDER_FIRST, release_aps, NULL);
1306 sysctl_hlt_cpus(SYSCTL_HANDLER_ARGS)
1311 mask = hlt_cpus_mask;
1312 error = sysctl_handle_int(oidp, &mask, 0, req);
1313 if (error || !req->newptr)
1316 if (logical_cpus_mask != 0 &&
1317 (mask & logical_cpus_mask) == logical_cpus_mask)
1318 hlt_logical_cpus = 1;
1320 hlt_logical_cpus = 0;
1322 if (! hyperthreading_allowed)
1323 mask |= hyperthreading_cpus_mask;
1325 if ((mask & all_cpus) == all_cpus)
1327 hlt_cpus_mask = mask;
1330 SYSCTL_PROC(_machdep, OID_AUTO, hlt_cpus, CTLTYPE_INT|CTLFLAG_RW,
1331 0, 0, sysctl_hlt_cpus, "IU",
1332 "Bitmap of CPUs to halt. 101 (binary) will halt CPUs 0 and 2.");
1335 sysctl_hlt_logical_cpus(SYSCTL_HANDLER_ARGS)
1339 disable = hlt_logical_cpus;
1340 error = sysctl_handle_int(oidp, &disable, 0, req);
1341 if (error || !req->newptr)
1345 hlt_cpus_mask |= logical_cpus_mask;
1347 hlt_cpus_mask &= ~logical_cpus_mask;
1349 if (! hyperthreading_allowed)
1350 hlt_cpus_mask |= hyperthreading_cpus_mask;
1352 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1353 hlt_cpus_mask &= ~(1<<0);
1355 hlt_logical_cpus = disable;
1360 sysctl_hyperthreading_allowed(SYSCTL_HANDLER_ARGS)
1364 allowed = hyperthreading_allowed;
1365 error = sysctl_handle_int(oidp, &allowed, 0, req);
1366 if (error || !req->newptr)
1370 hlt_cpus_mask &= ~hyperthreading_cpus_mask;
1372 hlt_cpus_mask |= hyperthreading_cpus_mask;
1374 if (logical_cpus_mask != 0 &&
1375 (hlt_cpus_mask & logical_cpus_mask) == logical_cpus_mask)
1376 hlt_logical_cpus = 1;
1378 hlt_logical_cpus = 0;
1380 if ((hlt_cpus_mask & all_cpus) == all_cpus)
1381 hlt_cpus_mask &= ~(1<<0);
1383 hyperthreading_allowed = allowed;
1388 cpu_hlt_setup(void *dummy __unused)
1391 if (logical_cpus_mask != 0) {
1392 TUNABLE_INT_FETCH("machdep.hlt_logical_cpus",
1394 sysctl_ctx_init(&logical_cpu_clist);
1395 SYSCTL_ADD_PROC(&logical_cpu_clist,
1396 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1397 "hlt_logical_cpus", CTLTYPE_INT|CTLFLAG_RW, 0, 0,
1398 sysctl_hlt_logical_cpus, "IU", "");
1399 SYSCTL_ADD_UINT(&logical_cpu_clist,
1400 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1401 "logical_cpus_mask", CTLTYPE_INT|CTLFLAG_RD,
1402 &logical_cpus_mask, 0, "");
1404 if (hlt_logical_cpus)
1405 hlt_cpus_mask |= logical_cpus_mask;
1408 * If necessary for security purposes, force
1409 * hyperthreading off, regardless of the value
1410 * of hlt_logical_cpus.
1412 if (hyperthreading_cpus_mask) {
1413 TUNABLE_INT_FETCH("machdep.hyperthreading_allowed",
1414 &hyperthreading_allowed);
1415 SYSCTL_ADD_PROC(&logical_cpu_clist,
1416 SYSCTL_STATIC_CHILDREN(_machdep), OID_AUTO,
1417 "hyperthreading_allowed", CTLTYPE_INT|CTLFLAG_RW,
1418 0, 0, sysctl_hyperthreading_allowed, "IU", "");
1419 if (! hyperthreading_allowed)
1420 hlt_cpus_mask |= hyperthreading_cpus_mask;
1424 SYSINIT(cpu_hlt, SI_SUB_SMP, SI_ORDER_ANY, cpu_hlt_setup, NULL);
1427 mp_grab_cpu_hlt(void)
1429 u_int mask = PCPU_GET(cpumask);
1431 u_int cpuid = PCPU_GET(cpuid);
1439 retval = mask & hlt_cpus_mask;
1440 while (mask & hlt_cpus_mask)
1441 __asm __volatile("sti; hlt" : : : "memory");
1447 * Setup interrupt counters for IPI handlers.
1450 mp_ipi_intrcnt(void *dummy)
1455 for (i = 0; i < mp_maxid; i++) {
1458 snprintf(buf, sizeof(buf), "cpu%d: invltlb", i);
1459 intrcnt_add(buf, &ipi_invltlb_counts[i]);
1460 snprintf(buf, sizeof(buf), "cpu%d: invlrng", i);
1461 intrcnt_add(buf, &ipi_invlrng_counts[i]);
1462 snprintf(buf, sizeof(buf), "cpu%d: invlpg", i);
1463 intrcnt_add(buf, &ipi_invlpg_counts[i]);
1464 snprintf(buf, sizeof(buf), "cpu%d: preempt", i);
1465 intrcnt_add(buf, &ipi_preempt_counts[i]);
1466 snprintf(buf, sizeof(buf), "cpu%d: ast", i);
1467 intrcnt_add(buf, &ipi_ast_counts[i]);
1468 snprintf(buf, sizeof(buf), "cpu%d: rendezvous", i);
1469 intrcnt_add(buf, &ipi_rendezvous_counts[i]);
1470 snprintf(buf, sizeof(buf), "cpu%d: lazypmap", i);
1471 intrcnt_add(buf, &ipi_lazypmap_counts[i]);
1474 SYSINIT(mp_ipi_intrcnt, SI_SUB_INTR, SI_ORDER_MIDDLE, mp_ipi_intrcnt, NULL);