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