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