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