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