2 * Copyright (c) 2008, Jeffrey Roberson <jeff@freebsd.org>
5 * Copyright (c) 2008 Nokia Corporation
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice unmodified, this list of conditions, and the following
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/sysproto.h>
37 #include <sys/kernel.h>
39 #include <sys/malloc.h>
40 #include <sys/mutex.h>
43 #include <sys/refcount.h>
44 #include <sys/sched.h>
46 #include <sys/syscallsubr.h>
47 #include <sys/cpuset.h>
49 #include <sys/refcount.h>
50 #include <sys/queue.h>
51 #include <sys/limits.h>
53 #include <sys/interrupt.h>
58 * cpusets provide a mechanism for creating and manipulating sets of
59 * processors for the purpose of constraining the scheduling of threads to
60 * specific processors.
62 * Each process belongs to an identified set, by default this is set 1. Each
63 * thread may further restrict the cpus it may run on to a subset of this
64 * named set. This creates an anonymous set which other threads and processes
65 * may not join by number.
67 * The named set is referred to herein as the 'base' set to avoid ambiguity.
68 * This set is usually a child of a 'root' set while the anonymous set may
69 * simply be referred to as a mask. In the syscall api these are referred to
70 * as the ROOT, CPUSET, and MASK levels where CPUSET is called 'base' here.
72 * Threads inherit their set from their creator whether it be anonymous or
73 * not. This means that anonymous sets are immutable because they may be
74 * shared. To modify an anonymous set a new set is created with the desired
75 * mask and the same parent as the existing anonymous set. This gives the
76 * illusion of each thread having a private mask.A
78 * Via the syscall apis a user may ask to retrieve or modify the root, base,
79 * or mask that is discovered via a pid, tid, or setid. Modifying a set
80 * modifies all numbered and anonymous child sets to comply with the new mask.
81 * Modifying a pid or tid's mask applies only to that tid but must still
82 * exist within the assigned parent set.
84 * A thread may not be assigned to a a group seperate from other threads in
85 * the process. This is to remove ambiguity when the setid is queried with
86 * a pid argument. There is no other technical limitation.
88 * This somewhat complex arrangement is intended to make it easy for
89 * applications to query available processors and bind their threads to
90 * specific processors while also allowing administrators to dynamically
91 * reprovision by changing sets which apply to groups of processes.
93 * A simple application should not concern itself with sets at all and
94 * rather apply masks to its own threads via CPU_WHICH_TID and a -1 id
95 * meaning 'curthread'. It may query availble cpus for that tid with a
96 * getaffinity call using (CPU_LEVEL_CPUSET, CPU_WHICH_PID, -1, ...).
98 static uma_zone_t cpuset_zone;
99 static struct mtx cpuset_lock;
100 static struct setlist cpuset_ids;
101 static struct unrhdr *cpuset_unr;
102 static struct cpuset *cpuset_zero;
104 cpuset_t *cpuset_root;
107 * Acquire a reference to a cpuset, all pointers must be tracked with refs.
110 cpuset_ref(struct cpuset *set)
113 refcount_acquire(&set->cs_ref);
118 * Release a reference in a context where it is safe to allocte.
121 cpuset_rel(struct cpuset *set)
125 if (refcount_release(&set->cs_ref) == 0)
127 mtx_lock_spin(&cpuset_lock);
128 LIST_REMOVE(set, cs_siblings);
130 if (id != CPUSET_INVALID)
131 LIST_REMOVE(set, cs_link);
132 mtx_unlock_spin(&cpuset_lock);
133 cpuset_rel(set->cs_parent);
134 uma_zfree(cpuset_zone, set);
135 if (id != CPUSET_INVALID)
136 free_unr(cpuset_unr, id);
140 * Deferred release must be used when in a context that is not safe to
141 * allocate/free. This places any unreferenced sets on the list 'head'.
144 cpuset_rel_defer(struct setlist *head, struct cpuset *set)
147 if (refcount_release(&set->cs_ref) == 0)
149 mtx_lock_spin(&cpuset_lock);
150 LIST_REMOVE(set, cs_siblings);
151 if (set->cs_id != CPUSET_INVALID)
152 LIST_REMOVE(set, cs_link);
153 LIST_INSERT_HEAD(head, set, cs_link);
154 mtx_unlock_spin(&cpuset_lock);
158 * Complete a deferred release. Removes the set from the list provided to
162 cpuset_rel_complete(struct cpuset *set)
164 LIST_REMOVE(set, cs_link);
165 cpuset_rel(set->cs_parent);
166 uma_zfree(cpuset_zone, set);
170 * Find a set based on an id. Returns it with a ref.
172 static struct cpuset *
173 cpuset_lookup(cpusetid_t setid)
177 if (setid == CPUSET_INVALID)
179 mtx_lock_spin(&cpuset_lock);
180 LIST_FOREACH(set, &cpuset_ids, cs_link)
181 if (set->cs_id == setid)
185 mtx_unlock_spin(&cpuset_lock);
190 * Create a set in the space provided in 'set' with the provided parameters.
191 * The set is returned with a single ref. May return EDEADLK if the set
192 * will have no valid cpu based on restrictions from the parent.
195 _cpuset_create(struct cpuset *set, struct cpuset *parent, cpuset_t *mask,
199 if (!CPU_OVERLAP(&parent->cs_mask, mask))
201 CPU_COPY(mask, &set->cs_mask);
202 LIST_INIT(&set->cs_children);
203 refcount_init(&set->cs_ref, 1);
205 mtx_lock_spin(&cpuset_lock);
206 CPU_AND(mask, &parent->cs_mask);
208 set->cs_parent = cpuset_ref(parent);
209 LIST_INSERT_HEAD(&parent->cs_children, set, cs_siblings);
210 if (set->cs_id != CPUSET_INVALID)
211 LIST_INSERT_HEAD(&cpuset_ids, set, cs_link);
212 mtx_unlock_spin(&cpuset_lock);
218 * Create a new non-anonymous set with the requested parent and mask. May
219 * return failures if the mask is invalid or a new number can not be
223 cpuset_create(struct cpuset **setp, struct cpuset *parent, cpuset_t *mask)
229 id = alloc_unr(cpuset_unr);
232 *setp = set = uma_zalloc(cpuset_zone, M_WAITOK);
233 error = _cpuset_create(set, parent, mask, id);
236 free_unr(cpuset_unr, id);
237 uma_zfree(cpuset_zone, set);
243 * Recursively check for errors that would occur from applying mask to
244 * the tree of sets starting at 'set'. Checks for sets that would become
245 * empty as well as RDONLY flags.
248 cpuset_testupdate(struct cpuset *set, cpuset_t *mask)
254 mtx_assert(&cpuset_lock, MA_OWNED);
255 if (set->cs_flags & CPU_SET_RDONLY)
257 if (!CPU_OVERLAP(&set->cs_mask, mask))
259 CPU_COPY(&set->cs_mask, &newmask);
260 CPU_AND(&newmask, mask);
262 LIST_FOREACH(nset, &set->cs_children, cs_siblings)
263 if ((error = cpuset_testupdate(nset, &newmask)) != 0)
269 * Applies the mask 'mask' without checking for empty sets or permissions.
272 cpuset_update(struct cpuset *set, cpuset_t *mask)
276 mtx_assert(&cpuset_lock, MA_OWNED);
277 CPU_AND(&set->cs_mask, mask);
278 LIST_FOREACH(nset, &set->cs_children, cs_siblings)
279 cpuset_update(nset, &set->cs_mask);
285 * Modify the set 'set' to use a copy of the mask provided. Apply this new
286 * mask to restrict all children in the tree. Checks for validity before
287 * applying the changes.
290 cpuset_modify(struct cpuset *set, cpuset_t *mask)
295 error = priv_check(curthread, PRIV_SCHED_CPUSET);
299 * Verify that we have access to this set of
302 root = set->cs_parent;
303 if (root && !CPU_SUBSET(&root->cs_mask, mask))
305 mtx_lock_spin(&cpuset_lock);
306 error = cpuset_testupdate(set, mask);
309 cpuset_update(set, mask);
310 CPU_COPY(mask, &set->cs_mask);
312 mtx_unlock_spin(&cpuset_lock);
318 * Walks up the tree from 'set' to find the root. Returns the root
321 static struct cpuset *
322 cpuset_refroot(struct cpuset *set)
325 for (; set->cs_parent != NULL; set = set->cs_parent)
326 if (set->cs_flags & CPU_SET_ROOT)
334 * Find the first non-anonymous set starting from 'set'. Returns this set
335 * referenced. May return the passed in set with an extra ref if it is
338 static struct cpuset *
339 cpuset_refbase(struct cpuset *set)
342 if (set->cs_id == CPUSET_INVALID)
343 set = set->cs_parent;
350 * Resolve the 'which' parameter of several cpuset apis.
352 * For WHICH_PID and WHICH_TID return a locked proc and valid proc/tid. Also
353 * checks for permission via p_cansched().
355 * For WHICH_SET returns a valid set with a new reference.
357 * -1 may be supplied for any argument to mean the current proc/thread or
358 * the base set of the current thread. May fail with ESRCH/EPERM.
361 cpuset_which(cpuwhich_t which, id_t id, struct proc **pp, struct thread **tdp,
362 struct cpuset **setp)
379 if ((p = pfind(id)) == NULL)
389 sx_slock(&allproc_lock);
390 FOREACH_PROC_IN_SYSTEM(p) {
392 FOREACH_THREAD_IN_PROC(p, td)
393 if (td->td_tid == id)
399 sx_sunlock(&allproc_lock);
403 case CPU_WHICH_CPUSET:
405 thread_lock(curthread);
406 set = cpuset_refbase(curthread->td_cpuset);
407 thread_unlock(curthread);
409 set = cpuset_lookup(id);
420 error = p_cansched(curthread, p);
426 td = FIRST_THREAD_IN_PROC(p);
433 * Create an anonymous set with the provided mask in the space provided by
434 * 'fset'. If the passed in set is anonymous we use its parent otherwise
435 * the new set is a child of 'set'.
438 cpuset_shadow(struct cpuset *set, struct cpuset *fset, cpuset_t *mask)
440 struct cpuset *parent;
442 if (set->cs_id == CPUSET_INVALID)
443 parent = set->cs_parent;
446 if (!CPU_SUBSET(&parent->cs_mask, mask))
448 return (_cpuset_create(fset, parent, mask, CPUSET_INVALID));
452 * Handle two cases for replacing the base set or mask of an entire process.
454 * 1) Set is non-null and mask is null. This reparents all anonymous sets
455 * to the provided set and replaces all non-anonymous td_cpusets with the
457 * 2) Mask is non-null and set is null. This replaces or creates anonymous
458 * sets for every thread with the existing base as a parent.
460 * This is overly complicated because we can't allocate while holding a
461 * spinlock and spinlocks must be held while changing and examining thread
465 cpuset_setproc(pid_t pid, struct cpuset *set, cpuset_t *mask)
467 struct setlist freelist;
468 struct setlist droplist;
469 struct cpuset *tdset;
477 * The algorithm requires two passes due to locking considerations.
479 * 1) Lookup the process and acquire the locks in the required order.
480 * 2) If enough cpusets have not been allocated release the locks and
481 * allocate them. Loop.
483 LIST_INIT(&freelist);
484 LIST_INIT(&droplist);
487 error = cpuset_which(CPU_WHICH_PID, pid, &p, &td, &nset);
490 if (nfree >= p->p_numthreads)
492 threads = p->p_numthreads;
494 for (; nfree < threads; nfree++) {
495 nset = uma_zalloc(cpuset_zone, M_WAITOK);
496 LIST_INSERT_HEAD(&freelist, nset, cs_link);
499 PROC_LOCK_ASSERT(p, MA_OWNED);
501 * Now that the appropriate locks are held and we have enough cpusets,
502 * make sure the operation will succeed before applying changes. The
503 * proc lock prevents td_cpuset from changing between calls.
506 FOREACH_THREAD_IN_PROC(p, td) {
508 tdset = td->td_cpuset;
510 * Verify that a new mask doesn't specify cpus outside of
511 * the set the thread is a member of.
514 if (tdset->cs_id == CPUSET_INVALID)
515 tdset = tdset->cs_parent;
516 if (!CPU_SUBSET(&tdset->cs_mask, mask))
519 * Verify that a new set won't leave an existing thread
520 * mask without a cpu to run on. It can, however, restrict
523 } else if (tdset->cs_id == CPUSET_INVALID) {
524 if (!CPU_OVERLAP(&set->cs_mask, &tdset->cs_mask))
532 * Replace each thread's cpuset while using deferred release. We
533 * must do this because the thread lock must be held while operating
534 * on the thread and this limits the type of operations allowed.
536 FOREACH_THREAD_IN_PROC(p, td) {
539 * If we presently have an anonymous set or are applying a
540 * mask we must create an anonymous shadow set. That is
541 * either parented to our existing base or the supplied set.
543 * If we have a base set with no anonymous shadow we simply
544 * replace it outright.
546 tdset = td->td_cpuset;
547 if (tdset->cs_id == CPUSET_INVALID || mask) {
548 nset = LIST_FIRST(&freelist);
549 LIST_REMOVE(nset, cs_link);
551 error = cpuset_shadow(tdset, nset, mask);
553 error = _cpuset_create(nset, set,
554 &tdset->cs_mask, CPUSET_INVALID);
556 LIST_INSERT_HEAD(&freelist, nset, cs_link);
561 nset = cpuset_ref(set);
562 cpuset_rel_defer(&droplist, tdset);
563 td->td_cpuset = nset;
570 while ((nset = LIST_FIRST(&droplist)) != NULL)
571 cpuset_rel_complete(nset);
572 while ((nset = LIST_FIRST(&freelist)) != NULL) {
573 LIST_REMOVE(nset, cs_link);
574 uma_zfree(cpuset_zone, nset);
580 * Apply an anonymous mask to a single thread.
583 cpuset_setthread(lwpid_t id, cpuset_t *mask)
591 nset = uma_zalloc(cpuset_zone, M_WAITOK);
592 error = cpuset_which(CPU_WHICH_TID, id, &p, &td, &set);
597 error = cpuset_shadow(td->td_cpuset, nset, mask);
600 td->td_cpuset = nset;
610 uma_zfree(cpuset_zone, nset);
615 * Creates the cpuset for thread0. We make two sets:
617 * 0 - The root set which should represent all valid processors in the
618 * system. It is initially created with a mask of all processors
619 * because we don't know what processors are valid until cpuset_init()
620 * runs. This set is immutable.
621 * 1 - The default set which all processes are a member of until changed.
622 * This allows an administrator to move all threads off of given cpus to
623 * dedicate them to high priority tasks or save power etc.
631 cpuset_zone = uma_zcreate("cpuset", sizeof(struct cpuset), NULL, NULL,
632 NULL, NULL, UMA_ALIGN_PTR, 0);
633 mtx_init(&cpuset_lock, "cpuset", NULL, MTX_SPIN | MTX_RECURSE);
635 * Create the root system set for the whole machine. Doesn't use
636 * cpuset_create() due to NULL parent.
638 set = uma_zalloc(cpuset_zone, M_WAITOK | M_ZERO);
639 set->cs_mask.__bits[0] = -1;
640 LIST_INIT(&set->cs_children);
641 LIST_INSERT_HEAD(&cpuset_ids, set, cs_link);
643 set->cs_flags = CPU_SET_ROOT;
645 cpuset_root = &set->cs_mask;
647 * Now derive a default, modifiable set from that to give out.
649 set = uma_zalloc(cpuset_zone, M_WAITOK);
650 error = _cpuset_create(set, cpuset_zero, &cpuset_zero->cs_mask, 1);
651 KASSERT(error == 0, ("Error creating default set: %d\n", error));
653 * Initialize the unit allocator. 0 and 1 are allocated above.
655 cpuset_unr = new_unrhdr(2, INT_MAX, NULL);
661 * This is called once the final set of system cpus is known. Modifies
662 * the root set and all children and mark the root readonly.
665 cpuset_init(void *arg)
671 mask.__bits[0] = all_cpus;
675 if (cpuset_modify(cpuset_zero, &mask))
676 panic("Can't set initial cpuset mask.\n");
677 cpuset_zero->cs_flags |= CPU_SET_RDONLY;
679 SYSINIT(cpuset, SI_SUB_SMP, SI_ORDER_ANY, cpuset_init, NULL);
681 #ifndef _SYS_SYSPROTO_H_
687 cpuset(struct thread *td, struct cpuset_args *uap)
694 root = cpuset_refroot(td->td_cpuset);
696 error = cpuset_create(&set, root, &root->cs_mask);
700 error = copyout(&set->cs_id, uap->setid, sizeof(set->cs_id));
702 error = cpuset_setproc(-1, set, NULL);
707 #ifndef _SYS_SYSPROTO_H_
708 struct cpuset_setid_args {
715 cpuset_setid(struct thread *td, struct cpuset_setid_args *uap)
721 * Presently we only support per-process sets.
723 if (uap->which != CPU_WHICH_PID)
725 set = cpuset_lookup(uap->setid);
728 error = cpuset_setproc(uap->id, set, NULL);
733 #ifndef _SYS_SYSPROTO_H_
734 struct cpuset_getid_args {
741 cpuset_getid(struct thread *td, struct cpuset_getid_args *uap)
750 if (uap->level == CPU_LEVEL_WHICH && uap->which != CPU_WHICH_CPUSET)
752 error = cpuset_which(uap->which, uap->id, &p, &ttd, &set);
755 switch (uap->which) {
759 set = cpuset_refbase(ttd->td_cpuset);
763 case CPU_WHICH_CPUSET:
768 switch (uap->level) {
770 nset = cpuset_refroot(set);
774 case CPU_LEVEL_CPUSET:
776 case CPU_LEVEL_WHICH:
782 error = copyout(&id, uap->setid, sizeof(id));
787 #ifndef _SYS_SYSPROTO_H_
788 struct cpuset_getaffinity_args {
797 cpuset_getaffinity(struct thread *td, struct cpuset_getaffinity_args *uap)
807 if (uap->cpusetsize < sizeof(cpuset_t) ||
808 uap->cpusetsize > CPU_MAXSIZE / NBBY)
810 size = uap->cpusetsize;
811 mask = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
812 error = cpuset_which(uap->which, uap->id, &p, &ttd, &set);
815 switch (uap->level) {
817 case CPU_LEVEL_CPUSET:
818 switch (uap->which) {
822 set = cpuset_ref(ttd->td_cpuset);
825 case CPU_WHICH_CPUSET:
831 if (uap->level == CPU_LEVEL_ROOT)
832 nset = cpuset_refroot(set);
834 nset = cpuset_refbase(set);
835 CPU_COPY(&nset->cs_mask, mask);
838 case CPU_LEVEL_WHICH:
839 switch (uap->which) {
842 CPU_COPY(&ttd->td_cpuset->cs_mask, mask);
846 FOREACH_THREAD_IN_PROC(p, ttd) {
848 CPU_OR(mask, &ttd->td_cpuset->cs_mask);
852 case CPU_WHICH_CPUSET:
853 CPU_COPY(&set->cs_mask, mask);
856 error = intr_getaffinity(uap->id, mask);
869 error = copyout(mask, uap->mask, size);
875 #ifndef _SYS_SYSPROTO_H_
876 struct cpuset_setaffinity_args {
881 const cpuset_t *mask;
885 cpuset_setaffinity(struct thread *td, struct cpuset_setaffinity_args *uap)
894 if (uap->cpusetsize < sizeof(cpuset_t) ||
895 uap->cpusetsize > CPU_MAXSIZE / NBBY)
897 mask = malloc(uap->cpusetsize, M_TEMP, M_WAITOK | M_ZERO);
898 error = copyin(uap->mask, mask, uap->cpusetsize);
902 * Verify that no high bits are set.
904 if (uap->cpusetsize > sizeof(cpuset_t)) {
908 end = cp = (char *)&mask->__bits;
909 end += uap->cpusetsize;
910 cp += sizeof(cpuset_t);
918 switch (uap->level) {
920 case CPU_LEVEL_CPUSET:
921 error = cpuset_which(uap->which, uap->id, &p, &ttd, &set);
924 switch (uap->which) {
928 set = cpuset_ref(ttd->td_cpuset);
932 case CPU_WHICH_CPUSET:
938 if (uap->level == CPU_LEVEL_ROOT)
939 nset = cpuset_refroot(set);
941 nset = cpuset_refbase(set);
942 error = cpuset_modify(nset, mask);
946 case CPU_LEVEL_WHICH:
947 switch (uap->which) {
949 error = cpuset_setthread(uap->id, mask);
952 error = cpuset_setproc(uap->id, NULL, mask);
954 case CPU_WHICH_CPUSET:
955 error = cpuset_which(CPU_WHICH_CPUSET, uap->id, &p,
958 error = cpuset_modify(set, mask);
963 error = intr_setaffinity(uap->id, mask);