xref: /freebsd/sys/kern/subr_smp.c (revision a2f733abcff64628b7771a47089628b7327a88bd)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2001, John Baldwin <jhb@FreeBSD.org>.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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.
14  *
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
25  * SUCH DAMAGE.
26  */
27 
28 /*
29  * This module holds the global variables and machine independent functions
30  * used for the kernel SMP support.
31  */
32 
33 #include <sys/cdefs.h>
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/ktr.h>
38 #include <sys/proc.h>
39 #include <sys/bus.h>
40 #include <sys/lock.h>
41 #include <sys/malloc.h>
42 #include <sys/mutex.h>
43 #include <sys/pcpu.h>
44 #include <sys/sched.h>
45 #include <sys/smp.h>
46 #include <sys/sysctl.h>
47 
48 #include <machine/cpu.h>
49 #include <machine/pcb.h>
50 #include <machine/smp.h>
51 
52 #include "opt_sched.h"
53 
54 #ifdef SMP
55 MALLOC_DEFINE(M_TOPO, "toponodes", "SMP topology data");
56 
57 volatile cpuset_t stopped_cpus;
58 volatile cpuset_t started_cpus;
59 volatile cpuset_t suspended_cpus;
60 cpuset_t hlt_cpus_mask;
61 cpuset_t logical_cpus_mask;
62 
63 void (*cpustop_restartfunc)(void);
64 #endif
65 
66 static int sysctl_kern_smp_active(SYSCTL_HANDLER_ARGS);
67 
68 /* This is used in modules that need to work in both SMP and UP. */
69 cpuset_t all_cpus;
70 
71 int mp_ncpus;
72 /* export this for libkvm consumers. */
73 int mp_maxcpus = MAXCPU;
74 
75 volatile int smp_started;
76 u_int mp_maxid;
77 
78 /* Array of CPU contexts saved during a panic. */
79 struct pcb *stoppcbs;
80 
81 static SYSCTL_NODE(_kern, OID_AUTO, smp,
82     CTLFLAG_RD | CTLFLAG_CAPRD | CTLFLAG_MPSAFE, NULL,
83     "Kernel SMP");
84 
85 SYSCTL_INT(_kern_smp, OID_AUTO, maxid, CTLFLAG_RD|CTLFLAG_CAPRD, &mp_maxid, 0,
86     "Max CPU ID.");
87 
88 SYSCTL_INT(_kern_smp, OID_AUTO, maxcpus, CTLFLAG_RD|CTLFLAG_CAPRD, &mp_maxcpus,
89     0, "Max number of CPUs that the system was compiled for.");
90 
91 SYSCTL_PROC(_kern_smp, OID_AUTO, active, CTLFLAG_RD|CTLTYPE_INT|CTLFLAG_MPSAFE,
92     NULL, 0, sysctl_kern_smp_active, "I",
93     "Indicates system is running in SMP mode");
94 
95 int smp_disabled = 0;	/* has smp been disabled? */
96 SYSCTL_INT(_kern_smp, OID_AUTO, disabled, CTLFLAG_RDTUN|CTLFLAG_CAPRD,
97     &smp_disabled, 0, "SMP has been disabled from the loader");
98 
99 int smp_cpus = 1;	/* how many cpu's running */
100 SYSCTL_INT(_kern_smp, OID_AUTO, cpus, CTLFLAG_RD|CTLFLAG_CAPRD, &smp_cpus, 0,
101     "Number of CPUs online");
102 
103 int smp_threads_per_core = 1;	/* how many SMT threads are running per core */
104 SYSCTL_INT(_kern_smp, OID_AUTO, threads_per_core, CTLFLAG_RD|CTLFLAG_CAPRD,
105     &smp_threads_per_core, 0, "Number of SMT threads online per core");
106 
107 int mp_ncores = -1;	/* how many physical cores running */
108 SYSCTL_INT(_kern_smp, OID_AUTO, cores, CTLFLAG_RD|CTLFLAG_CAPRD, &mp_ncores, 0,
109     "Number of physical cores online");
110 
111 int smp_topology = 0;	/* Which topology we're using. */
112 SYSCTL_INT(_kern_smp, OID_AUTO, topology, CTLFLAG_RDTUN, &smp_topology, 0,
113     "Topology override setting; 0 is default provided by hardware.");
114 
115 #ifdef SMP
116 /* Variables needed for SMP rendezvous. */
117 static volatile int smp_rv_ncpus;
118 static void (*volatile smp_rv_setup_func)(void *arg);
119 static void (*volatile smp_rv_action_func)(void *arg);
120 static void (*volatile smp_rv_teardown_func)(void *arg);
121 static void *volatile smp_rv_func_arg;
122 static volatile int smp_rv_waiters[4];
123 
124 /*
125  * Shared mutex to restrict busywaits between smp_rendezvous() and
126  * smp(_targeted)_tlb_shootdown().  A deadlock occurs if both of these
127  * functions trigger at once and cause multiple CPUs to busywait with
128  * interrupts disabled.
129  */
130 struct mtx smp_ipi_mtx;
131 
132 /*
133  * Let the MD SMP code initialize mp_maxid very early if it can.
134  */
135 static void
136 mp_setmaxid(void *dummy)
137 {
138 
139 	cpu_mp_setmaxid();
140 
141 	KASSERT(mp_ncpus >= 1, ("%s: CPU count < 1", __func__));
142 	KASSERT(mp_ncpus > 1 || mp_maxid == 0,
143 	    ("%s: one CPU but mp_maxid is not zero", __func__));
144 	KASSERT(mp_maxid >= mp_ncpus - 1,
145 	    ("%s: counters out of sync: max %d, count %d", __func__,
146 		mp_maxid, mp_ncpus));
147 
148 	cpusetsizemin = howmany(mp_maxid + 1, NBBY);
149 }
150 SYSINIT(cpu_mp_setmaxid, SI_SUB_TUNABLES, SI_ORDER_FIRST, mp_setmaxid, NULL);
151 
152 /*
153  * Call the MD SMP initialization code.
154  */
155 static void
156 mp_start(void *dummy)
157 {
158 
159 	mtx_init(&smp_ipi_mtx, "smp rendezvous", NULL, MTX_SPIN);
160 
161 	/* Probe for MP hardware. */
162 	if (smp_disabled != 0 || cpu_mp_probe() == 0) {
163 		mp_ncores = 1;
164 		mp_ncpus = 1;
165 		CPU_SETOF(PCPU_GET(cpuid), &all_cpus);
166 		return;
167 	}
168 
169 	cpu_mp_start();
170 	printf("FreeBSD/SMP: Multiprocessor System Detected: %d CPUs\n",
171 	    mp_ncpus);
172 
173 	/* Provide a default for most architectures that don't have SMT/HTT. */
174 	if (mp_ncores < 0)
175 		mp_ncores = mp_ncpus;
176 
177 	stoppcbs = mallocarray(mp_maxid + 1, sizeof(struct pcb), M_DEVBUF,
178 	    M_WAITOK | M_ZERO);
179 
180 	cpu_mp_announce();
181 }
182 SYSINIT(cpu_mp, SI_SUB_CPU, SI_ORDER_THIRD, mp_start, NULL);
183 
184 void
185 forward_signal(struct thread *td)
186 {
187 	int id;
188 
189 	/*
190 	 * signotify() has already set TDA_AST and TDA_SIG on td_ast for
191 	 * this thread, so all we need to do is poke it if it is currently
192 	 * executing so that it executes ast().
193 	 */
194 	THREAD_LOCK_ASSERT(td, MA_OWNED);
195 	KASSERT(TD_IS_RUNNING(td),
196 	    ("forward_signal: thread is not TDS_RUNNING"));
197 
198 	CTR1(KTR_SMP, "forward_signal(%p)", td->td_proc);
199 
200 	if (!smp_started || cold || KERNEL_PANICKED())
201 		return;
202 
203 	/* No need to IPI ourself. */
204 	if (td == curthread)
205 		return;
206 
207 	id = td->td_oncpu;
208 	if (id == NOCPU)
209 		return;
210 	ipi_cpu(id, IPI_AST);
211 }
212 
213 /*
214  * When called the executing CPU will send an IPI to all other CPUs
215  *  requesting that they halt execution.
216  *
217  * Usually (but not necessarily) called with 'other_cpus' as its arg.
218  *
219  *  - Signals all CPUs in map to stop.
220  *  - Waits for each to stop.
221  *
222  * Returns:
223  *  -1: error
224  *   0: NA
225  *   1: ok
226  *
227  */
228 #if defined(__amd64__) || defined(__i386__)
229 #define	X86	1
230 #else
231 #define	X86	0
232 #endif
233 static int
234 generic_stop_cpus(cpuset_t map, u_int type)
235 {
236 #ifdef KTR
237 	char cpusetbuf[CPUSETBUFSIZ];
238 #endif
239 	static volatile u_int stopping_cpu = NOCPU;
240 	int i;
241 	volatile cpuset_t *cpus;
242 
243 	KASSERT(
244 	    type == IPI_STOP || type == IPI_STOP_HARD
245 #if X86
246 	    || type == IPI_SUSPEND
247 #endif
248 	    , ("%s: invalid stop type", __func__));
249 
250 	if (!smp_started)
251 		return (0);
252 
253 	CTR2(KTR_SMP, "stop_cpus(%s) with %u type",
254 	    cpusetobj_strprint(cpusetbuf, &map), type);
255 
256 #if X86
257 	/*
258 	 * When suspending, ensure there are are no IPIs in progress.
259 	 * IPIs that have been issued, but not yet delivered (e.g.
260 	 * not pending on a vCPU when running under virtualization)
261 	 * will be lost, violating FreeBSD's assumption of reliable
262 	 * IPI delivery.
263 	 */
264 	if (type == IPI_SUSPEND)
265 		mtx_lock_spin(&smp_ipi_mtx);
266 #endif
267 
268 #if X86
269 	if (!nmi_is_broadcast || nmi_kdb_lock == 0) {
270 #endif
271 	if (stopping_cpu != PCPU_GET(cpuid))
272 		while (atomic_cmpset_int(&stopping_cpu, NOCPU,
273 		    PCPU_GET(cpuid)) == 0)
274 			while (stopping_cpu != NOCPU)
275 				cpu_spinwait(); /* spin */
276 
277 	/* send the stop IPI to all CPUs in map */
278 	ipi_selected(map, type);
279 #if X86
280 	}
281 #endif
282 
283 #if X86
284 	if (type == IPI_SUSPEND)
285 		cpus = &suspended_cpus;
286 	else
287 #endif
288 		cpus = &stopped_cpus;
289 
290 	i = 0;
291 	while (!CPU_SUBSET(cpus, &map)) {
292 		/* spin */
293 		cpu_spinwait();
294 		i++;
295 		if (i == 100000000) {
296 			printf("timeout stopping cpus\n");
297 			break;
298 		}
299 	}
300 
301 #if X86
302 	if (type == IPI_SUSPEND)
303 		mtx_unlock_spin(&smp_ipi_mtx);
304 #endif
305 
306 	stopping_cpu = NOCPU;
307 	return (1);
308 }
309 
310 int
311 stop_cpus(cpuset_t map)
312 {
313 
314 	return (generic_stop_cpus(map, IPI_STOP));
315 }
316 
317 int
318 stop_cpus_hard(cpuset_t map)
319 {
320 
321 	return (generic_stop_cpus(map, IPI_STOP_HARD));
322 }
323 
324 #if X86
325 int
326 suspend_cpus(cpuset_t map)
327 {
328 
329 	return (generic_stop_cpus(map, IPI_SUSPEND));
330 }
331 #endif
332 
333 /*
334  * Called by a CPU to restart stopped CPUs.
335  *
336  * Usually (but not necessarily) called with 'stopped_cpus' as its arg.
337  *
338  *  - Signals all CPUs in map to restart.
339  *  - Waits for each to restart.
340  *
341  * Returns:
342  *  -1: error
343  *   0: NA
344  *   1: ok
345  */
346 static int
347 generic_restart_cpus(cpuset_t map, u_int type)
348 {
349 #ifdef KTR
350 	char cpusetbuf[CPUSETBUFSIZ];
351 #endif
352 	volatile cpuset_t *cpus;
353 
354 #if X86
355 	KASSERT(type == IPI_STOP || type == IPI_STOP_HARD
356 	    || type == IPI_SUSPEND, ("%s: invalid stop type", __func__));
357 
358 	if (!smp_started)
359 		return (0);
360 
361 	CTR1(KTR_SMP, "restart_cpus(%s)", cpusetobj_strprint(cpusetbuf, &map));
362 
363 	if (type == IPI_SUSPEND)
364 		cpus = &resuming_cpus;
365 	else
366 		cpus = &stopped_cpus;
367 
368 	/* signal other cpus to restart */
369 	if (type == IPI_SUSPEND)
370 		CPU_COPY_STORE_REL(&map, &toresume_cpus);
371 	else
372 		CPU_COPY_STORE_REL(&map, &started_cpus);
373 
374 	/*
375 	 * Wake up any CPUs stopped with MWAIT.  From MI code we can't tell if
376 	 * MONITOR/MWAIT is enabled, but the potentially redundant writes are
377 	 * relatively inexpensive.
378 	 */
379 	if (type == IPI_STOP) {
380 		struct monitorbuf *mb;
381 		u_int id;
382 
383 		CPU_FOREACH(id) {
384 			if (!CPU_ISSET(id, &map))
385 				continue;
386 
387 			mb = &pcpu_find(id)->pc_monitorbuf;
388 			atomic_store_int(&mb->stop_state,
389 			    MONITOR_STOPSTATE_RUNNING);
390 		}
391 	}
392 
393 	if (!nmi_is_broadcast || nmi_kdb_lock == 0) {
394 		/* wait for each to clear its bit */
395 		while (CPU_OVERLAP(cpus, &map))
396 			cpu_spinwait();
397 	}
398 #else /* !X86 */
399 	KASSERT(type == IPI_STOP || type == IPI_STOP_HARD,
400 	    ("%s: invalid stop type", __func__));
401 
402 	if (!smp_started)
403 		return (0);
404 
405 	CTR1(KTR_SMP, "restart_cpus(%s)", cpusetobj_strprint(cpusetbuf, &map));
406 
407 	cpus = &stopped_cpus;
408 
409 	/* signal other cpus to restart */
410 	CPU_COPY_STORE_REL(&map, &started_cpus);
411 
412 	/* wait for each to clear its bit */
413 	while (CPU_OVERLAP(cpus, &map))
414 		cpu_spinwait();
415 #endif
416 	return (1);
417 }
418 
419 int
420 restart_cpus(cpuset_t map)
421 {
422 
423 	return (generic_restart_cpus(map, IPI_STOP));
424 }
425 
426 #if X86
427 int
428 resume_cpus(cpuset_t map)
429 {
430 
431 	return (generic_restart_cpus(map, IPI_SUSPEND));
432 }
433 #endif
434 #undef X86
435 
436 /*
437  * All-CPU rendezvous.  CPUs are signalled, all execute the setup function
438  * (if specified), rendezvous, execute the action function (if specified),
439  * rendezvous again, execute the teardown function (if specified), and then
440  * resume.
441  *
442  * Note that the supplied external functions _must_ be reentrant and aware
443  * that they are running in parallel and in an unknown lock context.
444  */
445 void
446 smp_rendezvous_action(void)
447 {
448 	struct thread *td;
449 	void *local_func_arg;
450 	void (*local_setup_func)(void*);
451 	void (*local_action_func)(void*);
452 	void (*local_teardown_func)(void*);
453 #ifdef INVARIANTS
454 	int owepreempt;
455 #endif
456 
457 	/* Ensure we have up-to-date values. */
458 	atomic_add_acq_int(&smp_rv_waiters[0], 1);
459 	while (smp_rv_waiters[0] < smp_rv_ncpus)
460 		cpu_spinwait();
461 
462 	/* Fetch rendezvous parameters after acquire barrier. */
463 	local_func_arg = smp_rv_func_arg;
464 	local_setup_func = smp_rv_setup_func;
465 	local_action_func = smp_rv_action_func;
466 	local_teardown_func = smp_rv_teardown_func;
467 
468 	/*
469 	 * Use a nested critical section to prevent any preemptions
470 	 * from occurring during a rendezvous action routine.
471 	 * Specifically, if a rendezvous handler is invoked via an IPI
472 	 * and the interrupted thread was in the critical_exit()
473 	 * function after setting td_critnest to 0 but before
474 	 * performing a deferred preemption, this routine can be
475 	 * invoked with td_critnest set to 0 and td_owepreempt true.
476 	 * In that case, a critical_exit() during the rendezvous
477 	 * action would trigger a preemption which is not permitted in
478 	 * a rendezvous action.  To fix this, wrap all of the
479 	 * rendezvous action handlers in a critical section.  We
480 	 * cannot use a regular critical section however as having
481 	 * critical_exit() preempt from this routine would also be
482 	 * problematic (the preemption must not occur before the IPI
483 	 * has been acknowledged via an EOI).  Instead, we
484 	 * intentionally ignore td_owepreempt when leaving the
485 	 * critical section.  This should be harmless because we do
486 	 * not permit rendezvous action routines to schedule threads,
487 	 * and thus td_owepreempt should never transition from 0 to 1
488 	 * during this routine.
489 	 */
490 	td = curthread;
491 	td->td_critnest++;
492 #ifdef INVARIANTS
493 	owepreempt = td->td_owepreempt;
494 #endif
495 
496 	/*
497 	 * If requested, run a setup function before the main action
498 	 * function.  Ensure all CPUs have completed the setup
499 	 * function before moving on to the action function.
500 	 */
501 	if (local_setup_func != smp_no_rendezvous_barrier) {
502 		if (local_setup_func != NULL)
503 			local_setup_func(local_func_arg);
504 		atomic_add_int(&smp_rv_waiters[1], 1);
505 		while (smp_rv_waiters[1] < smp_rv_ncpus)
506                 	cpu_spinwait();
507 	}
508 
509 	if (local_action_func != NULL)
510 		local_action_func(local_func_arg);
511 
512 	if (local_teardown_func != smp_no_rendezvous_barrier) {
513 		/*
514 		 * Signal that the main action has been completed.  If a
515 		 * full exit rendezvous is requested, then all CPUs will
516 		 * wait here until all CPUs have finished the main action.
517 		 */
518 		atomic_add_int(&smp_rv_waiters[2], 1);
519 		while (smp_rv_waiters[2] < smp_rv_ncpus)
520 			cpu_spinwait();
521 
522 		if (local_teardown_func != NULL)
523 			local_teardown_func(local_func_arg);
524 	}
525 
526 	/*
527 	 * Signal that the rendezvous is fully completed by this CPU.
528 	 * This means that no member of smp_rv_* pseudo-structure will be
529 	 * accessed by this target CPU after this point; in particular,
530 	 * memory pointed by smp_rv_func_arg.
531 	 *
532 	 * The release semantic ensures that all accesses performed by
533 	 * the current CPU are visible when smp_rendezvous_cpus()
534 	 * returns, by synchronizing with the
535 	 * atomic_load_acq_int(&smp_rv_waiters[3]).
536 	 */
537 	atomic_add_rel_int(&smp_rv_waiters[3], 1);
538 
539 	td->td_critnest--;
540 	KASSERT(owepreempt == td->td_owepreempt,
541 	    ("rendezvous action changed td_owepreempt"));
542 }
543 
544 void
545 smp_rendezvous_cpus(cpuset_t map,
546 	void (* setup_func)(void *),
547 	void (* action_func)(void *),
548 	void (* teardown_func)(void *),
549 	void *arg)
550 {
551 	int curcpumap, i, ncpus = 0;
552 
553 	/* See comments in the !SMP case. */
554 	if (!smp_started) {
555 		spinlock_enter();
556 		if (setup_func != NULL)
557 			setup_func(arg);
558 		if (action_func != NULL)
559 			action_func(arg);
560 		if (teardown_func != NULL)
561 			teardown_func(arg);
562 		spinlock_exit();
563 		return;
564 	}
565 
566 	/*
567 	 * Make sure we come here with interrupts enabled.  Otherwise we
568 	 * livelock if smp_ipi_mtx is owned by a thread which sent us an IPI.
569 	 */
570 	MPASS(curthread->td_md.md_spinlock_count == 0);
571 
572 	CPU_FOREACH(i) {
573 		if (CPU_ISSET(i, &map))
574 			ncpus++;
575 	}
576 	if (ncpus == 0)
577 		panic("ncpus is 0 with non-zero map");
578 
579 	mtx_lock_spin(&smp_ipi_mtx);
580 
581 	/* Pass rendezvous parameters via global variables. */
582 	smp_rv_ncpus = ncpus;
583 	smp_rv_setup_func = setup_func;
584 	smp_rv_action_func = action_func;
585 	smp_rv_teardown_func = teardown_func;
586 	smp_rv_func_arg = arg;
587 	smp_rv_waiters[1] = 0;
588 	smp_rv_waiters[2] = 0;
589 	smp_rv_waiters[3] = 0;
590 	atomic_store_rel_int(&smp_rv_waiters[0], 0);
591 
592 	/*
593 	 * Signal other processors, which will enter the IPI with
594 	 * interrupts off.
595 	 */
596 	curcpumap = CPU_ISSET(curcpu, &map);
597 	CPU_CLR(curcpu, &map);
598 	ipi_selected(map, IPI_RENDEZVOUS);
599 
600 	/* Check if the current CPU is in the map */
601 	if (curcpumap != 0)
602 		smp_rendezvous_action();
603 
604 	/*
605 	 * Ensure that the master CPU waits for all the other
606 	 * CPUs to finish the rendezvous, so that smp_rv_*
607 	 * pseudo-structure and the arg are guaranteed to not
608 	 * be in use.
609 	 *
610 	 * Load acquire synchronizes with the release add in
611 	 * smp_rendezvous_action(), which ensures that our caller sees
612 	 * all memory actions done by the called functions on other
613 	 * CPUs.
614 	 */
615 	while (atomic_load_acq_int(&smp_rv_waiters[3]) < ncpus)
616 		cpu_spinwait();
617 
618 	mtx_unlock_spin(&smp_ipi_mtx);
619 }
620 
621 void
622 smp_rendezvous(void (* setup_func)(void *),
623 	       void (* action_func)(void *),
624 	       void (* teardown_func)(void *),
625 	       void *arg)
626 {
627 	smp_rendezvous_cpus(all_cpus, setup_func, action_func, teardown_func, arg);
628 }
629 
630 static void
631 smp_topo_fill(struct cpu_group *cg)
632 {
633 	int c;
634 
635 	for (c = 0; c < cg->cg_children; c++)
636 		smp_topo_fill(&cg->cg_child[c]);
637 	cg->cg_first = CPU_FFS(&cg->cg_mask) - 1;
638 	cg->cg_last = CPU_FLS(&cg->cg_mask) - 1;
639 }
640 
641 struct cpu_group *
642 smp_topo(void)
643 {
644 	char cpusetbuf[CPUSETBUFSIZ], cpusetbuf2[CPUSETBUFSIZ];
645 	static struct cpu_group *top = NULL;
646 
647 	/*
648 	 * The first call to smp_topo() is guaranteed to occur
649 	 * during the kernel boot while we are still single-threaded.
650 	 */
651 	if (top != NULL)
652 		return (top);
653 
654 	/*
655 	 * Check for a fake topology request for debugging purposes.
656 	 */
657 	switch (smp_topology) {
658 	case 1:
659 		/* Dual core with no sharing.  */
660 		top = smp_topo_1level(CG_SHARE_NONE, 2, 0);
661 		break;
662 	case 2:
663 		/* No topology, all cpus are equal. */
664 		top = smp_topo_none();
665 		break;
666 	case 3:
667 		/* Dual core with shared L2.  */
668 		top = smp_topo_1level(CG_SHARE_L2, 2, 0);
669 		break;
670 	case 4:
671 		/* quad core, shared l3 among each package, private l2.  */
672 		top = smp_topo_1level(CG_SHARE_L3, 4, 0);
673 		break;
674 	case 5:
675 		/* quad core,  2 dualcore parts on each package share l2.  */
676 		top = smp_topo_2level(CG_SHARE_NONE, 2, CG_SHARE_L2, 2, 0);
677 		break;
678 	case 6:
679 		/* Single-core 2xHTT */
680 		top = smp_topo_1level(CG_SHARE_L1, 2, CG_FLAG_HTT);
681 		break;
682 	case 7:
683 		/* quad core with a shared l3, 8 threads sharing L2.  */
684 		top = smp_topo_2level(CG_SHARE_L3, 4, CG_SHARE_L2, 8,
685 		    CG_FLAG_SMT);
686 		break;
687 	default:
688 		/* Default, ask the system what it wants. */
689 		top = cpu_topo();
690 		break;
691 	}
692 	/*
693 	 * Verify the returned topology.
694 	 */
695 	if (top->cg_count != mp_ncpus)
696 		panic("Built bad topology at %p.  CPU count %d != %d",
697 		    top, top->cg_count, mp_ncpus);
698 	if (CPU_CMP(&top->cg_mask, &all_cpus))
699 		panic("Built bad topology at %p.  CPU mask (%s) != (%s)",
700 		    top, cpusetobj_strprint(cpusetbuf, &top->cg_mask),
701 		    cpusetobj_strprint(cpusetbuf2, &all_cpus));
702 
703 	/*
704 	 * Collapse nonsense levels that may be created out of convenience by
705 	 * the MD layers.  They cause extra work in the search functions.
706 	 */
707 	while (top->cg_children == 1) {
708 		top = &top->cg_child[0];
709 		top->cg_parent = NULL;
710 	}
711 	smp_topo_fill(top);
712 	return (top);
713 }
714 
715 struct cpu_group *
716 smp_topo_alloc(u_int count)
717 {
718 	static struct cpu_group *group = NULL;
719 	static u_int index;
720 	u_int curr;
721 
722 	if (group == NULL) {
723 		group = mallocarray((mp_maxid + 1) * MAX_CACHE_LEVELS + 1,
724 		    sizeof(*group), M_DEVBUF, M_WAITOK | M_ZERO);
725 	}
726 	curr = index;
727 	index += count;
728 	return (&group[curr]);
729 }
730 
731 struct cpu_group *
732 smp_topo_none(void)
733 {
734 	struct cpu_group *top;
735 
736 	top = smp_topo_alloc(1);
737 	top->cg_parent = NULL;
738 	top->cg_child = NULL;
739 	top->cg_mask = all_cpus;
740 	top->cg_count = mp_ncpus;
741 	top->cg_children = 0;
742 	top->cg_level = CG_SHARE_NONE;
743 	top->cg_flags = 0;
744 
745 	return (top);
746 }
747 
748 static int
749 smp_topo_addleaf(struct cpu_group *parent, struct cpu_group *child, int share,
750     int count, int flags, int start)
751 {
752 	char cpusetbuf[CPUSETBUFSIZ], cpusetbuf2[CPUSETBUFSIZ];
753 	cpuset_t mask;
754 	int i;
755 
756 	CPU_ZERO(&mask);
757 	for (i = 0; i < count; i++, start++)
758 		CPU_SET(start, &mask);
759 	child->cg_parent = parent;
760 	child->cg_child = NULL;
761 	child->cg_children = 0;
762 	child->cg_level = share;
763 	child->cg_count = count;
764 	child->cg_flags = flags;
765 	child->cg_mask = mask;
766 	parent->cg_children++;
767 	for (; parent != NULL; parent = parent->cg_parent) {
768 		if (CPU_OVERLAP(&parent->cg_mask, &child->cg_mask))
769 			panic("Duplicate children in %p.  mask (%s) child (%s)",
770 			    parent,
771 			    cpusetobj_strprint(cpusetbuf, &parent->cg_mask),
772 			    cpusetobj_strprint(cpusetbuf2, &child->cg_mask));
773 		CPU_OR(&parent->cg_mask, &parent->cg_mask, &child->cg_mask);
774 		parent->cg_count += child->cg_count;
775 	}
776 
777 	return (start);
778 }
779 
780 struct cpu_group *
781 smp_topo_1level(int share, int count, int flags)
782 {
783 	struct cpu_group *child;
784 	struct cpu_group *top;
785 	int packages;
786 	int cpu;
787 	int i;
788 
789 	cpu = 0;
790 	packages = mp_ncpus / count;
791 	top = smp_topo_alloc(1 + packages);
792 	top->cg_child = child = top + 1;
793 	top->cg_level = CG_SHARE_NONE;
794 	for (i = 0; i < packages; i++, child++)
795 		cpu = smp_topo_addleaf(top, child, share, count, flags, cpu);
796 	return (top);
797 }
798 
799 struct cpu_group *
800 smp_topo_2level(int l2share, int l2count, int l1share, int l1count,
801     int l1flags)
802 {
803 	struct cpu_group *top;
804 	struct cpu_group *l1g;
805 	struct cpu_group *l2g;
806 	int cpu;
807 	int i;
808 	int j;
809 
810 	cpu = 0;
811 	top = smp_topo_alloc(1 + mp_ncpus / (l2count * l1count) +
812 	    mp_ncpus / l1count);
813 	l2g = top + 1;
814 	top->cg_child = l2g;
815 	top->cg_level = CG_SHARE_NONE;
816 	top->cg_children = mp_ncpus / (l2count * l1count);
817 	l1g = l2g + top->cg_children;
818 	for (i = 0; i < top->cg_children; i++, l2g++) {
819 		l2g->cg_parent = top;
820 		l2g->cg_child = l1g;
821 		l2g->cg_level = l2share;
822 		for (j = 0; j < l2count; j++, l1g++)
823 			cpu = smp_topo_addleaf(l2g, l1g, l1share, l1count,
824 			    l1flags, cpu);
825 	}
826 	return (top);
827 }
828 
829 struct cpu_group *
830 smp_topo_find(struct cpu_group *top, int cpu)
831 {
832 	struct cpu_group *cg;
833 	cpuset_t mask;
834 	int children;
835 	int i;
836 
837 	CPU_SETOF(cpu, &mask);
838 	cg = top;
839 	for (;;) {
840 		if (!CPU_OVERLAP(&cg->cg_mask, &mask))
841 			return (NULL);
842 		if (cg->cg_children == 0)
843 			return (cg);
844 		children = cg->cg_children;
845 		for (i = 0, cg = cg->cg_child; i < children; cg++, i++)
846 			if (CPU_OVERLAP(&cg->cg_mask, &mask))
847 				break;
848 	}
849 	return (NULL);
850 }
851 #else /* !SMP */
852 
853 void
854 smp_rendezvous_cpus(cpuset_t map,
855 	void (*setup_func)(void *),
856 	void (*action_func)(void *),
857 	void (*teardown_func)(void *),
858 	void *arg)
859 {
860 	/*
861 	 * In the !SMP case we just need to ensure the same initial conditions
862 	 * as the SMP case.
863 	 */
864 	spinlock_enter();
865 	if (setup_func != NULL)
866 		setup_func(arg);
867 	if (action_func != NULL)
868 		action_func(arg);
869 	if (teardown_func != NULL)
870 		teardown_func(arg);
871 	spinlock_exit();
872 }
873 
874 void
875 smp_rendezvous(void (*setup_func)(void *),
876 	       void (*action_func)(void *),
877 	       void (*teardown_func)(void *),
878 	       void *arg)
879 {
880 
881 	smp_rendezvous_cpus(all_cpus, setup_func, action_func, teardown_func,
882 	    arg);
883 }
884 
885 /*
886  * Provide dummy SMP support for UP kernels.  Modules that need to use SMP
887  * APIs will still work using this dummy support.
888  */
889 static void
890 mp_setvariables_for_up(void *dummy)
891 {
892 	mp_ncpus = 1;
893 	mp_ncores = 1;
894 	mp_maxid = PCPU_GET(cpuid);
895 	CPU_SETOF(mp_maxid, &all_cpus);
896 	KASSERT(PCPU_GET(cpuid) == 0, ("UP must have a CPU ID of zero"));
897 }
898 SYSINIT(cpu_mp_setvariables, SI_SUB_TUNABLES, SI_ORDER_FIRST,
899     mp_setvariables_for_up, NULL);
900 #endif /* SMP */
901 
902 void
903 smp_no_rendezvous_barrier(void *dummy)
904 {
905 #ifdef SMP
906 	KASSERT((!smp_started),("smp_no_rendezvous called and smp is started"));
907 #endif
908 }
909 
910 void
911 smp_rendezvous_cpus_retry(cpuset_t map,
912 	void (* setup_func)(void *),
913 	void (* action_func)(void *),
914 	void (* teardown_func)(void *),
915 	void (* wait_func)(void *, int),
916 	struct smp_rendezvous_cpus_retry_arg *arg)
917 {
918 	int cpu;
919 
920 	CPU_COPY(&map, &arg->cpus);
921 
922 	/*
923 	 * Only one CPU to execute on.
924 	 */
925 	if (!smp_started) {
926 		spinlock_enter();
927 		if (setup_func != NULL)
928 			setup_func(arg);
929 		if (action_func != NULL)
930 			action_func(arg);
931 		if (teardown_func != NULL)
932 			teardown_func(arg);
933 		spinlock_exit();
934 		return;
935 	}
936 
937 	/*
938 	 * Execute an action on all specified CPUs while retrying until they
939 	 * all acknowledge completion.
940 	 */
941 	for (;;) {
942 		smp_rendezvous_cpus(
943 		    arg->cpus,
944 		    setup_func,
945 		    action_func,
946 		    teardown_func,
947 		    arg);
948 
949 		if (CPU_EMPTY(&arg->cpus))
950 			break;
951 
952 		CPU_FOREACH(cpu) {
953 			if (!CPU_ISSET(cpu, &arg->cpus))
954 				continue;
955 			wait_func(arg, cpu);
956 		}
957 	}
958 }
959 
960 void
961 smp_rendezvous_cpus_done(struct smp_rendezvous_cpus_retry_arg *arg)
962 {
963 
964 	CPU_CLR_ATOMIC(curcpu, &arg->cpus);
965 }
966 
967 /*
968  * If (prio & PDROP) == 0:
969  * Wait for specified idle threads to switch once.  This ensures that even
970  * preempted threads have cycled through the switch function once,
971  * exiting their codepaths.  This allows us to change global pointers
972  * with no other synchronization.
973  * If (prio & PDROP) != 0:
974  * Force the specified CPUs to switch context at least once.
975  */
976 int
977 quiesce_cpus(cpuset_t map, const char *wmesg, int prio)
978 {
979 	struct pcpu *pcpu;
980 	u_int *gen;
981 	int error;
982 	int cpu;
983 
984 	error = 0;
985 	if ((prio & PDROP) == 0) {
986 		gen = mallocarray(sizeof(u_int), mp_maxid + 1, M_TEMP,
987 		    M_WAITOK);
988 		for (cpu = 0; cpu <= mp_maxid; cpu++) {
989 			if (!CPU_ISSET(cpu, &map) || CPU_ABSENT(cpu))
990 				continue;
991 			pcpu = pcpu_find(cpu);
992 			gen[cpu] = pcpu->pc_idlethread->td_generation;
993 		}
994 	}
995 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
996 		if (!CPU_ISSET(cpu, &map) || CPU_ABSENT(cpu))
997 			continue;
998 		pcpu = pcpu_find(cpu);
999 		thread_lock(curthread);
1000 		sched_bind(curthread, cpu);
1001 		thread_unlock(curthread);
1002 		if ((prio & PDROP) != 0)
1003 			continue;
1004 		while (gen[cpu] == pcpu->pc_idlethread->td_generation) {
1005 			error = tsleep(quiesce_cpus, prio & ~PDROP, wmesg, 1);
1006 			if (error != EWOULDBLOCK)
1007 				goto out;
1008 			error = 0;
1009 		}
1010 	}
1011 out:
1012 	thread_lock(curthread);
1013 	sched_unbind(curthread);
1014 	thread_unlock(curthread);
1015 	if ((prio & PDROP) == 0)
1016 		free(gen, M_TEMP);
1017 
1018 	return (error);
1019 }
1020 
1021 int
1022 quiesce_all_cpus(const char *wmesg, int prio)
1023 {
1024 
1025 	return quiesce_cpus(all_cpus, wmesg, prio);
1026 }
1027 
1028 /*
1029  * Observe all CPUs not executing in critical section.
1030  * We are not in one so the check for us is safe. If the found
1031  * thread changes to something else we know the section was
1032  * exited as well.
1033  */
1034 void
1035 quiesce_all_critical(void)
1036 {
1037 	struct thread *td, *newtd;
1038 	struct pcpu *pcpu;
1039 	int cpu;
1040 
1041 	MPASS(curthread->td_critnest == 0);
1042 
1043 	CPU_FOREACH(cpu) {
1044 		pcpu = cpuid_to_pcpu[cpu];
1045 		td = pcpu->pc_curthread;
1046 		for (;;) {
1047 			if (td->td_critnest == 0)
1048 				break;
1049 			cpu_spinwait();
1050 			newtd = (struct thread *)
1051 			    atomic_load_acq_ptr((void *)pcpu->pc_curthread);
1052 			if (td != newtd)
1053 				break;
1054 		}
1055 	}
1056 }
1057 
1058 static void
1059 cpus_fence_seq_cst_issue(void *arg __unused)
1060 {
1061 
1062 	atomic_thread_fence_seq_cst();
1063 }
1064 
1065 /*
1066  * Send an IPI forcing a sequentially consistent fence.
1067  *
1068  * Allows replacement of an explicitly fence with a compiler barrier.
1069  * Trades speed up during normal execution for a significant slowdown when
1070  * the barrier is needed.
1071  */
1072 void
1073 cpus_fence_seq_cst(void)
1074 {
1075 
1076 #ifdef SMP
1077 	smp_rendezvous(
1078 	    smp_no_rendezvous_barrier,
1079 	    cpus_fence_seq_cst_issue,
1080 	    smp_no_rendezvous_barrier,
1081 	    NULL
1082 	);
1083 #else
1084 	cpus_fence_seq_cst_issue(NULL);
1085 #endif
1086 }
1087 
1088 /* Extra care is taken with this sysctl because the data type is volatile */
1089 static int
1090 sysctl_kern_smp_active(SYSCTL_HANDLER_ARGS)
1091 {
1092 	int error, active;
1093 
1094 	active = smp_started;
1095 	error = SYSCTL_OUT(req, &active, sizeof(active));
1096 	return (error);
1097 }
1098 
1099 #ifdef SMP
1100 void
1101 topo_init_node(struct topo_node *node)
1102 {
1103 
1104 	bzero(node, sizeof(*node));
1105 	TAILQ_INIT(&node->children);
1106 }
1107 
1108 void
1109 topo_init_root(struct topo_node *root)
1110 {
1111 
1112 	topo_init_node(root);
1113 	root->type = TOPO_TYPE_SYSTEM;
1114 }
1115 
1116 /*
1117  * Add a child node with the given ID under the given parent.
1118  * Do nothing if there is already a child with that ID.
1119  */
1120 struct topo_node *
1121 topo_add_node_by_hwid(struct topo_node *parent, int hwid,
1122     topo_node_type type, uintptr_t subtype)
1123 {
1124 	struct topo_node *node;
1125 
1126 	TAILQ_FOREACH_REVERSE(node, &parent->children,
1127 	    topo_children, siblings) {
1128 		if (node->hwid == hwid
1129 		    && node->type == type && node->subtype == subtype) {
1130 			return (node);
1131 		}
1132 	}
1133 
1134 	node = malloc(sizeof(*node), M_TOPO, M_WAITOK);
1135 	topo_init_node(node);
1136 	node->parent = parent;
1137 	node->hwid = hwid;
1138 	node->type = type;
1139 	node->subtype = subtype;
1140 	TAILQ_INSERT_TAIL(&parent->children, node, siblings);
1141 	parent->nchildren++;
1142 
1143 	return (node);
1144 }
1145 
1146 /*
1147  * Find a child node with the given ID under the given parent.
1148  */
1149 struct topo_node *
1150 topo_find_node_by_hwid(struct topo_node *parent, int hwid,
1151     topo_node_type type, uintptr_t subtype)
1152 {
1153 
1154 	struct topo_node *node;
1155 
1156 	TAILQ_FOREACH(node, &parent->children, siblings) {
1157 		if (node->hwid == hwid
1158 		    && node->type == type && node->subtype == subtype) {
1159 			return (node);
1160 		}
1161 	}
1162 
1163 	return (NULL);
1164 }
1165 
1166 /*
1167  * Given a node change the order of its parent's child nodes such
1168  * that the node becomes the firt child while preserving the cyclic
1169  * order of the children.  In other words, the given node is promoted
1170  * by rotation.
1171  */
1172 void
1173 topo_promote_child(struct topo_node *child)
1174 {
1175 	struct topo_node *next;
1176 	struct topo_node *node;
1177 	struct topo_node *parent;
1178 
1179 	parent = child->parent;
1180 	next = TAILQ_NEXT(child, siblings);
1181 	TAILQ_REMOVE(&parent->children, child, siblings);
1182 	TAILQ_INSERT_HEAD(&parent->children, child, siblings);
1183 
1184 	while (next != NULL) {
1185 		node = next;
1186 		next = TAILQ_NEXT(node, siblings);
1187 		TAILQ_REMOVE(&parent->children, node, siblings);
1188 		TAILQ_INSERT_AFTER(&parent->children, child, node, siblings);
1189 		child = node;
1190 	}
1191 }
1192 
1193 /*
1194  * Iterate to the next node in the depth-first search (traversal) of
1195  * the topology tree.
1196  */
1197 struct topo_node *
1198 topo_next_node(struct topo_node *top, struct topo_node *node)
1199 {
1200 	struct topo_node *next;
1201 
1202 	if ((next = TAILQ_FIRST(&node->children)) != NULL)
1203 		return (next);
1204 
1205 	if ((next = TAILQ_NEXT(node, siblings)) != NULL)
1206 		return (next);
1207 
1208 	while (node != top && (node = node->parent) != top)
1209 		if ((next = TAILQ_NEXT(node, siblings)) != NULL)
1210 			return (next);
1211 
1212 	return (NULL);
1213 }
1214 
1215 /*
1216  * Iterate to the next node in the depth-first search of the topology tree,
1217  * but without descending below the current node.
1218  */
1219 struct topo_node *
1220 topo_next_nonchild_node(struct topo_node *top, struct topo_node *node)
1221 {
1222 	struct topo_node *next;
1223 
1224 	if ((next = TAILQ_NEXT(node, siblings)) != NULL)
1225 		return (next);
1226 
1227 	while (node != top && (node = node->parent) != top)
1228 		if ((next = TAILQ_NEXT(node, siblings)) != NULL)
1229 			return (next);
1230 
1231 	return (NULL);
1232 }
1233 
1234 /*
1235  * Assign the given ID to the given topology node that represents a logical
1236  * processor.
1237  */
1238 void
1239 topo_set_pu_id(struct topo_node *node, cpuid_t id)
1240 {
1241 
1242 	KASSERT(node->type == TOPO_TYPE_PU,
1243 	    ("topo_set_pu_id: wrong node type: %u", node->type));
1244 	KASSERT(CPU_EMPTY(&node->cpuset) && node->cpu_count == 0,
1245 	    ("topo_set_pu_id: cpuset already not empty"));
1246 	node->id = id;
1247 	CPU_SET(id, &node->cpuset);
1248 	node->cpu_count = 1;
1249 	node->subtype = 1;
1250 
1251 	while ((node = node->parent) != NULL) {
1252 		KASSERT(!CPU_ISSET(id, &node->cpuset),
1253 		    ("logical ID %u is already set in node %p", id, node));
1254 		CPU_SET(id, &node->cpuset);
1255 		node->cpu_count++;
1256 	}
1257 }
1258 
1259 static struct topology_spec {
1260 	topo_node_type	type;
1261 	bool		match_subtype;
1262 	uintptr_t	subtype;
1263 } topology_level_table[TOPO_LEVEL_COUNT] = {
1264 	[TOPO_LEVEL_PKG] = { .type = TOPO_TYPE_PKG, },
1265 	[TOPO_LEVEL_GROUP] = { .type = TOPO_TYPE_GROUP, },
1266 	[TOPO_LEVEL_CACHEGROUP] = {
1267 		.type = TOPO_TYPE_CACHE,
1268 		.match_subtype = true,
1269 		.subtype = CG_SHARE_L3,
1270 	},
1271 	[TOPO_LEVEL_CORE] = { .type = TOPO_TYPE_CORE, },
1272 	[TOPO_LEVEL_THREAD] = { .type = TOPO_TYPE_PU, },
1273 };
1274 
1275 static bool
1276 topo_analyze_table(struct topo_node *root, int all, enum topo_level level,
1277     struct topo_analysis *results)
1278 {
1279 	struct topology_spec *spec;
1280 	struct topo_node *node;
1281 	int count;
1282 
1283 	if (level >= TOPO_LEVEL_COUNT)
1284 		return (true);
1285 
1286 	spec = &topology_level_table[level];
1287 	count = 0;
1288 	node = topo_next_node(root, root);
1289 
1290 	while (node != NULL) {
1291 		if (node->type != spec->type ||
1292 		    (spec->match_subtype && node->subtype != spec->subtype)) {
1293 			node = topo_next_node(root, node);
1294 			continue;
1295 		}
1296 		if (!all && CPU_EMPTY(&node->cpuset)) {
1297 			node = topo_next_nonchild_node(root, node);
1298 			continue;
1299 		}
1300 
1301 		count++;
1302 
1303 		if (!topo_analyze_table(node, all, level + 1, results))
1304 			return (false);
1305 
1306 		node = topo_next_nonchild_node(root, node);
1307 	}
1308 
1309 	/* No explicit subgroups is essentially one subgroup. */
1310 	if (count == 0) {
1311 		count = 1;
1312 
1313 		if (!topo_analyze_table(root, all, level + 1, results))
1314 			return (false);
1315 	}
1316 
1317 	if (results->entities[level] == -1)
1318 		results->entities[level] = count;
1319 	else if (results->entities[level] != count)
1320 		return (false);
1321 
1322 	return (true);
1323 }
1324 
1325 /*
1326  * Check if the topology is uniform, that is, each package has the same number
1327  * of cores in it and each core has the same number of threads (logical
1328  * processors) in it.  If so, calculate the number of packages, the number of
1329  * groups per package, the number of cachegroups per group, and the number of
1330  * logical processors per cachegroup.  'all' parameter tells whether to include
1331  * administratively disabled logical processors into the analysis.
1332  */
1333 int
1334 topo_analyze(struct topo_node *topo_root, int all,
1335     struct topo_analysis *results)
1336 {
1337 
1338 	results->entities[TOPO_LEVEL_PKG] = -1;
1339 	results->entities[TOPO_LEVEL_CORE] = -1;
1340 	results->entities[TOPO_LEVEL_THREAD] = -1;
1341 	results->entities[TOPO_LEVEL_GROUP] = -1;
1342 	results->entities[TOPO_LEVEL_CACHEGROUP] = -1;
1343 
1344 	if (!topo_analyze_table(topo_root, all, TOPO_LEVEL_PKG, results))
1345 		return (0);
1346 
1347 	KASSERT(results->entities[TOPO_LEVEL_PKG] > 0,
1348 		("bug in topology or analysis"));
1349 
1350 	return (1);
1351 }
1352 
1353 #endif /* SMP */
1354