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