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