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