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