2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2001, John Baldwin <jhb@FreeBSD.org>.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * This module holds the global variables and machine independent functions
30 * used for the kernel SMP support.
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
40 #include <sys/malloc.h>
41 #include <sys/mutex.h>
43 #include <sys/sched.h>
45 #include <sys/sysctl.h>
47 #include <machine/cpu.h>
48 #include <machine/pcb.h>
49 #include <machine/smp.h>
51 #include "opt_sched.h"
54 MALLOC_DEFINE(M_TOPO, "toponodes", "SMP topology data");
56 volatile cpuset_t stopped_cpus;
57 volatile cpuset_t started_cpus;
58 volatile cpuset_t suspended_cpus;
59 cpuset_t hlt_cpus_mask;
60 cpuset_t logical_cpus_mask;
62 void (*cpustop_restartfunc)(void);
65 static int sysctl_kern_smp_active(SYSCTL_HANDLER_ARGS);
67 /* This is used in modules that need to work in both SMP and UP. */
71 /* export this for libkvm consumers. */
72 int mp_maxcpus = MAXCPU;
74 volatile int smp_started;
77 /* Array of CPU contexts saved during a panic. */
80 static SYSCTL_NODE(_kern, OID_AUTO, smp,
81 CTLFLAG_RD | CTLFLAG_CAPRD | CTLFLAG_MPSAFE, NULL,
84 SYSCTL_INT(_kern_smp, OID_AUTO, maxid, CTLFLAG_RD|CTLFLAG_CAPRD, &mp_maxid, 0,
87 SYSCTL_INT(_kern_smp, OID_AUTO, maxcpus, CTLFLAG_RD|CTLFLAG_CAPRD, &mp_maxcpus,
88 0, "Max number of CPUs that the system was compiled for.");
90 SYSCTL_PROC(_kern_smp, OID_AUTO, active, CTLFLAG_RD|CTLTYPE_INT|CTLFLAG_MPSAFE,
91 NULL, 0, sysctl_kern_smp_active, "I",
92 "Indicates system is running in SMP mode");
94 int smp_disabled = 0; /* has smp been disabled? */
95 SYSCTL_INT(_kern_smp, OID_AUTO, disabled, CTLFLAG_RDTUN|CTLFLAG_CAPRD,
96 &smp_disabled, 0, "SMP has been disabled from the loader");
98 int smp_cpus = 1; /* how many cpu's running */
99 SYSCTL_INT(_kern_smp, OID_AUTO, cpus, CTLFLAG_RD|CTLFLAG_CAPRD, &smp_cpus, 0,
100 "Number of CPUs online");
102 int smp_threads_per_core = 1; /* how many SMT threads are running per core */
103 SYSCTL_INT(_kern_smp, OID_AUTO, threads_per_core, CTLFLAG_RD|CTLFLAG_CAPRD,
104 &smp_threads_per_core, 0, "Number of SMT threads online per core");
106 int mp_ncores = -1; /* how many physical cores running */
107 SYSCTL_INT(_kern_smp, OID_AUTO, cores, CTLFLAG_RD|CTLFLAG_CAPRD, &mp_ncores, 0,
108 "Number of physical cores online");
110 int smp_topology = 0; /* Which topology we're using. */
111 SYSCTL_INT(_kern_smp, OID_AUTO, topology, CTLFLAG_RDTUN, &smp_topology, 0,
112 "Topology override setting; 0 is default provided by hardware.");
115 /* Variables needed for SMP rendezvous. */
116 static volatile int smp_rv_ncpus;
117 static void (*volatile smp_rv_setup_func)(void *arg);
118 static void (*volatile smp_rv_action_func)(void *arg);
119 static void (*volatile smp_rv_teardown_func)(void *arg);
120 static void *volatile smp_rv_func_arg;
121 static volatile int smp_rv_waiters[4];
124 * Shared mutex to restrict busywaits between smp_rendezvous() and
125 * smp(_targeted)_tlb_shootdown(). A deadlock occurs if both of these
126 * functions trigger at once and cause multiple CPUs to busywait with
127 * interrupts disabled.
129 struct mtx smp_ipi_mtx;
132 * Let the MD SMP code initialize mp_maxid very early if it can.
135 mp_setmaxid(void *dummy)
140 KASSERT(mp_ncpus >= 1, ("%s: CPU count < 1", __func__));
141 KASSERT(mp_ncpus > 1 || mp_maxid == 0,
142 ("%s: one CPU but mp_maxid is not zero", __func__));
143 KASSERT(mp_maxid >= mp_ncpus - 1,
144 ("%s: counters out of sync: max %d, count %d", __func__,
145 mp_maxid, mp_ncpus));
147 cpusetsizemin = howmany(mp_maxid + 1, NBBY);
149 SYSINIT(cpu_mp_setmaxid, SI_SUB_TUNABLES, SI_ORDER_FIRST, mp_setmaxid, NULL);
152 * Call the MD SMP initialization code.
155 mp_start(void *dummy)
158 mtx_init(&smp_ipi_mtx, "smp rendezvous", NULL, MTX_SPIN);
160 /* Probe for MP hardware. */
161 if (smp_disabled != 0 || cpu_mp_probe() == 0) {
164 CPU_SETOF(PCPU_GET(cpuid), &all_cpus);
169 printf("FreeBSD/SMP: Multiprocessor System Detected: %d CPUs\n",
172 /* Provide a default for most architectures that don't have SMT/HTT. */
174 mp_ncores = mp_ncpus;
176 stoppcbs = mallocarray(mp_maxid + 1, sizeof(struct pcb), M_DEVBUF,
181 SYSINIT(cpu_mp, SI_SUB_CPU, SI_ORDER_THIRD, mp_start, NULL);
184 forward_signal(struct thread *td)
189 * signotify() has already set TDA_AST and TDA_SIG on td_ast for
190 * this thread, so all we need to do is poke it if it is currently
191 * executing so that it executes ast().
193 THREAD_LOCK_ASSERT(td, MA_OWNED);
194 KASSERT(TD_IS_RUNNING(td),
195 ("forward_signal: thread is not TDS_RUNNING"));
197 CTR1(KTR_SMP, "forward_signal(%p)", td->td_proc);
199 if (!smp_started || cold || KERNEL_PANICKED())
202 /* No need to IPI ourself. */
209 ipi_cpu(id, IPI_AST);
213 * When called the executing CPU will send an IPI to all other CPUs
214 * requesting that they halt execution.
216 * Usually (but not necessarily) called with 'other_cpus' as its arg.
218 * - Signals all CPUs in map to stop.
219 * - Waits for each to stop.
227 #if defined(__amd64__) || defined(__i386__)
233 generic_stop_cpus(cpuset_t map, u_int type)
236 char cpusetbuf[CPUSETBUFSIZ];
238 static volatile u_int stopping_cpu = NOCPU;
240 volatile cpuset_t *cpus;
243 type == IPI_STOP || type == IPI_STOP_HARD
245 || type == IPI_SUSPEND
247 , ("%s: invalid stop type", __func__));
252 CTR2(KTR_SMP, "stop_cpus(%s) with %u type",
253 cpusetobj_strprint(cpusetbuf, &map), type);
257 * When suspending, ensure there are are no IPIs in progress.
258 * IPIs that have been issued, but not yet delivered (e.g.
259 * not pending on a vCPU when running under virtualization)
260 * will be lost, violating FreeBSD's assumption of reliable
263 if (type == IPI_SUSPEND)
264 mtx_lock_spin(&smp_ipi_mtx);
268 if (!nmi_is_broadcast || nmi_kdb_lock == 0) {
270 if (stopping_cpu != PCPU_GET(cpuid))
271 while (atomic_cmpset_int(&stopping_cpu, NOCPU,
272 PCPU_GET(cpuid)) == 0)
273 while (stopping_cpu != NOCPU)
274 cpu_spinwait(); /* spin */
276 /* send the stop IPI to all CPUs in map */
277 ipi_selected(map, type);
283 if (type == IPI_SUSPEND)
284 cpus = &suspended_cpus;
287 cpus = &stopped_cpus;
290 while (!CPU_SUBSET(cpus, &map)) {
294 if (i == 100000000) {
295 printf("timeout stopping cpus\n");
301 if (type == IPI_SUSPEND)
302 mtx_unlock_spin(&smp_ipi_mtx);
305 stopping_cpu = NOCPU;
310 stop_cpus(cpuset_t map)
313 return (generic_stop_cpus(map, IPI_STOP));
317 stop_cpus_hard(cpuset_t map)
320 return (generic_stop_cpus(map, IPI_STOP_HARD));
325 suspend_cpus(cpuset_t map)
328 return (generic_stop_cpus(map, IPI_SUSPEND));
333 * Called by a CPU to restart stopped CPUs.
335 * Usually (but not necessarily) called with 'stopped_cpus' as its arg.
337 * - Signals all CPUs in map to restart.
338 * - Waits for each to restart.
346 generic_restart_cpus(cpuset_t map, u_int type)
349 char cpusetbuf[CPUSETBUFSIZ];
351 volatile cpuset_t *cpus;
354 KASSERT(type == IPI_STOP || type == IPI_STOP_HARD
355 || type == IPI_SUSPEND, ("%s: invalid stop type", __func__));
360 CTR1(KTR_SMP, "restart_cpus(%s)", cpusetobj_strprint(cpusetbuf, &map));
362 if (type == IPI_SUSPEND)
363 cpus = &resuming_cpus;
365 cpus = &stopped_cpus;
367 /* signal other cpus to restart */
368 if (type == IPI_SUSPEND)
369 CPU_COPY_STORE_REL(&map, &toresume_cpus);
371 CPU_COPY_STORE_REL(&map, &started_cpus);
374 * Wake up any CPUs stopped with MWAIT. From MI code we can't tell if
375 * MONITOR/MWAIT is enabled, but the potentially redundant writes are
376 * relatively inexpensive.
378 if (type == IPI_STOP) {
379 struct monitorbuf *mb;
383 if (!CPU_ISSET(id, &map))
386 mb = &pcpu_find(id)->pc_monitorbuf;
387 atomic_store_int(&mb->stop_state,
388 MONITOR_STOPSTATE_RUNNING);
392 if (!nmi_is_broadcast || nmi_kdb_lock == 0) {
393 /* wait for each to clear its bit */
394 while (CPU_OVERLAP(cpus, &map))
398 KASSERT(type == IPI_STOP || type == IPI_STOP_HARD,
399 ("%s: invalid stop type", __func__));
404 CTR1(KTR_SMP, "restart_cpus(%s)", cpusetobj_strprint(cpusetbuf, &map));
406 cpus = &stopped_cpus;
408 /* signal other cpus to restart */
409 CPU_COPY_STORE_REL(&map, &started_cpus);
411 /* wait for each to clear its bit */
412 while (CPU_OVERLAP(cpus, &map))
419 restart_cpus(cpuset_t map)
422 return (generic_restart_cpus(map, IPI_STOP));
427 resume_cpus(cpuset_t map)
430 return (generic_restart_cpus(map, IPI_SUSPEND));
436 * All-CPU rendezvous. CPUs are signalled, all execute the setup function
437 * (if specified), rendezvous, execute the action function (if specified),
438 * rendezvous again, execute the teardown function (if specified), and then
441 * Note that the supplied external functions _must_ be reentrant and aware
442 * that they are running in parallel and in an unknown lock context.
445 smp_rendezvous_action(void)
448 void *local_func_arg;
449 void (*local_setup_func)(void*);
450 void (*local_action_func)(void*);
451 void (*local_teardown_func)(void*);
456 /* Ensure we have up-to-date values. */
457 atomic_add_acq_int(&smp_rv_waiters[0], 1);
458 while (smp_rv_waiters[0] < smp_rv_ncpus)
461 /* Fetch rendezvous parameters after acquire barrier. */
462 local_func_arg = smp_rv_func_arg;
463 local_setup_func = smp_rv_setup_func;
464 local_action_func = smp_rv_action_func;
465 local_teardown_func = smp_rv_teardown_func;
468 * Use a nested critical section to prevent any preemptions
469 * from occurring during a rendezvous action routine.
470 * Specifically, if a rendezvous handler is invoked via an IPI
471 * and the interrupted thread was in the critical_exit()
472 * function after setting td_critnest to 0 but before
473 * performing a deferred preemption, this routine can be
474 * invoked with td_critnest set to 0 and td_owepreempt true.
475 * In that case, a critical_exit() during the rendezvous
476 * action would trigger a preemption which is not permitted in
477 * a rendezvous action. To fix this, wrap all of the
478 * rendezvous action handlers in a critical section. We
479 * cannot use a regular critical section however as having
480 * critical_exit() preempt from this routine would also be
481 * problematic (the preemption must not occur before the IPI
482 * has been acknowledged via an EOI). Instead, we
483 * intentionally ignore td_owepreempt when leaving the
484 * critical section. This should be harmless because we do
485 * not permit rendezvous action routines to schedule threads,
486 * and thus td_owepreempt should never transition from 0 to 1
487 * during this routine.
492 owepreempt = td->td_owepreempt;
496 * If requested, run a setup function before the main action
497 * function. Ensure all CPUs have completed the setup
498 * function before moving on to the action function.
500 if (local_setup_func != smp_no_rendezvous_barrier) {
501 if (local_setup_func != NULL)
502 local_setup_func(local_func_arg);
503 atomic_add_int(&smp_rv_waiters[1], 1);
504 while (smp_rv_waiters[1] < smp_rv_ncpus)
508 if (local_action_func != NULL)
509 local_action_func(local_func_arg);
511 if (local_teardown_func != smp_no_rendezvous_barrier) {
513 * Signal that the main action has been completed. If a
514 * full exit rendezvous is requested, then all CPUs will
515 * wait here until all CPUs have finished the main action.
517 atomic_add_int(&smp_rv_waiters[2], 1);
518 while (smp_rv_waiters[2] < smp_rv_ncpus)
521 if (local_teardown_func != NULL)
522 local_teardown_func(local_func_arg);
526 * Signal that the rendezvous is fully completed by this CPU.
527 * This means that no member of smp_rv_* pseudo-structure will be
528 * accessed by this target CPU after this point; in particular,
529 * memory pointed by smp_rv_func_arg.
531 * The release semantic ensures that all accesses performed by
532 * the current CPU are visible when smp_rendezvous_cpus()
533 * returns, by synchronizing with the
534 * atomic_load_acq_int(&smp_rv_waiters[3]).
536 atomic_add_rel_int(&smp_rv_waiters[3], 1);
539 KASSERT(owepreempt == td->td_owepreempt,
540 ("rendezvous action changed td_owepreempt"));
544 smp_rendezvous_cpus(cpuset_t map,
545 void (* setup_func)(void *),
546 void (* action_func)(void *),
547 void (* teardown_func)(void *),
550 int curcpumap, i, ncpus = 0;
552 /* See comments in the !SMP case. */
555 if (setup_func != NULL)
557 if (action_func != NULL)
559 if (teardown_func != NULL)
566 * Make sure we come here with interrupts enabled. Otherwise we
567 * livelock if smp_ipi_mtx is owned by a thread which sent us an IPI.
569 MPASS(curthread->td_md.md_spinlock_count == 0);
572 if (CPU_ISSET(i, &map))
576 panic("ncpus is 0 with non-zero map");
578 mtx_lock_spin(&smp_ipi_mtx);
580 /* Pass rendezvous parameters via global variables. */
581 smp_rv_ncpus = ncpus;
582 smp_rv_setup_func = setup_func;
583 smp_rv_action_func = action_func;
584 smp_rv_teardown_func = teardown_func;
585 smp_rv_func_arg = arg;
586 smp_rv_waiters[1] = 0;
587 smp_rv_waiters[2] = 0;
588 smp_rv_waiters[3] = 0;
589 atomic_store_rel_int(&smp_rv_waiters[0], 0);
592 * Signal other processors, which will enter the IPI with
595 curcpumap = CPU_ISSET(curcpu, &map);
596 CPU_CLR(curcpu, &map);
597 ipi_selected(map, IPI_RENDEZVOUS);
599 /* Check if the current CPU is in the map */
601 smp_rendezvous_action();
604 * Ensure that the master CPU waits for all the other
605 * CPUs to finish the rendezvous, so that smp_rv_*
606 * pseudo-structure and the arg are guaranteed to not
609 * Load acquire synchronizes with the release add in
610 * smp_rendezvous_action(), which ensures that our caller sees
611 * all memory actions done by the called functions on other
614 while (atomic_load_acq_int(&smp_rv_waiters[3]) < ncpus)
617 mtx_unlock_spin(&smp_ipi_mtx);
621 smp_rendezvous(void (* setup_func)(void *),
622 void (* action_func)(void *),
623 void (* teardown_func)(void *),
626 smp_rendezvous_cpus(all_cpus, setup_func, action_func, teardown_func, arg);
630 smp_topo_fill(struct cpu_group *cg)
634 for (c = 0; c < cg->cg_children; c++)
635 smp_topo_fill(&cg->cg_child[c]);
636 cg->cg_first = CPU_FFS(&cg->cg_mask) - 1;
637 cg->cg_last = CPU_FLS(&cg->cg_mask) - 1;
643 char cpusetbuf[CPUSETBUFSIZ], cpusetbuf2[CPUSETBUFSIZ];
644 static struct cpu_group *top = NULL;
647 * The first call to smp_topo() is guaranteed to occur
648 * during the kernel boot while we are still single-threaded.
654 * Check for a fake topology request for debugging purposes.
656 switch (smp_topology) {
658 /* Dual core with no sharing. */
659 top = smp_topo_1level(CG_SHARE_NONE, 2, 0);
662 /* No topology, all cpus are equal. */
663 top = smp_topo_none();
666 /* Dual core with shared L2. */
667 top = smp_topo_1level(CG_SHARE_L2, 2, 0);
670 /* quad core, shared l3 among each package, private l2. */
671 top = smp_topo_1level(CG_SHARE_L3, 4, 0);
674 /* quad core, 2 dualcore parts on each package share l2. */
675 top = smp_topo_2level(CG_SHARE_NONE, 2, CG_SHARE_L2, 2, 0);
678 /* Single-core 2xHTT */
679 top = smp_topo_1level(CG_SHARE_L1, 2, CG_FLAG_HTT);
682 /* quad core with a shared l3, 8 threads sharing L2. */
683 top = smp_topo_2level(CG_SHARE_L3, 4, CG_SHARE_L2, 8,
687 /* Default, ask the system what it wants. */
692 * Verify the returned topology.
694 if (top->cg_count != mp_ncpus)
695 panic("Built bad topology at %p. CPU count %d != %d",
696 top, top->cg_count, mp_ncpus);
697 if (CPU_CMP(&top->cg_mask, &all_cpus))
698 panic("Built bad topology at %p. CPU mask (%s) != (%s)",
699 top, cpusetobj_strprint(cpusetbuf, &top->cg_mask),
700 cpusetobj_strprint(cpusetbuf2, &all_cpus));
703 * Collapse nonsense levels that may be created out of convenience by
704 * the MD layers. They cause extra work in the search functions.
706 while (top->cg_children == 1) {
707 top = &top->cg_child[0];
708 top->cg_parent = NULL;
715 smp_topo_alloc(u_int count)
717 static struct cpu_group *group = NULL;
722 group = mallocarray((mp_maxid + 1) * MAX_CACHE_LEVELS + 1,
723 sizeof(*group), M_DEVBUF, M_WAITOK | M_ZERO);
727 return (&group[curr]);
733 struct cpu_group *top;
735 top = smp_topo_alloc(1);
736 top->cg_parent = NULL;
737 top->cg_child = NULL;
738 top->cg_mask = all_cpus;
739 top->cg_count = mp_ncpus;
740 top->cg_children = 0;
741 top->cg_level = CG_SHARE_NONE;
748 smp_topo_addleaf(struct cpu_group *parent, struct cpu_group *child, int share,
749 int count, int flags, int start)
751 char cpusetbuf[CPUSETBUFSIZ], cpusetbuf2[CPUSETBUFSIZ];
756 for (i = 0; i < count; i++, start++)
757 CPU_SET(start, &mask);
758 child->cg_parent = parent;
759 child->cg_child = NULL;
760 child->cg_children = 0;
761 child->cg_level = share;
762 child->cg_count = count;
763 child->cg_flags = flags;
764 child->cg_mask = mask;
765 parent->cg_children++;
766 for (; parent != NULL; parent = parent->cg_parent) {
767 if (CPU_OVERLAP(&parent->cg_mask, &child->cg_mask))
768 panic("Duplicate children in %p. mask (%s) child (%s)",
770 cpusetobj_strprint(cpusetbuf, &parent->cg_mask),
771 cpusetobj_strprint(cpusetbuf2, &child->cg_mask));
772 CPU_OR(&parent->cg_mask, &parent->cg_mask, &child->cg_mask);
773 parent->cg_count += child->cg_count;
780 smp_topo_1level(int share, int count, int flags)
782 struct cpu_group *child;
783 struct cpu_group *top;
789 packages = mp_ncpus / count;
790 top = smp_topo_alloc(1 + packages);
791 top->cg_child = child = top + 1;
792 top->cg_level = CG_SHARE_NONE;
793 for (i = 0; i < packages; i++, child++)
794 cpu = smp_topo_addleaf(top, child, share, count, flags, cpu);
799 smp_topo_2level(int l2share, int l2count, int l1share, int l1count,
802 struct cpu_group *top;
803 struct cpu_group *l1g;
804 struct cpu_group *l2g;
810 top = smp_topo_alloc(1 + mp_ncpus / (l2count * l1count) +
814 top->cg_level = CG_SHARE_NONE;
815 top->cg_children = mp_ncpus / (l2count * l1count);
816 l1g = l2g + top->cg_children;
817 for (i = 0; i < top->cg_children; i++, l2g++) {
818 l2g->cg_parent = top;
820 l2g->cg_level = l2share;
821 for (j = 0; j < l2count; j++, l1g++)
822 cpu = smp_topo_addleaf(l2g, l1g, l1share, l1count,
829 smp_topo_find(struct cpu_group *top, int cpu)
831 struct cpu_group *cg;
836 CPU_SETOF(cpu, &mask);
839 if (!CPU_OVERLAP(&cg->cg_mask, &mask))
841 if (cg->cg_children == 0)
843 children = cg->cg_children;
844 for (i = 0, cg = cg->cg_child; i < children; cg++, i++)
845 if (CPU_OVERLAP(&cg->cg_mask, &mask))
853 smp_rendezvous_cpus(cpuset_t map,
854 void (*setup_func)(void *),
855 void (*action_func)(void *),
856 void (*teardown_func)(void *),
860 * In the !SMP case we just need to ensure the same initial conditions
864 if (setup_func != NULL)
866 if (action_func != NULL)
868 if (teardown_func != NULL)
874 smp_rendezvous(void (*setup_func)(void *),
875 void (*action_func)(void *),
876 void (*teardown_func)(void *),
880 smp_rendezvous_cpus(all_cpus, setup_func, action_func, teardown_func,
885 * Provide dummy SMP support for UP kernels. Modules that need to use SMP
886 * APIs will still work using this dummy support.
889 mp_setvariables_for_up(void *dummy)
893 mp_maxid = PCPU_GET(cpuid);
894 CPU_SETOF(mp_maxid, &all_cpus);
895 KASSERT(PCPU_GET(cpuid) == 0, ("UP must have a CPU ID of zero"));
897 SYSINIT(cpu_mp_setvariables, SI_SUB_TUNABLES, SI_ORDER_FIRST,
898 mp_setvariables_for_up, NULL);
902 smp_no_rendezvous_barrier(void *dummy)
905 KASSERT((!smp_started),("smp_no_rendezvous called and smp is started"));
910 smp_rendezvous_cpus_retry(cpuset_t map,
911 void (* setup_func)(void *),
912 void (* action_func)(void *),
913 void (* teardown_func)(void *),
914 void (* wait_func)(void *, int),
915 struct smp_rendezvous_cpus_retry_arg *arg)
919 CPU_COPY(&map, &arg->cpus);
922 * Only one CPU to execute on.
926 if (setup_func != NULL)
928 if (action_func != NULL)
930 if (teardown_func != NULL)
937 * Execute an action on all specified CPUs while retrying until they
938 * all acknowledge completion.
948 if (CPU_EMPTY(&arg->cpus))
952 if (!CPU_ISSET(cpu, &arg->cpus))
960 smp_rendezvous_cpus_done(struct smp_rendezvous_cpus_retry_arg *arg)
963 CPU_CLR_ATOMIC(curcpu, &arg->cpus);
967 * If (prio & PDROP) == 0:
968 * Wait for specified idle threads to switch once. This ensures that even
969 * preempted threads have cycled through the switch function once,
970 * exiting their codepaths. This allows us to change global pointers
971 * with no other synchronization.
972 * If (prio & PDROP) != 0:
973 * Force the specified CPUs to switch context at least once.
976 quiesce_cpus(cpuset_t map, const char *wmesg, int prio)
984 if ((prio & PDROP) == 0) {
985 gen = mallocarray(sizeof(u_int), mp_maxid + 1, M_TEMP,
987 for (cpu = 0; cpu <= mp_maxid; cpu++) {
988 if (!CPU_ISSET(cpu, &map) || CPU_ABSENT(cpu))
990 pcpu = pcpu_find(cpu);
991 gen[cpu] = pcpu->pc_idlethread->td_generation;
994 for (cpu = 0; cpu <= mp_maxid; cpu++) {
995 if (!CPU_ISSET(cpu, &map) || CPU_ABSENT(cpu))
997 pcpu = pcpu_find(cpu);
998 thread_lock(curthread);
999 sched_bind(curthread, cpu);
1000 thread_unlock(curthread);
1001 if ((prio & PDROP) != 0)
1003 while (gen[cpu] == pcpu->pc_idlethread->td_generation) {
1004 error = tsleep(quiesce_cpus, prio & ~PDROP, wmesg, 1);
1005 if (error != EWOULDBLOCK)
1011 thread_lock(curthread);
1012 sched_unbind(curthread);
1013 thread_unlock(curthread);
1014 if ((prio & PDROP) == 0)
1021 quiesce_all_cpus(const char *wmesg, int prio)
1024 return quiesce_cpus(all_cpus, wmesg, prio);
1028 * Observe all CPUs not executing in critical section.
1029 * We are not in one so the check for us is safe. If the found
1030 * thread changes to something else we know the section was
1034 quiesce_all_critical(void)
1036 struct thread *td, *newtd;
1040 MPASS(curthread->td_critnest == 0);
1043 pcpu = cpuid_to_pcpu[cpu];
1044 td = pcpu->pc_curthread;
1046 if (td->td_critnest == 0)
1049 newtd = (struct thread *)
1050 atomic_load_acq_ptr((void *)pcpu->pc_curthread);
1058 cpus_fence_seq_cst_issue(void *arg __unused)
1061 atomic_thread_fence_seq_cst();
1065 * Send an IPI forcing a sequentially consistent fence.
1067 * Allows replacement of an explicitly fence with a compiler barrier.
1068 * Trades speed up during normal execution for a significant slowdown when
1069 * the barrier is needed.
1072 cpus_fence_seq_cst(void)
1077 smp_no_rendezvous_barrier,
1078 cpus_fence_seq_cst_issue,
1079 smp_no_rendezvous_barrier,
1083 cpus_fence_seq_cst_issue(NULL);
1087 /* Extra care is taken with this sysctl because the data type is volatile */
1089 sysctl_kern_smp_active(SYSCTL_HANDLER_ARGS)
1093 active = smp_started;
1094 error = SYSCTL_OUT(req, &active, sizeof(active));
1100 topo_init_node(struct topo_node *node)
1103 bzero(node, sizeof(*node));
1104 TAILQ_INIT(&node->children);
1108 topo_init_root(struct topo_node *root)
1111 topo_init_node(root);
1112 root->type = TOPO_TYPE_SYSTEM;
1116 * Add a child node with the given ID under the given parent.
1117 * Do nothing if there is already a child with that ID.
1120 topo_add_node_by_hwid(struct topo_node *parent, int hwid,
1121 topo_node_type type, uintptr_t subtype)
1123 struct topo_node *node;
1125 TAILQ_FOREACH_REVERSE(node, &parent->children,
1126 topo_children, siblings) {
1127 if (node->hwid == hwid
1128 && node->type == type && node->subtype == subtype) {
1133 node = malloc(sizeof(*node), M_TOPO, M_WAITOK);
1134 topo_init_node(node);
1135 node->parent = parent;
1138 node->subtype = subtype;
1139 TAILQ_INSERT_TAIL(&parent->children, node, siblings);
1140 parent->nchildren++;
1146 * Find a child node with the given ID under the given parent.
1149 topo_find_node_by_hwid(struct topo_node *parent, int hwid,
1150 topo_node_type type, uintptr_t subtype)
1153 struct topo_node *node;
1155 TAILQ_FOREACH(node, &parent->children, siblings) {
1156 if (node->hwid == hwid
1157 && node->type == type && node->subtype == subtype) {
1166 * Given a node change the order of its parent's child nodes such
1167 * that the node becomes the firt child while preserving the cyclic
1168 * order of the children. In other words, the given node is promoted
1172 topo_promote_child(struct topo_node *child)
1174 struct topo_node *next;
1175 struct topo_node *node;
1176 struct topo_node *parent;
1178 parent = child->parent;
1179 next = TAILQ_NEXT(child, siblings);
1180 TAILQ_REMOVE(&parent->children, child, siblings);
1181 TAILQ_INSERT_HEAD(&parent->children, child, siblings);
1183 while (next != NULL) {
1185 next = TAILQ_NEXT(node, siblings);
1186 TAILQ_REMOVE(&parent->children, node, siblings);
1187 TAILQ_INSERT_AFTER(&parent->children, child, node, siblings);
1193 * Iterate to the next node in the depth-first search (traversal) of
1194 * the topology tree.
1197 topo_next_node(struct topo_node *top, struct topo_node *node)
1199 struct topo_node *next;
1201 if ((next = TAILQ_FIRST(&node->children)) != NULL)
1204 if ((next = TAILQ_NEXT(node, siblings)) != NULL)
1207 while (node != top && (node = node->parent) != top)
1208 if ((next = TAILQ_NEXT(node, siblings)) != NULL)
1215 * Iterate to the next node in the depth-first search of the topology tree,
1216 * but without descending below the current node.
1219 topo_next_nonchild_node(struct topo_node *top, struct topo_node *node)
1221 struct topo_node *next;
1223 if ((next = TAILQ_NEXT(node, siblings)) != NULL)
1226 while (node != top && (node = node->parent) != top)
1227 if ((next = TAILQ_NEXT(node, siblings)) != NULL)
1234 * Assign the given ID to the given topology node that represents a logical
1238 topo_set_pu_id(struct topo_node *node, cpuid_t id)
1241 KASSERT(node->type == TOPO_TYPE_PU,
1242 ("topo_set_pu_id: wrong node type: %u", node->type));
1243 KASSERT(CPU_EMPTY(&node->cpuset) && node->cpu_count == 0,
1244 ("topo_set_pu_id: cpuset already not empty"));
1246 CPU_SET(id, &node->cpuset);
1247 node->cpu_count = 1;
1250 while ((node = node->parent) != NULL) {
1251 KASSERT(!CPU_ISSET(id, &node->cpuset),
1252 ("logical ID %u is already set in node %p", id, node));
1253 CPU_SET(id, &node->cpuset);
1258 static struct topology_spec {
1259 topo_node_type type;
1262 } topology_level_table[TOPO_LEVEL_COUNT] = {
1263 [TOPO_LEVEL_PKG] = { .type = TOPO_TYPE_PKG, },
1264 [TOPO_LEVEL_GROUP] = { .type = TOPO_TYPE_GROUP, },
1265 [TOPO_LEVEL_CACHEGROUP] = {
1266 .type = TOPO_TYPE_CACHE,
1267 .match_subtype = true,
1268 .subtype = CG_SHARE_L3,
1270 [TOPO_LEVEL_CORE] = { .type = TOPO_TYPE_CORE, },
1271 [TOPO_LEVEL_THREAD] = { .type = TOPO_TYPE_PU, },
1275 topo_analyze_table(struct topo_node *root, int all, enum topo_level level,
1276 struct topo_analysis *results)
1278 struct topology_spec *spec;
1279 struct topo_node *node;
1282 if (level >= TOPO_LEVEL_COUNT)
1285 spec = &topology_level_table[level];
1287 node = topo_next_node(root, root);
1289 while (node != NULL) {
1290 if (node->type != spec->type ||
1291 (spec->match_subtype && node->subtype != spec->subtype)) {
1292 node = topo_next_node(root, node);
1295 if (!all && CPU_EMPTY(&node->cpuset)) {
1296 node = topo_next_nonchild_node(root, node);
1302 if (!topo_analyze_table(node, all, level + 1, results))
1305 node = topo_next_nonchild_node(root, node);
1308 /* No explicit subgroups is essentially one subgroup. */
1312 if (!topo_analyze_table(root, all, level + 1, results))
1316 if (results->entities[level] == -1)
1317 results->entities[level] = count;
1318 else if (results->entities[level] != count)
1325 * Check if the topology is uniform, that is, each package has the same number
1326 * of cores in it and each core has the same number of threads (logical
1327 * processors) in it. If so, calculate the number of packages, the number of
1328 * groups per package, the number of cachegroups per group, and the number of
1329 * logical processors per cachegroup. 'all' parameter tells whether to include
1330 * administratively disabled logical processors into the analysis.
1333 topo_analyze(struct topo_node *topo_root, int all,
1334 struct topo_analysis *results)
1337 results->entities[TOPO_LEVEL_PKG] = -1;
1338 results->entities[TOPO_LEVEL_CORE] = -1;
1339 results->entities[TOPO_LEVEL_THREAD] = -1;
1340 results->entities[TOPO_LEVEL_GROUP] = -1;
1341 results->entities[TOPO_LEVEL_CACHEGROUP] = -1;
1343 if (!topo_analyze_table(topo_root, all, TOPO_LEVEL_PKG, results))
1346 KASSERT(results->entities[TOPO_LEVEL_PKG] > 0,
1347 ("bug in topology or analysis"));