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