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