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