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