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