• 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 
982 	lockdep_assert_held(&cpuset_mutex);
983 	lockdep_assert_cpus_held();
984 	lockdep_assert_held(&sched_domains_mutex);
985 
986 	rcu_read_lock();
987 
988 	/*
989 	 * Clear default root domain DL accounting, it will be computed again
990 	 * if a task belongs to it.
991 	 */
992 	dl_clear_root_domain(&def_root_domain);
993 
994 	cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
995 
996 		if (cpumask_empty(cs->effective_cpus)) {
997 			pos_css = css_rightmost_descendant(pos_css);
998 			continue;
999 		}
1000 
1001 		css_get(&cs->css);
1002 
1003 		rcu_read_unlock();
1004 
1005 		dl_update_tasks_root_domain(cs);
1006 
1007 		rcu_read_lock();
1008 		css_put(&cs->css);
1009 	}
1010 	rcu_read_unlock();
1011 }
1012 
1013 static void
partition_and_rebuild_sched_domains(int ndoms_new,cpumask_var_t doms_new[],struct sched_domain_attr * dattr_new)1014 partition_and_rebuild_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
1015 				    struct sched_domain_attr *dattr_new)
1016 {
1017 	mutex_lock(&sched_domains_mutex);
1018 	partition_sched_domains_locked(ndoms_new, doms_new, dattr_new);
1019 	dl_rebuild_rd_accounting();
1020 	mutex_unlock(&sched_domains_mutex);
1021 }
1022 
1023 /*
1024  * Rebuild scheduler domains.
1025  *
1026  * If the flag 'sched_load_balance' of any cpuset with non-empty
1027  * 'cpus' changes, or if the 'cpus' allowed changes in any cpuset
1028  * which has that flag enabled, or if any cpuset with a non-empty
1029  * 'cpus' is removed, then call this routine to rebuild the
1030  * scheduler's dynamic sched domains.
1031  *
1032  * Call with cpuset_mutex held.  Takes get_online_cpus().
1033  */
rebuild_sched_domains_locked(void)1034 static void rebuild_sched_domains_locked(void)
1035 {
1036 	struct cgroup_subsys_state *pos_css;
1037 	struct sched_domain_attr *attr;
1038 	cpumask_var_t *doms;
1039 	struct cpuset *cs;
1040 	int ndoms;
1041 
1042 	lockdep_assert_held(&cpuset_mutex);
1043 
1044 	/*
1045 	 * If we have raced with CPU hotplug, return early to avoid
1046 	 * passing doms with offlined cpu to partition_sched_domains().
1047 	 * Anyways, cpuset_hotplug_workfn() will rebuild sched domains.
1048 	 *
1049 	 * With no CPUs in any subpartitions, top_cpuset's effective CPUs
1050 	 * should be the same as the active CPUs, so checking only top_cpuset
1051 	 * is enough to detect racing CPU offlines.
1052 	 */
1053 	if (!top_cpuset.nr_subparts_cpus &&
1054 	    !cpumask_equal(top_cpuset.effective_cpus, cpu_active_mask))
1055 		return;
1056 
1057 	/*
1058 	 * With subpartition CPUs, however, the effective CPUs of a partition
1059 	 * root should be only a subset of the active CPUs.  Since a CPU in any
1060 	 * partition root could be offlined, all must be checked.
1061 	 */
1062 	if (top_cpuset.nr_subparts_cpus) {
1063 		rcu_read_lock();
1064 		cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
1065 			if (!is_partition_root(cs)) {
1066 				pos_css = css_rightmost_descendant(pos_css);
1067 				continue;
1068 			}
1069 			if (!cpumask_subset(cs->effective_cpus,
1070 					    cpu_active_mask)) {
1071 				rcu_read_unlock();
1072 				return;
1073 			}
1074 		}
1075 		rcu_read_unlock();
1076 	}
1077 
1078 	/* Generate domain masks and attrs */
1079 	ndoms = generate_sched_domains(&doms, &attr);
1080 
1081 	/* Have scheduler rebuild the domains */
1082 	partition_and_rebuild_sched_domains(ndoms, doms, attr);
1083 }
1084 #else /* !CONFIG_SMP */
rebuild_sched_domains_locked(void)1085 static void rebuild_sched_domains_locked(void)
1086 {
1087 }
1088 #endif /* CONFIG_SMP */
1089 
rebuild_sched_domains(void)1090 void rebuild_sched_domains(void)
1091 {
1092 	get_online_cpus();
1093 	mutex_lock(&cpuset_mutex);
1094 	rebuild_sched_domains_locked();
1095 	mutex_unlock(&cpuset_mutex);
1096 	put_online_cpus();
1097 }
1098 
update_cpus_allowed(struct cpuset * cs,struct task_struct * p,const struct cpumask * new_mask)1099 static int update_cpus_allowed(struct cpuset *cs, struct task_struct *p,
1100 				const struct cpumask *new_mask)
1101 {
1102 	int ret = -EINVAL;
1103 
1104 	trace_android_rvh_update_cpus_allowed(p, cs->cpus_requested, new_mask, &ret);
1105 	if (!ret)
1106 		return ret;
1107 
1108 	return set_cpus_allowed_ptr(p, new_mask);
1109 }
1110 
1111 /**
1112  * update_tasks_cpumask - Update the cpumasks of tasks in the cpuset.
1113  * @cs: the cpuset in which each task's cpus_allowed mask needs to be changed
1114  *
1115  * Iterate through each task of @cs updating its cpus_allowed to the
1116  * effective cpuset's.  As this function is called with cpuset_mutex held,
1117  * cpuset membership stays stable.
1118  */
update_tasks_cpumask(struct cpuset * cs)1119 static void update_tasks_cpumask(struct cpuset *cs)
1120 {
1121 	struct css_task_iter it;
1122 	struct task_struct *task;
1123 	bool top_cs = cs == &top_cpuset;
1124 
1125 	css_task_iter_start(&cs->css, 0, &it);
1126 	while ((task = css_task_iter_next(&it))) {
1127 		/*
1128 		 * Percpu kthreads in top_cpuset are ignored
1129 		 */
1130 		if (top_cs && (task->flags & PF_KTHREAD) &&
1131 		    kthread_is_per_cpu(task))
1132 			continue;
1133 		update_cpus_allowed(cs, task, cs->effective_cpus);
1134 	}
1135 	css_task_iter_end(&it);
1136 }
1137 
1138 /**
1139  * compute_effective_cpumask - Compute the effective cpumask of the cpuset
1140  * @new_cpus: the temp variable for the new effective_cpus mask
1141  * @cs: the cpuset the need to recompute the new effective_cpus mask
1142  * @parent: the parent cpuset
1143  *
1144  * If the parent has subpartition CPUs, include them in the list of
1145  * allowable CPUs in computing the new effective_cpus mask. Since offlined
1146  * CPUs are not removed from subparts_cpus, we have to use cpu_active_mask
1147  * to mask those out.
1148  */
compute_effective_cpumask(struct cpumask * new_cpus,struct cpuset * cs,struct cpuset * parent)1149 static void compute_effective_cpumask(struct cpumask *new_cpus,
1150 				      struct cpuset *cs, struct cpuset *parent)
1151 {
1152 	if (parent->nr_subparts_cpus) {
1153 		cpumask_or(new_cpus, parent->effective_cpus,
1154 			   parent->subparts_cpus);
1155 		cpumask_and(new_cpus, new_cpus, cs->cpus_requested);
1156 		cpumask_and(new_cpus, new_cpus, cpu_active_mask);
1157 	} else {
1158 		cpumask_and(new_cpus, cs->cpus_requested, parent_cs(cs)->effective_cpus);
1159 	}
1160 }
1161 
1162 /*
1163  * Commands for update_parent_subparts_cpumask
1164  */
1165 enum subparts_cmd {
1166 	partcmd_enable,		/* Enable partition root	 */
1167 	partcmd_disable,	/* Disable partition root	 */
1168 	partcmd_update,		/* Update parent's subparts_cpus */
1169 };
1170 
1171 /**
1172  * update_parent_subparts_cpumask - update subparts_cpus mask of parent cpuset
1173  * @cpuset:  The cpuset that requests change in partition root state
1174  * @cmd:     Partition root state change command
1175  * @newmask: Optional new cpumask for partcmd_update
1176  * @tmp:     Temporary addmask and delmask
1177  * Return:   0, 1 or an error code
1178  *
1179  * For partcmd_enable, the cpuset is being transformed from a non-partition
1180  * root to a partition root. The cpus_allowed mask of the given cpuset will
1181  * be put into parent's subparts_cpus and taken away from parent's
1182  * effective_cpus. The function will return 0 if all the CPUs listed in
1183  * cpus_allowed can be granted or an error code will be returned.
1184  *
1185  * For partcmd_disable, the cpuset is being transofrmed from a partition
1186  * root back to a non-partition root. Any CPUs in cpus_allowed that are in
1187  * parent's subparts_cpus will be taken away from that cpumask and put back
1188  * into parent's effective_cpus. 0 should always be returned.
1189  *
1190  * For partcmd_update, if the optional newmask is specified, the cpu
1191  * list is to be changed from cpus_allowed to newmask. Otherwise,
1192  * cpus_allowed is assumed to remain the same. The cpuset should either
1193  * be a partition root or an invalid partition root. The partition root
1194  * state may change if newmask is NULL and none of the requested CPUs can
1195  * be granted by the parent. The function will return 1 if changes to
1196  * parent's subparts_cpus and effective_cpus happen or 0 otherwise.
1197  * Error code should only be returned when newmask is non-NULL.
1198  *
1199  * The partcmd_enable and partcmd_disable commands are used by
1200  * update_prstate(). The partcmd_update command is used by
1201  * update_cpumasks_hier() with newmask NULL and update_cpumask() with
1202  * newmask set.
1203  *
1204  * The checking is more strict when enabling partition root than the
1205  * other two commands.
1206  *
1207  * Because of the implicit cpu exclusive nature of a partition root,
1208  * cpumask changes that violates the cpu exclusivity rule will not be
1209  * permitted when checked by validate_change(). The validate_change()
1210  * function will also prevent any changes to the cpu list if it is not
1211  * a superset of children's cpu lists.
1212  */
update_parent_subparts_cpumask(struct cpuset * cpuset,int cmd,struct cpumask * newmask,struct tmpmasks * tmp)1213 static int update_parent_subparts_cpumask(struct cpuset *cpuset, int cmd,
1214 					  struct cpumask *newmask,
1215 					  struct tmpmasks *tmp)
1216 {
1217 	struct cpuset *parent = parent_cs(cpuset);
1218 	int adding;	/* Moving cpus from effective_cpus to subparts_cpus */
1219 	int deleting;	/* Moving cpus from subparts_cpus to effective_cpus */
1220 	int new_prs;
1221 	bool part_error = false;	/* Partition error? */
1222 
1223 	lockdep_assert_held(&cpuset_mutex);
1224 
1225 	/*
1226 	 * The parent must be a partition root.
1227 	 * The new cpumask, if present, or the current cpus_allowed must
1228 	 * not be empty.
1229 	 */
1230 	if (!is_partition_root(parent) ||
1231 	   (newmask && cpumask_empty(newmask)) ||
1232 	   (!newmask && cpumask_empty(cpuset->cpus_allowed)))
1233 		return -EINVAL;
1234 
1235 	/*
1236 	 * Enabling/disabling partition root is not allowed if there are
1237 	 * online children.
1238 	 */
1239 	if ((cmd != partcmd_update) && css_has_online_children(&cpuset->css))
1240 		return -EBUSY;
1241 
1242 	/*
1243 	 * Enabling partition root is not allowed if not all the CPUs
1244 	 * can be granted from parent's effective_cpus or at least one
1245 	 * CPU will be left after that.
1246 	 */
1247 	if ((cmd == partcmd_enable) &&
1248 	   (!cpumask_subset(cpuset->cpus_allowed, parent->effective_cpus) ||
1249 	     cpumask_equal(cpuset->cpus_allowed, parent->effective_cpus)))
1250 		return -EINVAL;
1251 
1252 	/*
1253 	 * A cpumask update cannot make parent's effective_cpus become empty.
1254 	 */
1255 	adding = deleting = false;
1256 	new_prs = cpuset->partition_root_state;
1257 	if (cmd == partcmd_enable) {
1258 		cpumask_copy(tmp->addmask, cpuset->cpus_allowed);
1259 		adding = true;
1260 	} else if (cmd == partcmd_disable) {
1261 		deleting = cpumask_and(tmp->delmask, cpuset->cpus_allowed,
1262 				       parent->subparts_cpus);
1263 	} else if (newmask) {
1264 		/*
1265 		 * partcmd_update with newmask:
1266 		 *
1267 		 * delmask = cpus_allowed & ~newmask & parent->subparts_cpus
1268 		 * addmask = newmask & parent->effective_cpus
1269 		 *		     & ~parent->subparts_cpus
1270 		 */
1271 		cpumask_andnot(tmp->delmask, cpuset->cpus_allowed, newmask);
1272 		deleting = cpumask_and(tmp->delmask, tmp->delmask,
1273 				       parent->subparts_cpus);
1274 
1275 		cpumask_and(tmp->addmask, newmask, parent->effective_cpus);
1276 		adding = cpumask_andnot(tmp->addmask, tmp->addmask,
1277 					parent->subparts_cpus);
1278 		/*
1279 		 * Return error if the new effective_cpus could become empty.
1280 		 */
1281 		if (adding &&
1282 		    cpumask_equal(parent->effective_cpus, tmp->addmask)) {
1283 			if (!deleting)
1284 				return -EINVAL;
1285 			/*
1286 			 * As some of the CPUs in subparts_cpus might have
1287 			 * been offlined, we need to compute the real delmask
1288 			 * to confirm that.
1289 			 */
1290 			if (!cpumask_and(tmp->addmask, tmp->delmask,
1291 					 cpu_active_mask))
1292 				return -EINVAL;
1293 			cpumask_copy(tmp->addmask, parent->effective_cpus);
1294 		}
1295 	} else {
1296 		/*
1297 		 * partcmd_update w/o newmask:
1298 		 *
1299 		 * addmask = cpus_allowed & parent->effective_cpus
1300 		 *
1301 		 * Note that parent's subparts_cpus may have been
1302 		 * pre-shrunk in case there is a change in the cpu list.
1303 		 * So no deletion is needed.
1304 		 */
1305 		adding = cpumask_and(tmp->addmask, cpuset->cpus_allowed,
1306 				     parent->effective_cpus);
1307 		part_error = cpumask_equal(tmp->addmask,
1308 					   parent->effective_cpus);
1309 	}
1310 
1311 	if (cmd == partcmd_update) {
1312 		int prev_prs = cpuset->partition_root_state;
1313 
1314 		/*
1315 		 * Check for possible transition between PRS_ENABLED
1316 		 * and PRS_ERROR.
1317 		 */
1318 		switch (cpuset->partition_root_state) {
1319 		case PRS_ENABLED:
1320 			if (part_error)
1321 				new_prs = PRS_ERROR;
1322 			break;
1323 		case PRS_ERROR:
1324 			if (!part_error)
1325 				new_prs = PRS_ENABLED;
1326 			break;
1327 		}
1328 		/*
1329 		 * Set part_error if previously in invalid state.
1330 		 */
1331 		part_error = (prev_prs == PRS_ERROR);
1332 	}
1333 
1334 	if (!part_error && (new_prs == PRS_ERROR))
1335 		return 0;	/* Nothing need to be done */
1336 
1337 	if (new_prs == PRS_ERROR) {
1338 		/*
1339 		 * Remove all its cpus from parent's subparts_cpus.
1340 		 */
1341 		adding = false;
1342 		deleting = cpumask_and(tmp->delmask, cpuset->cpus_allowed,
1343 				       parent->subparts_cpus);
1344 	}
1345 
1346 	if (!adding && !deleting && (new_prs == cpuset->partition_root_state))
1347 		return 0;
1348 
1349 	/*
1350 	 * Change the parent's subparts_cpus.
1351 	 * Newly added CPUs will be removed from effective_cpus and
1352 	 * newly deleted ones will be added back to effective_cpus.
1353 	 */
1354 	spin_lock_irq(&callback_lock);
1355 	if (adding) {
1356 		cpumask_or(parent->subparts_cpus,
1357 			   parent->subparts_cpus, tmp->addmask);
1358 		cpumask_andnot(parent->effective_cpus,
1359 			       parent->effective_cpus, tmp->addmask);
1360 	}
1361 	if (deleting) {
1362 		cpumask_andnot(parent->subparts_cpus,
1363 			       parent->subparts_cpus, tmp->delmask);
1364 		/*
1365 		 * Some of the CPUs in subparts_cpus might have been offlined.
1366 		 */
1367 		cpumask_and(tmp->delmask, tmp->delmask, cpu_active_mask);
1368 		cpumask_or(parent->effective_cpus,
1369 			   parent->effective_cpus, tmp->delmask);
1370 	}
1371 
1372 	parent->nr_subparts_cpus = cpumask_weight(parent->subparts_cpus);
1373 
1374 	if (cpuset->partition_root_state != new_prs)
1375 		cpuset->partition_root_state = new_prs;
1376 	spin_unlock_irq(&callback_lock);
1377 
1378 	return cmd == partcmd_update;
1379 }
1380 
1381 /*
1382  * update_cpumasks_hier - Update effective cpumasks and tasks in the subtree
1383  * @cs:  the cpuset to consider
1384  * @tmp: temp variables for calculating effective_cpus & partition setup
1385  *
1386  * When congifured cpumask is changed, the effective cpumasks of this cpuset
1387  * and all its descendants need to be updated.
1388  *
1389  * On legacy hierachy, effective_cpus will be the same with cpu_allowed.
1390  *
1391  * Called with cpuset_mutex held
1392  */
update_cpumasks_hier(struct cpuset * cs,struct tmpmasks * tmp)1393 static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp)
1394 {
1395 	struct cpuset *cp;
1396 	struct cgroup_subsys_state *pos_css;
1397 	bool need_rebuild_sched_domains = false;
1398 	int new_prs;
1399 
1400 	rcu_read_lock();
1401 	cpuset_for_each_descendant_pre(cp, pos_css, cs) {
1402 		struct cpuset *parent = parent_cs(cp);
1403 
1404 		compute_effective_cpumask(tmp->new_cpus, cp, parent);
1405 
1406 		/*
1407 		 * If it becomes empty, inherit the effective mask of the
1408 		 * parent, which is guaranteed to have some CPUs.
1409 		 */
1410 		if (is_in_v2_mode() && cpumask_empty(tmp->new_cpus)) {
1411 			cpumask_copy(tmp->new_cpus, parent->effective_cpus);
1412 			if (!cp->use_parent_ecpus) {
1413 				cp->use_parent_ecpus = true;
1414 				parent->child_ecpus_count++;
1415 			}
1416 		} else if (cp->use_parent_ecpus) {
1417 			cp->use_parent_ecpus = false;
1418 			WARN_ON_ONCE(!parent->child_ecpus_count);
1419 			parent->child_ecpus_count--;
1420 		}
1421 
1422 		/*
1423 		 * Skip the whole subtree if the cpumask remains the same
1424 		 * and has no partition root state.
1425 		 */
1426 		if (!cp->partition_root_state &&
1427 		    cpumask_equal(tmp->new_cpus, cp->effective_cpus)) {
1428 			pos_css = css_rightmost_descendant(pos_css);
1429 			continue;
1430 		}
1431 
1432 		/*
1433 		 * update_parent_subparts_cpumask() should have been called
1434 		 * for cs already in update_cpumask(). We should also call
1435 		 * update_tasks_cpumask() again for tasks in the parent
1436 		 * cpuset if the parent's subparts_cpus changes.
1437 		 */
1438 		new_prs = cp->partition_root_state;
1439 		if ((cp != cs) && new_prs) {
1440 			switch (parent->partition_root_state) {
1441 			case PRS_DISABLED:
1442 				/*
1443 				 * If parent is not a partition root or an
1444 				 * invalid partition root, clear its state
1445 				 * and its CS_CPU_EXCLUSIVE flag.
1446 				 */
1447 				WARN_ON_ONCE(cp->partition_root_state
1448 					     != PRS_ERROR);
1449 				new_prs = PRS_DISABLED;
1450 
1451 				/*
1452 				 * clear_bit() is an atomic operation and
1453 				 * readers aren't interested in the state
1454 				 * of CS_CPU_EXCLUSIVE anyway. So we can
1455 				 * just update the flag without holding
1456 				 * the callback_lock.
1457 				 */
1458 				clear_bit(CS_CPU_EXCLUSIVE, &cp->flags);
1459 				break;
1460 
1461 			case PRS_ENABLED:
1462 				if (update_parent_subparts_cpumask(cp, partcmd_update, NULL, tmp))
1463 					update_tasks_cpumask(parent);
1464 				break;
1465 
1466 			case PRS_ERROR:
1467 				/*
1468 				 * When parent is invalid, it has to be too.
1469 				 */
1470 				new_prs = PRS_ERROR;
1471 				break;
1472 			}
1473 		}
1474 
1475 		if (!css_tryget_online(&cp->css))
1476 			continue;
1477 		rcu_read_unlock();
1478 
1479 		spin_lock_irq(&callback_lock);
1480 
1481 		cpumask_copy(cp->effective_cpus, tmp->new_cpus);
1482 		if (cp->nr_subparts_cpus && (new_prs != PRS_ENABLED)) {
1483 			cp->nr_subparts_cpus = 0;
1484 			cpumask_clear(cp->subparts_cpus);
1485 		} else if (cp->nr_subparts_cpus) {
1486 			/*
1487 			 * Make sure that effective_cpus & subparts_cpus
1488 			 * are mutually exclusive.
1489 			 *
1490 			 * In the unlikely event that effective_cpus
1491 			 * becomes empty. we clear cp->nr_subparts_cpus and
1492 			 * let its child partition roots to compete for
1493 			 * CPUs again.
1494 			 */
1495 			cpumask_andnot(cp->effective_cpus, cp->effective_cpus,
1496 				       cp->subparts_cpus);
1497 			if (cpumask_empty(cp->effective_cpus)) {
1498 				cpumask_copy(cp->effective_cpus, tmp->new_cpus);
1499 				cpumask_clear(cp->subparts_cpus);
1500 				cp->nr_subparts_cpus = 0;
1501 			} else if (!cpumask_subset(cp->subparts_cpus,
1502 						   tmp->new_cpus)) {
1503 				cpumask_andnot(cp->subparts_cpus,
1504 					cp->subparts_cpus, tmp->new_cpus);
1505 				cp->nr_subparts_cpus
1506 					= cpumask_weight(cp->subparts_cpus);
1507 			}
1508 		}
1509 
1510 		if (new_prs != cp->partition_root_state)
1511 			cp->partition_root_state = new_prs;
1512 
1513 		spin_unlock_irq(&callback_lock);
1514 
1515 		WARN_ON(!is_in_v2_mode() &&
1516 			!cpumask_equal(cp->cpus_allowed, cp->effective_cpus));
1517 
1518 		update_tasks_cpumask(cp);
1519 
1520 		/*
1521 		 * On legacy hierarchy, if the effective cpumask of any non-
1522 		 * empty cpuset is changed, we need to rebuild sched domains.
1523 		 * On default hierarchy, the cpuset needs to be a partition
1524 		 * root as well.
1525 		 */
1526 		if (!cpumask_empty(cp->cpus_allowed) &&
1527 		    is_sched_load_balance(cp) &&
1528 		   (!cgroup_subsys_on_dfl(cpuset_cgrp_subsys) ||
1529 		    is_partition_root(cp)))
1530 			need_rebuild_sched_domains = true;
1531 
1532 		rcu_read_lock();
1533 		css_put(&cp->css);
1534 	}
1535 	rcu_read_unlock();
1536 
1537 	if (need_rebuild_sched_domains)
1538 		rebuild_sched_domains_locked();
1539 }
1540 
1541 /**
1542  * update_sibling_cpumasks - Update siblings cpumasks
1543  * @parent:  Parent cpuset
1544  * @cs:      Current cpuset
1545  * @tmp:     Temp variables
1546  */
update_sibling_cpumasks(struct cpuset * parent,struct cpuset * cs,struct tmpmasks * tmp)1547 static void update_sibling_cpumasks(struct cpuset *parent, struct cpuset *cs,
1548 				    struct tmpmasks *tmp)
1549 {
1550 	struct cpuset *sibling;
1551 	struct cgroup_subsys_state *pos_css;
1552 
1553 	lockdep_assert_held(&cpuset_mutex);
1554 
1555 	/*
1556 	 * Check all its siblings and call update_cpumasks_hier()
1557 	 * if their use_parent_ecpus flag is set in order for them
1558 	 * to use the right effective_cpus value.
1559 	 *
1560 	 * The update_cpumasks_hier() function may sleep. So we have to
1561 	 * release the RCU read lock before calling it.
1562 	 */
1563 	rcu_read_lock();
1564 	cpuset_for_each_child(sibling, pos_css, parent) {
1565 		if (sibling == cs)
1566 			continue;
1567 		if (!sibling->use_parent_ecpus)
1568 			continue;
1569 		if (!css_tryget_online(&sibling->css))
1570 			continue;
1571 
1572 		rcu_read_unlock();
1573 		update_cpumasks_hier(sibling, tmp);
1574 		rcu_read_lock();
1575 		css_put(&sibling->css);
1576 	}
1577 	rcu_read_unlock();
1578 }
1579 
1580 /**
1581  * update_cpumask - update the cpus_allowed mask of a cpuset and all tasks in it
1582  * @cs: the cpuset to consider
1583  * @trialcs: trial cpuset
1584  * @buf: buffer of cpu numbers written to this cpuset
1585  */
update_cpumask(struct cpuset * cs,struct cpuset * trialcs,const char * buf)1586 static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs,
1587 			  const char *buf)
1588 {
1589 	int retval;
1590 	struct tmpmasks tmp;
1591 
1592 	/* top_cpuset.cpus_allowed tracks cpu_online_mask; it's read-only */
1593 	if (cs == &top_cpuset)
1594 		return -EACCES;
1595 
1596 	/*
1597 	 * An empty cpus_requested is ok only if the cpuset has no tasks.
1598 	 * Since cpulist_parse() fails on an empty mask, we special case
1599 	 * that parsing.  The validate_change() call ensures that cpusets
1600 	 * with tasks have cpus.
1601 	 */
1602 	if (!*buf) {
1603 		cpumask_clear(trialcs->cpus_requested);
1604 	} else {
1605 		retval = cpulist_parse(buf, trialcs->cpus_requested);
1606 		if (retval < 0)
1607 			return retval;
1608 	}
1609 
1610 	if (!cpumask_subset(trialcs->cpus_requested, cpu_present_mask))
1611 		return -EINVAL;
1612 
1613 	cpumask_and(trialcs->cpus_allowed, trialcs->cpus_requested, cpu_active_mask);
1614 
1615 	/* Nothing to do if the cpus didn't change */
1616 	if (cpumask_equal(cs->cpus_requested, trialcs->cpus_requested))
1617 		return 0;
1618 
1619 	retval = validate_change(cs, trialcs);
1620 	if (retval < 0)
1621 		return retval;
1622 
1623 #ifdef CONFIG_CPUMASK_OFFSTACK
1624 	/*
1625 	 * Use the cpumasks in trialcs for tmpmasks when they are pointers
1626 	 * to allocated cpumasks.
1627 	 */
1628 	tmp.addmask  = trialcs->subparts_cpus;
1629 	tmp.delmask  = trialcs->effective_cpus;
1630 	tmp.new_cpus = trialcs->cpus_allowed;
1631 #endif
1632 
1633 	if (cs->partition_root_state) {
1634 		/* Cpumask of a partition root cannot be empty */
1635 		if (cpumask_empty(trialcs->cpus_allowed))
1636 			return -EINVAL;
1637 		if (update_parent_subparts_cpumask(cs, partcmd_update,
1638 					trialcs->cpus_allowed, &tmp) < 0)
1639 			return -EINVAL;
1640 	}
1641 
1642 	spin_lock_irq(&callback_lock);
1643 	cpumask_copy(cs->cpus_allowed, trialcs->cpus_allowed);
1644 	cpumask_copy(cs->cpus_requested, trialcs->cpus_requested);
1645 
1646 	/*
1647 	 * Make sure that subparts_cpus is a subset of cpus_allowed.
1648 	 */
1649 	if (cs->nr_subparts_cpus) {
1650 		cpumask_and(cs->subparts_cpus, cs->subparts_cpus, cs->cpus_allowed);
1651 		cs->nr_subparts_cpus = cpumask_weight(cs->subparts_cpus);
1652 	}
1653 	spin_unlock_irq(&callback_lock);
1654 
1655 	update_cpumasks_hier(cs, &tmp);
1656 
1657 	if (cs->partition_root_state) {
1658 		struct cpuset *parent = parent_cs(cs);
1659 
1660 		/*
1661 		 * For partition root, update the cpumasks of sibling
1662 		 * cpusets if they use parent's effective_cpus.
1663 		 */
1664 		if (parent->child_ecpus_count)
1665 			update_sibling_cpumasks(parent, cs, &tmp);
1666 	}
1667 	return 0;
1668 }
1669 
1670 /*
1671  * Migrate memory region from one set of nodes to another.  This is
1672  * performed asynchronously as it can be called from process migration path
1673  * holding locks involved in process management.  All mm migrations are
1674  * performed in the queued order and can be waited for by flushing
1675  * cpuset_migrate_mm_wq.
1676  */
1677 
1678 struct cpuset_migrate_mm_work {
1679 	struct work_struct	work;
1680 	struct mm_struct	*mm;
1681 	nodemask_t		from;
1682 	nodemask_t		to;
1683 };
1684 
cpuset_migrate_mm_workfn(struct work_struct * work)1685 static void cpuset_migrate_mm_workfn(struct work_struct *work)
1686 {
1687 	struct cpuset_migrate_mm_work *mwork =
1688 		container_of(work, struct cpuset_migrate_mm_work, work);
1689 
1690 	/* on a wq worker, no need to worry about %current's mems_allowed */
1691 	do_migrate_pages(mwork->mm, &mwork->from, &mwork->to, MPOL_MF_MOVE_ALL);
1692 	mmput(mwork->mm);
1693 	kfree(mwork);
1694 }
1695 
cpuset_migrate_mm(struct mm_struct * mm,const nodemask_t * from,const nodemask_t * to)1696 static void cpuset_migrate_mm(struct mm_struct *mm, const nodemask_t *from,
1697 							const nodemask_t *to)
1698 {
1699 	struct cpuset_migrate_mm_work *mwork;
1700 
1701 	mwork = kzalloc(sizeof(*mwork), GFP_KERNEL);
1702 	if (mwork) {
1703 		mwork->mm = mm;
1704 		mwork->from = *from;
1705 		mwork->to = *to;
1706 		INIT_WORK(&mwork->work, cpuset_migrate_mm_workfn);
1707 		queue_work(cpuset_migrate_mm_wq, &mwork->work);
1708 	} else {
1709 		mmput(mm);
1710 	}
1711 }
1712 
cpuset_post_attach(void)1713 static void cpuset_post_attach(void)
1714 {
1715 	flush_workqueue(cpuset_migrate_mm_wq);
1716 }
1717 
1718 /*
1719  * cpuset_change_task_nodemask - change task's mems_allowed and mempolicy
1720  * @tsk: the task to change
1721  * @newmems: new nodes that the task will be set
1722  *
1723  * We use the mems_allowed_seq seqlock to safely update both tsk->mems_allowed
1724  * and rebind an eventual tasks' mempolicy. If the task is allocating in
1725  * parallel, it might temporarily see an empty intersection, which results in
1726  * a seqlock check and retry before OOM or allocation failure.
1727  */
cpuset_change_task_nodemask(struct task_struct * tsk,nodemask_t * newmems)1728 static void cpuset_change_task_nodemask(struct task_struct *tsk,
1729 					nodemask_t *newmems)
1730 {
1731 	task_lock(tsk);
1732 
1733 	local_irq_disable();
1734 	write_seqcount_begin(&tsk->mems_allowed_seq);
1735 
1736 	nodes_or(tsk->mems_allowed, tsk->mems_allowed, *newmems);
1737 	mpol_rebind_task(tsk, newmems);
1738 	tsk->mems_allowed = *newmems;
1739 
1740 	write_seqcount_end(&tsk->mems_allowed_seq);
1741 	local_irq_enable();
1742 
1743 	task_unlock(tsk);
1744 }
1745 
1746 static void *cpuset_being_rebound;
1747 
1748 /**
1749  * update_tasks_nodemask - Update the nodemasks of tasks in the cpuset.
1750  * @cs: the cpuset in which each task's mems_allowed mask needs to be changed
1751  *
1752  * Iterate through each task of @cs updating its mems_allowed to the
1753  * effective cpuset's.  As this function is called with cpuset_mutex held,
1754  * cpuset membership stays stable.
1755  */
update_tasks_nodemask(struct cpuset * cs)1756 static void update_tasks_nodemask(struct cpuset *cs)
1757 {
1758 	static nodemask_t newmems;	/* protected by cpuset_mutex */
1759 	struct css_task_iter it;
1760 	struct task_struct *task;
1761 
1762 	cpuset_being_rebound = cs;		/* causes mpol_dup() rebind */
1763 
1764 	guarantee_online_mems(cs, &newmems);
1765 
1766 	/*
1767 	 * The mpol_rebind_mm() call takes mmap_lock, which we couldn't
1768 	 * take while holding tasklist_lock.  Forks can happen - the
1769 	 * mpol_dup() cpuset_being_rebound check will catch such forks,
1770 	 * and rebind their vma mempolicies too.  Because we still hold
1771 	 * the global cpuset_mutex, we know that no other rebind effort
1772 	 * will be contending for the global variable cpuset_being_rebound.
1773 	 * It's ok if we rebind the same mm twice; mpol_rebind_mm()
1774 	 * is idempotent.  Also migrate pages in each mm to new nodes.
1775 	 */
1776 	css_task_iter_start(&cs->css, 0, &it);
1777 	while ((task = css_task_iter_next(&it))) {
1778 		struct mm_struct *mm;
1779 		bool migrate;
1780 
1781 		cpuset_change_task_nodemask(task, &newmems);
1782 
1783 		mm = get_task_mm(task);
1784 		if (!mm)
1785 			continue;
1786 
1787 		migrate = is_memory_migrate(cs);
1788 
1789 		mpol_rebind_mm(mm, &cs->mems_allowed);
1790 		if (migrate)
1791 			cpuset_migrate_mm(mm, &cs->old_mems_allowed, &newmems);
1792 		else
1793 			mmput(mm);
1794 	}
1795 	css_task_iter_end(&it);
1796 
1797 	/*
1798 	 * All the tasks' nodemasks have been updated, update
1799 	 * cs->old_mems_allowed.
1800 	 */
1801 	cs->old_mems_allowed = newmems;
1802 
1803 	/* We're done rebinding vmas to this cpuset's new mems_allowed. */
1804 	cpuset_being_rebound = NULL;
1805 }
1806 
1807 /*
1808  * update_nodemasks_hier - Update effective nodemasks and tasks in the subtree
1809  * @cs: the cpuset to consider
1810  * @new_mems: a temp variable for calculating new effective_mems
1811  *
1812  * When configured nodemask is changed, the effective nodemasks of this cpuset
1813  * and all its descendants need to be updated.
1814  *
1815  * On legacy hiearchy, effective_mems will be the same with mems_allowed.
1816  *
1817  * Called with cpuset_mutex held
1818  */
update_nodemasks_hier(struct cpuset * cs,nodemask_t * new_mems)1819 static void update_nodemasks_hier(struct cpuset *cs, nodemask_t *new_mems)
1820 {
1821 	struct cpuset *cp;
1822 	struct cgroup_subsys_state *pos_css;
1823 
1824 	rcu_read_lock();
1825 	cpuset_for_each_descendant_pre(cp, pos_css, cs) {
1826 		struct cpuset *parent = parent_cs(cp);
1827 
1828 		nodes_and(*new_mems, cp->mems_allowed, parent->effective_mems);
1829 
1830 		/*
1831 		 * If it becomes empty, inherit the effective mask of the
1832 		 * parent, which is guaranteed to have some MEMs.
1833 		 */
1834 		if (is_in_v2_mode() && nodes_empty(*new_mems))
1835 			*new_mems = parent->effective_mems;
1836 
1837 		/* Skip the whole subtree if the nodemask remains the same. */
1838 		if (nodes_equal(*new_mems, cp->effective_mems)) {
1839 			pos_css = css_rightmost_descendant(pos_css);
1840 			continue;
1841 		}
1842 
1843 		if (!css_tryget_online(&cp->css))
1844 			continue;
1845 		rcu_read_unlock();
1846 
1847 		spin_lock_irq(&callback_lock);
1848 		cp->effective_mems = *new_mems;
1849 		spin_unlock_irq(&callback_lock);
1850 
1851 		WARN_ON(!is_in_v2_mode() &&
1852 			!nodes_equal(cp->mems_allowed, cp->effective_mems));
1853 
1854 		update_tasks_nodemask(cp);
1855 
1856 		rcu_read_lock();
1857 		css_put(&cp->css);
1858 	}
1859 	rcu_read_unlock();
1860 }
1861 
1862 /*
1863  * Handle user request to change the 'mems' memory placement
1864  * of a cpuset.  Needs to validate the request, update the
1865  * cpusets mems_allowed, and for each task in the cpuset,
1866  * update mems_allowed and rebind task's mempolicy and any vma
1867  * mempolicies and if the cpuset is marked 'memory_migrate',
1868  * migrate the tasks pages to the new memory.
1869  *
1870  * Call with cpuset_mutex held. May take callback_lock during call.
1871  * Will take tasklist_lock, scan tasklist for tasks in cpuset cs,
1872  * lock each such tasks mm->mmap_lock, scan its vma's and rebind
1873  * their mempolicies to the cpusets new mems_allowed.
1874  */
update_nodemask(struct cpuset * cs,struct cpuset * trialcs,const char * buf)1875 static int update_nodemask(struct cpuset *cs, struct cpuset *trialcs,
1876 			   const char *buf)
1877 {
1878 	int retval;
1879 
1880 	/*
1881 	 * top_cpuset.mems_allowed tracks node_stats[N_MEMORY];
1882 	 * it's read-only
1883 	 */
1884 	if (cs == &top_cpuset) {
1885 		retval = -EACCES;
1886 		goto done;
1887 	}
1888 
1889 	/*
1890 	 * An empty mems_allowed is ok iff there are no tasks in the cpuset.
1891 	 * Since nodelist_parse() fails on an empty mask, we special case
1892 	 * that parsing.  The validate_change() call ensures that cpusets
1893 	 * with tasks have memory.
1894 	 */
1895 	if (!*buf) {
1896 		nodes_clear(trialcs->mems_allowed);
1897 	} else {
1898 		retval = nodelist_parse(buf, trialcs->mems_allowed);
1899 		if (retval < 0)
1900 			goto done;
1901 
1902 		if (!nodes_subset(trialcs->mems_allowed,
1903 				  top_cpuset.mems_allowed)) {
1904 			retval = -EINVAL;
1905 			goto done;
1906 		}
1907 	}
1908 
1909 	if (nodes_equal(cs->mems_allowed, trialcs->mems_allowed)) {
1910 		retval = 0;		/* Too easy - nothing to do */
1911 		goto done;
1912 	}
1913 	retval = validate_change(cs, trialcs);
1914 	if (retval < 0)
1915 		goto done;
1916 
1917 	spin_lock_irq(&callback_lock);
1918 	cs->mems_allowed = trialcs->mems_allowed;
1919 	spin_unlock_irq(&callback_lock);
1920 
1921 	/* use trialcs->mems_allowed as a temp variable */
1922 	update_nodemasks_hier(cs, &trialcs->mems_allowed);
1923 done:
1924 	return retval;
1925 }
1926 
current_cpuset_is_being_rebound(void)1927 bool current_cpuset_is_being_rebound(void)
1928 {
1929 	bool ret;
1930 
1931 	rcu_read_lock();
1932 	ret = task_cs(current) == cpuset_being_rebound;
1933 	rcu_read_unlock();
1934 
1935 	return ret;
1936 }
1937 
update_relax_domain_level(struct cpuset * cs,s64 val)1938 static int update_relax_domain_level(struct cpuset *cs, s64 val)
1939 {
1940 #ifdef CONFIG_SMP
1941 	if (val < -1 || val >= sched_domain_level_max)
1942 		return -EINVAL;
1943 #endif
1944 
1945 	if (val != cs->relax_domain_level) {
1946 		cs->relax_domain_level = val;
1947 		if (!cpumask_empty(cs->cpus_allowed) &&
1948 		    is_sched_load_balance(cs))
1949 			rebuild_sched_domains_locked();
1950 	}
1951 
1952 	return 0;
1953 }
1954 
1955 /**
1956  * update_tasks_flags - update the spread flags of tasks in the cpuset.
1957  * @cs: the cpuset in which each task's spread flags needs to be changed
1958  *
1959  * Iterate through each task of @cs updating its spread flags.  As this
1960  * function is called with cpuset_mutex held, cpuset membership stays
1961  * stable.
1962  */
update_tasks_flags(struct cpuset * cs)1963 static void update_tasks_flags(struct cpuset *cs)
1964 {
1965 	struct css_task_iter it;
1966 	struct task_struct *task;
1967 
1968 	css_task_iter_start(&cs->css, 0, &it);
1969 	while ((task = css_task_iter_next(&it)))
1970 		cpuset_update_task_spread_flag(cs, task);
1971 	css_task_iter_end(&it);
1972 }
1973 
1974 /*
1975  * update_flag - read a 0 or a 1 in a file and update associated flag
1976  * bit:		the bit to update (see cpuset_flagbits_t)
1977  * cs:		the cpuset to update
1978  * turning_on: 	whether the flag is being set or cleared
1979  *
1980  * Call with cpuset_mutex held.
1981  */
1982 
update_flag(cpuset_flagbits_t bit,struct cpuset * cs,int turning_on)1983 static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs,
1984 		       int turning_on)
1985 {
1986 	struct cpuset *trialcs;
1987 	int balance_flag_changed;
1988 	int spread_flag_changed;
1989 	int err;
1990 
1991 	trialcs = alloc_trial_cpuset(cs);
1992 	if (!trialcs)
1993 		return -ENOMEM;
1994 
1995 	if (turning_on)
1996 		set_bit(bit, &trialcs->flags);
1997 	else
1998 		clear_bit(bit, &trialcs->flags);
1999 
2000 	err = validate_change(cs, trialcs);
2001 	if (err < 0)
2002 		goto out;
2003 
2004 	balance_flag_changed = (is_sched_load_balance(cs) !=
2005 				is_sched_load_balance(trialcs));
2006 
2007 	spread_flag_changed = ((is_spread_slab(cs) != is_spread_slab(trialcs))
2008 			|| (is_spread_page(cs) != is_spread_page(trialcs)));
2009 
2010 	spin_lock_irq(&callback_lock);
2011 	cs->flags = trialcs->flags;
2012 	spin_unlock_irq(&callback_lock);
2013 
2014 	if (!cpumask_empty(trialcs->cpus_allowed) && balance_flag_changed)
2015 		rebuild_sched_domains_locked();
2016 
2017 	if (spread_flag_changed)
2018 		update_tasks_flags(cs);
2019 out:
2020 	free_cpuset(trialcs);
2021 	return err;
2022 }
2023 
2024 /*
2025  * update_prstate - update partititon_root_state
2026  * cs: the cpuset to update
2027  * new_prs: new partition root state
2028  *
2029  * Call with cpuset_mutex held.
2030  */
update_prstate(struct cpuset * cs,int new_prs)2031 static int update_prstate(struct cpuset *cs, int new_prs)
2032 {
2033 	int err, old_prs = cs->partition_root_state;
2034 	struct cpuset *parent = parent_cs(cs);
2035 	struct tmpmasks tmpmask;
2036 
2037 	if (old_prs == new_prs)
2038 		return 0;
2039 
2040 	/*
2041 	 * Cannot force a partial or invalid partition root to a full
2042 	 * partition root.
2043 	 */
2044 	if (new_prs && (old_prs == PRS_ERROR))
2045 		return -EINVAL;
2046 
2047 	if (alloc_cpumasks(NULL, &tmpmask))
2048 		return -ENOMEM;
2049 
2050 	err = -EINVAL;
2051 	if (!old_prs) {
2052 		/*
2053 		 * Turning on partition root requires setting the
2054 		 * CS_CPU_EXCLUSIVE bit implicitly as well and cpus_allowed
2055 		 * cannot be NULL.
2056 		 */
2057 		if (cpumask_empty(cs->cpus_allowed))
2058 			goto out;
2059 
2060 		err = update_flag(CS_CPU_EXCLUSIVE, cs, 1);
2061 		if (err)
2062 			goto out;
2063 
2064 		err = update_parent_subparts_cpumask(cs, partcmd_enable,
2065 						     NULL, &tmpmask);
2066 		if (err) {
2067 			update_flag(CS_CPU_EXCLUSIVE, cs, 0);
2068 			goto out;
2069 		}
2070 	} else {
2071 		/*
2072 		 * Turning off partition root will clear the
2073 		 * CS_CPU_EXCLUSIVE bit.
2074 		 */
2075 		if (old_prs == PRS_ERROR) {
2076 			update_flag(CS_CPU_EXCLUSIVE, cs, 0);
2077 			err = 0;
2078 			goto out;
2079 		}
2080 
2081 		err = update_parent_subparts_cpumask(cs, partcmd_disable,
2082 						     NULL, &tmpmask);
2083 		if (err)
2084 			goto out;
2085 
2086 		/* Turning off CS_CPU_EXCLUSIVE will not return error */
2087 		update_flag(CS_CPU_EXCLUSIVE, cs, 0);
2088 	}
2089 
2090 	update_tasks_cpumask(parent);
2091 
2092 	if (parent->child_ecpus_count)
2093 		update_sibling_cpumasks(parent, cs, &tmpmask);
2094 
2095 	rebuild_sched_domains_locked();
2096 out:
2097 	if (!err) {
2098 		spin_lock_irq(&callback_lock);
2099 		cs->partition_root_state = new_prs;
2100 		spin_unlock_irq(&callback_lock);
2101 	}
2102 
2103 	free_cpumasks(NULL, &tmpmask);
2104 	return err;
2105 }
2106 
2107 /*
2108  * Frequency meter - How fast is some event occurring?
2109  *
2110  * These routines manage a digitally filtered, constant time based,
2111  * event frequency meter.  There are four routines:
2112  *   fmeter_init() - initialize a frequency meter.
2113  *   fmeter_markevent() - called each time the event happens.
2114  *   fmeter_getrate() - returns the recent rate of such events.
2115  *   fmeter_update() - internal routine used to update fmeter.
2116  *
2117  * A common data structure is passed to each of these routines,
2118  * which is used to keep track of the state required to manage the
2119  * frequency meter and its digital filter.
2120  *
2121  * The filter works on the number of events marked per unit time.
2122  * The filter is single-pole low-pass recursive (IIR).  The time unit
2123  * is 1 second.  Arithmetic is done using 32-bit integers scaled to
2124  * simulate 3 decimal digits of precision (multiplied by 1000).
2125  *
2126  * With an FM_COEF of 933, and a time base of 1 second, the filter
2127  * has a half-life of 10 seconds, meaning that if the events quit
2128  * happening, then the rate returned from the fmeter_getrate()
2129  * will be cut in half each 10 seconds, until it converges to zero.
2130  *
2131  * It is not worth doing a real infinitely recursive filter.  If more
2132  * than FM_MAXTICKS ticks have elapsed since the last filter event,
2133  * just compute FM_MAXTICKS ticks worth, by which point the level
2134  * will be stable.
2135  *
2136  * Limit the count of unprocessed events to FM_MAXCNT, so as to avoid
2137  * arithmetic overflow in the fmeter_update() routine.
2138  *
2139  * Given the simple 32 bit integer arithmetic used, this meter works
2140  * best for reporting rates between one per millisecond (msec) and
2141  * one per 32 (approx) seconds.  At constant rates faster than one
2142  * per msec it maxes out at values just under 1,000,000.  At constant
2143  * rates between one per msec, and one per second it will stabilize
2144  * to a value N*1000, where N is the rate of events per second.
2145  * At constant rates between one per second and one per 32 seconds,
2146  * it will be choppy, moving up on the seconds that have an event,
2147  * and then decaying until the next event.  At rates slower than
2148  * about one in 32 seconds, it decays all the way back to zero between
2149  * each event.
2150  */
2151 
2152 #define FM_COEF 933		/* coefficient for half-life of 10 secs */
2153 #define FM_MAXTICKS ((u32)99)   /* useless computing more ticks than this */
2154 #define FM_MAXCNT 1000000	/* limit cnt to avoid overflow */
2155 #define FM_SCALE 1000		/* faux fixed point scale */
2156 
2157 /* Initialize a frequency meter */
fmeter_init(struct fmeter * fmp)2158 static void fmeter_init(struct fmeter *fmp)
2159 {
2160 	fmp->cnt = 0;
2161 	fmp->val = 0;
2162 	fmp->time = 0;
2163 	spin_lock_init(&fmp->lock);
2164 }
2165 
2166 /* Internal meter update - process cnt events and update value */
fmeter_update(struct fmeter * fmp)2167 static void fmeter_update(struct fmeter *fmp)
2168 {
2169 	time64_t now;
2170 	u32 ticks;
2171 
2172 	now = ktime_get_seconds();
2173 	ticks = now - fmp->time;
2174 
2175 	if (ticks == 0)
2176 		return;
2177 
2178 	ticks = min(FM_MAXTICKS, ticks);
2179 	while (ticks-- > 0)
2180 		fmp->val = (FM_COEF * fmp->val) / FM_SCALE;
2181 	fmp->time = now;
2182 
2183 	fmp->val += ((FM_SCALE - FM_COEF) * fmp->cnt) / FM_SCALE;
2184 	fmp->cnt = 0;
2185 }
2186 
2187 /* Process any previous ticks, then bump cnt by one (times scale). */
fmeter_markevent(struct fmeter * fmp)2188 static void fmeter_markevent(struct fmeter *fmp)
2189 {
2190 	spin_lock(&fmp->lock);
2191 	fmeter_update(fmp);
2192 	fmp->cnt = min(FM_MAXCNT, fmp->cnt + FM_SCALE);
2193 	spin_unlock(&fmp->lock);
2194 }
2195 
2196 /* Process any previous ticks, then return current value. */
fmeter_getrate(struct fmeter * fmp)2197 static int fmeter_getrate(struct fmeter *fmp)
2198 {
2199 	int val;
2200 
2201 	spin_lock(&fmp->lock);
2202 	fmeter_update(fmp);
2203 	val = fmp->val;
2204 	spin_unlock(&fmp->lock);
2205 	return val;
2206 }
2207 
2208 static struct cpuset *cpuset_attach_old_cs;
2209 
reset_migrate_dl_data(struct cpuset * cs)2210 static void reset_migrate_dl_data(struct cpuset *cs)
2211 {
2212 	cs->nr_migrate_dl_tasks = 0;
2213 	cs->sum_migrate_dl_bw = 0;
2214 }
2215 
2216 /* Called by cgroups to determine if a cpuset is usable; cpuset_mutex held */
cpuset_can_attach(struct cgroup_taskset * tset)2217 static int cpuset_can_attach(struct cgroup_taskset *tset)
2218 {
2219 	struct cgroup_subsys_state *css;
2220 	struct cpuset *cs, *oldcs;
2221 	struct task_struct *task;
2222 	int ret;
2223 
2224 	/* used later by cpuset_attach() */
2225 	cpuset_attach_old_cs = task_cs(cgroup_taskset_first(tset, &css));
2226 	oldcs = cpuset_attach_old_cs;
2227 	cs = css_cs(css);
2228 
2229 	mutex_lock(&cpuset_mutex);
2230 
2231 	/* allow moving tasks into an empty cpuset if on default hierarchy */
2232 	ret = -ENOSPC;
2233 	if (!is_in_v2_mode() &&
2234 	    (cpumask_empty(cs->cpus_allowed) || nodes_empty(cs->mems_allowed)))
2235 		goto out_unlock;
2236 
2237 	cgroup_taskset_for_each(task, css, tset) {
2238 		ret = task_can_attach(task);
2239 		if (ret)
2240 			goto out_unlock;
2241 		ret = security_task_setscheduler(task);
2242 		if (ret)
2243 			goto out_unlock;
2244 
2245 		if (dl_task(task)) {
2246 			cs->nr_migrate_dl_tasks++;
2247 			cs->sum_migrate_dl_bw += task->dl.dl_bw;
2248 		}
2249 	}
2250 
2251 	if (!cs->nr_migrate_dl_tasks)
2252 		goto out_success;
2253 
2254 	if (!cpumask_intersects(oldcs->effective_cpus, cs->effective_cpus)) {
2255 		int cpu = cpumask_any_and(cpu_active_mask, cs->effective_cpus);
2256 
2257 		if (unlikely(cpu >= nr_cpu_ids)) {
2258 			reset_migrate_dl_data(cs);
2259 			ret = -EINVAL;
2260 			goto out_unlock;
2261 		}
2262 
2263 		ret = dl_bw_alloc(cpu, cs->sum_migrate_dl_bw);
2264 		if (ret) {
2265 			reset_migrate_dl_data(cs);
2266 			goto out_unlock;
2267 		}
2268 	}
2269 
2270 out_success:
2271 	/*
2272 	 * Mark attach is in progress.  This makes validate_change() fail
2273 	 * changes which zero cpus/mems_allowed.
2274 	 */
2275 	cs->attach_in_progress++;
2276 	ret = 0;
2277 out_unlock:
2278 	mutex_unlock(&cpuset_mutex);
2279 	return ret;
2280 }
2281 
cpuset_cancel_attach(struct cgroup_taskset * tset)2282 static void cpuset_cancel_attach(struct cgroup_taskset *tset)
2283 {
2284 	struct cgroup_subsys_state *css;
2285 	struct cpuset *cs;
2286 
2287 	cgroup_taskset_first(tset, &css);
2288 	cs = css_cs(css);
2289 
2290 	mutex_lock(&cpuset_mutex);
2291 	cs->attach_in_progress--;
2292 	if (!cs->attach_in_progress)
2293 		wake_up(&cpuset_attach_wq);
2294 
2295 	if (cs->nr_migrate_dl_tasks) {
2296 		int cpu = cpumask_any(cs->effective_cpus);
2297 
2298 		dl_bw_free(cpu, cs->sum_migrate_dl_bw);
2299 		reset_migrate_dl_data(cs);
2300 	}
2301 
2302 	mutex_unlock(&cpuset_mutex);
2303 }
2304 
2305 /*
2306  * Protected by cpuset_mutex.  cpus_attach is used only by cpuset_attach()
2307  * but we can't allocate it dynamically there.  Define it global and
2308  * allocate from cpuset_init().
2309  */
2310 static cpumask_var_t cpus_attach;
2311 
cpuset_attach(struct cgroup_taskset * tset)2312 static void cpuset_attach(struct cgroup_taskset *tset)
2313 {
2314 	/* static buf protected by cpuset_mutex */
2315 	static nodemask_t cpuset_attach_nodemask_to;
2316 	struct task_struct *task;
2317 	struct task_struct *leader;
2318 	struct cgroup_subsys_state *css;
2319 	struct cpuset *cs;
2320 	struct cpuset *oldcs = cpuset_attach_old_cs;
2321 
2322 	cgroup_taskset_first(tset, &css);
2323 	cs = css_cs(css);
2324 
2325 	lockdep_assert_cpus_held();	/* see cgroup_attach_lock() */
2326 	mutex_lock(&cpuset_mutex);
2327 
2328 	guarantee_online_mems(cs, &cpuset_attach_nodemask_to);
2329 
2330 	cgroup_taskset_for_each(task, css, tset) {
2331 		if (cs != &top_cpuset)
2332 			guarantee_online_cpus(task, cpus_attach);
2333 		else
2334 			cpumask_copy(cpus_attach, task_cpu_possible_mask(task));
2335 		/*
2336 		 * can_attach beforehand should guarantee that this doesn't
2337 		 * fail.  TODO: have a better way to handle failure here
2338 		 */
2339 		WARN_ON_ONCE(update_cpus_allowed(cs, task, cpus_attach));
2340 
2341 		cpuset_change_task_nodemask(task, &cpuset_attach_nodemask_to);
2342 		cpuset_update_task_spread_flag(cs, task);
2343 	}
2344 
2345 	/*
2346 	 * Change mm for all threadgroup leaders. This is expensive and may
2347 	 * sleep and should be moved outside migration path proper.
2348 	 */
2349 	cpuset_attach_nodemask_to = cs->effective_mems;
2350 	cgroup_taskset_for_each_leader(leader, css, tset) {
2351 		struct mm_struct *mm = get_task_mm(leader);
2352 
2353 		if (mm) {
2354 			mpol_rebind_mm(mm, &cpuset_attach_nodemask_to);
2355 
2356 			/*
2357 			 * old_mems_allowed is the same with mems_allowed
2358 			 * here, except if this task is being moved
2359 			 * automatically due to hotplug.  In that case
2360 			 * @mems_allowed has been updated and is empty, so
2361 			 * @old_mems_allowed is the right nodesets that we
2362 			 * migrate mm from.
2363 			 */
2364 			if (is_memory_migrate(cs))
2365 				cpuset_migrate_mm(mm, &oldcs->old_mems_allowed,
2366 						  &cpuset_attach_nodemask_to);
2367 			else
2368 				mmput(mm);
2369 		}
2370 	}
2371 
2372 	cs->old_mems_allowed = cpuset_attach_nodemask_to;
2373 
2374 	if (cs->nr_migrate_dl_tasks) {
2375 		cs->nr_deadline_tasks += cs->nr_migrate_dl_tasks;
2376 		oldcs->nr_deadline_tasks -= cs->nr_migrate_dl_tasks;
2377 		reset_migrate_dl_data(cs);
2378 	}
2379 
2380 	cs->attach_in_progress--;
2381 	if (!cs->attach_in_progress)
2382 		wake_up(&cpuset_attach_wq);
2383 
2384 	mutex_unlock(&cpuset_mutex);
2385 }
2386 
2387 /* The various types of files and directories in a cpuset file system */
2388 
2389 typedef enum {
2390 	FILE_MEMORY_MIGRATE,
2391 	FILE_CPULIST,
2392 	FILE_MEMLIST,
2393 	FILE_EFFECTIVE_CPULIST,
2394 	FILE_EFFECTIVE_MEMLIST,
2395 	FILE_SUBPARTS_CPULIST,
2396 	FILE_CPU_EXCLUSIVE,
2397 	FILE_MEM_EXCLUSIVE,
2398 	FILE_MEM_HARDWALL,
2399 	FILE_SCHED_LOAD_BALANCE,
2400 	FILE_PARTITION_ROOT,
2401 	FILE_SCHED_RELAX_DOMAIN_LEVEL,
2402 	FILE_MEMORY_PRESSURE_ENABLED,
2403 	FILE_MEMORY_PRESSURE,
2404 	FILE_SPREAD_PAGE,
2405 	FILE_SPREAD_SLAB,
2406 } cpuset_filetype_t;
2407 
cpuset_write_u64(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)2408 static int cpuset_write_u64(struct cgroup_subsys_state *css, struct cftype *cft,
2409 			    u64 val)
2410 {
2411 	struct cpuset *cs = css_cs(css);
2412 	cpuset_filetype_t type = cft->private;
2413 	int retval = 0;
2414 
2415 	get_online_cpus();
2416 	mutex_lock(&cpuset_mutex);
2417 	if (!is_cpuset_online(cs)) {
2418 		retval = -ENODEV;
2419 		goto out_unlock;
2420 	}
2421 
2422 	switch (type) {
2423 	case FILE_CPU_EXCLUSIVE:
2424 		retval = update_flag(CS_CPU_EXCLUSIVE, cs, val);
2425 		break;
2426 	case FILE_MEM_EXCLUSIVE:
2427 		retval = update_flag(CS_MEM_EXCLUSIVE, cs, val);
2428 		break;
2429 	case FILE_MEM_HARDWALL:
2430 		retval = update_flag(CS_MEM_HARDWALL, cs, val);
2431 		break;
2432 	case FILE_SCHED_LOAD_BALANCE:
2433 		retval = update_flag(CS_SCHED_LOAD_BALANCE, cs, val);
2434 		break;
2435 	case FILE_MEMORY_MIGRATE:
2436 		retval = update_flag(CS_MEMORY_MIGRATE, cs, val);
2437 		break;
2438 	case FILE_MEMORY_PRESSURE_ENABLED:
2439 		cpuset_memory_pressure_enabled = !!val;
2440 		break;
2441 	case FILE_SPREAD_PAGE:
2442 		retval = update_flag(CS_SPREAD_PAGE, cs, val);
2443 		break;
2444 	case FILE_SPREAD_SLAB:
2445 		retval = update_flag(CS_SPREAD_SLAB, cs, val);
2446 		break;
2447 	default:
2448 		retval = -EINVAL;
2449 		break;
2450 	}
2451 out_unlock:
2452 	mutex_unlock(&cpuset_mutex);
2453 	put_online_cpus();
2454 	return retval;
2455 }
2456 
cpuset_write_s64(struct cgroup_subsys_state * css,struct cftype * cft,s64 val)2457 static int cpuset_write_s64(struct cgroup_subsys_state *css, struct cftype *cft,
2458 			    s64 val)
2459 {
2460 	struct cpuset *cs = css_cs(css);
2461 	cpuset_filetype_t type = cft->private;
2462 	int retval = -ENODEV;
2463 
2464 	get_online_cpus();
2465 	mutex_lock(&cpuset_mutex);
2466 	if (!is_cpuset_online(cs))
2467 		goto out_unlock;
2468 
2469 	switch (type) {
2470 	case FILE_SCHED_RELAX_DOMAIN_LEVEL:
2471 		retval = update_relax_domain_level(cs, val);
2472 		break;
2473 	default:
2474 		retval = -EINVAL;
2475 		break;
2476 	}
2477 out_unlock:
2478 	mutex_unlock(&cpuset_mutex);
2479 	put_online_cpus();
2480 	return retval;
2481 }
2482 
2483 /*
2484  * Common handling for a write to a "cpus" or "mems" file.
2485  */
cpuset_write_resmask(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)2486 static ssize_t cpuset_write_resmask(struct kernfs_open_file *of,
2487 				    char *buf, size_t nbytes, loff_t off)
2488 {
2489 	struct cpuset *cs = css_cs(of_css(of));
2490 	struct cpuset *trialcs;
2491 	int retval = -ENODEV;
2492 
2493 	buf = strstrip(buf);
2494 
2495 	/*
2496 	 * CPU or memory hotunplug may leave @cs w/o any execution
2497 	 * resources, in which case the hotplug code asynchronously updates
2498 	 * configuration and transfers all tasks to the nearest ancestor
2499 	 * which can execute.
2500 	 *
2501 	 * As writes to "cpus" or "mems" may restore @cs's execution
2502 	 * resources, wait for the previously scheduled operations before
2503 	 * proceeding, so that we don't end up keep removing tasks added
2504 	 * after execution capability is restored.
2505 	 *
2506 	 * cpuset_hotplug_work calls back into cgroup core via
2507 	 * cgroup_transfer_tasks() and waiting for it from a cgroupfs
2508 	 * operation like this one can lead to a deadlock through kernfs
2509 	 * active_ref protection.  Let's break the protection.  Losing the
2510 	 * protection is okay as we check whether @cs is online after
2511 	 * grabbing cpuset_mutex anyway.  This only happens on the legacy
2512 	 * hierarchies.
2513 	 */
2514 	css_get(&cs->css);
2515 	kernfs_break_active_protection(of->kn);
2516 	flush_work(&cpuset_hotplug_work);
2517 
2518 	get_online_cpus();
2519 	mutex_lock(&cpuset_mutex);
2520 	if (!is_cpuset_online(cs))
2521 		goto out_unlock;
2522 
2523 	trialcs = alloc_trial_cpuset(cs);
2524 	if (!trialcs) {
2525 		retval = -ENOMEM;
2526 		goto out_unlock;
2527 	}
2528 
2529 	switch (of_cft(of)->private) {
2530 	case FILE_CPULIST:
2531 		retval = update_cpumask(cs, trialcs, buf);
2532 		break;
2533 	case FILE_MEMLIST:
2534 		retval = update_nodemask(cs, trialcs, buf);
2535 		break;
2536 	default:
2537 		retval = -EINVAL;
2538 		break;
2539 	}
2540 
2541 	free_cpuset(trialcs);
2542 out_unlock:
2543 	mutex_unlock(&cpuset_mutex);
2544 	put_online_cpus();
2545 	kernfs_unbreak_active_protection(of->kn);
2546 	css_put(&cs->css);
2547 	flush_workqueue(cpuset_migrate_mm_wq);
2548 	return retval ?: nbytes;
2549 }
2550 
2551 /*
2552  * These ascii lists should be read in a single call, by using a user
2553  * buffer large enough to hold the entire map.  If read in smaller
2554  * chunks, there is no guarantee of atomicity.  Since the display format
2555  * used, list of ranges of sequential numbers, is variable length,
2556  * and since these maps can change value dynamically, one could read
2557  * gibberish by doing partial reads while a list was changing.
2558  */
cpuset_common_seq_show(struct seq_file * sf,void * v)2559 static int cpuset_common_seq_show(struct seq_file *sf, void *v)
2560 {
2561 	struct cpuset *cs = css_cs(seq_css(sf));
2562 	cpuset_filetype_t type = seq_cft(sf)->private;
2563 	int ret = 0;
2564 
2565 	spin_lock_irq(&callback_lock);
2566 
2567 	switch (type) {
2568 	case FILE_CPULIST:
2569 		seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->cpus_requested));
2570 		break;
2571 	case FILE_MEMLIST:
2572 		seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->mems_allowed));
2573 		break;
2574 	case FILE_EFFECTIVE_CPULIST:
2575 		seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->effective_cpus));
2576 		break;
2577 	case FILE_EFFECTIVE_MEMLIST:
2578 		seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->effective_mems));
2579 		break;
2580 	case FILE_SUBPARTS_CPULIST:
2581 		seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->subparts_cpus));
2582 		break;
2583 	default:
2584 		ret = -EINVAL;
2585 	}
2586 
2587 	spin_unlock_irq(&callback_lock);
2588 	return ret;
2589 }
2590 
cpuset_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)2591 static u64 cpuset_read_u64(struct cgroup_subsys_state *css, struct cftype *cft)
2592 {
2593 	struct cpuset *cs = css_cs(css);
2594 	cpuset_filetype_t type = cft->private;
2595 	switch (type) {
2596 	case FILE_CPU_EXCLUSIVE:
2597 		return is_cpu_exclusive(cs);
2598 	case FILE_MEM_EXCLUSIVE:
2599 		return is_mem_exclusive(cs);
2600 	case FILE_MEM_HARDWALL:
2601 		return is_mem_hardwall(cs);
2602 	case FILE_SCHED_LOAD_BALANCE:
2603 		return is_sched_load_balance(cs);
2604 	case FILE_MEMORY_MIGRATE:
2605 		return is_memory_migrate(cs);
2606 	case FILE_MEMORY_PRESSURE_ENABLED:
2607 		return cpuset_memory_pressure_enabled;
2608 	case FILE_MEMORY_PRESSURE:
2609 		return fmeter_getrate(&cs->fmeter);
2610 	case FILE_SPREAD_PAGE:
2611 		return is_spread_page(cs);
2612 	case FILE_SPREAD_SLAB:
2613 		return is_spread_slab(cs);
2614 	default:
2615 		BUG();
2616 	}
2617 
2618 	/* Unreachable but makes gcc happy */
2619 	return 0;
2620 }
2621 
cpuset_read_s64(struct cgroup_subsys_state * css,struct cftype * cft)2622 static s64 cpuset_read_s64(struct cgroup_subsys_state *css, struct cftype *cft)
2623 {
2624 	struct cpuset *cs = css_cs(css);
2625 	cpuset_filetype_t type = cft->private;
2626 	switch (type) {
2627 	case FILE_SCHED_RELAX_DOMAIN_LEVEL:
2628 		return cs->relax_domain_level;
2629 	default:
2630 		BUG();
2631 	}
2632 
2633 	/* Unrechable but makes gcc happy */
2634 	return 0;
2635 }
2636 
sched_partition_show(struct seq_file * seq,void * v)2637 static int sched_partition_show(struct seq_file *seq, void *v)
2638 {
2639 	struct cpuset *cs = css_cs(seq_css(seq));
2640 
2641 	switch (cs->partition_root_state) {
2642 	case PRS_ENABLED:
2643 		seq_puts(seq, "root\n");
2644 		break;
2645 	case PRS_DISABLED:
2646 		seq_puts(seq, "member\n");
2647 		break;
2648 	case PRS_ERROR:
2649 		seq_puts(seq, "root invalid\n");
2650 		break;
2651 	}
2652 	return 0;
2653 }
2654 
sched_partition_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)2655 static ssize_t sched_partition_write(struct kernfs_open_file *of, char *buf,
2656 				     size_t nbytes, loff_t off)
2657 {
2658 	struct cpuset *cs = css_cs(of_css(of));
2659 	int val;
2660 	int retval = -ENODEV;
2661 
2662 	buf = strstrip(buf);
2663 
2664 	/*
2665 	 * Convert "root" to ENABLED, and convert "member" to DISABLED.
2666 	 */
2667 	if (!strcmp(buf, "root"))
2668 		val = PRS_ENABLED;
2669 	else if (!strcmp(buf, "member"))
2670 		val = PRS_DISABLED;
2671 	else
2672 		return -EINVAL;
2673 
2674 	css_get(&cs->css);
2675 	get_online_cpus();
2676 	mutex_lock(&cpuset_mutex);
2677 	if (!is_cpuset_online(cs))
2678 		goto out_unlock;
2679 
2680 	retval = update_prstate(cs, val);
2681 out_unlock:
2682 	mutex_unlock(&cpuset_mutex);
2683 	put_online_cpus();
2684 	css_put(&cs->css);
2685 	return retval ?: nbytes;
2686 }
2687 
2688 /*
2689  * for the common functions, 'private' gives the type of file
2690  */
2691 
2692 static struct cftype legacy_files[] = {
2693 	{
2694 		.name = "cpus",
2695 		.seq_show = cpuset_common_seq_show,
2696 		.write = cpuset_write_resmask,
2697 		.max_write_len = (100U + 6 * NR_CPUS),
2698 		.private = FILE_CPULIST,
2699 	},
2700 
2701 	{
2702 		.name = "mems",
2703 		.seq_show = cpuset_common_seq_show,
2704 		.write = cpuset_write_resmask,
2705 		.max_write_len = (100U + 6 * MAX_NUMNODES),
2706 		.private = FILE_MEMLIST,
2707 	},
2708 
2709 	{
2710 		.name = "effective_cpus",
2711 		.seq_show = cpuset_common_seq_show,
2712 		.private = FILE_EFFECTIVE_CPULIST,
2713 	},
2714 
2715 	{
2716 		.name = "effective_mems",
2717 		.seq_show = cpuset_common_seq_show,
2718 		.private = FILE_EFFECTIVE_MEMLIST,
2719 	},
2720 
2721 	{
2722 		.name = "cpu_exclusive",
2723 		.read_u64 = cpuset_read_u64,
2724 		.write_u64 = cpuset_write_u64,
2725 		.private = FILE_CPU_EXCLUSIVE,
2726 	},
2727 
2728 	{
2729 		.name = "mem_exclusive",
2730 		.read_u64 = cpuset_read_u64,
2731 		.write_u64 = cpuset_write_u64,
2732 		.private = FILE_MEM_EXCLUSIVE,
2733 	},
2734 
2735 	{
2736 		.name = "mem_hardwall",
2737 		.read_u64 = cpuset_read_u64,
2738 		.write_u64 = cpuset_write_u64,
2739 		.private = FILE_MEM_HARDWALL,
2740 	},
2741 
2742 	{
2743 		.name = "sched_load_balance",
2744 		.read_u64 = cpuset_read_u64,
2745 		.write_u64 = cpuset_write_u64,
2746 		.private = FILE_SCHED_LOAD_BALANCE,
2747 	},
2748 
2749 	{
2750 		.name = "sched_relax_domain_level",
2751 		.read_s64 = cpuset_read_s64,
2752 		.write_s64 = cpuset_write_s64,
2753 		.private = FILE_SCHED_RELAX_DOMAIN_LEVEL,
2754 	},
2755 
2756 	{
2757 		.name = "memory_migrate",
2758 		.read_u64 = cpuset_read_u64,
2759 		.write_u64 = cpuset_write_u64,
2760 		.private = FILE_MEMORY_MIGRATE,
2761 	},
2762 
2763 	{
2764 		.name = "memory_pressure",
2765 		.read_u64 = cpuset_read_u64,
2766 		.private = FILE_MEMORY_PRESSURE,
2767 	},
2768 
2769 	{
2770 		.name = "memory_spread_page",
2771 		.read_u64 = cpuset_read_u64,
2772 		.write_u64 = cpuset_write_u64,
2773 		.private = FILE_SPREAD_PAGE,
2774 	},
2775 
2776 	{
2777 		.name = "memory_spread_slab",
2778 		.read_u64 = cpuset_read_u64,
2779 		.write_u64 = cpuset_write_u64,
2780 		.private = FILE_SPREAD_SLAB,
2781 	},
2782 
2783 	{
2784 		.name = "memory_pressure_enabled",
2785 		.flags = CFTYPE_ONLY_ON_ROOT,
2786 		.read_u64 = cpuset_read_u64,
2787 		.write_u64 = cpuset_write_u64,
2788 		.private = FILE_MEMORY_PRESSURE_ENABLED,
2789 	},
2790 
2791 	{ }	/* terminate */
2792 };
2793 
2794 /*
2795  * This is currently a minimal set for the default hierarchy. It can be
2796  * expanded later on by migrating more features and control files from v1.
2797  */
2798 static struct cftype dfl_files[] = {
2799 	{
2800 		.name = "cpus",
2801 		.seq_show = cpuset_common_seq_show,
2802 		.write = cpuset_write_resmask,
2803 		.max_write_len = (100U + 6 * NR_CPUS),
2804 		.private = FILE_CPULIST,
2805 		.flags = CFTYPE_NOT_ON_ROOT,
2806 	},
2807 
2808 	{
2809 		.name = "mems",
2810 		.seq_show = cpuset_common_seq_show,
2811 		.write = cpuset_write_resmask,
2812 		.max_write_len = (100U + 6 * MAX_NUMNODES),
2813 		.private = FILE_MEMLIST,
2814 		.flags = CFTYPE_NOT_ON_ROOT,
2815 	},
2816 
2817 	{
2818 		.name = "cpus.effective",
2819 		.seq_show = cpuset_common_seq_show,
2820 		.private = FILE_EFFECTIVE_CPULIST,
2821 	},
2822 
2823 	{
2824 		.name = "mems.effective",
2825 		.seq_show = cpuset_common_seq_show,
2826 		.private = FILE_EFFECTIVE_MEMLIST,
2827 	},
2828 
2829 	{
2830 		.name = "cpus.partition",
2831 		.seq_show = sched_partition_show,
2832 		.write = sched_partition_write,
2833 		.private = FILE_PARTITION_ROOT,
2834 		.flags = CFTYPE_NOT_ON_ROOT,
2835 	},
2836 
2837 	{
2838 		.name = "cpus.subpartitions",
2839 		.seq_show = cpuset_common_seq_show,
2840 		.private = FILE_SUBPARTS_CPULIST,
2841 		.flags = CFTYPE_DEBUG,
2842 	},
2843 
2844 	{ }	/* terminate */
2845 };
2846 
2847 
2848 /*
2849  *	cpuset_css_alloc - allocate a cpuset css
2850  *	cgrp:	control group that the new cpuset will be part of
2851  */
2852 
2853 static struct cgroup_subsys_state *
cpuset_css_alloc(struct cgroup_subsys_state * parent_css)2854 cpuset_css_alloc(struct cgroup_subsys_state *parent_css)
2855 {
2856 	struct cpuset *cs;
2857 
2858 	if (!parent_css)
2859 		return &top_cpuset.css;
2860 
2861 	cs = kzalloc(sizeof(*cs), GFP_KERNEL);
2862 	if (!cs)
2863 		return ERR_PTR(-ENOMEM);
2864 
2865 	if (alloc_cpumasks(cs, NULL)) {
2866 		kfree(cs);
2867 		return ERR_PTR(-ENOMEM);
2868 	}
2869 
2870 	set_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
2871 	nodes_clear(cs->mems_allowed);
2872 	nodes_clear(cs->effective_mems);
2873 	fmeter_init(&cs->fmeter);
2874 	cs->relax_domain_level = -1;
2875 
2876 	return &cs->css;
2877 }
2878 
cpuset_css_online(struct cgroup_subsys_state * css)2879 static int cpuset_css_online(struct cgroup_subsys_state *css)
2880 {
2881 	struct cpuset *cs = css_cs(css);
2882 	struct cpuset *parent = parent_cs(cs);
2883 	struct cpuset *tmp_cs;
2884 	struct cgroup_subsys_state *pos_css;
2885 
2886 	if (!parent)
2887 		return 0;
2888 
2889 	get_online_cpus();
2890 	mutex_lock(&cpuset_mutex);
2891 
2892 	set_bit(CS_ONLINE, &cs->flags);
2893 	if (is_spread_page(parent))
2894 		set_bit(CS_SPREAD_PAGE, &cs->flags);
2895 	if (is_spread_slab(parent))
2896 		set_bit(CS_SPREAD_SLAB, &cs->flags);
2897 
2898 	cpuset_inc();
2899 
2900 	spin_lock_irq(&callback_lock);
2901 	if (is_in_v2_mode()) {
2902 		cpumask_copy(cs->effective_cpus, parent->effective_cpus);
2903 		cs->effective_mems = parent->effective_mems;
2904 		cs->use_parent_ecpus = true;
2905 		parent->child_ecpus_count++;
2906 	}
2907 	spin_unlock_irq(&callback_lock);
2908 
2909 	if (!test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags))
2910 		goto out_unlock;
2911 
2912 	/*
2913 	 * Clone @parent's configuration if CGRP_CPUSET_CLONE_CHILDREN is
2914 	 * set.  This flag handling is implemented in cgroup core for
2915 	 * histrical reasons - the flag may be specified during mount.
2916 	 *
2917 	 * Currently, if any sibling cpusets have exclusive cpus or mem, we
2918 	 * refuse to clone the configuration - thereby refusing the task to
2919 	 * be entered, and as a result refusing the sys_unshare() or
2920 	 * clone() which initiated it.  If this becomes a problem for some
2921 	 * users who wish to allow that scenario, then this could be
2922 	 * changed to grant parent->cpus_allowed-sibling_cpus_exclusive
2923 	 * (and likewise for mems) to the new cgroup.
2924 	 */
2925 	rcu_read_lock();
2926 	cpuset_for_each_child(tmp_cs, pos_css, parent) {
2927 		if (is_mem_exclusive(tmp_cs) || is_cpu_exclusive(tmp_cs)) {
2928 			rcu_read_unlock();
2929 			goto out_unlock;
2930 		}
2931 	}
2932 	rcu_read_unlock();
2933 
2934 	spin_lock_irq(&callback_lock);
2935 	cs->mems_allowed = parent->mems_allowed;
2936 	cs->effective_mems = parent->mems_allowed;
2937 	cpumask_copy(cs->cpus_allowed, parent->cpus_allowed);
2938 	cpumask_copy(cs->cpus_requested, parent->cpus_requested);
2939 	cpumask_copy(cs->effective_cpus, parent->cpus_allowed);
2940 	spin_unlock_irq(&callback_lock);
2941 out_unlock:
2942 	mutex_unlock(&cpuset_mutex);
2943 	put_online_cpus();
2944 	return 0;
2945 }
2946 
2947 /*
2948  * If the cpuset being removed has its flag 'sched_load_balance'
2949  * enabled, then simulate turning sched_load_balance off, which
2950  * will call rebuild_sched_domains_locked(). That is not needed
2951  * in the default hierarchy where only changes in partition
2952  * will cause repartitioning.
2953  *
2954  * If the cpuset has the 'sched.partition' flag enabled, simulate
2955  * turning 'sched.partition" off.
2956  */
2957 
cpuset_css_offline(struct cgroup_subsys_state * css)2958 static void cpuset_css_offline(struct cgroup_subsys_state *css)
2959 {
2960 	struct cpuset *cs = css_cs(css);
2961 
2962 	get_online_cpus();
2963 	mutex_lock(&cpuset_mutex);
2964 
2965 	if (is_partition_root(cs))
2966 		update_prstate(cs, 0);
2967 
2968 	if (!cgroup_subsys_on_dfl(cpuset_cgrp_subsys) &&
2969 	    is_sched_load_balance(cs))
2970 		update_flag(CS_SCHED_LOAD_BALANCE, cs, 0);
2971 
2972 	if (cs->use_parent_ecpus) {
2973 		struct cpuset *parent = parent_cs(cs);
2974 
2975 		cs->use_parent_ecpus = false;
2976 		parent->child_ecpus_count--;
2977 	}
2978 
2979 	cpuset_dec();
2980 	clear_bit(CS_ONLINE, &cs->flags);
2981 
2982 	mutex_unlock(&cpuset_mutex);
2983 	put_online_cpus();
2984 }
2985 
cpuset_css_free(struct cgroup_subsys_state * css)2986 static void cpuset_css_free(struct cgroup_subsys_state *css)
2987 {
2988 	struct cpuset *cs = css_cs(css);
2989 
2990 	free_cpuset(cs);
2991 }
2992 
cpuset_bind(struct cgroup_subsys_state * root_css)2993 static void cpuset_bind(struct cgroup_subsys_state *root_css)
2994 {
2995 	mutex_lock(&cpuset_mutex);
2996 	spin_lock_irq(&callback_lock);
2997 
2998 	if (is_in_v2_mode()) {
2999 		cpumask_copy(top_cpuset.cpus_allowed, cpu_possible_mask);
3000 		top_cpuset.mems_allowed = node_possible_map;
3001 	} else {
3002 		cpumask_copy(top_cpuset.cpus_allowed,
3003 			     top_cpuset.effective_cpus);
3004 		top_cpuset.mems_allowed = top_cpuset.effective_mems;
3005 	}
3006 
3007 	spin_unlock_irq(&callback_lock);
3008 	mutex_unlock(&cpuset_mutex);
3009 }
3010 
3011 /*
3012  * Make sure the new task conform to the current state of its parent,
3013  * which could have been changed by cpuset just after it inherits the
3014  * state from the parent and before it sits on the cgroup's task list.
3015  */
cpuset_fork(struct task_struct * task)3016 static void cpuset_fork(struct task_struct *task)
3017 {
3018 	int inherit_cpus = 0;
3019 	if (task_css_is_root(task, cpuset_cgrp_id))
3020 		return;
3021 
3022 	trace_android_rvh_cpuset_fork(task, &inherit_cpus);
3023 	if (!inherit_cpus)
3024 		set_cpus_allowed_ptr(task, current->cpus_ptr);
3025 	task->mems_allowed = current->mems_allowed;
3026 }
3027 
3028 struct cgroup_subsys cpuset_cgrp_subsys = {
3029 	.css_alloc	= cpuset_css_alloc,
3030 	.css_online	= cpuset_css_online,
3031 	.css_offline	= cpuset_css_offline,
3032 	.css_free	= cpuset_css_free,
3033 	.can_attach	= cpuset_can_attach,
3034 	.cancel_attach	= cpuset_cancel_attach,
3035 	.attach		= cpuset_attach,
3036 	.post_attach	= cpuset_post_attach,
3037 	.bind		= cpuset_bind,
3038 	.fork		= cpuset_fork,
3039 	.legacy_cftypes	= legacy_files,
3040 	.dfl_cftypes	= dfl_files,
3041 	.early_init	= true,
3042 	.threaded	= true,
3043 };
3044 
3045 /**
3046  * cpuset_init - initialize cpusets at system boot
3047  *
3048  * Description: Initialize top_cpuset
3049  **/
3050 
cpuset_init(void)3051 int __init cpuset_init(void)
3052 {
3053 	BUG_ON(!alloc_cpumask_var(&top_cpuset.cpus_allowed, GFP_KERNEL));
3054 	BUG_ON(!alloc_cpumask_var(&top_cpuset.effective_cpus, GFP_KERNEL));
3055 	BUG_ON(!zalloc_cpumask_var(&top_cpuset.subparts_cpus, GFP_KERNEL));
3056 	BUG_ON(!alloc_cpumask_var(&top_cpuset.cpus_requested, GFP_KERNEL));
3057 
3058 	cpumask_setall(top_cpuset.cpus_allowed);
3059 	cpumask_setall(top_cpuset.cpus_requested);
3060 	nodes_setall(top_cpuset.mems_allowed);
3061 	cpumask_setall(top_cpuset.effective_cpus);
3062 	nodes_setall(top_cpuset.effective_mems);
3063 
3064 	fmeter_init(&top_cpuset.fmeter);
3065 	set_bit(CS_SCHED_LOAD_BALANCE, &top_cpuset.flags);
3066 	top_cpuset.relax_domain_level = -1;
3067 
3068 	BUG_ON(!alloc_cpumask_var(&cpus_attach, GFP_KERNEL));
3069 
3070 	return 0;
3071 }
3072 
3073 /*
3074  * If CPU and/or memory hotplug handlers, below, unplug any CPUs
3075  * or memory nodes, we need to walk over the cpuset hierarchy,
3076  * removing that CPU or node from all cpusets.  If this removes the
3077  * last CPU or node from a cpuset, then move the tasks in the empty
3078  * cpuset to its next-highest non-empty parent.
3079  */
remove_tasks_in_empty_cpuset(struct cpuset * cs)3080 static void remove_tasks_in_empty_cpuset(struct cpuset *cs)
3081 {
3082 	struct cpuset *parent;
3083 
3084 	/*
3085 	 * Find its next-highest non-empty parent, (top cpuset
3086 	 * has online cpus, so can't be empty).
3087 	 */
3088 	parent = parent_cs(cs);
3089 	while (cpumask_empty(parent->cpus_allowed) ||
3090 			nodes_empty(parent->mems_allowed))
3091 		parent = parent_cs(parent);
3092 
3093 	if (cgroup_transfer_tasks(parent->css.cgroup, cs->css.cgroup)) {
3094 		pr_err("cpuset: failed to transfer tasks out of empty cpuset ");
3095 		pr_cont_cgroup_name(cs->css.cgroup);
3096 		pr_cont("\n");
3097 	}
3098 }
3099 
3100 static void
hotplug_update_tasks_legacy(struct cpuset * cs,struct cpumask * new_cpus,nodemask_t * new_mems,bool cpus_updated,bool mems_updated)3101 hotplug_update_tasks_legacy(struct cpuset *cs,
3102 			    struct cpumask *new_cpus, nodemask_t *new_mems,
3103 			    bool cpus_updated, bool mems_updated)
3104 {
3105 	bool is_empty;
3106 
3107 	spin_lock_irq(&callback_lock);
3108 	cpumask_copy(cs->cpus_allowed, new_cpus);
3109 	cpumask_copy(cs->effective_cpus, new_cpus);
3110 	cs->mems_allowed = *new_mems;
3111 	cs->effective_mems = *new_mems;
3112 	spin_unlock_irq(&callback_lock);
3113 
3114 	/*
3115 	 * Don't call update_tasks_cpumask() if the cpuset becomes empty,
3116 	 * as the tasks will be migratecd to an ancestor.
3117 	 */
3118 	if (cpus_updated && !cpumask_empty(cs->cpus_allowed))
3119 		update_tasks_cpumask(cs);
3120 	if (mems_updated && !nodes_empty(cs->mems_allowed))
3121 		update_tasks_nodemask(cs);
3122 
3123 	is_empty = cpumask_empty(cs->cpus_allowed) ||
3124 		   nodes_empty(cs->mems_allowed);
3125 
3126 	mutex_unlock(&cpuset_mutex);
3127 
3128 	/*
3129 	 * Move tasks to the nearest ancestor with execution resources,
3130 	 * This is full cgroup operation which will also call back into
3131 	 * cpuset. Should be done outside any lock.
3132 	 */
3133 	if (is_empty)
3134 		remove_tasks_in_empty_cpuset(cs);
3135 
3136 	mutex_lock(&cpuset_mutex);
3137 }
3138 
3139 static void
hotplug_update_tasks(struct cpuset * cs,struct cpumask * new_cpus,nodemask_t * new_mems,bool cpus_updated,bool mems_updated)3140 hotplug_update_tasks(struct cpuset *cs,
3141 		     struct cpumask *new_cpus, nodemask_t *new_mems,
3142 		     bool cpus_updated, bool mems_updated)
3143 {
3144 	if (cpumask_empty(new_cpus))
3145 		cpumask_copy(new_cpus, parent_cs(cs)->effective_cpus);
3146 	if (nodes_empty(*new_mems))
3147 		*new_mems = parent_cs(cs)->effective_mems;
3148 
3149 	spin_lock_irq(&callback_lock);
3150 	cpumask_copy(cs->effective_cpus, new_cpus);
3151 	cs->effective_mems = *new_mems;
3152 	spin_unlock_irq(&callback_lock);
3153 
3154 	if (cpus_updated)
3155 		update_tasks_cpumask(cs);
3156 	if (mems_updated)
3157 		update_tasks_nodemask(cs);
3158 }
3159 
3160 static bool force_rebuild;
3161 
cpuset_force_rebuild(void)3162 void cpuset_force_rebuild(void)
3163 {
3164 	force_rebuild = true;
3165 }
3166 
3167 /**
3168  * cpuset_hotplug_update_tasks - update tasks in a cpuset for hotunplug
3169  * @cs: cpuset in interest
3170  * @tmp: the tmpmasks structure pointer
3171  *
3172  * Compare @cs's cpu and mem masks against top_cpuset and if some have gone
3173  * offline, update @cs accordingly.  If @cs ends up with no CPU or memory,
3174  * all its tasks are moved to the nearest ancestor with both resources.
3175  */
cpuset_hotplug_update_tasks(struct cpuset * cs,struct tmpmasks * tmp)3176 static void cpuset_hotplug_update_tasks(struct cpuset *cs, struct tmpmasks *tmp)
3177 {
3178 	static cpumask_t new_cpus;
3179 	static nodemask_t new_mems;
3180 	bool cpus_updated;
3181 	bool mems_updated;
3182 	struct cpuset *parent;
3183 retry:
3184 	wait_event(cpuset_attach_wq, cs->attach_in_progress == 0);
3185 
3186 	mutex_lock(&cpuset_mutex);
3187 
3188 	/*
3189 	 * We have raced with task attaching. We wait until attaching
3190 	 * is finished, so we won't attach a task to an empty cpuset.
3191 	 */
3192 	if (cs->attach_in_progress) {
3193 		mutex_unlock(&cpuset_mutex);
3194 		goto retry;
3195 	}
3196 
3197 	parent = parent_cs(cs);
3198 	compute_effective_cpumask(&new_cpus, cs, parent);
3199 	nodes_and(new_mems, cs->mems_allowed, parent->effective_mems);
3200 
3201 	if (cs->nr_subparts_cpus)
3202 		/*
3203 		 * Make sure that CPUs allocated to child partitions
3204 		 * do not show up in effective_cpus.
3205 		 */
3206 		cpumask_andnot(&new_cpus, &new_cpus, cs->subparts_cpus);
3207 
3208 	if (!tmp || !cs->partition_root_state)
3209 		goto update_tasks;
3210 
3211 	/*
3212 	 * In the unlikely event that a partition root has empty
3213 	 * effective_cpus or its parent becomes erroneous, we have to
3214 	 * transition it to the erroneous state.
3215 	 */
3216 	if (is_partition_root(cs) && (cpumask_empty(&new_cpus) ||
3217 	   (parent->partition_root_state == PRS_ERROR))) {
3218 		if (cs->nr_subparts_cpus) {
3219 			spin_lock_irq(&callback_lock);
3220 			cs->nr_subparts_cpus = 0;
3221 			cpumask_clear(cs->subparts_cpus);
3222 			spin_unlock_irq(&callback_lock);
3223 			compute_effective_cpumask(&new_cpus, cs, parent);
3224 		}
3225 
3226 		/*
3227 		 * If the effective_cpus is empty because the child
3228 		 * partitions take away all the CPUs, we can keep
3229 		 * the current partition and let the child partitions
3230 		 * fight for available CPUs.
3231 		 */
3232 		if ((parent->partition_root_state == PRS_ERROR) ||
3233 		     cpumask_empty(&new_cpus)) {
3234 			update_parent_subparts_cpumask(cs, partcmd_disable,
3235 						       NULL, tmp);
3236 			spin_lock_irq(&callback_lock);
3237 			cs->partition_root_state = PRS_ERROR;
3238 			spin_unlock_irq(&callback_lock);
3239 		}
3240 		cpuset_force_rebuild();
3241 	}
3242 
3243 	/*
3244 	 * On the other hand, an erroneous partition root may be transitioned
3245 	 * back to a regular one or a partition root with no CPU allocated
3246 	 * from the parent may change to erroneous.
3247 	 */
3248 	if (is_partition_root(parent) &&
3249 	   ((cs->partition_root_state == PRS_ERROR) ||
3250 	    !cpumask_intersects(&new_cpus, parent->subparts_cpus)) &&
3251 	     update_parent_subparts_cpumask(cs, partcmd_update, NULL, tmp))
3252 		cpuset_force_rebuild();
3253 
3254 update_tasks:
3255 	cpus_updated = !cpumask_equal(&new_cpus, cs->effective_cpus);
3256 	mems_updated = !nodes_equal(new_mems, cs->effective_mems);
3257 
3258 	if (is_in_v2_mode())
3259 		hotplug_update_tasks(cs, &new_cpus, &new_mems,
3260 				     cpus_updated, mems_updated);
3261 	else
3262 		hotplug_update_tasks_legacy(cs, &new_cpus, &new_mems,
3263 					    cpus_updated, mems_updated);
3264 
3265 	mutex_unlock(&cpuset_mutex);
3266 }
3267 
3268 /**
3269  * cpuset_hotplug_workfn - handle CPU/memory hotunplug for a cpuset
3270  *
3271  * This function is called after either CPU or memory configuration has
3272  * changed and updates cpuset accordingly.  The top_cpuset is always
3273  * synchronized to cpu_active_mask and N_MEMORY, which is necessary in
3274  * order to make cpusets transparent (of no affect) on systems that are
3275  * actively using CPU hotplug but making no active use of cpusets.
3276  *
3277  * Non-root cpusets are only affected by offlining.  If any CPUs or memory
3278  * nodes have been taken down, cpuset_hotplug_update_tasks() is invoked on
3279  * all descendants.
3280  *
3281  * Note that CPU offlining during suspend is ignored.  We don't modify
3282  * cpusets across suspend/resume cycles at all.
3283  */
cpuset_hotplug_workfn(struct work_struct * work)3284 void cpuset_hotplug_workfn(struct work_struct *work)
3285 {
3286 	static cpumask_t new_cpus;
3287 	static nodemask_t new_mems;
3288 	bool cpus_updated, mems_updated;
3289 	bool on_dfl = is_in_v2_mode();
3290 	struct tmpmasks tmp, *ptmp = NULL;
3291 
3292 	if (on_dfl && !alloc_cpumasks(NULL, &tmp))
3293 		ptmp = &tmp;
3294 
3295 	mutex_lock(&cpuset_mutex);
3296 
3297 	/* fetch the available cpus/mems and find out which changed how */
3298 	cpumask_copy(&new_cpus, cpu_active_mask);
3299 	new_mems = node_states[N_MEMORY];
3300 
3301 	/*
3302 	 * If subparts_cpus is populated, it is likely that the check below
3303 	 * will produce a false positive on cpus_updated when the cpu list
3304 	 * isn't changed. It is extra work, but it is better to be safe.
3305 	 */
3306 	cpus_updated = !cpumask_equal(top_cpuset.effective_cpus, &new_cpus);
3307 	mems_updated = !nodes_equal(top_cpuset.effective_mems, new_mems);
3308 
3309 	/*
3310 	 * In the rare case that hotplug removes all the cpus in subparts_cpus,
3311 	 * we assumed that cpus are updated.
3312 	 */
3313 	if (!cpus_updated && top_cpuset.nr_subparts_cpus)
3314 		cpus_updated = true;
3315 
3316 	/* synchronize cpus_allowed to cpu_active_mask */
3317 	if (cpus_updated) {
3318 		spin_lock_irq(&callback_lock);
3319 		if (!on_dfl)
3320 			cpumask_copy(top_cpuset.cpus_allowed, &new_cpus);
3321 		/*
3322 		 * Make sure that CPUs allocated to child partitions
3323 		 * do not show up in effective_cpus. If no CPU is left,
3324 		 * we clear the subparts_cpus & let the child partitions
3325 		 * fight for the CPUs again.
3326 		 */
3327 		if (top_cpuset.nr_subparts_cpus) {
3328 			if (cpumask_subset(&new_cpus,
3329 					   top_cpuset.subparts_cpus)) {
3330 				top_cpuset.nr_subparts_cpus = 0;
3331 				cpumask_clear(top_cpuset.subparts_cpus);
3332 			} else {
3333 				cpumask_andnot(&new_cpus, &new_cpus,
3334 					       top_cpuset.subparts_cpus);
3335 			}
3336 		}
3337 		cpumask_copy(top_cpuset.effective_cpus, &new_cpus);
3338 		spin_unlock_irq(&callback_lock);
3339 		/* we don't mess with cpumasks of tasks in top_cpuset */
3340 	}
3341 
3342 	/* synchronize mems_allowed to N_MEMORY */
3343 	if (mems_updated) {
3344 		spin_lock_irq(&callback_lock);
3345 		if (!on_dfl)
3346 			top_cpuset.mems_allowed = new_mems;
3347 		top_cpuset.effective_mems = new_mems;
3348 		spin_unlock_irq(&callback_lock);
3349 		update_tasks_nodemask(&top_cpuset);
3350 	}
3351 
3352 	mutex_unlock(&cpuset_mutex);
3353 
3354 	/* if cpus or mems changed, we need to propagate to descendants */
3355 	if (cpus_updated || mems_updated) {
3356 		struct cpuset *cs;
3357 		struct cgroup_subsys_state *pos_css;
3358 
3359 		rcu_read_lock();
3360 		cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
3361 			if (cs == &top_cpuset || !css_tryget_online(&cs->css))
3362 				continue;
3363 			rcu_read_unlock();
3364 
3365 			cpuset_hotplug_update_tasks(cs, ptmp);
3366 
3367 			rcu_read_lock();
3368 			css_put(&cs->css);
3369 		}
3370 		rcu_read_unlock();
3371 	}
3372 
3373 	/* rebuild sched domains if cpus_allowed has changed */
3374 	if (cpus_updated || force_rebuild) {
3375 		force_rebuild = false;
3376 		rebuild_sched_domains();
3377 	}
3378 
3379 	free_cpumasks(NULL, ptmp);
3380 }
3381 
cpuset_update_active_cpus(void)3382 void cpuset_update_active_cpus(void)
3383 {
3384 	/*
3385 	 * We're inside cpu hotplug critical region which usually nests
3386 	 * inside cgroup synchronization.  Bounce actual hotplug processing
3387 	 * to a work item to avoid reverse locking order.
3388 	 */
3389 	schedule_work(&cpuset_hotplug_work);
3390 }
3391 
cpuset_update_active_cpus_affine(int cpu)3392 void cpuset_update_active_cpus_affine(int cpu)
3393 {
3394 	schedule_work_on(cpu, &cpuset_hotplug_work);
3395 }
3396 
cpuset_wait_for_hotplug(void)3397 void cpuset_wait_for_hotplug(void)
3398 {
3399 	flush_work(&cpuset_hotplug_work);
3400 }
3401 
3402 /*
3403  * Keep top_cpuset.mems_allowed tracking node_states[N_MEMORY].
3404  * Call this routine anytime after node_states[N_MEMORY] changes.
3405  * See cpuset_update_active_cpus() for CPU hotplug handling.
3406  */
cpuset_track_online_nodes(struct notifier_block * self,unsigned long action,void * arg)3407 static int cpuset_track_online_nodes(struct notifier_block *self,
3408 				unsigned long action, void *arg)
3409 {
3410 	schedule_work(&cpuset_hotplug_work);
3411 	return NOTIFY_OK;
3412 }
3413 
3414 static struct notifier_block cpuset_track_online_nodes_nb = {
3415 	.notifier_call = cpuset_track_online_nodes,
3416 	.priority = 10,		/* ??! */
3417 };
3418 
3419 /**
3420  * cpuset_init_smp - initialize cpus_allowed
3421  *
3422  * Description: Finish top cpuset after cpu, node maps are initialized
3423  */
cpuset_init_smp(void)3424 void __init cpuset_init_smp(void)
3425 {
3426 	/*
3427 	 * cpus_allowd/mems_allowed set to v2 values in the initial
3428 	 * cpuset_bind() call will be reset to v1 values in another
3429 	 * cpuset_bind() call when v1 cpuset is mounted.
3430 	 */
3431 	top_cpuset.old_mems_allowed = top_cpuset.mems_allowed;
3432 
3433 	cpumask_copy(top_cpuset.effective_cpus, cpu_active_mask);
3434 	top_cpuset.effective_mems = node_states[N_MEMORY];
3435 
3436 	register_hotmemory_notifier(&cpuset_track_online_nodes_nb);
3437 
3438 	cpuset_migrate_mm_wq = alloc_ordered_workqueue("cpuset_migrate_mm", 0);
3439 	BUG_ON(!cpuset_migrate_mm_wq);
3440 }
3441 
3442 /**
3443  * cpuset_cpus_allowed - return cpus_allowed mask from a tasks cpuset.
3444  * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
3445  * @pmask: pointer to struct cpumask variable to receive cpus_allowed set.
3446  *
3447  * Description: Returns the cpumask_var_t cpus_allowed of the cpuset
3448  * attached to the specified @tsk.  Guaranteed to return some non-empty
3449  * subset of cpu_online_mask, even if this means going outside the
3450  * tasks cpuset.
3451  **/
3452 
cpuset_cpus_allowed(struct task_struct * tsk,struct cpumask * pmask)3453 void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
3454 {
3455 	unsigned long flags;
3456 
3457 	spin_lock_irqsave(&callback_lock, flags);
3458 	rcu_read_lock();
3459 	guarantee_online_cpus(tsk, pmask);
3460 	rcu_read_unlock();
3461 	spin_unlock_irqrestore(&callback_lock, flags);
3462 }
3463 EXPORT_SYMBOL_GPL(cpuset_cpus_allowed);
3464 /**
3465  * cpuset_cpus_allowed_fallback - final fallback before complete catastrophe.
3466  * @tsk: pointer to task_struct with which the scheduler is struggling
3467  *
3468  * Description: In the case that the scheduler cannot find an allowed cpu in
3469  * tsk->cpus_allowed, we fall back to task_cs(tsk)->cpus_allowed. In legacy
3470  * mode however, this value is the same as task_cs(tsk)->effective_cpus,
3471  * which will not contain a sane cpumask during cases such as cpu hotplugging.
3472  * This is the absolute last resort for the scheduler and it is only used if
3473  * _every_ other avenue has been traveled.
3474  **/
3475 
cpuset_cpus_allowed_fallback(struct task_struct * tsk)3476 void cpuset_cpus_allowed_fallback(struct task_struct *tsk)
3477 {
3478 	const struct cpumask *possible_mask = task_cpu_possible_mask(tsk);
3479 	const struct cpumask *cs_mask;
3480 
3481 	rcu_read_lock();
3482 	cs_mask = task_cs(tsk)->cpus_allowed;
3483 
3484 	if (!is_in_v2_mode() || !cpumask_subset(cs_mask, possible_mask))
3485 		goto unlock; /* select_fallback_rq will try harder */
3486 
3487 	do_set_cpus_allowed(tsk, cs_mask);
3488 unlock:
3489 	rcu_read_unlock();
3490 
3491 	/*
3492 	 * We own tsk->cpus_allowed, nobody can change it under us.
3493 	 *
3494 	 * But we used cs && cs->cpus_allowed lockless and thus can
3495 	 * race with cgroup_attach_task() or update_cpumask() and get
3496 	 * the wrong tsk->cpus_allowed. However, both cases imply the
3497 	 * subsequent cpuset_change_cpumask()->set_cpus_allowed_ptr()
3498 	 * which takes task_rq_lock().
3499 	 *
3500 	 * If we are called after it dropped the lock we must see all
3501 	 * changes in tsk_cs()->cpus_allowed. Otherwise we can temporary
3502 	 * set any mask even if it is not right from task_cs() pov,
3503 	 * the pending set_cpus_allowed_ptr() will fix things.
3504 	 *
3505 	 * select_fallback_rq() will fix things ups and set cpu_possible_mask
3506 	 * if required.
3507 	 */
3508 }
3509 
cpuset_init_current_mems_allowed(void)3510 void __init cpuset_init_current_mems_allowed(void)
3511 {
3512 	nodes_setall(current->mems_allowed);
3513 }
3514 
3515 /**
3516  * cpuset_mems_allowed - return mems_allowed mask from a tasks cpuset.
3517  * @tsk: pointer to task_struct from which to obtain cpuset->mems_allowed.
3518  *
3519  * Description: Returns the nodemask_t mems_allowed of the cpuset
3520  * attached to the specified @tsk.  Guaranteed to return some non-empty
3521  * subset of node_states[N_MEMORY], even if this means going outside the
3522  * tasks cpuset.
3523  **/
3524 
cpuset_mems_allowed(struct task_struct * tsk)3525 nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
3526 {
3527 	nodemask_t mask;
3528 	unsigned long flags;
3529 
3530 	spin_lock_irqsave(&callback_lock, flags);
3531 	rcu_read_lock();
3532 	guarantee_online_mems(task_cs(tsk), &mask);
3533 	rcu_read_unlock();
3534 	spin_unlock_irqrestore(&callback_lock, flags);
3535 
3536 	return mask;
3537 }
3538 
3539 /**
3540  * cpuset_nodemask_valid_mems_allowed - check nodemask vs. curremt mems_allowed
3541  * @nodemask: the nodemask to be checked
3542  *
3543  * Are any of the nodes in the nodemask allowed in current->mems_allowed?
3544  */
cpuset_nodemask_valid_mems_allowed(nodemask_t * nodemask)3545 int cpuset_nodemask_valid_mems_allowed(nodemask_t *nodemask)
3546 {
3547 	return nodes_intersects(*nodemask, current->mems_allowed);
3548 }
3549 
3550 /*
3551  * nearest_hardwall_ancestor() - Returns the nearest mem_exclusive or
3552  * mem_hardwall ancestor to the specified cpuset.  Call holding
3553  * callback_lock.  If no ancestor is mem_exclusive or mem_hardwall
3554  * (an unusual configuration), then returns the root cpuset.
3555  */
nearest_hardwall_ancestor(struct cpuset * cs)3556 static struct cpuset *nearest_hardwall_ancestor(struct cpuset *cs)
3557 {
3558 	while (!(is_mem_exclusive(cs) || is_mem_hardwall(cs)) && parent_cs(cs))
3559 		cs = parent_cs(cs);
3560 	return cs;
3561 }
3562 
3563 /**
3564  * cpuset_node_allowed - Can we allocate on a memory node?
3565  * @node: is this an allowed node?
3566  * @gfp_mask: memory allocation flags
3567  *
3568  * If we're in interrupt, yes, we can always allocate.  If @node is set in
3569  * current's mems_allowed, yes.  If it's not a __GFP_HARDWALL request and this
3570  * node is set in the nearest hardwalled cpuset ancestor to current's cpuset,
3571  * yes.  If current has access to memory reserves as an oom victim, yes.
3572  * Otherwise, no.
3573  *
3574  * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
3575  * and do not allow allocations outside the current tasks cpuset
3576  * unless the task has been OOM killed.
3577  * GFP_KERNEL allocations are not so marked, so can escape to the
3578  * nearest enclosing hardwalled ancestor cpuset.
3579  *
3580  * Scanning up parent cpusets requires callback_lock.  The
3581  * __alloc_pages() routine only calls here with __GFP_HARDWALL bit
3582  * _not_ set if it's a GFP_KERNEL allocation, and all nodes in the
3583  * current tasks mems_allowed came up empty on the first pass over
3584  * the zonelist.  So only GFP_KERNEL allocations, if all nodes in the
3585  * cpuset are short of memory, might require taking the callback_lock.
3586  *
3587  * The first call here from mm/page_alloc:get_page_from_freelist()
3588  * has __GFP_HARDWALL set in gfp_mask, enforcing hardwall cpusets,
3589  * so no allocation on a node outside the cpuset is allowed (unless
3590  * in interrupt, of course).
3591  *
3592  * The second pass through get_page_from_freelist() doesn't even call
3593  * here for GFP_ATOMIC calls.  For those calls, the __alloc_pages()
3594  * variable 'wait' is not set, and the bit ALLOC_CPUSET is not set
3595  * in alloc_flags.  That logic and the checks below have the combined
3596  * affect that:
3597  *	in_interrupt - any node ok (current task context irrelevant)
3598  *	GFP_ATOMIC   - any node ok
3599  *	tsk_is_oom_victim   - any node ok
3600  *	GFP_KERNEL   - any node in enclosing hardwalled cpuset ok
3601  *	GFP_USER     - only nodes in current tasks mems allowed ok.
3602  */
__cpuset_node_allowed(int node,gfp_t gfp_mask)3603 bool __cpuset_node_allowed(int node, gfp_t gfp_mask)
3604 {
3605 	struct cpuset *cs;		/* current cpuset ancestors */
3606 	int allowed;			/* is allocation in zone z allowed? */
3607 	unsigned long flags;
3608 
3609 	if (in_interrupt())
3610 		return true;
3611 	if (node_isset(node, current->mems_allowed))
3612 		return true;
3613 	/*
3614 	 * Allow tasks that have access to memory reserves because they have
3615 	 * been OOM killed to get memory anywhere.
3616 	 */
3617 	if (unlikely(tsk_is_oom_victim(current)))
3618 		return true;
3619 	if (gfp_mask & __GFP_HARDWALL)	/* If hardwall request, stop here */
3620 		return false;
3621 
3622 	if (current->flags & PF_EXITING) /* Let dying task have memory */
3623 		return true;
3624 
3625 	/* Not hardwall and node outside mems_allowed: scan up cpusets */
3626 	spin_lock_irqsave(&callback_lock, flags);
3627 
3628 	rcu_read_lock();
3629 	cs = nearest_hardwall_ancestor(task_cs(current));
3630 	allowed = node_isset(node, cs->mems_allowed);
3631 	rcu_read_unlock();
3632 
3633 	spin_unlock_irqrestore(&callback_lock, flags);
3634 	return allowed;
3635 }
3636 
3637 /**
3638  * cpuset_mem_spread_node() - On which node to begin search for a file page
3639  * cpuset_slab_spread_node() - On which node to begin search for a slab page
3640  *
3641  * If a task is marked PF_SPREAD_PAGE or PF_SPREAD_SLAB (as for
3642  * tasks in a cpuset with is_spread_page or is_spread_slab set),
3643  * and if the memory allocation used cpuset_mem_spread_node()
3644  * to determine on which node to start looking, as it will for
3645  * certain page cache or slab cache pages such as used for file
3646  * system buffers and inode caches, then instead of starting on the
3647  * local node to look for a free page, rather spread the starting
3648  * node around the tasks mems_allowed nodes.
3649  *
3650  * We don't have to worry about the returned node being offline
3651  * because "it can't happen", and even if it did, it would be ok.
3652  *
3653  * The routines calling guarantee_online_mems() are careful to
3654  * only set nodes in task->mems_allowed that are online.  So it
3655  * should not be possible for the following code to return an
3656  * offline node.  But if it did, that would be ok, as this routine
3657  * is not returning the node where the allocation must be, only
3658  * the node where the search should start.  The zonelist passed to
3659  * __alloc_pages() will include all nodes.  If the slab allocator
3660  * is passed an offline node, it will fall back to the local node.
3661  * See kmem_cache_alloc_node().
3662  */
3663 
cpuset_spread_node(int * rotor)3664 static int cpuset_spread_node(int *rotor)
3665 {
3666 	return *rotor = next_node_in(*rotor, current->mems_allowed);
3667 }
3668 
cpuset_mem_spread_node(void)3669 int cpuset_mem_spread_node(void)
3670 {
3671 	if (current->cpuset_mem_spread_rotor == NUMA_NO_NODE)
3672 		current->cpuset_mem_spread_rotor =
3673 			node_random(&current->mems_allowed);
3674 
3675 	return cpuset_spread_node(&current->cpuset_mem_spread_rotor);
3676 }
3677 
cpuset_slab_spread_node(void)3678 int cpuset_slab_spread_node(void)
3679 {
3680 	if (current->cpuset_slab_spread_rotor == NUMA_NO_NODE)
3681 		current->cpuset_slab_spread_rotor =
3682 			node_random(&current->mems_allowed);
3683 
3684 	return cpuset_spread_node(&current->cpuset_slab_spread_rotor);
3685 }
3686 
3687 EXPORT_SYMBOL_GPL(cpuset_mem_spread_node);
3688 
3689 /**
3690  * cpuset_mems_allowed_intersects - Does @tsk1's mems_allowed intersect @tsk2's?
3691  * @tsk1: pointer to task_struct of some task.
3692  * @tsk2: pointer to task_struct of some other task.
3693  *
3694  * Description: Return true if @tsk1's mems_allowed intersects the
3695  * mems_allowed of @tsk2.  Used by the OOM killer to determine if
3696  * one of the task's memory usage might impact the memory available
3697  * to the other.
3698  **/
3699 
cpuset_mems_allowed_intersects(const struct task_struct * tsk1,const struct task_struct * tsk2)3700 int cpuset_mems_allowed_intersects(const struct task_struct *tsk1,
3701 				   const struct task_struct *tsk2)
3702 {
3703 	return nodes_intersects(tsk1->mems_allowed, tsk2->mems_allowed);
3704 }
3705 
3706 /**
3707  * cpuset_print_current_mems_allowed - prints current's cpuset and mems_allowed
3708  *
3709  * Description: Prints current's name, cpuset name, and cached copy of its
3710  * mems_allowed to the kernel log.
3711  */
cpuset_print_current_mems_allowed(void)3712 void cpuset_print_current_mems_allowed(void)
3713 {
3714 	struct cgroup *cgrp;
3715 
3716 	rcu_read_lock();
3717 
3718 	cgrp = task_cs(current)->css.cgroup;
3719 	pr_cont(",cpuset=");
3720 	pr_cont_cgroup_name(cgrp);
3721 	pr_cont(",mems_allowed=%*pbl",
3722 		nodemask_pr_args(&current->mems_allowed));
3723 
3724 	rcu_read_unlock();
3725 }
3726 
3727 /*
3728  * Collection of memory_pressure is suppressed unless
3729  * this flag is enabled by writing "1" to the special
3730  * cpuset file 'memory_pressure_enabled' in the root cpuset.
3731  */
3732 
3733 int cpuset_memory_pressure_enabled __read_mostly;
3734 
3735 /**
3736  * cpuset_memory_pressure_bump - keep stats of per-cpuset reclaims.
3737  *
3738  * Keep a running average of the rate of synchronous (direct)
3739  * page reclaim efforts initiated by tasks in each cpuset.
3740  *
3741  * This represents the rate at which some task in the cpuset
3742  * ran low on memory on all nodes it was allowed to use, and
3743  * had to enter the kernels page reclaim code in an effort to
3744  * create more free memory by tossing clean pages or swapping
3745  * or writing dirty pages.
3746  *
3747  * Display to user space in the per-cpuset read-only file
3748  * "memory_pressure".  Value displayed is an integer
3749  * representing the recent rate of entry into the synchronous
3750  * (direct) page reclaim by any task attached to the cpuset.
3751  **/
3752 
__cpuset_memory_pressure_bump(void)3753 void __cpuset_memory_pressure_bump(void)
3754 {
3755 	rcu_read_lock();
3756 	fmeter_markevent(&task_cs(current)->fmeter);
3757 	rcu_read_unlock();
3758 }
3759 
3760 #ifdef CONFIG_PROC_PID_CPUSET
3761 /*
3762  * proc_cpuset_show()
3763  *  - Print tasks cpuset path into seq_file.
3764  *  - Used for /proc/<pid>/cpuset.
3765  *  - No need to task_lock(tsk) on this tsk->cpuset reference, as it
3766  *    doesn't really matter if tsk->cpuset changes after we read it,
3767  *    and we take cpuset_mutex, keeping cpuset_attach() from changing it
3768  *    anyway.
3769  */
proc_cpuset_show(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * tsk)3770 int proc_cpuset_show(struct seq_file *m, struct pid_namespace *ns,
3771 		     struct pid *pid, struct task_struct *tsk)
3772 {
3773 	char *buf;
3774 	struct cgroup_subsys_state *css;
3775 	int retval;
3776 
3777 	retval = -ENOMEM;
3778 	buf = kmalloc(PATH_MAX, GFP_KERNEL);
3779 	if (!buf)
3780 		goto out;
3781 
3782 	css = task_get_css(tsk, cpuset_cgrp_id);
3783 	retval = cgroup_path_ns(css->cgroup, buf, PATH_MAX,
3784 				current->nsproxy->cgroup_ns);
3785 	css_put(css);
3786 	if (retval >= PATH_MAX)
3787 		retval = -ENAMETOOLONG;
3788 	if (retval < 0)
3789 		goto out_free;
3790 	seq_puts(m, buf);
3791 	seq_putc(m, '\n');
3792 	retval = 0;
3793 out_free:
3794 	kfree(buf);
3795 out:
3796 	return retval;
3797 }
3798 #endif /* CONFIG_PROC_PID_CPUSET */
3799 
3800 /* Display task mems_allowed in /proc/<pid>/status file. */
cpuset_task_status_allowed(struct seq_file * m,struct task_struct * task)3801 void cpuset_task_status_allowed(struct seq_file *m, struct task_struct *task)
3802 {
3803 	seq_printf(m, "Mems_allowed:\t%*pb\n",
3804 		   nodemask_pr_args(&task->mems_allowed));
3805 	seq_printf(m, "Mems_allowed_list:\t%*pbl\n",
3806 		   nodemask_pr_args(&task->mems_allowed));
3807 }
3808