xref: /openbmc/linux/kernel/cgroup/cpuset.c (revision ac5f3136)
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/err.h>
29 #include <linux/errno.h>
30 #include <linux/file.h>
31 #include <linux/fs.h>
32 #include <linux/init.h>
33 #include <linux/interrupt.h>
34 #include <linux/kernel.h>
35 #include <linux/kmod.h>
36 #include <linux/list.h>
37 #include <linux/mempolicy.h>
38 #include <linux/mm.h>
39 #include <linux/memory.h>
40 #include <linux/export.h>
41 #include <linux/mount.h>
42 #include <linux/fs_context.h>
43 #include <linux/namei.h>
44 #include <linux/pagemap.h>
45 #include <linux/proc_fs.h>
46 #include <linux/rcupdate.h>
47 #include <linux/sched.h>
48 #include <linux/sched/deadline.h>
49 #include <linux/sched/mm.h>
50 #include <linux/sched/task.h>
51 #include <linux/seq_file.h>
52 #include <linux/security.h>
53 #include <linux/slab.h>
54 #include <linux/spinlock.h>
55 #include <linux/stat.h>
56 #include <linux/string.h>
57 #include <linux/time.h>
58 #include <linux/time64.h>
59 #include <linux/backing-dev.h>
60 #include <linux/sort.h>
61 #include <linux/oom.h>
62 #include <linux/sched/isolation.h>
63 #include <linux/uaccess.h>
64 #include <linux/atomic.h>
65 #include <linux/mutex.h>
66 #include <linux/cgroup.h>
67 #include <linux/wait.h>
68 
69 DEFINE_STATIC_KEY_FALSE(cpusets_pre_enable_key);
70 DEFINE_STATIC_KEY_FALSE(cpusets_enabled_key);
71 
72 /* See "Frequency meter" comments, below. */
73 
74 struct fmeter {
75 	int cnt;		/* unprocessed events count */
76 	int val;		/* most recent output value */
77 	time64_t time;		/* clock (secs) when val computed */
78 	spinlock_t lock;	/* guards read or write of above */
79 };
80 
81 struct cpuset {
82 	struct cgroup_subsys_state css;
83 
84 	unsigned long flags;		/* "unsigned long" so bitops work */
85 
86 	/*
87 	 * On default hierarchy:
88 	 *
89 	 * The user-configured masks can only be changed by writing to
90 	 * cpuset.cpus and cpuset.mems, and won't be limited by the
91 	 * parent masks.
92 	 *
93 	 * The effective masks is the real masks that apply to the tasks
94 	 * in the cpuset. They may be changed if the configured masks are
95 	 * changed or hotplug happens.
96 	 *
97 	 * effective_mask == configured_mask & parent's effective_mask,
98 	 * and if it ends up empty, it will inherit the parent's mask.
99 	 *
100 	 *
101 	 * On legacy hierarchy:
102 	 *
103 	 * The user-configured masks are always the same with effective masks.
104 	 */
105 
106 	/* user-configured CPUs and Memory Nodes allow to tasks */
107 	cpumask_var_t cpus_allowed;
108 	nodemask_t mems_allowed;
109 
110 	/* effective CPUs and Memory Nodes allow to tasks */
111 	cpumask_var_t effective_cpus;
112 	nodemask_t effective_mems;
113 
114 	/*
115 	 * CPUs allocated to child sub-partitions (default hierarchy only)
116 	 * - CPUs granted by the parent = effective_cpus U subparts_cpus
117 	 * - effective_cpus and subparts_cpus are mutually exclusive.
118 	 *
119 	 * effective_cpus contains only onlined CPUs, but subparts_cpus
120 	 * may have offlined ones.
121 	 */
122 	cpumask_var_t subparts_cpus;
123 
124 	/*
125 	 * This is old Memory Nodes tasks took on.
126 	 *
127 	 * - top_cpuset.old_mems_allowed is initialized to mems_allowed.
128 	 * - A new cpuset's old_mems_allowed is initialized when some
129 	 *   task is moved into it.
130 	 * - old_mems_allowed is used in cpuset_migrate_mm() when we change
131 	 *   cpuset.mems_allowed and have tasks' nodemask updated, and
132 	 *   then old_mems_allowed is updated to mems_allowed.
133 	 */
134 	nodemask_t old_mems_allowed;
135 
136 	struct fmeter fmeter;		/* memory_pressure filter */
137 
138 	/*
139 	 * Tasks are being attached to this cpuset.  Used to prevent
140 	 * zeroing cpus/mems_allowed between ->can_attach() and ->attach().
141 	 */
142 	int attach_in_progress;
143 
144 	/* partition number for rebuild_sched_domains() */
145 	int pn;
146 
147 	/* for custom sched domain */
148 	int relax_domain_level;
149 
150 	/* number of CPUs in subparts_cpus */
151 	int nr_subparts_cpus;
152 
153 	/* partition root state */
154 	int partition_root_state;
155 
156 	/*
157 	 * Default hierarchy only:
158 	 * use_parent_ecpus - set if using parent's effective_cpus
159 	 * child_ecpus_count - # of children with use_parent_ecpus set
160 	 */
161 	int use_parent_ecpus;
162 	int child_ecpus_count;
163 
164 	/* Handle for cpuset.cpus.partition */
165 	struct cgroup_file partition_file;
166 };
167 
168 /*
169  * Partition root states:
170  *
171  *   0 - not a partition root
172  *
173  *   1 - partition root
174  *
175  *  -1 - invalid partition root
176  *       None of the cpus in cpus_allowed can be put into the parent's
177  *       subparts_cpus. In this case, the cpuset is not a real partition
178  *       root anymore.  However, the CPU_EXCLUSIVE bit will still be set
179  *       and the cpuset can be restored back to a partition root if the
180  *       parent cpuset can give more CPUs back to this child cpuset.
181  */
182 #define PRS_DISABLED		0
183 #define PRS_ENABLED		1
184 #define PRS_ERROR		-1
185 
186 /*
187  * Temporary cpumasks for working with partitions that are passed among
188  * functions to avoid memory allocation in inner functions.
189  */
190 struct tmpmasks {
191 	cpumask_var_t addmask, delmask;	/* For partition root */
192 	cpumask_var_t new_cpus;		/* For update_cpumasks_hier() */
193 };
194 
195 static inline struct cpuset *css_cs(struct cgroup_subsys_state *css)
196 {
197 	return css ? container_of(css, struct cpuset, css) : NULL;
198 }
199 
200 /* Retrieve the cpuset for a task */
201 static inline struct cpuset *task_cs(struct task_struct *task)
202 {
203 	return css_cs(task_css(task, cpuset_cgrp_id));
204 }
205 
206 static inline struct cpuset *parent_cs(struct cpuset *cs)
207 {
208 	return css_cs(cs->css.parent);
209 }
210 
211 /* bits in struct cpuset flags field */
212 typedef enum {
213 	CS_ONLINE,
214 	CS_CPU_EXCLUSIVE,
215 	CS_MEM_EXCLUSIVE,
216 	CS_MEM_HARDWALL,
217 	CS_MEMORY_MIGRATE,
218 	CS_SCHED_LOAD_BALANCE,
219 	CS_SPREAD_PAGE,
220 	CS_SPREAD_SLAB,
221 } cpuset_flagbits_t;
222 
223 /* convenient tests for these bits */
224 static inline bool is_cpuset_online(struct cpuset *cs)
225 {
226 	return test_bit(CS_ONLINE, &cs->flags) && !css_is_dying(&cs->css);
227 }
228 
229 static inline int is_cpu_exclusive(const struct cpuset *cs)
230 {
231 	return test_bit(CS_CPU_EXCLUSIVE, &cs->flags);
232 }
233 
234 static inline int is_mem_exclusive(const struct cpuset *cs)
235 {
236 	return test_bit(CS_MEM_EXCLUSIVE, &cs->flags);
237 }
238 
239 static inline int is_mem_hardwall(const struct cpuset *cs)
240 {
241 	return test_bit(CS_MEM_HARDWALL, &cs->flags);
242 }
243 
244 static inline int is_sched_load_balance(const struct cpuset *cs)
245 {
246 	return test_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
247 }
248 
249 static inline int is_memory_migrate(const struct cpuset *cs)
250 {
251 	return test_bit(CS_MEMORY_MIGRATE, &cs->flags);
252 }
253 
254 static inline int is_spread_page(const struct cpuset *cs)
255 {
256 	return test_bit(CS_SPREAD_PAGE, &cs->flags);
257 }
258 
259 static inline int is_spread_slab(const struct cpuset *cs)
260 {
261 	return test_bit(CS_SPREAD_SLAB, &cs->flags);
262 }
263 
264 static inline int is_partition_root(const struct cpuset *cs)
265 {
266 	return cs->partition_root_state > 0;
267 }
268 
269 /*
270  * Send notification event of whenever partition_root_state changes.
271  */
272 static inline void notify_partition_change(struct cpuset *cs,
273 					   int old_prs, int new_prs)
274 {
275 	if (old_prs != new_prs)
276 		cgroup_file_notify(&cs->partition_file);
277 }
278 
279 static struct cpuset top_cpuset = {
280 	.flags = ((1 << CS_ONLINE) | (1 << CS_CPU_EXCLUSIVE) |
281 		  (1 << CS_MEM_EXCLUSIVE)),
282 	.partition_root_state = PRS_ENABLED,
283 };
284 
285 /**
286  * cpuset_for_each_child - traverse online children of a cpuset
287  * @child_cs: loop cursor pointing to the current child
288  * @pos_css: used for iteration
289  * @parent_cs: target cpuset to walk children of
290  *
291  * Walk @child_cs through the online children of @parent_cs.  Must be used
292  * with RCU read locked.
293  */
294 #define cpuset_for_each_child(child_cs, pos_css, parent_cs)		\
295 	css_for_each_child((pos_css), &(parent_cs)->css)		\
296 		if (is_cpuset_online(((child_cs) = css_cs((pos_css)))))
297 
298 /**
299  * cpuset_for_each_descendant_pre - pre-order walk of a cpuset's descendants
300  * @des_cs: loop cursor pointing to the current descendant
301  * @pos_css: used for iteration
302  * @root_cs: target cpuset to walk ancestor of
303  *
304  * Walk @des_cs through the online descendants of @root_cs.  Must be used
305  * with RCU read locked.  The caller may modify @pos_css by calling
306  * css_rightmost_descendant() to skip subtree.  @root_cs is included in the
307  * iteration and the first node to be visited.
308  */
309 #define cpuset_for_each_descendant_pre(des_cs, pos_css, root_cs)	\
310 	css_for_each_descendant_pre((pos_css), &(root_cs)->css)		\
311 		if (is_cpuset_online(((des_cs) = css_cs((pos_css)))))
312 
313 /*
314  * There are two global locks guarding cpuset structures - cpuset_mutex and
315  * callback_lock. We also require taking task_lock() when dereferencing a
316  * task's cpuset pointer. See "The task_lock() exception", at the end of this
317  * comment.
318  *
319  * A task must hold both locks to modify cpusets.  If a task holds
320  * cpuset_mutex, then it blocks others wanting that mutex, ensuring that it
321  * is the only task able to also acquire callback_lock and be able to
322  * modify cpusets.  It can perform various checks on the cpuset structure
323  * first, knowing nothing will change.  It can also allocate memory while
324  * just holding cpuset_mutex.  While it is performing these checks, various
325  * callback routines can briefly acquire callback_lock to query cpusets.
326  * Once it is ready to make the changes, it takes callback_lock, blocking
327  * everyone else.
328  *
329  * Calls to the kernel memory allocator can not be made while holding
330  * callback_lock, as that would risk double tripping on callback_lock
331  * from one of the callbacks into the cpuset code from within
332  * __alloc_pages().
333  *
334  * If a task is only holding callback_lock, then it has read-only
335  * access to cpusets.
336  *
337  * Now, the task_struct fields mems_allowed and mempolicy may be changed
338  * by other task, we use alloc_lock in the task_struct fields to protect
339  * them.
340  *
341  * The cpuset_common_file_read() handlers only hold callback_lock across
342  * small pieces of code, such as when reading out possibly multi-word
343  * cpumasks and nodemasks.
344  *
345  * Accessing a task's cpuset should be done in accordance with the
346  * guidelines for accessing subsystem state in kernel/cgroup.c
347  */
348 
349 DEFINE_STATIC_PERCPU_RWSEM(cpuset_rwsem);
350 
351 void cpuset_read_lock(void)
352 {
353 	percpu_down_read(&cpuset_rwsem);
354 }
355 
356 void cpuset_read_unlock(void)
357 {
358 	percpu_up_read(&cpuset_rwsem);
359 }
360 
361 static DEFINE_SPINLOCK(callback_lock);
362 
363 static struct workqueue_struct *cpuset_migrate_mm_wq;
364 
365 /*
366  * CPU / memory hotplug is handled asynchronously.
367  */
368 static void cpuset_hotplug_workfn(struct work_struct *work);
369 static DECLARE_WORK(cpuset_hotplug_work, cpuset_hotplug_workfn);
370 
371 static DECLARE_WAIT_QUEUE_HEAD(cpuset_attach_wq);
372 
373 /*
374  * Cgroup v2 behavior is used on the "cpus" and "mems" control files when
375  * on default hierarchy or when the cpuset_v2_mode flag is set by mounting
376  * the v1 cpuset cgroup filesystem with the "cpuset_v2_mode" mount option.
377  * With v2 behavior, "cpus" and "mems" are always what the users have
378  * requested and won't be changed by hotplug events. Only the effective
379  * cpus or mems will be affected.
380  */
381 static inline bool is_in_v2_mode(void)
382 {
383 	return cgroup_subsys_on_dfl(cpuset_cgrp_subsys) ||
384 	      (cpuset_cgrp_subsys.root->flags & CGRP_ROOT_CPUSET_V2_MODE);
385 }
386 
387 /*
388  * Return in pmask the portion of a task's cpusets's cpus_allowed that
389  * are online and are capable of running the task.  If none are found,
390  * walk up the cpuset hierarchy until we find one that does have some
391  * appropriate cpus.
392  *
393  * One way or another, we guarantee to return some non-empty subset
394  * of cpu_online_mask.
395  *
396  * Call with callback_lock or cpuset_mutex held.
397  */
398 static void guarantee_online_cpus(struct task_struct *tsk,
399 				  struct cpumask *pmask)
400 {
401 	const struct cpumask *possible_mask = task_cpu_possible_mask(tsk);
402 	struct cpuset *cs;
403 
404 	if (WARN_ON(!cpumask_and(pmask, possible_mask, cpu_online_mask)))
405 		cpumask_copy(pmask, cpu_online_mask);
406 
407 	rcu_read_lock();
408 	cs = task_cs(tsk);
409 
410 	while (!cpumask_intersects(cs->effective_cpus, pmask)) {
411 		cs = parent_cs(cs);
412 		if (unlikely(!cs)) {
413 			/*
414 			 * The top cpuset doesn't have any online cpu as a
415 			 * consequence of a race between cpuset_hotplug_work
416 			 * and cpu hotplug notifier.  But we know the top
417 			 * cpuset's effective_cpus is on its way to be
418 			 * identical to cpu_online_mask.
419 			 */
420 			goto out_unlock;
421 		}
422 	}
423 	cpumask_and(pmask, pmask, cs->effective_cpus);
424 
425 out_unlock:
426 	rcu_read_unlock();
427 }
428 
429 /*
430  * Return in *pmask the portion of a cpusets's mems_allowed that
431  * are online, with memory.  If none are online with memory, walk
432  * up the cpuset hierarchy until we find one that does have some
433  * online mems.  The top cpuset always has some mems online.
434  *
435  * One way or another, we guarantee to return some non-empty subset
436  * of node_states[N_MEMORY].
437  *
438  * Call with callback_lock or cpuset_mutex held.
439  */
440 static void guarantee_online_mems(struct cpuset *cs, nodemask_t *pmask)
441 {
442 	while (!nodes_intersects(cs->effective_mems, node_states[N_MEMORY]))
443 		cs = parent_cs(cs);
444 	nodes_and(*pmask, cs->effective_mems, node_states[N_MEMORY]);
445 }
446 
447 /*
448  * update task's spread flag if cpuset's page/slab spread flag is set
449  *
450  * Call with callback_lock or cpuset_mutex held.
451  */
452 static void cpuset_update_task_spread_flag(struct cpuset *cs,
453 					struct task_struct *tsk)
454 {
455 	if (is_spread_page(cs))
456 		task_set_spread_page(tsk);
457 	else
458 		task_clear_spread_page(tsk);
459 
460 	if (is_spread_slab(cs))
461 		task_set_spread_slab(tsk);
462 	else
463 		task_clear_spread_slab(tsk);
464 }
465 
466 /*
467  * is_cpuset_subset(p, q) - Is cpuset p a subset of cpuset q?
468  *
469  * One cpuset is a subset of another if all its allowed CPUs and
470  * Memory Nodes are a subset of the other, and its exclusive flags
471  * are only set if the other's are set.  Call holding cpuset_mutex.
472  */
473 
474 static int is_cpuset_subset(const struct cpuset *p, const struct cpuset *q)
475 {
476 	return	cpumask_subset(p->cpus_allowed, q->cpus_allowed) &&
477 		nodes_subset(p->mems_allowed, q->mems_allowed) &&
478 		is_cpu_exclusive(p) <= is_cpu_exclusive(q) &&
479 		is_mem_exclusive(p) <= is_mem_exclusive(q);
480 }
481 
482 /**
483  * alloc_cpumasks - allocate three cpumasks for cpuset
484  * @cs:  the cpuset that have cpumasks to be allocated.
485  * @tmp: the tmpmasks structure pointer
486  * Return: 0 if successful, -ENOMEM otherwise.
487  *
488  * Only one of the two input arguments should be non-NULL.
489  */
490 static inline int alloc_cpumasks(struct cpuset *cs, struct tmpmasks *tmp)
491 {
492 	cpumask_var_t *pmask1, *pmask2, *pmask3;
493 
494 	if (cs) {
495 		pmask1 = &cs->cpus_allowed;
496 		pmask2 = &cs->effective_cpus;
497 		pmask3 = &cs->subparts_cpus;
498 	} else {
499 		pmask1 = &tmp->new_cpus;
500 		pmask2 = &tmp->addmask;
501 		pmask3 = &tmp->delmask;
502 	}
503 
504 	if (!zalloc_cpumask_var(pmask1, GFP_KERNEL))
505 		return -ENOMEM;
506 
507 	if (!zalloc_cpumask_var(pmask2, GFP_KERNEL))
508 		goto free_one;
509 
510 	if (!zalloc_cpumask_var(pmask3, GFP_KERNEL))
511 		goto free_two;
512 
513 	return 0;
514 
515 free_two:
516 	free_cpumask_var(*pmask2);
517 free_one:
518 	free_cpumask_var(*pmask1);
519 	return -ENOMEM;
520 }
521 
522 /**
523  * free_cpumasks - free cpumasks in a tmpmasks structure
524  * @cs:  the cpuset that have cpumasks to be free.
525  * @tmp: the tmpmasks structure pointer
526  */
527 static inline void free_cpumasks(struct cpuset *cs, struct tmpmasks *tmp)
528 {
529 	if (cs) {
530 		free_cpumask_var(cs->cpus_allowed);
531 		free_cpumask_var(cs->effective_cpus);
532 		free_cpumask_var(cs->subparts_cpus);
533 	}
534 	if (tmp) {
535 		free_cpumask_var(tmp->new_cpus);
536 		free_cpumask_var(tmp->addmask);
537 		free_cpumask_var(tmp->delmask);
538 	}
539 }
540 
541 /**
542  * alloc_trial_cpuset - allocate a trial cpuset
543  * @cs: the cpuset that the trial cpuset duplicates
544  */
545 static struct cpuset *alloc_trial_cpuset(struct cpuset *cs)
546 {
547 	struct cpuset *trial;
548 
549 	trial = kmemdup(cs, sizeof(*cs), GFP_KERNEL);
550 	if (!trial)
551 		return NULL;
552 
553 	if (alloc_cpumasks(trial, NULL)) {
554 		kfree(trial);
555 		return NULL;
556 	}
557 
558 	cpumask_copy(trial->cpus_allowed, cs->cpus_allowed);
559 	cpumask_copy(trial->effective_cpus, cs->effective_cpus);
560 	return trial;
561 }
562 
563 /**
564  * free_cpuset - free the cpuset
565  * @cs: the cpuset to be freed
566  */
567 static inline void free_cpuset(struct cpuset *cs)
568 {
569 	free_cpumasks(cs, NULL);
570 	kfree(cs);
571 }
572 
573 /*
574  * validate_change() - Used to validate that any proposed cpuset change
575  *		       follows the structural rules for cpusets.
576  *
577  * If we replaced the flag and mask values of the current cpuset
578  * (cur) with those values in the trial cpuset (trial), would
579  * our various subset and exclusive rules still be valid?  Presumes
580  * cpuset_mutex held.
581  *
582  * 'cur' is the address of an actual, in-use cpuset.  Operations
583  * such as list traversal that depend on the actual address of the
584  * cpuset in the list must use cur below, not trial.
585  *
586  * 'trial' is the address of bulk structure copy of cur, with
587  * perhaps one or more of the fields cpus_allowed, mems_allowed,
588  * or flags changed to new, trial values.
589  *
590  * Return 0 if valid, -errno if not.
591  */
592 
593 static int validate_change(struct cpuset *cur, struct cpuset *trial)
594 {
595 	struct cgroup_subsys_state *css;
596 	struct cpuset *c, *par;
597 	int ret;
598 
599 	rcu_read_lock();
600 
601 	/* Each of our child cpusets must be a subset of us */
602 	ret = -EBUSY;
603 	cpuset_for_each_child(c, css, cur)
604 		if (!is_cpuset_subset(c, trial))
605 			goto out;
606 
607 	/* Remaining checks don't apply to root cpuset */
608 	ret = 0;
609 	if (cur == &top_cpuset)
610 		goto out;
611 
612 	par = parent_cs(cur);
613 
614 	/* On legacy hierarchy, we must be a subset of our parent cpuset. */
615 	ret = -EACCES;
616 	if (!is_in_v2_mode() && !is_cpuset_subset(trial, par))
617 		goto out;
618 
619 	/*
620 	 * If either I or some sibling (!= me) is exclusive, we can't
621 	 * overlap
622 	 */
623 	ret = -EINVAL;
624 	cpuset_for_each_child(c, css, par) {
625 		if ((is_cpu_exclusive(trial) || is_cpu_exclusive(c)) &&
626 		    c != cur &&
627 		    cpumask_intersects(trial->cpus_allowed, c->cpus_allowed))
628 			goto out;
629 		if ((is_mem_exclusive(trial) || is_mem_exclusive(c)) &&
630 		    c != cur &&
631 		    nodes_intersects(trial->mems_allowed, c->mems_allowed))
632 			goto out;
633 	}
634 
635 	/*
636 	 * Cpusets with tasks - existing or newly being attached - can't
637 	 * be changed to have empty cpus_allowed or mems_allowed.
638 	 */
639 	ret = -ENOSPC;
640 	if ((cgroup_is_populated(cur->css.cgroup) || cur->attach_in_progress)) {
641 		if (!cpumask_empty(cur->cpus_allowed) &&
642 		    cpumask_empty(trial->cpus_allowed))
643 			goto out;
644 		if (!nodes_empty(cur->mems_allowed) &&
645 		    nodes_empty(trial->mems_allowed))
646 			goto out;
647 	}
648 
649 	/*
650 	 * We can't shrink if we won't have enough room for SCHED_DEADLINE
651 	 * tasks.
652 	 */
653 	ret = -EBUSY;
654 	if (is_cpu_exclusive(cur) &&
655 	    !cpuset_cpumask_can_shrink(cur->cpus_allowed,
656 				       trial->cpus_allowed))
657 		goto out;
658 
659 	ret = 0;
660 out:
661 	rcu_read_unlock();
662 	return ret;
663 }
664 
665 #ifdef CONFIG_SMP
666 /*
667  * Helper routine for generate_sched_domains().
668  * Do cpusets a, b have overlapping effective cpus_allowed masks?
669  */
670 static int cpusets_overlap(struct cpuset *a, struct cpuset *b)
671 {
672 	return cpumask_intersects(a->effective_cpus, b->effective_cpus);
673 }
674 
675 static void
676 update_domain_attr(struct sched_domain_attr *dattr, struct cpuset *c)
677 {
678 	if (dattr->relax_domain_level < c->relax_domain_level)
679 		dattr->relax_domain_level = c->relax_domain_level;
680 	return;
681 }
682 
683 static void update_domain_attr_tree(struct sched_domain_attr *dattr,
684 				    struct cpuset *root_cs)
685 {
686 	struct cpuset *cp;
687 	struct cgroup_subsys_state *pos_css;
688 
689 	rcu_read_lock();
690 	cpuset_for_each_descendant_pre(cp, pos_css, root_cs) {
691 		/* skip the whole subtree if @cp doesn't have any CPU */
692 		if (cpumask_empty(cp->cpus_allowed)) {
693 			pos_css = css_rightmost_descendant(pos_css);
694 			continue;
695 		}
696 
697 		if (is_sched_load_balance(cp))
698 			update_domain_attr(dattr, cp);
699 	}
700 	rcu_read_unlock();
701 }
702 
703 /* Must be called with cpuset_mutex held.  */
704 static inline int nr_cpusets(void)
705 {
706 	/* jump label reference count + the top-level cpuset */
707 	return static_key_count(&cpusets_enabled_key.key) + 1;
708 }
709 
710 /*
711  * generate_sched_domains()
712  *
713  * This function builds a partial partition of the systems CPUs
714  * A 'partial partition' is a set of non-overlapping subsets whose
715  * union is a subset of that set.
716  * The output of this function needs to be passed to kernel/sched/core.c
717  * partition_sched_domains() routine, which will rebuild the scheduler's
718  * load balancing domains (sched domains) as specified by that partial
719  * partition.
720  *
721  * See "What is sched_load_balance" in Documentation/admin-guide/cgroup-v1/cpusets.rst
722  * for a background explanation of this.
723  *
724  * Does not return errors, on the theory that the callers of this
725  * routine would rather not worry about failures to rebuild sched
726  * domains when operating in the severe memory shortage situations
727  * that could cause allocation failures below.
728  *
729  * Must be called with cpuset_mutex held.
730  *
731  * The three key local variables below are:
732  *    cp - cpuset pointer, used (together with pos_css) to perform a
733  *	   top-down scan of all cpusets. For our purposes, rebuilding
734  *	   the schedulers sched domains, we can ignore !is_sched_load_
735  *	   balance cpusets.
736  *  csa  - (for CpuSet Array) Array of pointers to all the cpusets
737  *	   that need to be load balanced, for convenient iterative
738  *	   access by the subsequent code that finds the best partition,
739  *	   i.e the set of domains (subsets) of CPUs such that the
740  *	   cpus_allowed of every cpuset marked is_sched_load_balance
741  *	   is a subset of one of these domains, while there are as
742  *	   many such domains as possible, each as small as possible.
743  * doms  - Conversion of 'csa' to an array of cpumasks, for passing to
744  *	   the kernel/sched/core.c routine partition_sched_domains() in a
745  *	   convenient format, that can be easily compared to the prior
746  *	   value to determine what partition elements (sched domains)
747  *	   were changed (added or removed.)
748  *
749  * Finding the best partition (set of domains):
750  *	The triple nested loops below over i, j, k scan over the
751  *	load balanced cpusets (using the array of cpuset pointers in
752  *	csa[]) looking for pairs of cpusets that have overlapping
753  *	cpus_allowed, but which don't have the same 'pn' partition
754  *	number and gives them in the same partition number.  It keeps
755  *	looping on the 'restart' label until it can no longer find
756  *	any such pairs.
757  *
758  *	The union of the cpus_allowed masks from the set of
759  *	all cpusets having the same 'pn' value then form the one
760  *	element of the partition (one sched domain) to be passed to
761  *	partition_sched_domains().
762  */
763 static int generate_sched_domains(cpumask_var_t **domains,
764 			struct sched_domain_attr **attributes)
765 {
766 	struct cpuset *cp;	/* top-down scan of cpusets */
767 	struct cpuset **csa;	/* array of all cpuset ptrs */
768 	int csn;		/* how many cpuset ptrs in csa so far */
769 	int i, j, k;		/* indices for partition finding loops */
770 	cpumask_var_t *doms;	/* resulting partition; i.e. sched domains */
771 	struct sched_domain_attr *dattr;  /* attributes for custom domains */
772 	int ndoms = 0;		/* number of sched domains in result */
773 	int nslot;		/* next empty doms[] struct cpumask slot */
774 	struct cgroup_subsys_state *pos_css;
775 	bool root_load_balance = is_sched_load_balance(&top_cpuset);
776 
777 	doms = NULL;
778 	dattr = NULL;
779 	csa = NULL;
780 
781 	/* Special case for the 99% of systems with one, full, sched domain */
782 	if (root_load_balance && !top_cpuset.nr_subparts_cpus) {
783 		ndoms = 1;
784 		doms = alloc_sched_domains(ndoms);
785 		if (!doms)
786 			goto done;
787 
788 		dattr = kmalloc(sizeof(struct sched_domain_attr), GFP_KERNEL);
789 		if (dattr) {
790 			*dattr = SD_ATTR_INIT;
791 			update_domain_attr_tree(dattr, &top_cpuset);
792 		}
793 		cpumask_and(doms[0], top_cpuset.effective_cpus,
794 			    housekeeping_cpumask(HK_FLAG_DOMAIN));
795 
796 		goto done;
797 	}
798 
799 	csa = kmalloc_array(nr_cpusets(), sizeof(cp), GFP_KERNEL);
800 	if (!csa)
801 		goto done;
802 	csn = 0;
803 
804 	rcu_read_lock();
805 	if (root_load_balance)
806 		csa[csn++] = &top_cpuset;
807 	cpuset_for_each_descendant_pre(cp, pos_css, &top_cpuset) {
808 		if (cp == &top_cpuset)
809 			continue;
810 		/*
811 		 * Continue traversing beyond @cp iff @cp has some CPUs and
812 		 * isn't load balancing.  The former is obvious.  The
813 		 * latter: All child cpusets contain a subset of the
814 		 * parent's cpus, so just skip them, and then we call
815 		 * update_domain_attr_tree() to calc relax_domain_level of
816 		 * the corresponding sched domain.
817 		 *
818 		 * If root is load-balancing, we can skip @cp if it
819 		 * is a subset of the root's effective_cpus.
820 		 */
821 		if (!cpumask_empty(cp->cpus_allowed) &&
822 		    !(is_sched_load_balance(cp) &&
823 		      cpumask_intersects(cp->cpus_allowed,
824 					 housekeeping_cpumask(HK_FLAG_DOMAIN))))
825 			continue;
826 
827 		if (root_load_balance &&
828 		    cpumask_subset(cp->cpus_allowed, top_cpuset.effective_cpus))
829 			continue;
830 
831 		if (is_sched_load_balance(cp) &&
832 		    !cpumask_empty(cp->effective_cpus))
833 			csa[csn++] = cp;
834 
835 		/* skip @cp's subtree if not a partition root */
836 		if (!is_partition_root(cp))
837 			pos_css = css_rightmost_descendant(pos_css);
838 	}
839 	rcu_read_unlock();
840 
841 	for (i = 0; i < csn; i++)
842 		csa[i]->pn = i;
843 	ndoms = csn;
844 
845 restart:
846 	/* Find the best partition (set of sched domains) */
847 	for (i = 0; i < csn; i++) {
848 		struct cpuset *a = csa[i];
849 		int apn = a->pn;
850 
851 		for (j = 0; j < csn; j++) {
852 			struct cpuset *b = csa[j];
853 			int bpn = b->pn;
854 
855 			if (apn != bpn && cpusets_overlap(a, b)) {
856 				for (k = 0; k < csn; k++) {
857 					struct cpuset *c = csa[k];
858 
859 					if (c->pn == bpn)
860 						c->pn = apn;
861 				}
862 				ndoms--;	/* one less element */
863 				goto restart;
864 			}
865 		}
866 	}
867 
868 	/*
869 	 * Now we know how many domains to create.
870 	 * Convert <csn, csa> to <ndoms, doms> and populate cpu masks.
871 	 */
872 	doms = alloc_sched_domains(ndoms);
873 	if (!doms)
874 		goto done;
875 
876 	/*
877 	 * The rest of the code, including the scheduler, can deal with
878 	 * dattr==NULL case. No need to abort if alloc fails.
879 	 */
880 	dattr = kmalloc_array(ndoms, sizeof(struct sched_domain_attr),
881 			      GFP_KERNEL);
882 
883 	for (nslot = 0, i = 0; i < csn; i++) {
884 		struct cpuset *a = csa[i];
885 		struct cpumask *dp;
886 		int apn = a->pn;
887 
888 		if (apn < 0) {
889 			/* Skip completed partitions */
890 			continue;
891 		}
892 
893 		dp = doms[nslot];
894 
895 		if (nslot == ndoms) {
896 			static int warnings = 10;
897 			if (warnings) {
898 				pr_warn("rebuild_sched_domains confused: nslot %d, ndoms %d, csn %d, i %d, apn %d\n",
899 					nslot, ndoms, csn, i, apn);
900 				warnings--;
901 			}
902 			continue;
903 		}
904 
905 		cpumask_clear(dp);
906 		if (dattr)
907 			*(dattr + nslot) = SD_ATTR_INIT;
908 		for (j = i; j < csn; j++) {
909 			struct cpuset *b = csa[j];
910 
911 			if (apn == b->pn) {
912 				cpumask_or(dp, dp, b->effective_cpus);
913 				cpumask_and(dp, dp, housekeeping_cpumask(HK_FLAG_DOMAIN));
914 				if (dattr)
915 					update_domain_attr_tree(dattr + nslot, b);
916 
917 				/* Done with this partition */
918 				b->pn = -1;
919 			}
920 		}
921 		nslot++;
922 	}
923 	BUG_ON(nslot != ndoms);
924 
925 done:
926 	kfree(csa);
927 
928 	/*
929 	 * Fallback to the default domain if kmalloc() failed.
930 	 * See comments in partition_sched_domains().
931 	 */
932 	if (doms == NULL)
933 		ndoms = 1;
934 
935 	*domains    = doms;
936 	*attributes = dattr;
937 	return ndoms;
938 }
939 
940 static void update_tasks_root_domain(struct cpuset *cs)
941 {
942 	struct css_task_iter it;
943 	struct task_struct *task;
944 
945 	css_task_iter_start(&cs->css, 0, &it);
946 
947 	while ((task = css_task_iter_next(&it)))
948 		dl_add_task_root_domain(task);
949 
950 	css_task_iter_end(&it);
951 }
952 
953 static void rebuild_root_domains(void)
954 {
955 	struct cpuset *cs = NULL;
956 	struct cgroup_subsys_state *pos_css;
957 
958 	percpu_rwsem_assert_held(&cpuset_rwsem);
959 	lockdep_assert_cpus_held();
960 	lockdep_assert_held(&sched_domains_mutex);
961 
962 	rcu_read_lock();
963 
964 	/*
965 	 * Clear default root domain DL accounting, it will be computed again
966 	 * if a task belongs to it.
967 	 */
968 	dl_clear_root_domain(&def_root_domain);
969 
970 	cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
971 
972 		if (cpumask_empty(cs->effective_cpus)) {
973 			pos_css = css_rightmost_descendant(pos_css);
974 			continue;
975 		}
976 
977 		css_get(&cs->css);
978 
979 		rcu_read_unlock();
980 
981 		update_tasks_root_domain(cs);
982 
983 		rcu_read_lock();
984 		css_put(&cs->css);
985 	}
986 	rcu_read_unlock();
987 }
988 
989 static void
990 partition_and_rebuild_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
991 				    struct sched_domain_attr *dattr_new)
992 {
993 	mutex_lock(&sched_domains_mutex);
994 	partition_sched_domains_locked(ndoms_new, doms_new, dattr_new);
995 	rebuild_root_domains();
996 	mutex_unlock(&sched_domains_mutex);
997 }
998 
999 /*
1000  * Rebuild scheduler domains.
1001  *
1002  * If the flag 'sched_load_balance' of any cpuset with non-empty
1003  * 'cpus' changes, or if the 'cpus' allowed changes in any cpuset
1004  * which has that flag enabled, or if any cpuset with a non-empty
1005  * 'cpus' is removed, then call this routine to rebuild the
1006  * scheduler's dynamic sched domains.
1007  *
1008  * Call with cpuset_mutex held.  Takes cpus_read_lock().
1009  */
1010 static void rebuild_sched_domains_locked(void)
1011 {
1012 	struct cgroup_subsys_state *pos_css;
1013 	struct sched_domain_attr *attr;
1014 	cpumask_var_t *doms;
1015 	struct cpuset *cs;
1016 	int ndoms;
1017 
1018 	lockdep_assert_cpus_held();
1019 	percpu_rwsem_assert_held(&cpuset_rwsem);
1020 
1021 	/*
1022 	 * If we have raced with CPU hotplug, return early to avoid
1023 	 * passing doms with offlined cpu to partition_sched_domains().
1024 	 * Anyways, cpuset_hotplug_workfn() will rebuild sched domains.
1025 	 *
1026 	 * With no CPUs in any subpartitions, top_cpuset's effective CPUs
1027 	 * should be the same as the active CPUs, so checking only top_cpuset
1028 	 * is enough to detect racing CPU offlines.
1029 	 */
1030 	if (!top_cpuset.nr_subparts_cpus &&
1031 	    !cpumask_equal(top_cpuset.effective_cpus, cpu_active_mask))
1032 		return;
1033 
1034 	/*
1035 	 * With subpartition CPUs, however, the effective CPUs of a partition
1036 	 * root should be only a subset of the active CPUs.  Since a CPU in any
1037 	 * partition root could be offlined, all must be checked.
1038 	 */
1039 	if (top_cpuset.nr_subparts_cpus) {
1040 		rcu_read_lock();
1041 		cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
1042 			if (!is_partition_root(cs)) {
1043 				pos_css = css_rightmost_descendant(pos_css);
1044 				continue;
1045 			}
1046 			if (!cpumask_subset(cs->effective_cpus,
1047 					    cpu_active_mask)) {
1048 				rcu_read_unlock();
1049 				return;
1050 			}
1051 		}
1052 		rcu_read_unlock();
1053 	}
1054 
1055 	/* Generate domain masks and attrs */
1056 	ndoms = generate_sched_domains(&doms, &attr);
1057 
1058 	/* Have scheduler rebuild the domains */
1059 	partition_and_rebuild_sched_domains(ndoms, doms, attr);
1060 }
1061 #else /* !CONFIG_SMP */
1062 static void rebuild_sched_domains_locked(void)
1063 {
1064 }
1065 #endif /* CONFIG_SMP */
1066 
1067 void rebuild_sched_domains(void)
1068 {
1069 	cpus_read_lock();
1070 	percpu_down_write(&cpuset_rwsem);
1071 	rebuild_sched_domains_locked();
1072 	percpu_up_write(&cpuset_rwsem);
1073 	cpus_read_unlock();
1074 }
1075 
1076 /**
1077  * update_tasks_cpumask - Update the cpumasks of tasks in the cpuset.
1078  * @cs: the cpuset in which each task's cpus_allowed mask needs to be changed
1079  *
1080  * Iterate through each task of @cs updating its cpus_allowed to the
1081  * effective cpuset's.  As this function is called with cpuset_mutex held,
1082  * cpuset membership stays stable.
1083  */
1084 static void update_tasks_cpumask(struct cpuset *cs)
1085 {
1086 	struct css_task_iter it;
1087 	struct task_struct *task;
1088 
1089 	css_task_iter_start(&cs->css, 0, &it);
1090 	while ((task = css_task_iter_next(&it)))
1091 		set_cpus_allowed_ptr(task, cs->effective_cpus);
1092 	css_task_iter_end(&it);
1093 }
1094 
1095 /**
1096  * compute_effective_cpumask - Compute the effective cpumask of the cpuset
1097  * @new_cpus: the temp variable for the new effective_cpus mask
1098  * @cs: the cpuset the need to recompute the new effective_cpus mask
1099  * @parent: the parent cpuset
1100  *
1101  * If the parent has subpartition CPUs, include them in the list of
1102  * allowable CPUs in computing the new effective_cpus mask. Since offlined
1103  * CPUs are not removed from subparts_cpus, we have to use cpu_active_mask
1104  * to mask those out.
1105  */
1106 static void compute_effective_cpumask(struct cpumask *new_cpus,
1107 				      struct cpuset *cs, struct cpuset *parent)
1108 {
1109 	if (parent->nr_subparts_cpus) {
1110 		cpumask_or(new_cpus, parent->effective_cpus,
1111 			   parent->subparts_cpus);
1112 		cpumask_and(new_cpus, new_cpus, cs->cpus_allowed);
1113 		cpumask_and(new_cpus, new_cpus, cpu_active_mask);
1114 	} else {
1115 		cpumask_and(new_cpus, cs->cpus_allowed, parent->effective_cpus);
1116 	}
1117 }
1118 
1119 /*
1120  * Commands for update_parent_subparts_cpumask
1121  */
1122 enum subparts_cmd {
1123 	partcmd_enable,		/* Enable partition root	 */
1124 	partcmd_disable,	/* Disable partition root	 */
1125 	partcmd_update,		/* Update parent's subparts_cpus */
1126 };
1127 
1128 /**
1129  * update_parent_subparts_cpumask - update subparts_cpus mask of parent cpuset
1130  * @cpuset:  The cpuset that requests change in partition root state
1131  * @cmd:     Partition root state change command
1132  * @newmask: Optional new cpumask for partcmd_update
1133  * @tmp:     Temporary addmask and delmask
1134  * Return:   0, 1 or an error code
1135  *
1136  * For partcmd_enable, the cpuset is being transformed from a non-partition
1137  * root to a partition root. The cpus_allowed mask of the given cpuset will
1138  * be put into parent's subparts_cpus and taken away from parent's
1139  * effective_cpus. The function will return 0 if all the CPUs listed in
1140  * cpus_allowed can be granted or an error code will be returned.
1141  *
1142  * For partcmd_disable, the cpuset is being transofrmed from a partition
1143  * root back to a non-partition root. Any CPUs in cpus_allowed that are in
1144  * parent's subparts_cpus will be taken away from that cpumask and put back
1145  * into parent's effective_cpus. 0 should always be returned.
1146  *
1147  * For partcmd_update, if the optional newmask is specified, the cpu
1148  * list is to be changed from cpus_allowed to newmask. Otherwise,
1149  * cpus_allowed is assumed to remain the same. The cpuset should either
1150  * be a partition root or an invalid partition root. The partition root
1151  * state may change if newmask is NULL and none of the requested CPUs can
1152  * be granted by the parent. The function will return 1 if changes to
1153  * parent's subparts_cpus and effective_cpus happen or 0 otherwise.
1154  * Error code should only be returned when newmask is non-NULL.
1155  *
1156  * The partcmd_enable and partcmd_disable commands are used by
1157  * update_prstate(). The partcmd_update command is used by
1158  * update_cpumasks_hier() with newmask NULL and update_cpumask() with
1159  * newmask set.
1160  *
1161  * The checking is more strict when enabling partition root than the
1162  * other two commands.
1163  *
1164  * Because of the implicit cpu exclusive nature of a partition root,
1165  * cpumask changes that violates the cpu exclusivity rule will not be
1166  * permitted when checked by validate_change(). The validate_change()
1167  * function will also prevent any changes to the cpu list if it is not
1168  * a superset of children's cpu lists.
1169  */
1170 static int update_parent_subparts_cpumask(struct cpuset *cpuset, int cmd,
1171 					  struct cpumask *newmask,
1172 					  struct tmpmasks *tmp)
1173 {
1174 	struct cpuset *parent = parent_cs(cpuset);
1175 	int adding;	/* Moving cpus from effective_cpus to subparts_cpus */
1176 	int deleting;	/* Moving cpus from subparts_cpus to effective_cpus */
1177 	int old_prs, new_prs;
1178 	bool part_error = false;	/* Partition error? */
1179 
1180 	percpu_rwsem_assert_held(&cpuset_rwsem);
1181 
1182 	/*
1183 	 * The parent must be a partition root.
1184 	 * The new cpumask, if present, or the current cpus_allowed must
1185 	 * not be empty.
1186 	 */
1187 	if (!is_partition_root(parent) ||
1188 	   (newmask && cpumask_empty(newmask)) ||
1189 	   (!newmask && cpumask_empty(cpuset->cpus_allowed)))
1190 		return -EINVAL;
1191 
1192 	/*
1193 	 * Enabling/disabling partition root is not allowed if there are
1194 	 * online children.
1195 	 */
1196 	if ((cmd != partcmd_update) && css_has_online_children(&cpuset->css))
1197 		return -EBUSY;
1198 
1199 	/*
1200 	 * Enabling partition root is not allowed if not all the CPUs
1201 	 * can be granted from parent's effective_cpus or at least one
1202 	 * CPU will be left after that.
1203 	 */
1204 	if ((cmd == partcmd_enable) &&
1205 	   (!cpumask_subset(cpuset->cpus_allowed, parent->effective_cpus) ||
1206 	     cpumask_equal(cpuset->cpus_allowed, parent->effective_cpus)))
1207 		return -EINVAL;
1208 
1209 	/*
1210 	 * A cpumask update cannot make parent's effective_cpus become empty.
1211 	 */
1212 	adding = deleting = false;
1213 	old_prs = new_prs = cpuset->partition_root_state;
1214 	if (cmd == partcmd_enable) {
1215 		cpumask_copy(tmp->addmask, cpuset->cpus_allowed);
1216 		adding = true;
1217 	} else if (cmd == partcmd_disable) {
1218 		deleting = cpumask_and(tmp->delmask, cpuset->cpus_allowed,
1219 				       parent->subparts_cpus);
1220 	} else if (newmask) {
1221 		/*
1222 		 * partcmd_update with newmask:
1223 		 *
1224 		 * delmask = cpus_allowed & ~newmask & parent->subparts_cpus
1225 		 * addmask = newmask & parent->effective_cpus
1226 		 *		     & ~parent->subparts_cpus
1227 		 */
1228 		cpumask_andnot(tmp->delmask, cpuset->cpus_allowed, newmask);
1229 		deleting = cpumask_and(tmp->delmask, tmp->delmask,
1230 				       parent->subparts_cpus);
1231 
1232 		cpumask_and(tmp->addmask, newmask, parent->effective_cpus);
1233 		adding = cpumask_andnot(tmp->addmask, tmp->addmask,
1234 					parent->subparts_cpus);
1235 		/*
1236 		 * Return error if the new effective_cpus could become empty.
1237 		 */
1238 		if (adding &&
1239 		    cpumask_equal(parent->effective_cpus, tmp->addmask)) {
1240 			if (!deleting)
1241 				return -EINVAL;
1242 			/*
1243 			 * As some of the CPUs in subparts_cpus might have
1244 			 * been offlined, we need to compute the real delmask
1245 			 * to confirm that.
1246 			 */
1247 			if (!cpumask_and(tmp->addmask, tmp->delmask,
1248 					 cpu_active_mask))
1249 				return -EINVAL;
1250 			cpumask_copy(tmp->addmask, parent->effective_cpus);
1251 		}
1252 	} else {
1253 		/*
1254 		 * partcmd_update w/o newmask:
1255 		 *
1256 		 * addmask = cpus_allowed & parent->effective_cpus
1257 		 *
1258 		 * Note that parent's subparts_cpus may have been
1259 		 * pre-shrunk in case there is a change in the cpu list.
1260 		 * So no deletion is needed.
1261 		 */
1262 		adding = cpumask_and(tmp->addmask, cpuset->cpus_allowed,
1263 				     parent->effective_cpus);
1264 		part_error = cpumask_equal(tmp->addmask,
1265 					   parent->effective_cpus);
1266 	}
1267 
1268 	if (cmd == partcmd_update) {
1269 		int prev_prs = cpuset->partition_root_state;
1270 
1271 		/*
1272 		 * Check for possible transition between PRS_ENABLED
1273 		 * and PRS_ERROR.
1274 		 */
1275 		switch (cpuset->partition_root_state) {
1276 		case PRS_ENABLED:
1277 			if (part_error)
1278 				new_prs = PRS_ERROR;
1279 			break;
1280 		case PRS_ERROR:
1281 			if (!part_error)
1282 				new_prs = PRS_ENABLED;
1283 			break;
1284 		}
1285 		/*
1286 		 * Set part_error if previously in invalid state.
1287 		 */
1288 		part_error = (prev_prs == PRS_ERROR);
1289 	}
1290 
1291 	if (!part_error && (new_prs == PRS_ERROR))
1292 		return 0;	/* Nothing need to be done */
1293 
1294 	if (new_prs == PRS_ERROR) {
1295 		/*
1296 		 * Remove all its cpus from parent's subparts_cpus.
1297 		 */
1298 		adding = false;
1299 		deleting = cpumask_and(tmp->delmask, cpuset->cpus_allowed,
1300 				       parent->subparts_cpus);
1301 	}
1302 
1303 	if (!adding && !deleting && (new_prs == old_prs))
1304 		return 0;
1305 
1306 	/*
1307 	 * Change the parent's subparts_cpus.
1308 	 * Newly added CPUs will be removed from effective_cpus and
1309 	 * newly deleted ones will be added back to effective_cpus.
1310 	 */
1311 	spin_lock_irq(&callback_lock);
1312 	if (adding) {
1313 		cpumask_or(parent->subparts_cpus,
1314 			   parent->subparts_cpus, tmp->addmask);
1315 		cpumask_andnot(parent->effective_cpus,
1316 			       parent->effective_cpus, tmp->addmask);
1317 	}
1318 	if (deleting) {
1319 		cpumask_andnot(parent->subparts_cpus,
1320 			       parent->subparts_cpus, tmp->delmask);
1321 		/*
1322 		 * Some of the CPUs in subparts_cpus might have been offlined.
1323 		 */
1324 		cpumask_and(tmp->delmask, tmp->delmask, cpu_active_mask);
1325 		cpumask_or(parent->effective_cpus,
1326 			   parent->effective_cpus, tmp->delmask);
1327 	}
1328 
1329 	parent->nr_subparts_cpus = cpumask_weight(parent->subparts_cpus);
1330 
1331 	if (old_prs != new_prs)
1332 		cpuset->partition_root_state = new_prs;
1333 
1334 	spin_unlock_irq(&callback_lock);
1335 	notify_partition_change(cpuset, old_prs, new_prs);
1336 
1337 	return cmd == partcmd_update;
1338 }
1339 
1340 /*
1341  * update_cpumasks_hier - Update effective cpumasks and tasks in the subtree
1342  * @cs:  the cpuset to consider
1343  * @tmp: temp variables for calculating effective_cpus & partition setup
1344  *
1345  * When configured cpumask is changed, the effective cpumasks of this cpuset
1346  * and all its descendants need to be updated.
1347  *
1348  * On legacy hierarchy, effective_cpus will be the same with cpu_allowed.
1349  *
1350  * Called with cpuset_mutex held
1351  */
1352 static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp)
1353 {
1354 	struct cpuset *cp;
1355 	struct cgroup_subsys_state *pos_css;
1356 	bool need_rebuild_sched_domains = false;
1357 	int old_prs, new_prs;
1358 
1359 	rcu_read_lock();
1360 	cpuset_for_each_descendant_pre(cp, pos_css, cs) {
1361 		struct cpuset *parent = parent_cs(cp);
1362 
1363 		compute_effective_cpumask(tmp->new_cpus, cp, parent);
1364 
1365 		/*
1366 		 * If it becomes empty, inherit the effective mask of the
1367 		 * parent, which is guaranteed to have some CPUs.
1368 		 */
1369 		if (is_in_v2_mode() && cpumask_empty(tmp->new_cpus)) {
1370 			cpumask_copy(tmp->new_cpus, parent->effective_cpus);
1371 			if (!cp->use_parent_ecpus) {
1372 				cp->use_parent_ecpus = true;
1373 				parent->child_ecpus_count++;
1374 			}
1375 		} else if (cp->use_parent_ecpus) {
1376 			cp->use_parent_ecpus = false;
1377 			WARN_ON_ONCE(!parent->child_ecpus_count);
1378 			parent->child_ecpus_count--;
1379 		}
1380 
1381 		/*
1382 		 * Skip the whole subtree if the cpumask remains the same
1383 		 * and has no partition root state.
1384 		 */
1385 		if (!cp->partition_root_state &&
1386 		    cpumask_equal(tmp->new_cpus, cp->effective_cpus)) {
1387 			pos_css = css_rightmost_descendant(pos_css);
1388 			continue;
1389 		}
1390 
1391 		/*
1392 		 * update_parent_subparts_cpumask() should have been called
1393 		 * for cs already in update_cpumask(). We should also call
1394 		 * update_tasks_cpumask() again for tasks in the parent
1395 		 * cpuset if the parent's subparts_cpus changes.
1396 		 */
1397 		old_prs = new_prs = cp->partition_root_state;
1398 		if ((cp != cs) && old_prs) {
1399 			switch (parent->partition_root_state) {
1400 			case PRS_DISABLED:
1401 				/*
1402 				 * If parent is not a partition root or an
1403 				 * invalid partition root, clear its state
1404 				 * and its CS_CPU_EXCLUSIVE flag.
1405 				 */
1406 				WARN_ON_ONCE(cp->partition_root_state
1407 					     != PRS_ERROR);
1408 				new_prs = PRS_DISABLED;
1409 
1410 				/*
1411 				 * clear_bit() is an atomic operation and
1412 				 * readers aren't interested in the state
1413 				 * of CS_CPU_EXCLUSIVE anyway. So we can
1414 				 * just update the flag without holding
1415 				 * the callback_lock.
1416 				 */
1417 				clear_bit(CS_CPU_EXCLUSIVE, &cp->flags);
1418 				break;
1419 
1420 			case PRS_ENABLED:
1421 				if (update_parent_subparts_cpumask(cp, partcmd_update, NULL, tmp))
1422 					update_tasks_cpumask(parent);
1423 				break;
1424 
1425 			case PRS_ERROR:
1426 				/*
1427 				 * When parent is invalid, it has to be too.
1428 				 */
1429 				new_prs = PRS_ERROR;
1430 				break;
1431 			}
1432 		}
1433 
1434 		if (!css_tryget_online(&cp->css))
1435 			continue;
1436 		rcu_read_unlock();
1437 
1438 		spin_lock_irq(&callback_lock);
1439 
1440 		cpumask_copy(cp->effective_cpus, tmp->new_cpus);
1441 		if (cp->nr_subparts_cpus && (new_prs != PRS_ENABLED)) {
1442 			cp->nr_subparts_cpus = 0;
1443 			cpumask_clear(cp->subparts_cpus);
1444 		} else if (cp->nr_subparts_cpus) {
1445 			/*
1446 			 * Make sure that effective_cpus & subparts_cpus
1447 			 * are mutually exclusive.
1448 			 *
1449 			 * In the unlikely event that effective_cpus
1450 			 * becomes empty. we clear cp->nr_subparts_cpus and
1451 			 * let its child partition roots to compete for
1452 			 * CPUs again.
1453 			 */
1454 			cpumask_andnot(cp->effective_cpus, cp->effective_cpus,
1455 				       cp->subparts_cpus);
1456 			if (cpumask_empty(cp->effective_cpus)) {
1457 				cpumask_copy(cp->effective_cpus, tmp->new_cpus);
1458 				cpumask_clear(cp->subparts_cpus);
1459 				cp->nr_subparts_cpus = 0;
1460 			} else if (!cpumask_subset(cp->subparts_cpus,
1461 						   tmp->new_cpus)) {
1462 				cpumask_andnot(cp->subparts_cpus,
1463 					cp->subparts_cpus, tmp->new_cpus);
1464 				cp->nr_subparts_cpus
1465 					= cpumask_weight(cp->subparts_cpus);
1466 			}
1467 		}
1468 
1469 		if (new_prs != old_prs)
1470 			cp->partition_root_state = new_prs;
1471 
1472 		spin_unlock_irq(&callback_lock);
1473 		notify_partition_change(cp, old_prs, new_prs);
1474 
1475 		WARN_ON(!is_in_v2_mode() &&
1476 			!cpumask_equal(cp->cpus_allowed, cp->effective_cpus));
1477 
1478 		update_tasks_cpumask(cp);
1479 
1480 		/*
1481 		 * On legacy hierarchy, if the effective cpumask of any non-
1482 		 * empty cpuset is changed, we need to rebuild sched domains.
1483 		 * On default hierarchy, the cpuset needs to be a partition
1484 		 * root as well.
1485 		 */
1486 		if (!cpumask_empty(cp->cpus_allowed) &&
1487 		    is_sched_load_balance(cp) &&
1488 		   (!cgroup_subsys_on_dfl(cpuset_cgrp_subsys) ||
1489 		    is_partition_root(cp)))
1490 			need_rebuild_sched_domains = true;
1491 
1492 		rcu_read_lock();
1493 		css_put(&cp->css);
1494 	}
1495 	rcu_read_unlock();
1496 
1497 	if (need_rebuild_sched_domains)
1498 		rebuild_sched_domains_locked();
1499 }
1500 
1501 /**
1502  * update_sibling_cpumasks - Update siblings cpumasks
1503  * @parent:  Parent cpuset
1504  * @cs:      Current cpuset
1505  * @tmp:     Temp variables
1506  */
1507 static void update_sibling_cpumasks(struct cpuset *parent, struct cpuset *cs,
1508 				    struct tmpmasks *tmp)
1509 {
1510 	struct cpuset *sibling;
1511 	struct cgroup_subsys_state *pos_css;
1512 
1513 	/*
1514 	 * Check all its siblings and call update_cpumasks_hier()
1515 	 * if their use_parent_ecpus flag is set in order for them
1516 	 * to use the right effective_cpus value.
1517 	 */
1518 	rcu_read_lock();
1519 	cpuset_for_each_child(sibling, pos_css, parent) {
1520 		if (sibling == cs)
1521 			continue;
1522 		if (!sibling->use_parent_ecpus)
1523 			continue;
1524 
1525 		update_cpumasks_hier(sibling, tmp);
1526 	}
1527 	rcu_read_unlock();
1528 }
1529 
1530 /**
1531  * update_cpumask - update the cpus_allowed mask of a cpuset and all tasks in it
1532  * @cs: the cpuset to consider
1533  * @trialcs: trial cpuset
1534  * @buf: buffer of cpu numbers written to this cpuset
1535  */
1536 static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs,
1537 			  const char *buf)
1538 {
1539 	int retval;
1540 	struct tmpmasks tmp;
1541 
1542 	/* top_cpuset.cpus_allowed tracks cpu_online_mask; it's read-only */
1543 	if (cs == &top_cpuset)
1544 		return -EACCES;
1545 
1546 	/*
1547 	 * An empty cpus_allowed is ok only if the cpuset has no tasks.
1548 	 * Since cpulist_parse() fails on an empty mask, we special case
1549 	 * that parsing.  The validate_change() call ensures that cpusets
1550 	 * with tasks have cpus.
1551 	 */
1552 	if (!*buf) {
1553 		cpumask_clear(trialcs->cpus_allowed);
1554 	} else {
1555 		retval = cpulist_parse(buf, trialcs->cpus_allowed);
1556 		if (retval < 0)
1557 			return retval;
1558 
1559 		if (!cpumask_subset(trialcs->cpus_allowed,
1560 				    top_cpuset.cpus_allowed))
1561 			return -EINVAL;
1562 	}
1563 
1564 	/* Nothing to do if the cpus didn't change */
1565 	if (cpumask_equal(cs->cpus_allowed, trialcs->cpus_allowed))
1566 		return 0;
1567 
1568 	retval = validate_change(cs, trialcs);
1569 	if (retval < 0)
1570 		return retval;
1571 
1572 #ifdef CONFIG_CPUMASK_OFFSTACK
1573 	/*
1574 	 * Use the cpumasks in trialcs for tmpmasks when they are pointers
1575 	 * to allocated cpumasks.
1576 	 */
1577 	tmp.addmask  = trialcs->subparts_cpus;
1578 	tmp.delmask  = trialcs->effective_cpus;
1579 	tmp.new_cpus = trialcs->cpus_allowed;
1580 #endif
1581 
1582 	if (cs->partition_root_state) {
1583 		/* Cpumask of a partition root cannot be empty */
1584 		if (cpumask_empty(trialcs->cpus_allowed))
1585 			return -EINVAL;
1586 		if (update_parent_subparts_cpumask(cs, partcmd_update,
1587 					trialcs->cpus_allowed, &tmp) < 0)
1588 			return -EINVAL;
1589 	}
1590 
1591 	spin_lock_irq(&callback_lock);
1592 	cpumask_copy(cs->cpus_allowed, trialcs->cpus_allowed);
1593 
1594 	/*
1595 	 * Make sure that subparts_cpus is a subset of cpus_allowed.
1596 	 */
1597 	if (cs->nr_subparts_cpus) {
1598 		cpumask_andnot(cs->subparts_cpus, cs->subparts_cpus,
1599 			       cs->cpus_allowed);
1600 		cs->nr_subparts_cpus = cpumask_weight(cs->subparts_cpus);
1601 	}
1602 	spin_unlock_irq(&callback_lock);
1603 
1604 	update_cpumasks_hier(cs, &tmp);
1605 
1606 	if (cs->partition_root_state) {
1607 		struct cpuset *parent = parent_cs(cs);
1608 
1609 		/*
1610 		 * For partition root, update the cpumasks of sibling
1611 		 * cpusets if they use parent's effective_cpus.
1612 		 */
1613 		if (parent->child_ecpus_count)
1614 			update_sibling_cpumasks(parent, cs, &tmp);
1615 	}
1616 	return 0;
1617 }
1618 
1619 /*
1620  * Migrate memory region from one set of nodes to another.  This is
1621  * performed asynchronously as it can be called from process migration path
1622  * holding locks involved in process management.  All mm migrations are
1623  * performed in the queued order and can be waited for by flushing
1624  * cpuset_migrate_mm_wq.
1625  */
1626 
1627 struct cpuset_migrate_mm_work {
1628 	struct work_struct	work;
1629 	struct mm_struct	*mm;
1630 	nodemask_t		from;
1631 	nodemask_t		to;
1632 };
1633 
1634 static void cpuset_migrate_mm_workfn(struct work_struct *work)
1635 {
1636 	struct cpuset_migrate_mm_work *mwork =
1637 		container_of(work, struct cpuset_migrate_mm_work, work);
1638 
1639 	/* on a wq worker, no need to worry about %current's mems_allowed */
1640 	do_migrate_pages(mwork->mm, &mwork->from, &mwork->to, MPOL_MF_MOVE_ALL);
1641 	mmput(mwork->mm);
1642 	kfree(mwork);
1643 }
1644 
1645 static void cpuset_migrate_mm(struct mm_struct *mm, const nodemask_t *from,
1646 							const nodemask_t *to)
1647 {
1648 	struct cpuset_migrate_mm_work *mwork;
1649 
1650 	if (nodes_equal(*from, *to)) {
1651 		mmput(mm);
1652 		return;
1653 	}
1654 
1655 	mwork = kzalloc(sizeof(*mwork), GFP_KERNEL);
1656 	if (mwork) {
1657 		mwork->mm = mm;
1658 		mwork->from = *from;
1659 		mwork->to = *to;
1660 		INIT_WORK(&mwork->work, cpuset_migrate_mm_workfn);
1661 		queue_work(cpuset_migrate_mm_wq, &mwork->work);
1662 	} else {
1663 		mmput(mm);
1664 	}
1665 }
1666 
1667 static void cpuset_post_attach(void)
1668 {
1669 	flush_workqueue(cpuset_migrate_mm_wq);
1670 }
1671 
1672 /*
1673  * cpuset_change_task_nodemask - change task's mems_allowed and mempolicy
1674  * @tsk: the task to change
1675  * @newmems: new nodes that the task will be set
1676  *
1677  * We use the mems_allowed_seq seqlock to safely update both tsk->mems_allowed
1678  * and rebind an eventual tasks' mempolicy. If the task is allocating in
1679  * parallel, it might temporarily see an empty intersection, which results in
1680  * a seqlock check and retry before OOM or allocation failure.
1681  */
1682 static void cpuset_change_task_nodemask(struct task_struct *tsk,
1683 					nodemask_t *newmems)
1684 {
1685 	task_lock(tsk);
1686 
1687 	local_irq_disable();
1688 	write_seqcount_begin(&tsk->mems_allowed_seq);
1689 
1690 	nodes_or(tsk->mems_allowed, tsk->mems_allowed, *newmems);
1691 	mpol_rebind_task(tsk, newmems);
1692 	tsk->mems_allowed = *newmems;
1693 
1694 	write_seqcount_end(&tsk->mems_allowed_seq);
1695 	local_irq_enable();
1696 
1697 	task_unlock(tsk);
1698 }
1699 
1700 static void *cpuset_being_rebound;
1701 
1702 /**
1703  * update_tasks_nodemask - Update the nodemasks of tasks in the cpuset.
1704  * @cs: the cpuset in which each task's mems_allowed mask needs to be changed
1705  *
1706  * Iterate through each task of @cs updating its mems_allowed to the
1707  * effective cpuset's.  As this function is called with cpuset_mutex held,
1708  * cpuset membership stays stable.
1709  */
1710 static void update_tasks_nodemask(struct cpuset *cs)
1711 {
1712 	static nodemask_t newmems;	/* protected by cpuset_mutex */
1713 	struct css_task_iter it;
1714 	struct task_struct *task;
1715 
1716 	cpuset_being_rebound = cs;		/* causes mpol_dup() rebind */
1717 
1718 	guarantee_online_mems(cs, &newmems);
1719 
1720 	/*
1721 	 * The mpol_rebind_mm() call takes mmap_lock, which we couldn't
1722 	 * take while holding tasklist_lock.  Forks can happen - the
1723 	 * mpol_dup() cpuset_being_rebound check will catch such forks,
1724 	 * and rebind their vma mempolicies too.  Because we still hold
1725 	 * the global cpuset_mutex, we know that no other rebind effort
1726 	 * will be contending for the global variable cpuset_being_rebound.
1727 	 * It's ok if we rebind the same mm twice; mpol_rebind_mm()
1728 	 * is idempotent.  Also migrate pages in each mm to new nodes.
1729 	 */
1730 	css_task_iter_start(&cs->css, 0, &it);
1731 	while ((task = css_task_iter_next(&it))) {
1732 		struct mm_struct *mm;
1733 		bool migrate;
1734 
1735 		cpuset_change_task_nodemask(task, &newmems);
1736 
1737 		mm = get_task_mm(task);
1738 		if (!mm)
1739 			continue;
1740 
1741 		migrate = is_memory_migrate(cs);
1742 
1743 		mpol_rebind_mm(mm, &cs->mems_allowed);
1744 		if (migrate)
1745 			cpuset_migrate_mm(mm, &cs->old_mems_allowed, &newmems);
1746 		else
1747 			mmput(mm);
1748 	}
1749 	css_task_iter_end(&it);
1750 
1751 	/*
1752 	 * All the tasks' nodemasks have been updated, update
1753 	 * cs->old_mems_allowed.
1754 	 */
1755 	cs->old_mems_allowed = newmems;
1756 
1757 	/* We're done rebinding vmas to this cpuset's new mems_allowed. */
1758 	cpuset_being_rebound = NULL;
1759 }
1760 
1761 /*
1762  * update_nodemasks_hier - Update effective nodemasks and tasks in the subtree
1763  * @cs: the cpuset to consider
1764  * @new_mems: a temp variable for calculating new effective_mems
1765  *
1766  * When configured nodemask is changed, the effective nodemasks of this cpuset
1767  * and all its descendants need to be updated.
1768  *
1769  * On legacy hierarchy, effective_mems will be the same with mems_allowed.
1770  *
1771  * Called with cpuset_mutex held
1772  */
1773 static void update_nodemasks_hier(struct cpuset *cs, nodemask_t *new_mems)
1774 {
1775 	struct cpuset *cp;
1776 	struct cgroup_subsys_state *pos_css;
1777 
1778 	rcu_read_lock();
1779 	cpuset_for_each_descendant_pre(cp, pos_css, cs) {
1780 		struct cpuset *parent = parent_cs(cp);
1781 
1782 		nodes_and(*new_mems, cp->mems_allowed, parent->effective_mems);
1783 
1784 		/*
1785 		 * If it becomes empty, inherit the effective mask of the
1786 		 * parent, which is guaranteed to have some MEMs.
1787 		 */
1788 		if (is_in_v2_mode() && nodes_empty(*new_mems))
1789 			*new_mems = parent->effective_mems;
1790 
1791 		/* Skip the whole subtree if the nodemask remains the same. */
1792 		if (nodes_equal(*new_mems, cp->effective_mems)) {
1793 			pos_css = css_rightmost_descendant(pos_css);
1794 			continue;
1795 		}
1796 
1797 		if (!css_tryget_online(&cp->css))
1798 			continue;
1799 		rcu_read_unlock();
1800 
1801 		spin_lock_irq(&callback_lock);
1802 		cp->effective_mems = *new_mems;
1803 		spin_unlock_irq(&callback_lock);
1804 
1805 		WARN_ON(!is_in_v2_mode() &&
1806 			!nodes_equal(cp->mems_allowed, cp->effective_mems));
1807 
1808 		update_tasks_nodemask(cp);
1809 
1810 		rcu_read_lock();
1811 		css_put(&cp->css);
1812 	}
1813 	rcu_read_unlock();
1814 }
1815 
1816 /*
1817  * Handle user request to change the 'mems' memory placement
1818  * of a cpuset.  Needs to validate the request, update the
1819  * cpusets mems_allowed, and for each task in the cpuset,
1820  * update mems_allowed and rebind task's mempolicy and any vma
1821  * mempolicies and if the cpuset is marked 'memory_migrate',
1822  * migrate the tasks pages to the new memory.
1823  *
1824  * Call with cpuset_mutex held. May take callback_lock during call.
1825  * Will take tasklist_lock, scan tasklist for tasks in cpuset cs,
1826  * lock each such tasks mm->mmap_lock, scan its vma's and rebind
1827  * their mempolicies to the cpusets new mems_allowed.
1828  */
1829 static int update_nodemask(struct cpuset *cs, struct cpuset *trialcs,
1830 			   const char *buf)
1831 {
1832 	int retval;
1833 
1834 	/*
1835 	 * top_cpuset.mems_allowed tracks node_stats[N_MEMORY];
1836 	 * it's read-only
1837 	 */
1838 	if (cs == &top_cpuset) {
1839 		retval = -EACCES;
1840 		goto done;
1841 	}
1842 
1843 	/*
1844 	 * An empty mems_allowed is ok iff there are no tasks in the cpuset.
1845 	 * Since nodelist_parse() fails on an empty mask, we special case
1846 	 * that parsing.  The validate_change() call ensures that cpusets
1847 	 * with tasks have memory.
1848 	 */
1849 	if (!*buf) {
1850 		nodes_clear(trialcs->mems_allowed);
1851 	} else {
1852 		retval = nodelist_parse(buf, trialcs->mems_allowed);
1853 		if (retval < 0)
1854 			goto done;
1855 
1856 		if (!nodes_subset(trialcs->mems_allowed,
1857 				  top_cpuset.mems_allowed)) {
1858 			retval = -EINVAL;
1859 			goto done;
1860 		}
1861 	}
1862 
1863 	if (nodes_equal(cs->mems_allowed, trialcs->mems_allowed)) {
1864 		retval = 0;		/* Too easy - nothing to do */
1865 		goto done;
1866 	}
1867 	retval = validate_change(cs, trialcs);
1868 	if (retval < 0)
1869 		goto done;
1870 
1871 	spin_lock_irq(&callback_lock);
1872 	cs->mems_allowed = trialcs->mems_allowed;
1873 	spin_unlock_irq(&callback_lock);
1874 
1875 	/* use trialcs->mems_allowed as a temp variable */
1876 	update_nodemasks_hier(cs, &trialcs->mems_allowed);
1877 done:
1878 	return retval;
1879 }
1880 
1881 bool current_cpuset_is_being_rebound(void)
1882 {
1883 	bool ret;
1884 
1885 	rcu_read_lock();
1886 	ret = task_cs(current) == cpuset_being_rebound;
1887 	rcu_read_unlock();
1888 
1889 	return ret;
1890 }
1891 
1892 static int update_relax_domain_level(struct cpuset *cs, s64 val)
1893 {
1894 #ifdef CONFIG_SMP
1895 	if (val < -1 || val >= sched_domain_level_max)
1896 		return -EINVAL;
1897 #endif
1898 
1899 	if (val != cs->relax_domain_level) {
1900 		cs->relax_domain_level = val;
1901 		if (!cpumask_empty(cs->cpus_allowed) &&
1902 		    is_sched_load_balance(cs))
1903 			rebuild_sched_domains_locked();
1904 	}
1905 
1906 	return 0;
1907 }
1908 
1909 /**
1910  * update_tasks_flags - update the spread flags of tasks in the cpuset.
1911  * @cs: the cpuset in which each task's spread flags needs to be changed
1912  *
1913  * Iterate through each task of @cs updating its spread flags.  As this
1914  * function is called with cpuset_mutex held, cpuset membership stays
1915  * stable.
1916  */
1917 static void update_tasks_flags(struct cpuset *cs)
1918 {
1919 	struct css_task_iter it;
1920 	struct task_struct *task;
1921 
1922 	css_task_iter_start(&cs->css, 0, &it);
1923 	while ((task = css_task_iter_next(&it)))
1924 		cpuset_update_task_spread_flag(cs, task);
1925 	css_task_iter_end(&it);
1926 }
1927 
1928 /*
1929  * update_flag - read a 0 or a 1 in a file and update associated flag
1930  * bit:		the bit to update (see cpuset_flagbits_t)
1931  * cs:		the cpuset to update
1932  * turning_on: 	whether the flag is being set or cleared
1933  *
1934  * Call with cpuset_mutex held.
1935  */
1936 
1937 static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs,
1938 		       int turning_on)
1939 {
1940 	struct cpuset *trialcs;
1941 	int balance_flag_changed;
1942 	int spread_flag_changed;
1943 	int err;
1944 
1945 	trialcs = alloc_trial_cpuset(cs);
1946 	if (!trialcs)
1947 		return -ENOMEM;
1948 
1949 	if (turning_on)
1950 		set_bit(bit, &trialcs->flags);
1951 	else
1952 		clear_bit(bit, &trialcs->flags);
1953 
1954 	err = validate_change(cs, trialcs);
1955 	if (err < 0)
1956 		goto out;
1957 
1958 	balance_flag_changed = (is_sched_load_balance(cs) !=
1959 				is_sched_load_balance(trialcs));
1960 
1961 	spread_flag_changed = ((is_spread_slab(cs) != is_spread_slab(trialcs))
1962 			|| (is_spread_page(cs) != is_spread_page(trialcs)));
1963 
1964 	spin_lock_irq(&callback_lock);
1965 	cs->flags = trialcs->flags;
1966 	spin_unlock_irq(&callback_lock);
1967 
1968 	if (!cpumask_empty(trialcs->cpus_allowed) && balance_flag_changed)
1969 		rebuild_sched_domains_locked();
1970 
1971 	if (spread_flag_changed)
1972 		update_tasks_flags(cs);
1973 out:
1974 	free_cpuset(trialcs);
1975 	return err;
1976 }
1977 
1978 /*
1979  * update_prstate - update partititon_root_state
1980  * cs: the cpuset to update
1981  * new_prs: new partition root state
1982  *
1983  * Call with cpuset_mutex held.
1984  */
1985 static int update_prstate(struct cpuset *cs, int new_prs)
1986 {
1987 	int err, old_prs = cs->partition_root_state;
1988 	struct cpuset *parent = parent_cs(cs);
1989 	struct tmpmasks tmpmask;
1990 
1991 	if (old_prs == new_prs)
1992 		return 0;
1993 
1994 	/*
1995 	 * Cannot force a partial or invalid partition root to a full
1996 	 * partition root.
1997 	 */
1998 	if (new_prs && (old_prs == PRS_ERROR))
1999 		return -EINVAL;
2000 
2001 	if (alloc_cpumasks(NULL, &tmpmask))
2002 		return -ENOMEM;
2003 
2004 	err = -EINVAL;
2005 	if (!old_prs) {
2006 		/*
2007 		 * Turning on partition root requires setting the
2008 		 * CS_CPU_EXCLUSIVE bit implicitly as well and cpus_allowed
2009 		 * cannot be NULL.
2010 		 */
2011 		if (cpumask_empty(cs->cpus_allowed))
2012 			goto out;
2013 
2014 		err = update_flag(CS_CPU_EXCLUSIVE, cs, 1);
2015 		if (err)
2016 			goto out;
2017 
2018 		err = update_parent_subparts_cpumask(cs, partcmd_enable,
2019 						     NULL, &tmpmask);
2020 		if (err) {
2021 			update_flag(CS_CPU_EXCLUSIVE, cs, 0);
2022 			goto out;
2023 		}
2024 	} else {
2025 		/*
2026 		 * Turning off partition root will clear the
2027 		 * CS_CPU_EXCLUSIVE bit.
2028 		 */
2029 		if (old_prs == PRS_ERROR) {
2030 			update_flag(CS_CPU_EXCLUSIVE, cs, 0);
2031 			err = 0;
2032 			goto out;
2033 		}
2034 
2035 		err = update_parent_subparts_cpumask(cs, partcmd_disable,
2036 						     NULL, &tmpmask);
2037 		if (err)
2038 			goto out;
2039 
2040 		/* Turning off CS_CPU_EXCLUSIVE will not return error */
2041 		update_flag(CS_CPU_EXCLUSIVE, cs, 0);
2042 	}
2043 
2044 	/*
2045 	 * Update cpumask of parent's tasks except when it is the top
2046 	 * cpuset as some system daemons cannot be mapped to other CPUs.
2047 	 */
2048 	if (parent != &top_cpuset)
2049 		update_tasks_cpumask(parent);
2050 
2051 	if (parent->child_ecpus_count)
2052 		update_sibling_cpumasks(parent, cs, &tmpmask);
2053 
2054 	rebuild_sched_domains_locked();
2055 out:
2056 	if (!err) {
2057 		spin_lock_irq(&callback_lock);
2058 		cs->partition_root_state = new_prs;
2059 		spin_unlock_irq(&callback_lock);
2060 		notify_partition_change(cs, old_prs, new_prs);
2061 	}
2062 
2063 	free_cpumasks(NULL, &tmpmask);
2064 	return err;
2065 }
2066 
2067 /*
2068  * Frequency meter - How fast is some event occurring?
2069  *
2070  * These routines manage a digitally filtered, constant time based,
2071  * event frequency meter.  There are four routines:
2072  *   fmeter_init() - initialize a frequency meter.
2073  *   fmeter_markevent() - called each time the event happens.
2074  *   fmeter_getrate() - returns the recent rate of such events.
2075  *   fmeter_update() - internal routine used to update fmeter.
2076  *
2077  * A common data structure is passed to each of these routines,
2078  * which is used to keep track of the state required to manage the
2079  * frequency meter and its digital filter.
2080  *
2081  * The filter works on the number of events marked per unit time.
2082  * The filter is single-pole low-pass recursive (IIR).  The time unit
2083  * is 1 second.  Arithmetic is done using 32-bit integers scaled to
2084  * simulate 3 decimal digits of precision (multiplied by 1000).
2085  *
2086  * With an FM_COEF of 933, and a time base of 1 second, the filter
2087  * has a half-life of 10 seconds, meaning that if the events quit
2088  * happening, then the rate returned from the fmeter_getrate()
2089  * will be cut in half each 10 seconds, until it converges to zero.
2090  *
2091  * It is not worth doing a real infinitely recursive filter.  If more
2092  * than FM_MAXTICKS ticks have elapsed since the last filter event,
2093  * just compute FM_MAXTICKS ticks worth, by which point the level
2094  * will be stable.
2095  *
2096  * Limit the count of unprocessed events to FM_MAXCNT, so as to avoid
2097  * arithmetic overflow in the fmeter_update() routine.
2098  *
2099  * Given the simple 32 bit integer arithmetic used, this meter works
2100  * best for reporting rates between one per millisecond (msec) and
2101  * one per 32 (approx) seconds.  At constant rates faster than one
2102  * per msec it maxes out at values just under 1,000,000.  At constant
2103  * rates between one per msec, and one per second it will stabilize
2104  * to a value N*1000, where N is the rate of events per second.
2105  * At constant rates between one per second and one per 32 seconds,
2106  * it will be choppy, moving up on the seconds that have an event,
2107  * and then decaying until the next event.  At rates slower than
2108  * about one in 32 seconds, it decays all the way back to zero between
2109  * each event.
2110  */
2111 
2112 #define FM_COEF 933		/* coefficient for half-life of 10 secs */
2113 #define FM_MAXTICKS ((u32)99)   /* useless computing more ticks than this */
2114 #define FM_MAXCNT 1000000	/* limit cnt to avoid overflow */
2115 #define FM_SCALE 1000		/* faux fixed point scale */
2116 
2117 /* Initialize a frequency meter */
2118 static void fmeter_init(struct fmeter *fmp)
2119 {
2120 	fmp->cnt = 0;
2121 	fmp->val = 0;
2122 	fmp->time = 0;
2123 	spin_lock_init(&fmp->lock);
2124 }
2125 
2126 /* Internal meter update - process cnt events and update value */
2127 static void fmeter_update(struct fmeter *fmp)
2128 {
2129 	time64_t now;
2130 	u32 ticks;
2131 
2132 	now = ktime_get_seconds();
2133 	ticks = now - fmp->time;
2134 
2135 	if (ticks == 0)
2136 		return;
2137 
2138 	ticks = min(FM_MAXTICKS, ticks);
2139 	while (ticks-- > 0)
2140 		fmp->val = (FM_COEF * fmp->val) / FM_SCALE;
2141 	fmp->time = now;
2142 
2143 	fmp->val += ((FM_SCALE - FM_COEF) * fmp->cnt) / FM_SCALE;
2144 	fmp->cnt = 0;
2145 }
2146 
2147 /* Process any previous ticks, then bump cnt by one (times scale). */
2148 static void fmeter_markevent(struct fmeter *fmp)
2149 {
2150 	spin_lock(&fmp->lock);
2151 	fmeter_update(fmp);
2152 	fmp->cnt = min(FM_MAXCNT, fmp->cnt + FM_SCALE);
2153 	spin_unlock(&fmp->lock);
2154 }
2155 
2156 /* Process any previous ticks, then return current value. */
2157 static int fmeter_getrate(struct fmeter *fmp)
2158 {
2159 	int val;
2160 
2161 	spin_lock(&fmp->lock);
2162 	fmeter_update(fmp);
2163 	val = fmp->val;
2164 	spin_unlock(&fmp->lock);
2165 	return val;
2166 }
2167 
2168 static struct cpuset *cpuset_attach_old_cs;
2169 
2170 /* Called by cgroups to determine if a cpuset is usable; cpuset_mutex held */
2171 static int cpuset_can_attach(struct cgroup_taskset *tset)
2172 {
2173 	struct cgroup_subsys_state *css;
2174 	struct cpuset *cs;
2175 	struct task_struct *task;
2176 	int ret;
2177 
2178 	/* used later by cpuset_attach() */
2179 	cpuset_attach_old_cs = task_cs(cgroup_taskset_first(tset, &css));
2180 	cs = css_cs(css);
2181 
2182 	percpu_down_write(&cpuset_rwsem);
2183 
2184 	/* allow moving tasks into an empty cpuset if on default hierarchy */
2185 	ret = -ENOSPC;
2186 	if (!is_in_v2_mode() &&
2187 	    (cpumask_empty(cs->cpus_allowed) || nodes_empty(cs->mems_allowed)))
2188 		goto out_unlock;
2189 
2190 	cgroup_taskset_for_each(task, css, tset) {
2191 		ret = task_can_attach(task, cs->cpus_allowed);
2192 		if (ret)
2193 			goto out_unlock;
2194 		ret = security_task_setscheduler(task);
2195 		if (ret)
2196 			goto out_unlock;
2197 	}
2198 
2199 	/*
2200 	 * Mark attach is in progress.  This makes validate_change() fail
2201 	 * changes which zero cpus/mems_allowed.
2202 	 */
2203 	cs->attach_in_progress++;
2204 	ret = 0;
2205 out_unlock:
2206 	percpu_up_write(&cpuset_rwsem);
2207 	return ret;
2208 }
2209 
2210 static void cpuset_cancel_attach(struct cgroup_taskset *tset)
2211 {
2212 	struct cgroup_subsys_state *css;
2213 
2214 	cgroup_taskset_first(tset, &css);
2215 
2216 	percpu_down_write(&cpuset_rwsem);
2217 	css_cs(css)->attach_in_progress--;
2218 	percpu_up_write(&cpuset_rwsem);
2219 }
2220 
2221 /*
2222  * Protected by cpuset_mutex.  cpus_attach is used only by cpuset_attach()
2223  * but we can't allocate it dynamically there.  Define it global and
2224  * allocate from cpuset_init().
2225  */
2226 static cpumask_var_t cpus_attach;
2227 
2228 static void cpuset_attach(struct cgroup_taskset *tset)
2229 {
2230 	/* static buf protected by cpuset_mutex */
2231 	static nodemask_t cpuset_attach_nodemask_to;
2232 	struct task_struct *task;
2233 	struct task_struct *leader;
2234 	struct cgroup_subsys_state *css;
2235 	struct cpuset *cs;
2236 	struct cpuset *oldcs = cpuset_attach_old_cs;
2237 
2238 	cgroup_taskset_first(tset, &css);
2239 	cs = css_cs(css);
2240 
2241 	percpu_down_write(&cpuset_rwsem);
2242 
2243 	guarantee_online_mems(cs, &cpuset_attach_nodemask_to);
2244 
2245 	cgroup_taskset_for_each(task, css, tset) {
2246 		if (cs != &top_cpuset)
2247 			guarantee_online_cpus(task, cpus_attach);
2248 		else
2249 			cpumask_copy(cpus_attach, task_cpu_possible_mask(task));
2250 		/*
2251 		 * can_attach beforehand should guarantee that this doesn't
2252 		 * fail.  TODO: have a better way to handle failure here
2253 		 */
2254 		WARN_ON_ONCE(set_cpus_allowed_ptr(task, cpus_attach));
2255 
2256 		cpuset_change_task_nodemask(task, &cpuset_attach_nodemask_to);
2257 		cpuset_update_task_spread_flag(cs, task);
2258 	}
2259 
2260 	/*
2261 	 * Change mm for all threadgroup leaders. This is expensive and may
2262 	 * sleep and should be moved outside migration path proper.
2263 	 */
2264 	cpuset_attach_nodemask_to = cs->effective_mems;
2265 	cgroup_taskset_for_each_leader(leader, css, tset) {
2266 		struct mm_struct *mm = get_task_mm(leader);
2267 
2268 		if (mm) {
2269 			mpol_rebind_mm(mm, &cpuset_attach_nodemask_to);
2270 
2271 			/*
2272 			 * old_mems_allowed is the same with mems_allowed
2273 			 * here, except if this task is being moved
2274 			 * automatically due to hotplug.  In that case
2275 			 * @mems_allowed has been updated and is empty, so
2276 			 * @old_mems_allowed is the right nodesets that we
2277 			 * migrate mm from.
2278 			 */
2279 			if (is_memory_migrate(cs))
2280 				cpuset_migrate_mm(mm, &oldcs->old_mems_allowed,
2281 						  &cpuset_attach_nodemask_to);
2282 			else
2283 				mmput(mm);
2284 		}
2285 	}
2286 
2287 	cs->old_mems_allowed = cpuset_attach_nodemask_to;
2288 
2289 	cs->attach_in_progress--;
2290 	if (!cs->attach_in_progress)
2291 		wake_up(&cpuset_attach_wq);
2292 
2293 	percpu_up_write(&cpuset_rwsem);
2294 }
2295 
2296 /* The various types of files and directories in a cpuset file system */
2297 
2298 typedef enum {
2299 	FILE_MEMORY_MIGRATE,
2300 	FILE_CPULIST,
2301 	FILE_MEMLIST,
2302 	FILE_EFFECTIVE_CPULIST,
2303 	FILE_EFFECTIVE_MEMLIST,
2304 	FILE_SUBPARTS_CPULIST,
2305 	FILE_CPU_EXCLUSIVE,
2306 	FILE_MEM_EXCLUSIVE,
2307 	FILE_MEM_HARDWALL,
2308 	FILE_SCHED_LOAD_BALANCE,
2309 	FILE_PARTITION_ROOT,
2310 	FILE_SCHED_RELAX_DOMAIN_LEVEL,
2311 	FILE_MEMORY_PRESSURE_ENABLED,
2312 	FILE_MEMORY_PRESSURE,
2313 	FILE_SPREAD_PAGE,
2314 	FILE_SPREAD_SLAB,
2315 } cpuset_filetype_t;
2316 
2317 static int cpuset_write_u64(struct cgroup_subsys_state *css, struct cftype *cft,
2318 			    u64 val)
2319 {
2320 	struct cpuset *cs = css_cs(css);
2321 	cpuset_filetype_t type = cft->private;
2322 	int retval = 0;
2323 
2324 	cpus_read_lock();
2325 	percpu_down_write(&cpuset_rwsem);
2326 	if (!is_cpuset_online(cs)) {
2327 		retval = -ENODEV;
2328 		goto out_unlock;
2329 	}
2330 
2331 	switch (type) {
2332 	case FILE_CPU_EXCLUSIVE:
2333 		retval = update_flag(CS_CPU_EXCLUSIVE, cs, val);
2334 		break;
2335 	case FILE_MEM_EXCLUSIVE:
2336 		retval = update_flag(CS_MEM_EXCLUSIVE, cs, val);
2337 		break;
2338 	case FILE_MEM_HARDWALL:
2339 		retval = update_flag(CS_MEM_HARDWALL, cs, val);
2340 		break;
2341 	case FILE_SCHED_LOAD_BALANCE:
2342 		retval = update_flag(CS_SCHED_LOAD_BALANCE, cs, val);
2343 		break;
2344 	case FILE_MEMORY_MIGRATE:
2345 		retval = update_flag(CS_MEMORY_MIGRATE, cs, val);
2346 		break;
2347 	case FILE_MEMORY_PRESSURE_ENABLED:
2348 		cpuset_memory_pressure_enabled = !!val;
2349 		break;
2350 	case FILE_SPREAD_PAGE:
2351 		retval = update_flag(CS_SPREAD_PAGE, cs, val);
2352 		break;
2353 	case FILE_SPREAD_SLAB:
2354 		retval = update_flag(CS_SPREAD_SLAB, cs, val);
2355 		break;
2356 	default:
2357 		retval = -EINVAL;
2358 		break;
2359 	}
2360 out_unlock:
2361 	percpu_up_write(&cpuset_rwsem);
2362 	cpus_read_unlock();
2363 	return retval;
2364 }
2365 
2366 static int cpuset_write_s64(struct cgroup_subsys_state *css, struct cftype *cft,
2367 			    s64 val)
2368 {
2369 	struct cpuset *cs = css_cs(css);
2370 	cpuset_filetype_t type = cft->private;
2371 	int retval = -ENODEV;
2372 
2373 	cpus_read_lock();
2374 	percpu_down_write(&cpuset_rwsem);
2375 	if (!is_cpuset_online(cs))
2376 		goto out_unlock;
2377 
2378 	switch (type) {
2379 	case FILE_SCHED_RELAX_DOMAIN_LEVEL:
2380 		retval = update_relax_domain_level(cs, val);
2381 		break;
2382 	default:
2383 		retval = -EINVAL;
2384 		break;
2385 	}
2386 out_unlock:
2387 	percpu_up_write(&cpuset_rwsem);
2388 	cpus_read_unlock();
2389 	return retval;
2390 }
2391 
2392 /*
2393  * Common handling for a write to a "cpus" or "mems" file.
2394  */
2395 static ssize_t cpuset_write_resmask(struct kernfs_open_file *of,
2396 				    char *buf, size_t nbytes, loff_t off)
2397 {
2398 	struct cpuset *cs = css_cs(of_css(of));
2399 	struct cpuset *trialcs;
2400 	int retval = -ENODEV;
2401 
2402 	buf = strstrip(buf);
2403 
2404 	/*
2405 	 * CPU or memory hotunplug may leave @cs w/o any execution
2406 	 * resources, in which case the hotplug code asynchronously updates
2407 	 * configuration and transfers all tasks to the nearest ancestor
2408 	 * which can execute.
2409 	 *
2410 	 * As writes to "cpus" or "mems" may restore @cs's execution
2411 	 * resources, wait for the previously scheduled operations before
2412 	 * proceeding, so that we don't end up keep removing tasks added
2413 	 * after execution capability is restored.
2414 	 *
2415 	 * cpuset_hotplug_work calls back into cgroup core via
2416 	 * cgroup_transfer_tasks() and waiting for it from a cgroupfs
2417 	 * operation like this one can lead to a deadlock through kernfs
2418 	 * active_ref protection.  Let's break the protection.  Losing the
2419 	 * protection is okay as we check whether @cs is online after
2420 	 * grabbing cpuset_mutex anyway.  This only happens on the legacy
2421 	 * hierarchies.
2422 	 */
2423 	css_get(&cs->css);
2424 	kernfs_break_active_protection(of->kn);
2425 	flush_work(&cpuset_hotplug_work);
2426 
2427 	cpus_read_lock();
2428 	percpu_down_write(&cpuset_rwsem);
2429 	if (!is_cpuset_online(cs))
2430 		goto out_unlock;
2431 
2432 	trialcs = alloc_trial_cpuset(cs);
2433 	if (!trialcs) {
2434 		retval = -ENOMEM;
2435 		goto out_unlock;
2436 	}
2437 
2438 	switch (of_cft(of)->private) {
2439 	case FILE_CPULIST:
2440 		retval = update_cpumask(cs, trialcs, buf);
2441 		break;
2442 	case FILE_MEMLIST:
2443 		retval = update_nodemask(cs, trialcs, buf);
2444 		break;
2445 	default:
2446 		retval = -EINVAL;
2447 		break;
2448 	}
2449 
2450 	free_cpuset(trialcs);
2451 out_unlock:
2452 	percpu_up_write(&cpuset_rwsem);
2453 	cpus_read_unlock();
2454 	kernfs_unbreak_active_protection(of->kn);
2455 	css_put(&cs->css);
2456 	flush_workqueue(cpuset_migrate_mm_wq);
2457 	return retval ?: nbytes;
2458 }
2459 
2460 /*
2461  * These ascii lists should be read in a single call, by using a user
2462  * buffer large enough to hold the entire map.  If read in smaller
2463  * chunks, there is no guarantee of atomicity.  Since the display format
2464  * used, list of ranges of sequential numbers, is variable length,
2465  * and since these maps can change value dynamically, one could read
2466  * gibberish by doing partial reads while a list was changing.
2467  */
2468 static int cpuset_common_seq_show(struct seq_file *sf, void *v)
2469 {
2470 	struct cpuset *cs = css_cs(seq_css(sf));
2471 	cpuset_filetype_t type = seq_cft(sf)->private;
2472 	int ret = 0;
2473 
2474 	spin_lock_irq(&callback_lock);
2475 
2476 	switch (type) {
2477 	case FILE_CPULIST:
2478 		seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->cpus_allowed));
2479 		break;
2480 	case FILE_MEMLIST:
2481 		seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->mems_allowed));
2482 		break;
2483 	case FILE_EFFECTIVE_CPULIST:
2484 		seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->effective_cpus));
2485 		break;
2486 	case FILE_EFFECTIVE_MEMLIST:
2487 		seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->effective_mems));
2488 		break;
2489 	case FILE_SUBPARTS_CPULIST:
2490 		seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->subparts_cpus));
2491 		break;
2492 	default:
2493 		ret = -EINVAL;
2494 	}
2495 
2496 	spin_unlock_irq(&callback_lock);
2497 	return ret;
2498 }
2499 
2500 static u64 cpuset_read_u64(struct cgroup_subsys_state *css, struct cftype *cft)
2501 {
2502 	struct cpuset *cs = css_cs(css);
2503 	cpuset_filetype_t type = cft->private;
2504 	switch (type) {
2505 	case FILE_CPU_EXCLUSIVE:
2506 		return is_cpu_exclusive(cs);
2507 	case FILE_MEM_EXCLUSIVE:
2508 		return is_mem_exclusive(cs);
2509 	case FILE_MEM_HARDWALL:
2510 		return is_mem_hardwall(cs);
2511 	case FILE_SCHED_LOAD_BALANCE:
2512 		return is_sched_load_balance(cs);
2513 	case FILE_MEMORY_MIGRATE:
2514 		return is_memory_migrate(cs);
2515 	case FILE_MEMORY_PRESSURE_ENABLED:
2516 		return cpuset_memory_pressure_enabled;
2517 	case FILE_MEMORY_PRESSURE:
2518 		return fmeter_getrate(&cs->fmeter);
2519 	case FILE_SPREAD_PAGE:
2520 		return is_spread_page(cs);
2521 	case FILE_SPREAD_SLAB:
2522 		return is_spread_slab(cs);
2523 	default:
2524 		BUG();
2525 	}
2526 
2527 	/* Unreachable but makes gcc happy */
2528 	return 0;
2529 }
2530 
2531 static s64 cpuset_read_s64(struct cgroup_subsys_state *css, struct cftype *cft)
2532 {
2533 	struct cpuset *cs = css_cs(css);
2534 	cpuset_filetype_t type = cft->private;
2535 	switch (type) {
2536 	case FILE_SCHED_RELAX_DOMAIN_LEVEL:
2537 		return cs->relax_domain_level;
2538 	default:
2539 		BUG();
2540 	}
2541 
2542 	/* Unreachable but makes gcc happy */
2543 	return 0;
2544 }
2545 
2546 static int sched_partition_show(struct seq_file *seq, void *v)
2547 {
2548 	struct cpuset *cs = css_cs(seq_css(seq));
2549 
2550 	switch (cs->partition_root_state) {
2551 	case PRS_ENABLED:
2552 		seq_puts(seq, "root\n");
2553 		break;
2554 	case PRS_DISABLED:
2555 		seq_puts(seq, "member\n");
2556 		break;
2557 	case PRS_ERROR:
2558 		seq_puts(seq, "root invalid\n");
2559 		break;
2560 	}
2561 	return 0;
2562 }
2563 
2564 static ssize_t sched_partition_write(struct kernfs_open_file *of, char *buf,
2565 				     size_t nbytes, loff_t off)
2566 {
2567 	struct cpuset *cs = css_cs(of_css(of));
2568 	int val;
2569 	int retval = -ENODEV;
2570 
2571 	buf = strstrip(buf);
2572 
2573 	/*
2574 	 * Convert "root" to ENABLED, and convert "member" to DISABLED.
2575 	 */
2576 	if (!strcmp(buf, "root"))
2577 		val = PRS_ENABLED;
2578 	else if (!strcmp(buf, "member"))
2579 		val = PRS_DISABLED;
2580 	else
2581 		return -EINVAL;
2582 
2583 	css_get(&cs->css);
2584 	cpus_read_lock();
2585 	percpu_down_write(&cpuset_rwsem);
2586 	if (!is_cpuset_online(cs))
2587 		goto out_unlock;
2588 
2589 	retval = update_prstate(cs, val);
2590 out_unlock:
2591 	percpu_up_write(&cpuset_rwsem);
2592 	cpus_read_unlock();
2593 	css_put(&cs->css);
2594 	return retval ?: nbytes;
2595 }
2596 
2597 /*
2598  * for the common functions, 'private' gives the type of file
2599  */
2600 
2601 static struct cftype legacy_files[] = {
2602 	{
2603 		.name = "cpus",
2604 		.seq_show = cpuset_common_seq_show,
2605 		.write = cpuset_write_resmask,
2606 		.max_write_len = (100U + 6 * NR_CPUS),
2607 		.private = FILE_CPULIST,
2608 	},
2609 
2610 	{
2611 		.name = "mems",
2612 		.seq_show = cpuset_common_seq_show,
2613 		.write = cpuset_write_resmask,
2614 		.max_write_len = (100U + 6 * MAX_NUMNODES),
2615 		.private = FILE_MEMLIST,
2616 	},
2617 
2618 	{
2619 		.name = "effective_cpus",
2620 		.seq_show = cpuset_common_seq_show,
2621 		.private = FILE_EFFECTIVE_CPULIST,
2622 	},
2623 
2624 	{
2625 		.name = "effective_mems",
2626 		.seq_show = cpuset_common_seq_show,
2627 		.private = FILE_EFFECTIVE_MEMLIST,
2628 	},
2629 
2630 	{
2631 		.name = "cpu_exclusive",
2632 		.read_u64 = cpuset_read_u64,
2633 		.write_u64 = cpuset_write_u64,
2634 		.private = FILE_CPU_EXCLUSIVE,
2635 	},
2636 
2637 	{
2638 		.name = "mem_exclusive",
2639 		.read_u64 = cpuset_read_u64,
2640 		.write_u64 = cpuset_write_u64,
2641 		.private = FILE_MEM_EXCLUSIVE,
2642 	},
2643 
2644 	{
2645 		.name = "mem_hardwall",
2646 		.read_u64 = cpuset_read_u64,
2647 		.write_u64 = cpuset_write_u64,
2648 		.private = FILE_MEM_HARDWALL,
2649 	},
2650 
2651 	{
2652 		.name = "sched_load_balance",
2653 		.read_u64 = cpuset_read_u64,
2654 		.write_u64 = cpuset_write_u64,
2655 		.private = FILE_SCHED_LOAD_BALANCE,
2656 	},
2657 
2658 	{
2659 		.name = "sched_relax_domain_level",
2660 		.read_s64 = cpuset_read_s64,
2661 		.write_s64 = cpuset_write_s64,
2662 		.private = FILE_SCHED_RELAX_DOMAIN_LEVEL,
2663 	},
2664 
2665 	{
2666 		.name = "memory_migrate",
2667 		.read_u64 = cpuset_read_u64,
2668 		.write_u64 = cpuset_write_u64,
2669 		.private = FILE_MEMORY_MIGRATE,
2670 	},
2671 
2672 	{
2673 		.name = "memory_pressure",
2674 		.read_u64 = cpuset_read_u64,
2675 		.private = FILE_MEMORY_PRESSURE,
2676 	},
2677 
2678 	{
2679 		.name = "memory_spread_page",
2680 		.read_u64 = cpuset_read_u64,
2681 		.write_u64 = cpuset_write_u64,
2682 		.private = FILE_SPREAD_PAGE,
2683 	},
2684 
2685 	{
2686 		.name = "memory_spread_slab",
2687 		.read_u64 = cpuset_read_u64,
2688 		.write_u64 = cpuset_write_u64,
2689 		.private = FILE_SPREAD_SLAB,
2690 	},
2691 
2692 	{
2693 		.name = "memory_pressure_enabled",
2694 		.flags = CFTYPE_ONLY_ON_ROOT,
2695 		.read_u64 = cpuset_read_u64,
2696 		.write_u64 = cpuset_write_u64,
2697 		.private = FILE_MEMORY_PRESSURE_ENABLED,
2698 	},
2699 
2700 	{ }	/* terminate */
2701 };
2702 
2703 /*
2704  * This is currently a minimal set for the default hierarchy. It can be
2705  * expanded later on by migrating more features and control files from v1.
2706  */
2707 static struct cftype dfl_files[] = {
2708 	{
2709 		.name = "cpus",
2710 		.seq_show = cpuset_common_seq_show,
2711 		.write = cpuset_write_resmask,
2712 		.max_write_len = (100U + 6 * NR_CPUS),
2713 		.private = FILE_CPULIST,
2714 		.flags = CFTYPE_NOT_ON_ROOT,
2715 	},
2716 
2717 	{
2718 		.name = "mems",
2719 		.seq_show = cpuset_common_seq_show,
2720 		.write = cpuset_write_resmask,
2721 		.max_write_len = (100U + 6 * MAX_NUMNODES),
2722 		.private = FILE_MEMLIST,
2723 		.flags = CFTYPE_NOT_ON_ROOT,
2724 	},
2725 
2726 	{
2727 		.name = "cpus.effective",
2728 		.seq_show = cpuset_common_seq_show,
2729 		.private = FILE_EFFECTIVE_CPULIST,
2730 	},
2731 
2732 	{
2733 		.name = "mems.effective",
2734 		.seq_show = cpuset_common_seq_show,
2735 		.private = FILE_EFFECTIVE_MEMLIST,
2736 	},
2737 
2738 	{
2739 		.name = "cpus.partition",
2740 		.seq_show = sched_partition_show,
2741 		.write = sched_partition_write,
2742 		.private = FILE_PARTITION_ROOT,
2743 		.flags = CFTYPE_NOT_ON_ROOT,
2744 		.file_offset = offsetof(struct cpuset, partition_file),
2745 	},
2746 
2747 	{
2748 		.name = "cpus.subpartitions",
2749 		.seq_show = cpuset_common_seq_show,
2750 		.private = FILE_SUBPARTS_CPULIST,
2751 		.flags = CFTYPE_DEBUG,
2752 	},
2753 
2754 	{ }	/* terminate */
2755 };
2756 
2757 
2758 /*
2759  *	cpuset_css_alloc - allocate a cpuset css
2760  *	cgrp:	control group that the new cpuset will be part of
2761  */
2762 
2763 static struct cgroup_subsys_state *
2764 cpuset_css_alloc(struct cgroup_subsys_state *parent_css)
2765 {
2766 	struct cpuset *cs;
2767 
2768 	if (!parent_css)
2769 		return &top_cpuset.css;
2770 
2771 	cs = kzalloc(sizeof(*cs), GFP_KERNEL);
2772 	if (!cs)
2773 		return ERR_PTR(-ENOMEM);
2774 
2775 	if (alloc_cpumasks(cs, NULL)) {
2776 		kfree(cs);
2777 		return ERR_PTR(-ENOMEM);
2778 	}
2779 
2780 	__set_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
2781 	nodes_clear(cs->mems_allowed);
2782 	nodes_clear(cs->effective_mems);
2783 	fmeter_init(&cs->fmeter);
2784 	cs->relax_domain_level = -1;
2785 
2786 	/* Set CS_MEMORY_MIGRATE for default hierarchy */
2787 	if (cgroup_subsys_on_dfl(cpuset_cgrp_subsys))
2788 		__set_bit(CS_MEMORY_MIGRATE, &cs->flags);
2789 
2790 	return &cs->css;
2791 }
2792 
2793 static int cpuset_css_online(struct cgroup_subsys_state *css)
2794 {
2795 	struct cpuset *cs = css_cs(css);
2796 	struct cpuset *parent = parent_cs(cs);
2797 	struct cpuset *tmp_cs;
2798 	struct cgroup_subsys_state *pos_css;
2799 
2800 	if (!parent)
2801 		return 0;
2802 
2803 	cpus_read_lock();
2804 	percpu_down_write(&cpuset_rwsem);
2805 
2806 	set_bit(CS_ONLINE, &cs->flags);
2807 	if (is_spread_page(parent))
2808 		set_bit(CS_SPREAD_PAGE, &cs->flags);
2809 	if (is_spread_slab(parent))
2810 		set_bit(CS_SPREAD_SLAB, &cs->flags);
2811 
2812 	cpuset_inc();
2813 
2814 	spin_lock_irq(&callback_lock);
2815 	if (is_in_v2_mode()) {
2816 		cpumask_copy(cs->effective_cpus, parent->effective_cpus);
2817 		cs->effective_mems = parent->effective_mems;
2818 		cs->use_parent_ecpus = true;
2819 		parent->child_ecpus_count++;
2820 	}
2821 	spin_unlock_irq(&callback_lock);
2822 
2823 	if (!test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags))
2824 		goto out_unlock;
2825 
2826 	/*
2827 	 * Clone @parent's configuration if CGRP_CPUSET_CLONE_CHILDREN is
2828 	 * set.  This flag handling is implemented in cgroup core for
2829 	 * histrical reasons - the flag may be specified during mount.
2830 	 *
2831 	 * Currently, if any sibling cpusets have exclusive cpus or mem, we
2832 	 * refuse to clone the configuration - thereby refusing the task to
2833 	 * be entered, and as a result refusing the sys_unshare() or
2834 	 * clone() which initiated it.  If this becomes a problem for some
2835 	 * users who wish to allow that scenario, then this could be
2836 	 * changed to grant parent->cpus_allowed-sibling_cpus_exclusive
2837 	 * (and likewise for mems) to the new cgroup.
2838 	 */
2839 	rcu_read_lock();
2840 	cpuset_for_each_child(tmp_cs, pos_css, parent) {
2841 		if (is_mem_exclusive(tmp_cs) || is_cpu_exclusive(tmp_cs)) {
2842 			rcu_read_unlock();
2843 			goto out_unlock;
2844 		}
2845 	}
2846 	rcu_read_unlock();
2847 
2848 	spin_lock_irq(&callback_lock);
2849 	cs->mems_allowed = parent->mems_allowed;
2850 	cs->effective_mems = parent->mems_allowed;
2851 	cpumask_copy(cs->cpus_allowed, parent->cpus_allowed);
2852 	cpumask_copy(cs->effective_cpus, parent->cpus_allowed);
2853 	spin_unlock_irq(&callback_lock);
2854 out_unlock:
2855 	percpu_up_write(&cpuset_rwsem);
2856 	cpus_read_unlock();
2857 	return 0;
2858 }
2859 
2860 /*
2861  * If the cpuset being removed has its flag 'sched_load_balance'
2862  * enabled, then simulate turning sched_load_balance off, which
2863  * will call rebuild_sched_domains_locked(). That is not needed
2864  * in the default hierarchy where only changes in partition
2865  * will cause repartitioning.
2866  *
2867  * If the cpuset has the 'sched.partition' flag enabled, simulate
2868  * turning 'sched.partition" off.
2869  */
2870 
2871 static void cpuset_css_offline(struct cgroup_subsys_state *css)
2872 {
2873 	struct cpuset *cs = css_cs(css);
2874 
2875 	cpus_read_lock();
2876 	percpu_down_write(&cpuset_rwsem);
2877 
2878 	if (is_partition_root(cs))
2879 		update_prstate(cs, 0);
2880 
2881 	if (!cgroup_subsys_on_dfl(cpuset_cgrp_subsys) &&
2882 	    is_sched_load_balance(cs))
2883 		update_flag(CS_SCHED_LOAD_BALANCE, cs, 0);
2884 
2885 	if (cs->use_parent_ecpus) {
2886 		struct cpuset *parent = parent_cs(cs);
2887 
2888 		cs->use_parent_ecpus = false;
2889 		parent->child_ecpus_count--;
2890 	}
2891 
2892 	cpuset_dec();
2893 	clear_bit(CS_ONLINE, &cs->flags);
2894 
2895 	percpu_up_write(&cpuset_rwsem);
2896 	cpus_read_unlock();
2897 }
2898 
2899 static void cpuset_css_free(struct cgroup_subsys_state *css)
2900 {
2901 	struct cpuset *cs = css_cs(css);
2902 
2903 	free_cpuset(cs);
2904 }
2905 
2906 static void cpuset_bind(struct cgroup_subsys_state *root_css)
2907 {
2908 	percpu_down_write(&cpuset_rwsem);
2909 	spin_lock_irq(&callback_lock);
2910 
2911 	if (is_in_v2_mode()) {
2912 		cpumask_copy(top_cpuset.cpus_allowed, cpu_possible_mask);
2913 		top_cpuset.mems_allowed = node_possible_map;
2914 	} else {
2915 		cpumask_copy(top_cpuset.cpus_allowed,
2916 			     top_cpuset.effective_cpus);
2917 		top_cpuset.mems_allowed = top_cpuset.effective_mems;
2918 	}
2919 
2920 	spin_unlock_irq(&callback_lock);
2921 	percpu_up_write(&cpuset_rwsem);
2922 }
2923 
2924 /*
2925  * Make sure the new task conform to the current state of its parent,
2926  * which could have been changed by cpuset just after it inherits the
2927  * state from the parent and before it sits on the cgroup's task list.
2928  */
2929 static void cpuset_fork(struct task_struct *task)
2930 {
2931 	if (task_css_is_root(task, cpuset_cgrp_id))
2932 		return;
2933 
2934 	set_cpus_allowed_ptr(task, current->cpus_ptr);
2935 	task->mems_allowed = current->mems_allowed;
2936 }
2937 
2938 struct cgroup_subsys cpuset_cgrp_subsys = {
2939 	.css_alloc	= cpuset_css_alloc,
2940 	.css_online	= cpuset_css_online,
2941 	.css_offline	= cpuset_css_offline,
2942 	.css_free	= cpuset_css_free,
2943 	.can_attach	= cpuset_can_attach,
2944 	.cancel_attach	= cpuset_cancel_attach,
2945 	.attach		= cpuset_attach,
2946 	.post_attach	= cpuset_post_attach,
2947 	.bind		= cpuset_bind,
2948 	.fork		= cpuset_fork,
2949 	.legacy_cftypes	= legacy_files,
2950 	.dfl_cftypes	= dfl_files,
2951 	.early_init	= true,
2952 	.threaded	= true,
2953 };
2954 
2955 /**
2956  * cpuset_init - initialize cpusets at system boot
2957  *
2958  * Description: Initialize top_cpuset
2959  **/
2960 
2961 int __init cpuset_init(void)
2962 {
2963 	BUG_ON(percpu_init_rwsem(&cpuset_rwsem));
2964 
2965 	BUG_ON(!alloc_cpumask_var(&top_cpuset.cpus_allowed, GFP_KERNEL));
2966 	BUG_ON(!alloc_cpumask_var(&top_cpuset.effective_cpus, GFP_KERNEL));
2967 	BUG_ON(!zalloc_cpumask_var(&top_cpuset.subparts_cpus, GFP_KERNEL));
2968 
2969 	cpumask_setall(top_cpuset.cpus_allowed);
2970 	nodes_setall(top_cpuset.mems_allowed);
2971 	cpumask_setall(top_cpuset.effective_cpus);
2972 	nodes_setall(top_cpuset.effective_mems);
2973 
2974 	fmeter_init(&top_cpuset.fmeter);
2975 	set_bit(CS_SCHED_LOAD_BALANCE, &top_cpuset.flags);
2976 	top_cpuset.relax_domain_level = -1;
2977 
2978 	BUG_ON(!alloc_cpumask_var(&cpus_attach, GFP_KERNEL));
2979 
2980 	return 0;
2981 }
2982 
2983 /*
2984  * If CPU and/or memory hotplug handlers, below, unplug any CPUs
2985  * or memory nodes, we need to walk over the cpuset hierarchy,
2986  * removing that CPU or node from all cpusets.  If this removes the
2987  * last CPU or node from a cpuset, then move the tasks in the empty
2988  * cpuset to its next-highest non-empty parent.
2989  */
2990 static void remove_tasks_in_empty_cpuset(struct cpuset *cs)
2991 {
2992 	struct cpuset *parent;
2993 
2994 	/*
2995 	 * Find its next-highest non-empty parent, (top cpuset
2996 	 * has online cpus, so can't be empty).
2997 	 */
2998 	parent = parent_cs(cs);
2999 	while (cpumask_empty(parent->cpus_allowed) ||
3000 			nodes_empty(parent->mems_allowed))
3001 		parent = parent_cs(parent);
3002 
3003 	if (cgroup_transfer_tasks(parent->css.cgroup, cs->css.cgroup)) {
3004 		pr_err("cpuset: failed to transfer tasks out of empty cpuset ");
3005 		pr_cont_cgroup_name(cs->css.cgroup);
3006 		pr_cont("\n");
3007 	}
3008 }
3009 
3010 static void
3011 hotplug_update_tasks_legacy(struct cpuset *cs,
3012 			    struct cpumask *new_cpus, nodemask_t *new_mems,
3013 			    bool cpus_updated, bool mems_updated)
3014 {
3015 	bool is_empty;
3016 
3017 	spin_lock_irq(&callback_lock);
3018 	cpumask_copy(cs->cpus_allowed, new_cpus);
3019 	cpumask_copy(cs->effective_cpus, new_cpus);
3020 	cs->mems_allowed = *new_mems;
3021 	cs->effective_mems = *new_mems;
3022 	spin_unlock_irq(&callback_lock);
3023 
3024 	/*
3025 	 * Don't call update_tasks_cpumask() if the cpuset becomes empty,
3026 	 * as the tasks will be migratecd to an ancestor.
3027 	 */
3028 	if (cpus_updated && !cpumask_empty(cs->cpus_allowed))
3029 		update_tasks_cpumask(cs);
3030 	if (mems_updated && !nodes_empty(cs->mems_allowed))
3031 		update_tasks_nodemask(cs);
3032 
3033 	is_empty = cpumask_empty(cs->cpus_allowed) ||
3034 		   nodes_empty(cs->mems_allowed);
3035 
3036 	percpu_up_write(&cpuset_rwsem);
3037 
3038 	/*
3039 	 * Move tasks to the nearest ancestor with execution resources,
3040 	 * This is full cgroup operation which will also call back into
3041 	 * cpuset. Should be done outside any lock.
3042 	 */
3043 	if (is_empty)
3044 		remove_tasks_in_empty_cpuset(cs);
3045 
3046 	percpu_down_write(&cpuset_rwsem);
3047 }
3048 
3049 static void
3050 hotplug_update_tasks(struct cpuset *cs,
3051 		     struct cpumask *new_cpus, nodemask_t *new_mems,
3052 		     bool cpus_updated, bool mems_updated)
3053 {
3054 	if (cpumask_empty(new_cpus))
3055 		cpumask_copy(new_cpus, parent_cs(cs)->effective_cpus);
3056 	if (nodes_empty(*new_mems))
3057 		*new_mems = parent_cs(cs)->effective_mems;
3058 
3059 	spin_lock_irq(&callback_lock);
3060 	cpumask_copy(cs->effective_cpus, new_cpus);
3061 	cs->effective_mems = *new_mems;
3062 	spin_unlock_irq(&callback_lock);
3063 
3064 	if (cpus_updated)
3065 		update_tasks_cpumask(cs);
3066 	if (mems_updated)
3067 		update_tasks_nodemask(cs);
3068 }
3069 
3070 static bool force_rebuild;
3071 
3072 void cpuset_force_rebuild(void)
3073 {
3074 	force_rebuild = true;
3075 }
3076 
3077 /**
3078  * cpuset_hotplug_update_tasks - update tasks in a cpuset for hotunplug
3079  * @cs: cpuset in interest
3080  * @tmp: the tmpmasks structure pointer
3081  *
3082  * Compare @cs's cpu and mem masks against top_cpuset and if some have gone
3083  * offline, update @cs accordingly.  If @cs ends up with no CPU or memory,
3084  * all its tasks are moved to the nearest ancestor with both resources.
3085  */
3086 static void cpuset_hotplug_update_tasks(struct cpuset *cs, struct tmpmasks *tmp)
3087 {
3088 	static cpumask_t new_cpus;
3089 	static nodemask_t new_mems;
3090 	bool cpus_updated;
3091 	bool mems_updated;
3092 	struct cpuset *parent;
3093 retry:
3094 	wait_event(cpuset_attach_wq, cs->attach_in_progress == 0);
3095 
3096 	percpu_down_write(&cpuset_rwsem);
3097 
3098 	/*
3099 	 * We have raced with task attaching. We wait until attaching
3100 	 * is finished, so we won't attach a task to an empty cpuset.
3101 	 */
3102 	if (cs->attach_in_progress) {
3103 		percpu_up_write(&cpuset_rwsem);
3104 		goto retry;
3105 	}
3106 
3107 	parent = parent_cs(cs);
3108 	compute_effective_cpumask(&new_cpus, cs, parent);
3109 	nodes_and(new_mems, cs->mems_allowed, parent->effective_mems);
3110 
3111 	if (cs->nr_subparts_cpus)
3112 		/*
3113 		 * Make sure that CPUs allocated to child partitions
3114 		 * do not show up in effective_cpus.
3115 		 */
3116 		cpumask_andnot(&new_cpus, &new_cpus, cs->subparts_cpus);
3117 
3118 	if (!tmp || !cs->partition_root_state)
3119 		goto update_tasks;
3120 
3121 	/*
3122 	 * In the unlikely event that a partition root has empty
3123 	 * effective_cpus or its parent becomes erroneous, we have to
3124 	 * transition it to the erroneous state.
3125 	 */
3126 	if (is_partition_root(cs) && (cpumask_empty(&new_cpus) ||
3127 	   (parent->partition_root_state == PRS_ERROR))) {
3128 		if (cs->nr_subparts_cpus) {
3129 			spin_lock_irq(&callback_lock);
3130 			cs->nr_subparts_cpus = 0;
3131 			cpumask_clear(cs->subparts_cpus);
3132 			spin_unlock_irq(&callback_lock);
3133 			compute_effective_cpumask(&new_cpus, cs, parent);
3134 		}
3135 
3136 		/*
3137 		 * If the effective_cpus is empty because the child
3138 		 * partitions take away all the CPUs, we can keep
3139 		 * the current partition and let the child partitions
3140 		 * fight for available CPUs.
3141 		 */
3142 		if ((parent->partition_root_state == PRS_ERROR) ||
3143 		     cpumask_empty(&new_cpus)) {
3144 			int old_prs;
3145 
3146 			update_parent_subparts_cpumask(cs, partcmd_disable,
3147 						       NULL, tmp);
3148 			old_prs = cs->partition_root_state;
3149 			if (old_prs != PRS_ERROR) {
3150 				spin_lock_irq(&callback_lock);
3151 				cs->partition_root_state = PRS_ERROR;
3152 				spin_unlock_irq(&callback_lock);
3153 				notify_partition_change(cs, old_prs, PRS_ERROR);
3154 			}
3155 		}
3156 		cpuset_force_rebuild();
3157 	}
3158 
3159 	/*
3160 	 * On the other hand, an erroneous partition root may be transitioned
3161 	 * back to a regular one or a partition root with no CPU allocated
3162 	 * from the parent may change to erroneous.
3163 	 */
3164 	if (is_partition_root(parent) &&
3165 	   ((cs->partition_root_state == PRS_ERROR) ||
3166 	    !cpumask_intersects(&new_cpus, parent->subparts_cpus)) &&
3167 	     update_parent_subparts_cpumask(cs, partcmd_update, NULL, tmp))
3168 		cpuset_force_rebuild();
3169 
3170 update_tasks:
3171 	cpus_updated = !cpumask_equal(&new_cpus, cs->effective_cpus);
3172 	mems_updated = !nodes_equal(new_mems, cs->effective_mems);
3173 
3174 	if (is_in_v2_mode())
3175 		hotplug_update_tasks(cs, &new_cpus, &new_mems,
3176 				     cpus_updated, mems_updated);
3177 	else
3178 		hotplug_update_tasks_legacy(cs, &new_cpus, &new_mems,
3179 					    cpus_updated, mems_updated);
3180 
3181 	percpu_up_write(&cpuset_rwsem);
3182 }
3183 
3184 /**
3185  * cpuset_hotplug_workfn - handle CPU/memory hotunplug for a cpuset
3186  *
3187  * This function is called after either CPU or memory configuration has
3188  * changed and updates cpuset accordingly.  The top_cpuset is always
3189  * synchronized to cpu_active_mask and N_MEMORY, which is necessary in
3190  * order to make cpusets transparent (of no affect) on systems that are
3191  * actively using CPU hotplug but making no active use of cpusets.
3192  *
3193  * Non-root cpusets are only affected by offlining.  If any CPUs or memory
3194  * nodes have been taken down, cpuset_hotplug_update_tasks() is invoked on
3195  * all descendants.
3196  *
3197  * Note that CPU offlining during suspend is ignored.  We don't modify
3198  * cpusets across suspend/resume cycles at all.
3199  */
3200 static void cpuset_hotplug_workfn(struct work_struct *work)
3201 {
3202 	static cpumask_t new_cpus;
3203 	static nodemask_t new_mems;
3204 	bool cpus_updated, mems_updated;
3205 	bool on_dfl = is_in_v2_mode();
3206 	struct tmpmasks tmp, *ptmp = NULL;
3207 
3208 	if (on_dfl && !alloc_cpumasks(NULL, &tmp))
3209 		ptmp = &tmp;
3210 
3211 	percpu_down_write(&cpuset_rwsem);
3212 
3213 	/* fetch the available cpus/mems and find out which changed how */
3214 	cpumask_copy(&new_cpus, cpu_active_mask);
3215 	new_mems = node_states[N_MEMORY];
3216 
3217 	/*
3218 	 * If subparts_cpus is populated, it is likely that the check below
3219 	 * will produce a false positive on cpus_updated when the cpu list
3220 	 * isn't changed. It is extra work, but it is better to be safe.
3221 	 */
3222 	cpus_updated = !cpumask_equal(top_cpuset.effective_cpus, &new_cpus);
3223 	mems_updated = !nodes_equal(top_cpuset.effective_mems, new_mems);
3224 
3225 	/*
3226 	 * In the rare case that hotplug removes all the cpus in subparts_cpus,
3227 	 * we assumed that cpus are updated.
3228 	 */
3229 	if (!cpus_updated && top_cpuset.nr_subparts_cpus)
3230 		cpus_updated = true;
3231 
3232 	/* synchronize cpus_allowed to cpu_active_mask */
3233 	if (cpus_updated) {
3234 		spin_lock_irq(&callback_lock);
3235 		if (!on_dfl)
3236 			cpumask_copy(top_cpuset.cpus_allowed, &new_cpus);
3237 		/*
3238 		 * Make sure that CPUs allocated to child partitions
3239 		 * do not show up in effective_cpus. If no CPU is left,
3240 		 * we clear the subparts_cpus & let the child partitions
3241 		 * fight for the CPUs again.
3242 		 */
3243 		if (top_cpuset.nr_subparts_cpus) {
3244 			if (cpumask_subset(&new_cpus,
3245 					   top_cpuset.subparts_cpus)) {
3246 				top_cpuset.nr_subparts_cpus = 0;
3247 				cpumask_clear(top_cpuset.subparts_cpus);
3248 			} else {
3249 				cpumask_andnot(&new_cpus, &new_cpus,
3250 					       top_cpuset.subparts_cpus);
3251 			}
3252 		}
3253 		cpumask_copy(top_cpuset.effective_cpus, &new_cpus);
3254 		spin_unlock_irq(&callback_lock);
3255 		/* we don't mess with cpumasks of tasks in top_cpuset */
3256 	}
3257 
3258 	/* synchronize mems_allowed to N_MEMORY */
3259 	if (mems_updated) {
3260 		spin_lock_irq(&callback_lock);
3261 		if (!on_dfl)
3262 			top_cpuset.mems_allowed = new_mems;
3263 		top_cpuset.effective_mems = new_mems;
3264 		spin_unlock_irq(&callback_lock);
3265 		update_tasks_nodemask(&top_cpuset);
3266 	}
3267 
3268 	percpu_up_write(&cpuset_rwsem);
3269 
3270 	/* if cpus or mems changed, we need to propagate to descendants */
3271 	if (cpus_updated || mems_updated) {
3272 		struct cpuset *cs;
3273 		struct cgroup_subsys_state *pos_css;
3274 
3275 		rcu_read_lock();
3276 		cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
3277 			if (cs == &top_cpuset || !css_tryget_online(&cs->css))
3278 				continue;
3279 			rcu_read_unlock();
3280 
3281 			cpuset_hotplug_update_tasks(cs, ptmp);
3282 
3283 			rcu_read_lock();
3284 			css_put(&cs->css);
3285 		}
3286 		rcu_read_unlock();
3287 	}
3288 
3289 	/* rebuild sched domains if cpus_allowed has changed */
3290 	if (cpus_updated || force_rebuild) {
3291 		force_rebuild = false;
3292 		rebuild_sched_domains();
3293 	}
3294 
3295 	free_cpumasks(NULL, ptmp);
3296 }
3297 
3298 void cpuset_update_active_cpus(void)
3299 {
3300 	/*
3301 	 * We're inside cpu hotplug critical region which usually nests
3302 	 * inside cgroup synchronization.  Bounce actual hotplug processing
3303 	 * to a work item to avoid reverse locking order.
3304 	 */
3305 	schedule_work(&cpuset_hotplug_work);
3306 }
3307 
3308 void cpuset_wait_for_hotplug(void)
3309 {
3310 	flush_work(&cpuset_hotplug_work);
3311 }
3312 
3313 /*
3314  * Keep top_cpuset.mems_allowed tracking node_states[N_MEMORY].
3315  * Call this routine anytime after node_states[N_MEMORY] changes.
3316  * See cpuset_update_active_cpus() for CPU hotplug handling.
3317  */
3318 static int cpuset_track_online_nodes(struct notifier_block *self,
3319 				unsigned long action, void *arg)
3320 {
3321 	schedule_work(&cpuset_hotplug_work);
3322 	return NOTIFY_OK;
3323 }
3324 
3325 static struct notifier_block cpuset_track_online_nodes_nb = {
3326 	.notifier_call = cpuset_track_online_nodes,
3327 	.priority = 10,		/* ??! */
3328 };
3329 
3330 /**
3331  * cpuset_init_smp - initialize cpus_allowed
3332  *
3333  * Description: Finish top cpuset after cpu, node maps are initialized
3334  */
3335 void __init cpuset_init_smp(void)
3336 {
3337 	cpumask_copy(top_cpuset.cpus_allowed, cpu_active_mask);
3338 	top_cpuset.mems_allowed = node_states[N_MEMORY];
3339 	top_cpuset.old_mems_allowed = top_cpuset.mems_allowed;
3340 
3341 	cpumask_copy(top_cpuset.effective_cpus, cpu_active_mask);
3342 	top_cpuset.effective_mems = node_states[N_MEMORY];
3343 
3344 	register_hotmemory_notifier(&cpuset_track_online_nodes_nb);
3345 
3346 	cpuset_migrate_mm_wq = alloc_ordered_workqueue("cpuset_migrate_mm", 0);
3347 	BUG_ON(!cpuset_migrate_mm_wq);
3348 }
3349 
3350 /**
3351  * cpuset_cpus_allowed - return cpus_allowed mask from a tasks cpuset.
3352  * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
3353  * @pmask: pointer to struct cpumask variable to receive cpus_allowed set.
3354  *
3355  * Description: Returns the cpumask_var_t cpus_allowed of the cpuset
3356  * attached to the specified @tsk.  Guaranteed to return some non-empty
3357  * subset of cpu_online_mask, even if this means going outside the
3358  * tasks cpuset.
3359  **/
3360 
3361 void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
3362 {
3363 	unsigned long flags;
3364 
3365 	spin_lock_irqsave(&callback_lock, flags);
3366 	guarantee_online_cpus(tsk, pmask);
3367 	spin_unlock_irqrestore(&callback_lock, flags);
3368 }
3369 
3370 /**
3371  * cpuset_cpus_allowed_fallback - final fallback before complete catastrophe.
3372  * @tsk: pointer to task_struct with which the scheduler is struggling
3373  *
3374  * Description: In the case that the scheduler cannot find an allowed cpu in
3375  * tsk->cpus_allowed, we fall back to task_cs(tsk)->cpus_allowed. In legacy
3376  * mode however, this value is the same as task_cs(tsk)->effective_cpus,
3377  * which will not contain a sane cpumask during cases such as cpu hotplugging.
3378  * This is the absolute last resort for the scheduler and it is only used if
3379  * _every_ other avenue has been traveled.
3380  *
3381  * Returns true if the affinity of @tsk was changed, false otherwise.
3382  **/
3383 
3384 bool cpuset_cpus_allowed_fallback(struct task_struct *tsk)
3385 {
3386 	const struct cpumask *possible_mask = task_cpu_possible_mask(tsk);
3387 	const struct cpumask *cs_mask;
3388 	bool changed = false;
3389 
3390 	rcu_read_lock();
3391 	cs_mask = task_cs(tsk)->cpus_allowed;
3392 	if (is_in_v2_mode() && cpumask_subset(cs_mask, possible_mask)) {
3393 		do_set_cpus_allowed(tsk, cs_mask);
3394 		changed = true;
3395 	}
3396 	rcu_read_unlock();
3397 
3398 	/*
3399 	 * We own tsk->cpus_allowed, nobody can change it under us.
3400 	 *
3401 	 * But we used cs && cs->cpus_allowed lockless and thus can
3402 	 * race with cgroup_attach_task() or update_cpumask() and get
3403 	 * the wrong tsk->cpus_allowed. However, both cases imply the
3404 	 * subsequent cpuset_change_cpumask()->set_cpus_allowed_ptr()
3405 	 * which takes task_rq_lock().
3406 	 *
3407 	 * If we are called after it dropped the lock we must see all
3408 	 * changes in tsk_cs()->cpus_allowed. Otherwise we can temporary
3409 	 * set any mask even if it is not right from task_cs() pov,
3410 	 * the pending set_cpus_allowed_ptr() will fix things.
3411 	 *
3412 	 * select_fallback_rq() will fix things ups and set cpu_possible_mask
3413 	 * if required.
3414 	 */
3415 	return changed;
3416 }
3417 
3418 void __init cpuset_init_current_mems_allowed(void)
3419 {
3420 	nodes_setall(current->mems_allowed);
3421 }
3422 
3423 /**
3424  * cpuset_mems_allowed - return mems_allowed mask from a tasks cpuset.
3425  * @tsk: pointer to task_struct from which to obtain cpuset->mems_allowed.
3426  *
3427  * Description: Returns the nodemask_t mems_allowed of the cpuset
3428  * attached to the specified @tsk.  Guaranteed to return some non-empty
3429  * subset of node_states[N_MEMORY], even if this means going outside the
3430  * tasks cpuset.
3431  **/
3432 
3433 nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
3434 {
3435 	nodemask_t mask;
3436 	unsigned long flags;
3437 
3438 	spin_lock_irqsave(&callback_lock, flags);
3439 	rcu_read_lock();
3440 	guarantee_online_mems(task_cs(tsk), &mask);
3441 	rcu_read_unlock();
3442 	spin_unlock_irqrestore(&callback_lock, flags);
3443 
3444 	return mask;
3445 }
3446 
3447 /**
3448  * cpuset_nodemask_valid_mems_allowed - check nodemask vs. current mems_allowed
3449  * @nodemask: the nodemask to be checked
3450  *
3451  * Are any of the nodes in the nodemask allowed in current->mems_allowed?
3452  */
3453 int cpuset_nodemask_valid_mems_allowed(nodemask_t *nodemask)
3454 {
3455 	return nodes_intersects(*nodemask, current->mems_allowed);
3456 }
3457 
3458 /*
3459  * nearest_hardwall_ancestor() - Returns the nearest mem_exclusive or
3460  * mem_hardwall ancestor to the specified cpuset.  Call holding
3461  * callback_lock.  If no ancestor is mem_exclusive or mem_hardwall
3462  * (an unusual configuration), then returns the root cpuset.
3463  */
3464 static struct cpuset *nearest_hardwall_ancestor(struct cpuset *cs)
3465 {
3466 	while (!(is_mem_exclusive(cs) || is_mem_hardwall(cs)) && parent_cs(cs))
3467 		cs = parent_cs(cs);
3468 	return cs;
3469 }
3470 
3471 /**
3472  * cpuset_node_allowed - Can we allocate on a memory node?
3473  * @node: is this an allowed node?
3474  * @gfp_mask: memory allocation flags
3475  *
3476  * If we're in interrupt, yes, we can always allocate.  If @node is set in
3477  * current's mems_allowed, yes.  If it's not a __GFP_HARDWALL request and this
3478  * node is set in the nearest hardwalled cpuset ancestor to current's cpuset,
3479  * yes.  If current has access to memory reserves as an oom victim, yes.
3480  * Otherwise, no.
3481  *
3482  * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
3483  * and do not allow allocations outside the current tasks cpuset
3484  * unless the task has been OOM killed.
3485  * GFP_KERNEL allocations are not so marked, so can escape to the
3486  * nearest enclosing hardwalled ancestor cpuset.
3487  *
3488  * Scanning up parent cpusets requires callback_lock.  The
3489  * __alloc_pages() routine only calls here with __GFP_HARDWALL bit
3490  * _not_ set if it's a GFP_KERNEL allocation, and all nodes in the
3491  * current tasks mems_allowed came up empty on the first pass over
3492  * the zonelist.  So only GFP_KERNEL allocations, if all nodes in the
3493  * cpuset are short of memory, might require taking the callback_lock.
3494  *
3495  * The first call here from mm/page_alloc:get_page_from_freelist()
3496  * has __GFP_HARDWALL set in gfp_mask, enforcing hardwall cpusets,
3497  * so no allocation on a node outside the cpuset is allowed (unless
3498  * in interrupt, of course).
3499  *
3500  * The second pass through get_page_from_freelist() doesn't even call
3501  * here for GFP_ATOMIC calls.  For those calls, the __alloc_pages()
3502  * variable 'wait' is not set, and the bit ALLOC_CPUSET is not set
3503  * in alloc_flags.  That logic and the checks below have the combined
3504  * affect that:
3505  *	in_interrupt - any node ok (current task context irrelevant)
3506  *	GFP_ATOMIC   - any node ok
3507  *	tsk_is_oom_victim   - any node ok
3508  *	GFP_KERNEL   - any node in enclosing hardwalled cpuset ok
3509  *	GFP_USER     - only nodes in current tasks mems allowed ok.
3510  */
3511 bool __cpuset_node_allowed(int node, gfp_t gfp_mask)
3512 {
3513 	struct cpuset *cs;		/* current cpuset ancestors */
3514 	int allowed;			/* is allocation in zone z allowed? */
3515 	unsigned long flags;
3516 
3517 	if (in_interrupt())
3518 		return true;
3519 	if (node_isset(node, current->mems_allowed))
3520 		return true;
3521 	/*
3522 	 * Allow tasks that have access to memory reserves because they have
3523 	 * been OOM killed to get memory anywhere.
3524 	 */
3525 	if (unlikely(tsk_is_oom_victim(current)))
3526 		return true;
3527 	if (gfp_mask & __GFP_HARDWALL)	/* If hardwall request, stop here */
3528 		return false;
3529 
3530 	if (current->flags & PF_EXITING) /* Let dying task have memory */
3531 		return true;
3532 
3533 	/* Not hardwall and node outside mems_allowed: scan up cpusets */
3534 	spin_lock_irqsave(&callback_lock, flags);
3535 
3536 	rcu_read_lock();
3537 	cs = nearest_hardwall_ancestor(task_cs(current));
3538 	allowed = node_isset(node, cs->mems_allowed);
3539 	rcu_read_unlock();
3540 
3541 	spin_unlock_irqrestore(&callback_lock, flags);
3542 	return allowed;
3543 }
3544 
3545 /**
3546  * cpuset_mem_spread_node() - On which node to begin search for a file page
3547  * cpuset_slab_spread_node() - On which node to begin search for a slab page
3548  *
3549  * If a task is marked PF_SPREAD_PAGE or PF_SPREAD_SLAB (as for
3550  * tasks in a cpuset with is_spread_page or is_spread_slab set),
3551  * and if the memory allocation used cpuset_mem_spread_node()
3552  * to determine on which node to start looking, as it will for
3553  * certain page cache or slab cache pages such as used for file
3554  * system buffers and inode caches, then instead of starting on the
3555  * local node to look for a free page, rather spread the starting
3556  * node around the tasks mems_allowed nodes.
3557  *
3558  * We don't have to worry about the returned node being offline
3559  * because "it can't happen", and even if it did, it would be ok.
3560  *
3561  * The routines calling guarantee_online_mems() are careful to
3562  * only set nodes in task->mems_allowed that are online.  So it
3563  * should not be possible for the following code to return an
3564  * offline node.  But if it did, that would be ok, as this routine
3565  * is not returning the node where the allocation must be, only
3566  * the node where the search should start.  The zonelist passed to
3567  * __alloc_pages() will include all nodes.  If the slab allocator
3568  * is passed an offline node, it will fall back to the local node.
3569  * See kmem_cache_alloc_node().
3570  */
3571 
3572 static int cpuset_spread_node(int *rotor)
3573 {
3574 	return *rotor = next_node_in(*rotor, current->mems_allowed);
3575 }
3576 
3577 int cpuset_mem_spread_node(void)
3578 {
3579 	if (current->cpuset_mem_spread_rotor == NUMA_NO_NODE)
3580 		current->cpuset_mem_spread_rotor =
3581 			node_random(&current->mems_allowed);
3582 
3583 	return cpuset_spread_node(&current->cpuset_mem_spread_rotor);
3584 }
3585 
3586 int cpuset_slab_spread_node(void)
3587 {
3588 	if (current->cpuset_slab_spread_rotor == NUMA_NO_NODE)
3589 		current->cpuset_slab_spread_rotor =
3590 			node_random(&current->mems_allowed);
3591 
3592 	return cpuset_spread_node(&current->cpuset_slab_spread_rotor);
3593 }
3594 
3595 EXPORT_SYMBOL_GPL(cpuset_mem_spread_node);
3596 
3597 /**
3598  * cpuset_mems_allowed_intersects - Does @tsk1's mems_allowed intersect @tsk2's?
3599  * @tsk1: pointer to task_struct of some task.
3600  * @tsk2: pointer to task_struct of some other task.
3601  *
3602  * Description: Return true if @tsk1's mems_allowed intersects the
3603  * mems_allowed of @tsk2.  Used by the OOM killer to determine if
3604  * one of the task's memory usage might impact the memory available
3605  * to the other.
3606  **/
3607 
3608 int cpuset_mems_allowed_intersects(const struct task_struct *tsk1,
3609 				   const struct task_struct *tsk2)
3610 {
3611 	return nodes_intersects(tsk1->mems_allowed, tsk2->mems_allowed);
3612 }
3613 
3614 /**
3615  * cpuset_print_current_mems_allowed - prints current's cpuset and mems_allowed
3616  *
3617  * Description: Prints current's name, cpuset name, and cached copy of its
3618  * mems_allowed to the kernel log.
3619  */
3620 void cpuset_print_current_mems_allowed(void)
3621 {
3622 	struct cgroup *cgrp;
3623 
3624 	rcu_read_lock();
3625 
3626 	cgrp = task_cs(current)->css.cgroup;
3627 	pr_cont(",cpuset=");
3628 	pr_cont_cgroup_name(cgrp);
3629 	pr_cont(",mems_allowed=%*pbl",
3630 		nodemask_pr_args(&current->mems_allowed));
3631 
3632 	rcu_read_unlock();
3633 }
3634 
3635 /*
3636  * Collection of memory_pressure is suppressed unless
3637  * this flag is enabled by writing "1" to the special
3638  * cpuset file 'memory_pressure_enabled' in the root cpuset.
3639  */
3640 
3641 int cpuset_memory_pressure_enabled __read_mostly;
3642 
3643 /**
3644  * cpuset_memory_pressure_bump - keep stats of per-cpuset reclaims.
3645  *
3646  * Keep a running average of the rate of synchronous (direct)
3647  * page reclaim efforts initiated by tasks in each cpuset.
3648  *
3649  * This represents the rate at which some task in the cpuset
3650  * ran low on memory on all nodes it was allowed to use, and
3651  * had to enter the kernels page reclaim code in an effort to
3652  * create more free memory by tossing clean pages or swapping
3653  * or writing dirty pages.
3654  *
3655  * Display to user space in the per-cpuset read-only file
3656  * "memory_pressure".  Value displayed is an integer
3657  * representing the recent rate of entry into the synchronous
3658  * (direct) page reclaim by any task attached to the cpuset.
3659  **/
3660 
3661 void __cpuset_memory_pressure_bump(void)
3662 {
3663 	rcu_read_lock();
3664 	fmeter_markevent(&task_cs(current)->fmeter);
3665 	rcu_read_unlock();
3666 }
3667 
3668 #ifdef CONFIG_PROC_PID_CPUSET
3669 /*
3670  * proc_cpuset_show()
3671  *  - Print tasks cpuset path into seq_file.
3672  *  - Used for /proc/<pid>/cpuset.
3673  *  - No need to task_lock(tsk) on this tsk->cpuset reference, as it
3674  *    doesn't really matter if tsk->cpuset changes after we read it,
3675  *    and we take cpuset_mutex, keeping cpuset_attach() from changing it
3676  *    anyway.
3677  */
3678 int proc_cpuset_show(struct seq_file *m, struct pid_namespace *ns,
3679 		     struct pid *pid, struct task_struct *tsk)
3680 {
3681 	char *buf;
3682 	struct cgroup_subsys_state *css;
3683 	int retval;
3684 
3685 	retval = -ENOMEM;
3686 	buf = kmalloc(PATH_MAX, GFP_KERNEL);
3687 	if (!buf)
3688 		goto out;
3689 
3690 	css = task_get_css(tsk, cpuset_cgrp_id);
3691 	retval = cgroup_path_ns(css->cgroup, buf, PATH_MAX,
3692 				current->nsproxy->cgroup_ns);
3693 	css_put(css);
3694 	if (retval >= PATH_MAX)
3695 		retval = -ENAMETOOLONG;
3696 	if (retval < 0)
3697 		goto out_free;
3698 	seq_puts(m, buf);
3699 	seq_putc(m, '\n');
3700 	retval = 0;
3701 out_free:
3702 	kfree(buf);
3703 out:
3704 	return retval;
3705 }
3706 #endif /* CONFIG_PROC_PID_CPUSET */
3707 
3708 /* Display task mems_allowed in /proc/<pid>/status file. */
3709 void cpuset_task_status_allowed(struct seq_file *m, struct task_struct *task)
3710 {
3711 	seq_printf(m, "Mems_allowed:\t%*pb\n",
3712 		   nodemask_pr_args(&task->mems_allowed));
3713 	seq_printf(m, "Mems_allowed_list:\t%*pbl\n",
3714 		   nodemask_pr_args(&task->mems_allowed));
3715 }
3716