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