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