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