xref: /freebsd/sys/kern/subr_smp.c (revision f4b37ed0f8b307b1f3f0f630ca725d68f1dff30d)
1 /*-
2  * Copyright (c) 2001, John Baldwin <jhb@FreeBSD.org>.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * This module holds the global variables and machine independent functions
29  * used for the kernel SMP support.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/ktr.h>
39 #include <sys/proc.h>
40 #include <sys/bus.h>
41 #include <sys/lock.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/smp.h>
50 
51 #include "opt_sched.h"
52 
53 #ifdef SMP
54 volatile cpuset_t stopped_cpus;
55 volatile cpuset_t started_cpus;
56 volatile cpuset_t suspended_cpus;
57 cpuset_t hlt_cpus_mask;
58 cpuset_t logical_cpus_mask;
59 
60 void (*cpustop_restartfunc)(void);
61 #endif
62 
63 static int sysctl_kern_smp_active(SYSCTL_HANDLER_ARGS);
64 
65 /* This is used in modules that need to work in both SMP and UP. */
66 cpuset_t all_cpus;
67 
68 int mp_ncpus;
69 /* export this for libkvm consumers. */
70 int mp_maxcpus = MAXCPU;
71 
72 volatile int smp_started;
73 u_int mp_maxid;
74 
75 static SYSCTL_NODE(_kern, OID_AUTO, smp, CTLFLAG_RD|CTLFLAG_CAPRD, NULL,
76     "Kernel SMP");
77 
78 SYSCTL_INT(_kern_smp, OID_AUTO, maxid, CTLFLAG_RD|CTLFLAG_CAPRD, &mp_maxid, 0,
79     "Max CPU ID.");
80 
81 SYSCTL_INT(_kern_smp, OID_AUTO, maxcpus, CTLFLAG_RD|CTLFLAG_CAPRD, &mp_maxcpus,
82     0, "Max number of CPUs that the system was compiled for.");
83 
84 SYSCTL_PROC(_kern_smp, OID_AUTO, active, CTLFLAG_RD | CTLTYPE_INT, NULL, 0,
85     sysctl_kern_smp_active, "I", "Indicates system is running in SMP mode");
86 
87 int smp_disabled = 0;	/* has smp been disabled? */
88 SYSCTL_INT(_kern_smp, OID_AUTO, disabled, CTLFLAG_RDTUN|CTLFLAG_CAPRD,
89     &smp_disabled, 0, "SMP has been disabled from the loader");
90 
91 int smp_cpus = 1;	/* how many cpu's running */
92 SYSCTL_INT(_kern_smp, OID_AUTO, cpus, CTLFLAG_RD|CTLFLAG_CAPRD, &smp_cpus, 0,
93     "Number of CPUs online");
94 
95 int smp_topology = 0;	/* Which topology we're using. */
96 SYSCTL_INT(_kern_smp, OID_AUTO, topology, CTLFLAG_RDTUN, &smp_topology, 0,
97     "Topology override setting; 0 is default provided by hardware.");
98 
99 #ifdef SMP
100 /* Enable forwarding of a signal to a process running on a different CPU */
101 static int forward_signal_enabled = 1;
102 SYSCTL_INT(_kern_smp, OID_AUTO, forward_signal_enabled, CTLFLAG_RW,
103 	   &forward_signal_enabled, 0,
104 	   "Forwarding of a signal to a process on a different CPU");
105 
106 /* Variables needed for SMP rendezvous. */
107 static volatile int smp_rv_ncpus;
108 static void (*volatile smp_rv_setup_func)(void *arg);
109 static void (*volatile smp_rv_action_func)(void *arg);
110 static void (*volatile smp_rv_teardown_func)(void *arg);
111 static void *volatile smp_rv_func_arg;
112 static volatile int smp_rv_waiters[4];
113 
114 /*
115  * Shared mutex to restrict busywaits between smp_rendezvous() and
116  * smp(_targeted)_tlb_shootdown().  A deadlock occurs if both of these
117  * functions trigger at once and cause multiple CPUs to busywait with
118  * interrupts disabled.
119  */
120 struct mtx smp_ipi_mtx;
121 
122 /*
123  * Let the MD SMP code initialize mp_maxid very early if it can.
124  */
125 static void
126 mp_setmaxid(void *dummy)
127 {
128 	cpu_mp_setmaxid();
129 }
130 SYSINIT(cpu_mp_setmaxid, SI_SUB_TUNABLES, SI_ORDER_FIRST, mp_setmaxid, NULL);
131 
132 /*
133  * Call the MD SMP initialization code.
134  */
135 static void
136 mp_start(void *dummy)
137 {
138 
139 	mtx_init(&smp_ipi_mtx, "smp rendezvous", NULL, MTX_SPIN);
140 
141 	/* Probe for MP hardware. */
142 	if (smp_disabled != 0 || cpu_mp_probe() == 0) {
143 		mp_ncpus = 1;
144 		CPU_SETOF(PCPU_GET(cpuid), &all_cpus);
145 		return;
146 	}
147 
148 	cpu_mp_start();
149 	printf("FreeBSD/SMP: Multiprocessor System Detected: %d CPUs\n",
150 	    mp_ncpus);
151 	cpu_mp_announce();
152 }
153 SYSINIT(cpu_mp, SI_SUB_CPU, SI_ORDER_THIRD, mp_start, NULL);
154 
155 void
156 forward_signal(struct thread *td)
157 {
158 	int id;
159 
160 	/*
161 	 * signotify() has already set TDF_ASTPENDING and TDF_NEEDSIGCHECK on
162 	 * this thread, so all we need to do is poke it if it is currently
163 	 * executing so that it executes ast().
164 	 */
165 	THREAD_LOCK_ASSERT(td, MA_OWNED);
166 	KASSERT(TD_IS_RUNNING(td),
167 	    ("forward_signal: thread is not TDS_RUNNING"));
168 
169 	CTR1(KTR_SMP, "forward_signal(%p)", td->td_proc);
170 
171 	if (!smp_started || cold || panicstr)
172 		return;
173 	if (!forward_signal_enabled)
174 		return;
175 
176 	/* No need to IPI ourself. */
177 	if (td == curthread)
178 		return;
179 
180 	id = td->td_oncpu;
181 	if (id == NOCPU)
182 		return;
183 	ipi_cpu(id, IPI_AST);
184 }
185 
186 /*
187  * When called the executing CPU will send an IPI to all other CPUs
188  *  requesting that they halt execution.
189  *
190  * Usually (but not necessarily) called with 'other_cpus' as its arg.
191  *
192  *  - Signals all CPUs in map to stop.
193  *  - Waits for each to stop.
194  *
195  * Returns:
196  *  -1: error
197  *   0: NA
198  *   1: ok
199  *
200  */
201 static int
202 generic_stop_cpus(cpuset_t map, u_int type)
203 {
204 #ifdef KTR
205 	char cpusetbuf[CPUSETBUFSIZ];
206 #endif
207 	static volatile u_int stopping_cpu = NOCPU;
208 	int i;
209 	volatile cpuset_t *cpus;
210 
211 	KASSERT(
212 #if defined(__amd64__) || defined(__i386__)
213 	    type == IPI_STOP || type == IPI_STOP_HARD || type == IPI_SUSPEND,
214 #else
215 	    type == IPI_STOP || type == IPI_STOP_HARD,
216 #endif
217 	    ("%s: invalid stop type", __func__));
218 
219 	if (!smp_started)
220 		return (0);
221 
222 	CTR2(KTR_SMP, "stop_cpus(%s) with %u type",
223 	    cpusetobj_strprint(cpusetbuf, &map), type);
224 
225 #if defined(__amd64__) || defined(__i386__)
226 	/*
227 	 * When suspending, ensure there are are no IPIs in progress.
228 	 * IPIs that have been issued, but not yet delivered (e.g.
229 	 * not pending on a vCPU when running under virtualization)
230 	 * will be lost, violating FreeBSD's assumption of reliable
231 	 * IPI delivery.
232 	 */
233 	if (type == IPI_SUSPEND)
234 		mtx_lock_spin(&smp_ipi_mtx);
235 #endif
236 
237 	if (stopping_cpu != PCPU_GET(cpuid))
238 		while (atomic_cmpset_int(&stopping_cpu, NOCPU,
239 		    PCPU_GET(cpuid)) == 0)
240 			while (stopping_cpu != NOCPU)
241 				cpu_spinwait(); /* spin */
242 
243 	/* send the stop IPI to all CPUs in map */
244 	ipi_selected(map, type);
245 
246 #if defined(__amd64__) || defined(__i386__)
247 	if (type == IPI_SUSPEND)
248 		cpus = &suspended_cpus;
249 	else
250 #endif
251 		cpus = &stopped_cpus;
252 
253 	i = 0;
254 	while (!CPU_SUBSET(cpus, &map)) {
255 		/* spin */
256 		cpu_spinwait();
257 		i++;
258 		if (i == 100000000) {
259 			printf("timeout stopping cpus\n");
260 			break;
261 		}
262 	}
263 
264 #if defined(__amd64__) || defined(__i386__)
265 	if (type == IPI_SUSPEND)
266 		mtx_unlock_spin(&smp_ipi_mtx);
267 #endif
268 
269 	stopping_cpu = NOCPU;
270 	return (1);
271 }
272 
273 int
274 stop_cpus(cpuset_t map)
275 {
276 
277 	return (generic_stop_cpus(map, IPI_STOP));
278 }
279 
280 int
281 stop_cpus_hard(cpuset_t map)
282 {
283 
284 	return (generic_stop_cpus(map, IPI_STOP_HARD));
285 }
286 
287 #if defined(__amd64__) || defined(__i386__)
288 int
289 suspend_cpus(cpuset_t map)
290 {
291 
292 	return (generic_stop_cpus(map, IPI_SUSPEND));
293 }
294 #endif
295 
296 /*
297  * Called by a CPU to restart stopped CPUs.
298  *
299  * Usually (but not necessarily) called with 'stopped_cpus' as its arg.
300  *
301  *  - Signals all CPUs in map to restart.
302  *  - Waits for each to restart.
303  *
304  * Returns:
305  *  -1: error
306  *   0: NA
307  *   1: ok
308  */
309 static int
310 generic_restart_cpus(cpuset_t map, u_int type)
311 {
312 #ifdef KTR
313 	char cpusetbuf[CPUSETBUFSIZ];
314 #endif
315 	volatile cpuset_t *cpus;
316 
317 	KASSERT(
318 #if defined(__amd64__) || defined(__i386__)
319 	    type == IPI_STOP || type == IPI_STOP_HARD || type == IPI_SUSPEND,
320 #else
321 	    type == IPI_STOP || type == IPI_STOP_HARD,
322 #endif
323 	    ("%s: invalid stop type", __func__));
324 
325 	if (!smp_started)
326 		return 0;
327 
328 	CTR1(KTR_SMP, "restart_cpus(%s)", cpusetobj_strprint(cpusetbuf, &map));
329 
330 #if defined(__amd64__) || defined(__i386__)
331 	if (type == IPI_SUSPEND)
332 		cpus = &suspended_cpus;
333 	else
334 #endif
335 		cpus = &stopped_cpus;
336 
337 	/* signal other cpus to restart */
338 	CPU_COPY_STORE_REL(&map, &started_cpus);
339 
340 	/* wait for each to clear its bit */
341 	while (CPU_OVERLAP(cpus, &map))
342 		cpu_spinwait();
343 
344 	return 1;
345 }
346 
347 int
348 restart_cpus(cpuset_t map)
349 {
350 
351 	return (generic_restart_cpus(map, IPI_STOP));
352 }
353 
354 #if defined(__amd64__) || defined(__i386__)
355 int
356 resume_cpus(cpuset_t map)
357 {
358 
359 	return (generic_restart_cpus(map, IPI_SUSPEND));
360 }
361 #endif
362 
363 /*
364  * All-CPU rendezvous.  CPUs are signalled, all execute the setup function
365  * (if specified), rendezvous, execute the action function (if specified),
366  * rendezvous again, execute the teardown function (if specified), and then
367  * resume.
368  *
369  * Note that the supplied external functions _must_ be reentrant and aware
370  * that they are running in parallel and in an unknown lock context.
371  */
372 void
373 smp_rendezvous_action(void)
374 {
375 	struct thread *td;
376 	void *local_func_arg;
377 	void (*local_setup_func)(void*);
378 	void (*local_action_func)(void*);
379 	void (*local_teardown_func)(void*);
380 #ifdef INVARIANTS
381 	int owepreempt;
382 #endif
383 
384 	/* Ensure we have up-to-date values. */
385 	atomic_add_acq_int(&smp_rv_waiters[0], 1);
386 	while (smp_rv_waiters[0] < smp_rv_ncpus)
387 		cpu_spinwait();
388 
389 	/* Fetch rendezvous parameters after acquire barrier. */
390 	local_func_arg = smp_rv_func_arg;
391 	local_setup_func = smp_rv_setup_func;
392 	local_action_func = smp_rv_action_func;
393 	local_teardown_func = smp_rv_teardown_func;
394 
395 	/*
396 	 * Use a nested critical section to prevent any preemptions
397 	 * from occurring during a rendezvous action routine.
398 	 * Specifically, if a rendezvous handler is invoked via an IPI
399 	 * and the interrupted thread was in the critical_exit()
400 	 * function after setting td_critnest to 0 but before
401 	 * performing a deferred preemption, this routine can be
402 	 * invoked with td_critnest set to 0 and td_owepreempt true.
403 	 * In that case, a critical_exit() during the rendezvous
404 	 * action would trigger a preemption which is not permitted in
405 	 * a rendezvous action.  To fix this, wrap all of the
406 	 * rendezvous action handlers in a critical section.  We
407 	 * cannot use a regular critical section however as having
408 	 * critical_exit() preempt from this routine would also be
409 	 * problematic (the preemption must not occur before the IPI
410 	 * has been acknowledged via an EOI).  Instead, we
411 	 * intentionally ignore td_owepreempt when leaving the
412 	 * critical section.  This should be harmless because we do
413 	 * not permit rendezvous action routines to schedule threads,
414 	 * and thus td_owepreempt should never transition from 0 to 1
415 	 * during this routine.
416 	 */
417 	td = curthread;
418 	td->td_critnest++;
419 #ifdef INVARIANTS
420 	owepreempt = td->td_owepreempt;
421 #endif
422 
423 	/*
424 	 * If requested, run a setup function before the main action
425 	 * function.  Ensure all CPUs have completed the setup
426 	 * function before moving on to the action function.
427 	 */
428 	if (local_setup_func != smp_no_rendevous_barrier) {
429 		if (smp_rv_setup_func != NULL)
430 			smp_rv_setup_func(smp_rv_func_arg);
431 		atomic_add_int(&smp_rv_waiters[1], 1);
432 		while (smp_rv_waiters[1] < smp_rv_ncpus)
433                 	cpu_spinwait();
434 	}
435 
436 	if (local_action_func != NULL)
437 		local_action_func(local_func_arg);
438 
439 	if (local_teardown_func != smp_no_rendevous_barrier) {
440 		/*
441 		 * Signal that the main action has been completed.  If a
442 		 * full exit rendezvous is requested, then all CPUs will
443 		 * wait here until all CPUs have finished the main action.
444 		 */
445 		atomic_add_int(&smp_rv_waiters[2], 1);
446 		while (smp_rv_waiters[2] < smp_rv_ncpus)
447 			cpu_spinwait();
448 
449 		if (local_teardown_func != NULL)
450 			local_teardown_func(local_func_arg);
451 	}
452 
453 	/*
454 	 * Signal that the rendezvous is fully completed by this CPU.
455 	 * This means that no member of smp_rv_* pseudo-structure will be
456 	 * accessed by this target CPU after this point; in particular,
457 	 * memory pointed by smp_rv_func_arg.
458 	 *
459 	 * The release semantic ensures that all accesses performed by
460 	 * the current CPU are visible when smp_rendezvous_cpus()
461 	 * returns, by synchronizing with the
462 	 * atomic_load_acq_int(&smp_rv_waiters[3]).
463 	 */
464 	atomic_add_rel_int(&smp_rv_waiters[3], 1);
465 
466 	td->td_critnest--;
467 	KASSERT(owepreempt == td->td_owepreempt,
468 	    ("rendezvous action changed td_owepreempt"));
469 }
470 
471 void
472 smp_rendezvous_cpus(cpuset_t map,
473 	void (* setup_func)(void *),
474 	void (* action_func)(void *),
475 	void (* teardown_func)(void *),
476 	void *arg)
477 {
478 	int curcpumap, i, ncpus = 0;
479 
480 	/* Look comments in the !SMP case. */
481 	if (!smp_started) {
482 		spinlock_enter();
483 		if (setup_func != NULL)
484 			setup_func(arg);
485 		if (action_func != NULL)
486 			action_func(arg);
487 		if (teardown_func != NULL)
488 			teardown_func(arg);
489 		spinlock_exit();
490 		return;
491 	}
492 
493 	CPU_FOREACH(i) {
494 		if (CPU_ISSET(i, &map))
495 			ncpus++;
496 	}
497 	if (ncpus == 0)
498 		panic("ncpus is 0 with non-zero map");
499 
500 	mtx_lock_spin(&smp_ipi_mtx);
501 
502 	/* Pass rendezvous parameters via global variables. */
503 	smp_rv_ncpus = ncpus;
504 	smp_rv_setup_func = setup_func;
505 	smp_rv_action_func = action_func;
506 	smp_rv_teardown_func = teardown_func;
507 	smp_rv_func_arg = arg;
508 	smp_rv_waiters[1] = 0;
509 	smp_rv_waiters[2] = 0;
510 	smp_rv_waiters[3] = 0;
511 	atomic_store_rel_int(&smp_rv_waiters[0], 0);
512 
513 	/*
514 	 * Signal other processors, which will enter the IPI with
515 	 * interrupts off.
516 	 */
517 	curcpumap = CPU_ISSET(curcpu, &map);
518 	CPU_CLR(curcpu, &map);
519 	ipi_selected(map, IPI_RENDEZVOUS);
520 
521 	/* Check if the current CPU is in the map */
522 	if (curcpumap != 0)
523 		smp_rendezvous_action();
524 
525 	/*
526 	 * Ensure that the master CPU waits for all the other
527 	 * CPUs to finish the rendezvous, so that smp_rv_*
528 	 * pseudo-structure and the arg are guaranteed to not
529 	 * be in use.
530 	 *
531 	 * Load acquire synchronizes with the release add in
532 	 * smp_rendezvous_action(), which ensures that our caller sees
533 	 * all memory actions done by the called functions on other
534 	 * CPUs.
535 	 */
536 	while (atomic_load_acq_int(&smp_rv_waiters[3]) < ncpus)
537 		cpu_spinwait();
538 
539 	mtx_unlock_spin(&smp_ipi_mtx);
540 }
541 
542 void
543 smp_rendezvous(void (* setup_func)(void *),
544 	       void (* action_func)(void *),
545 	       void (* teardown_func)(void *),
546 	       void *arg)
547 {
548 	smp_rendezvous_cpus(all_cpus, setup_func, action_func, teardown_func, arg);
549 }
550 
551 static struct cpu_group group[MAXCPU];
552 
553 struct cpu_group *
554 smp_topo(void)
555 {
556 	char cpusetbuf[CPUSETBUFSIZ], cpusetbuf2[CPUSETBUFSIZ];
557 	struct cpu_group *top;
558 
559 	/*
560 	 * Check for a fake topology request for debugging purposes.
561 	 */
562 	switch (smp_topology) {
563 	case 1:
564 		/* Dual core with no sharing.  */
565 		top = smp_topo_1level(CG_SHARE_NONE, 2, 0);
566 		break;
567 	case 2:
568 		/* No topology, all cpus are equal. */
569 		top = smp_topo_none();
570 		break;
571 	case 3:
572 		/* Dual core with shared L2.  */
573 		top = smp_topo_1level(CG_SHARE_L2, 2, 0);
574 		break;
575 	case 4:
576 		/* quad core, shared l3 among each package, private l2.  */
577 		top = smp_topo_1level(CG_SHARE_L3, 4, 0);
578 		break;
579 	case 5:
580 		/* quad core,  2 dualcore parts on each package share l2.  */
581 		top = smp_topo_2level(CG_SHARE_NONE, 2, CG_SHARE_L2, 2, 0);
582 		break;
583 	case 6:
584 		/* Single-core 2xHTT */
585 		top = smp_topo_1level(CG_SHARE_L1, 2, CG_FLAG_HTT);
586 		break;
587 	case 7:
588 		/* quad core with a shared l3, 8 threads sharing L2.  */
589 		top = smp_topo_2level(CG_SHARE_L3, 4, CG_SHARE_L2, 8,
590 		    CG_FLAG_SMT);
591 		break;
592 	default:
593 		/* Default, ask the system what it wants. */
594 		top = cpu_topo();
595 		break;
596 	}
597 	/*
598 	 * Verify the returned topology.
599 	 */
600 	if (top->cg_count != mp_ncpus)
601 		panic("Built bad topology at %p.  CPU count %d != %d",
602 		    top, top->cg_count, mp_ncpus);
603 	if (CPU_CMP(&top->cg_mask, &all_cpus))
604 		panic("Built bad topology at %p.  CPU mask (%s) != (%s)",
605 		    top, cpusetobj_strprint(cpusetbuf, &top->cg_mask),
606 		    cpusetobj_strprint(cpusetbuf2, &all_cpus));
607 	return (top);
608 }
609 
610 struct cpu_group *
611 smp_topo_none(void)
612 {
613 	struct cpu_group *top;
614 
615 	top = &group[0];
616 	top->cg_parent = NULL;
617 	top->cg_child = NULL;
618 	top->cg_mask = all_cpus;
619 	top->cg_count = mp_ncpus;
620 	top->cg_children = 0;
621 	top->cg_level = CG_SHARE_NONE;
622 	top->cg_flags = 0;
623 
624 	return (top);
625 }
626 
627 static int
628 smp_topo_addleaf(struct cpu_group *parent, struct cpu_group *child, int share,
629     int count, int flags, int start)
630 {
631 	char cpusetbuf[CPUSETBUFSIZ], cpusetbuf2[CPUSETBUFSIZ];
632 	cpuset_t mask;
633 	int i;
634 
635 	CPU_ZERO(&mask);
636 	for (i = 0; i < count; i++, start++)
637 		CPU_SET(start, &mask);
638 	child->cg_parent = parent;
639 	child->cg_child = NULL;
640 	child->cg_children = 0;
641 	child->cg_level = share;
642 	child->cg_count = count;
643 	child->cg_flags = flags;
644 	child->cg_mask = mask;
645 	parent->cg_children++;
646 	for (; parent != NULL; parent = parent->cg_parent) {
647 		if (CPU_OVERLAP(&parent->cg_mask, &child->cg_mask))
648 			panic("Duplicate children in %p.  mask (%s) child (%s)",
649 			    parent,
650 			    cpusetobj_strprint(cpusetbuf, &parent->cg_mask),
651 			    cpusetobj_strprint(cpusetbuf2, &child->cg_mask));
652 		CPU_OR(&parent->cg_mask, &child->cg_mask);
653 		parent->cg_count += child->cg_count;
654 	}
655 
656 	return (start);
657 }
658 
659 struct cpu_group *
660 smp_topo_1level(int share, int count, int flags)
661 {
662 	struct cpu_group *child;
663 	struct cpu_group *top;
664 	int packages;
665 	int cpu;
666 	int i;
667 
668 	cpu = 0;
669 	top = &group[0];
670 	packages = mp_ncpus / count;
671 	top->cg_child = child = &group[1];
672 	top->cg_level = CG_SHARE_NONE;
673 	for (i = 0; i < packages; i++, child++)
674 		cpu = smp_topo_addleaf(top, child, share, count, flags, cpu);
675 	return (top);
676 }
677 
678 struct cpu_group *
679 smp_topo_2level(int l2share, int l2count, int l1share, int l1count,
680     int l1flags)
681 {
682 	struct cpu_group *top;
683 	struct cpu_group *l1g;
684 	struct cpu_group *l2g;
685 	int cpu;
686 	int i;
687 	int j;
688 
689 	cpu = 0;
690 	top = &group[0];
691 	l2g = &group[1];
692 	top->cg_child = l2g;
693 	top->cg_level = CG_SHARE_NONE;
694 	top->cg_children = mp_ncpus / (l2count * l1count);
695 	l1g = l2g + top->cg_children;
696 	for (i = 0; i < top->cg_children; i++, l2g++) {
697 		l2g->cg_parent = top;
698 		l2g->cg_child = l1g;
699 		l2g->cg_level = l2share;
700 		for (j = 0; j < l2count; j++, l1g++)
701 			cpu = smp_topo_addleaf(l2g, l1g, l1share, l1count,
702 			    l1flags, cpu);
703 	}
704 	return (top);
705 }
706 
707 
708 struct cpu_group *
709 smp_topo_find(struct cpu_group *top, int cpu)
710 {
711 	struct cpu_group *cg;
712 	cpuset_t mask;
713 	int children;
714 	int i;
715 
716 	CPU_SETOF(cpu, &mask);
717 	cg = top;
718 	for (;;) {
719 		if (!CPU_OVERLAP(&cg->cg_mask, &mask))
720 			return (NULL);
721 		if (cg->cg_children == 0)
722 			return (cg);
723 		children = cg->cg_children;
724 		for (i = 0, cg = cg->cg_child; i < children; cg++, i++)
725 			if (CPU_OVERLAP(&cg->cg_mask, &mask))
726 				break;
727 	}
728 	return (NULL);
729 }
730 #else /* !SMP */
731 
732 void
733 smp_rendezvous_cpus(cpuset_t map,
734 	void (*setup_func)(void *),
735 	void (*action_func)(void *),
736 	void (*teardown_func)(void *),
737 	void *arg)
738 {
739 	/*
740 	 * In the !SMP case we just need to ensure the same initial conditions
741 	 * as the SMP case.
742 	 */
743 	spinlock_enter();
744 	if (setup_func != NULL)
745 		setup_func(arg);
746 	if (action_func != NULL)
747 		action_func(arg);
748 	if (teardown_func != NULL)
749 		teardown_func(arg);
750 	spinlock_exit();
751 }
752 
753 void
754 smp_rendezvous(void (*setup_func)(void *),
755 	       void (*action_func)(void *),
756 	       void (*teardown_func)(void *),
757 	       void *arg)
758 {
759 
760 	/* Look comments in the smp_rendezvous_cpus() case. */
761 	spinlock_enter();
762 	if (setup_func != NULL)
763 		setup_func(arg);
764 	if (action_func != NULL)
765 		action_func(arg);
766 	if (teardown_func != NULL)
767 		teardown_func(arg);
768 	spinlock_exit();
769 }
770 
771 /*
772  * Provide dummy SMP support for UP kernels.  Modules that need to use SMP
773  * APIs will still work using this dummy support.
774  */
775 static void
776 mp_setvariables_for_up(void *dummy)
777 {
778 	mp_ncpus = 1;
779 	mp_maxid = PCPU_GET(cpuid);
780 	CPU_SETOF(mp_maxid, &all_cpus);
781 	KASSERT(PCPU_GET(cpuid) == 0, ("UP must have a CPU ID of zero"));
782 }
783 SYSINIT(cpu_mp_setvariables, SI_SUB_TUNABLES, SI_ORDER_FIRST,
784     mp_setvariables_for_up, NULL);
785 #endif /* SMP */
786 
787 void
788 smp_no_rendevous_barrier(void *dummy)
789 {
790 #ifdef SMP
791 	KASSERT((!smp_started),("smp_no_rendevous called and smp is started"));
792 #endif
793 }
794 
795 /*
796  * Wait specified idle threads to switch once.  This ensures that even
797  * preempted threads have cycled through the switch function once,
798  * exiting their codepaths.  This allows us to change global pointers
799  * with no other synchronization.
800  */
801 int
802 quiesce_cpus(cpuset_t map, const char *wmesg, int prio)
803 {
804 	struct pcpu *pcpu;
805 	u_int gen[MAXCPU];
806 	int error;
807 	int cpu;
808 
809 	error = 0;
810 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
811 		if (!CPU_ISSET(cpu, &map) || CPU_ABSENT(cpu))
812 			continue;
813 		pcpu = pcpu_find(cpu);
814 		gen[cpu] = pcpu->pc_idlethread->td_generation;
815 	}
816 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
817 		if (!CPU_ISSET(cpu, &map) || CPU_ABSENT(cpu))
818 			continue;
819 		pcpu = pcpu_find(cpu);
820 		thread_lock(curthread);
821 		sched_bind(curthread, cpu);
822 		thread_unlock(curthread);
823 		while (gen[cpu] == pcpu->pc_idlethread->td_generation) {
824 			error = tsleep(quiesce_cpus, prio, wmesg, 1);
825 			if (error != EWOULDBLOCK)
826 				goto out;
827 			error = 0;
828 		}
829 	}
830 out:
831 	thread_lock(curthread);
832 	sched_unbind(curthread);
833 	thread_unlock(curthread);
834 
835 	return (error);
836 }
837 
838 int
839 quiesce_all_cpus(const char *wmesg, int prio)
840 {
841 
842 	return quiesce_cpus(all_cpus, wmesg, prio);
843 }
844 
845 /* Extra care is taken with this sysctl because the data type is volatile */
846 static int
847 sysctl_kern_smp_active(SYSCTL_HANDLER_ARGS)
848 {
849 	int error, active;
850 
851 	active = smp_started;
852 	error = SYSCTL_OUT(req, &active, sizeof(active));
853 	return (error);
854 }
855 
856