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