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