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