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