15f399153a2e02bdfd659c9a0c0702295e497a9b
[linux-2.6-microblaze.git] / kernel / cgroup / cpuset.c
1 /*
2  *  kernel/cpuset.c
3  *
4  *  Processor and Memory placement constraints for sets of tasks.
5  *
6  *  Copyright (C) 2003 BULL SA.
7  *  Copyright (C) 2004-2007 Silicon Graphics, Inc.
8  *  Copyright (C) 2006 Google, Inc
9  *
10  *  Portions derived from Patrick Mochel's sysfs code.
11  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
12  *
13  *  2003-10-10 Written by Simon Derr.
14  *  2003-10-22 Updates by Stephen Hemminger.
15  *  2004 May-July Rework by Paul Jackson.
16  *  2006 Rework by Paul Menage to use generic cgroups
17  *  2008 Rework of the scheduler domains and CPU hotplug handling
18  *       by Max Krasnyansky
19  *
20  *  This file is subject to the terms and conditions of the GNU General Public
21  *  License.  See the file COPYING in the main directory of the Linux
22  *  distribution for more details.
23  */
24
25 #include <linux/cpu.h>
26 #include <linux/cpumask.h>
27 #include <linux/cpuset.h>
28 #include <linux/init.h>
29 #include <linux/interrupt.h>
30 #include <linux/kernel.h>
31 #include <linux/mempolicy.h>
32 #include <linux/mm.h>
33 #include <linux/memory.h>
34 #include <linux/export.h>
35 #include <linux/rcupdate.h>
36 #include <linux/sched.h>
37 #include <linux/sched/deadline.h>
38 #include <linux/sched/mm.h>
39 #include <linux/sched/task.h>
40 #include <linux/security.h>
41 #include <linux/spinlock.h>
42 #include <linux/oom.h>
43 #include <linux/sched/isolation.h>
44 #include <linux/cgroup.h>
45 #include <linux/wait.h>
46
47 DEFINE_STATIC_KEY_FALSE(cpusets_pre_enable_key);
48 DEFINE_STATIC_KEY_FALSE(cpusets_enabled_key);
49
50 /*
51  * There could be abnormal cpuset configurations for cpu or memory
52  * node binding, add this key to provide a quick low-cost judgment
53  * of the situation.
54  */
55 DEFINE_STATIC_KEY_FALSE(cpusets_insane_config_key);
56
57 /* See "Frequency meter" comments, below. */
58
59 struct fmeter {
60         int cnt;                /* unprocessed events count */
61         int val;                /* most recent output value */
62         time64_t time;          /* clock (secs) when val computed */
63         spinlock_t lock;        /* guards read or write of above */
64 };
65
66 /*
67  * Invalid partition error code
68  */
69 enum prs_errcode {
70         PERR_NONE = 0,
71         PERR_INVCPUS,
72         PERR_INVPARENT,
73         PERR_NOTPART,
74         PERR_NOTEXCL,
75         PERR_NOCPUS,
76         PERR_HOTPLUG,
77         PERR_CPUSEMPTY,
78         PERR_HKEEPING,
79 };
80
81 static const char * const perr_strings[] = {
82         [PERR_INVCPUS]   = "Invalid cpu list in cpuset.cpus.exclusive",
83         [PERR_INVPARENT] = "Parent is an invalid partition root",
84         [PERR_NOTPART]   = "Parent is not a partition root",
85         [PERR_NOTEXCL]   = "Cpu list in cpuset.cpus not exclusive",
86         [PERR_NOCPUS]    = "Parent unable to distribute cpu downstream",
87         [PERR_HOTPLUG]   = "No cpu available due to hotplug",
88         [PERR_CPUSEMPTY] = "cpuset.cpus is empty",
89         [PERR_HKEEPING]  = "partition config conflicts with housekeeping setup",
90 };
91
92 struct cpuset {
93         struct cgroup_subsys_state css;
94
95         unsigned long flags;            /* "unsigned long" so bitops work */
96
97         /*
98          * On default hierarchy:
99          *
100          * The user-configured masks can only be changed by writing to
101          * cpuset.cpus and cpuset.mems, and won't be limited by the
102          * parent masks.
103          *
104          * The effective masks is the real masks that apply to the tasks
105          * in the cpuset. They may be changed if the configured masks are
106          * changed or hotplug happens.
107          *
108          * effective_mask == configured_mask & parent's effective_mask,
109          * and if it ends up empty, it will inherit the parent's mask.
110          *
111          *
112          * On legacy hierarchy:
113          *
114          * The user-configured masks are always the same with effective masks.
115          */
116
117         /* user-configured CPUs and Memory Nodes allow to tasks */
118         cpumask_var_t cpus_allowed;
119         nodemask_t mems_allowed;
120
121         /* effective CPUs and Memory Nodes allow to tasks */
122         cpumask_var_t effective_cpus;
123         nodemask_t effective_mems;
124
125         /*
126          * Exclusive CPUs dedicated to current cgroup (default hierarchy only)
127          *
128          * This exclusive CPUs must be a subset of cpus_allowed. A parent
129          * cgroup can only grant exclusive CPUs to one of its children.
130          *
131          * When the cgroup becomes a valid partition root, effective_xcpus
132          * defaults to cpus_allowed if not set. The effective_cpus of a valid
133          * partition root comes solely from its effective_xcpus and some of the
134          * effective_xcpus may be distributed to sub-partitions below & hence
135          * excluded from its effective_cpus.
136          */
137         cpumask_var_t effective_xcpus;
138
139         /*
140          * Exclusive CPUs as requested by the user (default hierarchy only)
141          */
142         cpumask_var_t exclusive_cpus;
143
144         /*
145          * This is old Memory Nodes tasks took on.
146          *
147          * - top_cpuset.old_mems_allowed is initialized to mems_allowed.
148          * - A new cpuset's old_mems_allowed is initialized when some
149          *   task is moved into it.
150          * - old_mems_allowed is used in cpuset_migrate_mm() when we change
151          *   cpuset.mems_allowed and have tasks' nodemask updated, and
152          *   then old_mems_allowed is updated to mems_allowed.
153          */
154         nodemask_t old_mems_allowed;
155
156         struct fmeter fmeter;           /* memory_pressure filter */
157
158         /*
159          * Tasks are being attached to this cpuset.  Used to prevent
160          * zeroing cpus/mems_allowed between ->can_attach() and ->attach().
161          */
162         int attach_in_progress;
163
164         /* partition number for rebuild_sched_domains() */
165         int pn;
166
167         /* for custom sched domain */
168         int relax_domain_level;
169
170         /* number of valid sub-partitions */
171         int nr_subparts;
172
173         /* partition root state */
174         int partition_root_state;
175
176         /*
177          * Default hierarchy only:
178          * use_parent_ecpus - set if using parent's effective_cpus
179          * child_ecpus_count - # of children with use_parent_ecpus set
180          */
181         int use_parent_ecpus;
182         int child_ecpus_count;
183
184         /*
185          * number of SCHED_DEADLINE tasks attached to this cpuset, so that we
186          * know when to rebuild associated root domain bandwidth information.
187          */
188         int nr_deadline_tasks;
189         int nr_migrate_dl_tasks;
190         u64 sum_migrate_dl_bw;
191
192         /* Invalid partition error code, not lock protected */
193         enum prs_errcode prs_err;
194
195         /* Handle for cpuset.cpus.partition */
196         struct cgroup_file partition_file;
197
198         /* Remote partition silbling list anchored at remote_children */
199         struct list_head remote_sibling;
200 };
201
202 /*
203  * Exclusive CPUs distributed out to sub-partitions of top_cpuset
204  */
205 static cpumask_var_t    subpartitions_cpus;
206
207 /* List of remote partition root children */
208 static struct list_head remote_children;
209
210 /*
211  * Partition root states:
212  *
213  *   0 - member (not a partition root)
214  *   1 - partition root
215  *   2 - partition root without load balancing (isolated)
216  *  -1 - invalid partition root
217  *  -2 - invalid isolated partition root
218  */
219 #define PRS_MEMBER              0
220 #define PRS_ROOT                1
221 #define PRS_ISOLATED            2
222 #define PRS_INVALID_ROOT        -1
223 #define PRS_INVALID_ISOLATED    -2
224
225 static inline bool is_prs_invalid(int prs_state)
226 {
227         return prs_state < 0;
228 }
229
230 /*
231  * Temporary cpumasks for working with partitions that are passed among
232  * functions to avoid memory allocation in inner functions.
233  */
234 struct tmpmasks {
235         cpumask_var_t addmask, delmask; /* For partition root */
236         cpumask_var_t new_cpus;         /* For update_cpumasks_hier() */
237 };
238
239 static inline struct cpuset *css_cs(struct cgroup_subsys_state *css)
240 {
241         return css ? container_of(css, struct cpuset, css) : NULL;
242 }
243
244 /* Retrieve the cpuset for a task */
245 static inline struct cpuset *task_cs(struct task_struct *task)
246 {
247         return css_cs(task_css(task, cpuset_cgrp_id));
248 }
249
250 static inline struct cpuset *parent_cs(struct cpuset *cs)
251 {
252         return css_cs(cs->css.parent);
253 }
254
255 void inc_dl_tasks_cs(struct task_struct *p)
256 {
257         struct cpuset *cs = task_cs(p);
258
259         cs->nr_deadline_tasks++;
260 }
261
262 void dec_dl_tasks_cs(struct task_struct *p)
263 {
264         struct cpuset *cs = task_cs(p);
265
266         cs->nr_deadline_tasks--;
267 }
268
269 /* bits in struct cpuset flags field */
270 typedef enum {
271         CS_ONLINE,
272         CS_CPU_EXCLUSIVE,
273         CS_MEM_EXCLUSIVE,
274         CS_MEM_HARDWALL,
275         CS_MEMORY_MIGRATE,
276         CS_SCHED_LOAD_BALANCE,
277         CS_SPREAD_PAGE,
278         CS_SPREAD_SLAB,
279 } cpuset_flagbits_t;
280
281 /* convenient tests for these bits */
282 static inline bool is_cpuset_online(struct cpuset *cs)
283 {
284         return test_bit(CS_ONLINE, &cs->flags) && !css_is_dying(&cs->css);
285 }
286
287 static inline int is_cpu_exclusive(const struct cpuset *cs)
288 {
289         return test_bit(CS_CPU_EXCLUSIVE, &cs->flags);
290 }
291
292 static inline int is_mem_exclusive(const struct cpuset *cs)
293 {
294         return test_bit(CS_MEM_EXCLUSIVE, &cs->flags);
295 }
296
297 static inline int is_mem_hardwall(const struct cpuset *cs)
298 {
299         return test_bit(CS_MEM_HARDWALL, &cs->flags);
300 }
301
302 static inline int is_sched_load_balance(const struct cpuset *cs)
303 {
304         return test_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
305 }
306
307 static inline int is_memory_migrate(const struct cpuset *cs)
308 {
309         return test_bit(CS_MEMORY_MIGRATE, &cs->flags);
310 }
311
312 static inline int is_spread_page(const struct cpuset *cs)
313 {
314         return test_bit(CS_SPREAD_PAGE, &cs->flags);
315 }
316
317 static inline int is_spread_slab(const struct cpuset *cs)
318 {
319         return test_bit(CS_SPREAD_SLAB, &cs->flags);
320 }
321
322 static inline int is_partition_valid(const struct cpuset *cs)
323 {
324         return cs->partition_root_state > 0;
325 }
326
327 static inline int is_partition_invalid(const struct cpuset *cs)
328 {
329         return cs->partition_root_state < 0;
330 }
331
332 /*
333  * Callers should hold callback_lock to modify partition_root_state.
334  */
335 static inline void make_partition_invalid(struct cpuset *cs)
336 {
337         if (cs->partition_root_state > 0)
338                 cs->partition_root_state = -cs->partition_root_state;
339 }
340
341 /*
342  * Send notification event of whenever partition_root_state changes.
343  */
344 static inline void notify_partition_change(struct cpuset *cs, int old_prs)
345 {
346         if (old_prs == cs->partition_root_state)
347                 return;
348         cgroup_file_notify(&cs->partition_file);
349
350         /* Reset prs_err if not invalid */
351         if (is_partition_valid(cs))
352                 WRITE_ONCE(cs->prs_err, PERR_NONE);
353 }
354
355 static struct cpuset top_cpuset = {
356         .flags = ((1 << CS_ONLINE) | (1 << CS_CPU_EXCLUSIVE) |
357                   (1 << CS_MEM_EXCLUSIVE)),
358         .partition_root_state = PRS_ROOT,
359         .remote_sibling = LIST_HEAD_INIT(top_cpuset.remote_sibling),
360 };
361
362 /**
363  * cpuset_for_each_child - traverse online children of a cpuset
364  * @child_cs: loop cursor pointing to the current child
365  * @pos_css: used for iteration
366  * @parent_cs: target cpuset to walk children of
367  *
368  * Walk @child_cs through the online children of @parent_cs.  Must be used
369  * with RCU read locked.
370  */
371 #define cpuset_for_each_child(child_cs, pos_css, parent_cs)             \
372         css_for_each_child((pos_css), &(parent_cs)->css)                \
373                 if (is_cpuset_online(((child_cs) = css_cs((pos_css)))))
374
375 /**
376  * cpuset_for_each_descendant_pre - pre-order walk of a cpuset's descendants
377  * @des_cs: loop cursor pointing to the current descendant
378  * @pos_css: used for iteration
379  * @root_cs: target cpuset to walk ancestor of
380  *
381  * Walk @des_cs through the online descendants of @root_cs.  Must be used
382  * with RCU read locked.  The caller may modify @pos_css by calling
383  * css_rightmost_descendant() to skip subtree.  @root_cs is included in the
384  * iteration and the first node to be visited.
385  */
386 #define cpuset_for_each_descendant_pre(des_cs, pos_css, root_cs)        \
387         css_for_each_descendant_pre((pos_css), &(root_cs)->css)         \
388                 if (is_cpuset_online(((des_cs) = css_cs((pos_css)))))
389
390 /*
391  * There are two global locks guarding cpuset structures - cpuset_mutex and
392  * callback_lock. We also require taking task_lock() when dereferencing a
393  * task's cpuset pointer. See "The task_lock() exception", at the end of this
394  * comment.  The cpuset code uses only cpuset_mutex. Other kernel subsystems
395  * can use cpuset_lock()/cpuset_unlock() to prevent change to cpuset
396  * structures. Note that cpuset_mutex needs to be a mutex as it is used in
397  * paths that rely on priority inheritance (e.g. scheduler - on RT) for
398  * correctness.
399  *
400  * A task must hold both locks to modify cpusets.  If a task holds
401  * cpuset_mutex, it blocks others, ensuring that it is the only task able to
402  * also acquire callback_lock and be able to modify cpusets.  It can perform
403  * various checks on the cpuset structure first, knowing nothing will change.
404  * It can also allocate memory while just holding cpuset_mutex.  While it is
405  * performing these checks, various callback routines can briefly acquire
406  * callback_lock to query cpusets.  Once it is ready to make the changes, it
407  * takes callback_lock, blocking everyone else.
408  *
409  * Calls to the kernel memory allocator can not be made while holding
410  * callback_lock, as that would risk double tripping on callback_lock
411  * from one of the callbacks into the cpuset code from within
412  * __alloc_pages().
413  *
414  * If a task is only holding callback_lock, then it has read-only
415  * access to cpusets.
416  *
417  * Now, the task_struct fields mems_allowed and mempolicy may be changed
418  * by other task, we use alloc_lock in the task_struct fields to protect
419  * them.
420  *
421  * The cpuset_common_file_read() handlers only hold callback_lock across
422  * small pieces of code, such as when reading out possibly multi-word
423  * cpumasks and nodemasks.
424  *
425  * Accessing a task's cpuset should be done in accordance with the
426  * guidelines for accessing subsystem state in kernel/cgroup.c
427  */
428
429 static DEFINE_MUTEX(cpuset_mutex);
430
431 void cpuset_lock(void)
432 {
433         mutex_lock(&cpuset_mutex);
434 }
435
436 void cpuset_unlock(void)
437 {
438         mutex_unlock(&cpuset_mutex);
439 }
440
441 static DEFINE_SPINLOCK(callback_lock);
442
443 static struct workqueue_struct *cpuset_migrate_mm_wq;
444
445 /*
446  * CPU / memory hotplug is handled asynchronously.
447  */
448 static void cpuset_hotplug_workfn(struct work_struct *work);
449 static DECLARE_WORK(cpuset_hotplug_work, cpuset_hotplug_workfn);
450
451 static DECLARE_WAIT_QUEUE_HEAD(cpuset_attach_wq);
452
453 static inline void check_insane_mems_config(nodemask_t *nodes)
454 {
455         if (!cpusets_insane_config() &&
456                 movable_only_nodes(nodes)) {
457                 static_branch_enable(&cpusets_insane_config_key);
458                 pr_info("Unsupported (movable nodes only) cpuset configuration detected (nmask=%*pbl)!\n"
459                         "Cpuset allocations might fail even with a lot of memory available.\n",
460                         nodemask_pr_args(nodes));
461         }
462 }
463
464 /*
465  * Cgroup v2 behavior is used on the "cpus" and "mems" control files when
466  * on default hierarchy or when the cpuset_v2_mode flag is set by mounting
467  * the v1 cpuset cgroup filesystem with the "cpuset_v2_mode" mount option.
468  * With v2 behavior, "cpus" and "mems" are always what the users have
469  * requested and won't be changed by hotplug events. Only the effective
470  * cpus or mems will be affected.
471  */
472 static inline bool is_in_v2_mode(void)
473 {
474         return cgroup_subsys_on_dfl(cpuset_cgrp_subsys) ||
475               (cpuset_cgrp_subsys.root->flags & CGRP_ROOT_CPUSET_V2_MODE);
476 }
477
478 /**
479  * partition_is_populated - check if partition has tasks
480  * @cs: partition root to be checked
481  * @excluded_child: a child cpuset to be excluded in task checking
482  * Return: true if there are tasks, false otherwise
483  *
484  * It is assumed that @cs is a valid partition root. @excluded_child should
485  * be non-NULL when this cpuset is going to become a partition itself.
486  */
487 static inline bool partition_is_populated(struct cpuset *cs,
488                                           struct cpuset *excluded_child)
489 {
490         struct cgroup_subsys_state *css;
491         struct cpuset *child;
492
493         if (cs->css.cgroup->nr_populated_csets)
494                 return true;
495         if (!excluded_child && !cs->nr_subparts)
496                 return cgroup_is_populated(cs->css.cgroup);
497
498         rcu_read_lock();
499         cpuset_for_each_child(child, css, cs) {
500                 if (child == excluded_child)
501                         continue;
502                 if (is_partition_valid(child))
503                         continue;
504                 if (cgroup_is_populated(child->css.cgroup)) {
505                         rcu_read_unlock();
506                         return true;
507                 }
508         }
509         rcu_read_unlock();
510         return false;
511 }
512
513 /*
514  * Return in pmask the portion of a task's cpusets's cpus_allowed that
515  * are online and are capable of running the task.  If none are found,
516  * walk up the cpuset hierarchy until we find one that does have some
517  * appropriate cpus.
518  *
519  * One way or another, we guarantee to return some non-empty subset
520  * of cpu_online_mask.
521  *
522  * Call with callback_lock or cpuset_mutex held.
523  */
524 static void guarantee_online_cpus(struct task_struct *tsk,
525                                   struct cpumask *pmask)
526 {
527         const struct cpumask *possible_mask = task_cpu_possible_mask(tsk);
528         struct cpuset *cs;
529
530         if (WARN_ON(!cpumask_and(pmask, possible_mask, cpu_online_mask)))
531                 cpumask_copy(pmask, cpu_online_mask);
532
533         rcu_read_lock();
534         cs = task_cs(tsk);
535
536         while (!cpumask_intersects(cs->effective_cpus, pmask)) {
537                 cs = parent_cs(cs);
538                 if (unlikely(!cs)) {
539                         /*
540                          * The top cpuset doesn't have any online cpu as a
541                          * consequence of a race between cpuset_hotplug_work
542                          * and cpu hotplug notifier.  But we know the top
543                          * cpuset's effective_cpus is on its way to be
544                          * identical to cpu_online_mask.
545                          */
546                         goto out_unlock;
547                 }
548         }
549         cpumask_and(pmask, pmask, cs->effective_cpus);
550
551 out_unlock:
552         rcu_read_unlock();
553 }
554
555 /*
556  * Return in *pmask the portion of a cpusets's mems_allowed that
557  * are online, with memory.  If none are online with memory, walk
558  * up the cpuset hierarchy until we find one that does have some
559  * online mems.  The top cpuset always has some mems online.
560  *
561  * One way or another, we guarantee to return some non-empty subset
562  * of node_states[N_MEMORY].
563  *
564  * Call with callback_lock or cpuset_mutex held.
565  */
566 static void guarantee_online_mems(struct cpuset *cs, nodemask_t *pmask)
567 {
568         while (!nodes_intersects(cs->effective_mems, node_states[N_MEMORY]))
569                 cs = parent_cs(cs);
570         nodes_and(*pmask, cs->effective_mems, node_states[N_MEMORY]);
571 }
572
573 /*
574  * update task's spread flag if cpuset's page/slab spread flag is set
575  *
576  * Call with callback_lock or cpuset_mutex held. The check can be skipped
577  * if on default hierarchy.
578  */
579 static void cpuset_update_task_spread_flags(struct cpuset *cs,
580                                         struct task_struct *tsk)
581 {
582         if (cgroup_subsys_on_dfl(cpuset_cgrp_subsys))
583                 return;
584
585         if (is_spread_page(cs))
586                 task_set_spread_page(tsk);
587         else
588                 task_clear_spread_page(tsk);
589
590         if (is_spread_slab(cs))
591                 task_set_spread_slab(tsk);
592         else
593                 task_clear_spread_slab(tsk);
594 }
595
596 /*
597  * is_cpuset_subset(p, q) - Is cpuset p a subset of cpuset q?
598  *
599  * One cpuset is a subset of another if all its allowed CPUs and
600  * Memory Nodes are a subset of the other, and its exclusive flags
601  * are only set if the other's are set.  Call holding cpuset_mutex.
602  */
603
604 static int is_cpuset_subset(const struct cpuset *p, const struct cpuset *q)
605 {
606         return  cpumask_subset(p->cpus_allowed, q->cpus_allowed) &&
607                 nodes_subset(p->mems_allowed, q->mems_allowed) &&
608                 is_cpu_exclusive(p) <= is_cpu_exclusive(q) &&
609                 is_mem_exclusive(p) <= is_mem_exclusive(q);
610 }
611
612 /**
613  * alloc_cpumasks - allocate three cpumasks for cpuset
614  * @cs:  the cpuset that have cpumasks to be allocated.
615  * @tmp: the tmpmasks structure pointer
616  * Return: 0 if successful, -ENOMEM otherwise.
617  *
618  * Only one of the two input arguments should be non-NULL.
619  */
620 static inline int alloc_cpumasks(struct cpuset *cs, struct tmpmasks *tmp)
621 {
622         cpumask_var_t *pmask1, *pmask2, *pmask3, *pmask4;
623
624         if (cs) {
625                 pmask1 = &cs->cpus_allowed;
626                 pmask2 = &cs->effective_cpus;
627                 pmask3 = &cs->effective_xcpus;
628                 pmask4 = &cs->exclusive_cpus;
629         } else {
630                 pmask1 = &tmp->new_cpus;
631                 pmask2 = &tmp->addmask;
632                 pmask3 = &tmp->delmask;
633                 pmask4 = NULL;
634         }
635
636         if (!zalloc_cpumask_var(pmask1, GFP_KERNEL))
637                 return -ENOMEM;
638
639         if (!zalloc_cpumask_var(pmask2, GFP_KERNEL))
640                 goto free_one;
641
642         if (!zalloc_cpumask_var(pmask3, GFP_KERNEL))
643                 goto free_two;
644
645         if (pmask4 && !zalloc_cpumask_var(pmask4, GFP_KERNEL))
646                 goto free_three;
647
648
649         return 0;
650
651 free_three:
652         free_cpumask_var(*pmask3);
653 free_two:
654         free_cpumask_var(*pmask2);
655 free_one:
656         free_cpumask_var(*pmask1);
657         return -ENOMEM;
658 }
659
660 /**
661  * free_cpumasks - free cpumasks in a tmpmasks structure
662  * @cs:  the cpuset that have cpumasks to be free.
663  * @tmp: the tmpmasks structure pointer
664  */
665 static inline void free_cpumasks(struct cpuset *cs, struct tmpmasks *tmp)
666 {
667         if (cs) {
668                 free_cpumask_var(cs->cpus_allowed);
669                 free_cpumask_var(cs->effective_cpus);
670                 free_cpumask_var(cs->effective_xcpus);
671                 free_cpumask_var(cs->exclusive_cpus);
672         }
673         if (tmp) {
674                 free_cpumask_var(tmp->new_cpus);
675                 free_cpumask_var(tmp->addmask);
676                 free_cpumask_var(tmp->delmask);
677         }
678 }
679
680 /**
681  * alloc_trial_cpuset - allocate a trial cpuset
682  * @cs: the cpuset that the trial cpuset duplicates
683  */
684 static struct cpuset *alloc_trial_cpuset(struct cpuset *cs)
685 {
686         struct cpuset *trial;
687
688         trial = kmemdup(cs, sizeof(*cs), GFP_KERNEL);
689         if (!trial)
690                 return NULL;
691
692         if (alloc_cpumasks(trial, NULL)) {
693                 kfree(trial);
694                 return NULL;
695         }
696
697         cpumask_copy(trial->cpus_allowed, cs->cpus_allowed);
698         cpumask_copy(trial->effective_cpus, cs->effective_cpus);
699         cpumask_copy(trial->effective_xcpus, cs->effective_xcpus);
700         cpumask_copy(trial->exclusive_cpus, cs->exclusive_cpus);
701         return trial;
702 }
703
704 /**
705  * free_cpuset - free the cpuset
706  * @cs: the cpuset to be freed
707  */
708 static inline void free_cpuset(struct cpuset *cs)
709 {
710         free_cpumasks(cs, NULL);
711         kfree(cs);
712 }
713
714 static inline struct cpumask *fetch_xcpus(struct cpuset *cs)
715 {
716         return !cpumask_empty(cs->exclusive_cpus) ? cs->exclusive_cpus :
717                cpumask_empty(cs->effective_xcpus) ? cs->cpus_allowed
718                                                   : cs->effective_xcpus;
719 }
720
721 /*
722  * cpu_exclusive_check() - check if two cpusets are exclusive
723  *
724  * Return 0 if exclusive, -EINVAL if not
725  */
726 static inline bool cpu_exclusive_check(struct cpuset *cs1, struct cpuset *cs2)
727 {
728         struct cpumask *xcpus1 = fetch_xcpus(cs1);
729         struct cpumask *xcpus2 = fetch_xcpus(cs2);
730
731         if (cpumask_intersects(xcpus1, xcpus2))
732                 return -EINVAL;
733         return 0;
734 }
735
736 /*
737  * validate_change_legacy() - Validate conditions specific to legacy (v1)
738  *                            behavior.
739  */
740 static int validate_change_legacy(struct cpuset *cur, struct cpuset *trial)
741 {
742         struct cgroup_subsys_state *css;
743         struct cpuset *c, *par;
744         int ret;
745
746         WARN_ON_ONCE(!rcu_read_lock_held());
747
748         /* Each of our child cpusets must be a subset of us */
749         ret = -EBUSY;
750         cpuset_for_each_child(c, css, cur)
751                 if (!is_cpuset_subset(c, trial))
752                         goto out;
753
754         /* On legacy hierarchy, we must be a subset of our parent cpuset. */
755         ret = -EACCES;
756         par = parent_cs(cur);
757         if (par && !is_cpuset_subset(trial, par))
758                 goto out;
759
760         ret = 0;
761 out:
762         return ret;
763 }
764
765 /*
766  * validate_change() - Used to validate that any proposed cpuset change
767  *                     follows the structural rules for cpusets.
768  *
769  * If we replaced the flag and mask values of the current cpuset
770  * (cur) with those values in the trial cpuset (trial), would
771  * our various subset and exclusive rules still be valid?  Presumes
772  * cpuset_mutex held.
773  *
774  * 'cur' is the address of an actual, in-use cpuset.  Operations
775  * such as list traversal that depend on the actual address of the
776  * cpuset in the list must use cur below, not trial.
777  *
778  * 'trial' is the address of bulk structure copy of cur, with
779  * perhaps one or more of the fields cpus_allowed, mems_allowed,
780  * or flags changed to new, trial values.
781  *
782  * Return 0 if valid, -errno if not.
783  */
784
785 static int validate_change(struct cpuset *cur, struct cpuset *trial)
786 {
787         struct cgroup_subsys_state *css;
788         struct cpuset *c, *par;
789         int ret = 0;
790
791         rcu_read_lock();
792
793         if (!is_in_v2_mode())
794                 ret = validate_change_legacy(cur, trial);
795         if (ret)
796                 goto out;
797
798         /* Remaining checks don't apply to root cpuset */
799         if (cur == &top_cpuset)
800                 goto out;
801
802         par = parent_cs(cur);
803
804         /*
805          * Cpusets with tasks - existing or newly being attached - can't
806          * be changed to have empty cpus_allowed or mems_allowed.
807          */
808         ret = -ENOSPC;
809         if ((cgroup_is_populated(cur->css.cgroup) || cur->attach_in_progress)) {
810                 if (!cpumask_empty(cur->cpus_allowed) &&
811                     cpumask_empty(trial->cpus_allowed))
812                         goto out;
813                 if (!nodes_empty(cur->mems_allowed) &&
814                     nodes_empty(trial->mems_allowed))
815                         goto out;
816         }
817
818         /*
819          * We can't shrink if we won't have enough room for SCHED_DEADLINE
820          * tasks.
821          */
822         ret = -EBUSY;
823         if (is_cpu_exclusive(cur) &&
824             !cpuset_cpumask_can_shrink(cur->cpus_allowed,
825                                        trial->cpus_allowed))
826                 goto out;
827
828         /*
829          * If either I or some sibling (!= me) is exclusive, we can't
830          * overlap
831          */
832         ret = -EINVAL;
833         cpuset_for_each_child(c, css, par) {
834                 if ((is_cpu_exclusive(trial) || is_cpu_exclusive(c)) &&
835                     c != cur) {
836                         if (cpu_exclusive_check(trial, c))
837                                 goto out;
838                 }
839                 if ((is_mem_exclusive(trial) || is_mem_exclusive(c)) &&
840                     c != cur &&
841                     nodes_intersects(trial->mems_allowed, c->mems_allowed))
842                         goto out;
843         }
844
845         ret = 0;
846 out:
847         rcu_read_unlock();
848         return ret;
849 }
850
851 #ifdef CONFIG_SMP
852 /*
853  * Helper routine for generate_sched_domains().
854  * Do cpusets a, b have overlapping effective cpus_allowed masks?
855  */
856 static int cpusets_overlap(struct cpuset *a, struct cpuset *b)
857 {
858         return cpumask_intersects(a->effective_cpus, b->effective_cpus);
859 }
860
861 static void
862 update_domain_attr(struct sched_domain_attr *dattr, struct cpuset *c)
863 {
864         if (dattr->relax_domain_level < c->relax_domain_level)
865                 dattr->relax_domain_level = c->relax_domain_level;
866         return;
867 }
868
869 static void update_domain_attr_tree(struct sched_domain_attr *dattr,
870                                     struct cpuset *root_cs)
871 {
872         struct cpuset *cp;
873         struct cgroup_subsys_state *pos_css;
874
875         rcu_read_lock();
876         cpuset_for_each_descendant_pre(cp, pos_css, root_cs) {
877                 /* skip the whole subtree if @cp doesn't have any CPU */
878                 if (cpumask_empty(cp->cpus_allowed)) {
879                         pos_css = css_rightmost_descendant(pos_css);
880                         continue;
881                 }
882
883                 if (is_sched_load_balance(cp))
884                         update_domain_attr(dattr, cp);
885         }
886         rcu_read_unlock();
887 }
888
889 /* Must be called with cpuset_mutex held.  */
890 static inline int nr_cpusets(void)
891 {
892         /* jump label reference count + the top-level cpuset */
893         return static_key_count(&cpusets_enabled_key.key) + 1;
894 }
895
896 /*
897  * generate_sched_domains()
898  *
899  * This function builds a partial partition of the systems CPUs
900  * A 'partial partition' is a set of non-overlapping subsets whose
901  * union is a subset of that set.
902  * The output of this function needs to be passed to kernel/sched/core.c
903  * partition_sched_domains() routine, which will rebuild the scheduler's
904  * load balancing domains (sched domains) as specified by that partial
905  * partition.
906  *
907  * See "What is sched_load_balance" in Documentation/admin-guide/cgroup-v1/cpusets.rst
908  * for a background explanation of this.
909  *
910  * Does not return errors, on the theory that the callers of this
911  * routine would rather not worry about failures to rebuild sched
912  * domains when operating in the severe memory shortage situations
913  * that could cause allocation failures below.
914  *
915  * Must be called with cpuset_mutex held.
916  *
917  * The three key local variables below are:
918  *    cp - cpuset pointer, used (together with pos_css) to perform a
919  *         top-down scan of all cpusets. For our purposes, rebuilding
920  *         the schedulers sched domains, we can ignore !is_sched_load_
921  *         balance cpusets.
922  *  csa  - (for CpuSet Array) Array of pointers to all the cpusets
923  *         that need to be load balanced, for convenient iterative
924  *         access by the subsequent code that finds the best partition,
925  *         i.e the set of domains (subsets) of CPUs such that the
926  *         cpus_allowed of every cpuset marked is_sched_load_balance
927  *         is a subset of one of these domains, while there are as
928  *         many such domains as possible, each as small as possible.
929  * doms  - Conversion of 'csa' to an array of cpumasks, for passing to
930  *         the kernel/sched/core.c routine partition_sched_domains() in a
931  *         convenient format, that can be easily compared to the prior
932  *         value to determine what partition elements (sched domains)
933  *         were changed (added or removed.)
934  *
935  * Finding the best partition (set of domains):
936  *      The triple nested loops below over i, j, k scan over the
937  *      load balanced cpusets (using the array of cpuset pointers in
938  *      csa[]) looking for pairs of cpusets that have overlapping
939  *      cpus_allowed, but which don't have the same 'pn' partition
940  *      number and gives them in the same partition number.  It keeps
941  *      looping on the 'restart' label until it can no longer find
942  *      any such pairs.
943  *
944  *      The union of the cpus_allowed masks from the set of
945  *      all cpusets having the same 'pn' value then form the one
946  *      element of the partition (one sched domain) to be passed to
947  *      partition_sched_domains().
948  */
949 static int generate_sched_domains(cpumask_var_t **domains,
950                         struct sched_domain_attr **attributes)
951 {
952         struct cpuset *cp;      /* top-down scan of cpusets */
953         struct cpuset **csa;    /* array of all cpuset ptrs */
954         int csn;                /* how many cpuset ptrs in csa so far */
955         int i, j, k;            /* indices for partition finding loops */
956         cpumask_var_t *doms;    /* resulting partition; i.e. sched domains */
957         struct sched_domain_attr *dattr;  /* attributes for custom domains */
958         int ndoms = 0;          /* number of sched domains in result */
959         int nslot;              /* next empty doms[] struct cpumask slot */
960         struct cgroup_subsys_state *pos_css;
961         bool root_load_balance = is_sched_load_balance(&top_cpuset);
962
963         doms = NULL;
964         dattr = NULL;
965         csa = NULL;
966
967         /* Special case for the 99% of systems with one, full, sched domain */
968         if (root_load_balance && !top_cpuset.nr_subparts) {
969                 ndoms = 1;
970                 doms = alloc_sched_domains(ndoms);
971                 if (!doms)
972                         goto done;
973
974                 dattr = kmalloc(sizeof(struct sched_domain_attr), GFP_KERNEL);
975                 if (dattr) {
976                         *dattr = SD_ATTR_INIT;
977                         update_domain_attr_tree(dattr, &top_cpuset);
978                 }
979                 cpumask_and(doms[0], top_cpuset.effective_cpus,
980                             housekeeping_cpumask(HK_TYPE_DOMAIN));
981
982                 goto done;
983         }
984
985         csa = kmalloc_array(nr_cpusets(), sizeof(cp), GFP_KERNEL);
986         if (!csa)
987                 goto done;
988         csn = 0;
989
990         rcu_read_lock();
991         if (root_load_balance)
992                 csa[csn++] = &top_cpuset;
993         cpuset_for_each_descendant_pre(cp, pos_css, &top_cpuset) {
994                 if (cp == &top_cpuset)
995                         continue;
996                 /*
997                  * Continue traversing beyond @cp iff @cp has some CPUs and
998                  * isn't load balancing.  The former is obvious.  The
999                  * latter: All child cpusets contain a subset of the
1000                  * parent's cpus, so just skip them, and then we call
1001                  * update_domain_attr_tree() to calc relax_domain_level of
1002                  * the corresponding sched domain.
1003                  *
1004                  * If root is load-balancing, we can skip @cp if it
1005                  * is a subset of the root's effective_cpus.
1006                  */
1007                 if (!cpumask_empty(cp->cpus_allowed) &&
1008                     !(is_sched_load_balance(cp) &&
1009                       cpumask_intersects(cp->cpus_allowed,
1010                                          housekeeping_cpumask(HK_TYPE_DOMAIN))))
1011                         continue;
1012
1013                 if (root_load_balance &&
1014                     cpumask_subset(cp->cpus_allowed, top_cpuset.effective_cpus))
1015                         continue;
1016
1017                 if (is_sched_load_balance(cp) &&
1018                     !cpumask_empty(cp->effective_cpus))
1019                         csa[csn++] = cp;
1020
1021                 /* skip @cp's subtree if not a partition root */
1022                 if (!is_partition_valid(cp))
1023                         pos_css = css_rightmost_descendant(pos_css);
1024         }
1025         rcu_read_unlock();
1026
1027         for (i = 0; i < csn; i++)
1028                 csa[i]->pn = i;
1029         ndoms = csn;
1030
1031 restart:
1032         /* Find the best partition (set of sched domains) */
1033         for (i = 0; i < csn; i++) {
1034                 struct cpuset *a = csa[i];
1035                 int apn = a->pn;
1036
1037                 for (j = 0; j < csn; j++) {
1038                         struct cpuset *b = csa[j];
1039                         int bpn = b->pn;
1040
1041                         if (apn != bpn && cpusets_overlap(a, b)) {
1042                                 for (k = 0; k < csn; k++) {
1043                                         struct cpuset *c = csa[k];
1044
1045                                         if (c->pn == bpn)
1046                                                 c->pn = apn;
1047                                 }
1048                                 ndoms--;        /* one less element */
1049                                 goto restart;
1050                         }
1051                 }
1052         }
1053
1054         /*
1055          * Now we know how many domains to create.
1056          * Convert <csn, csa> to <ndoms, doms> and populate cpu masks.
1057          */
1058         doms = alloc_sched_domains(ndoms);
1059         if (!doms)
1060                 goto done;
1061
1062         /*
1063          * The rest of the code, including the scheduler, can deal with
1064          * dattr==NULL case. No need to abort if alloc fails.
1065          */
1066         dattr = kmalloc_array(ndoms, sizeof(struct sched_domain_attr),
1067                               GFP_KERNEL);
1068
1069         for (nslot = 0, i = 0; i < csn; i++) {
1070                 struct cpuset *a = csa[i];
1071                 struct cpumask *dp;
1072                 int apn = a->pn;
1073
1074                 if (apn < 0) {
1075                         /* Skip completed partitions */
1076                         continue;
1077                 }
1078
1079                 dp = doms[nslot];
1080
1081                 if (nslot == ndoms) {
1082                         static int warnings = 10;
1083                         if (warnings) {
1084                                 pr_warn("rebuild_sched_domains confused: nslot %d, ndoms %d, csn %d, i %d, apn %d\n",
1085                                         nslot, ndoms, csn, i, apn);
1086                                 warnings--;
1087                         }
1088                         continue;
1089                 }
1090
1091                 cpumask_clear(dp);
1092                 if (dattr)
1093                         *(dattr + nslot) = SD_ATTR_INIT;
1094                 for (j = i; j < csn; j++) {
1095                         struct cpuset *b = csa[j];
1096
1097                         if (apn == b->pn) {
1098                                 cpumask_or(dp, dp, b->effective_cpus);
1099                                 cpumask_and(dp, dp, housekeeping_cpumask(HK_TYPE_DOMAIN));
1100                                 if (dattr)
1101                                         update_domain_attr_tree(dattr + nslot, b);
1102
1103                                 /* Done with this partition */
1104                                 b->pn = -1;
1105                         }
1106                 }
1107                 nslot++;
1108         }
1109         BUG_ON(nslot != ndoms);
1110
1111 done:
1112         kfree(csa);
1113
1114         /*
1115          * Fallback to the default domain if kmalloc() failed.
1116          * See comments in partition_sched_domains().
1117          */
1118         if (doms == NULL)
1119                 ndoms = 1;
1120
1121         *domains    = doms;
1122         *attributes = dattr;
1123         return ndoms;
1124 }
1125
1126 static void dl_update_tasks_root_domain(struct cpuset *cs)
1127 {
1128         struct css_task_iter it;
1129         struct task_struct *task;
1130
1131         if (cs->nr_deadline_tasks == 0)
1132                 return;
1133
1134         css_task_iter_start(&cs->css, 0, &it);
1135
1136         while ((task = css_task_iter_next(&it)))
1137                 dl_add_task_root_domain(task);
1138
1139         css_task_iter_end(&it);
1140 }
1141
1142 static void dl_rebuild_rd_accounting(void)
1143 {
1144         struct cpuset *cs = NULL;
1145         struct cgroup_subsys_state *pos_css;
1146
1147         lockdep_assert_held(&cpuset_mutex);
1148         lockdep_assert_cpus_held();
1149         lockdep_assert_held(&sched_domains_mutex);
1150
1151         rcu_read_lock();
1152
1153         /*
1154          * Clear default root domain DL accounting, it will be computed again
1155          * if a task belongs to it.
1156          */
1157         dl_clear_root_domain(&def_root_domain);
1158
1159         cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
1160
1161                 if (cpumask_empty(cs->effective_cpus)) {
1162                         pos_css = css_rightmost_descendant(pos_css);
1163                         continue;
1164                 }
1165
1166                 css_get(&cs->css);
1167
1168                 rcu_read_unlock();
1169
1170                 dl_update_tasks_root_domain(cs);
1171
1172                 rcu_read_lock();
1173                 css_put(&cs->css);
1174         }
1175         rcu_read_unlock();
1176 }
1177
1178 static void
1179 partition_and_rebuild_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
1180                                     struct sched_domain_attr *dattr_new)
1181 {
1182         mutex_lock(&sched_domains_mutex);
1183         partition_sched_domains_locked(ndoms_new, doms_new, dattr_new);
1184         dl_rebuild_rd_accounting();
1185         mutex_unlock(&sched_domains_mutex);
1186 }
1187
1188 /*
1189  * Rebuild scheduler domains.
1190  *
1191  * If the flag 'sched_load_balance' of any cpuset with non-empty
1192  * 'cpus' changes, or if the 'cpus' allowed changes in any cpuset
1193  * which has that flag enabled, or if any cpuset with a non-empty
1194  * 'cpus' is removed, then call this routine to rebuild the
1195  * scheduler's dynamic sched domains.
1196  *
1197  * Call with cpuset_mutex held.  Takes cpus_read_lock().
1198  */
1199 static void rebuild_sched_domains_locked(void)
1200 {
1201         struct cgroup_subsys_state *pos_css;
1202         struct sched_domain_attr *attr;
1203         cpumask_var_t *doms;
1204         struct cpuset *cs;
1205         int ndoms;
1206
1207         lockdep_assert_cpus_held();
1208         lockdep_assert_held(&cpuset_mutex);
1209
1210         /*
1211          * If we have raced with CPU hotplug, return early to avoid
1212          * passing doms with offlined cpu to partition_sched_domains().
1213          * Anyways, cpuset_hotplug_workfn() will rebuild sched domains.
1214          *
1215          * With no CPUs in any subpartitions, top_cpuset's effective CPUs
1216          * should be the same as the active CPUs, so checking only top_cpuset
1217          * is enough to detect racing CPU offlines.
1218          */
1219         if (cpumask_empty(subpartitions_cpus) &&
1220             !cpumask_equal(top_cpuset.effective_cpus, cpu_active_mask))
1221                 return;
1222
1223         /*
1224          * With subpartition CPUs, however, the effective CPUs of a partition
1225          * root should be only a subset of the active CPUs.  Since a CPU in any
1226          * partition root could be offlined, all must be checked.
1227          */
1228         if (top_cpuset.nr_subparts) {
1229                 rcu_read_lock();
1230                 cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
1231                         if (!is_partition_valid(cs)) {
1232                                 pos_css = css_rightmost_descendant(pos_css);
1233                                 continue;
1234                         }
1235                         if (!cpumask_subset(cs->effective_cpus,
1236                                             cpu_active_mask)) {
1237                                 rcu_read_unlock();
1238                                 return;
1239                         }
1240                 }
1241                 rcu_read_unlock();
1242         }
1243
1244         /* Generate domain masks and attrs */
1245         ndoms = generate_sched_domains(&doms, &attr);
1246
1247         /* Have scheduler rebuild the domains */
1248         partition_and_rebuild_sched_domains(ndoms, doms, attr);
1249 }
1250 #else /* !CONFIG_SMP */
1251 static void rebuild_sched_domains_locked(void)
1252 {
1253 }
1254 #endif /* CONFIG_SMP */
1255
1256 void rebuild_sched_domains(void)
1257 {
1258         cpus_read_lock();
1259         mutex_lock(&cpuset_mutex);
1260         rebuild_sched_domains_locked();
1261         mutex_unlock(&cpuset_mutex);
1262         cpus_read_unlock();
1263 }
1264
1265 /**
1266  * update_tasks_cpumask - Update the cpumasks of tasks in the cpuset.
1267  * @cs: the cpuset in which each task's cpus_allowed mask needs to be changed
1268  * @new_cpus: the temp variable for the new effective_cpus mask
1269  *
1270  * Iterate through each task of @cs updating its cpus_allowed to the
1271  * effective cpuset's.  As this function is called with cpuset_mutex held,
1272  * cpuset membership stays stable. For top_cpuset, task_cpu_possible_mask()
1273  * is used instead of effective_cpus to make sure all offline CPUs are also
1274  * included as hotplug code won't update cpumasks for tasks in top_cpuset.
1275  */
1276 static void update_tasks_cpumask(struct cpuset *cs, struct cpumask *new_cpus)
1277 {
1278         struct css_task_iter it;
1279         struct task_struct *task;
1280         bool top_cs = cs == &top_cpuset;
1281
1282         css_task_iter_start(&cs->css, 0, &it);
1283         while ((task = css_task_iter_next(&it))) {
1284                 const struct cpumask *possible_mask = task_cpu_possible_mask(task);
1285
1286                 if (top_cs) {
1287                         /*
1288                          * Percpu kthreads in top_cpuset are ignored
1289                          */
1290                         if (kthread_is_per_cpu(task))
1291                                 continue;
1292                         cpumask_andnot(new_cpus, possible_mask, subpartitions_cpus);
1293                 } else {
1294                         cpumask_and(new_cpus, possible_mask, cs->effective_cpus);
1295                 }
1296                 set_cpus_allowed_ptr(task, new_cpus);
1297         }
1298         css_task_iter_end(&it);
1299 }
1300
1301 /**
1302  * compute_effective_cpumask - Compute the effective cpumask of the cpuset
1303  * @new_cpus: the temp variable for the new effective_cpus mask
1304  * @cs: the cpuset the need to recompute the new effective_cpus mask
1305  * @parent: the parent cpuset
1306  *
1307  * The result is valid only if the given cpuset isn't a partition root.
1308  */
1309 static void compute_effective_cpumask(struct cpumask *new_cpus,
1310                                       struct cpuset *cs, struct cpuset *parent)
1311 {
1312         cpumask_and(new_cpus, cs->cpus_allowed, parent->effective_cpus);
1313 }
1314
1315 /*
1316  * Commands for update_parent_effective_cpumask
1317  */
1318 enum partition_cmd {
1319         partcmd_enable,         /* Enable partition root          */
1320         partcmd_disable,        /* Disable partition root         */
1321         partcmd_update,         /* Update parent's effective_cpus */
1322         partcmd_invalidate,     /* Make partition invalid         */
1323 };
1324
1325 static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs,
1326                        int turning_on);
1327 static void update_sibling_cpumasks(struct cpuset *parent, struct cpuset *cs,
1328                                     struct tmpmasks *tmp);
1329
1330 /*
1331  * Update partition exclusive flag
1332  *
1333  * Return: 0 if successful, an error code otherwise
1334  */
1335 static int update_partition_exclusive(struct cpuset *cs, int new_prs)
1336 {
1337         bool exclusive = (new_prs > 0);
1338
1339         if (exclusive && !is_cpu_exclusive(cs)) {
1340                 if (update_flag(CS_CPU_EXCLUSIVE, cs, 1))
1341                         return PERR_NOTEXCL;
1342         } else if (!exclusive && is_cpu_exclusive(cs)) {
1343                 /* Turning off CS_CPU_EXCLUSIVE will not return error */
1344                 update_flag(CS_CPU_EXCLUSIVE, cs, 0);
1345         }
1346         return 0;
1347 }
1348
1349 /*
1350  * Update partition load balance flag and/or rebuild sched domain
1351  *
1352  * Changing load balance flag will automatically call
1353  * rebuild_sched_domains_locked().
1354  * This function is for cgroup v2 only.
1355  */
1356 static void update_partition_sd_lb(struct cpuset *cs, int old_prs)
1357 {
1358         int new_prs = cs->partition_root_state;
1359         bool rebuild_domains = (new_prs > 0) || (old_prs > 0);
1360         bool new_lb;
1361
1362         /*
1363          * If cs is not a valid partition root, the load balance state
1364          * will follow its parent.
1365          */
1366         if (new_prs > 0) {
1367                 new_lb = (new_prs != PRS_ISOLATED);
1368         } else {
1369                 new_lb = is_sched_load_balance(parent_cs(cs));
1370         }
1371         if (new_lb != !!is_sched_load_balance(cs)) {
1372                 rebuild_domains = true;
1373                 if (new_lb)
1374                         set_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
1375                 else
1376                         clear_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
1377         }
1378
1379         if (rebuild_domains)
1380                 rebuild_sched_domains_locked();
1381 }
1382
1383 /*
1384  * tasks_nocpu_error - Return true if tasks will have no effective_cpus
1385  */
1386 static bool tasks_nocpu_error(struct cpuset *parent, struct cpuset *cs,
1387                               struct cpumask *xcpus)
1388 {
1389         /*
1390          * A populated partition (cs or parent) can't have empty effective_cpus
1391          */
1392         return (cpumask_subset(parent->effective_cpus, xcpus) &&
1393                 partition_is_populated(parent, cs)) ||
1394                (!cpumask_intersects(xcpus, cpu_active_mask) &&
1395                 partition_is_populated(cs, NULL));
1396 }
1397
1398 static void reset_partition_data(struct cpuset *cs)
1399 {
1400         struct cpuset *parent = parent_cs(cs);
1401
1402         if (!cgroup_subsys_on_dfl(cpuset_cgrp_subsys))
1403                 return;
1404
1405         lockdep_assert_held(&callback_lock);
1406
1407         cs->nr_subparts = 0;
1408         if (cpumask_empty(cs->exclusive_cpus)) {
1409                 cpumask_clear(cs->effective_xcpus);
1410                 if (is_cpu_exclusive(cs))
1411                         clear_bit(CS_CPU_EXCLUSIVE, &cs->flags);
1412         }
1413         if (!cpumask_and(cs->effective_cpus,
1414                          parent->effective_cpus, cs->cpus_allowed)) {
1415                 cs->use_parent_ecpus = true;
1416                 parent->child_ecpus_count++;
1417                 cpumask_copy(cs->effective_cpus, parent->effective_cpus);
1418         }
1419 }
1420
1421 /*
1422  * compute_effective_exclusive_cpumask - compute effective exclusive CPUs
1423  * @cs: cpuset
1424  * @xcpus: effective exclusive CPUs value to be set
1425  * Return: true if xcpus is not empty, false otherwise.
1426  *
1427  * Starting with exclusive_cpus (cpus_allowed if exclusive_cpus is not set),
1428  * it must be a subset of cpus_allowed and parent's effective_xcpus.
1429  */
1430 static bool compute_effective_exclusive_cpumask(struct cpuset *cs,
1431                                                 struct cpumask *xcpus)
1432 {
1433         struct cpuset *parent = parent_cs(cs);
1434
1435         if (!xcpus)
1436                 xcpus = cs->effective_xcpus;
1437
1438         if (!cpumask_empty(cs->exclusive_cpus))
1439                 cpumask_and(xcpus, cs->exclusive_cpus, cs->cpus_allowed);
1440         else
1441                 cpumask_copy(xcpus, cs->cpus_allowed);
1442
1443         return cpumask_and(xcpus, xcpus, parent->effective_xcpus);
1444 }
1445
1446 static inline bool is_remote_partition(struct cpuset *cs)
1447 {
1448         return !list_empty(&cs->remote_sibling);
1449 }
1450
1451 static inline bool is_local_partition(struct cpuset *cs)
1452 {
1453         return is_partition_valid(cs) && !is_remote_partition(cs);
1454 }
1455
1456 /*
1457  * remote_partition_enable - Enable current cpuset as a remote partition root
1458  * @cs: the cpuset to update
1459  * @tmp: temparary masks
1460  * Return: 1 if successful, 0 if error
1461  *
1462  * Enable the current cpuset to become a remote partition root taking CPUs
1463  * directly from the top cpuset. cpuset_mutex must be held by the caller.
1464  */
1465 static int remote_partition_enable(struct cpuset *cs, struct tmpmasks *tmp)
1466 {
1467         /*
1468          * The user must have sysadmin privilege.
1469          */
1470         if (!capable(CAP_SYS_ADMIN))
1471                 return 0;
1472
1473         /*
1474          * The requested exclusive_cpus must not be allocated to other
1475          * partitions and it can't use up all the root's effective_cpus.
1476          *
1477          * Note that if there is any local partition root above it or
1478          * remote partition root underneath it, its exclusive_cpus must
1479          * have overlapped with subpartitions_cpus.
1480          */
1481         compute_effective_exclusive_cpumask(cs, tmp->new_cpus);
1482         if (cpumask_empty(tmp->new_cpus) ||
1483             cpumask_intersects(tmp->new_cpus, subpartitions_cpus) ||
1484             cpumask_subset(top_cpuset.effective_cpus, tmp->new_cpus))
1485                 return 0;
1486
1487         spin_lock_irq(&callback_lock);
1488         cpumask_andnot(top_cpuset.effective_cpus,
1489                        top_cpuset.effective_cpus, tmp->new_cpus);
1490         cpumask_or(subpartitions_cpus,
1491                    subpartitions_cpus, tmp->new_cpus);
1492
1493         if (cs->use_parent_ecpus) {
1494                 struct cpuset *parent = parent_cs(cs);
1495
1496                 cs->use_parent_ecpus = false;
1497                 parent->child_ecpus_count--;
1498         }
1499         list_add(&cs->remote_sibling, &remote_children);
1500         spin_unlock_irq(&callback_lock);
1501
1502         /*
1503          * Proprogate changes in top_cpuset's effective_cpus down the hierarchy.
1504          */
1505         update_tasks_cpumask(&top_cpuset, tmp->new_cpus);
1506         update_sibling_cpumasks(&top_cpuset, NULL, tmp);
1507
1508         return 1;
1509 }
1510
1511 /*
1512  * remote_partition_disable - Remove current cpuset from remote partition list
1513  * @cs: the cpuset to update
1514  * @tmp: temparary masks
1515  *
1516  * The effective_cpus is also updated.
1517  *
1518  * cpuset_mutex must be held by the caller.
1519  */
1520 static void remote_partition_disable(struct cpuset *cs, struct tmpmasks *tmp)
1521 {
1522         compute_effective_exclusive_cpumask(cs, tmp->new_cpus);
1523         WARN_ON_ONCE(!is_remote_partition(cs));
1524         WARN_ON_ONCE(!cpumask_subset(tmp->new_cpus, subpartitions_cpus));
1525
1526         spin_lock_irq(&callback_lock);
1527         cpumask_andnot(subpartitions_cpus,
1528                        subpartitions_cpus, tmp->new_cpus);
1529         cpumask_and(tmp->new_cpus,
1530                     tmp->new_cpus, cpu_active_mask);
1531         cpumask_or(top_cpuset.effective_cpus,
1532                    top_cpuset.effective_cpus, tmp->new_cpus);
1533         list_del_init(&cs->remote_sibling);
1534         cs->partition_root_state = -cs->partition_root_state;
1535         if (!cs->prs_err)
1536                 cs->prs_err = PERR_INVCPUS;
1537         reset_partition_data(cs);
1538         spin_unlock_irq(&callback_lock);
1539
1540         /*
1541          * Proprogate changes in top_cpuset's effective_cpus down the hierarchy.
1542          */
1543         update_tasks_cpumask(&top_cpuset, tmp->new_cpus);
1544         update_sibling_cpumasks(&top_cpuset, NULL, tmp);
1545 }
1546
1547 /*
1548  * remote_cpus_update - cpus_exclusive change of remote partition
1549  * @cs: the cpuset to be updated
1550  * @newmask: the new effective_xcpus mask
1551  * @tmp: temparary masks
1552  *
1553  * top_cpuset and subpartitions_cpus will be updated or partition can be
1554  * invalidated.
1555  */
1556 static void remote_cpus_update(struct cpuset *cs, struct cpumask *newmask,
1557                                struct tmpmasks *tmp)
1558 {
1559         bool adding, deleting;
1560
1561         if (WARN_ON_ONCE(!is_remote_partition(cs)))
1562                 return;
1563
1564         WARN_ON_ONCE(!cpumask_subset(cs->effective_xcpus, subpartitions_cpus));
1565
1566         if (cpumask_empty(newmask))
1567                 goto invalidate;
1568
1569         adding   = cpumask_andnot(tmp->addmask, newmask, cs->effective_xcpus);
1570         deleting = cpumask_andnot(tmp->delmask, cs->effective_xcpus, newmask);
1571
1572         /*
1573          * Additions of remote CPUs is only allowed if those CPUs are
1574          * not allocated to other partitions and there are effective_cpus
1575          * left in the top cpuset.
1576          */
1577         if (adding && (!capable(CAP_SYS_ADMIN) ||
1578                        cpumask_intersects(tmp->addmask, subpartitions_cpus) ||
1579                        cpumask_subset(top_cpuset.effective_cpus, tmp->addmask)))
1580                 goto invalidate;
1581
1582         spin_lock_irq(&callback_lock);
1583         if (adding) {
1584                 cpumask_or(subpartitions_cpus,
1585                            subpartitions_cpus, tmp->addmask);
1586                 cpumask_andnot(top_cpuset.effective_cpus,
1587                                top_cpuset.effective_cpus, tmp->addmask);
1588         }
1589         if (deleting) {
1590                 cpumask_andnot(subpartitions_cpus,
1591                                subpartitions_cpus, tmp->delmask);
1592                 cpumask_and(tmp->delmask,
1593                             tmp->delmask, cpu_active_mask);
1594                 cpumask_or(top_cpuset.effective_cpus,
1595                            top_cpuset.effective_cpus, tmp->delmask);
1596         }
1597         spin_unlock_irq(&callback_lock);
1598
1599         /*
1600          * Proprogate changes in top_cpuset's effective_cpus down the hierarchy.
1601          */
1602         update_tasks_cpumask(&top_cpuset, tmp->new_cpus);
1603         update_sibling_cpumasks(&top_cpuset, NULL, tmp);
1604         return;
1605
1606 invalidate:
1607         remote_partition_disable(cs, tmp);
1608 }
1609
1610 /*
1611  * remote_partition_check - check if a child remote partition needs update
1612  * @cs: the cpuset to be updated
1613  * @newmask: the new effective_xcpus mask
1614  * @delmask: temporary mask for deletion (not in tmp)
1615  * @tmp: temparary masks
1616  *
1617  * This should be called before the given cs has updated its cpus_allowed
1618  * and/or effective_xcpus.
1619  */
1620 static void remote_partition_check(struct cpuset *cs, struct cpumask *newmask,
1621                                    struct cpumask *delmask, struct tmpmasks *tmp)
1622 {
1623         struct cpuset *child, *next;
1624         int disable_cnt = 0;
1625
1626         /*
1627          * Compute the effective exclusive CPUs that will be deleted.
1628          */
1629         if (!cpumask_andnot(delmask, cs->effective_xcpus, newmask) ||
1630             !cpumask_intersects(delmask, subpartitions_cpus))
1631                 return; /* No deletion of exclusive CPUs in partitions */
1632
1633         /*
1634          * Searching the remote children list to look for those that will
1635          * be impacted by the deletion of exclusive CPUs.
1636          *
1637          * Since a cpuset must be removed from the remote children list
1638          * before it can go offline and holding cpuset_mutex will prevent
1639          * any change in cpuset status. RCU read lock isn't needed.
1640          */
1641         lockdep_assert_held(&cpuset_mutex);
1642         list_for_each_entry_safe(child, next, &remote_children, remote_sibling)
1643                 if (cpumask_intersects(child->effective_cpus, delmask)) {
1644                         remote_partition_disable(child, tmp);
1645                         disable_cnt++;
1646                 }
1647         if (disable_cnt)
1648                 rebuild_sched_domains_locked();
1649 }
1650
1651 /*
1652  * prstate_housekeeping_conflict - check for partition & housekeeping conflicts
1653  * @prstate: partition root state to be checked
1654  * @new_cpus: cpu mask
1655  * Return: true if there is conflict, false otherwise
1656  *
1657  * CPUs outside of housekeeping_cpumask(HK_TYPE_DOMAIN) can only be used in
1658  * an isolated partition.
1659  */
1660 static bool prstate_housekeeping_conflict(int prstate, struct cpumask *new_cpus)
1661 {
1662         const struct cpumask *hk_domain = housekeeping_cpumask(HK_TYPE_DOMAIN);
1663         bool all_in_hk = cpumask_subset(new_cpus, hk_domain);
1664
1665         if (!all_in_hk && (prstate != PRS_ISOLATED))
1666                 return true;
1667
1668         return false;
1669 }
1670
1671 /**
1672  * update_parent_effective_cpumask - update effective_cpus mask of parent cpuset
1673  * @cs:      The cpuset that requests change in partition root state
1674  * @cmd:     Partition root state change command
1675  * @newmask: Optional new cpumask for partcmd_update
1676  * @tmp:     Temporary addmask and delmask
1677  * Return:   0 or a partition root state error code
1678  *
1679  * For partcmd_enable, the cpuset is being transformed from a non-partition
1680  * root to a partition root. The effective_xcpus (cpus_allowed if effective_xcpus
1681  * not set) mask of the given cpuset will be taken away from parent's
1682  * effective_cpus. The function will return 0 if all the CPUs listed in
1683  * effective_xcpus can be granted or an error code will be returned.
1684  *
1685  * For partcmd_disable, the cpuset is being transformed from a partition
1686  * root back to a non-partition root. Any CPUs in effective_xcpus will be
1687  * given back to parent's effective_cpus. 0 will always be returned.
1688  *
1689  * For partcmd_update, if the optional newmask is specified, the cpu list is
1690  * to be changed from effective_xcpus to newmask. Otherwise, effective_xcpus is
1691  * assumed to remain the same. The cpuset should either be a valid or invalid
1692  * partition root. The partition root state may change from valid to invalid
1693  * or vice versa. An error code will be returned if transitioning from
1694  * invalid to valid violates the exclusivity rule.
1695  *
1696  * For partcmd_invalidate, the current partition will be made invalid.
1697  *
1698  * The partcmd_enable and partcmd_disable commands are used by
1699  * update_prstate(). An error code may be returned and the caller will check
1700  * for error.
1701  *
1702  * The partcmd_update command is used by update_cpumasks_hier() with newmask
1703  * NULL and update_cpumask() with newmask set. The partcmd_invalidate is used
1704  * by update_cpumask() with NULL newmask. In both cases, the callers won't
1705  * check for error and so partition_root_state and prs_error will be updated
1706  * directly.
1707  */
1708 static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
1709                                            struct cpumask *newmask,
1710                                            struct tmpmasks *tmp)
1711 {
1712         struct cpuset *parent = parent_cs(cs);
1713         int adding;     /* Adding cpus to parent's effective_cpus       */
1714         int deleting;   /* Deleting cpus from parent's effective_cpus   */
1715         int old_prs, new_prs;
1716         int part_error = PERR_NONE;     /* Partition error? */
1717         int subparts_delta = 0;
1718         struct cpumask *xcpus;          /* cs effective_xcpus */
1719         bool nocpu;
1720
1721         lockdep_assert_held(&cpuset_mutex);
1722
1723         /*
1724          * new_prs will only be changed for the partcmd_update and
1725          * partcmd_invalidate commands.
1726          */
1727         adding = deleting = false;
1728         old_prs = new_prs = cs->partition_root_state;
1729         xcpus = !cpumask_empty(cs->exclusive_cpus)
1730                 ? cs->effective_xcpus : cs->cpus_allowed;
1731
1732         if (cmd == partcmd_invalidate) {
1733                 if (is_prs_invalid(old_prs))
1734                         return 0;
1735
1736                 /*
1737                  * Make the current partition invalid.
1738                  */
1739                 if (is_partition_valid(parent))
1740                         adding = cpumask_and(tmp->addmask,
1741                                              xcpus, parent->effective_xcpus);
1742                 if (old_prs > 0) {
1743                         new_prs = -old_prs;
1744                         subparts_delta--;
1745                 }
1746                 goto write_error;
1747         }
1748
1749         /*
1750          * The parent must be a partition root.
1751          * The new cpumask, if present, or the current cpus_allowed must
1752          * not be empty.
1753          */
1754         if (!is_partition_valid(parent)) {
1755                 return is_partition_invalid(parent)
1756                        ? PERR_INVPARENT : PERR_NOTPART;
1757         }
1758         if (!newmask && cpumask_empty(cs->cpus_allowed))
1759                 return PERR_CPUSEMPTY;
1760
1761         nocpu = tasks_nocpu_error(parent, cs, xcpus);
1762
1763         if (cmd == partcmd_enable) {
1764                 /*
1765                  * Enabling partition root is not allowed if its
1766                  * effective_xcpus is empty or doesn't overlap with
1767                  * parent's effective_xcpus.
1768                  */
1769                 if (cpumask_empty(xcpus) ||
1770                     !cpumask_intersects(xcpus, parent->effective_xcpus))
1771                         return PERR_INVCPUS;
1772
1773                 if (prstate_housekeeping_conflict(new_prs, xcpus))
1774                         return PERR_HKEEPING;
1775
1776                 /*
1777                  * A parent can be left with no CPU as long as there is no
1778                  * task directly associated with the parent partition.
1779                  */
1780                 if (nocpu)
1781                         return PERR_NOCPUS;
1782
1783                 cpumask_copy(tmp->delmask, xcpus);
1784                 deleting = true;
1785                 subparts_delta++;
1786         } else if (cmd == partcmd_disable) {
1787                 /*
1788                  * May need to add cpus to parent's effective_cpus for
1789                  * valid partition root.
1790                  */
1791                 adding = !is_prs_invalid(old_prs) &&
1792                           cpumask_and(tmp->addmask, xcpus, parent->effective_xcpus);
1793                 if (adding)
1794                         subparts_delta--;
1795         } else if (newmask) {
1796                 /*
1797                  * Empty cpumask is not allowed
1798                  */
1799                 if (cpumask_empty(newmask)) {
1800                         part_error = PERR_CPUSEMPTY;
1801                         goto write_error;
1802                 }
1803
1804                 /*
1805                  * partcmd_update with newmask:
1806                  *
1807                  * Compute add/delete mask to/from effective_cpus
1808                  *
1809                  * addmask = effective_xcpus & ~newmask & parent->effective_xcpus
1810                  * delmask = newmask & ~cs->effective_xcpus
1811                  *                   & parent->effective_xcpus
1812                  */
1813                 cpumask_andnot(tmp->addmask, xcpus, newmask);
1814                 adding = cpumask_and(tmp->addmask, tmp->addmask,
1815                                      parent->effective_xcpus);
1816
1817                 cpumask_andnot(tmp->delmask, newmask, xcpus);
1818                 deleting = cpumask_and(tmp->delmask, tmp->delmask,
1819                                        parent->effective_xcpus);
1820                 /*
1821                  * Make partition invalid if parent's effective_cpus could
1822                  * become empty and there are tasks in the parent.
1823                  */
1824                 if (nocpu && (!adding ||
1825                     !cpumask_intersects(tmp->addmask, cpu_active_mask))) {
1826                         part_error = PERR_NOCPUS;
1827                         deleting = false;
1828                         adding = cpumask_and(tmp->addmask,
1829                                              xcpus, parent->effective_xcpus);
1830                 }
1831         } else {
1832                 /*
1833                  * partcmd_update w/o newmask
1834                  *
1835                  * delmask = effective_xcpus & parent->effective_cpus
1836                  *
1837                  * This can be called from:
1838                  * 1) update_cpumasks_hier()
1839                  * 2) cpuset_hotplug_update_tasks()
1840                  *
1841                  * Check to see if it can be transitioned from valid to
1842                  * invalid partition or vice versa.
1843                  *
1844                  * A partition error happens when parent has tasks and all
1845                  * its effective CPUs will have to be distributed out.
1846                  */
1847                 WARN_ON_ONCE(!is_partition_valid(parent));
1848                 if (nocpu) {
1849                         part_error = PERR_NOCPUS;
1850                         if (is_partition_valid(cs))
1851                                 adding = cpumask_and(tmp->addmask,
1852                                                 xcpus, parent->effective_xcpus);
1853                 } else if (is_partition_invalid(cs) &&
1854                            cpumask_subset(xcpus, parent->effective_xcpus)) {
1855                         struct cgroup_subsys_state *css;
1856                         struct cpuset *child;
1857                         bool exclusive = true;
1858
1859                         /*
1860                          * Convert invalid partition to valid has to
1861                          * pass the cpu exclusivity test.
1862                          */
1863                         rcu_read_lock();
1864                         cpuset_for_each_child(child, css, parent) {
1865                                 if (child == cs)
1866                                         continue;
1867                                 if (cpu_exclusive_check(cs, child)) {
1868                                         exclusive = false;
1869                                         break;
1870                                 }
1871                         }
1872                         rcu_read_unlock();
1873                         if (exclusive)
1874                                 deleting = cpumask_and(tmp->delmask,
1875                                                 xcpus, parent->effective_cpus);
1876                         else
1877                                 part_error = PERR_NOTEXCL;
1878                 }
1879         }
1880
1881 write_error:
1882         if (part_error)
1883                 WRITE_ONCE(cs->prs_err, part_error);
1884
1885         if (cmd == partcmd_update) {
1886                 /*
1887                  * Check for possible transition between valid and invalid
1888                  * partition root.
1889                  */
1890                 switch (cs->partition_root_state) {
1891                 case PRS_ROOT:
1892                 case PRS_ISOLATED:
1893                         if (part_error) {
1894                                 new_prs = -old_prs;
1895                                 subparts_delta--;
1896                         }
1897                         break;
1898                 case PRS_INVALID_ROOT:
1899                 case PRS_INVALID_ISOLATED:
1900                         if (!part_error) {
1901                                 new_prs = -old_prs;
1902                                 subparts_delta++;
1903                         }
1904                         break;
1905                 }
1906         }
1907
1908         if (!adding && !deleting && (new_prs == old_prs))
1909                 return 0;
1910
1911         /*
1912          * Transitioning between invalid to valid or vice versa may require
1913          * changing CS_CPU_EXCLUSIVE.
1914          */
1915         if (old_prs != new_prs) {
1916                 int err = update_partition_exclusive(cs, new_prs);
1917
1918                 if (err)
1919                         return err;
1920         }
1921
1922         /*
1923          * Change the parent's effective_cpus & effective_xcpus (top cpuset
1924          * only).
1925          *
1926          * Newly added CPUs will be removed from effective_cpus and
1927          * newly deleted ones will be added back to effective_cpus.
1928          */
1929         spin_lock_irq(&callback_lock);
1930         if (adding) {
1931                 if (parent == &top_cpuset)
1932                         cpumask_andnot(subpartitions_cpus,
1933                                        subpartitions_cpus, tmp->addmask);
1934                 /*
1935                  * Some of the CPUs in effective_xcpus might have been offlined.
1936                  */
1937                 cpumask_or(parent->effective_cpus,
1938                            parent->effective_cpus, tmp->addmask);
1939                 cpumask_and(parent->effective_cpus,
1940                             parent->effective_cpus, cpu_active_mask);
1941         }
1942         if (deleting) {
1943                 if (parent == &top_cpuset)
1944                         cpumask_or(subpartitions_cpus,
1945                                    subpartitions_cpus, tmp->delmask);
1946                 cpumask_andnot(parent->effective_cpus,
1947                                parent->effective_cpus, tmp->delmask);
1948         }
1949
1950         if (is_partition_valid(parent)) {
1951                 parent->nr_subparts += subparts_delta;
1952                 WARN_ON_ONCE(parent->nr_subparts < 0);
1953         }
1954
1955         if (old_prs != new_prs) {
1956                 cs->partition_root_state = new_prs;
1957                 if (new_prs <= 0)
1958                         cs->nr_subparts = 0;
1959         }
1960
1961         spin_unlock_irq(&callback_lock);
1962
1963         if (adding || deleting) {
1964                 update_tasks_cpumask(parent, tmp->addmask);
1965                 update_sibling_cpumasks(parent, cs, tmp);
1966         }
1967
1968         /*
1969          * For partcmd_update without newmask, it is being called from
1970          * cpuset_hotplug_workfn() where cpus_read_lock() wasn't taken.
1971          * Update the load balance flag and scheduling domain if
1972          * cpus_read_trylock() is successful.
1973          */
1974         if ((cmd == partcmd_update) && !newmask && cpus_read_trylock()) {
1975                 update_partition_sd_lb(cs, old_prs);
1976                 cpus_read_unlock();
1977         }
1978
1979         notify_partition_change(cs, old_prs);
1980         return 0;
1981 }
1982
1983 /**
1984  * compute_partition_effective_cpumask - compute effective_cpus for partition
1985  * @cs: partition root cpuset
1986  * @new_ecpus: previously computed effective_cpus to be updated
1987  *
1988  * Compute the effective_cpus of a partition root by scanning effective_xcpus
1989  * of child partition roots and excluding their effective_xcpus.
1990  *
1991  * This has the side effect of invalidating valid child partition roots,
1992  * if necessary. Since it is called from either cpuset_hotplug_update_tasks()
1993  * or update_cpumasks_hier() where parent and children are modified
1994  * successively, we don't need to call update_parent_effective_cpumask()
1995  * and the child's effective_cpus will be updated in later iterations.
1996  *
1997  * Note that rcu_read_lock() is assumed to be held.
1998  */
1999 static void compute_partition_effective_cpumask(struct cpuset *cs,
2000                                                 struct cpumask *new_ecpus)
2001 {
2002         struct cgroup_subsys_state *css;
2003         struct cpuset *child;
2004         bool populated = partition_is_populated(cs, NULL);
2005
2006         /*
2007          * Check child partition roots to see if they should be
2008          * invalidated when
2009          *  1) child effective_xcpus not a subset of new
2010          *     excluisve_cpus
2011          *  2) All the effective_cpus will be used up and cp
2012          *     has tasks
2013          */
2014         compute_effective_exclusive_cpumask(cs, new_ecpus);
2015         cpumask_and(new_ecpus, new_ecpus, cpu_active_mask);
2016
2017         rcu_read_lock();
2018         cpuset_for_each_child(child, css, cs) {
2019                 if (!is_partition_valid(child))
2020                         continue;
2021
2022                 child->prs_err = 0;
2023                 if (!cpumask_subset(child->effective_xcpus,
2024                                     cs->effective_xcpus))
2025                         child->prs_err = PERR_INVCPUS;
2026                 else if (populated &&
2027                          cpumask_subset(new_ecpus, child->effective_xcpus))
2028                         child->prs_err = PERR_NOCPUS;
2029
2030                 if (child->prs_err) {
2031                         int old_prs = child->partition_root_state;
2032
2033                         /*
2034                          * Invalidate child partition
2035                          */
2036                         spin_lock_irq(&callback_lock);
2037                         make_partition_invalid(child);
2038                         cs->nr_subparts--;
2039                         child->nr_subparts = 0;
2040                         spin_unlock_irq(&callback_lock);
2041                         notify_partition_change(child, old_prs);
2042                         continue;
2043                 }
2044                 cpumask_andnot(new_ecpus, new_ecpus,
2045                                child->effective_xcpus);
2046         }
2047         rcu_read_unlock();
2048 }
2049
2050 /*
2051  * update_cpumasks_hier() flags
2052  */
2053 #define HIER_CHECKALL           0x01    /* Check all cpusets with no skipping */
2054 #define HIER_NO_SD_REBUILD      0x02    /* Don't rebuild sched domains */
2055
2056 /*
2057  * update_cpumasks_hier - Update effective cpumasks and tasks in the subtree
2058  * @cs:  the cpuset to consider
2059  * @tmp: temp variables for calculating effective_cpus & partition setup
2060  * @force: don't skip any descendant cpusets if set
2061  *
2062  * When configured cpumask is changed, the effective cpumasks of this cpuset
2063  * and all its descendants need to be updated.
2064  *
2065  * On legacy hierarchy, effective_cpus will be the same with cpu_allowed.
2066  *
2067  * Called with cpuset_mutex held
2068  */
2069 static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
2070                                  int flags)
2071 {
2072         struct cpuset *cp;
2073         struct cgroup_subsys_state *pos_css;
2074         bool need_rebuild_sched_domains = false;
2075         int old_prs, new_prs;
2076
2077         rcu_read_lock();
2078         cpuset_for_each_descendant_pre(cp, pos_css, cs) {
2079                 struct cpuset *parent = parent_cs(cp);
2080                 bool remote = is_remote_partition(cp);
2081                 bool update_parent = false;
2082
2083                 /*
2084                  * Skip descendent remote partition that acquires CPUs
2085                  * directly from top cpuset unless it is cs.
2086                  */
2087                 if (remote && (cp != cs)) {
2088                         pos_css = css_rightmost_descendant(pos_css);
2089                         continue;
2090                 }
2091
2092                 /*
2093                  * Update effective_xcpus if exclusive_cpus set.
2094                  * The case when exclusive_cpus isn't set is handled later.
2095                  */
2096                 if (!cpumask_empty(cp->exclusive_cpus) && (cp != cs)) {
2097                         spin_lock_irq(&callback_lock);
2098                         compute_effective_exclusive_cpumask(cp, NULL);
2099                         spin_unlock_irq(&callback_lock);
2100                 }
2101
2102                 old_prs = new_prs = cp->partition_root_state;
2103                 if (remote || (is_partition_valid(parent) &&
2104                                is_partition_valid(cp)))
2105                         compute_partition_effective_cpumask(cp, tmp->new_cpus);
2106                 else
2107                         compute_effective_cpumask(tmp->new_cpus, cp, parent);
2108
2109                 /*
2110                  * A partition with no effective_cpus is allowed as long as
2111                  * there is no task associated with it. Call
2112                  * update_parent_effective_cpumask() to check it.
2113                  */
2114                 if (is_partition_valid(cp) && cpumask_empty(tmp->new_cpus)) {
2115                         update_parent = true;
2116                         goto update_parent_effective;
2117                 }
2118
2119                 /*
2120                  * If it becomes empty, inherit the effective mask of the
2121                  * parent, which is guaranteed to have some CPUs unless
2122                  * it is a partition root that has explicitly distributed
2123                  * out all its CPUs.
2124                  */
2125                 if (is_in_v2_mode() && !remote && cpumask_empty(tmp->new_cpus)) {
2126                         cpumask_copy(tmp->new_cpus, parent->effective_cpus);
2127                         if (!cp->use_parent_ecpus) {
2128                                 cp->use_parent_ecpus = true;
2129                                 parent->child_ecpus_count++;
2130                         }
2131                 } else if (cp->use_parent_ecpus) {
2132                         cp->use_parent_ecpus = false;
2133                         WARN_ON_ONCE(!parent->child_ecpus_count);
2134                         parent->child_ecpus_count--;
2135                 }
2136
2137                 if (remote)
2138                         goto get_css;
2139
2140                 /*
2141                  * Skip the whole subtree if
2142                  * 1) the cpumask remains the same,
2143                  * 2) has no partition root state,
2144                  * 3) HIER_CHECKALL flag not set, and
2145                  * 4) for v2 load balance state same as its parent.
2146                  */
2147                 if (!cp->partition_root_state && !(flags & HIER_CHECKALL) &&
2148                     cpumask_equal(tmp->new_cpus, cp->effective_cpus) &&
2149                     (!cgroup_subsys_on_dfl(cpuset_cgrp_subsys) ||
2150                     (is_sched_load_balance(parent) == is_sched_load_balance(cp)))) {
2151                         pos_css = css_rightmost_descendant(pos_css);
2152                         continue;
2153                 }
2154
2155 update_parent_effective:
2156                 /*
2157                  * update_parent_effective_cpumask() should have been called
2158                  * for cs already in update_cpumask(). We should also call
2159                  * update_tasks_cpumask() again for tasks in the parent
2160                  * cpuset if the parent's effective_cpus changes.
2161                  */
2162                 if ((cp != cs) && old_prs) {
2163                         switch (parent->partition_root_state) {
2164                         case PRS_ROOT:
2165                         case PRS_ISOLATED:
2166                                 update_parent = true;
2167                                 break;
2168
2169                         default:
2170                                 /*
2171                                  * When parent is not a partition root or is
2172                                  * invalid, child partition roots become
2173                                  * invalid too.
2174                                  */
2175                                 if (is_partition_valid(cp))
2176                                         new_prs = -cp->partition_root_state;
2177                                 WRITE_ONCE(cp->prs_err,
2178                                            is_partition_invalid(parent)
2179                                            ? PERR_INVPARENT : PERR_NOTPART);
2180                                 break;
2181                         }
2182                 }
2183 get_css:
2184                 if (!css_tryget_online(&cp->css))
2185                         continue;
2186                 rcu_read_unlock();
2187
2188                 if (update_parent) {
2189                         update_parent_effective_cpumask(cp, partcmd_update, NULL, tmp);
2190                         /*
2191                          * The cpuset partition_root_state may become
2192                          * invalid. Capture it.
2193                          */
2194                         new_prs = cp->partition_root_state;
2195                 }
2196
2197                 spin_lock_irq(&callback_lock);
2198                 cpumask_copy(cp->effective_cpus, tmp->new_cpus);
2199                 cp->partition_root_state = new_prs;
2200                 /*
2201                  * Make sure effective_xcpus is properly set for a valid
2202                  * partition root.
2203                  */
2204                 if ((new_prs > 0) && cpumask_empty(cp->exclusive_cpus))
2205                         cpumask_and(cp->effective_xcpus,
2206                                     cp->cpus_allowed, parent->effective_xcpus);
2207                 else if (new_prs < 0)
2208                         reset_partition_data(cp);
2209                 spin_unlock_irq(&callback_lock);
2210
2211                 notify_partition_change(cp, old_prs);
2212
2213                 WARN_ON(!is_in_v2_mode() &&
2214                         !cpumask_equal(cp->cpus_allowed, cp->effective_cpus));
2215
2216                 update_tasks_cpumask(cp, cp->effective_cpus);
2217
2218                 /*
2219                  * On default hierarchy, inherit the CS_SCHED_LOAD_BALANCE
2220                  * from parent if current cpuset isn't a valid partition root
2221                  * and their load balance states differ.
2222                  */
2223                 if (cgroup_subsys_on_dfl(cpuset_cgrp_subsys) &&
2224                     !is_partition_valid(cp) &&
2225                     (is_sched_load_balance(parent) != is_sched_load_balance(cp))) {
2226                         if (is_sched_load_balance(parent))
2227                                 set_bit(CS_SCHED_LOAD_BALANCE, &cp->flags);
2228                         else
2229                                 clear_bit(CS_SCHED_LOAD_BALANCE, &cp->flags);
2230                 }
2231
2232                 /*
2233                  * On legacy hierarchy, if the effective cpumask of any non-
2234                  * empty cpuset is changed, we need to rebuild sched domains.
2235                  * On default hierarchy, the cpuset needs to be a partition
2236                  * root as well.
2237                  */
2238                 if (!cpumask_empty(cp->cpus_allowed) &&
2239                     is_sched_load_balance(cp) &&
2240                    (!cgroup_subsys_on_dfl(cpuset_cgrp_subsys) ||
2241                     is_partition_valid(cp)))
2242                         need_rebuild_sched_domains = true;
2243
2244                 rcu_read_lock();
2245                 css_put(&cp->css);
2246         }
2247         rcu_read_unlock();
2248
2249         if (need_rebuild_sched_domains && !(flags & HIER_NO_SD_REBUILD))
2250                 rebuild_sched_domains_locked();
2251 }
2252
2253 /**
2254  * update_sibling_cpumasks - Update siblings cpumasks
2255  * @parent:  Parent cpuset
2256  * @cs:      Current cpuset
2257  * @tmp:     Temp variables
2258  */
2259 static void update_sibling_cpumasks(struct cpuset *parent, struct cpuset *cs,
2260                                     struct tmpmasks *tmp)
2261 {
2262         struct cpuset *sibling;
2263         struct cgroup_subsys_state *pos_css;
2264
2265         lockdep_assert_held(&cpuset_mutex);
2266
2267         /*
2268          * Check all its siblings and call update_cpumasks_hier()
2269          * if their effective_cpus will need to be changed.
2270          *
2271          * With the addition of effective_xcpus which is a subset of
2272          * cpus_allowed. It is possible a change in parent's effective_cpus
2273          * due to a change in a child partition's effective_xcpus will impact
2274          * its siblings even if they do not inherit parent's effective_cpus
2275          * directly.
2276          *
2277          * The update_cpumasks_hier() function may sleep. So we have to
2278          * release the RCU read lock before calling it. HIER_NO_SD_REBUILD
2279          * flag is used to suppress rebuild of sched domains as the callers
2280          * will take care of that.
2281          */
2282         rcu_read_lock();
2283         cpuset_for_each_child(sibling, pos_css, parent) {
2284                 if (sibling == cs)
2285                         continue;
2286                 if (!sibling->use_parent_ecpus &&
2287                     !is_partition_valid(sibling)) {
2288                         compute_effective_cpumask(tmp->new_cpus, sibling,
2289                                                   parent);
2290                         if (cpumask_equal(tmp->new_cpus, sibling->effective_cpus))
2291                                 continue;
2292                 }
2293                 if (!css_tryget_online(&sibling->css))
2294                         continue;
2295
2296                 rcu_read_unlock();
2297                 update_cpumasks_hier(sibling, tmp, HIER_NO_SD_REBUILD);
2298                 rcu_read_lock();
2299                 css_put(&sibling->css);
2300         }
2301         rcu_read_unlock();
2302 }
2303
2304 /**
2305  * update_cpumask - update the cpus_allowed mask of a cpuset and all tasks in it
2306  * @cs: the cpuset to consider
2307  * @trialcs: trial cpuset
2308  * @buf: buffer of cpu numbers written to this cpuset
2309  */
2310 static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs,
2311                           const char *buf)
2312 {
2313         int retval;
2314         struct tmpmasks tmp;
2315         struct cpuset *parent = parent_cs(cs);
2316         bool invalidate = false;
2317         int hier_flags = 0;
2318         int old_prs = cs->partition_root_state;
2319
2320         /* top_cpuset.cpus_allowed tracks cpu_online_mask; it's read-only */
2321         if (cs == &top_cpuset)
2322                 return -EACCES;
2323
2324         /*
2325          * An empty cpus_allowed is ok only if the cpuset has no tasks.
2326          * Since cpulist_parse() fails on an empty mask, we special case
2327          * that parsing.  The validate_change() call ensures that cpusets
2328          * with tasks have cpus.
2329          */
2330         if (!*buf) {
2331                 cpumask_clear(trialcs->cpus_allowed);
2332                 cpumask_clear(trialcs->effective_xcpus);
2333         } else {
2334                 retval = cpulist_parse(buf, trialcs->cpus_allowed);
2335                 if (retval < 0)
2336                         return retval;
2337
2338                 if (!cpumask_subset(trialcs->cpus_allowed,
2339                                     top_cpuset.cpus_allowed))
2340                         return -EINVAL;
2341
2342                 /*
2343                  * When exclusive_cpus isn't explicitly set, it is constrainted
2344                  * by cpus_allowed and parent's effective_xcpus. Otherwise,
2345                  * trialcs->effective_xcpus is used as a temporary cpumask
2346                  * for checking validity of the partition root.
2347                  */
2348                 if (!cpumask_empty(trialcs->exclusive_cpus) || is_partition_valid(cs))
2349                         compute_effective_exclusive_cpumask(trialcs, NULL);
2350         }
2351
2352         /* Nothing to do if the cpus didn't change */
2353         if (cpumask_equal(cs->cpus_allowed, trialcs->cpus_allowed))
2354                 return 0;
2355
2356         if (alloc_cpumasks(NULL, &tmp))
2357                 return -ENOMEM;
2358
2359         if (is_partition_valid(cs)) {
2360                 if (cpumask_empty(trialcs->effective_xcpus)) {
2361                         invalidate = true;
2362                         cs->prs_err = PERR_INVCPUS;
2363                 } else if (prstate_housekeeping_conflict(old_prs, trialcs->effective_xcpus)) {
2364                         invalidate = true;
2365                         cs->prs_err = PERR_HKEEPING;
2366                 } else if (tasks_nocpu_error(parent, cs, trialcs->effective_xcpus)) {
2367                         invalidate = true;
2368                         cs->prs_err = PERR_NOCPUS;
2369                 }
2370         }
2371
2372         /*
2373          * Check all the descendants in update_cpumasks_hier() if
2374          * effective_xcpus is to be changed.
2375          */
2376         if (!cpumask_equal(cs->effective_xcpus, trialcs->effective_xcpus))
2377                 hier_flags = HIER_CHECKALL;
2378
2379         retval = validate_change(cs, trialcs);
2380
2381         if ((retval == -EINVAL) && cgroup_subsys_on_dfl(cpuset_cgrp_subsys)) {
2382                 struct cgroup_subsys_state *css;
2383                 struct cpuset *cp;
2384
2385                 /*
2386                  * The -EINVAL error code indicates that partition sibling
2387                  * CPU exclusivity rule has been violated. We still allow
2388                  * the cpumask change to proceed while invalidating the
2389                  * partition. However, any conflicting sibling partitions
2390                  * have to be marked as invalid too.
2391                  */
2392                 invalidate = true;
2393                 rcu_read_lock();
2394                 cpuset_for_each_child(cp, css, parent)
2395                         if (is_partition_valid(cp) &&
2396                             cpumask_intersects(trialcs->effective_xcpus, cp->effective_xcpus)) {
2397                                 rcu_read_unlock();
2398                                 update_parent_effective_cpumask(cp, partcmd_invalidate, NULL, &tmp);
2399                                 rcu_read_lock();
2400                         }
2401                 rcu_read_unlock();
2402                 retval = 0;
2403         }
2404
2405         if (retval < 0)
2406                 goto out_free;
2407
2408         if (is_partition_valid(cs)) {
2409                 /*
2410                  * Call remote_cpus_update() to handle valid remote partition
2411                  */
2412                 if (is_remote_partition(cs))
2413                         remote_cpus_update(cs, trialcs->effective_xcpus, &tmp);
2414                 else if (invalidate)
2415                         update_parent_effective_cpumask(cs, partcmd_invalidate,
2416                                                         NULL, &tmp);
2417                 else
2418                         update_parent_effective_cpumask(cs, partcmd_update,
2419                                                 trialcs->effective_xcpus, &tmp);
2420         } else if (!cpumask_empty(cs->exclusive_cpus)) {
2421                 /*
2422                  * Use trialcs->effective_cpus as a temp cpumask
2423                  */
2424                 remote_partition_check(cs, trialcs->effective_xcpus,
2425                                        trialcs->effective_cpus, &tmp);
2426         }
2427
2428         spin_lock_irq(&callback_lock);
2429         cpumask_copy(cs->cpus_allowed, trialcs->cpus_allowed);
2430         cpumask_copy(cs->effective_xcpus, trialcs->effective_xcpus);
2431         if ((old_prs > 0) && !is_partition_valid(cs))
2432                 reset_partition_data(cs);
2433         spin_unlock_irq(&callback_lock);
2434
2435         /* effective_cpus/effective_xcpus will be updated here */
2436         update_cpumasks_hier(cs, &tmp, hier_flags);
2437
2438         /* Update CS_SCHED_LOAD_BALANCE and/or sched_domains, if necessary */
2439         if (cs->partition_root_state)
2440                 update_partition_sd_lb(cs, old_prs);
2441 out_free:
2442         free_cpumasks(NULL, &tmp);
2443         return 0;
2444 }
2445
2446 /**
2447  * update_exclusive_cpumask - update the exclusive_cpus mask of a cpuset
2448  * @cs: the cpuset to consider
2449  * @trialcs: trial cpuset
2450  * @buf: buffer of cpu numbers written to this cpuset
2451  *
2452  * The tasks' cpumask will be updated if cs is a valid partition root.
2453  */
2454 static int update_exclusive_cpumask(struct cpuset *cs, struct cpuset *trialcs,
2455                                     const char *buf)
2456 {
2457         int retval;
2458         struct tmpmasks tmp;
2459         struct cpuset *parent = parent_cs(cs);
2460         bool invalidate = false;
2461         int hier_flags = 0;
2462         int old_prs = cs->partition_root_state;
2463
2464         if (!*buf) {
2465                 cpumask_clear(trialcs->exclusive_cpus);
2466                 cpumask_clear(trialcs->effective_xcpus);
2467         } else {
2468                 retval = cpulist_parse(buf, trialcs->exclusive_cpus);
2469                 if (retval < 0)
2470                         return retval;
2471                 if (!is_cpu_exclusive(cs))
2472                         set_bit(CS_CPU_EXCLUSIVE, &trialcs->flags);
2473         }
2474
2475         /* Nothing to do if the CPUs didn't change */
2476         if (cpumask_equal(cs->exclusive_cpus, trialcs->exclusive_cpus))
2477                 return 0;
2478
2479         if (alloc_cpumasks(NULL, &tmp))
2480                 return -ENOMEM;
2481
2482         if (*buf)
2483                 compute_effective_exclusive_cpumask(trialcs, NULL);
2484
2485         /*
2486          * Check all the descendants in update_cpumasks_hier() if
2487          * effective_xcpus is to be changed.
2488          */
2489         if (!cpumask_equal(cs->effective_xcpus, trialcs->effective_xcpus))
2490                 hier_flags = HIER_CHECKALL;
2491
2492         retval = validate_change(cs, trialcs);
2493         if (retval)
2494                 return retval;
2495
2496         if (is_partition_valid(cs)) {
2497                 if (cpumask_empty(trialcs->effective_xcpus)) {
2498                         invalidate = true;
2499                         cs->prs_err = PERR_INVCPUS;
2500                 } else if (prstate_housekeeping_conflict(old_prs, trialcs->effective_xcpus)) {
2501                         invalidate = true;
2502                         cs->prs_err = PERR_HKEEPING;
2503                 } else if (tasks_nocpu_error(parent, cs, trialcs->effective_xcpus)) {
2504                         invalidate = true;
2505                         cs->prs_err = PERR_NOCPUS;
2506                 }
2507
2508                 if (is_remote_partition(cs)) {
2509                         if (invalidate)
2510                                 remote_partition_disable(cs, &tmp);
2511                         else
2512                                 remote_cpus_update(cs, trialcs->effective_xcpus,
2513                                                    &tmp);
2514                 } else if (invalidate) {
2515                         update_parent_effective_cpumask(cs, partcmd_invalidate,
2516                                                         NULL, &tmp);
2517                 } else {
2518                         update_parent_effective_cpumask(cs, partcmd_update,
2519                                                 trialcs->effective_xcpus, &tmp);
2520                 }
2521         } else if (!cpumask_empty(trialcs->exclusive_cpus)) {
2522                 /*
2523                  * Use trialcs->effective_cpus as a temp cpumask
2524                  */
2525                 remote_partition_check(cs, trialcs->effective_xcpus,
2526                                        trialcs->effective_cpus, &tmp);
2527         }
2528         spin_lock_irq(&callback_lock);
2529         cpumask_copy(cs->exclusive_cpus, trialcs->exclusive_cpus);
2530         cpumask_copy(cs->effective_xcpus, trialcs->effective_xcpus);
2531         if ((old_prs > 0) && !is_partition_valid(cs))
2532                 reset_partition_data(cs);
2533         spin_unlock_irq(&callback_lock);
2534
2535         /*
2536          * Call update_cpumasks_hier() to update effective_cpus/effective_xcpus
2537          * of the subtree when it is a valid partition root or effective_xcpus
2538          * is updated.
2539          */
2540         if (is_partition_valid(cs) || hier_flags)
2541                 update_cpumasks_hier(cs, &tmp, hier_flags);
2542
2543         /* Update CS_SCHED_LOAD_BALANCE and/or sched_domains, if necessary */
2544         if (cs->partition_root_state)
2545                 update_partition_sd_lb(cs, old_prs);
2546
2547         free_cpumasks(NULL, &tmp);
2548         return 0;
2549 }
2550
2551 /*
2552  * Migrate memory region from one set of nodes to another.  This is
2553  * performed asynchronously as it can be called from process migration path
2554  * holding locks involved in process management.  All mm migrations are
2555  * performed in the queued order and can be waited for by flushing
2556  * cpuset_migrate_mm_wq.
2557  */
2558
2559 struct cpuset_migrate_mm_work {
2560         struct work_struct      work;
2561         struct mm_struct        *mm;
2562         nodemask_t              from;
2563         nodemask_t              to;
2564 };
2565
2566 static void cpuset_migrate_mm_workfn(struct work_struct *work)
2567 {
2568         struct cpuset_migrate_mm_work *mwork =
2569                 container_of(work, struct cpuset_migrate_mm_work, work);
2570
2571         /* on a wq worker, no need to worry about %current's mems_allowed */
2572         do_migrate_pages(mwork->mm, &mwork->from, &mwork->to, MPOL_MF_MOVE_ALL);
2573         mmput(mwork->mm);
2574         kfree(mwork);
2575 }
2576
2577 static void cpuset_migrate_mm(struct mm_struct *mm, const nodemask_t *from,
2578                                                         const nodemask_t *to)
2579 {
2580         struct cpuset_migrate_mm_work *mwork;
2581
2582         if (nodes_equal(*from, *to)) {
2583                 mmput(mm);
2584                 return;
2585         }
2586
2587         mwork = kzalloc(sizeof(*mwork), GFP_KERNEL);
2588         if (mwork) {
2589                 mwork->mm = mm;
2590                 mwork->from = *from;
2591                 mwork->to = *to;
2592                 INIT_WORK(&mwork->work, cpuset_migrate_mm_workfn);
2593                 queue_work(cpuset_migrate_mm_wq, &mwork->work);
2594         } else {
2595                 mmput(mm);
2596         }
2597 }
2598
2599 static void cpuset_post_attach(void)
2600 {
2601         flush_workqueue(cpuset_migrate_mm_wq);
2602 }
2603
2604 /*
2605  * cpuset_change_task_nodemask - change task's mems_allowed and mempolicy
2606  * @tsk: the task to change
2607  * @newmems: new nodes that the task will be set
2608  *
2609  * We use the mems_allowed_seq seqlock to safely update both tsk->mems_allowed
2610  * and rebind an eventual tasks' mempolicy. If the task is allocating in
2611  * parallel, it might temporarily see an empty intersection, which results in
2612  * a seqlock check and retry before OOM or allocation failure.
2613  */
2614 static void cpuset_change_task_nodemask(struct task_struct *tsk,
2615                                         nodemask_t *newmems)
2616 {
2617         task_lock(tsk);
2618
2619         local_irq_disable();
2620         write_seqcount_begin(&tsk->mems_allowed_seq);
2621
2622         nodes_or(tsk->mems_allowed, tsk->mems_allowed, *newmems);
2623         mpol_rebind_task(tsk, newmems);
2624         tsk->mems_allowed = *newmems;
2625
2626         write_seqcount_end(&tsk->mems_allowed_seq);
2627         local_irq_enable();
2628
2629         task_unlock(tsk);
2630 }
2631
2632 static void *cpuset_being_rebound;
2633
2634 /**
2635  * update_tasks_nodemask - Update the nodemasks of tasks in the cpuset.
2636  * @cs: the cpuset in which each task's mems_allowed mask needs to be changed
2637  *
2638  * Iterate through each task of @cs updating its mems_allowed to the
2639  * effective cpuset's.  As this function is called with cpuset_mutex held,
2640  * cpuset membership stays stable.
2641  */
2642 static void update_tasks_nodemask(struct cpuset *cs)
2643 {
2644         static nodemask_t newmems;      /* protected by cpuset_mutex */
2645         struct css_task_iter it;
2646         struct task_struct *task;
2647
2648         cpuset_being_rebound = cs;              /* causes mpol_dup() rebind */
2649
2650         guarantee_online_mems(cs, &newmems);
2651
2652         /*
2653          * The mpol_rebind_mm() call takes mmap_lock, which we couldn't
2654          * take while holding tasklist_lock.  Forks can happen - the
2655          * mpol_dup() cpuset_being_rebound check will catch such forks,
2656          * and rebind their vma mempolicies too.  Because we still hold
2657          * the global cpuset_mutex, we know that no other rebind effort
2658          * will be contending for the global variable cpuset_being_rebound.
2659          * It's ok if we rebind the same mm twice; mpol_rebind_mm()
2660          * is idempotent.  Also migrate pages in each mm to new nodes.
2661          */
2662         css_task_iter_start(&cs->css, 0, &it);
2663         while ((task = css_task_iter_next(&it))) {
2664                 struct mm_struct *mm;
2665                 bool migrate;
2666
2667                 cpuset_change_task_nodemask(task, &newmems);
2668
2669                 mm = get_task_mm(task);
2670                 if (!mm)
2671                         continue;
2672
2673                 migrate = is_memory_migrate(cs);
2674
2675                 mpol_rebind_mm(mm, &cs->mems_allowed);
2676                 if (migrate)
2677                         cpuset_migrate_mm(mm, &cs->old_mems_allowed, &newmems);
2678                 else
2679                         mmput(mm);
2680         }
2681         css_task_iter_end(&it);
2682
2683         /*
2684          * All the tasks' nodemasks have been updated, update
2685          * cs->old_mems_allowed.
2686          */
2687         cs->old_mems_allowed = newmems;
2688
2689         /* We're done rebinding vmas to this cpuset's new mems_allowed. */
2690         cpuset_being_rebound = NULL;
2691 }
2692
2693 /*
2694  * update_nodemasks_hier - Update effective nodemasks and tasks in the subtree
2695  * @cs: the cpuset to consider
2696  * @new_mems: a temp variable for calculating new effective_mems
2697  *
2698  * When configured nodemask is changed, the effective nodemasks of this cpuset
2699  * and all its descendants need to be updated.
2700  *
2701  * On legacy hierarchy, effective_mems will be the same with mems_allowed.
2702  *
2703  * Called with cpuset_mutex held
2704  */
2705 static void update_nodemasks_hier(struct cpuset *cs, nodemask_t *new_mems)
2706 {
2707         struct cpuset *cp;
2708         struct cgroup_subsys_state *pos_css;
2709
2710         rcu_read_lock();
2711         cpuset_for_each_descendant_pre(cp, pos_css, cs) {
2712                 struct cpuset *parent = parent_cs(cp);
2713
2714                 nodes_and(*new_mems, cp->mems_allowed, parent->effective_mems);
2715
2716                 /*
2717                  * If it becomes empty, inherit the effective mask of the
2718                  * parent, which is guaranteed to have some MEMs.
2719                  */
2720                 if (is_in_v2_mode() && nodes_empty(*new_mems))
2721                         *new_mems = parent->effective_mems;
2722
2723                 /* Skip the whole subtree if the nodemask remains the same. */
2724                 if (nodes_equal(*new_mems, cp->effective_mems)) {
2725                         pos_css = css_rightmost_descendant(pos_css);
2726                         continue;
2727                 }
2728
2729                 if (!css_tryget_online(&cp->css))
2730                         continue;
2731                 rcu_read_unlock();
2732
2733                 spin_lock_irq(&callback_lock);
2734                 cp->effective_mems = *new_mems;
2735                 spin_unlock_irq(&callback_lock);
2736
2737                 WARN_ON(!is_in_v2_mode() &&
2738                         !nodes_equal(cp->mems_allowed, cp->effective_mems));
2739
2740                 update_tasks_nodemask(cp);
2741
2742                 rcu_read_lock();
2743                 css_put(&cp->css);
2744         }
2745         rcu_read_unlock();
2746 }
2747
2748 /*
2749  * Handle user request to change the 'mems' memory placement
2750  * of a cpuset.  Needs to validate the request, update the
2751  * cpusets mems_allowed, and for each task in the cpuset,
2752  * update mems_allowed and rebind task's mempolicy and any vma
2753  * mempolicies and if the cpuset is marked 'memory_migrate',
2754  * migrate the tasks pages to the new memory.
2755  *
2756  * Call with cpuset_mutex held. May take callback_lock during call.
2757  * Will take tasklist_lock, scan tasklist for tasks in cpuset cs,
2758  * lock each such tasks mm->mmap_lock, scan its vma's and rebind
2759  * their mempolicies to the cpusets new mems_allowed.
2760  */
2761 static int update_nodemask(struct cpuset *cs, struct cpuset *trialcs,
2762                            const char *buf)
2763 {
2764         int retval;
2765
2766         /*
2767          * top_cpuset.mems_allowed tracks node_stats[N_MEMORY];
2768          * it's read-only
2769          */
2770         if (cs == &top_cpuset) {
2771                 retval = -EACCES;
2772                 goto done;
2773         }
2774
2775         /*
2776          * An empty mems_allowed is ok iff there are no tasks in the cpuset.
2777          * Since nodelist_parse() fails on an empty mask, we special case
2778          * that parsing.  The validate_change() call ensures that cpusets
2779          * with tasks have memory.
2780          */
2781         if (!*buf) {
2782                 nodes_clear(trialcs->mems_allowed);
2783         } else {
2784                 retval = nodelist_parse(buf, trialcs->mems_allowed);
2785                 if (retval < 0)
2786                         goto done;
2787
2788                 if (!nodes_subset(trialcs->mems_allowed,
2789                                   top_cpuset.mems_allowed)) {
2790                         retval = -EINVAL;
2791                         goto done;
2792                 }
2793         }
2794
2795         if (nodes_equal(cs->mems_allowed, trialcs->mems_allowed)) {
2796                 retval = 0;             /* Too easy - nothing to do */
2797                 goto done;
2798         }
2799         retval = validate_change(cs, trialcs);
2800         if (retval < 0)
2801                 goto done;
2802
2803         check_insane_mems_config(&trialcs->mems_allowed);
2804
2805         spin_lock_irq(&callback_lock);
2806         cs->mems_allowed = trialcs->mems_allowed;
2807         spin_unlock_irq(&callback_lock);
2808
2809         /* use trialcs->mems_allowed as a temp variable */
2810         update_nodemasks_hier(cs, &trialcs->mems_allowed);
2811 done:
2812         return retval;
2813 }
2814
2815 bool current_cpuset_is_being_rebound(void)
2816 {
2817         bool ret;
2818
2819         rcu_read_lock();
2820         ret = task_cs(current) == cpuset_being_rebound;
2821         rcu_read_unlock();
2822
2823         return ret;
2824 }
2825
2826 static int update_relax_domain_level(struct cpuset *cs, s64 val)
2827 {
2828 #ifdef CONFIG_SMP
2829         if (val < -1 || val >= sched_domain_level_max)
2830                 return -EINVAL;
2831 #endif
2832
2833         if (val != cs->relax_domain_level) {
2834                 cs->relax_domain_level = val;
2835                 if (!cpumask_empty(cs->cpus_allowed) &&
2836                     is_sched_load_balance(cs))
2837                         rebuild_sched_domains_locked();
2838         }
2839
2840         return 0;
2841 }
2842
2843 /**
2844  * update_tasks_flags - update the spread flags of tasks in the cpuset.
2845  * @cs: the cpuset in which each task's spread flags needs to be changed
2846  *
2847  * Iterate through each task of @cs updating its spread flags.  As this
2848  * function is called with cpuset_mutex held, cpuset membership stays
2849  * stable.
2850  */
2851 static void update_tasks_flags(struct cpuset *cs)
2852 {
2853         struct css_task_iter it;
2854         struct task_struct *task;
2855
2856         css_task_iter_start(&cs->css, 0, &it);
2857         while ((task = css_task_iter_next(&it)))
2858                 cpuset_update_task_spread_flags(cs, task);
2859         css_task_iter_end(&it);
2860 }
2861
2862 /*
2863  * update_flag - read a 0 or a 1 in a file and update associated flag
2864  * bit:         the bit to update (see cpuset_flagbits_t)
2865  * cs:          the cpuset to update
2866  * turning_on:  whether the flag is being set or cleared
2867  *
2868  * Call with cpuset_mutex held.
2869  */
2870
2871 static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs,
2872                        int turning_on)
2873 {
2874         struct cpuset *trialcs;
2875         int balance_flag_changed;
2876         int spread_flag_changed;
2877         int err;
2878
2879         trialcs = alloc_trial_cpuset(cs);
2880         if (!trialcs)
2881                 return -ENOMEM;
2882
2883         if (turning_on)
2884                 set_bit(bit, &trialcs->flags);
2885         else
2886                 clear_bit(bit, &trialcs->flags);
2887
2888         err = validate_change(cs, trialcs);
2889         if (err < 0)
2890                 goto out;
2891
2892         balance_flag_changed = (is_sched_load_balance(cs) !=
2893                                 is_sched_load_balance(trialcs));
2894
2895         spread_flag_changed = ((is_spread_slab(cs) != is_spread_slab(trialcs))
2896                         || (is_spread_page(cs) != is_spread_page(trialcs)));
2897
2898         spin_lock_irq(&callback_lock);
2899         cs->flags = trialcs->flags;
2900         spin_unlock_irq(&callback_lock);
2901
2902         if (!cpumask_empty(trialcs->cpus_allowed) && balance_flag_changed)
2903                 rebuild_sched_domains_locked();
2904
2905         if (spread_flag_changed)
2906                 update_tasks_flags(cs);
2907 out:
2908         free_cpuset(trialcs);
2909         return err;
2910 }
2911
2912 /**
2913  * update_prstate - update partition_root_state
2914  * @cs: the cpuset to update
2915  * @new_prs: new partition root state
2916  * Return: 0 if successful, != 0 if error
2917  *
2918  * Call with cpuset_mutex held.
2919  */
2920 static int update_prstate(struct cpuset *cs, int new_prs)
2921 {
2922         int err = PERR_NONE, old_prs = cs->partition_root_state;
2923         struct cpuset *parent = parent_cs(cs);
2924         struct tmpmasks tmpmask;
2925
2926         if (old_prs == new_prs)
2927                 return 0;
2928
2929         /*
2930          * For a previously invalid partition root with valid partition root
2931          * parent, treat it as if it is a "member". Otherwise, reject it as
2932          * remote partition cannot currently self-recover from an invalid
2933          * state.
2934          */
2935         if (new_prs && is_prs_invalid(old_prs)) {
2936                 if (is_partition_valid(parent)) {
2937                         old_prs = PRS_MEMBER;
2938                 } else {
2939                         cs->partition_root_state = -new_prs;
2940                         return 0;
2941                 }
2942         }
2943
2944         if (alloc_cpumasks(NULL, &tmpmask))
2945                 return -ENOMEM;
2946
2947         /*
2948          * Setup effective_xcpus if not properly set yet, it will be cleared
2949          * later if partition becomes invalid.
2950          */
2951         if ((new_prs > 0) && cpumask_empty(cs->exclusive_cpus)) {
2952                 spin_lock_irq(&callback_lock);
2953                 cpumask_and(cs->effective_xcpus,
2954                             cs->cpus_allowed, parent->effective_xcpus);
2955                 spin_unlock_irq(&callback_lock);
2956         }
2957
2958         err = update_partition_exclusive(cs, new_prs);
2959         if (err)
2960                 goto out;
2961
2962         if (!old_prs) {
2963                 /*
2964                  * cpus_allowed cannot be empty.
2965                  */
2966                 if (cpumask_empty(cs->cpus_allowed)) {
2967                         err = PERR_CPUSEMPTY;
2968                         goto out;
2969                 }
2970
2971                 err = update_parent_effective_cpumask(cs, partcmd_enable,
2972                                                       NULL, &tmpmask);
2973                 /*
2974                  * If an attempt to become local partition root fails,
2975                  * try to become a remote partition root instead.
2976                  */
2977                 if (err && remote_partition_enable(cs, &tmpmask))
2978                         err = 0;
2979         } else if (old_prs && new_prs) {
2980                 /*
2981                  * A change in load balance state only, no change in cpumasks.
2982                  */
2983                 ;
2984         } else {
2985                 /*
2986                  * Switching back to member is always allowed even if it
2987                  * disables child partitions.
2988                  */
2989                 if (is_remote_partition(cs))
2990                         remote_partition_disable(cs, &tmpmask);
2991                 else
2992                         update_parent_effective_cpumask(cs, partcmd_disable,
2993                                                         NULL, &tmpmask);
2994
2995                 /*
2996                  * Invalidation of child partitions will be done in
2997                  * update_cpumasks_hier().
2998                  */
2999         }
3000 out:
3001         /*
3002          * Make partition invalid & disable CS_CPU_EXCLUSIVE if an error
3003          * happens.
3004          */
3005         if (err) {
3006                 new_prs = -new_prs;
3007                 update_partition_exclusive(cs, new_prs);
3008         }
3009
3010         spin_lock_irq(&callback_lock);
3011         cs->partition_root_state = new_prs;
3012         WRITE_ONCE(cs->prs_err, err);
3013         if (!is_partition_valid(cs))
3014                 reset_partition_data(cs);
3015         spin_unlock_irq(&callback_lock);
3016
3017         /* Force update if switching back to member */
3018         update_cpumasks_hier(cs, &tmpmask, !new_prs ? HIER_CHECKALL : 0);
3019
3020         /* Update sched domains and load balance flag */
3021         update_partition_sd_lb(cs, old_prs);
3022
3023         notify_partition_change(cs, old_prs);
3024         free_cpumasks(NULL, &tmpmask);
3025         return 0;
3026 }
3027
3028 /*
3029  * Frequency meter - How fast is some event occurring?
3030  *
3031  * These routines manage a digitally filtered, constant time based,
3032  * event frequency meter.  There are four routines:
3033  *   fmeter_init() - initialize a frequency meter.
3034  *   fmeter_markevent() - called each time the event happens.
3035  *   fmeter_getrate() - returns the recent rate of such events.
3036  *   fmeter_update() - internal routine used to update fmeter.
3037  *
3038  * A common data structure is passed to each of these routines,
3039  * which is used to keep track of the state required to manage the
3040  * frequency meter and its digital filter.
3041  *
3042  * The filter works on the number of events marked per unit time.
3043  * The filter is single-pole low-pass recursive (IIR).  The time unit
3044  * is 1 second.  Arithmetic is done using 32-bit integers scaled to
3045  * simulate 3 decimal digits of precision (multiplied by 1000).
3046  *
3047  * With an FM_COEF of 933, and a time base of 1 second, the filter
3048  * has a half-life of 10 seconds, meaning that if the events quit
3049  * happening, then the rate returned from the fmeter_getrate()
3050  * will be cut in half each 10 seconds, until it converges to zero.
3051  *
3052  * It is not worth doing a real infinitely recursive filter.  If more
3053  * than FM_MAXTICKS ticks have elapsed since the last filter event,
3054  * just compute FM_MAXTICKS ticks worth, by which point the level
3055  * will be stable.
3056  *
3057  * Limit the count of unprocessed events to FM_MAXCNT, so as to avoid
3058  * arithmetic overflow in the fmeter_update() routine.
3059  *
3060  * Given the simple 32 bit integer arithmetic used, this meter works
3061  * best for reporting rates between one per millisecond (msec) and
3062  * one per 32 (approx) seconds.  At constant rates faster than one
3063  * per msec it maxes out at values just under 1,000,000.  At constant
3064  * rates between one per msec, and one per second it will stabilize
3065  * to a value N*1000, where N is the rate of events per second.
3066  * At constant rates between one per second and one per 32 seconds,
3067  * it will be choppy, moving up on the seconds that have an event,
3068  * and then decaying until the next event.  At rates slower than
3069  * about one in 32 seconds, it decays all the way back to zero between
3070  * each event.
3071  */
3072
3073 #define FM_COEF 933             /* coefficient for half-life of 10 secs */
3074 #define FM_MAXTICKS ((u32)99)   /* useless computing more ticks than this */
3075 #define FM_MAXCNT 1000000       /* limit cnt to avoid overflow */
3076 #define FM_SCALE 1000           /* faux fixed point scale */
3077
3078 /* Initialize a frequency meter */
3079 static void fmeter_init(struct fmeter *fmp)
3080 {
3081         fmp->cnt = 0;
3082         fmp->val = 0;
3083         fmp->time = 0;
3084         spin_lock_init(&fmp->lock);
3085 }
3086
3087 /* Internal meter update - process cnt events and update value */
3088 static void fmeter_update(struct fmeter *fmp)
3089 {
3090         time64_t now;
3091         u32 ticks;
3092
3093         now = ktime_get_seconds();
3094         ticks = now - fmp->time;
3095
3096         if (ticks == 0)
3097                 return;
3098
3099         ticks = min(FM_MAXTICKS, ticks);
3100         while (ticks-- > 0)
3101                 fmp->val = (FM_COEF * fmp->val) / FM_SCALE;
3102         fmp->time = now;
3103
3104         fmp->val += ((FM_SCALE - FM_COEF) * fmp->cnt) / FM_SCALE;
3105         fmp->cnt = 0;
3106 }
3107
3108 /* Process any previous ticks, then bump cnt by one (times scale). */
3109 static void fmeter_markevent(struct fmeter *fmp)
3110 {
3111         spin_lock(&fmp->lock);
3112         fmeter_update(fmp);
3113         fmp->cnt = min(FM_MAXCNT, fmp->cnt + FM_SCALE);
3114         spin_unlock(&fmp->lock);
3115 }
3116
3117 /* Process any previous ticks, then return current value. */
3118 static int fmeter_getrate(struct fmeter *fmp)
3119 {
3120         int val;
3121
3122         spin_lock(&fmp->lock);
3123         fmeter_update(fmp);
3124         val = fmp->val;
3125         spin_unlock(&fmp->lock);
3126         return val;
3127 }
3128
3129 static struct cpuset *cpuset_attach_old_cs;
3130
3131 /*
3132  * Check to see if a cpuset can accept a new task
3133  * For v1, cpus_allowed and mems_allowed can't be empty.
3134  * For v2, effective_cpus can't be empty.
3135  * Note that in v1, effective_cpus = cpus_allowed.
3136  */
3137 static int cpuset_can_attach_check(struct cpuset *cs)
3138 {
3139         if (cpumask_empty(cs->effective_cpus) ||
3140            (!is_in_v2_mode() && nodes_empty(cs->mems_allowed)))
3141                 return -ENOSPC;
3142         return 0;
3143 }
3144
3145 static void reset_migrate_dl_data(struct cpuset *cs)
3146 {
3147         cs->nr_migrate_dl_tasks = 0;
3148         cs->sum_migrate_dl_bw = 0;
3149 }
3150
3151 /* Called by cgroups to determine if a cpuset is usable; cpuset_mutex held */
3152 static int cpuset_can_attach(struct cgroup_taskset *tset)
3153 {
3154         struct cgroup_subsys_state *css;
3155         struct cpuset *cs, *oldcs;
3156         struct task_struct *task;
3157         bool cpus_updated, mems_updated;
3158         int ret;
3159
3160         /* used later by cpuset_attach() */
3161         cpuset_attach_old_cs = task_cs(cgroup_taskset_first(tset, &css));
3162         oldcs = cpuset_attach_old_cs;
3163         cs = css_cs(css);
3164
3165         mutex_lock(&cpuset_mutex);
3166
3167         /* Check to see if task is allowed in the cpuset */
3168         ret = cpuset_can_attach_check(cs);
3169         if (ret)
3170                 goto out_unlock;
3171
3172         cpus_updated = !cpumask_equal(cs->effective_cpus, oldcs->effective_cpus);
3173         mems_updated = !nodes_equal(cs->effective_mems, oldcs->effective_mems);
3174
3175         cgroup_taskset_for_each(task, css, tset) {
3176                 ret = task_can_attach(task);
3177                 if (ret)
3178                         goto out_unlock;
3179
3180                 /*
3181                  * Skip rights over task check in v2 when nothing changes,
3182                  * migration permission derives from hierarchy ownership in
3183                  * cgroup_procs_write_permission()).
3184                  */
3185                 if (!cgroup_subsys_on_dfl(cpuset_cgrp_subsys) ||
3186                     (cpus_updated || mems_updated)) {
3187                         ret = security_task_setscheduler(task);
3188                         if (ret)
3189                                 goto out_unlock;
3190                 }
3191
3192                 if (dl_task(task)) {
3193                         cs->nr_migrate_dl_tasks++;
3194                         cs->sum_migrate_dl_bw += task->dl.dl_bw;
3195                 }
3196         }
3197
3198         if (!cs->nr_migrate_dl_tasks)
3199                 goto out_success;
3200
3201         if (!cpumask_intersects(oldcs->effective_cpus, cs->effective_cpus)) {
3202                 int cpu = cpumask_any_and(cpu_active_mask, cs->effective_cpus);
3203
3204                 if (unlikely(cpu >= nr_cpu_ids)) {
3205                         reset_migrate_dl_data(cs);
3206                         ret = -EINVAL;
3207                         goto out_unlock;
3208                 }
3209
3210                 ret = dl_bw_alloc(cpu, cs->sum_migrate_dl_bw);
3211                 if (ret) {
3212                         reset_migrate_dl_data(cs);
3213                         goto out_unlock;
3214                 }
3215         }
3216
3217 out_success:
3218         /*
3219          * Mark attach is in progress.  This makes validate_change() fail
3220          * changes which zero cpus/mems_allowed.
3221          */
3222         cs->attach_in_progress++;
3223 out_unlock:
3224         mutex_unlock(&cpuset_mutex);
3225         return ret;
3226 }
3227
3228 static void cpuset_cancel_attach(struct cgroup_taskset *tset)
3229 {
3230         struct cgroup_subsys_state *css;
3231         struct cpuset *cs;
3232
3233         cgroup_taskset_first(tset, &css);
3234         cs = css_cs(css);
3235
3236         mutex_lock(&cpuset_mutex);
3237         cs->attach_in_progress--;
3238         if (!cs->attach_in_progress)
3239                 wake_up(&cpuset_attach_wq);
3240
3241         if (cs->nr_migrate_dl_tasks) {
3242                 int cpu = cpumask_any(cs->effective_cpus);
3243
3244                 dl_bw_free(cpu, cs->sum_migrate_dl_bw);
3245                 reset_migrate_dl_data(cs);
3246         }
3247
3248         mutex_unlock(&cpuset_mutex);
3249 }
3250
3251 /*
3252  * Protected by cpuset_mutex. cpus_attach is used only by cpuset_attach_task()
3253  * but we can't allocate it dynamically there.  Define it global and
3254  * allocate from cpuset_init().
3255  */
3256 static cpumask_var_t cpus_attach;
3257 static nodemask_t cpuset_attach_nodemask_to;
3258
3259 static void cpuset_attach_task(struct cpuset *cs, struct task_struct *task)
3260 {
3261         lockdep_assert_held(&cpuset_mutex);
3262
3263         if (cs != &top_cpuset)
3264                 guarantee_online_cpus(task, cpus_attach);
3265         else
3266                 cpumask_andnot(cpus_attach, task_cpu_possible_mask(task),
3267                                subpartitions_cpus);
3268         /*
3269          * can_attach beforehand should guarantee that this doesn't
3270          * fail.  TODO: have a better way to handle failure here
3271          */
3272         WARN_ON_ONCE(set_cpus_allowed_ptr(task, cpus_attach));
3273
3274         cpuset_change_task_nodemask(task, &cpuset_attach_nodemask_to);
3275         cpuset_update_task_spread_flags(cs, task);
3276 }
3277
3278 static void cpuset_attach(struct cgroup_taskset *tset)
3279 {
3280         struct task_struct *task;
3281         struct task_struct *leader;
3282         struct cgroup_subsys_state *css;
3283         struct cpuset *cs;
3284         struct cpuset *oldcs = cpuset_attach_old_cs;
3285         bool cpus_updated, mems_updated;
3286
3287         cgroup_taskset_first(tset, &css);
3288         cs = css_cs(css);
3289
3290         lockdep_assert_cpus_held();     /* see cgroup_attach_lock() */
3291         mutex_lock(&cpuset_mutex);
3292         cpus_updated = !cpumask_equal(cs->effective_cpus,
3293                                       oldcs->effective_cpus);
3294         mems_updated = !nodes_equal(cs->effective_mems, oldcs->effective_mems);
3295
3296         /*
3297          * In the default hierarchy, enabling cpuset in the child cgroups
3298          * will trigger a number of cpuset_attach() calls with no change
3299          * in effective cpus and mems. In that case, we can optimize out
3300          * by skipping the task iteration and update.
3301          */
3302         if (cgroup_subsys_on_dfl(cpuset_cgrp_subsys) &&
3303             !cpus_updated && !mems_updated) {
3304                 cpuset_attach_nodemask_to = cs->effective_mems;
3305                 goto out;
3306         }
3307
3308         guarantee_online_mems(cs, &cpuset_attach_nodemask_to);
3309
3310         cgroup_taskset_for_each(task, css, tset)
3311                 cpuset_attach_task(cs, task);
3312
3313         /*
3314          * Change mm for all threadgroup leaders. This is expensive and may
3315          * sleep and should be moved outside migration path proper. Skip it
3316          * if there is no change in effective_mems and CS_MEMORY_MIGRATE is
3317          * not set.
3318          */
3319         cpuset_attach_nodemask_to = cs->effective_mems;
3320         if (!is_memory_migrate(cs) && !mems_updated)
3321                 goto out;
3322
3323         cgroup_taskset_for_each_leader(leader, css, tset) {
3324                 struct mm_struct *mm = get_task_mm(leader);
3325
3326                 if (mm) {
3327                         mpol_rebind_mm(mm, &cpuset_attach_nodemask_to);
3328
3329                         /*
3330                          * old_mems_allowed is the same with mems_allowed
3331                          * here, except if this task is being moved
3332                          * automatically due to hotplug.  In that case
3333                          * @mems_allowed has been updated and is empty, so
3334                          * @old_mems_allowed is the right nodesets that we
3335                          * migrate mm from.
3336                          */
3337                         if (is_memory_migrate(cs))
3338                                 cpuset_migrate_mm(mm, &oldcs->old_mems_allowed,
3339                                                   &cpuset_attach_nodemask_to);
3340                         else
3341                                 mmput(mm);
3342                 }
3343         }
3344
3345 out:
3346         cs->old_mems_allowed = cpuset_attach_nodemask_to;
3347
3348         if (cs->nr_migrate_dl_tasks) {
3349                 cs->nr_deadline_tasks += cs->nr_migrate_dl_tasks;
3350                 oldcs->nr_deadline_tasks -= cs->nr_migrate_dl_tasks;
3351                 reset_migrate_dl_data(cs);
3352         }
3353
3354         cs->attach_in_progress--;
3355         if (!cs->attach_in_progress)
3356                 wake_up(&cpuset_attach_wq);
3357
3358         mutex_unlock(&cpuset_mutex);
3359 }
3360
3361 /* The various types of files and directories in a cpuset file system */
3362
3363 typedef enum {
3364         FILE_MEMORY_MIGRATE,
3365         FILE_CPULIST,
3366         FILE_MEMLIST,
3367         FILE_EFFECTIVE_CPULIST,
3368         FILE_EFFECTIVE_MEMLIST,
3369         FILE_SUBPARTS_CPULIST,
3370         FILE_EXCLUSIVE_CPULIST,
3371         FILE_EFFECTIVE_XCPULIST,
3372         FILE_CPU_EXCLUSIVE,
3373         FILE_MEM_EXCLUSIVE,
3374         FILE_MEM_HARDWALL,
3375         FILE_SCHED_LOAD_BALANCE,
3376         FILE_PARTITION_ROOT,
3377         FILE_SCHED_RELAX_DOMAIN_LEVEL,
3378         FILE_MEMORY_PRESSURE_ENABLED,
3379         FILE_MEMORY_PRESSURE,
3380         FILE_SPREAD_PAGE,
3381         FILE_SPREAD_SLAB,
3382 } cpuset_filetype_t;
3383
3384 static int cpuset_write_u64(struct cgroup_subsys_state *css, struct cftype *cft,
3385                             u64 val)
3386 {
3387         struct cpuset *cs = css_cs(css);
3388         cpuset_filetype_t type = cft->private;
3389         int retval = 0;
3390
3391         cpus_read_lock();
3392         mutex_lock(&cpuset_mutex);
3393         if (!is_cpuset_online(cs)) {
3394                 retval = -ENODEV;
3395                 goto out_unlock;
3396         }
3397
3398         switch (type) {
3399         case FILE_CPU_EXCLUSIVE:
3400                 retval = update_flag(CS_CPU_EXCLUSIVE, cs, val);
3401                 break;
3402         case FILE_MEM_EXCLUSIVE:
3403                 retval = update_flag(CS_MEM_EXCLUSIVE, cs, val);
3404                 break;
3405         case FILE_MEM_HARDWALL:
3406                 retval = update_flag(CS_MEM_HARDWALL, cs, val);
3407                 break;
3408         case FILE_SCHED_LOAD_BALANCE:
3409                 retval = update_flag(CS_SCHED_LOAD_BALANCE, cs, val);
3410                 break;
3411         case FILE_MEMORY_MIGRATE:
3412                 retval = update_flag(CS_MEMORY_MIGRATE, cs, val);
3413                 break;
3414         case FILE_MEMORY_PRESSURE_ENABLED:
3415                 cpuset_memory_pressure_enabled = !!val;
3416                 break;
3417         case FILE_SPREAD_PAGE:
3418                 retval = update_flag(CS_SPREAD_PAGE, cs, val);
3419                 break;
3420         case FILE_SPREAD_SLAB:
3421                 retval = update_flag(CS_SPREAD_SLAB, cs, val);
3422                 break;
3423         default:
3424                 retval = -EINVAL;
3425                 break;
3426         }
3427 out_unlock:
3428         mutex_unlock(&cpuset_mutex);
3429         cpus_read_unlock();
3430         return retval;
3431 }
3432
3433 static int cpuset_write_s64(struct cgroup_subsys_state *css, struct cftype *cft,
3434                             s64 val)
3435 {
3436         struct cpuset *cs = css_cs(css);
3437         cpuset_filetype_t type = cft->private;
3438         int retval = -ENODEV;
3439
3440         cpus_read_lock();
3441         mutex_lock(&cpuset_mutex);
3442         if (!is_cpuset_online(cs))
3443                 goto out_unlock;
3444
3445         switch (type) {
3446         case FILE_SCHED_RELAX_DOMAIN_LEVEL:
3447                 retval = update_relax_domain_level(cs, val);
3448                 break;
3449         default:
3450                 retval = -EINVAL;
3451                 break;
3452         }
3453 out_unlock:
3454         mutex_unlock(&cpuset_mutex);
3455         cpus_read_unlock();
3456         return retval;
3457 }
3458
3459 /*
3460  * Common handling for a write to a "cpus" or "mems" file.
3461  */
3462 static ssize_t cpuset_write_resmask(struct kernfs_open_file *of,
3463                                     char *buf, size_t nbytes, loff_t off)
3464 {
3465         struct cpuset *cs = css_cs(of_css(of));
3466         struct cpuset *trialcs;
3467         int retval = -ENODEV;
3468
3469         buf = strstrip(buf);
3470
3471         /*
3472          * CPU or memory hotunplug may leave @cs w/o any execution
3473          * resources, in which case the hotplug code asynchronously updates
3474          * configuration and transfers all tasks to the nearest ancestor
3475          * which can execute.
3476          *
3477          * As writes to "cpus" or "mems" may restore @cs's execution
3478          * resources, wait for the previously scheduled operations before
3479          * proceeding, so that we don't end up keep removing tasks added
3480          * after execution capability is restored.
3481          *
3482          * cpuset_hotplug_work calls back into cgroup core via
3483          * cgroup_transfer_tasks() and waiting for it from a cgroupfs
3484          * operation like this one can lead to a deadlock through kernfs
3485          * active_ref protection.  Let's break the protection.  Losing the
3486          * protection is okay as we check whether @cs is online after
3487          * grabbing cpuset_mutex anyway.  This only happens on the legacy
3488          * hierarchies.
3489          */
3490         css_get(&cs->css);
3491         kernfs_break_active_protection(of->kn);
3492         flush_work(&cpuset_hotplug_work);
3493
3494         cpus_read_lock();
3495         mutex_lock(&cpuset_mutex);
3496         if (!is_cpuset_online(cs))
3497                 goto out_unlock;
3498
3499         trialcs = alloc_trial_cpuset(cs);
3500         if (!trialcs) {
3501                 retval = -ENOMEM;
3502                 goto out_unlock;
3503         }
3504
3505         switch (of_cft(of)->private) {
3506         case FILE_CPULIST:
3507                 retval = update_cpumask(cs, trialcs, buf);
3508                 break;
3509         case FILE_EXCLUSIVE_CPULIST:
3510                 retval = update_exclusive_cpumask(cs, trialcs, buf);
3511                 break;
3512         case FILE_MEMLIST:
3513                 retval = update_nodemask(cs, trialcs, buf);
3514                 break;
3515         default:
3516                 retval = -EINVAL;
3517                 break;
3518         }
3519
3520         free_cpuset(trialcs);
3521 out_unlock:
3522         mutex_unlock(&cpuset_mutex);
3523         cpus_read_unlock();
3524         kernfs_unbreak_active_protection(of->kn);
3525         css_put(&cs->css);
3526         flush_workqueue(cpuset_migrate_mm_wq);
3527         return retval ?: nbytes;
3528 }
3529
3530 /*
3531  * These ascii lists should be read in a single call, by using a user
3532  * buffer large enough to hold the entire map.  If read in smaller
3533  * chunks, there is no guarantee of atomicity.  Since the display format
3534  * used, list of ranges of sequential numbers, is variable length,
3535  * and since these maps can change value dynamically, one could read
3536  * gibberish by doing partial reads while a list was changing.
3537  */
3538 static int cpuset_common_seq_show(struct seq_file *sf, void *v)
3539 {
3540         struct cpuset *cs = css_cs(seq_css(sf));
3541         cpuset_filetype_t type = seq_cft(sf)->private;
3542         int ret = 0;
3543
3544         spin_lock_irq(&callback_lock);
3545
3546         switch (type) {
3547         case FILE_CPULIST:
3548                 seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->cpus_allowed));
3549                 break;
3550         case FILE_MEMLIST:
3551                 seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->mems_allowed));
3552                 break;
3553         case FILE_EFFECTIVE_CPULIST:
3554                 seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->effective_cpus));
3555                 break;
3556         case FILE_EFFECTIVE_MEMLIST:
3557                 seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->effective_mems));
3558                 break;
3559         case FILE_EXCLUSIVE_CPULIST:
3560                 seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->exclusive_cpus));
3561                 break;
3562         case FILE_EFFECTIVE_XCPULIST:
3563                 seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->effective_xcpus));
3564                 break;
3565         case FILE_SUBPARTS_CPULIST:
3566                 seq_printf(sf, "%*pbl\n", cpumask_pr_args(subpartitions_cpus));
3567                 break;
3568         default:
3569                 ret = -EINVAL;
3570         }
3571
3572         spin_unlock_irq(&callback_lock);
3573         return ret;
3574 }
3575
3576 static u64 cpuset_read_u64(struct cgroup_subsys_state *css, struct cftype *cft)
3577 {
3578         struct cpuset *cs = css_cs(css);
3579         cpuset_filetype_t type = cft->private;
3580         switch (type) {
3581         case FILE_CPU_EXCLUSIVE:
3582                 return is_cpu_exclusive(cs);
3583         case FILE_MEM_EXCLUSIVE:
3584                 return is_mem_exclusive(cs);
3585         case FILE_MEM_HARDWALL:
3586                 return is_mem_hardwall(cs);
3587         case FILE_SCHED_LOAD_BALANCE:
3588                 return is_sched_load_balance(cs);
3589         case FILE_MEMORY_MIGRATE:
3590                 return is_memory_migrate(cs);
3591         case FILE_MEMORY_PRESSURE_ENABLED:
3592                 return cpuset_memory_pressure_enabled;
3593         case FILE_MEMORY_PRESSURE:
3594                 return fmeter_getrate(&cs->fmeter);
3595         case FILE_SPREAD_PAGE:
3596                 return is_spread_page(cs);
3597         case FILE_SPREAD_SLAB:
3598                 return is_spread_slab(cs);
3599         default:
3600                 BUG();
3601         }
3602
3603         /* Unreachable but makes gcc happy */
3604         return 0;
3605 }
3606
3607 static s64 cpuset_read_s64(struct cgroup_subsys_state *css, struct cftype *cft)
3608 {
3609         struct cpuset *cs = css_cs(css);
3610         cpuset_filetype_t type = cft->private;
3611         switch (type) {
3612         case FILE_SCHED_RELAX_DOMAIN_LEVEL:
3613                 return cs->relax_domain_level;
3614         default:
3615                 BUG();
3616         }
3617
3618         /* Unreachable but makes gcc happy */
3619         return 0;
3620 }
3621
3622 static int sched_partition_show(struct seq_file *seq, void *v)
3623 {
3624         struct cpuset *cs = css_cs(seq_css(seq));
3625         const char *err, *type = NULL;
3626
3627         switch (cs->partition_root_state) {
3628         case PRS_ROOT:
3629                 seq_puts(seq, "root\n");
3630                 break;
3631         case PRS_ISOLATED:
3632                 seq_puts(seq, "isolated\n");
3633                 break;
3634         case PRS_MEMBER:
3635                 seq_puts(seq, "member\n");
3636                 break;
3637         case PRS_INVALID_ROOT:
3638                 type = "root";
3639                 fallthrough;
3640         case PRS_INVALID_ISOLATED:
3641                 if (!type)
3642                         type = "isolated";
3643                 err = perr_strings[READ_ONCE(cs->prs_err)];
3644                 if (err)
3645                         seq_printf(seq, "%s invalid (%s)\n", type, err);
3646                 else
3647                         seq_printf(seq, "%s invalid\n", type);
3648                 break;
3649         }
3650         return 0;
3651 }
3652
3653 static ssize_t sched_partition_write(struct kernfs_open_file *of, char *buf,
3654                                      size_t nbytes, loff_t off)
3655 {
3656         struct cpuset *cs = css_cs(of_css(of));
3657         int val;
3658         int retval = -ENODEV;
3659
3660         buf = strstrip(buf);
3661
3662         /*
3663          * Convert "root" to ENABLED, and convert "member" to DISABLED.
3664          */
3665         if (!strcmp(buf, "root"))
3666                 val = PRS_ROOT;
3667         else if (!strcmp(buf, "member"))
3668                 val = PRS_MEMBER;
3669         else if (!strcmp(buf, "isolated"))
3670                 val = PRS_ISOLATED;
3671         else
3672                 return -EINVAL;
3673
3674         css_get(&cs->css);
3675         cpus_read_lock();
3676         mutex_lock(&cpuset_mutex);
3677         if (!is_cpuset_online(cs))
3678                 goto out_unlock;
3679
3680         retval = update_prstate(cs, val);
3681 out_unlock:
3682         mutex_unlock(&cpuset_mutex);
3683         cpus_read_unlock();
3684         css_put(&cs->css);
3685         return retval ?: nbytes;
3686 }
3687
3688 /*
3689  * for the common functions, 'private' gives the type of file
3690  */
3691
3692 static struct cftype legacy_files[] = {
3693         {
3694                 .name = "cpus",
3695                 .seq_show = cpuset_common_seq_show,
3696                 .write = cpuset_write_resmask,
3697                 .max_write_len = (100U + 6 * NR_CPUS),
3698                 .private = FILE_CPULIST,
3699         },
3700
3701         {
3702                 .name = "mems",
3703                 .seq_show = cpuset_common_seq_show,
3704                 .write = cpuset_write_resmask,
3705                 .max_write_len = (100U + 6 * MAX_NUMNODES),
3706                 .private = FILE_MEMLIST,
3707         },
3708
3709         {
3710                 .name = "effective_cpus",
3711                 .seq_show = cpuset_common_seq_show,
3712                 .private = FILE_EFFECTIVE_CPULIST,
3713         },
3714
3715         {
3716                 .name = "effective_mems",
3717                 .seq_show = cpuset_common_seq_show,
3718                 .private = FILE_EFFECTIVE_MEMLIST,
3719         },
3720
3721         {
3722                 .name = "cpu_exclusive",
3723                 .read_u64 = cpuset_read_u64,
3724                 .write_u64 = cpuset_write_u64,
3725                 .private = FILE_CPU_EXCLUSIVE,
3726         },
3727
3728         {
3729                 .name = "mem_exclusive",
3730                 .read_u64 = cpuset_read_u64,
3731                 .write_u64 = cpuset_write_u64,
3732                 .private = FILE_MEM_EXCLUSIVE,
3733         },
3734
3735         {
3736                 .name = "mem_hardwall",
3737                 .read_u64 = cpuset_read_u64,
3738                 .write_u64 = cpuset_write_u64,
3739                 .private = FILE_MEM_HARDWALL,
3740         },
3741
3742         {
3743                 .name = "sched_load_balance",
3744                 .read_u64 = cpuset_read_u64,
3745                 .write_u64 = cpuset_write_u64,
3746                 .private = FILE_SCHED_LOAD_BALANCE,
3747         },
3748
3749         {
3750                 .name = "sched_relax_domain_level",
3751                 .read_s64 = cpuset_read_s64,
3752                 .write_s64 = cpuset_write_s64,
3753                 .private = FILE_SCHED_RELAX_DOMAIN_LEVEL,
3754         },
3755
3756         {
3757                 .name = "memory_migrate",
3758                 .read_u64 = cpuset_read_u64,
3759                 .write_u64 = cpuset_write_u64,
3760                 .private = FILE_MEMORY_MIGRATE,
3761         },
3762
3763         {
3764                 .name = "memory_pressure",
3765                 .read_u64 = cpuset_read_u64,
3766                 .private = FILE_MEMORY_PRESSURE,
3767         },
3768
3769         {
3770                 .name = "memory_spread_page",
3771                 .read_u64 = cpuset_read_u64,
3772                 .write_u64 = cpuset_write_u64,
3773                 .private = FILE_SPREAD_PAGE,
3774         },
3775
3776         {
3777                 .name = "memory_spread_slab",
3778                 .read_u64 = cpuset_read_u64,
3779                 .write_u64 = cpuset_write_u64,
3780                 .private = FILE_SPREAD_SLAB,
3781         },
3782
3783         {
3784                 .name = "memory_pressure_enabled",
3785                 .flags = CFTYPE_ONLY_ON_ROOT,
3786                 .read_u64 = cpuset_read_u64,
3787                 .write_u64 = cpuset_write_u64,
3788                 .private = FILE_MEMORY_PRESSURE_ENABLED,
3789         },
3790
3791         { }     /* terminate */
3792 };
3793
3794 /*
3795  * This is currently a minimal set for the default hierarchy. It can be
3796  * expanded later on by migrating more features and control files from v1.
3797  */
3798 static struct cftype dfl_files[] = {
3799         {
3800                 .name = "cpus",
3801                 .seq_show = cpuset_common_seq_show,
3802                 .write = cpuset_write_resmask,
3803                 .max_write_len = (100U + 6 * NR_CPUS),
3804                 .private = FILE_CPULIST,
3805                 .flags = CFTYPE_NOT_ON_ROOT,
3806         },
3807
3808         {
3809                 .name = "mems",
3810                 .seq_show = cpuset_common_seq_show,
3811                 .write = cpuset_write_resmask,
3812                 .max_write_len = (100U + 6 * MAX_NUMNODES),
3813                 .private = FILE_MEMLIST,
3814                 .flags = CFTYPE_NOT_ON_ROOT,
3815         },
3816
3817         {
3818                 .name = "cpus.effective",
3819                 .seq_show = cpuset_common_seq_show,
3820                 .private = FILE_EFFECTIVE_CPULIST,
3821         },
3822
3823         {
3824                 .name = "mems.effective",
3825                 .seq_show = cpuset_common_seq_show,
3826                 .private = FILE_EFFECTIVE_MEMLIST,
3827         },
3828
3829         {
3830                 .name = "cpus.partition",
3831                 .seq_show = sched_partition_show,
3832                 .write = sched_partition_write,
3833                 .private = FILE_PARTITION_ROOT,
3834                 .flags = CFTYPE_NOT_ON_ROOT,
3835                 .file_offset = offsetof(struct cpuset, partition_file),
3836         },
3837
3838         {
3839                 .name = "cpus.exclusive",
3840                 .seq_show = cpuset_common_seq_show,
3841                 .write = cpuset_write_resmask,
3842                 .max_write_len = (100U + 6 * NR_CPUS),
3843                 .private = FILE_EXCLUSIVE_CPULIST,
3844                 .flags = CFTYPE_NOT_ON_ROOT,
3845         },
3846
3847         {
3848                 .name = "cpus.exclusive.effective",
3849                 .seq_show = cpuset_common_seq_show,
3850                 .private = FILE_EFFECTIVE_XCPULIST,
3851                 .flags = CFTYPE_NOT_ON_ROOT,
3852         },
3853
3854         {
3855                 .name = "cpus.subpartitions",
3856                 .seq_show = cpuset_common_seq_show,
3857                 .private = FILE_SUBPARTS_CPULIST,
3858                 .flags = CFTYPE_ONLY_ON_ROOT | CFTYPE_DEBUG,
3859         },
3860
3861         { }     /* terminate */
3862 };
3863
3864
3865 /**
3866  * cpuset_css_alloc - Allocate a cpuset css
3867  * @parent_css: Parent css of the control group that the new cpuset will be
3868  *              part of
3869  * Return: cpuset css on success, -ENOMEM on failure.
3870  *
3871  * Allocate and initialize a new cpuset css, for non-NULL @parent_css, return
3872  * top cpuset css otherwise.
3873  */
3874 static struct cgroup_subsys_state *
3875 cpuset_css_alloc(struct cgroup_subsys_state *parent_css)
3876 {
3877         struct cpuset *cs;
3878
3879         if (!parent_css)
3880                 return &top_cpuset.css;
3881
3882         cs = kzalloc(sizeof(*cs), GFP_KERNEL);
3883         if (!cs)
3884                 return ERR_PTR(-ENOMEM);
3885
3886         if (alloc_cpumasks(cs, NULL)) {
3887                 kfree(cs);
3888                 return ERR_PTR(-ENOMEM);
3889         }
3890
3891         __set_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
3892         nodes_clear(cs->mems_allowed);
3893         nodes_clear(cs->effective_mems);
3894         fmeter_init(&cs->fmeter);
3895         cs->relax_domain_level = -1;
3896         INIT_LIST_HEAD(&cs->remote_sibling);
3897
3898         /* Set CS_MEMORY_MIGRATE for default hierarchy */
3899         if (cgroup_subsys_on_dfl(cpuset_cgrp_subsys))
3900                 __set_bit(CS_MEMORY_MIGRATE, &cs->flags);
3901
3902         return &cs->css;
3903 }
3904
3905 static int cpuset_css_online(struct cgroup_subsys_state *css)
3906 {
3907         struct cpuset *cs = css_cs(css);
3908         struct cpuset *parent = parent_cs(cs);
3909         struct cpuset *tmp_cs;
3910         struct cgroup_subsys_state *pos_css;
3911
3912         if (!parent)
3913                 return 0;
3914
3915         cpus_read_lock();
3916         mutex_lock(&cpuset_mutex);
3917
3918         set_bit(CS_ONLINE, &cs->flags);
3919         if (is_spread_page(parent))
3920                 set_bit(CS_SPREAD_PAGE, &cs->flags);
3921         if (is_spread_slab(parent))
3922                 set_bit(CS_SPREAD_SLAB, &cs->flags);
3923
3924         cpuset_inc();
3925
3926         spin_lock_irq(&callback_lock);
3927         if (is_in_v2_mode()) {
3928                 cpumask_copy(cs->effective_cpus, parent->effective_cpus);
3929                 cs->effective_mems = parent->effective_mems;
3930                 cs->use_parent_ecpus = true;
3931                 parent->child_ecpus_count++;
3932                 /*
3933                  * Clear CS_SCHED_LOAD_BALANCE if parent is isolated
3934                  */
3935                 if (!is_sched_load_balance(parent))
3936                         clear_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
3937         }
3938
3939         /*
3940          * For v2, clear CS_SCHED_LOAD_BALANCE if parent is isolated
3941          */
3942         if (cgroup_subsys_on_dfl(cpuset_cgrp_subsys) &&
3943             !is_sched_load_balance(parent))
3944                 clear_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
3945
3946         spin_unlock_irq(&callback_lock);
3947
3948         if (!test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags))
3949                 goto out_unlock;
3950
3951         /*
3952          * Clone @parent's configuration if CGRP_CPUSET_CLONE_CHILDREN is
3953          * set.  This flag handling is implemented in cgroup core for
3954          * historical reasons - the flag may be specified during mount.
3955          *
3956          * Currently, if any sibling cpusets have exclusive cpus or mem, we
3957          * refuse to clone the configuration - thereby refusing the task to
3958          * be entered, and as a result refusing the sys_unshare() or
3959          * clone() which initiated it.  If this becomes a problem for some
3960          * users who wish to allow that scenario, then this could be
3961          * changed to grant parent->cpus_allowed-sibling_cpus_exclusive
3962          * (and likewise for mems) to the new cgroup.
3963          */
3964         rcu_read_lock();
3965         cpuset_for_each_child(tmp_cs, pos_css, parent) {
3966                 if (is_mem_exclusive(tmp_cs) || is_cpu_exclusive(tmp_cs)) {
3967                         rcu_read_unlock();
3968                         goto out_unlock;
3969                 }
3970         }
3971         rcu_read_unlock();
3972
3973         spin_lock_irq(&callback_lock);
3974         cs->mems_allowed = parent->mems_allowed;
3975         cs->effective_mems = parent->mems_allowed;
3976         cpumask_copy(cs->cpus_allowed, parent->cpus_allowed);
3977         cpumask_copy(cs->effective_cpus, parent->cpus_allowed);
3978         spin_unlock_irq(&callback_lock);
3979 out_unlock:
3980         mutex_unlock(&cpuset_mutex);
3981         cpus_read_unlock();
3982         return 0;
3983 }
3984
3985 /*
3986  * If the cpuset being removed has its flag 'sched_load_balance'
3987  * enabled, then simulate turning sched_load_balance off, which
3988  * will call rebuild_sched_domains_locked(). That is not needed
3989  * in the default hierarchy where only changes in partition
3990  * will cause repartitioning.
3991  *
3992  * If the cpuset has the 'sched.partition' flag enabled, simulate
3993  * turning 'sched.partition" off.
3994  */
3995
3996 static void cpuset_css_offline(struct cgroup_subsys_state *css)
3997 {
3998         struct cpuset *cs = css_cs(css);
3999
4000         cpus_read_lock();
4001         mutex_lock(&cpuset_mutex);
4002
4003         if (is_partition_valid(cs))
4004                 update_prstate(cs, 0);
4005
4006         if (!cgroup_subsys_on_dfl(cpuset_cgrp_subsys) &&
4007             is_sched_load_balance(cs))
4008                 update_flag(CS_SCHED_LOAD_BALANCE, cs, 0);
4009
4010         if (cs->use_parent_ecpus) {
4011                 struct cpuset *parent = parent_cs(cs);
4012
4013                 cs->use_parent_ecpus = false;
4014                 parent->child_ecpus_count--;
4015         }
4016
4017         cpuset_dec();
4018         clear_bit(CS_ONLINE, &cs->flags);
4019
4020         mutex_unlock(&cpuset_mutex);
4021         cpus_read_unlock();
4022 }
4023
4024 static void cpuset_css_free(struct cgroup_subsys_state *css)
4025 {
4026         struct cpuset *cs = css_cs(css);
4027
4028         free_cpuset(cs);
4029 }
4030
4031 static void cpuset_bind(struct cgroup_subsys_state *root_css)
4032 {
4033         mutex_lock(&cpuset_mutex);
4034         spin_lock_irq(&callback_lock);
4035
4036         if (is_in_v2_mode()) {
4037                 cpumask_copy(top_cpuset.cpus_allowed, cpu_possible_mask);
4038                 cpumask_copy(top_cpuset.effective_xcpus, cpu_possible_mask);
4039                 top_cpuset.mems_allowed = node_possible_map;
4040         } else {
4041                 cpumask_copy(top_cpuset.cpus_allowed,
4042                              top_cpuset.effective_cpus);
4043                 top_cpuset.mems_allowed = top_cpuset.effective_mems;
4044         }
4045
4046         spin_unlock_irq(&callback_lock);
4047         mutex_unlock(&cpuset_mutex);
4048 }
4049
4050 /*
4051  * In case the child is cloned into a cpuset different from its parent,
4052  * additional checks are done to see if the move is allowed.
4053  */
4054 static int cpuset_can_fork(struct task_struct *task, struct css_set *cset)
4055 {
4056         struct cpuset *cs = css_cs(cset->subsys[cpuset_cgrp_id]);
4057         bool same_cs;
4058         int ret;
4059
4060         rcu_read_lock();
4061         same_cs = (cs == task_cs(current));
4062         rcu_read_unlock();
4063
4064         if (same_cs)
4065                 return 0;
4066
4067         lockdep_assert_held(&cgroup_mutex);
4068         mutex_lock(&cpuset_mutex);
4069
4070         /* Check to see if task is allowed in the cpuset */
4071         ret = cpuset_can_attach_check(cs);
4072         if (ret)
4073                 goto out_unlock;
4074
4075         ret = task_can_attach(task);
4076         if (ret)
4077                 goto out_unlock;
4078
4079         ret = security_task_setscheduler(task);
4080         if (ret)
4081                 goto out_unlock;
4082
4083         /*
4084          * Mark attach is in progress.  This makes validate_change() fail
4085          * changes which zero cpus/mems_allowed.
4086          */
4087         cs->attach_in_progress++;
4088 out_unlock:
4089         mutex_unlock(&cpuset_mutex);
4090         return ret;
4091 }
4092
4093 static void cpuset_cancel_fork(struct task_struct *task, struct css_set *cset)
4094 {
4095         struct cpuset *cs = css_cs(cset->subsys[cpuset_cgrp_id]);
4096         bool same_cs;
4097
4098         rcu_read_lock();
4099         same_cs = (cs == task_cs(current));
4100         rcu_read_unlock();
4101
4102         if (same_cs)
4103                 return;
4104
4105         mutex_lock(&cpuset_mutex);
4106         cs->attach_in_progress--;
4107         if (!cs->attach_in_progress)
4108                 wake_up(&cpuset_attach_wq);
4109         mutex_unlock(&cpuset_mutex);
4110 }
4111
4112 /*
4113  * Make sure the new task conform to the current state of its parent,
4114  * which could have been changed by cpuset just after it inherits the
4115  * state from the parent and before it sits on the cgroup's task list.
4116  */
4117 static void cpuset_fork(struct task_struct *task)
4118 {
4119         struct cpuset *cs;
4120         bool same_cs;
4121
4122         rcu_read_lock();
4123         cs = task_cs(task);
4124         same_cs = (cs == task_cs(current));
4125         rcu_read_unlock();
4126
4127         if (same_cs) {
4128                 if (cs == &top_cpuset)
4129                         return;
4130
4131                 set_cpus_allowed_ptr(task, current->cpus_ptr);
4132                 task->mems_allowed = current->mems_allowed;
4133                 return;
4134         }
4135
4136         /* CLONE_INTO_CGROUP */
4137         mutex_lock(&cpuset_mutex);
4138         guarantee_online_mems(cs, &cpuset_attach_nodemask_to);
4139         cpuset_attach_task(cs, task);
4140
4141         cs->attach_in_progress--;
4142         if (!cs->attach_in_progress)
4143                 wake_up(&cpuset_attach_wq);
4144
4145         mutex_unlock(&cpuset_mutex);
4146 }
4147
4148 struct cgroup_subsys cpuset_cgrp_subsys = {
4149         .css_alloc      = cpuset_css_alloc,
4150         .css_online     = cpuset_css_online,
4151         .css_offline    = cpuset_css_offline,
4152         .css_free       = cpuset_css_free,
4153         .can_attach     = cpuset_can_attach,
4154         .cancel_attach  = cpuset_cancel_attach,
4155         .attach         = cpuset_attach,
4156         .post_attach    = cpuset_post_attach,
4157         .bind           = cpuset_bind,
4158         .can_fork       = cpuset_can_fork,
4159         .cancel_fork    = cpuset_cancel_fork,
4160         .fork           = cpuset_fork,
4161         .legacy_cftypes = legacy_files,
4162         .dfl_cftypes    = dfl_files,
4163         .early_init     = true,
4164         .threaded       = true,
4165 };
4166
4167 /**
4168  * cpuset_init - initialize cpusets at system boot
4169  *
4170  * Description: Initialize top_cpuset
4171  **/
4172
4173 int __init cpuset_init(void)
4174 {
4175         BUG_ON(!alloc_cpumask_var(&top_cpuset.cpus_allowed, GFP_KERNEL));
4176         BUG_ON(!alloc_cpumask_var(&top_cpuset.effective_cpus, GFP_KERNEL));
4177         BUG_ON(!alloc_cpumask_var(&top_cpuset.effective_xcpus, GFP_KERNEL));
4178         BUG_ON(!alloc_cpumask_var(&top_cpuset.exclusive_cpus, GFP_KERNEL));
4179         BUG_ON(!zalloc_cpumask_var(&subpartitions_cpus, GFP_KERNEL));
4180
4181         cpumask_setall(top_cpuset.cpus_allowed);
4182         nodes_setall(top_cpuset.mems_allowed);
4183         cpumask_setall(top_cpuset.effective_cpus);
4184         cpumask_setall(top_cpuset.effective_xcpus);
4185         cpumask_setall(top_cpuset.exclusive_cpus);
4186         nodes_setall(top_cpuset.effective_mems);
4187
4188         fmeter_init(&top_cpuset.fmeter);
4189         set_bit(CS_SCHED_LOAD_BALANCE, &top_cpuset.flags);
4190         top_cpuset.relax_domain_level = -1;
4191         INIT_LIST_HEAD(&remote_children);
4192
4193         BUG_ON(!alloc_cpumask_var(&cpus_attach, GFP_KERNEL));
4194
4195         return 0;
4196 }
4197
4198 /*
4199  * If CPU and/or memory hotplug handlers, below, unplug any CPUs
4200  * or memory nodes, we need to walk over the cpuset hierarchy,
4201  * removing that CPU or node from all cpusets.  If this removes the
4202  * last CPU or node from a cpuset, then move the tasks in the empty
4203  * cpuset to its next-highest non-empty parent.
4204  */
4205 static void remove_tasks_in_empty_cpuset(struct cpuset *cs)
4206 {
4207         struct cpuset *parent;
4208
4209         /*
4210          * Find its next-highest non-empty parent, (top cpuset
4211          * has online cpus, so can't be empty).
4212          */
4213         parent = parent_cs(cs);
4214         while (cpumask_empty(parent->cpus_allowed) ||
4215                         nodes_empty(parent->mems_allowed))
4216                 parent = parent_cs(parent);
4217
4218         if (cgroup_transfer_tasks(parent->css.cgroup, cs->css.cgroup)) {
4219                 pr_err("cpuset: failed to transfer tasks out of empty cpuset ");
4220                 pr_cont_cgroup_name(cs->css.cgroup);
4221                 pr_cont("\n");
4222         }
4223 }
4224
4225 static void
4226 hotplug_update_tasks_legacy(struct cpuset *cs,
4227                             struct cpumask *new_cpus, nodemask_t *new_mems,
4228                             bool cpus_updated, bool mems_updated)
4229 {
4230         bool is_empty;
4231
4232         spin_lock_irq(&callback_lock);
4233         cpumask_copy(cs->cpus_allowed, new_cpus);
4234         cpumask_copy(cs->effective_cpus, new_cpus);
4235         cs->mems_allowed = *new_mems;
4236         cs->effective_mems = *new_mems;
4237         spin_unlock_irq(&callback_lock);
4238
4239         /*
4240          * Don't call update_tasks_cpumask() if the cpuset becomes empty,
4241          * as the tasks will be migrated to an ancestor.
4242          */
4243         if (cpus_updated && !cpumask_empty(cs->cpus_allowed))
4244                 update_tasks_cpumask(cs, new_cpus);
4245         if (mems_updated && !nodes_empty(cs->mems_allowed))
4246                 update_tasks_nodemask(cs);
4247
4248         is_empty = cpumask_empty(cs->cpus_allowed) ||
4249                    nodes_empty(cs->mems_allowed);
4250
4251         /*
4252          * Move tasks to the nearest ancestor with execution resources,
4253          * This is full cgroup operation which will also call back into
4254          * cpuset. Should be done outside any lock.
4255          */
4256         if (is_empty) {
4257                 mutex_unlock(&cpuset_mutex);
4258                 remove_tasks_in_empty_cpuset(cs);
4259                 mutex_lock(&cpuset_mutex);
4260         }
4261 }
4262
4263 static void
4264 hotplug_update_tasks(struct cpuset *cs,
4265                      struct cpumask *new_cpus, nodemask_t *new_mems,
4266                      bool cpus_updated, bool mems_updated)
4267 {
4268         /* A partition root is allowed to have empty effective cpus */
4269         if (cpumask_empty(new_cpus) && !is_partition_valid(cs))
4270                 cpumask_copy(new_cpus, parent_cs(cs)->effective_cpus);
4271         if (nodes_empty(*new_mems))
4272                 *new_mems = parent_cs(cs)->effective_mems;
4273
4274         spin_lock_irq(&callback_lock);
4275         cpumask_copy(cs->effective_cpus, new_cpus);
4276         cs->effective_mems = *new_mems;
4277         spin_unlock_irq(&callback_lock);
4278
4279         if (cpus_updated)
4280                 update_tasks_cpumask(cs, new_cpus);
4281         if (mems_updated)
4282                 update_tasks_nodemask(cs);
4283 }
4284
4285 static bool force_rebuild;
4286
4287 void cpuset_force_rebuild(void)
4288 {
4289         force_rebuild = true;
4290 }
4291
4292 /**
4293  * cpuset_hotplug_update_tasks - update tasks in a cpuset for hotunplug
4294  * @cs: cpuset in interest
4295  * @tmp: the tmpmasks structure pointer
4296  *
4297  * Compare @cs's cpu and mem masks against top_cpuset and if some have gone
4298  * offline, update @cs accordingly.  If @cs ends up with no CPU or memory,
4299  * all its tasks are moved to the nearest ancestor with both resources.
4300  */
4301 static void cpuset_hotplug_update_tasks(struct cpuset *cs, struct tmpmasks *tmp)
4302 {
4303         static cpumask_t new_cpus;
4304         static nodemask_t new_mems;
4305         bool cpus_updated;
4306         bool mems_updated;
4307         bool remote;
4308         struct cpuset *parent;
4309 retry:
4310         wait_event(cpuset_attach_wq, cs->attach_in_progress == 0);
4311
4312         mutex_lock(&cpuset_mutex);
4313
4314         /*
4315          * We have raced with task attaching. We wait until attaching
4316          * is finished, so we won't attach a task to an empty cpuset.
4317          */
4318         if (cs->attach_in_progress) {
4319                 mutex_unlock(&cpuset_mutex);
4320                 goto retry;
4321         }
4322
4323         parent = parent_cs(cs);
4324         compute_effective_cpumask(&new_cpus, cs, parent);
4325         nodes_and(new_mems, cs->mems_allowed, parent->effective_mems);
4326
4327         if (!tmp || !cs->partition_root_state)
4328                 goto update_tasks;
4329
4330         /*
4331          * Compute effective_cpus for valid partition root, may invalidate
4332          * child partition roots if necessary.
4333          */
4334         remote = is_remote_partition(cs);
4335         if (remote || (is_partition_valid(cs) && is_partition_valid(parent)))
4336                 compute_partition_effective_cpumask(cs, &new_cpus);
4337
4338         if (remote && cpumask_empty(&new_cpus) &&
4339             partition_is_populated(cs, NULL)) {
4340                 remote_partition_disable(cs, tmp);
4341                 compute_effective_cpumask(&new_cpus, cs, parent);
4342                 remote = false;
4343                 cpuset_force_rebuild();
4344         }
4345
4346         /*
4347          * Force the partition to become invalid if either one of
4348          * the following conditions hold:
4349          * 1) empty effective cpus but not valid empty partition.
4350          * 2) parent is invalid or doesn't grant any cpus to child
4351          *    partitions.
4352          */
4353         if (is_local_partition(cs) && (!is_partition_valid(parent) ||
4354                                 tasks_nocpu_error(parent, cs, &new_cpus))) {
4355                 update_parent_effective_cpumask(cs, partcmd_invalidate, NULL, tmp);
4356                 compute_effective_cpumask(&new_cpus, cs, parent);
4357                 cpuset_force_rebuild();
4358         }
4359         /*
4360          * On the other hand, an invalid partition root may be transitioned
4361          * back to a regular one.
4362          */
4363         else if (is_partition_valid(parent) && is_partition_invalid(cs)) {
4364                 update_parent_effective_cpumask(cs, partcmd_update, NULL, tmp);
4365                 if (is_partition_valid(cs)) {
4366                         compute_partition_effective_cpumask(cs, &new_cpus);
4367                         cpuset_force_rebuild();
4368                 }
4369         }
4370
4371 update_tasks:
4372         cpus_updated = !cpumask_equal(&new_cpus, cs->effective_cpus);
4373         mems_updated = !nodes_equal(new_mems, cs->effective_mems);
4374         if (!cpus_updated && !mems_updated)
4375                 goto unlock;    /* Hotplug doesn't affect this cpuset */
4376
4377         if (mems_updated)
4378                 check_insane_mems_config(&new_mems);
4379
4380         if (is_in_v2_mode())
4381                 hotplug_update_tasks(cs, &new_cpus, &new_mems,
4382                                      cpus_updated, mems_updated);
4383         else
4384                 hotplug_update_tasks_legacy(cs, &new_cpus, &new_mems,
4385                                             cpus_updated, mems_updated);
4386
4387 unlock:
4388         mutex_unlock(&cpuset_mutex);
4389 }
4390
4391 /**
4392  * cpuset_hotplug_workfn - handle CPU/memory hotunplug for a cpuset
4393  * @work: unused
4394  *
4395  * This function is called after either CPU or memory configuration has
4396  * changed and updates cpuset accordingly.  The top_cpuset is always
4397  * synchronized to cpu_active_mask and N_MEMORY, which is necessary in
4398  * order to make cpusets transparent (of no affect) on systems that are
4399  * actively using CPU hotplug but making no active use of cpusets.
4400  *
4401  * Non-root cpusets are only affected by offlining.  If any CPUs or memory
4402  * nodes have been taken down, cpuset_hotplug_update_tasks() is invoked on
4403  * all descendants.
4404  *
4405  * Note that CPU offlining during suspend is ignored.  We don't modify
4406  * cpusets across suspend/resume cycles at all.
4407  */
4408 static void cpuset_hotplug_workfn(struct work_struct *work)
4409 {
4410         static cpumask_t new_cpus;
4411         static nodemask_t new_mems;
4412         bool cpus_updated, mems_updated;
4413         bool on_dfl = is_in_v2_mode();
4414         struct tmpmasks tmp, *ptmp = NULL;
4415
4416         if (on_dfl && !alloc_cpumasks(NULL, &tmp))
4417                 ptmp = &tmp;
4418
4419         mutex_lock(&cpuset_mutex);
4420
4421         /* fetch the available cpus/mems and find out which changed how */
4422         cpumask_copy(&new_cpus, cpu_active_mask);
4423         new_mems = node_states[N_MEMORY];
4424
4425         /*
4426          * If subpartitions_cpus is populated, it is likely that the check
4427          * below will produce a false positive on cpus_updated when the cpu
4428          * list isn't changed. It is extra work, but it is better to be safe.
4429          */
4430         cpus_updated = !cpumask_equal(top_cpuset.effective_cpus, &new_cpus) ||
4431                        !cpumask_empty(subpartitions_cpus);
4432         mems_updated = !nodes_equal(top_cpuset.effective_mems, new_mems);
4433
4434         /*
4435          * In the rare case that hotplug removes all the cpus in
4436          * subpartitions_cpus, we assumed that cpus are updated.
4437          */
4438         if (!cpus_updated && top_cpuset.nr_subparts)
4439                 cpus_updated = true;
4440
4441         /* For v1, synchronize cpus_allowed to cpu_active_mask */
4442         if (cpus_updated) {
4443                 spin_lock_irq(&callback_lock);
4444                 if (!on_dfl)
4445                         cpumask_copy(top_cpuset.cpus_allowed, &new_cpus);
4446                 /*
4447                  * Make sure that CPUs allocated to child partitions
4448                  * do not show up in effective_cpus. If no CPU is left,
4449                  * we clear the subpartitions_cpus & let the child partitions
4450                  * fight for the CPUs again.
4451                  */
4452                 if (!cpumask_empty(subpartitions_cpus)) {
4453                         if (cpumask_subset(&new_cpus, subpartitions_cpus)) {
4454                                 top_cpuset.nr_subparts = 0;
4455                                 cpumask_clear(subpartitions_cpus);
4456                         } else {
4457                                 cpumask_andnot(&new_cpus, &new_cpus,
4458                                                subpartitions_cpus);
4459                         }
4460                 }
4461                 cpumask_copy(top_cpuset.effective_cpus, &new_cpus);
4462                 spin_unlock_irq(&callback_lock);
4463                 /* we don't mess with cpumasks of tasks in top_cpuset */
4464         }
4465
4466         /* synchronize mems_allowed to N_MEMORY */
4467         if (mems_updated) {
4468                 spin_lock_irq(&callback_lock);
4469                 if (!on_dfl)
4470                         top_cpuset.mems_allowed = new_mems;
4471                 top_cpuset.effective_mems = new_mems;
4472                 spin_unlock_irq(&callback_lock);
4473                 update_tasks_nodemask(&top_cpuset);
4474         }
4475
4476         mutex_unlock(&cpuset_mutex);
4477
4478         /* if cpus or mems changed, we need to propagate to descendants */
4479         if (cpus_updated || mems_updated) {
4480                 struct cpuset *cs;
4481                 struct cgroup_subsys_state *pos_css;
4482
4483                 rcu_read_lock();
4484                 cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
4485                         if (cs == &top_cpuset || !css_tryget_online(&cs->css))
4486                                 continue;
4487                         rcu_read_unlock();
4488
4489                         cpuset_hotplug_update_tasks(cs, ptmp);
4490
4491                         rcu_read_lock();
4492                         css_put(&cs->css);
4493                 }
4494                 rcu_read_unlock();
4495         }
4496
4497         /* rebuild sched domains if cpus_allowed has changed */
4498         if (cpus_updated || force_rebuild) {
4499                 force_rebuild = false;
4500                 rebuild_sched_domains();
4501         }
4502
4503         free_cpumasks(NULL, ptmp);
4504 }
4505
4506 void cpuset_update_active_cpus(void)
4507 {
4508         /*
4509          * We're inside cpu hotplug critical region which usually nests
4510          * inside cgroup synchronization.  Bounce actual hotplug processing
4511          * to a work item to avoid reverse locking order.
4512          */
4513         schedule_work(&cpuset_hotplug_work);
4514 }
4515
4516 void cpuset_wait_for_hotplug(void)
4517 {
4518         flush_work(&cpuset_hotplug_work);
4519 }
4520
4521 /*
4522  * Keep top_cpuset.mems_allowed tracking node_states[N_MEMORY].
4523  * Call this routine anytime after node_states[N_MEMORY] changes.
4524  * See cpuset_update_active_cpus() for CPU hotplug handling.
4525  */
4526 static int cpuset_track_online_nodes(struct notifier_block *self,
4527                                 unsigned long action, void *arg)
4528 {
4529         schedule_work(&cpuset_hotplug_work);
4530         return NOTIFY_OK;
4531 }
4532
4533 /**
4534  * cpuset_init_smp - initialize cpus_allowed
4535  *
4536  * Description: Finish top cpuset after cpu, node maps are initialized
4537  */
4538 void __init cpuset_init_smp(void)
4539 {
4540         /*
4541          * cpus_allowd/mems_allowed set to v2 values in the initial
4542          * cpuset_bind() call will be reset to v1 values in another
4543          * cpuset_bind() call when v1 cpuset is mounted.
4544          */
4545         top_cpuset.old_mems_allowed = top_cpuset.mems_allowed;
4546
4547         cpumask_copy(top_cpuset.effective_cpus, cpu_active_mask);
4548         top_cpuset.effective_mems = node_states[N_MEMORY];
4549
4550         hotplug_memory_notifier(cpuset_track_online_nodes, CPUSET_CALLBACK_PRI);
4551
4552         cpuset_migrate_mm_wq = alloc_ordered_workqueue("cpuset_migrate_mm", 0);
4553         BUG_ON(!cpuset_migrate_mm_wq);
4554 }
4555
4556 /**
4557  * cpuset_cpus_allowed - return cpus_allowed mask from a tasks cpuset.
4558  * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
4559  * @pmask: pointer to struct cpumask variable to receive cpus_allowed set.
4560  *
4561  * Description: Returns the cpumask_var_t cpus_allowed of the cpuset
4562  * attached to the specified @tsk.  Guaranteed to return some non-empty
4563  * subset of cpu_online_mask, even if this means going outside the
4564  * tasks cpuset, except when the task is in the top cpuset.
4565  **/
4566
4567 void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
4568 {
4569         unsigned long flags;
4570         struct cpuset *cs;
4571
4572         spin_lock_irqsave(&callback_lock, flags);
4573         rcu_read_lock();
4574
4575         cs = task_cs(tsk);
4576         if (cs != &top_cpuset)
4577                 guarantee_online_cpus(tsk, pmask);
4578         /*
4579          * Tasks in the top cpuset won't get update to their cpumasks
4580          * when a hotplug online/offline event happens. So we include all
4581          * offline cpus in the allowed cpu list.
4582          */
4583         if ((cs == &top_cpuset) || cpumask_empty(pmask)) {
4584                 const struct cpumask *possible_mask = task_cpu_possible_mask(tsk);
4585
4586                 /*
4587                  * We first exclude cpus allocated to partitions. If there is no
4588                  * allowable online cpu left, we fall back to all possible cpus.
4589                  */
4590                 cpumask_andnot(pmask, possible_mask, subpartitions_cpus);
4591                 if (!cpumask_intersects(pmask, cpu_online_mask))
4592                         cpumask_copy(pmask, possible_mask);
4593         }
4594
4595         rcu_read_unlock();
4596         spin_unlock_irqrestore(&callback_lock, flags);
4597 }
4598
4599 /**
4600  * cpuset_cpus_allowed_fallback - final fallback before complete catastrophe.
4601  * @tsk: pointer to task_struct with which the scheduler is struggling
4602  *
4603  * Description: In the case that the scheduler cannot find an allowed cpu in
4604  * tsk->cpus_allowed, we fall back to task_cs(tsk)->cpus_allowed. In legacy
4605  * mode however, this value is the same as task_cs(tsk)->effective_cpus,
4606  * which will not contain a sane cpumask during cases such as cpu hotplugging.
4607  * This is the absolute last resort for the scheduler and it is only used if
4608  * _every_ other avenue has been traveled.
4609  *
4610  * Returns true if the affinity of @tsk was changed, false otherwise.
4611  **/
4612
4613 bool cpuset_cpus_allowed_fallback(struct task_struct *tsk)
4614 {
4615         const struct cpumask *possible_mask = task_cpu_possible_mask(tsk);
4616         const struct cpumask *cs_mask;
4617         bool changed = false;
4618
4619         rcu_read_lock();
4620         cs_mask = task_cs(tsk)->cpus_allowed;
4621         if (is_in_v2_mode() && cpumask_subset(cs_mask, possible_mask)) {
4622                 do_set_cpus_allowed(tsk, cs_mask);
4623                 changed = true;
4624         }
4625         rcu_read_unlock();
4626
4627         /*
4628          * We own tsk->cpus_allowed, nobody can change it under us.
4629          *
4630          * But we used cs && cs->cpus_allowed lockless and thus can
4631          * race with cgroup_attach_task() or update_cpumask() and get
4632          * the wrong tsk->cpus_allowed. However, both cases imply the
4633          * subsequent cpuset_change_cpumask()->set_cpus_allowed_ptr()
4634          * which takes task_rq_lock().
4635          *
4636          * If we are called after it dropped the lock we must see all
4637          * changes in tsk_cs()->cpus_allowed. Otherwise we can temporary
4638          * set any mask even if it is not right from task_cs() pov,
4639          * the pending set_cpus_allowed_ptr() will fix things.
4640          *
4641          * select_fallback_rq() will fix things ups and set cpu_possible_mask
4642          * if required.
4643          */
4644         return changed;
4645 }
4646
4647 void __init cpuset_init_current_mems_allowed(void)
4648 {
4649         nodes_setall(current->mems_allowed);
4650 }
4651
4652 /**
4653  * cpuset_mems_allowed - return mems_allowed mask from a tasks cpuset.
4654  * @tsk: pointer to task_struct from which to obtain cpuset->mems_allowed.
4655  *
4656  * Description: Returns the nodemask_t mems_allowed of the cpuset
4657  * attached to the specified @tsk.  Guaranteed to return some non-empty
4658  * subset of node_states[N_MEMORY], even if this means going outside the
4659  * tasks cpuset.
4660  **/
4661
4662 nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
4663 {
4664         nodemask_t mask;
4665         unsigned long flags;
4666
4667         spin_lock_irqsave(&callback_lock, flags);
4668         rcu_read_lock();
4669         guarantee_online_mems(task_cs(tsk), &mask);
4670         rcu_read_unlock();
4671         spin_unlock_irqrestore(&callback_lock, flags);
4672
4673         return mask;
4674 }
4675
4676 /**
4677  * cpuset_nodemask_valid_mems_allowed - check nodemask vs. current mems_allowed
4678  * @nodemask: the nodemask to be checked
4679  *
4680  * Are any of the nodes in the nodemask allowed in current->mems_allowed?
4681  */
4682 int cpuset_nodemask_valid_mems_allowed(nodemask_t *nodemask)
4683 {
4684         return nodes_intersects(*nodemask, current->mems_allowed);
4685 }
4686
4687 /*
4688  * nearest_hardwall_ancestor() - Returns the nearest mem_exclusive or
4689  * mem_hardwall ancestor to the specified cpuset.  Call holding
4690  * callback_lock.  If no ancestor is mem_exclusive or mem_hardwall
4691  * (an unusual configuration), then returns the root cpuset.
4692  */
4693 static struct cpuset *nearest_hardwall_ancestor(struct cpuset *cs)
4694 {
4695         while (!(is_mem_exclusive(cs) || is_mem_hardwall(cs)) && parent_cs(cs))
4696                 cs = parent_cs(cs);
4697         return cs;
4698 }
4699
4700 /*
4701  * cpuset_node_allowed - Can we allocate on a memory node?
4702  * @node: is this an allowed node?
4703  * @gfp_mask: memory allocation flags
4704  *
4705  * If we're in interrupt, yes, we can always allocate.  If @node is set in
4706  * current's mems_allowed, yes.  If it's not a __GFP_HARDWALL request and this
4707  * node is set in the nearest hardwalled cpuset ancestor to current's cpuset,
4708  * yes.  If current has access to memory reserves as an oom victim, yes.
4709  * Otherwise, no.
4710  *
4711  * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
4712  * and do not allow allocations outside the current tasks cpuset
4713  * unless the task has been OOM killed.
4714  * GFP_KERNEL allocations are not so marked, so can escape to the
4715  * nearest enclosing hardwalled ancestor cpuset.
4716  *
4717  * Scanning up parent cpusets requires callback_lock.  The
4718  * __alloc_pages() routine only calls here with __GFP_HARDWALL bit
4719  * _not_ set if it's a GFP_KERNEL allocation, and all nodes in the
4720  * current tasks mems_allowed came up empty on the first pass over
4721  * the zonelist.  So only GFP_KERNEL allocations, if all nodes in the
4722  * cpuset are short of memory, might require taking the callback_lock.
4723  *
4724  * The first call here from mm/page_alloc:get_page_from_freelist()
4725  * has __GFP_HARDWALL set in gfp_mask, enforcing hardwall cpusets,
4726  * so no allocation on a node outside the cpuset is allowed (unless
4727  * in interrupt, of course).
4728  *
4729  * The second pass through get_page_from_freelist() doesn't even call
4730  * here for GFP_ATOMIC calls.  For those calls, the __alloc_pages()
4731  * variable 'wait' is not set, and the bit ALLOC_CPUSET is not set
4732  * in alloc_flags.  That logic and the checks below have the combined
4733  * affect that:
4734  *      in_interrupt - any node ok (current task context irrelevant)
4735  *      GFP_ATOMIC   - any node ok
4736  *      tsk_is_oom_victim   - any node ok
4737  *      GFP_KERNEL   - any node in enclosing hardwalled cpuset ok
4738  *      GFP_USER     - only nodes in current tasks mems allowed ok.
4739  */
4740 bool cpuset_node_allowed(int node, gfp_t gfp_mask)
4741 {
4742         struct cpuset *cs;              /* current cpuset ancestors */
4743         bool allowed;                   /* is allocation in zone z allowed? */
4744         unsigned long flags;
4745
4746         if (in_interrupt())
4747                 return true;
4748         if (node_isset(node, current->mems_allowed))
4749                 return true;
4750         /*
4751          * Allow tasks that have access to memory reserves because they have
4752          * been OOM killed to get memory anywhere.
4753          */
4754         if (unlikely(tsk_is_oom_victim(current)))
4755                 return true;
4756         if (gfp_mask & __GFP_HARDWALL)  /* If hardwall request, stop here */
4757                 return false;
4758
4759         if (current->flags & PF_EXITING) /* Let dying task have memory */
4760                 return true;
4761
4762         /* Not hardwall and node outside mems_allowed: scan up cpusets */
4763         spin_lock_irqsave(&callback_lock, flags);
4764
4765         rcu_read_lock();
4766         cs = nearest_hardwall_ancestor(task_cs(current));
4767         allowed = node_isset(node, cs->mems_allowed);
4768         rcu_read_unlock();
4769
4770         spin_unlock_irqrestore(&callback_lock, flags);
4771         return allowed;
4772 }
4773
4774 /**
4775  * cpuset_spread_node() - On which node to begin search for a page
4776  * @rotor: round robin rotor
4777  *
4778  * If a task is marked PF_SPREAD_PAGE or PF_SPREAD_SLAB (as for
4779  * tasks in a cpuset with is_spread_page or is_spread_slab set),
4780  * and if the memory allocation used cpuset_mem_spread_node()
4781  * to determine on which node to start looking, as it will for
4782  * certain page cache or slab cache pages such as used for file
4783  * system buffers and inode caches, then instead of starting on the
4784  * local node to look for a free page, rather spread the starting
4785  * node around the tasks mems_allowed nodes.
4786  *
4787  * We don't have to worry about the returned node being offline
4788  * because "it can't happen", and even if it did, it would be ok.
4789  *
4790  * The routines calling guarantee_online_mems() are careful to
4791  * only set nodes in task->mems_allowed that are online.  So it
4792  * should not be possible for the following code to return an
4793  * offline node.  But if it did, that would be ok, as this routine
4794  * is not returning the node where the allocation must be, only
4795  * the node where the search should start.  The zonelist passed to
4796  * __alloc_pages() will include all nodes.  If the slab allocator
4797  * is passed an offline node, it will fall back to the local node.
4798  * See kmem_cache_alloc_node().
4799  */
4800 static int cpuset_spread_node(int *rotor)
4801 {
4802         return *rotor = next_node_in(*rotor, current->mems_allowed);
4803 }
4804
4805 /**
4806  * cpuset_mem_spread_node() - On which node to begin search for a file page
4807  */
4808 int cpuset_mem_spread_node(void)
4809 {
4810         if (current->cpuset_mem_spread_rotor == NUMA_NO_NODE)
4811                 current->cpuset_mem_spread_rotor =
4812                         node_random(&current->mems_allowed);
4813
4814         return cpuset_spread_node(&current->cpuset_mem_spread_rotor);
4815 }
4816
4817 /**
4818  * cpuset_slab_spread_node() - On which node to begin search for a slab page
4819  */
4820 int cpuset_slab_spread_node(void)
4821 {
4822         if (current->cpuset_slab_spread_rotor == NUMA_NO_NODE)
4823                 current->cpuset_slab_spread_rotor =
4824                         node_random(&current->mems_allowed);
4825
4826         return cpuset_spread_node(&current->cpuset_slab_spread_rotor);
4827 }
4828 EXPORT_SYMBOL_GPL(cpuset_mem_spread_node);
4829
4830 /**
4831  * cpuset_mems_allowed_intersects - Does @tsk1's mems_allowed intersect @tsk2's?
4832  * @tsk1: pointer to task_struct of some task.
4833  * @tsk2: pointer to task_struct of some other task.
4834  *
4835  * Description: Return true if @tsk1's mems_allowed intersects the
4836  * mems_allowed of @tsk2.  Used by the OOM killer to determine if
4837  * one of the task's memory usage might impact the memory available
4838  * to the other.
4839  **/
4840
4841 int cpuset_mems_allowed_intersects(const struct task_struct *tsk1,
4842                                    const struct task_struct *tsk2)
4843 {
4844         return nodes_intersects(tsk1->mems_allowed, tsk2->mems_allowed);
4845 }
4846
4847 /**
4848  * cpuset_print_current_mems_allowed - prints current's cpuset and mems_allowed
4849  *
4850  * Description: Prints current's name, cpuset name, and cached copy of its
4851  * mems_allowed to the kernel log.
4852  */
4853 void cpuset_print_current_mems_allowed(void)
4854 {
4855         struct cgroup *cgrp;
4856
4857         rcu_read_lock();
4858
4859         cgrp = task_cs(current)->css.cgroup;
4860         pr_cont(",cpuset=");
4861         pr_cont_cgroup_name(cgrp);
4862         pr_cont(",mems_allowed=%*pbl",
4863                 nodemask_pr_args(&current->mems_allowed));
4864
4865         rcu_read_unlock();
4866 }
4867
4868 /*
4869  * Collection of memory_pressure is suppressed unless
4870  * this flag is enabled by writing "1" to the special
4871  * cpuset file 'memory_pressure_enabled' in the root cpuset.
4872  */
4873
4874 int cpuset_memory_pressure_enabled __read_mostly;
4875
4876 /*
4877  * __cpuset_memory_pressure_bump - keep stats of per-cpuset reclaims.
4878  *
4879  * Keep a running average of the rate of synchronous (direct)
4880  * page reclaim efforts initiated by tasks in each cpuset.
4881  *
4882  * This represents the rate at which some task in the cpuset
4883  * ran low on memory on all nodes it was allowed to use, and
4884  * had to enter the kernels page reclaim code in an effort to
4885  * create more free memory by tossing clean pages or swapping
4886  * or writing dirty pages.
4887  *
4888  * Display to user space in the per-cpuset read-only file
4889  * "memory_pressure".  Value displayed is an integer
4890  * representing the recent rate of entry into the synchronous
4891  * (direct) page reclaim by any task attached to the cpuset.
4892  */
4893
4894 void __cpuset_memory_pressure_bump(void)
4895 {
4896         rcu_read_lock();
4897         fmeter_markevent(&task_cs(current)->fmeter);
4898         rcu_read_unlock();
4899 }
4900
4901 #ifdef CONFIG_PROC_PID_CPUSET
4902 /*
4903  * proc_cpuset_show()
4904  *  - Print tasks cpuset path into seq_file.
4905  *  - Used for /proc/<pid>/cpuset.
4906  *  - No need to task_lock(tsk) on this tsk->cpuset reference, as it
4907  *    doesn't really matter if tsk->cpuset changes after we read it,
4908  *    and we take cpuset_mutex, keeping cpuset_attach() from changing it
4909  *    anyway.
4910  */
4911 int proc_cpuset_show(struct seq_file *m, struct pid_namespace *ns,
4912                      struct pid *pid, struct task_struct *tsk)
4913 {
4914         char *buf;
4915         struct cgroup_subsys_state *css;
4916         int retval;
4917
4918         retval = -ENOMEM;
4919         buf = kmalloc(PATH_MAX, GFP_KERNEL);
4920         if (!buf)
4921                 goto out;
4922
4923         css = task_get_css(tsk, cpuset_cgrp_id);
4924         retval = cgroup_path_ns(css->cgroup, buf, PATH_MAX,
4925                                 current->nsproxy->cgroup_ns);
4926         css_put(css);
4927         if (retval >= PATH_MAX)
4928                 retval = -ENAMETOOLONG;
4929         if (retval < 0)
4930                 goto out_free;
4931         seq_puts(m, buf);
4932         seq_putc(m, '\n');
4933         retval = 0;
4934 out_free:
4935         kfree(buf);
4936 out:
4937         return retval;
4938 }
4939 #endif /* CONFIG_PROC_PID_CPUSET */
4940
4941 /* Display task mems_allowed in /proc/<pid>/status file. */
4942 void cpuset_task_status_allowed(struct seq_file *m, struct task_struct *task)
4943 {
4944         seq_printf(m, "Mems_allowed:\t%*pb\n",
4945                    nodemask_pr_args(&task->mems_allowed));
4946         seq_printf(m, "Mems_allowed_list:\t%*pbl\n",
4947                    nodemask_pr_args(&task->mems_allowed));
4948 }