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