xref: /freebsd/sys/kern/kern_cpuset.c (revision cd8537910406e68d4719136a5b0cf6d23bb1b23b)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2008,  Jeffrey Roberson <jeff@freebsd.org>
5  * All rights reserved.
6  *
7  * Copyright (c) 2008 Nokia Corporation
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice unmodified, this list of conditions, and the following
15  *    disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  *
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "opt_ddb.h"
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/sysctl.h>
41 #include <sys/ctype.h>
42 #include <sys/sysproto.h>
43 #include <sys/jail.h>
44 #include <sys/kernel.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/mutex.h>
48 #include <sys/priv.h>
49 #include <sys/proc.h>
50 #include <sys/refcount.h>
51 #include <sys/sched.h>
52 #include <sys/smp.h>
53 #include <sys/syscallsubr.h>
54 #include <sys/capsicum.h>
55 #include <sys/cpuset.h>
56 #include <sys/domainset.h>
57 #include <sys/sx.h>
58 #include <sys/queue.h>
59 #include <sys/libkern.h>
60 #include <sys/limits.h>
61 #include <sys/bus.h>
62 #include <sys/interrupt.h>
63 #include <sys/vmmeter.h>
64 
65 #include <vm/uma.h>
66 #include <vm/vm.h>
67 #include <vm/vm_object.h>
68 #include <vm/vm_page.h>
69 #include <vm/vm_pageout.h>
70 #include <vm/vm_extern.h>
71 #include <vm/vm_param.h>
72 #include <vm/vm_phys.h>
73 #include <vm/vm_pagequeue.h>
74 
75 #ifdef DDB
76 #include <ddb/ddb.h>
77 #endif /* DDB */
78 
79 /*
80  * cpusets provide a mechanism for creating and manipulating sets of
81  * processors for the purpose of constraining the scheduling of threads to
82  * specific processors.
83  *
84  * Each process belongs to an identified set, by default this is set 1.  Each
85  * thread may further restrict the cpus it may run on to a subset of this
86  * named set.  This creates an anonymous set which other threads and processes
87  * may not join by number.
88  *
89  * The named set is referred to herein as the 'base' set to avoid ambiguity.
90  * This set is usually a child of a 'root' set while the anonymous set may
91  * simply be referred to as a mask.  In the syscall api these are referred to
92  * as the ROOT, CPUSET, and MASK levels where CPUSET is called 'base' here.
93  *
94  * Threads inherit their set from their creator whether it be anonymous or
95  * not.  This means that anonymous sets are immutable because they may be
96  * shared.  To modify an anonymous set a new set is created with the desired
97  * mask and the same parent as the existing anonymous set.  This gives the
98  * illusion of each thread having a private mask.
99  *
100  * Via the syscall apis a user may ask to retrieve or modify the root, base,
101  * or mask that is discovered via a pid, tid, or setid.  Modifying a set
102  * modifies all numbered and anonymous child sets to comply with the new mask.
103  * Modifying a pid or tid's mask applies only to that tid but must still
104  * exist within the assigned parent set.
105  *
106  * A thread may not be assigned to a group separate from other threads in
107  * the process.  This is to remove ambiguity when the setid is queried with
108  * a pid argument.  There is no other technical limitation.
109  *
110  * This somewhat complex arrangement is intended to make it easy for
111  * applications to query available processors and bind their threads to
112  * specific processors while also allowing administrators to dynamically
113  * reprovision by changing sets which apply to groups of processes.
114  *
115  * A simple application should not concern itself with sets at all and
116  * rather apply masks to its own threads via CPU_WHICH_TID and a -1 id
117  * meaning 'curthread'.  It may query available cpus for that tid with a
118  * getaffinity call using (CPU_LEVEL_CPUSET, CPU_WHICH_PID, -1, ...).
119  */
120 
121 LIST_HEAD(domainlist, domainset);
122 struct domainset __read_mostly domainset_fixed[MAXMEMDOM];
123 struct domainset __read_mostly domainset_prefer[MAXMEMDOM];
124 struct domainset __read_mostly domainset_roundrobin;
125 
126 static uma_zone_t cpuset_zone;
127 static uma_zone_t domainset_zone;
128 static struct mtx cpuset_lock;
129 static struct setlist cpuset_ids;
130 static struct domainlist cpuset_domains;
131 static struct unrhdr *cpuset_unr;
132 static struct cpuset *cpuset_zero, *cpuset_default, *cpuset_kernel;
133 static struct domainset domainset0, domainset2;
134 
135 /* Return the size of cpuset_t at the kernel level */
136 SYSCTL_INT(_kern_sched, OID_AUTO, cpusetsize, CTLFLAG_RD | CTLFLAG_CAPRD,
137     SYSCTL_NULL_INT_PTR, sizeof(cpuset_t), "sizeof(cpuset_t)");
138 
139 cpuset_t *cpuset_root;
140 cpuset_t cpuset_domain[MAXMEMDOM];
141 
142 static int domainset_valid(const struct domainset *, const struct domainset *);
143 
144 /*
145  * Find the first non-anonymous set starting from 'set'.
146  */
147 static struct cpuset *
148 cpuset_getbase(struct cpuset *set)
149 {
150 
151 	if (set->cs_id == CPUSET_INVALID)
152 		set = set->cs_parent;
153 	return (set);
154 }
155 
156 /*
157  * Walks up the tree from 'set' to find the root.
158  */
159 static struct cpuset *
160 cpuset_getroot(struct cpuset *set)
161 {
162 
163 	while ((set->cs_flags & CPU_SET_ROOT) == 0 && set->cs_parent != NULL)
164 		set = set->cs_parent;
165 	return (set);
166 }
167 
168 /*
169  * Acquire a reference to a cpuset, all pointers must be tracked with refs.
170  */
171 struct cpuset *
172 cpuset_ref(struct cpuset *set)
173 {
174 
175 	refcount_acquire(&set->cs_ref);
176 	return (set);
177 }
178 
179 /*
180  * Walks up the tree from 'set' to find the root.  Returns the root
181  * referenced.
182  */
183 static struct cpuset *
184 cpuset_refroot(struct cpuset *set)
185 {
186 
187 	return (cpuset_ref(cpuset_getroot(set)));
188 }
189 
190 /*
191  * Find the first non-anonymous set starting from 'set'.  Returns this set
192  * referenced.  May return the passed in set with an extra ref if it is
193  * not anonymous.
194  */
195 static struct cpuset *
196 cpuset_refbase(struct cpuset *set)
197 {
198 
199 	return (cpuset_ref(cpuset_getbase(set)));
200 }
201 
202 /*
203  * Release a reference in a context where it is safe to allocate.
204  */
205 void
206 cpuset_rel(struct cpuset *set)
207 {
208 	cpusetid_t id;
209 
210 	if (refcount_release(&set->cs_ref) == 0)
211 		return;
212 	mtx_lock_spin(&cpuset_lock);
213 	LIST_REMOVE(set, cs_siblings);
214 	id = set->cs_id;
215 	if (id != CPUSET_INVALID)
216 		LIST_REMOVE(set, cs_link);
217 	mtx_unlock_spin(&cpuset_lock);
218 	cpuset_rel(set->cs_parent);
219 	uma_zfree(cpuset_zone, set);
220 	if (id != CPUSET_INVALID)
221 		free_unr(cpuset_unr, id);
222 }
223 
224 /*
225  * Deferred release must be used when in a context that is not safe to
226  * allocate/free.  This places any unreferenced sets on the list 'head'.
227  */
228 static void
229 cpuset_rel_defer(struct setlist *head, struct cpuset *set)
230 {
231 
232 	if (refcount_release(&set->cs_ref) == 0)
233 		return;
234 	mtx_lock_spin(&cpuset_lock);
235 	LIST_REMOVE(set, cs_siblings);
236 	if (set->cs_id != CPUSET_INVALID)
237 		LIST_REMOVE(set, cs_link);
238 	LIST_INSERT_HEAD(head, set, cs_link);
239 	mtx_unlock_spin(&cpuset_lock);
240 }
241 
242 /*
243  * Complete a deferred release.  Removes the set from the list provided to
244  * cpuset_rel_defer.
245  */
246 static void
247 cpuset_rel_complete(struct cpuset *set)
248 {
249 	LIST_REMOVE(set, cs_link);
250 	cpuset_rel(set->cs_parent);
251 	uma_zfree(cpuset_zone, set);
252 }
253 
254 /*
255  * Find a set based on an id.  Returns it with a ref.
256  */
257 static struct cpuset *
258 cpuset_lookup(cpusetid_t setid, struct thread *td)
259 {
260 	struct cpuset *set;
261 
262 	if (setid == CPUSET_INVALID)
263 		return (NULL);
264 	mtx_lock_spin(&cpuset_lock);
265 	LIST_FOREACH(set, &cpuset_ids, cs_link)
266 		if (set->cs_id == setid)
267 			break;
268 	if (set)
269 		cpuset_ref(set);
270 	mtx_unlock_spin(&cpuset_lock);
271 
272 	KASSERT(td != NULL, ("[%s:%d] td is NULL", __func__, __LINE__));
273 	if (set != NULL && jailed(td->td_ucred)) {
274 		struct cpuset *jset, *tset;
275 
276 		jset = td->td_ucred->cr_prison->pr_cpuset;
277 		for (tset = set; tset != NULL; tset = tset->cs_parent)
278 			if (tset == jset)
279 				break;
280 		if (tset == NULL) {
281 			cpuset_rel(set);
282 			set = NULL;
283 		}
284 	}
285 
286 	return (set);
287 }
288 
289 /*
290  * Initialize a set in the space provided in 'set' with the provided parameters.
291  * The set is returned with a single ref.  May return EDEADLK if the set
292  * will have no valid cpu based on restrictions from the parent.
293  */
294 static int
295 cpuset_init(struct cpuset *set, struct cpuset *parent,
296     const cpuset_t *mask, struct domainset *domain, cpusetid_t id)
297 {
298 
299 	if (domain == NULL)
300 		domain = parent->cs_domain;
301 	if (mask == NULL)
302 		mask = &parent->cs_mask;
303 	if (!CPU_OVERLAP(&parent->cs_mask, mask))
304 		return (EDEADLK);
305 	/* The domain must be prepared ahead of time. */
306 	if (!domainset_valid(parent->cs_domain, domain))
307 		return (EDEADLK);
308 	CPU_COPY(mask, &set->cs_mask);
309 	LIST_INIT(&set->cs_children);
310 	refcount_init(&set->cs_ref, 1);
311 	set->cs_flags = 0;
312 	mtx_lock_spin(&cpuset_lock);
313 	set->cs_domain = domain;
314 	CPU_AND(&set->cs_mask, &parent->cs_mask);
315 	set->cs_id = id;
316 	set->cs_parent = cpuset_ref(parent);
317 	LIST_INSERT_HEAD(&parent->cs_children, set, cs_siblings);
318 	if (set->cs_id != CPUSET_INVALID)
319 		LIST_INSERT_HEAD(&cpuset_ids, set, cs_link);
320 	mtx_unlock_spin(&cpuset_lock);
321 
322 	return (0);
323 }
324 
325 /*
326  * Create a new non-anonymous set with the requested parent and mask.  May
327  * return failures if the mask is invalid or a new number can not be
328  * allocated.
329  *
330  * If *setp is not NULL, then it will be used as-is.  The caller must take
331  * into account that *setp will be inserted at the head of cpuset_ids and
332  * plan any potentially conflicting cs_link usage accordingly.
333  */
334 static int
335 cpuset_create(struct cpuset **setp, struct cpuset *parent, const cpuset_t *mask)
336 {
337 	struct cpuset *set;
338 	cpusetid_t id;
339 	int error;
340 	bool dofree;
341 
342 	id = alloc_unr(cpuset_unr);
343 	if (id == -1)
344 		return (ENFILE);
345 	dofree = (*setp == NULL);
346 	if (*setp != NULL)
347 		set = *setp;
348 	else
349 		*setp = set = uma_zalloc(cpuset_zone, M_WAITOK | M_ZERO);
350 	error = cpuset_init(set, parent, mask, NULL, id);
351 	if (error == 0)
352 		return (0);
353 	free_unr(cpuset_unr, id);
354 	if (dofree)
355 		uma_zfree(cpuset_zone, set);
356 
357 	return (error);
358 }
359 
360 static void
361 cpuset_freelist_add(struct setlist *list, int count)
362 {
363 	struct cpuset *set;
364 	int i;
365 
366 	for (i = 0; i < count; i++) {
367 		set = uma_zalloc(cpuset_zone, M_ZERO | M_WAITOK);
368 		LIST_INSERT_HEAD(list, set, cs_link);
369 	}
370 }
371 
372 static void
373 cpuset_freelist_init(struct setlist *list, int count)
374 {
375 
376 	LIST_INIT(list);
377 	cpuset_freelist_add(list, count);
378 }
379 
380 static void
381 cpuset_freelist_free(struct setlist *list)
382 {
383 	struct cpuset *set;
384 
385 	while ((set = LIST_FIRST(list)) != NULL) {
386 		LIST_REMOVE(set, cs_link);
387 		uma_zfree(cpuset_zone, set);
388 	}
389 }
390 
391 static void
392 domainset_freelist_add(struct domainlist *list, int count)
393 {
394 	struct domainset *set;
395 	int i;
396 
397 	for (i = 0; i < count; i++) {
398 		set = uma_zalloc(domainset_zone, M_ZERO | M_WAITOK);
399 		LIST_INSERT_HEAD(list, set, ds_link);
400 	}
401 }
402 
403 static void
404 domainset_freelist_init(struct domainlist *list, int count)
405 {
406 
407 	LIST_INIT(list);
408 	domainset_freelist_add(list, count);
409 }
410 
411 static void
412 domainset_freelist_free(struct domainlist *list)
413 {
414 	struct domainset *set;
415 
416 	while ((set = LIST_FIRST(list)) != NULL) {
417 		LIST_REMOVE(set, ds_link);
418 		uma_zfree(domainset_zone, set);
419 	}
420 }
421 
422 /* Copy a domainset preserving mask and policy. */
423 static void
424 domainset_copy(const struct domainset *from, struct domainset *to)
425 {
426 
427 	DOMAINSET_COPY(&from->ds_mask, &to->ds_mask);
428 	to->ds_policy = from->ds_policy;
429 	to->ds_prefer = from->ds_prefer;
430 }
431 
432 /* Return 1 if mask and policy are equal, otherwise 0. */
433 static int
434 domainset_equal(const struct domainset *one, const struct domainset *two)
435 {
436 
437 	return (DOMAINSET_CMP(&one->ds_mask, &two->ds_mask) == 0 &&
438 	    one->ds_policy == two->ds_policy &&
439 	    one->ds_prefer == two->ds_prefer);
440 }
441 
442 /* Return 1 if child is a valid subset of parent. */
443 static int
444 domainset_valid(const struct domainset *parent, const struct domainset *child)
445 {
446 	if (child->ds_policy != DOMAINSET_POLICY_PREFER)
447 		return (DOMAINSET_SUBSET(&parent->ds_mask, &child->ds_mask));
448 	return (DOMAINSET_ISSET(child->ds_prefer, &parent->ds_mask));
449 }
450 
451 static int
452 domainset_restrict(const struct domainset *parent,
453     const struct domainset *child)
454 {
455 	if (child->ds_policy != DOMAINSET_POLICY_PREFER)
456 		return (DOMAINSET_OVERLAP(&parent->ds_mask, &child->ds_mask));
457 	return (DOMAINSET_ISSET(child->ds_prefer, &parent->ds_mask));
458 }
459 
460 /*
461  * Lookup or create a domainset.  The key is provided in ds_mask and
462  * ds_policy.  If the domainset does not yet exist the storage in
463  * 'domain' is used to insert.  Otherwise this storage is freed to the
464  * domainset_zone and the existing domainset is returned.
465  */
466 static struct domainset *
467 _domainset_create(struct domainset *domain, struct domainlist *freelist)
468 {
469 	struct domainset *ndomain;
470 	int i, j;
471 
472 	KASSERT(domain->ds_cnt <= vm_ndomains,
473 	    ("invalid domain count in domainset %p", domain));
474 	KASSERT(domain->ds_policy != DOMAINSET_POLICY_PREFER ||
475 	    domain->ds_prefer < vm_ndomains,
476 	    ("invalid preferred domain in domains %p", domain));
477 
478 	mtx_lock_spin(&cpuset_lock);
479 	LIST_FOREACH(ndomain, &cpuset_domains, ds_link)
480 		if (domainset_equal(ndomain, domain))
481 			break;
482 	/*
483 	 * If the domain does not yet exist we insert it and initialize
484 	 * various iteration helpers which are not part of the key.
485 	 */
486 	if (ndomain == NULL) {
487 		LIST_INSERT_HEAD(&cpuset_domains, domain, ds_link);
488 		domain->ds_cnt = DOMAINSET_COUNT(&domain->ds_mask);
489 		for (i = 0, j = 0; i < DOMAINSET_FLS(&domain->ds_mask); i++)
490 			if (DOMAINSET_ISSET(i, &domain->ds_mask))
491 				domain->ds_order[j++] = i;
492 	}
493 	mtx_unlock_spin(&cpuset_lock);
494 	if (ndomain == NULL)
495 		return (domain);
496 	if (freelist != NULL)
497 		LIST_INSERT_HEAD(freelist, domain, ds_link);
498 	else
499 		uma_zfree(domainset_zone, domain);
500 	return (ndomain);
501 
502 }
503 
504 /*
505  * Are any of the domains in the mask empty?  If so, silently
506  * remove them and update the domainset accordingly.  If only empty
507  * domains are present, we must return failure.
508  */
509 static bool
510 domainset_empty_vm(struct domainset *domain)
511 {
512 	domainset_t empty;
513 	int i, j;
514 
515 	DOMAINSET_ZERO(&empty);
516 	for (i = 0; i < vm_ndomains; i++)
517 		if (VM_DOMAIN_EMPTY(i))
518 			DOMAINSET_SET(i, &empty);
519 	if (DOMAINSET_SUBSET(&empty, &domain->ds_mask))
520 		return (true);
521 
522 	/* Remove empty domains from the set and recompute. */
523 	DOMAINSET_ANDNOT(&domain->ds_mask, &empty);
524 	domain->ds_cnt = DOMAINSET_COUNT(&domain->ds_mask);
525 	for (i = j = 0; i < DOMAINSET_FLS(&domain->ds_mask); i++)
526 		if (DOMAINSET_ISSET(i, &domain->ds_mask))
527 			domain->ds_order[j++] = i;
528 
529 	/* Convert a PREFER policy referencing an empty domain to RR. */
530 	if (domain->ds_policy == DOMAINSET_POLICY_PREFER &&
531 	    DOMAINSET_ISSET(domain->ds_prefer, &empty)) {
532 		domain->ds_policy = DOMAINSET_POLICY_ROUNDROBIN;
533 		domain->ds_prefer = -1;
534 	}
535 
536 	return (false);
537 }
538 
539 /*
540  * Create or lookup a domainset based on the key held in 'domain'.
541  */
542 struct domainset *
543 domainset_create(const struct domainset *domain)
544 {
545 	struct domainset *ndomain;
546 
547 	/*
548 	 * Validate the policy.  It must specify a useable policy number with
549 	 * only valid domains.  Preferred must include the preferred domain
550 	 * in the mask.
551 	 */
552 	if (domain->ds_policy <= DOMAINSET_POLICY_INVALID ||
553 	    domain->ds_policy > DOMAINSET_POLICY_MAX)
554 		return (NULL);
555 	if (domain->ds_policy == DOMAINSET_POLICY_PREFER &&
556 	    !DOMAINSET_ISSET(domain->ds_prefer, &domain->ds_mask))
557 		return (NULL);
558 	if (!DOMAINSET_SUBSET(&domainset0.ds_mask, &domain->ds_mask))
559 		return (NULL);
560 	ndomain = uma_zalloc(domainset_zone, M_WAITOK | M_ZERO);
561 	domainset_copy(domain, ndomain);
562 	return _domainset_create(ndomain, NULL);
563 }
564 
565 /*
566  * Update thread domainset pointers.
567  */
568 static void
569 domainset_notify(void)
570 {
571 	struct thread *td;
572 	struct proc *p;
573 
574 	sx_slock(&allproc_lock);
575 	FOREACH_PROC_IN_SYSTEM(p) {
576 		PROC_LOCK(p);
577 		if (p->p_state == PRS_NEW) {
578 			PROC_UNLOCK(p);
579 			continue;
580 		}
581 		FOREACH_THREAD_IN_PROC(p, td) {
582 			thread_lock(td);
583 			td->td_domain.dr_policy = td->td_cpuset->cs_domain;
584 			thread_unlock(td);
585 		}
586 		PROC_UNLOCK(p);
587 	}
588 	sx_sunlock(&allproc_lock);
589 	kernel_object->domain.dr_policy = cpuset_kernel->cs_domain;
590 }
591 
592 /*
593  * Create a new set that is a subset of a parent.
594  */
595 static struct domainset *
596 domainset_shadow(const struct domainset *pdomain,
597     const struct domainset *domain, struct domainlist *freelist)
598 {
599 	struct domainset *ndomain;
600 
601 	ndomain = LIST_FIRST(freelist);
602 	LIST_REMOVE(ndomain, ds_link);
603 
604 	/*
605 	 * Initialize the key from the request.
606 	 */
607 	domainset_copy(domain, ndomain);
608 
609 	/*
610 	 * Restrict the key by the parent.
611 	 */
612 	DOMAINSET_AND(&ndomain->ds_mask, &pdomain->ds_mask);
613 
614 	return _domainset_create(ndomain, freelist);
615 }
616 
617 /*
618  * Recursively check for errors that would occur from applying mask to
619  * the tree of sets starting at 'set'.  Checks for sets that would become
620  * empty as well as RDONLY flags.
621  */
622 static int
623 cpuset_testupdate(struct cpuset *set, cpuset_t *mask, int check_mask)
624 {
625 	struct cpuset *nset;
626 	cpuset_t newmask;
627 	int error;
628 
629 	mtx_assert(&cpuset_lock, MA_OWNED);
630 	if (set->cs_flags & CPU_SET_RDONLY)
631 		return (EPERM);
632 	if (check_mask) {
633 		if (!CPU_OVERLAP(&set->cs_mask, mask))
634 			return (EDEADLK);
635 		CPU_COPY(&set->cs_mask, &newmask);
636 		CPU_AND(&newmask, mask);
637 	} else
638 		CPU_COPY(mask, &newmask);
639 	error = 0;
640 	LIST_FOREACH(nset, &set->cs_children, cs_siblings)
641 		if ((error = cpuset_testupdate(nset, &newmask, 1)) != 0)
642 			break;
643 	return (error);
644 }
645 
646 /*
647  * Applies the mask 'mask' without checking for empty sets or permissions.
648  */
649 static void
650 cpuset_update(struct cpuset *set, cpuset_t *mask)
651 {
652 	struct cpuset *nset;
653 
654 	mtx_assert(&cpuset_lock, MA_OWNED);
655 	CPU_AND(&set->cs_mask, mask);
656 	LIST_FOREACH(nset, &set->cs_children, cs_siblings)
657 		cpuset_update(nset, &set->cs_mask);
658 
659 	return;
660 }
661 
662 /*
663  * Modify the set 'set' to use a copy of the mask provided.  Apply this new
664  * mask to restrict all children in the tree.  Checks for validity before
665  * applying the changes.
666  */
667 static int
668 cpuset_modify(struct cpuset *set, cpuset_t *mask)
669 {
670 	struct cpuset *root;
671 	int error;
672 
673 	error = priv_check(curthread, PRIV_SCHED_CPUSET);
674 	if (error)
675 		return (error);
676 	/*
677 	 * In case we are called from within the jail
678 	 * we do not allow modifying the dedicated root
679 	 * cpuset of the jail but may still allow to
680 	 * change child sets.
681 	 */
682 	if (jailed(curthread->td_ucred) &&
683 	    set->cs_flags & CPU_SET_ROOT)
684 		return (EPERM);
685 	/*
686 	 * Verify that we have access to this set of
687 	 * cpus.
688 	 */
689 	root = cpuset_getroot(set);
690 	mtx_lock_spin(&cpuset_lock);
691 	if (root && !CPU_SUBSET(&root->cs_mask, mask)) {
692 		error = EINVAL;
693 		goto out;
694 	}
695 	error = cpuset_testupdate(set, mask, 0);
696 	if (error)
697 		goto out;
698 	CPU_COPY(mask, &set->cs_mask);
699 	cpuset_update(set, mask);
700 out:
701 	mtx_unlock_spin(&cpuset_lock);
702 
703 	return (error);
704 }
705 
706 /*
707  * Recursively check for errors that would occur from applying mask to
708  * the tree of sets starting at 'set'.  Checks for sets that would become
709  * empty as well as RDONLY flags.
710  */
711 static int
712 cpuset_testupdate_domain(struct cpuset *set, struct domainset *dset,
713     struct domainset *orig, int *count, int check_mask)
714 {
715 	struct cpuset *nset;
716 	struct domainset *domain;
717 	struct domainset newset;
718 	int error;
719 
720 	mtx_assert(&cpuset_lock, MA_OWNED);
721 	if (set->cs_flags & CPU_SET_RDONLY)
722 		return (EPERM);
723 	domain = set->cs_domain;
724 	domainset_copy(domain, &newset);
725 	if (!domainset_equal(domain, orig)) {
726 		if (!domainset_restrict(domain, dset))
727 			return (EDEADLK);
728 		DOMAINSET_AND(&newset.ds_mask, &dset->ds_mask);
729 		/* Count the number of domains that are changing. */
730 		(*count)++;
731 	}
732 	error = 0;
733 	LIST_FOREACH(nset, &set->cs_children, cs_siblings)
734 		if ((error = cpuset_testupdate_domain(nset, &newset, domain,
735 		    count, 1)) != 0)
736 			break;
737 	return (error);
738 }
739 
740 /*
741  * Applies the mask 'mask' without checking for empty sets or permissions.
742  */
743 static void
744 cpuset_update_domain(struct cpuset *set, struct domainset *domain,
745     struct domainset *orig, struct domainlist *domains)
746 {
747 	struct cpuset *nset;
748 
749 	mtx_assert(&cpuset_lock, MA_OWNED);
750 	/*
751 	 * If this domainset has changed from the parent we must calculate
752 	 * a new set.  Otherwise it simply inherits from the parent.  When
753 	 * we inherit from the parent we get a new mask and policy.  If the
754 	 * set is modified from the parent we keep the policy and only
755 	 * update the mask.
756 	 */
757 	if (set->cs_domain != orig) {
758 		orig = set->cs_domain;
759 		set->cs_domain = domainset_shadow(domain, orig, domains);
760 	} else
761 		set->cs_domain = domain;
762 	LIST_FOREACH(nset, &set->cs_children, cs_siblings)
763 		cpuset_update_domain(nset, set->cs_domain, orig, domains);
764 
765 	return;
766 }
767 
768 /*
769  * Modify the set 'set' to use a copy the domainset provided.  Apply this new
770  * mask to restrict all children in the tree.  Checks for validity before
771  * applying the changes.
772  */
773 static int
774 cpuset_modify_domain(struct cpuset *set, struct domainset *domain)
775 {
776 	struct domainlist domains;
777 	struct domainset temp;
778 	struct domainset *dset;
779 	struct cpuset *root;
780 	int ndomains, needed;
781 	int error;
782 
783 	error = priv_check(curthread, PRIV_SCHED_CPUSET);
784 	if (error)
785 		return (error);
786 	/*
787 	 * In case we are called from within the jail
788 	 * we do not allow modifying the dedicated root
789 	 * cpuset of the jail but may still allow to
790 	 * change child sets.
791 	 */
792 	if (jailed(curthread->td_ucred) &&
793 	    set->cs_flags & CPU_SET_ROOT)
794 		return (EPERM);
795 	domainset_freelist_init(&domains, 0);
796 	domain = domainset_create(domain);
797 	ndomains = 0;
798 
799 	mtx_lock_spin(&cpuset_lock);
800 	for (;;) {
801 		root = cpuset_getroot(set);
802 		dset = root->cs_domain;
803 		/*
804 		 * Verify that we have access to this set of domains.
805 		 */
806 		if (!domainset_valid(dset, domain)) {
807 			error = EINVAL;
808 			goto out;
809 		}
810 		/*
811 		 * If applying prefer we keep the current set as the fallback.
812 		 */
813 		if (domain->ds_policy == DOMAINSET_POLICY_PREFER)
814 			DOMAINSET_COPY(&set->cs_domain->ds_mask,
815 			    &domain->ds_mask);
816 		/*
817 		 * Determine whether we can apply this set of domains and
818 		 * how many new domain structures it will require.
819 		 */
820 		domainset_copy(domain, &temp);
821 		needed = 0;
822 		error = cpuset_testupdate_domain(set, &temp, set->cs_domain,
823 		    &needed, 0);
824 		if (error)
825 			goto out;
826 		if (ndomains >= needed)
827 			break;
828 
829 		/* Dropping the lock; we'll need to re-evaluate again. */
830 		mtx_unlock_spin(&cpuset_lock);
831 		domainset_freelist_add(&domains, needed - ndomains);
832 		ndomains = needed;
833 		mtx_lock_spin(&cpuset_lock);
834 	}
835 	dset = set->cs_domain;
836 	cpuset_update_domain(set, domain, dset, &domains);
837 out:
838 	mtx_unlock_spin(&cpuset_lock);
839 	domainset_freelist_free(&domains);
840 	if (error == 0)
841 		domainset_notify();
842 
843 	return (error);
844 }
845 
846 /*
847  * Resolve the 'which' parameter of several cpuset apis.
848  *
849  * For WHICH_PID and WHICH_TID return a locked proc and valid proc/tid.  Also
850  * checks for permission via p_cansched().
851  *
852  * For WHICH_SET returns a valid set with a new reference.
853  *
854  * -1 may be supplied for any argument to mean the current proc/thread or
855  * the base set of the current thread.  May fail with ESRCH/EPERM.
856  */
857 int
858 cpuset_which(cpuwhich_t which, id_t id, struct proc **pp, struct thread **tdp,
859     struct cpuset **setp)
860 {
861 	struct cpuset *set;
862 	struct thread *td;
863 	struct proc *p;
864 	int error;
865 
866 	*pp = p = NULL;
867 	*tdp = td = NULL;
868 	*setp = set = NULL;
869 	switch (which) {
870 	case CPU_WHICH_PID:
871 		if (id == -1) {
872 			PROC_LOCK(curproc);
873 			p = curproc;
874 			break;
875 		}
876 		if ((p = pfind(id)) == NULL)
877 			return (ESRCH);
878 		break;
879 	case CPU_WHICH_TID:
880 		if (id == -1) {
881 			PROC_LOCK(curproc);
882 			p = curproc;
883 			td = curthread;
884 			break;
885 		}
886 		td = tdfind(id, -1);
887 		if (td == NULL)
888 			return (ESRCH);
889 		p = td->td_proc;
890 		break;
891 	case CPU_WHICH_CPUSET:
892 		if (id == -1) {
893 			thread_lock(curthread);
894 			set = cpuset_refbase(curthread->td_cpuset);
895 			thread_unlock(curthread);
896 		} else
897 			set = cpuset_lookup(id, curthread);
898 		if (set) {
899 			*setp = set;
900 			return (0);
901 		}
902 		return (ESRCH);
903 	case CPU_WHICH_JAIL:
904 	{
905 		/* Find `set' for prison with given id. */
906 		struct prison *pr;
907 
908 		sx_slock(&allprison_lock);
909 		pr = prison_find_child(curthread->td_ucred->cr_prison, id);
910 		sx_sunlock(&allprison_lock);
911 		if (pr == NULL)
912 			return (ESRCH);
913 		cpuset_ref(pr->pr_cpuset);
914 		*setp = pr->pr_cpuset;
915 		mtx_unlock(&pr->pr_mtx);
916 		return (0);
917 	}
918 	case CPU_WHICH_IRQ:
919 	case CPU_WHICH_DOMAIN:
920 		return (0);
921 	default:
922 		return (EINVAL);
923 	}
924 	error = p_cansched(curthread, p);
925 	if (error) {
926 		PROC_UNLOCK(p);
927 		return (error);
928 	}
929 	if (td == NULL)
930 		td = FIRST_THREAD_IN_PROC(p);
931 	*pp = p;
932 	*tdp = td;
933 	return (0);
934 }
935 
936 static int
937 cpuset_testshadow(struct cpuset *set, const cpuset_t *mask,
938     const struct domainset *domain)
939 {
940 	struct cpuset *parent;
941 	struct domainset *dset;
942 
943 	parent = cpuset_getbase(set);
944 	/*
945 	 * If we are restricting a cpu mask it must be a subset of the
946 	 * parent or invalid CPUs have been specified.
947 	 */
948 	if (mask != NULL && !CPU_SUBSET(&parent->cs_mask, mask))
949 		return (EINVAL);
950 
951 	/*
952 	 * If we are restricting a domain mask it must be a subset of the
953 	 * parent or invalid domains have been specified.
954 	 */
955 	dset = parent->cs_domain;
956 	if (domain != NULL && !domainset_valid(dset, domain))
957 		return (EINVAL);
958 
959 	return (0);
960 }
961 
962 /*
963  * Create an anonymous set with the provided mask in the space provided by
964  * 'nset'.  If the passed in set is anonymous we use its parent otherwise
965  * the new set is a child of 'set'.
966  */
967 static int
968 cpuset_shadow(struct cpuset *set, struct cpuset **nsetp,
969    const cpuset_t *mask, const struct domainset *domain,
970    struct setlist *cpusets, struct domainlist *domains)
971 {
972 	struct cpuset *parent;
973 	struct cpuset *nset;
974 	struct domainset *dset;
975 	struct domainset *d;
976 	int error;
977 
978 	error = cpuset_testshadow(set, mask, domain);
979 	if (error)
980 		return (error);
981 
982 	parent = cpuset_getbase(set);
983 	dset = parent->cs_domain;
984 	if (mask == NULL)
985 		mask = &set->cs_mask;
986 	if (domain != NULL)
987 		d = domainset_shadow(dset, domain, domains);
988 	else
989 		d = set->cs_domain;
990 	nset = LIST_FIRST(cpusets);
991 	error = cpuset_init(nset, parent, mask, d, CPUSET_INVALID);
992 	if (error == 0) {
993 		LIST_REMOVE(nset, cs_link);
994 		*nsetp = nset;
995 	}
996 	return (error);
997 }
998 
999 static struct cpuset *
1000 cpuset_update_thread(struct thread *td, struct cpuset *nset)
1001 {
1002 	struct cpuset *tdset;
1003 
1004 	tdset = td->td_cpuset;
1005 	td->td_cpuset = nset;
1006 	td->td_domain.dr_policy = nset->cs_domain;
1007 	sched_affinity(td);
1008 
1009 	return (tdset);
1010 }
1011 
1012 static int
1013 cpuset_setproc_test_maskthread(struct cpuset *tdset, cpuset_t *mask,
1014     struct domainset *domain)
1015 {
1016 	struct cpuset *parent;
1017 
1018 	parent = cpuset_getbase(tdset);
1019 	if (mask == NULL)
1020 		mask = &tdset->cs_mask;
1021 	if (domain == NULL)
1022 		domain = tdset->cs_domain;
1023 	return cpuset_testshadow(parent, mask, domain);
1024 }
1025 
1026 static int
1027 cpuset_setproc_maskthread(struct cpuset *tdset, cpuset_t *mask,
1028     struct domainset *domain, struct cpuset **nsetp,
1029     struct setlist *freelist, struct domainlist *domainlist)
1030 {
1031 	struct cpuset *parent;
1032 
1033 	parent = cpuset_getbase(tdset);
1034 	if (mask == NULL)
1035 		mask = &tdset->cs_mask;
1036 	if (domain == NULL)
1037 		domain = tdset->cs_domain;
1038 	return cpuset_shadow(parent, nsetp, mask, domain, freelist,
1039 	    domainlist);
1040 }
1041 
1042 static int
1043 cpuset_setproc_setthread_mask(struct cpuset *tdset, struct cpuset *set,
1044     cpuset_t *mask, struct domainset *domain)
1045 {
1046 	struct cpuset *parent;
1047 
1048 	parent = cpuset_getbase(tdset);
1049 
1050 	/*
1051 	 * If the thread restricted its mask then apply that same
1052 	 * restriction to the new set, otherwise take it wholesale.
1053 	 */
1054 	if (CPU_CMP(&tdset->cs_mask, &parent->cs_mask) != 0) {
1055 		CPU_COPY(&tdset->cs_mask, mask);
1056 		CPU_AND(mask, &set->cs_mask);
1057 	} else
1058 		CPU_COPY(&set->cs_mask, mask);
1059 
1060 	/*
1061 	 * If the thread restricted the domain then we apply the
1062 	 * restriction to the new set but retain the policy.
1063 	 */
1064 	if (tdset->cs_domain != parent->cs_domain) {
1065 		domainset_copy(tdset->cs_domain, domain);
1066 		DOMAINSET_AND(&domain->ds_mask, &set->cs_domain->ds_mask);
1067 	} else
1068 		domainset_copy(set->cs_domain, domain);
1069 
1070 	if (CPU_EMPTY(mask) || DOMAINSET_EMPTY(&domain->ds_mask))
1071 		return (EDEADLK);
1072 
1073 	return (0);
1074 }
1075 
1076 static int
1077 cpuset_setproc_test_setthread(struct cpuset *tdset, struct cpuset *set)
1078 {
1079 	struct domainset domain;
1080 	cpuset_t mask;
1081 
1082 	if (tdset->cs_id != CPUSET_INVALID)
1083 		return (0);
1084 	return cpuset_setproc_setthread_mask(tdset, set, &mask, &domain);
1085 }
1086 
1087 static int
1088 cpuset_setproc_setthread(struct cpuset *tdset, struct cpuset *set,
1089     struct cpuset **nsetp, struct setlist *freelist,
1090     struct domainlist *domainlist)
1091 {
1092 	struct domainset domain;
1093 	cpuset_t mask;
1094 	int error;
1095 
1096 	/*
1097 	 * If we're replacing on a thread that has not constrained the
1098 	 * original set we can simply accept the new set.
1099 	 */
1100 	if (tdset->cs_id != CPUSET_INVALID) {
1101 		*nsetp = cpuset_ref(set);
1102 		return (0);
1103 	}
1104 	error = cpuset_setproc_setthread_mask(tdset, set, &mask, &domain);
1105 	if (error)
1106 		return (error);
1107 
1108 	return cpuset_shadow(set, nsetp, &mask, &domain, freelist,
1109 	    domainlist);
1110 }
1111 
1112 static int
1113 cpuset_setproc_newbase(struct thread *td, struct cpuset *set,
1114     struct cpuset *nroot, struct cpuset **nsetp,
1115     struct setlist *cpusets, struct domainlist *domainlist)
1116 {
1117 	struct domainset ndomain;
1118 	cpuset_t nmask;
1119 	struct cpuset *pbase;
1120 	int error;
1121 
1122 	pbase = cpuset_getbase(td->td_cpuset);
1123 
1124 	/* Copy process mask, then further apply the new root mask. */
1125 	CPU_COPY(&pbase->cs_mask, &nmask);
1126 	CPU_AND(&nmask, &nroot->cs_mask);
1127 
1128 	domainset_copy(pbase->cs_domain, &ndomain);
1129 	DOMAINSET_AND(&ndomain.ds_mask, &set->cs_domain->ds_mask);
1130 
1131 	/* Policy is too restrictive, will not work. */
1132 	if (CPU_EMPTY(&nmask) || DOMAINSET_EMPTY(&ndomain.ds_mask))
1133 		return (EDEADLK);
1134 
1135 	/*
1136 	 * Remove pbase from the freelist in advance, it'll be pushed to
1137 	 * cpuset_ids on success.  We assume here that cpuset_create() will not
1138 	 * touch pbase on failure, and we just enqueue it back to the freelist
1139 	 * to remain in a consistent state.
1140 	 */
1141 	pbase = LIST_FIRST(cpusets);
1142 	LIST_REMOVE(pbase, cs_link);
1143 	error = cpuset_create(&pbase, set, &nmask);
1144 	if (error != 0) {
1145 		LIST_INSERT_HEAD(cpusets, pbase, cs_link);
1146 		return (error);
1147 	}
1148 
1149 	/* Duplicates some work from above... oh well. */
1150 	pbase->cs_domain = domainset_shadow(set->cs_domain, &ndomain,
1151 	    domainlist);
1152 	*nsetp = pbase;
1153 	return (0);
1154 }
1155 
1156 /*
1157  * Handle four cases for updating an entire process.
1158  *
1159  * 1) Set is non-null and the process is not rebasing onto a new root.  This
1160  *    reparents all anonymous sets to the provided set and replaces all
1161  *    non-anonymous td_cpusets with the provided set.
1162  * 2) Set is non-null and the process is rebasing onto a new root.  This
1163  *    creates a new base set if the process previously had its own base set,
1164  *    then reparents all anonymous sets either to that set or the provided set
1165  *    if one was not created.  Non-anonymous sets are similarly replaced.
1166  * 3) Mask is non-null.  This replaces or creates anonymous sets for every
1167  *    thread with the existing base as a parent.
1168  * 4) domain is non-null.  This creates anonymous sets for every thread
1169  *    and replaces the domain set.
1170  *
1171  * This is overly complicated because we can't allocate while holding a
1172  * spinlock and spinlocks must be held while changing and examining thread
1173  * state.
1174  */
1175 static int
1176 cpuset_setproc(pid_t pid, struct cpuset *set, cpuset_t *mask,
1177     struct domainset *domain, bool rebase)
1178 {
1179 	struct setlist freelist;
1180 	struct setlist droplist;
1181 	struct domainlist domainlist;
1182 	struct cpuset *base, *nset, *nroot, *tdroot;
1183 	struct thread *td;
1184 	struct proc *p;
1185 	int needed;
1186 	int nfree;
1187 	int error;
1188 
1189 	/*
1190 	 * The algorithm requires two passes due to locking considerations.
1191 	 *
1192 	 * 1) Lookup the process and acquire the locks in the required order.
1193 	 * 2) If enough cpusets have not been allocated release the locks and
1194 	 *    allocate them.  Loop.
1195 	 */
1196 	cpuset_freelist_init(&freelist, 1);
1197 	domainset_freelist_init(&domainlist, 1);
1198 	nfree = 1;
1199 	LIST_INIT(&droplist);
1200 	nfree = 0;
1201 	base = set;
1202 	nroot = NULL;
1203 	if (set != NULL)
1204 		nroot = cpuset_getroot(set);
1205 	for (;;) {
1206 		error = cpuset_which(CPU_WHICH_PID, pid, &p, &td, &nset);
1207 		if (error)
1208 			goto out;
1209 		tdroot = cpuset_getroot(td->td_cpuset);
1210 		needed = p->p_numthreads;
1211 		if (set != NULL && rebase && tdroot != nroot)
1212 			needed++;
1213 		if (nfree >= needed)
1214 			break;
1215 		PROC_UNLOCK(p);
1216 		if (nfree < needed) {
1217 			cpuset_freelist_add(&freelist, needed - nfree);
1218 			domainset_freelist_add(&domainlist, needed - nfree);
1219 			nfree = needed;
1220 		}
1221 	}
1222 	PROC_LOCK_ASSERT(p, MA_OWNED);
1223 
1224 	/*
1225 	 * If we're changing roots and the root set is what has been specified
1226 	 * as the parent, then we'll check if the process was previously using
1227 	 * the root set and, if it wasn't, create a new base with the process's
1228 	 * mask applied to it.
1229 	 */
1230 	if (set != NULL && rebase && nroot != tdroot) {
1231 		cpusetid_t base_id, root_id;
1232 
1233 		root_id = td->td_ucred->cr_prison->pr_cpuset->cs_id;
1234 		base_id = cpuset_getbase(td->td_cpuset)->cs_id;
1235 
1236 		if (base_id != root_id) {
1237 			error = cpuset_setproc_newbase(td, set, nroot, &base,
1238 			    &freelist, &domainlist);
1239 			if (error != 0)
1240 				goto unlock_out;
1241 		}
1242 	}
1243 
1244 	/*
1245 	 * Now that the appropriate locks are held and we have enough cpusets,
1246 	 * make sure the operation will succeed before applying changes. The
1247 	 * proc lock prevents td_cpuset from changing between calls.
1248 	 */
1249 	error = 0;
1250 	FOREACH_THREAD_IN_PROC(p, td) {
1251 		thread_lock(td);
1252 		if (set != NULL)
1253 			error = cpuset_setproc_test_setthread(td->td_cpuset,
1254 			    base);
1255 		else
1256 			error = cpuset_setproc_test_maskthread(td->td_cpuset,
1257 			    mask, domain);
1258 		thread_unlock(td);
1259 		if (error)
1260 			goto unlock_out;
1261 	}
1262 	/*
1263 	 * Replace each thread's cpuset while using deferred release.  We
1264 	 * must do this because the thread lock must be held while operating
1265 	 * on the thread and this limits the type of operations allowed.
1266 	 */
1267 	FOREACH_THREAD_IN_PROC(p, td) {
1268 		thread_lock(td);
1269 		if (set != NULL)
1270 			error = cpuset_setproc_setthread(td->td_cpuset, base,
1271 			    &nset, &freelist, &domainlist);
1272 		else
1273 			error = cpuset_setproc_maskthread(td->td_cpuset, mask,
1274 			    domain, &nset, &freelist, &domainlist);
1275 		if (error) {
1276 			thread_unlock(td);
1277 			break;
1278 		}
1279 		cpuset_rel_defer(&droplist, cpuset_update_thread(td, nset));
1280 		thread_unlock(td);
1281 	}
1282 unlock_out:
1283 	PROC_UNLOCK(p);
1284 out:
1285 	if (base != NULL && base != set)
1286 		cpuset_rel(base);
1287 	while ((nset = LIST_FIRST(&droplist)) != NULL)
1288 		cpuset_rel_complete(nset);
1289 	cpuset_freelist_free(&freelist);
1290 	domainset_freelist_free(&domainlist);
1291 	return (error);
1292 }
1293 
1294 static int
1295 bitset_strprint(char *buf, size_t bufsiz, const struct bitset *set, int setlen)
1296 {
1297 	size_t bytes;
1298 	int i, once;
1299 	char *p;
1300 
1301 	once = 0;
1302 	p = buf;
1303 	for (i = 0; i < __bitset_words(setlen); i++) {
1304 		if (once != 0) {
1305 			if (bufsiz < 1)
1306 				return (0);
1307 			*p = ',';
1308 			p++;
1309 			bufsiz--;
1310 		} else
1311 			once = 1;
1312 		if (bufsiz < sizeof(__STRING(ULONG_MAX)))
1313 			return (0);
1314 		bytes = snprintf(p, bufsiz, "%lx", set->__bits[i]);
1315 		p += bytes;
1316 		bufsiz -= bytes;
1317 	}
1318 	return (p - buf);
1319 }
1320 
1321 static int
1322 bitset_strscan(struct bitset *set, int setlen, const char *buf)
1323 {
1324 	int i, ret;
1325 	const char *p;
1326 
1327 	BIT_ZERO(setlen, set);
1328 	p = buf;
1329 	for (i = 0; i < __bitset_words(setlen); i++) {
1330 		if (*p == ',') {
1331 			p++;
1332 			continue;
1333 		}
1334 		ret = sscanf(p, "%lx", &set->__bits[i]);
1335 		if (ret == 0 || ret == -1)
1336 			break;
1337 		while (isxdigit(*p))
1338 			p++;
1339 	}
1340 	return (p - buf);
1341 }
1342 
1343 /*
1344  * Return a string representing a valid layout for a cpuset_t object.
1345  * It expects an incoming buffer at least sized as CPUSETBUFSIZ.
1346  */
1347 char *
1348 cpusetobj_strprint(char *buf, const cpuset_t *set)
1349 {
1350 
1351 	bitset_strprint(buf, CPUSETBUFSIZ, (const struct bitset *)set,
1352 	    CPU_SETSIZE);
1353 	return (buf);
1354 }
1355 
1356 /*
1357  * Build a valid cpuset_t object from a string representation.
1358  * It expects an incoming buffer at least sized as CPUSETBUFSIZ.
1359  */
1360 int
1361 cpusetobj_strscan(cpuset_t *set, const char *buf)
1362 {
1363 	char p;
1364 
1365 	if (strlen(buf) > CPUSETBUFSIZ - 1)
1366 		return (-1);
1367 
1368 	p = buf[bitset_strscan((struct bitset *)set, CPU_SETSIZE, buf)];
1369 	if (p != '\0')
1370 		return (-1);
1371 
1372 	return (0);
1373 }
1374 
1375 /*
1376  * Handle a domainset specifier in the sysctl tree.  A poiner to a pointer to
1377  * a domainset is in arg1.  If the user specifies a valid domainset the
1378  * pointer is updated.
1379  *
1380  * Format is:
1381  * hex mask word 0,hex mask word 1,...:decimal policy:decimal preferred
1382  */
1383 int
1384 sysctl_handle_domainset(SYSCTL_HANDLER_ARGS)
1385 {
1386 	char buf[DOMAINSETBUFSIZ];
1387 	struct domainset *dset;
1388 	struct domainset key;
1389 	int policy, prefer, error;
1390 	char *p;
1391 
1392 	dset = *(struct domainset **)arg1;
1393 	error = 0;
1394 
1395 	if (dset != NULL) {
1396 		p = buf + bitset_strprint(buf, DOMAINSETBUFSIZ,
1397 		    (const struct bitset *)&dset->ds_mask, DOMAINSET_SETSIZE);
1398 		sprintf(p, ":%d:%d", dset->ds_policy, dset->ds_prefer);
1399 	} else
1400 		sprintf(buf, "<NULL>");
1401 	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
1402 	if (error != 0 || req->newptr == NULL)
1403 		return (error);
1404 
1405 	/*
1406 	 * Read in and validate the string.
1407 	 */
1408 	memset(&key, 0, sizeof(key));
1409 	p = &buf[bitset_strscan((struct bitset *)&key.ds_mask,
1410 	    DOMAINSET_SETSIZE, buf)];
1411 	if (p == buf)
1412 		return (EINVAL);
1413 	if (sscanf(p, ":%d:%d", &policy, &prefer) != 2)
1414 		return (EINVAL);
1415 	key.ds_policy = policy;
1416 	key.ds_prefer = prefer;
1417 
1418 	/* Domainset_create() validates the policy.*/
1419 	dset = domainset_create(&key);
1420 	if (dset == NULL)
1421 		return (EINVAL);
1422 	*(struct domainset **)arg1 = dset;
1423 
1424 	return (error);
1425 }
1426 
1427 /*
1428  * Apply an anonymous mask or a domain to a single thread.
1429  */
1430 static int
1431 _cpuset_setthread(lwpid_t id, cpuset_t *mask, struct domainset *domain)
1432 {
1433 	struct setlist cpusets;
1434 	struct domainlist domainlist;
1435 	struct cpuset *nset;
1436 	struct cpuset *set;
1437 	struct thread *td;
1438 	struct proc *p;
1439 	int error;
1440 
1441 	cpuset_freelist_init(&cpusets, 1);
1442 	domainset_freelist_init(&domainlist, domain != NULL);
1443 	error = cpuset_which(CPU_WHICH_TID, id, &p, &td, &set);
1444 	if (error)
1445 		goto out;
1446 	set = NULL;
1447 	thread_lock(td);
1448 	error = cpuset_shadow(td->td_cpuset, &nset, mask, domain,
1449 	    &cpusets, &domainlist);
1450 	if (error == 0)
1451 		set = cpuset_update_thread(td, nset);
1452 	thread_unlock(td);
1453 	PROC_UNLOCK(p);
1454 	if (set)
1455 		cpuset_rel(set);
1456 out:
1457 	cpuset_freelist_free(&cpusets);
1458 	domainset_freelist_free(&domainlist);
1459 	return (error);
1460 }
1461 
1462 /*
1463  * Apply an anonymous mask to a single thread.
1464  */
1465 int
1466 cpuset_setthread(lwpid_t id, cpuset_t *mask)
1467 {
1468 
1469 	return _cpuset_setthread(id, mask, NULL);
1470 }
1471 
1472 /*
1473  * Apply new cpumask to the ithread.
1474  */
1475 int
1476 cpuset_setithread(lwpid_t id, int cpu)
1477 {
1478 	cpuset_t mask;
1479 
1480 	CPU_ZERO(&mask);
1481 	if (cpu == NOCPU)
1482 		CPU_COPY(cpuset_root, &mask);
1483 	else
1484 		CPU_SET(cpu, &mask);
1485 	return _cpuset_setthread(id, &mask, NULL);
1486 }
1487 
1488 /*
1489  * Initialize static domainsets after NUMA information is available.  This is
1490  * called before memory allocators are initialized.
1491  */
1492 void
1493 domainset_init(void)
1494 {
1495 	struct domainset *dset;
1496 	int i;
1497 
1498 	dset = &domainset_roundrobin;
1499 	DOMAINSET_COPY(&all_domains, &dset->ds_mask);
1500 	dset->ds_policy = DOMAINSET_POLICY_ROUNDROBIN;
1501 	dset->ds_prefer = -1;
1502 	_domainset_create(dset, NULL);
1503 
1504 	for (i = 0; i < vm_ndomains; i++) {
1505 		dset = &domainset_fixed[i];
1506 		DOMAINSET_ZERO(&dset->ds_mask);
1507 		DOMAINSET_SET(i, &dset->ds_mask);
1508 		dset->ds_policy = DOMAINSET_POLICY_ROUNDROBIN;
1509 		_domainset_create(dset, NULL);
1510 
1511 		dset = &domainset_prefer[i];
1512 		DOMAINSET_COPY(&all_domains, &dset->ds_mask);
1513 		dset->ds_policy = DOMAINSET_POLICY_PREFER;
1514 		dset->ds_prefer = i;
1515 		_domainset_create(dset, NULL);
1516 	}
1517 }
1518 
1519 /*
1520  * Create the domainset for cpuset 0, 1 and cpuset 2.
1521  */
1522 void
1523 domainset_zero(void)
1524 {
1525 	struct domainset *dset, *tmp;
1526 
1527 	mtx_init(&cpuset_lock, "cpuset", NULL, MTX_SPIN | MTX_RECURSE);
1528 
1529 	dset = &domainset0;
1530 	DOMAINSET_COPY(&all_domains, &dset->ds_mask);
1531 	dset->ds_policy = DOMAINSET_POLICY_FIRSTTOUCH;
1532 	dset->ds_prefer = -1;
1533 	curthread->td_domain.dr_policy = _domainset_create(dset, NULL);
1534 
1535 	domainset_copy(dset, &domainset2);
1536 	domainset2.ds_policy = DOMAINSET_POLICY_INTERLEAVE;
1537 	kernel_object->domain.dr_policy = _domainset_create(&domainset2, NULL);
1538 
1539 	/* Remove empty domains from the global policies. */
1540 	LIST_FOREACH_SAFE(dset, &cpuset_domains, ds_link, tmp)
1541 		if (domainset_empty_vm(dset))
1542 			LIST_REMOVE(dset, ds_link);
1543 }
1544 
1545 /*
1546  * Creates system-wide cpusets and the cpuset for thread0 including three
1547  * sets:
1548  *
1549  * 0 - The root set which should represent all valid processors in the
1550  *     system.  This set is immutable.
1551  * 1 - The default set which all processes are a member of until changed.
1552  *     This allows an administrator to move all threads off of given cpus to
1553  *     dedicate them to high priority tasks or save power etc.
1554  * 2 - The kernel set which allows restriction and policy to be applied only
1555  *     to kernel threads and the kernel_object.
1556  */
1557 struct cpuset *
1558 cpuset_thread0(void)
1559 {
1560 	struct cpuset *set;
1561 	int i;
1562 	int error __unused;
1563 
1564 	cpuset_zone = uma_zcreate("cpuset", sizeof(struct cpuset), NULL, NULL,
1565 	    NULL, NULL, UMA_ALIGN_CACHE, 0);
1566 	domainset_zone = uma_zcreate("domainset", sizeof(struct domainset),
1567 	    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
1568 
1569 	/*
1570 	 * Create the root system set (0) for the whole machine.  Doesn't use
1571 	 * cpuset_create() due to NULL parent.
1572 	 */
1573 	set = uma_zalloc(cpuset_zone, M_WAITOK | M_ZERO);
1574 	CPU_COPY(&all_cpus, &set->cs_mask);
1575 	LIST_INIT(&set->cs_children);
1576 	LIST_INSERT_HEAD(&cpuset_ids, set, cs_link);
1577 	refcount_init(&set->cs_ref, 1);
1578 	set->cs_flags = CPU_SET_ROOT | CPU_SET_RDONLY;
1579 	set->cs_domain = &domainset0;
1580 	cpuset_zero = set;
1581 	cpuset_root = &set->cs_mask;
1582 
1583 	/*
1584 	 * Now derive a default (1), modifiable set from that to give out.
1585 	 */
1586 	set = uma_zalloc(cpuset_zone, M_WAITOK | M_ZERO);
1587 	error = cpuset_init(set, cpuset_zero, NULL, NULL, 1);
1588 	KASSERT(error == 0, ("Error creating default set: %d\n", error));
1589 	cpuset_default = set;
1590 	/*
1591 	 * Create the kernel set (2).
1592 	 */
1593 	set = uma_zalloc(cpuset_zone, M_WAITOK | M_ZERO);
1594 	error = cpuset_init(set, cpuset_zero, NULL, NULL, 2);
1595 	KASSERT(error == 0, ("Error creating kernel set: %d\n", error));
1596 	set->cs_domain = &domainset2;
1597 	cpuset_kernel = set;
1598 
1599 	/*
1600 	 * Initialize the unit allocator. 0 and 1 are allocated above.
1601 	 */
1602 	cpuset_unr = new_unrhdr(3, INT_MAX, NULL);
1603 
1604 	/*
1605 	 * If MD code has not initialized per-domain cpusets, place all
1606 	 * CPUs in domain 0.
1607 	 */
1608 	for (i = 0; i < MAXMEMDOM; i++)
1609 		if (!CPU_EMPTY(&cpuset_domain[i]))
1610 			goto domains_set;
1611 	CPU_COPY(&all_cpus, &cpuset_domain[0]);
1612 domains_set:
1613 
1614 	return (cpuset_default);
1615 }
1616 
1617 void
1618 cpuset_kernthread(struct thread *td)
1619 {
1620 	struct cpuset *set;
1621 
1622 	thread_lock(td);
1623 	set = td->td_cpuset;
1624 	td->td_cpuset = cpuset_ref(cpuset_kernel);
1625 	thread_unlock(td);
1626 	cpuset_rel(set);
1627 }
1628 
1629 /*
1630  * Create a cpuset, which would be cpuset_create() but
1631  * mark the new 'set' as root.
1632  *
1633  * We are not going to reparent the td to it.  Use cpuset_setproc_update_set()
1634  * for that.
1635  *
1636  * In case of no error, returns the set in *setp locked with a reference.
1637  */
1638 int
1639 cpuset_create_root(struct prison *pr, struct cpuset **setp)
1640 {
1641 	struct cpuset *set;
1642 	int error;
1643 
1644 	KASSERT(pr != NULL, ("[%s:%d] invalid pr", __func__, __LINE__));
1645 	KASSERT(setp != NULL, ("[%s:%d] invalid setp", __func__, __LINE__));
1646 
1647 	set = NULL;
1648 	error = cpuset_create(&set, pr->pr_cpuset, &pr->pr_cpuset->cs_mask);
1649 	if (error)
1650 		return (error);
1651 
1652 	KASSERT(set != NULL, ("[%s:%d] cpuset_create returned invalid data",
1653 	    __func__, __LINE__));
1654 
1655 	/* Mark the set as root. */
1656 	set->cs_flags |= CPU_SET_ROOT;
1657 	*setp = set;
1658 
1659 	return (0);
1660 }
1661 
1662 int
1663 cpuset_setproc_update_set(struct proc *p, struct cpuset *set)
1664 {
1665 	int error;
1666 
1667 	KASSERT(p != NULL, ("[%s:%d] invalid proc", __func__, __LINE__));
1668 	KASSERT(set != NULL, ("[%s:%d] invalid set", __func__, __LINE__));
1669 
1670 	cpuset_ref(set);
1671 	error = cpuset_setproc(p->p_pid, set, NULL, NULL, true);
1672 	if (error)
1673 		return (error);
1674 	cpuset_rel(set);
1675 	return (0);
1676 }
1677 
1678 /*
1679  * In Capability mode, the only accesses that are permitted are to the current
1680  * thread and process' CPU and domain sets.
1681  */
1682 static int
1683 cpuset_check_capabilities(struct thread *td, cpulevel_t level, cpuwhich_t which,
1684     id_t id)
1685 {
1686 	if (IN_CAPABILITY_MODE(td)) {
1687 		if (level != CPU_LEVEL_WHICH)
1688 			return (ECAPMODE);
1689 		if (which != CPU_WHICH_TID && which != CPU_WHICH_PID)
1690 			return (ECAPMODE);
1691 		if (id != -1 &&
1692 		    !(which == CPU_WHICH_TID && id == td->td_tid) &&
1693 		    !(which == CPU_WHICH_PID && id == td->td_proc->p_pid))
1694 			return (ECAPMODE);
1695 	}
1696 	return (0);
1697 }
1698 
1699 #ifndef _SYS_SYSPROTO_H_
1700 struct cpuset_args {
1701 	cpusetid_t	*setid;
1702 };
1703 #endif
1704 int
1705 sys_cpuset(struct thread *td, struct cpuset_args *uap)
1706 {
1707 	struct cpuset *root;
1708 	struct cpuset *set;
1709 	int error;
1710 
1711 	thread_lock(td);
1712 	root = cpuset_refroot(td->td_cpuset);
1713 	thread_unlock(td);
1714 	set = NULL;
1715 	error = cpuset_create(&set, root, &root->cs_mask);
1716 	cpuset_rel(root);
1717 	if (error)
1718 		return (error);
1719 	error = copyout(&set->cs_id, uap->setid, sizeof(set->cs_id));
1720 	if (error == 0)
1721 		error = cpuset_setproc(-1, set, NULL, NULL, false);
1722 	cpuset_rel(set);
1723 	return (error);
1724 }
1725 
1726 #ifndef _SYS_SYSPROTO_H_
1727 struct cpuset_setid_args {
1728 	cpuwhich_t	which;
1729 	id_t		id;
1730 	cpusetid_t	setid;
1731 };
1732 #endif
1733 int
1734 sys_cpuset_setid(struct thread *td, struct cpuset_setid_args *uap)
1735 {
1736 
1737 	return (kern_cpuset_setid(td, uap->which, uap->id, uap->setid));
1738 }
1739 
1740 int
1741 kern_cpuset_setid(struct thread *td, cpuwhich_t which,
1742     id_t id, cpusetid_t setid)
1743 {
1744 	struct cpuset *set;
1745 	int error;
1746 
1747 	/*
1748 	 * Presently we only support per-process sets.
1749 	 */
1750 	if (which != CPU_WHICH_PID)
1751 		return (EINVAL);
1752 	set = cpuset_lookup(setid, td);
1753 	if (set == NULL)
1754 		return (ESRCH);
1755 	error = cpuset_setproc(id, set, NULL, NULL, false);
1756 	cpuset_rel(set);
1757 	return (error);
1758 }
1759 
1760 #ifndef _SYS_SYSPROTO_H_
1761 struct cpuset_getid_args {
1762 	cpulevel_t	level;
1763 	cpuwhich_t	which;
1764 	id_t		id;
1765 	cpusetid_t	*setid;
1766 };
1767 #endif
1768 int
1769 sys_cpuset_getid(struct thread *td, struct cpuset_getid_args *uap)
1770 {
1771 
1772 	return (kern_cpuset_getid(td, uap->level, uap->which, uap->id,
1773 	    uap->setid));
1774 }
1775 
1776 int
1777 kern_cpuset_getid(struct thread *td, cpulevel_t level, cpuwhich_t which,
1778     id_t id, cpusetid_t *setid)
1779 {
1780 	struct cpuset *nset;
1781 	struct cpuset *set;
1782 	struct thread *ttd;
1783 	struct proc *p;
1784 	cpusetid_t tmpid;
1785 	int error;
1786 
1787 	if (level == CPU_LEVEL_WHICH && which != CPU_WHICH_CPUSET)
1788 		return (EINVAL);
1789 	error = cpuset_which(which, id, &p, &ttd, &set);
1790 	if (error)
1791 		return (error);
1792 	switch (which) {
1793 	case CPU_WHICH_TID:
1794 	case CPU_WHICH_PID:
1795 		thread_lock(ttd);
1796 		set = cpuset_refbase(ttd->td_cpuset);
1797 		thread_unlock(ttd);
1798 		PROC_UNLOCK(p);
1799 		break;
1800 	case CPU_WHICH_CPUSET:
1801 	case CPU_WHICH_JAIL:
1802 		break;
1803 	case CPU_WHICH_IRQ:
1804 	case CPU_WHICH_DOMAIN:
1805 		return (EINVAL);
1806 	}
1807 	switch (level) {
1808 	case CPU_LEVEL_ROOT:
1809 		nset = cpuset_refroot(set);
1810 		cpuset_rel(set);
1811 		set = nset;
1812 		break;
1813 	case CPU_LEVEL_CPUSET:
1814 		break;
1815 	case CPU_LEVEL_WHICH:
1816 		break;
1817 	}
1818 	tmpid = set->cs_id;
1819 	cpuset_rel(set);
1820 	if (error == 0)
1821 		error = copyout(&tmpid, setid, sizeof(tmpid));
1822 
1823 	return (error);
1824 }
1825 
1826 #ifndef _SYS_SYSPROTO_H_
1827 struct cpuset_getaffinity_args {
1828 	cpulevel_t	level;
1829 	cpuwhich_t	which;
1830 	id_t		id;
1831 	size_t		cpusetsize;
1832 	cpuset_t	*mask;
1833 };
1834 #endif
1835 int
1836 sys_cpuset_getaffinity(struct thread *td, struct cpuset_getaffinity_args *uap)
1837 {
1838 
1839 	return (kern_cpuset_getaffinity(td, uap->level, uap->which,
1840 	    uap->id, uap->cpusetsize, uap->mask));
1841 }
1842 
1843 int
1844 kern_cpuset_getaffinity(struct thread *td, cpulevel_t level, cpuwhich_t which,
1845     id_t id, size_t cpusetsize, cpuset_t *maskp)
1846 {
1847 	struct thread *ttd;
1848 	struct cpuset *nset;
1849 	struct cpuset *set;
1850 	struct proc *p;
1851 	cpuset_t *mask;
1852 	int error;
1853 	size_t size;
1854 
1855 	if (cpusetsize < sizeof(cpuset_t) || cpusetsize > CPU_MAXSIZE / NBBY)
1856 		return (ERANGE);
1857 	error = cpuset_check_capabilities(td, level, which, id);
1858 	if (error != 0)
1859 		return (error);
1860 	size = cpusetsize;
1861 	mask = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
1862 	error = cpuset_which(which, id, &p, &ttd, &set);
1863 	if (error)
1864 		goto out;
1865 	switch (level) {
1866 	case CPU_LEVEL_ROOT:
1867 	case CPU_LEVEL_CPUSET:
1868 		switch (which) {
1869 		case CPU_WHICH_TID:
1870 		case CPU_WHICH_PID:
1871 			thread_lock(ttd);
1872 			set = cpuset_ref(ttd->td_cpuset);
1873 			thread_unlock(ttd);
1874 			break;
1875 		case CPU_WHICH_CPUSET:
1876 		case CPU_WHICH_JAIL:
1877 			break;
1878 		case CPU_WHICH_IRQ:
1879 		case CPU_WHICH_INTRHANDLER:
1880 		case CPU_WHICH_ITHREAD:
1881 		case CPU_WHICH_DOMAIN:
1882 			error = EINVAL;
1883 			goto out;
1884 		}
1885 		if (level == CPU_LEVEL_ROOT)
1886 			nset = cpuset_refroot(set);
1887 		else
1888 			nset = cpuset_refbase(set);
1889 		CPU_COPY(&nset->cs_mask, mask);
1890 		cpuset_rel(nset);
1891 		break;
1892 	case CPU_LEVEL_WHICH:
1893 		switch (which) {
1894 		case CPU_WHICH_TID:
1895 			thread_lock(ttd);
1896 			CPU_COPY(&ttd->td_cpuset->cs_mask, mask);
1897 			thread_unlock(ttd);
1898 			break;
1899 		case CPU_WHICH_PID:
1900 			FOREACH_THREAD_IN_PROC(p, ttd) {
1901 				thread_lock(ttd);
1902 				CPU_OR(mask, &ttd->td_cpuset->cs_mask);
1903 				thread_unlock(ttd);
1904 			}
1905 			break;
1906 		case CPU_WHICH_CPUSET:
1907 		case CPU_WHICH_JAIL:
1908 			CPU_COPY(&set->cs_mask, mask);
1909 			break;
1910 		case CPU_WHICH_IRQ:
1911 		case CPU_WHICH_INTRHANDLER:
1912 		case CPU_WHICH_ITHREAD:
1913 			error = intr_getaffinity(id, which, mask);
1914 			break;
1915 		case CPU_WHICH_DOMAIN:
1916 			if (id < 0 || id >= MAXMEMDOM)
1917 				error = ESRCH;
1918 			else
1919 				CPU_COPY(&cpuset_domain[id], mask);
1920 			break;
1921 		}
1922 		break;
1923 	default:
1924 		error = EINVAL;
1925 		break;
1926 	}
1927 	if (set)
1928 		cpuset_rel(set);
1929 	if (p)
1930 		PROC_UNLOCK(p);
1931 	if (error == 0)
1932 		error = copyout(mask, maskp, size);
1933 out:
1934 	free(mask, M_TEMP);
1935 	return (error);
1936 }
1937 
1938 #ifndef _SYS_SYSPROTO_H_
1939 struct cpuset_setaffinity_args {
1940 	cpulevel_t	level;
1941 	cpuwhich_t	which;
1942 	id_t		id;
1943 	size_t		cpusetsize;
1944 	const cpuset_t	*mask;
1945 };
1946 #endif
1947 int
1948 sys_cpuset_setaffinity(struct thread *td, struct cpuset_setaffinity_args *uap)
1949 {
1950 
1951 	return (kern_cpuset_setaffinity(td, uap->level, uap->which,
1952 	    uap->id, uap->cpusetsize, uap->mask));
1953 }
1954 
1955 int
1956 kern_cpuset_setaffinity(struct thread *td, cpulevel_t level, cpuwhich_t which,
1957     id_t id, size_t cpusetsize, const cpuset_t *maskp)
1958 {
1959 	struct cpuset *nset;
1960 	struct cpuset *set;
1961 	struct thread *ttd;
1962 	struct proc *p;
1963 	cpuset_t *mask;
1964 	int error;
1965 
1966 	if (cpusetsize < sizeof(cpuset_t) || cpusetsize > CPU_MAXSIZE / NBBY)
1967 		return (ERANGE);
1968 	error = cpuset_check_capabilities(td, level, which, id);
1969 	if (error != 0)
1970 		return (error);
1971 	mask = malloc(cpusetsize, M_TEMP, M_WAITOK | M_ZERO);
1972 	error = copyin(maskp, mask, cpusetsize);
1973 	if (error)
1974 		goto out;
1975 	/*
1976 	 * Verify that no high bits are set.
1977 	 */
1978 	if (cpusetsize > sizeof(cpuset_t)) {
1979 		char *end;
1980 		char *cp;
1981 
1982 		end = cp = (char *)&mask->__bits;
1983 		end += cpusetsize;
1984 		cp += sizeof(cpuset_t);
1985 		while (cp != end)
1986 			if (*cp++ != 0) {
1987 				error = EINVAL;
1988 				goto out;
1989 			}
1990 	}
1991 	switch (level) {
1992 	case CPU_LEVEL_ROOT:
1993 	case CPU_LEVEL_CPUSET:
1994 		error = cpuset_which(which, id, &p, &ttd, &set);
1995 		if (error)
1996 			break;
1997 		switch (which) {
1998 		case CPU_WHICH_TID:
1999 		case CPU_WHICH_PID:
2000 			thread_lock(ttd);
2001 			set = cpuset_ref(ttd->td_cpuset);
2002 			thread_unlock(ttd);
2003 			PROC_UNLOCK(p);
2004 			break;
2005 		case CPU_WHICH_CPUSET:
2006 		case CPU_WHICH_JAIL:
2007 			break;
2008 		case CPU_WHICH_IRQ:
2009 		case CPU_WHICH_INTRHANDLER:
2010 		case CPU_WHICH_ITHREAD:
2011 		case CPU_WHICH_DOMAIN:
2012 			error = EINVAL;
2013 			goto out;
2014 		}
2015 		if (level == CPU_LEVEL_ROOT)
2016 			nset = cpuset_refroot(set);
2017 		else
2018 			nset = cpuset_refbase(set);
2019 		error = cpuset_modify(nset, mask);
2020 		cpuset_rel(nset);
2021 		cpuset_rel(set);
2022 		break;
2023 	case CPU_LEVEL_WHICH:
2024 		switch (which) {
2025 		case CPU_WHICH_TID:
2026 			error = cpuset_setthread(id, mask);
2027 			break;
2028 		case CPU_WHICH_PID:
2029 			error = cpuset_setproc(id, NULL, mask, NULL, false);
2030 			break;
2031 		case CPU_WHICH_CPUSET:
2032 		case CPU_WHICH_JAIL:
2033 			error = cpuset_which(which, id, &p, &ttd, &set);
2034 			if (error == 0) {
2035 				error = cpuset_modify(set, mask);
2036 				cpuset_rel(set);
2037 			}
2038 			break;
2039 		case CPU_WHICH_IRQ:
2040 		case CPU_WHICH_INTRHANDLER:
2041 		case CPU_WHICH_ITHREAD:
2042 			error = intr_setaffinity(id, which, mask);
2043 			break;
2044 		default:
2045 			error = EINVAL;
2046 			break;
2047 		}
2048 		break;
2049 	default:
2050 		error = EINVAL;
2051 		break;
2052 	}
2053 out:
2054 	free(mask, M_TEMP);
2055 	return (error);
2056 }
2057 
2058 #ifndef _SYS_SYSPROTO_H_
2059 struct cpuset_getdomain_args {
2060 	cpulevel_t	level;
2061 	cpuwhich_t	which;
2062 	id_t		id;
2063 	size_t		domainsetsize;
2064 	domainset_t	*mask;
2065 	int 		*policy;
2066 };
2067 #endif
2068 int
2069 sys_cpuset_getdomain(struct thread *td, struct cpuset_getdomain_args *uap)
2070 {
2071 
2072 	return (kern_cpuset_getdomain(td, uap->level, uap->which,
2073 	    uap->id, uap->domainsetsize, uap->mask, uap->policy));
2074 }
2075 
2076 int
2077 kern_cpuset_getdomain(struct thread *td, cpulevel_t level, cpuwhich_t which,
2078     id_t id, size_t domainsetsize, domainset_t *maskp, int *policyp)
2079 {
2080 	struct domainset outset;
2081 	struct thread *ttd;
2082 	struct cpuset *nset;
2083 	struct cpuset *set;
2084 	struct domainset *dset;
2085 	struct proc *p;
2086 	domainset_t *mask;
2087 	int error;
2088 
2089 	if (domainsetsize < sizeof(domainset_t) ||
2090 	    domainsetsize > DOMAINSET_MAXSIZE / NBBY)
2091 		return (ERANGE);
2092 	error = cpuset_check_capabilities(td, level, which, id);
2093 	if (error != 0)
2094 		return (error);
2095 	mask = malloc(domainsetsize, M_TEMP, M_WAITOK | M_ZERO);
2096 	bzero(&outset, sizeof(outset));
2097 	error = cpuset_which(which, id, &p, &ttd, &set);
2098 	if (error)
2099 		goto out;
2100 	switch (level) {
2101 	case CPU_LEVEL_ROOT:
2102 	case CPU_LEVEL_CPUSET:
2103 		switch (which) {
2104 		case CPU_WHICH_TID:
2105 		case CPU_WHICH_PID:
2106 			thread_lock(ttd);
2107 			set = cpuset_ref(ttd->td_cpuset);
2108 			thread_unlock(ttd);
2109 			break;
2110 		case CPU_WHICH_CPUSET:
2111 		case CPU_WHICH_JAIL:
2112 			break;
2113 		case CPU_WHICH_IRQ:
2114 		case CPU_WHICH_INTRHANDLER:
2115 		case CPU_WHICH_ITHREAD:
2116 		case CPU_WHICH_DOMAIN:
2117 			error = EINVAL;
2118 			goto out;
2119 		}
2120 		if (level == CPU_LEVEL_ROOT)
2121 			nset = cpuset_refroot(set);
2122 		else
2123 			nset = cpuset_refbase(set);
2124 		domainset_copy(nset->cs_domain, &outset);
2125 		cpuset_rel(nset);
2126 		break;
2127 	case CPU_LEVEL_WHICH:
2128 		switch (which) {
2129 		case CPU_WHICH_TID:
2130 			thread_lock(ttd);
2131 			domainset_copy(ttd->td_cpuset->cs_domain, &outset);
2132 			thread_unlock(ttd);
2133 			break;
2134 		case CPU_WHICH_PID:
2135 			FOREACH_THREAD_IN_PROC(p, ttd) {
2136 				thread_lock(ttd);
2137 				dset = ttd->td_cpuset->cs_domain;
2138 				/* Show all domains in the proc. */
2139 				DOMAINSET_OR(&outset.ds_mask, &dset->ds_mask);
2140 				/* Last policy wins. */
2141 				outset.ds_policy = dset->ds_policy;
2142 				outset.ds_prefer = dset->ds_prefer;
2143 				thread_unlock(ttd);
2144 			}
2145 			break;
2146 		case CPU_WHICH_CPUSET:
2147 		case CPU_WHICH_JAIL:
2148 			domainset_copy(set->cs_domain, &outset);
2149 			break;
2150 		case CPU_WHICH_IRQ:
2151 		case CPU_WHICH_INTRHANDLER:
2152 		case CPU_WHICH_ITHREAD:
2153 		case CPU_WHICH_DOMAIN:
2154 			error = EINVAL;
2155 			break;
2156 		}
2157 		break;
2158 	default:
2159 		error = EINVAL;
2160 		break;
2161 	}
2162 	if (set)
2163 		cpuset_rel(set);
2164 	if (p)
2165 		PROC_UNLOCK(p);
2166 	/*
2167 	 * Translate prefer into a set containing only the preferred domain,
2168 	 * not the entire fallback set.
2169 	 */
2170 	if (outset.ds_policy == DOMAINSET_POLICY_PREFER) {
2171 		DOMAINSET_ZERO(&outset.ds_mask);
2172 		DOMAINSET_SET(outset.ds_prefer, &outset.ds_mask);
2173 	}
2174 	DOMAINSET_COPY(&outset.ds_mask, mask);
2175 	if (error == 0)
2176 		error = copyout(mask, maskp, domainsetsize);
2177 	if (error == 0)
2178 		if (suword32(policyp, outset.ds_policy) != 0)
2179 			error = EFAULT;
2180 out:
2181 	free(mask, M_TEMP);
2182 	return (error);
2183 }
2184 
2185 #ifndef _SYS_SYSPROTO_H_
2186 struct cpuset_setdomain_args {
2187 	cpulevel_t	level;
2188 	cpuwhich_t	which;
2189 	id_t		id;
2190 	size_t		domainsetsize;
2191 	domainset_t	*mask;
2192 	int 		policy;
2193 };
2194 #endif
2195 int
2196 sys_cpuset_setdomain(struct thread *td, struct cpuset_setdomain_args *uap)
2197 {
2198 
2199 	return (kern_cpuset_setdomain(td, uap->level, uap->which,
2200 	    uap->id, uap->domainsetsize, uap->mask, uap->policy));
2201 }
2202 
2203 int
2204 kern_cpuset_setdomain(struct thread *td, cpulevel_t level, cpuwhich_t which,
2205     id_t id, size_t domainsetsize, const domainset_t *maskp, int policy)
2206 {
2207 	struct cpuset *nset;
2208 	struct cpuset *set;
2209 	struct thread *ttd;
2210 	struct proc *p;
2211 	struct domainset domain;
2212 	domainset_t *mask;
2213 	int error;
2214 
2215 	if (domainsetsize < sizeof(domainset_t) ||
2216 	    domainsetsize > DOMAINSET_MAXSIZE / NBBY)
2217 		return (ERANGE);
2218 	if (policy <= DOMAINSET_POLICY_INVALID ||
2219 	    policy > DOMAINSET_POLICY_MAX)
2220 		return (EINVAL);
2221 	error = cpuset_check_capabilities(td, level, which, id);
2222 	if (error != 0)
2223 		return (error);
2224 	memset(&domain, 0, sizeof(domain));
2225 	mask = malloc(domainsetsize, M_TEMP, M_WAITOK | M_ZERO);
2226 	error = copyin(maskp, mask, domainsetsize);
2227 	if (error)
2228 		goto out;
2229 	/*
2230 	 * Verify that no high bits are set.
2231 	 */
2232 	if (domainsetsize > sizeof(domainset_t)) {
2233 		char *end;
2234 		char *cp;
2235 
2236 		end = cp = (char *)&mask->__bits;
2237 		end += domainsetsize;
2238 		cp += sizeof(domainset_t);
2239 		while (cp != end)
2240 			if (*cp++ != 0) {
2241 				error = EINVAL;
2242 				goto out;
2243 			}
2244 	}
2245 	DOMAINSET_COPY(mask, &domain.ds_mask);
2246 	domain.ds_policy = policy;
2247 
2248 	/*
2249 	 * Sanitize the provided mask.
2250 	 */
2251 	if (!DOMAINSET_SUBSET(&all_domains, &domain.ds_mask)) {
2252 		error = EINVAL;
2253 		goto out;
2254 	}
2255 
2256 	/* Translate preferred policy into a mask and fallback. */
2257 	if (policy == DOMAINSET_POLICY_PREFER) {
2258 		/* Only support a single preferred domain. */
2259 		if (DOMAINSET_COUNT(&domain.ds_mask) != 1) {
2260 			error = EINVAL;
2261 			goto out;
2262 		}
2263 		domain.ds_prefer = DOMAINSET_FFS(&domain.ds_mask) - 1;
2264 		/* This will be constrained by domainset_shadow(). */
2265 		DOMAINSET_COPY(&all_domains, &domain.ds_mask);
2266 	}
2267 
2268 	/*
2269 	 * When given an impossible policy, fall back to interleaving
2270 	 * across all domains.
2271 	 */
2272 	if (domainset_empty_vm(&domain))
2273 		domainset_copy(&domainset2, &domain);
2274 
2275 	switch (level) {
2276 	case CPU_LEVEL_ROOT:
2277 	case CPU_LEVEL_CPUSET:
2278 		error = cpuset_which(which, id, &p, &ttd, &set);
2279 		if (error)
2280 			break;
2281 		switch (which) {
2282 		case CPU_WHICH_TID:
2283 		case CPU_WHICH_PID:
2284 			thread_lock(ttd);
2285 			set = cpuset_ref(ttd->td_cpuset);
2286 			thread_unlock(ttd);
2287 			PROC_UNLOCK(p);
2288 			break;
2289 		case CPU_WHICH_CPUSET:
2290 		case CPU_WHICH_JAIL:
2291 			break;
2292 		case CPU_WHICH_IRQ:
2293 		case CPU_WHICH_INTRHANDLER:
2294 		case CPU_WHICH_ITHREAD:
2295 		case CPU_WHICH_DOMAIN:
2296 			error = EINVAL;
2297 			goto out;
2298 		}
2299 		if (level == CPU_LEVEL_ROOT)
2300 			nset = cpuset_refroot(set);
2301 		else
2302 			nset = cpuset_refbase(set);
2303 		error = cpuset_modify_domain(nset, &domain);
2304 		cpuset_rel(nset);
2305 		cpuset_rel(set);
2306 		break;
2307 	case CPU_LEVEL_WHICH:
2308 		switch (which) {
2309 		case CPU_WHICH_TID:
2310 			error = _cpuset_setthread(id, NULL, &domain);
2311 			break;
2312 		case CPU_WHICH_PID:
2313 			error = cpuset_setproc(id, NULL, NULL, &domain, false);
2314 			break;
2315 		case CPU_WHICH_CPUSET:
2316 		case CPU_WHICH_JAIL:
2317 			error = cpuset_which(which, id, &p, &ttd, &set);
2318 			if (error == 0) {
2319 				error = cpuset_modify_domain(set, &domain);
2320 				cpuset_rel(set);
2321 			}
2322 			break;
2323 		case CPU_WHICH_IRQ:
2324 		case CPU_WHICH_INTRHANDLER:
2325 		case CPU_WHICH_ITHREAD:
2326 		default:
2327 			error = EINVAL;
2328 			break;
2329 		}
2330 		break;
2331 	default:
2332 		error = EINVAL;
2333 		break;
2334 	}
2335 out:
2336 	free(mask, M_TEMP);
2337 	return (error);
2338 }
2339 
2340 #ifdef DDB
2341 
2342 static void
2343 ddb_display_bitset(const struct bitset *set, int size)
2344 {
2345 	int bit, once;
2346 
2347 	for (once = 0, bit = 0; bit < size; bit++) {
2348 		if (CPU_ISSET(bit, set)) {
2349 			if (once == 0) {
2350 				db_printf("%d", bit);
2351 				once = 1;
2352 			} else
2353 				db_printf(",%d", bit);
2354 		}
2355 	}
2356 	if (once == 0)
2357 		db_printf("<none>");
2358 }
2359 
2360 void
2361 ddb_display_cpuset(const cpuset_t *set)
2362 {
2363 	ddb_display_bitset((const struct bitset *)set, CPU_SETSIZE);
2364 }
2365 
2366 static void
2367 ddb_display_domainset(const domainset_t *set)
2368 {
2369 	ddb_display_bitset((const struct bitset *)set, DOMAINSET_SETSIZE);
2370 }
2371 
2372 DB_SHOW_COMMAND(cpusets, db_show_cpusets)
2373 {
2374 	struct cpuset *set;
2375 
2376 	LIST_FOREACH(set, &cpuset_ids, cs_link) {
2377 		db_printf("set=%p id=%-6u ref=%-6d flags=0x%04x parent id=%d\n",
2378 		    set, set->cs_id, refcount_load(&set->cs_ref), set->cs_flags,
2379 		    (set->cs_parent != NULL) ? set->cs_parent->cs_id : 0);
2380 		db_printf("  cpu mask=");
2381 		ddb_display_cpuset(&set->cs_mask);
2382 		db_printf("\n");
2383 		db_printf("  domain policy %d prefer %d mask=",
2384 		    set->cs_domain->ds_policy, set->cs_domain->ds_prefer);
2385 		ddb_display_domainset(&set->cs_domain->ds_mask);
2386 		db_printf("\n");
2387 		if (db_pager_quit)
2388 			break;
2389 	}
2390 }
2391 
2392 DB_SHOW_COMMAND(domainsets, db_show_domainsets)
2393 {
2394 	struct domainset *set;
2395 
2396 	LIST_FOREACH(set, &cpuset_domains, ds_link) {
2397 		db_printf("set=%p policy %d prefer %d cnt %d\n",
2398 		    set, set->ds_policy, set->ds_prefer, set->ds_cnt);
2399 		db_printf("  mask =");
2400 		ddb_display_domainset(&set->ds_mask);
2401 		db_printf("\n");
2402 	}
2403 }
2404 #endif /* DDB */
2405