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