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