• 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/list.h>
37 #include <linux/mempolicy.h>
38 #include <linux/mm.h>
39 #include <linux/memory.h>
40 #include <linux/export.h>
41 #include <linux/mount.h>
42 #include <linux/namei.h>
43 #include <linux/pagemap.h>
44 #include <linux/proc_fs.h>
45 #include <linux/rcupdate.h>
46 #include <linux/sched.h>
47 #include <linux/sched/mm.h>
48 #include <linux/sched/task.h>
49 #include <linux/seq_file.h>
50 #include <linux/security.h>
51 #include <linux/slab.h>
52 #include <linux/spinlock.h>
53 #include <linux/stat.h>
54 #include <linux/string.h>
55 #include <linux/time.h>
56 #include <linux/time64.h>
57 #include <linux/backing-dev.h>
58 #include <linux/sort.h>
59 #include <linux/oom.h>
60 
61 #include <linux/uaccess.h>
62 #include <linux/atomic.h>
63 #include <linux/mutex.h>
64 #include <linux/cgroup.h>
65 #include <linux/wait.h>
66 
67 DEFINE_STATIC_KEY_FALSE(cpusets_pre_enable_key);
68 DEFINE_STATIC_KEY_FALSE(cpusets_enabled_key);
69 
70 /* See "Frequency meter" comments, below. */
71 
72 struct fmeter {
73 	int cnt;		/* unprocessed events count */
74 	int val;		/* most recent output value */
75 	time64_t time;		/* clock (secs) when val computed */
76 	spinlock_t lock;	/* guards read or write of above */
77 };
78 
79 struct cpuset {
80 	struct cgroup_subsys_state css;
81 
82 	unsigned long flags;		/* "unsigned long" so bitops work */
83 
84 	/*
85 	 * On default hierarchy:
86 	 *
87 	 * The user-configured masks can only be changed by writing to
88 	 * cpuset.cpus and cpuset.mems, and won't be limited by the
89 	 * parent masks.
90 	 *
91 	 * The effective masks is the real masks that apply to the tasks
92 	 * in the cpuset. They may be changed if the configured masks are
93 	 * changed or hotplug happens.
94 	 *
95 	 * effective_mask == configured_mask & parent's effective_mask,
96 	 * and if it ends up empty, it will inherit the parent's mask.
97 	 *
98 	 *
99 	 * On legacy hierachy:
100 	 *
101 	 * The user-configured masks are always the same with effective masks.
102 	 */
103 
104 	/* user-configured CPUs and Memory Nodes allow to tasks */
105 	cpumask_var_t cpus_allowed;
106 	cpumask_var_t cpus_requested;
107 	nodemask_t mems_allowed;
108 
109 	/* effective CPUs and Memory Nodes allow to tasks */
110 	cpumask_var_t effective_cpus;
111 	nodemask_t effective_mems;
112 
113 	/*
114 	 * This is old Memory Nodes tasks took on.
115 	 *
116 	 * - top_cpuset.old_mems_allowed is initialized to mems_allowed.
117 	 * - A new cpuset's old_mems_allowed is initialized when some
118 	 *   task is moved into it.
119 	 * - old_mems_allowed is used in cpuset_migrate_mm() when we change
120 	 *   cpuset.mems_allowed and have tasks' nodemask updated, and
121 	 *   then old_mems_allowed is updated to mems_allowed.
122 	 */
123 	nodemask_t old_mems_allowed;
124 
125 	struct fmeter fmeter;		/* memory_pressure filter */
126 
127 	/*
128 	 * Tasks are being attached to this cpuset.  Used to prevent
129 	 * zeroing cpus/mems_allowed between ->can_attach() and ->attach().
130 	 */
131 	int attach_in_progress;
132 
133 	/* partition number for rebuild_sched_domains() */
134 	int pn;
135 
136 	/* for custom sched domain */
137 	int relax_domain_level;
138 };
139 
css_cs(struct cgroup_subsys_state * css)140 static inline struct cpuset *css_cs(struct cgroup_subsys_state *css)
141 {
142 	return css ? container_of(css, struct cpuset, css) : NULL;
143 }
144 
145 /* Retrieve the cpuset for a task */
task_cs(struct task_struct * task)146 static inline struct cpuset *task_cs(struct task_struct *task)
147 {
148 	return css_cs(task_css(task, cpuset_cgrp_id));
149 }
150 
parent_cs(struct cpuset * cs)151 static inline struct cpuset *parent_cs(struct cpuset *cs)
152 {
153 	return css_cs(cs->css.parent);
154 }
155 
156 #ifdef CONFIG_NUMA
task_has_mempolicy(struct task_struct * task)157 static inline bool task_has_mempolicy(struct task_struct *task)
158 {
159 	return task->mempolicy;
160 }
161 #else
task_has_mempolicy(struct task_struct * task)162 static inline bool task_has_mempolicy(struct task_struct *task)
163 {
164 	return false;
165 }
166 #endif
167 
168 
169 /* bits in struct cpuset flags field */
170 typedef enum {
171 	CS_ONLINE,
172 	CS_CPU_EXCLUSIVE,
173 	CS_MEM_EXCLUSIVE,
174 	CS_MEM_HARDWALL,
175 	CS_MEMORY_MIGRATE,
176 	CS_SCHED_LOAD_BALANCE,
177 	CS_SPREAD_PAGE,
178 	CS_SPREAD_SLAB,
179 } cpuset_flagbits_t;
180 
181 /* convenient tests for these bits */
is_cpuset_online(struct cpuset * cs)182 static inline bool is_cpuset_online(struct cpuset *cs)
183 {
184 	return test_bit(CS_ONLINE, &cs->flags) && !css_is_dying(&cs->css);
185 }
186 
is_cpu_exclusive(const struct cpuset * cs)187 static inline int is_cpu_exclusive(const struct cpuset *cs)
188 {
189 	return test_bit(CS_CPU_EXCLUSIVE, &cs->flags);
190 }
191 
is_mem_exclusive(const struct cpuset * cs)192 static inline int is_mem_exclusive(const struct cpuset *cs)
193 {
194 	return test_bit(CS_MEM_EXCLUSIVE, &cs->flags);
195 }
196 
is_mem_hardwall(const struct cpuset * cs)197 static inline int is_mem_hardwall(const struct cpuset *cs)
198 {
199 	return test_bit(CS_MEM_HARDWALL, &cs->flags);
200 }
201 
is_sched_load_balance(const struct cpuset * cs)202 static inline int is_sched_load_balance(const struct cpuset *cs)
203 {
204 	return test_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
205 }
206 
is_memory_migrate(const struct cpuset * cs)207 static inline int is_memory_migrate(const struct cpuset *cs)
208 {
209 	return test_bit(CS_MEMORY_MIGRATE, &cs->flags);
210 }
211 
is_spread_page(const struct cpuset * cs)212 static inline int is_spread_page(const struct cpuset *cs)
213 {
214 	return test_bit(CS_SPREAD_PAGE, &cs->flags);
215 }
216 
is_spread_slab(const struct cpuset * cs)217 static inline int is_spread_slab(const struct cpuset *cs)
218 {
219 	return test_bit(CS_SPREAD_SLAB, &cs->flags);
220 }
221 
222 static struct cpuset top_cpuset = {
223 	.flags = ((1 << CS_ONLINE) | (1 << CS_CPU_EXCLUSIVE) |
224 		  (1 << CS_MEM_EXCLUSIVE)),
225 };
226 
227 /**
228  * cpuset_for_each_child - traverse online children of a cpuset
229  * @child_cs: loop cursor pointing to the current child
230  * @pos_css: used for iteration
231  * @parent_cs: target cpuset to walk children of
232  *
233  * Walk @child_cs through the online children of @parent_cs.  Must be used
234  * with RCU read locked.
235  */
236 #define cpuset_for_each_child(child_cs, pos_css, parent_cs)		\
237 	css_for_each_child((pos_css), &(parent_cs)->css)		\
238 		if (is_cpuset_online(((child_cs) = css_cs((pos_css)))))
239 
240 /**
241  * cpuset_for_each_descendant_pre - pre-order walk of a cpuset's descendants
242  * @des_cs: loop cursor pointing to the current descendant
243  * @pos_css: used for iteration
244  * @root_cs: target cpuset to walk ancestor of
245  *
246  * Walk @des_cs through the online descendants of @root_cs.  Must be used
247  * with RCU read locked.  The caller may modify @pos_css by calling
248  * css_rightmost_descendant() to skip subtree.  @root_cs is included in the
249  * iteration and the first node to be visited.
250  */
251 #define cpuset_for_each_descendant_pre(des_cs, pos_css, root_cs)	\
252 	css_for_each_descendant_pre((pos_css), &(root_cs)->css)		\
253 		if (is_cpuset_online(((des_cs) = css_cs((pos_css)))))
254 
255 /*
256  * There are two global locks guarding cpuset structures - cpuset_mutex and
257  * callback_lock. We also require taking task_lock() when dereferencing a
258  * task's cpuset pointer. See "The task_lock() exception", at the end of this
259  * comment.
260  *
261  * A task must hold both locks to modify cpusets.  If a task holds
262  * cpuset_mutex, then it blocks others wanting that mutex, ensuring that it
263  * is the only task able to also acquire callback_lock and be able to
264  * modify cpusets.  It can perform various checks on the cpuset structure
265  * first, knowing nothing will change.  It can also allocate memory while
266  * just holding cpuset_mutex.  While it is performing these checks, various
267  * callback routines can briefly acquire callback_lock to query cpusets.
268  * Once it is ready to make the changes, it takes callback_lock, blocking
269  * everyone else.
270  *
271  * Calls to the kernel memory allocator can not be made while holding
272  * callback_lock, as that would risk double tripping on callback_lock
273  * from one of the callbacks into the cpuset code from within
274  * __alloc_pages().
275  *
276  * If a task is only holding callback_lock, then it has read-only
277  * access to cpusets.
278  *
279  * Now, the task_struct fields mems_allowed and mempolicy may be changed
280  * by other task, we use alloc_lock in the task_struct fields to protect
281  * them.
282  *
283  * The cpuset_common_file_read() handlers only hold callback_lock across
284  * small pieces of code, such as when reading out possibly multi-word
285  * cpumasks and nodemasks.
286  *
287  * Accessing a task's cpuset should be done in accordance with the
288  * guidelines for accessing subsystem state in kernel/cgroup.c
289  */
290 
291 static DEFINE_MUTEX(cpuset_mutex);
292 static DEFINE_SPINLOCK(callback_lock);
293 
294 static struct workqueue_struct *cpuset_migrate_mm_wq;
295 
296 /*
297  * CPU / memory hotplug is handled asynchronously.
298  */
299 static void cpuset_hotplug_workfn(struct work_struct *work);
300 static DECLARE_WORK(cpuset_hotplug_work, cpuset_hotplug_workfn);
301 
302 static DECLARE_WAIT_QUEUE_HEAD(cpuset_attach_wq);
303 
304 /*
305  * Cgroup v2 behavior is used when on default hierarchy or the
306  * cgroup_v2_mode flag is set.
307  */
is_in_v2_mode(void)308 static inline bool is_in_v2_mode(void)
309 {
310 	return cgroup_subsys_on_dfl(cpuset_cgrp_subsys) ||
311 	      (cpuset_cgrp_subsys.root->flags & CGRP_ROOT_CPUSET_V2_MODE);
312 }
313 
314 /*
315  * This is ugly, but preserves the userspace API for existing cpuset
316  * users. If someone tries to mount the "cpuset" filesystem, we
317  * silently switch it to mount "cgroup" instead
318  */
cpuset_mount(struct file_system_type * fs_type,int flags,const char * unused_dev_name,void * data)319 static struct dentry *cpuset_mount(struct file_system_type *fs_type,
320 			 int flags, const char *unused_dev_name, void *data)
321 {
322 	struct file_system_type *cgroup_fs = get_fs_type("cgroup");
323 	struct dentry *ret = ERR_PTR(-ENODEV);
324 	if (cgroup_fs) {
325 		char mountopts[] =
326 			"cpuset,noprefix,"
327 			"release_agent=/sbin/cpuset_release_agent";
328 		ret = cgroup_fs->mount(cgroup_fs, flags,
329 					   unused_dev_name, mountopts);
330 		put_filesystem(cgroup_fs);
331 	}
332 	return ret;
333 }
334 
335 static struct file_system_type cpuset_fs_type = {
336 	.name = "cpuset",
337 	.mount = cpuset_mount,
338 };
339 
340 /*
341  * Return in pmask the portion of a cpusets's cpus_allowed that
342  * are online.  If none are online, walk up the cpuset hierarchy
343  * until we find one that does have some online cpus.
344  *
345  * One way or another, we guarantee to return some non-empty subset
346  * of cpu_online_mask.
347  *
348  * Call with callback_lock or cpuset_mutex held.
349  */
guarantee_online_cpus(struct cpuset * cs,struct cpumask * pmask)350 static void guarantee_online_cpus(struct cpuset *cs, struct cpumask *pmask)
351 {
352 	while (!cpumask_intersects(cs->effective_cpus, cpu_online_mask)) {
353 		cs = parent_cs(cs);
354 		if (unlikely(!cs)) {
355 			/*
356 			 * The top cpuset doesn't have any online cpu as a
357 			 * consequence of a race between cpuset_hotplug_work
358 			 * and cpu hotplug notifier.  But we know the top
359 			 * cpuset's effective_cpus is on its way to to be
360 			 * identical to cpu_online_mask.
361 			 */
362 			cpumask_copy(pmask, cpu_online_mask);
363 			return;
364 		}
365 	}
366 	cpumask_and(pmask, cs->effective_cpus, cpu_online_mask);
367 }
368 
369 /*
370  * Return in *pmask the portion of a cpusets's mems_allowed that
371  * are online, with memory.  If none are online with memory, walk
372  * up the cpuset hierarchy until we find one that does have some
373  * online mems.  The top cpuset always has some mems online.
374  *
375  * One way or another, we guarantee to return some non-empty subset
376  * of node_states[N_MEMORY].
377  *
378  * Call with callback_lock or cpuset_mutex held.
379  */
guarantee_online_mems(struct cpuset * cs,nodemask_t * pmask)380 static void guarantee_online_mems(struct cpuset *cs, nodemask_t *pmask)
381 {
382 	while (!nodes_intersects(cs->effective_mems, node_states[N_MEMORY]))
383 		cs = parent_cs(cs);
384 	nodes_and(*pmask, cs->effective_mems, node_states[N_MEMORY]);
385 }
386 
387 /*
388  * update task's spread flag if cpuset's page/slab spread flag is set
389  *
390  * Call with callback_lock or cpuset_mutex held.
391  */
cpuset_update_task_spread_flag(struct cpuset * cs,struct task_struct * tsk)392 static void cpuset_update_task_spread_flag(struct cpuset *cs,
393 					struct task_struct *tsk)
394 {
395 	if (is_spread_page(cs))
396 		task_set_spread_page(tsk);
397 	else
398 		task_clear_spread_page(tsk);
399 
400 	if (is_spread_slab(cs))
401 		task_set_spread_slab(tsk);
402 	else
403 		task_clear_spread_slab(tsk);
404 }
405 
406 /*
407  * is_cpuset_subset(p, q) - Is cpuset p a subset of cpuset q?
408  *
409  * One cpuset is a subset of another if all its allowed CPUs and
410  * Memory Nodes are a subset of the other, and its exclusive flags
411  * are only set if the other's are set.  Call holding cpuset_mutex.
412  */
413 
is_cpuset_subset(const struct cpuset * p,const struct cpuset * q)414 static int is_cpuset_subset(const struct cpuset *p, const struct cpuset *q)
415 {
416 	return	cpumask_subset(p->cpus_requested, q->cpus_requested) &&
417 		nodes_subset(p->mems_allowed, q->mems_allowed) &&
418 		is_cpu_exclusive(p) <= is_cpu_exclusive(q) &&
419 		is_mem_exclusive(p) <= is_mem_exclusive(q);
420 }
421 
422 /**
423  * alloc_trial_cpuset - allocate a trial cpuset
424  * @cs: the cpuset that the trial cpuset duplicates
425  */
alloc_trial_cpuset(struct cpuset * cs)426 static struct cpuset *alloc_trial_cpuset(struct cpuset *cs)
427 {
428 	struct cpuset *trial;
429 
430 	trial = kmemdup(cs, sizeof(*cs), GFP_KERNEL);
431 	if (!trial)
432 		return NULL;
433 
434 	if (!alloc_cpumask_var(&trial->cpus_allowed, GFP_KERNEL))
435 		goto free_cs;
436 	if (!alloc_cpumask_var(&trial->effective_cpus, GFP_KERNEL))
437 		goto free_cpus;
438 
439 	cpumask_copy(trial->cpus_allowed, cs->cpus_allowed);
440 	cpumask_copy(trial->effective_cpus, cs->effective_cpus);
441 	return trial;
442 
443 free_cpus:
444 	free_cpumask_var(trial->cpus_allowed);
445 free_cs:
446 	kfree(trial);
447 	return NULL;
448 }
449 
450 /**
451  * free_trial_cpuset - free the trial cpuset
452  * @trial: the trial cpuset to be freed
453  */
free_trial_cpuset(struct cpuset * trial)454 static void free_trial_cpuset(struct cpuset *trial)
455 {
456 	free_cpumask_var(trial->effective_cpus);
457 	free_cpumask_var(trial->cpus_allowed);
458 	kfree(trial);
459 }
460 
461 /*
462  * validate_change() - Used to validate that any proposed cpuset change
463  *		       follows the structural rules for cpusets.
464  *
465  * If we replaced the flag and mask values of the current cpuset
466  * (cur) with those values in the trial cpuset (trial), would
467  * our various subset and exclusive rules still be valid?  Presumes
468  * cpuset_mutex held.
469  *
470  * 'cur' is the address of an actual, in-use cpuset.  Operations
471  * such as list traversal that depend on the actual address of the
472  * cpuset in the list must use cur below, not trial.
473  *
474  * 'trial' is the address of bulk structure copy of cur, with
475  * perhaps one or more of the fields cpus_allowed, mems_allowed,
476  * or flags changed to new, trial values.
477  *
478  * Return 0 if valid, -errno if not.
479  */
480 
validate_change(struct cpuset * cur,struct cpuset * trial)481 static int validate_change(struct cpuset *cur, struct cpuset *trial)
482 {
483 	struct cgroup_subsys_state *css;
484 	struct cpuset *c, *par;
485 	int ret;
486 
487 	rcu_read_lock();
488 
489 	/* Each of our child cpusets must be a subset of us */
490 	ret = -EBUSY;
491 	cpuset_for_each_child(c, css, cur)
492 		if (!is_cpuset_subset(c, trial))
493 			goto out;
494 
495 	/* Remaining checks don't apply to root cpuset */
496 	ret = 0;
497 	if (cur == &top_cpuset)
498 		goto out;
499 
500 	par = parent_cs(cur);
501 
502 	/* On legacy hiearchy, we must be a subset of our parent cpuset. */
503 	ret = -EACCES;
504 	if (!is_in_v2_mode() && !is_cpuset_subset(trial, par))
505 		goto out;
506 
507 	/*
508 	 * If either I or some sibling (!= me) is exclusive, we can't
509 	 * overlap
510 	 */
511 	ret = -EINVAL;
512 	cpuset_for_each_child(c, css, par) {
513 		if ((is_cpu_exclusive(trial) || is_cpu_exclusive(c)) &&
514 		    c != cur &&
515 		    cpumask_intersects(trial->cpus_requested, c->cpus_requested))
516 			goto out;
517 		if ((is_mem_exclusive(trial) || is_mem_exclusive(c)) &&
518 		    c != cur &&
519 		    nodes_intersects(trial->mems_allowed, c->mems_allowed))
520 			goto out;
521 	}
522 
523 	/*
524 	 * Cpusets with tasks - existing or newly being attached - can't
525 	 * be changed to have empty cpus_allowed or mems_allowed.
526 	 */
527 	ret = -ENOSPC;
528 	if ((cgroup_is_populated(cur->css.cgroup) || cur->attach_in_progress)) {
529 		if (!cpumask_empty(cur->cpus_allowed) &&
530 		    cpumask_empty(trial->cpus_allowed))
531 			goto out;
532 		if (!nodes_empty(cur->mems_allowed) &&
533 		    nodes_empty(trial->mems_allowed))
534 			goto out;
535 	}
536 
537 	/*
538 	 * We can't shrink if we won't have enough room for SCHED_DEADLINE
539 	 * tasks.
540 	 */
541 	ret = -EBUSY;
542 	if (is_cpu_exclusive(cur) &&
543 	    !cpuset_cpumask_can_shrink(cur->cpus_allowed,
544 				       trial->cpus_allowed))
545 		goto out;
546 
547 	ret = 0;
548 out:
549 	rcu_read_unlock();
550 	return ret;
551 }
552 
553 #ifdef CONFIG_SMP
554 /*
555  * Helper routine for generate_sched_domains().
556  * Do cpusets a, b have overlapping effective cpus_allowed masks?
557  */
cpusets_overlap(struct cpuset * a,struct cpuset * b)558 static int cpusets_overlap(struct cpuset *a, struct cpuset *b)
559 {
560 	return cpumask_intersects(a->effective_cpus, b->effective_cpus);
561 }
562 
563 static void
update_domain_attr(struct sched_domain_attr * dattr,struct cpuset * c)564 update_domain_attr(struct sched_domain_attr *dattr, struct cpuset *c)
565 {
566 	if (dattr->relax_domain_level < c->relax_domain_level)
567 		dattr->relax_domain_level = c->relax_domain_level;
568 	return;
569 }
570 
update_domain_attr_tree(struct sched_domain_attr * dattr,struct cpuset * root_cs)571 static void update_domain_attr_tree(struct sched_domain_attr *dattr,
572 				    struct cpuset *root_cs)
573 {
574 	struct cpuset *cp;
575 	struct cgroup_subsys_state *pos_css;
576 
577 	rcu_read_lock();
578 	cpuset_for_each_descendant_pre(cp, pos_css, root_cs) {
579 		/* skip the whole subtree if @cp doesn't have any CPU */
580 		if (cpumask_empty(cp->cpus_allowed)) {
581 			pos_css = css_rightmost_descendant(pos_css);
582 			continue;
583 		}
584 
585 		if (is_sched_load_balance(cp))
586 			update_domain_attr(dattr, cp);
587 	}
588 	rcu_read_unlock();
589 }
590 
591 /* Must be called with cpuset_mutex held.  */
nr_cpusets(void)592 static inline int nr_cpusets(void)
593 {
594 	/* jump label reference count + the top-level cpuset */
595 	return static_key_count(&cpusets_enabled_key.key) + 1;
596 }
597 
598 /*
599  * generate_sched_domains()
600  *
601  * This function builds a partial partition of the systems CPUs
602  * A 'partial partition' is a set of non-overlapping subsets whose
603  * union is a subset of that set.
604  * The output of this function needs to be passed to kernel/sched/core.c
605  * partition_sched_domains() routine, which will rebuild the scheduler's
606  * load balancing domains (sched domains) as specified by that partial
607  * partition.
608  *
609  * See "What is sched_load_balance" in Documentation/cgroups/cpusets.txt
610  * for a background explanation of this.
611  *
612  * Does not return errors, on the theory that the callers of this
613  * routine would rather not worry about failures to rebuild sched
614  * domains when operating in the severe memory shortage situations
615  * that could cause allocation failures below.
616  *
617  * Must be called with cpuset_mutex held.
618  *
619  * The three key local variables below are:
620  *    q  - a linked-list queue of cpuset pointers, used to implement a
621  *	   top-down scan of all cpusets.  This scan loads a pointer
622  *	   to each cpuset marked is_sched_load_balance into the
623  *	   array 'csa'.  For our purposes, rebuilding the schedulers
624  *	   sched domains, we can ignore !is_sched_load_balance cpusets.
625  *  csa  - (for CpuSet Array) Array of pointers to all the cpusets
626  *	   that need to be load balanced, for convenient iterative
627  *	   access by the subsequent code that finds the best partition,
628  *	   i.e the set of domains (subsets) of CPUs such that the
629  *	   cpus_allowed of every cpuset marked is_sched_load_balance
630  *	   is a subset of one of these domains, while there are as
631  *	   many such domains as possible, each as small as possible.
632  * doms  - Conversion of 'csa' to an array of cpumasks, for passing to
633  *	   the kernel/sched/core.c routine partition_sched_domains() in a
634  *	   convenient format, that can be easily compared to the prior
635  *	   value to determine what partition elements (sched domains)
636  *	   were changed (added or removed.)
637  *
638  * Finding the best partition (set of domains):
639  *	The triple nested loops below over i, j, k scan over the
640  *	load balanced cpusets (using the array of cpuset pointers in
641  *	csa[]) looking for pairs of cpusets that have overlapping
642  *	cpus_allowed, but which don't have the same 'pn' partition
643  *	number and gives them in the same partition number.  It keeps
644  *	looping on the 'restart' label until it can no longer find
645  *	any such pairs.
646  *
647  *	The union of the cpus_allowed masks from the set of
648  *	all cpusets having the same 'pn' value then form the one
649  *	element of the partition (one sched domain) to be passed to
650  *	partition_sched_domains().
651  */
generate_sched_domains(cpumask_var_t ** domains,struct sched_domain_attr ** attributes)652 static int generate_sched_domains(cpumask_var_t **domains,
653 			struct sched_domain_attr **attributes)
654 {
655 	struct cpuset *cp;	/* scans q */
656 	struct cpuset **csa;	/* array of all cpuset ptrs */
657 	int csn;		/* how many cpuset ptrs in csa so far */
658 	int i, j, k;		/* indices for partition finding loops */
659 	cpumask_var_t *doms;	/* resulting partition; i.e. sched domains */
660 	cpumask_var_t non_isolated_cpus;  /* load balanced CPUs */
661 	struct sched_domain_attr *dattr;  /* attributes for custom domains */
662 	int ndoms = 0;		/* number of sched domains in result */
663 	int nslot;		/* next empty doms[] struct cpumask slot */
664 	struct cgroup_subsys_state *pos_css;
665 
666 	doms = NULL;
667 	dattr = NULL;
668 	csa = NULL;
669 
670 	if (!alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL))
671 		goto done;
672 	cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
673 
674 	/* Special case for the 99% of systems with one, full, sched domain */
675 	if (is_sched_load_balance(&top_cpuset)) {
676 		ndoms = 1;
677 		doms = alloc_sched_domains(ndoms);
678 		if (!doms)
679 			goto done;
680 
681 		dattr = kmalloc(sizeof(struct sched_domain_attr), GFP_KERNEL);
682 		if (dattr) {
683 			*dattr = SD_ATTR_INIT;
684 			update_domain_attr_tree(dattr, &top_cpuset);
685 		}
686 		cpumask_and(doms[0], top_cpuset.effective_cpus,
687 				     non_isolated_cpus);
688 
689 		goto done;
690 	}
691 
692 	csa = kmalloc(nr_cpusets() * sizeof(cp), GFP_KERNEL);
693 	if (!csa)
694 		goto done;
695 	csn = 0;
696 
697 	rcu_read_lock();
698 	cpuset_for_each_descendant_pre(cp, pos_css, &top_cpuset) {
699 		if (cp == &top_cpuset)
700 			continue;
701 		/*
702 		 * Continue traversing beyond @cp iff @cp has some CPUs and
703 		 * isn't load balancing.  The former is obvious.  The
704 		 * latter: All child cpusets contain a subset of the
705 		 * parent's cpus, so just skip them, and then we call
706 		 * update_domain_attr_tree() to calc relax_domain_level of
707 		 * the corresponding sched domain.
708 		 */
709 		if (!cpumask_empty(cp->cpus_allowed) &&
710 		    !(is_sched_load_balance(cp) &&
711 		      cpumask_intersects(cp->cpus_allowed, non_isolated_cpus)))
712 			continue;
713 
714 		if (is_sched_load_balance(cp))
715 			csa[csn++] = cp;
716 
717 		/* skip @cp's subtree */
718 		pos_css = css_rightmost_descendant(pos_css);
719 	}
720 	rcu_read_unlock();
721 
722 	for (i = 0; i < csn; i++)
723 		csa[i]->pn = i;
724 	ndoms = csn;
725 
726 restart:
727 	/* Find the best partition (set of sched domains) */
728 	for (i = 0; i < csn; i++) {
729 		struct cpuset *a = csa[i];
730 		int apn = a->pn;
731 
732 		for (j = 0; j < csn; j++) {
733 			struct cpuset *b = csa[j];
734 			int bpn = b->pn;
735 
736 			if (apn != bpn && cpusets_overlap(a, b)) {
737 				for (k = 0; k < csn; k++) {
738 					struct cpuset *c = csa[k];
739 
740 					if (c->pn == bpn)
741 						c->pn = apn;
742 				}
743 				ndoms--;	/* one less element */
744 				goto restart;
745 			}
746 		}
747 	}
748 
749 	/*
750 	 * Now we know how many domains to create.
751 	 * Convert <csn, csa> to <ndoms, doms> and populate cpu masks.
752 	 */
753 	doms = alloc_sched_domains(ndoms);
754 	if (!doms)
755 		goto done;
756 
757 	/*
758 	 * The rest of the code, including the scheduler, can deal with
759 	 * dattr==NULL case. No need to abort if alloc fails.
760 	 */
761 	dattr = kmalloc(ndoms * sizeof(struct sched_domain_attr), GFP_KERNEL);
762 
763 	for (nslot = 0, i = 0; i < csn; i++) {
764 		struct cpuset *a = csa[i];
765 		struct cpumask *dp;
766 		int apn = a->pn;
767 
768 		if (apn < 0) {
769 			/* Skip completed partitions */
770 			continue;
771 		}
772 
773 		dp = doms[nslot];
774 
775 		if (nslot == ndoms) {
776 			static int warnings = 10;
777 			if (warnings) {
778 				pr_warn("rebuild_sched_domains confused: nslot %d, ndoms %d, csn %d, i %d, apn %d\n",
779 					nslot, ndoms, csn, i, apn);
780 				warnings--;
781 			}
782 			continue;
783 		}
784 
785 		cpumask_clear(dp);
786 		if (dattr)
787 			*(dattr + nslot) = SD_ATTR_INIT;
788 		for (j = i; j < csn; j++) {
789 			struct cpuset *b = csa[j];
790 
791 			if (apn == b->pn) {
792 				cpumask_or(dp, dp, b->effective_cpus);
793 				cpumask_and(dp, dp, non_isolated_cpus);
794 				if (dattr)
795 					update_domain_attr_tree(dattr + nslot, b);
796 
797 				/* Done with this partition */
798 				b->pn = -1;
799 			}
800 		}
801 		nslot++;
802 	}
803 	BUG_ON(nslot != ndoms);
804 
805 done:
806 	free_cpumask_var(non_isolated_cpus);
807 	kfree(csa);
808 
809 	/*
810 	 * Fallback to the default domain if kmalloc() failed.
811 	 * See comments in partition_sched_domains().
812 	 */
813 	if (doms == NULL)
814 		ndoms = 1;
815 
816 	*domains    = doms;
817 	*attributes = dattr;
818 	return ndoms;
819 }
820 
821 /*
822  * Rebuild scheduler domains.
823  *
824  * If the flag 'sched_load_balance' of any cpuset with non-empty
825  * 'cpus' changes, or if the 'cpus' allowed changes in any cpuset
826  * which has that flag enabled, or if any cpuset with a non-empty
827  * 'cpus' is removed, then call this routine to rebuild the
828  * scheduler's dynamic sched domains.
829  *
830  * Call with cpuset_mutex held.  Takes get_online_cpus().
831  */
rebuild_sched_domains_locked(void)832 static void rebuild_sched_domains_locked(void)
833 {
834 	struct sched_domain_attr *attr;
835 	cpumask_var_t *doms;
836 	int ndoms;
837 
838 	lockdep_assert_held(&cpuset_mutex);
839 	get_online_cpus();
840 
841 	/*
842 	 * We have raced with CPU hotplug. Don't do anything to avoid
843 	 * passing doms with offlined cpu to partition_sched_domains().
844 	 * Anyways, hotplug work item will rebuild sched domains.
845 	 */
846 	if (!cpumask_equal(top_cpuset.effective_cpus, cpu_active_mask))
847 		goto out;
848 
849 	/* Generate domain masks and attrs */
850 	ndoms = generate_sched_domains(&doms, &attr);
851 
852 	/* Have scheduler rebuild the domains */
853 	partition_sched_domains(ndoms, doms, attr);
854 out:
855 	put_online_cpus();
856 }
857 #else /* !CONFIG_SMP */
rebuild_sched_domains_locked(void)858 static void rebuild_sched_domains_locked(void)
859 {
860 }
861 #endif /* CONFIG_SMP */
862 
rebuild_sched_domains(void)863 void rebuild_sched_domains(void)
864 {
865 	mutex_lock(&cpuset_mutex);
866 	rebuild_sched_domains_locked();
867 	mutex_unlock(&cpuset_mutex);
868 }
869 
870 /**
871  * update_tasks_cpumask - Update the cpumasks of tasks in the cpuset.
872  * @cs: the cpuset in which each task's cpus_allowed mask needs to be changed
873  *
874  * Iterate through each task of @cs updating its cpus_allowed to the
875  * effective cpuset's.  As this function is called with cpuset_mutex held,
876  * cpuset membership stays stable.
877  */
update_tasks_cpumask(struct cpuset * cs)878 static void update_tasks_cpumask(struct cpuset *cs)
879 {
880 	struct css_task_iter it;
881 	struct task_struct *task;
882 
883 	css_task_iter_start(&cs->css, 0, &it);
884 	while ((task = css_task_iter_next(&it)))
885 		set_cpus_allowed_ptr(task, cs->effective_cpus);
886 	css_task_iter_end(&it);
887 }
888 
889 /*
890  * update_cpumasks_hier - Update effective cpumasks and tasks in the subtree
891  * @cs: the cpuset to consider
892  * @new_cpus: temp variable for calculating new effective_cpus
893  *
894  * When congifured cpumask is changed, the effective cpumasks of this cpuset
895  * and all its descendants need to be updated.
896  *
897  * On legacy hierachy, effective_cpus will be the same with cpu_allowed.
898  *
899  * Called with cpuset_mutex held
900  */
update_cpumasks_hier(struct cpuset * cs,struct cpumask * new_cpus)901 static void update_cpumasks_hier(struct cpuset *cs, struct cpumask *new_cpus)
902 {
903 	struct cpuset *cp;
904 	struct cgroup_subsys_state *pos_css;
905 	bool need_rebuild_sched_domains = false;
906 
907 	rcu_read_lock();
908 	cpuset_for_each_descendant_pre(cp, pos_css, cs) {
909 		struct cpuset *parent = parent_cs(cp);
910 
911 		cpumask_and(new_cpus, cp->cpus_allowed, parent->effective_cpus);
912 
913 		/*
914 		 * If it becomes empty, inherit the effective mask of the
915 		 * parent, which is guaranteed to have some CPUs.
916 		 */
917 		if (is_in_v2_mode() && cpumask_empty(new_cpus))
918 			cpumask_copy(new_cpus, parent->effective_cpus);
919 
920 		/* Skip the whole subtree if the cpumask remains the same. */
921 		if (cpumask_equal(new_cpus, cp->effective_cpus)) {
922 			pos_css = css_rightmost_descendant(pos_css);
923 			continue;
924 		}
925 
926 		if (!css_tryget_online(&cp->css))
927 			continue;
928 		rcu_read_unlock();
929 
930 		spin_lock_irq(&callback_lock);
931 		cpumask_copy(cp->effective_cpus, new_cpus);
932 		spin_unlock_irq(&callback_lock);
933 
934 		WARN_ON(!is_in_v2_mode() &&
935 			!cpumask_equal(cp->cpus_allowed, cp->effective_cpus));
936 
937 		update_tasks_cpumask(cp);
938 
939 		/*
940 		 * If the effective cpumask of any non-empty cpuset is changed,
941 		 * we need to rebuild sched domains.
942 		 */
943 		if (!cpumask_empty(cp->cpus_allowed) &&
944 		    is_sched_load_balance(cp))
945 			need_rebuild_sched_domains = true;
946 
947 		rcu_read_lock();
948 		css_put(&cp->css);
949 	}
950 	rcu_read_unlock();
951 
952 	if (need_rebuild_sched_domains)
953 		rebuild_sched_domains_locked();
954 }
955 
956 /**
957  * update_cpumask - update the cpus_allowed mask of a cpuset and all tasks in it
958  * @cs: the cpuset to consider
959  * @trialcs: trial cpuset
960  * @buf: buffer of cpu numbers written to this cpuset
961  */
update_cpumask(struct cpuset * cs,struct cpuset * trialcs,const char * buf)962 static int update_cpumask(struct cpuset *cs, struct cpuset *trialcs,
963 			  const char *buf)
964 {
965 	int retval;
966 
967 	/* top_cpuset.cpus_allowed tracks cpu_online_mask; it's read-only */
968 	if (cs == &top_cpuset)
969 		return -EACCES;
970 
971 	/*
972 	 * An empty cpus_allowed is ok only if the cpuset has no tasks.
973 	 * Since cpulist_parse() fails on an empty mask, we special case
974 	 * that parsing.  The validate_change() call ensures that cpusets
975 	 * with tasks have cpus.
976 	 */
977 	if (!*buf) {
978 		cpumask_clear(trialcs->cpus_allowed);
979 	} else {
980 		retval = cpulist_parse(buf, trialcs->cpus_requested);
981 		if (retval < 0)
982 			return retval;
983 
984 		if (!cpumask_subset(trialcs->cpus_requested, cpu_present_mask))
985 			return -EINVAL;
986 
987 		cpumask_and(trialcs->cpus_allowed, trialcs->cpus_requested, cpu_active_mask);
988 	}
989 
990 	/* Nothing to do if the cpus didn't change */
991 	if (cpumask_equal(cs->cpus_requested, trialcs->cpus_requested))
992 		return 0;
993 
994 	retval = validate_change(cs, trialcs);
995 	if (retval < 0)
996 		return retval;
997 
998 	spin_lock_irq(&callback_lock);
999 	cpumask_copy(cs->cpus_allowed, trialcs->cpus_allowed);
1000 	cpumask_copy(cs->cpus_requested, trialcs->cpus_requested);
1001 	spin_unlock_irq(&callback_lock);
1002 
1003 	/* use trialcs->cpus_allowed as a temp variable */
1004 	update_cpumasks_hier(cs, trialcs->cpus_allowed);
1005 	return 0;
1006 }
1007 
1008 /*
1009  * Migrate memory region from one set of nodes to another.  This is
1010  * performed asynchronously as it can be called from process migration path
1011  * holding locks involved in process management.  All mm migrations are
1012  * performed in the queued order and can be waited for by flushing
1013  * cpuset_migrate_mm_wq.
1014  */
1015 
1016 struct cpuset_migrate_mm_work {
1017 	struct work_struct	work;
1018 	struct mm_struct	*mm;
1019 	nodemask_t		from;
1020 	nodemask_t		to;
1021 };
1022 
cpuset_migrate_mm_workfn(struct work_struct * work)1023 static void cpuset_migrate_mm_workfn(struct work_struct *work)
1024 {
1025 	struct cpuset_migrate_mm_work *mwork =
1026 		container_of(work, struct cpuset_migrate_mm_work, work);
1027 
1028 	/* on a wq worker, no need to worry about %current's mems_allowed */
1029 	do_migrate_pages(mwork->mm, &mwork->from, &mwork->to, MPOL_MF_MOVE_ALL);
1030 	mmput(mwork->mm);
1031 	kfree(mwork);
1032 }
1033 
cpuset_migrate_mm(struct mm_struct * mm,const nodemask_t * from,const nodemask_t * to)1034 static void cpuset_migrate_mm(struct mm_struct *mm, const nodemask_t *from,
1035 							const nodemask_t *to)
1036 {
1037 	struct cpuset_migrate_mm_work *mwork;
1038 
1039 	mwork = kzalloc(sizeof(*mwork), GFP_KERNEL);
1040 	if (mwork) {
1041 		mwork->mm = mm;
1042 		mwork->from = *from;
1043 		mwork->to = *to;
1044 		INIT_WORK(&mwork->work, cpuset_migrate_mm_workfn);
1045 		queue_work(cpuset_migrate_mm_wq, &mwork->work);
1046 	} else {
1047 		mmput(mm);
1048 	}
1049 }
1050 
cpuset_post_attach(void)1051 static void cpuset_post_attach(void)
1052 {
1053 	flush_workqueue(cpuset_migrate_mm_wq);
1054 }
1055 
1056 /*
1057  * cpuset_change_task_nodemask - change task's mems_allowed and mempolicy
1058  * @tsk: the task to change
1059  * @newmems: new nodes that the task will be set
1060  *
1061  * We use the mems_allowed_seq seqlock to safely update both tsk->mems_allowed
1062  * and rebind an eventual tasks' mempolicy. If the task is allocating in
1063  * parallel, it might temporarily see an empty intersection, which results in
1064  * a seqlock check and retry before OOM or allocation failure.
1065  */
cpuset_change_task_nodemask(struct task_struct * tsk,nodemask_t * newmems)1066 static void cpuset_change_task_nodemask(struct task_struct *tsk,
1067 					nodemask_t *newmems)
1068 {
1069 	task_lock(tsk);
1070 
1071 	local_irq_disable();
1072 	write_seqcount_begin(&tsk->mems_allowed_seq);
1073 
1074 	nodes_or(tsk->mems_allowed, tsk->mems_allowed, *newmems);
1075 	mpol_rebind_task(tsk, newmems);
1076 	tsk->mems_allowed = *newmems;
1077 
1078 	write_seqcount_end(&tsk->mems_allowed_seq);
1079 	local_irq_enable();
1080 
1081 	task_unlock(tsk);
1082 }
1083 
1084 static void *cpuset_being_rebound;
1085 
1086 /**
1087  * update_tasks_nodemask - Update the nodemasks of tasks in the cpuset.
1088  * @cs: the cpuset in which each task's mems_allowed mask needs to be changed
1089  *
1090  * Iterate through each task of @cs updating its mems_allowed to the
1091  * effective cpuset's.  As this function is called with cpuset_mutex held,
1092  * cpuset membership stays stable.
1093  */
update_tasks_nodemask(struct cpuset * cs)1094 static void update_tasks_nodemask(struct cpuset *cs)
1095 {
1096 	static nodemask_t newmems;	/* protected by cpuset_mutex */
1097 	struct css_task_iter it;
1098 	struct task_struct *task;
1099 
1100 	cpuset_being_rebound = cs;		/* causes mpol_dup() rebind */
1101 
1102 	guarantee_online_mems(cs, &newmems);
1103 
1104 	/*
1105 	 * The mpol_rebind_mm() call takes mmap_sem, which we couldn't
1106 	 * take while holding tasklist_lock.  Forks can happen - the
1107 	 * mpol_dup() cpuset_being_rebound check will catch such forks,
1108 	 * and rebind their vma mempolicies too.  Because we still hold
1109 	 * the global cpuset_mutex, we know that no other rebind effort
1110 	 * will be contending for the global variable cpuset_being_rebound.
1111 	 * It's ok if we rebind the same mm twice; mpol_rebind_mm()
1112 	 * is idempotent.  Also migrate pages in each mm to new nodes.
1113 	 */
1114 	css_task_iter_start(&cs->css, 0, &it);
1115 	while ((task = css_task_iter_next(&it))) {
1116 		struct mm_struct *mm;
1117 		bool migrate;
1118 
1119 		cpuset_change_task_nodemask(task, &newmems);
1120 
1121 		mm = get_task_mm(task);
1122 		if (!mm)
1123 			continue;
1124 
1125 		migrate = is_memory_migrate(cs);
1126 
1127 		mpol_rebind_mm(mm, &cs->mems_allowed);
1128 		if (migrate)
1129 			cpuset_migrate_mm(mm, &cs->old_mems_allowed, &newmems);
1130 		else
1131 			mmput(mm);
1132 	}
1133 	css_task_iter_end(&it);
1134 
1135 	/*
1136 	 * All the tasks' nodemasks have been updated, update
1137 	 * cs->old_mems_allowed.
1138 	 */
1139 	cs->old_mems_allowed = newmems;
1140 
1141 	/* We're done rebinding vmas to this cpuset's new mems_allowed. */
1142 	cpuset_being_rebound = NULL;
1143 }
1144 
1145 /*
1146  * update_nodemasks_hier - Update effective nodemasks and tasks in the subtree
1147  * @cs: the cpuset to consider
1148  * @new_mems: a temp variable for calculating new effective_mems
1149  *
1150  * When configured nodemask is changed, the effective nodemasks of this cpuset
1151  * and all its descendants need to be updated.
1152  *
1153  * On legacy hiearchy, effective_mems will be the same with mems_allowed.
1154  *
1155  * Called with cpuset_mutex held
1156  */
update_nodemasks_hier(struct cpuset * cs,nodemask_t * new_mems)1157 static void update_nodemasks_hier(struct cpuset *cs, nodemask_t *new_mems)
1158 {
1159 	struct cpuset *cp;
1160 	struct cgroup_subsys_state *pos_css;
1161 
1162 	rcu_read_lock();
1163 	cpuset_for_each_descendant_pre(cp, pos_css, cs) {
1164 		struct cpuset *parent = parent_cs(cp);
1165 
1166 		nodes_and(*new_mems, cp->mems_allowed, parent->effective_mems);
1167 
1168 		/*
1169 		 * If it becomes empty, inherit the effective mask of the
1170 		 * parent, which is guaranteed to have some MEMs.
1171 		 */
1172 		if (is_in_v2_mode() && nodes_empty(*new_mems))
1173 			*new_mems = parent->effective_mems;
1174 
1175 		/* Skip the whole subtree if the nodemask remains the same. */
1176 		if (nodes_equal(*new_mems, cp->effective_mems)) {
1177 			pos_css = css_rightmost_descendant(pos_css);
1178 			continue;
1179 		}
1180 
1181 		if (!css_tryget_online(&cp->css))
1182 			continue;
1183 		rcu_read_unlock();
1184 
1185 		spin_lock_irq(&callback_lock);
1186 		cp->effective_mems = *new_mems;
1187 		spin_unlock_irq(&callback_lock);
1188 
1189 		WARN_ON(!is_in_v2_mode() &&
1190 			!nodes_equal(cp->mems_allowed, cp->effective_mems));
1191 
1192 		update_tasks_nodemask(cp);
1193 
1194 		rcu_read_lock();
1195 		css_put(&cp->css);
1196 	}
1197 	rcu_read_unlock();
1198 }
1199 
1200 /*
1201  * Handle user request to change the 'mems' memory placement
1202  * of a cpuset.  Needs to validate the request, update the
1203  * cpusets mems_allowed, and for each task in the cpuset,
1204  * update mems_allowed and rebind task's mempolicy and any vma
1205  * mempolicies and if the cpuset is marked 'memory_migrate',
1206  * migrate the tasks pages to the new memory.
1207  *
1208  * Call with cpuset_mutex held. May take callback_lock during call.
1209  * Will take tasklist_lock, scan tasklist for tasks in cpuset cs,
1210  * lock each such tasks mm->mmap_sem, scan its vma's and rebind
1211  * their mempolicies to the cpusets new mems_allowed.
1212  */
update_nodemask(struct cpuset * cs,struct cpuset * trialcs,const char * buf)1213 static int update_nodemask(struct cpuset *cs, struct cpuset *trialcs,
1214 			   const char *buf)
1215 {
1216 	int retval;
1217 
1218 	/*
1219 	 * top_cpuset.mems_allowed tracks node_stats[N_MEMORY];
1220 	 * it's read-only
1221 	 */
1222 	if (cs == &top_cpuset) {
1223 		retval = -EACCES;
1224 		goto done;
1225 	}
1226 
1227 	/*
1228 	 * An empty mems_allowed is ok iff there are no tasks in the cpuset.
1229 	 * Since nodelist_parse() fails on an empty mask, we special case
1230 	 * that parsing.  The validate_change() call ensures that cpusets
1231 	 * with tasks have memory.
1232 	 */
1233 	if (!*buf) {
1234 		nodes_clear(trialcs->mems_allowed);
1235 	} else {
1236 		retval = nodelist_parse(buf, trialcs->mems_allowed);
1237 		if (retval < 0)
1238 			goto done;
1239 
1240 		if (!nodes_subset(trialcs->mems_allowed,
1241 				  top_cpuset.mems_allowed)) {
1242 			retval = -EINVAL;
1243 			goto done;
1244 		}
1245 	}
1246 
1247 	if (nodes_equal(cs->mems_allowed, trialcs->mems_allowed)) {
1248 		retval = 0;		/* Too easy - nothing to do */
1249 		goto done;
1250 	}
1251 	retval = validate_change(cs, trialcs);
1252 	if (retval < 0)
1253 		goto done;
1254 
1255 	spin_lock_irq(&callback_lock);
1256 	cs->mems_allowed = trialcs->mems_allowed;
1257 	spin_unlock_irq(&callback_lock);
1258 
1259 	/* use trialcs->mems_allowed as a temp variable */
1260 	update_nodemasks_hier(cs, &trialcs->mems_allowed);
1261 done:
1262 	return retval;
1263 }
1264 
current_cpuset_is_being_rebound(void)1265 int current_cpuset_is_being_rebound(void)
1266 {
1267 	int ret;
1268 
1269 	rcu_read_lock();
1270 	ret = task_cs(current) == cpuset_being_rebound;
1271 	rcu_read_unlock();
1272 
1273 	return ret;
1274 }
1275 
update_relax_domain_level(struct cpuset * cs,s64 val)1276 static int update_relax_domain_level(struct cpuset *cs, s64 val)
1277 {
1278 #ifdef CONFIG_SMP
1279 	if (val < -1 || val >= sched_domain_level_max)
1280 		return -EINVAL;
1281 #endif
1282 
1283 	if (val != cs->relax_domain_level) {
1284 		cs->relax_domain_level = val;
1285 		if (!cpumask_empty(cs->cpus_allowed) &&
1286 		    is_sched_load_balance(cs))
1287 			rebuild_sched_domains_locked();
1288 	}
1289 
1290 	return 0;
1291 }
1292 
1293 /**
1294  * update_tasks_flags - update the spread flags of tasks in the cpuset.
1295  * @cs: the cpuset in which each task's spread flags needs to be changed
1296  *
1297  * Iterate through each task of @cs updating its spread flags.  As this
1298  * function is called with cpuset_mutex held, cpuset membership stays
1299  * stable.
1300  */
update_tasks_flags(struct cpuset * cs)1301 static void update_tasks_flags(struct cpuset *cs)
1302 {
1303 	struct css_task_iter it;
1304 	struct task_struct *task;
1305 
1306 	css_task_iter_start(&cs->css, 0, &it);
1307 	while ((task = css_task_iter_next(&it)))
1308 		cpuset_update_task_spread_flag(cs, task);
1309 	css_task_iter_end(&it);
1310 }
1311 
1312 /*
1313  * update_flag - read a 0 or a 1 in a file and update associated flag
1314  * bit:		the bit to update (see cpuset_flagbits_t)
1315  * cs:		the cpuset to update
1316  * turning_on: 	whether the flag is being set or cleared
1317  *
1318  * Call with cpuset_mutex held.
1319  */
1320 
update_flag(cpuset_flagbits_t bit,struct cpuset * cs,int turning_on)1321 static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs,
1322 		       int turning_on)
1323 {
1324 	struct cpuset *trialcs;
1325 	int balance_flag_changed;
1326 	int spread_flag_changed;
1327 	int err;
1328 
1329 	trialcs = alloc_trial_cpuset(cs);
1330 	if (!trialcs)
1331 		return -ENOMEM;
1332 
1333 	if (turning_on)
1334 		set_bit(bit, &trialcs->flags);
1335 	else
1336 		clear_bit(bit, &trialcs->flags);
1337 
1338 	err = validate_change(cs, trialcs);
1339 	if (err < 0)
1340 		goto out;
1341 
1342 	balance_flag_changed = (is_sched_load_balance(cs) !=
1343 				is_sched_load_balance(trialcs));
1344 
1345 	spread_flag_changed = ((is_spread_slab(cs) != is_spread_slab(trialcs))
1346 			|| (is_spread_page(cs) != is_spread_page(trialcs)));
1347 
1348 	spin_lock_irq(&callback_lock);
1349 	cs->flags = trialcs->flags;
1350 	spin_unlock_irq(&callback_lock);
1351 
1352 	if (!cpumask_empty(trialcs->cpus_allowed) && balance_flag_changed)
1353 		rebuild_sched_domains_locked();
1354 
1355 	if (spread_flag_changed)
1356 		update_tasks_flags(cs);
1357 out:
1358 	free_trial_cpuset(trialcs);
1359 	return err;
1360 }
1361 
1362 /*
1363  * Frequency meter - How fast is some event occurring?
1364  *
1365  * These routines manage a digitally filtered, constant time based,
1366  * event frequency meter.  There are four routines:
1367  *   fmeter_init() - initialize a frequency meter.
1368  *   fmeter_markevent() - called each time the event happens.
1369  *   fmeter_getrate() - returns the recent rate of such events.
1370  *   fmeter_update() - internal routine used to update fmeter.
1371  *
1372  * A common data structure is passed to each of these routines,
1373  * which is used to keep track of the state required to manage the
1374  * frequency meter and its digital filter.
1375  *
1376  * The filter works on the number of events marked per unit time.
1377  * The filter is single-pole low-pass recursive (IIR).  The time unit
1378  * is 1 second.  Arithmetic is done using 32-bit integers scaled to
1379  * simulate 3 decimal digits of precision (multiplied by 1000).
1380  *
1381  * With an FM_COEF of 933, and a time base of 1 second, the filter
1382  * has a half-life of 10 seconds, meaning that if the events quit
1383  * happening, then the rate returned from the fmeter_getrate()
1384  * will be cut in half each 10 seconds, until it converges to zero.
1385  *
1386  * It is not worth doing a real infinitely recursive filter.  If more
1387  * than FM_MAXTICKS ticks have elapsed since the last filter event,
1388  * just compute FM_MAXTICKS ticks worth, by which point the level
1389  * will be stable.
1390  *
1391  * Limit the count of unprocessed events to FM_MAXCNT, so as to avoid
1392  * arithmetic overflow in the fmeter_update() routine.
1393  *
1394  * Given the simple 32 bit integer arithmetic used, this meter works
1395  * best for reporting rates between one per millisecond (msec) and
1396  * one per 32 (approx) seconds.  At constant rates faster than one
1397  * per msec it maxes out at values just under 1,000,000.  At constant
1398  * rates between one per msec, and one per second it will stabilize
1399  * to a value N*1000, where N is the rate of events per second.
1400  * At constant rates between one per second and one per 32 seconds,
1401  * it will be choppy, moving up on the seconds that have an event,
1402  * and then decaying until the next event.  At rates slower than
1403  * about one in 32 seconds, it decays all the way back to zero between
1404  * each event.
1405  */
1406 
1407 #define FM_COEF 933		/* coefficient for half-life of 10 secs */
1408 #define FM_MAXTICKS ((u32)99)   /* useless computing more ticks than this */
1409 #define FM_MAXCNT 1000000	/* limit cnt to avoid overflow */
1410 #define FM_SCALE 1000		/* faux fixed point scale */
1411 
1412 /* Initialize a frequency meter */
fmeter_init(struct fmeter * fmp)1413 static void fmeter_init(struct fmeter *fmp)
1414 {
1415 	fmp->cnt = 0;
1416 	fmp->val = 0;
1417 	fmp->time = 0;
1418 	spin_lock_init(&fmp->lock);
1419 }
1420 
1421 /* Internal meter update - process cnt events and update value */
fmeter_update(struct fmeter * fmp)1422 static void fmeter_update(struct fmeter *fmp)
1423 {
1424 	time64_t now;
1425 	u32 ticks;
1426 
1427 	now = ktime_get_seconds();
1428 	ticks = now - fmp->time;
1429 
1430 	if (ticks == 0)
1431 		return;
1432 
1433 	ticks = min(FM_MAXTICKS, ticks);
1434 	while (ticks-- > 0)
1435 		fmp->val = (FM_COEF * fmp->val) / FM_SCALE;
1436 	fmp->time = now;
1437 
1438 	fmp->val += ((FM_SCALE - FM_COEF) * fmp->cnt) / FM_SCALE;
1439 	fmp->cnt = 0;
1440 }
1441 
1442 /* Process any previous ticks, then bump cnt by one (times scale). */
fmeter_markevent(struct fmeter * fmp)1443 static void fmeter_markevent(struct fmeter *fmp)
1444 {
1445 	spin_lock(&fmp->lock);
1446 	fmeter_update(fmp);
1447 	fmp->cnt = min(FM_MAXCNT, fmp->cnt + FM_SCALE);
1448 	spin_unlock(&fmp->lock);
1449 }
1450 
1451 /* Process any previous ticks, then return current value. */
fmeter_getrate(struct fmeter * fmp)1452 static int fmeter_getrate(struct fmeter *fmp)
1453 {
1454 	int val;
1455 
1456 	spin_lock(&fmp->lock);
1457 	fmeter_update(fmp);
1458 	val = fmp->val;
1459 	spin_unlock(&fmp->lock);
1460 	return val;
1461 }
1462 
1463 static struct cpuset *cpuset_attach_old_cs;
1464 
1465 /* Called by cgroups to determine if a cpuset is usable; cpuset_mutex held */
cpuset_can_attach(struct cgroup_taskset * tset)1466 static int cpuset_can_attach(struct cgroup_taskset *tset)
1467 {
1468 	struct cgroup_subsys_state *css;
1469 	struct cpuset *cs;
1470 	struct task_struct *task;
1471 	int ret;
1472 
1473 	/* used later by cpuset_attach() */
1474 	cpuset_attach_old_cs = task_cs(cgroup_taskset_first(tset, &css));
1475 	cs = css_cs(css);
1476 
1477 	mutex_lock(&cpuset_mutex);
1478 
1479 	/* allow moving tasks into an empty cpuset if on default hierarchy */
1480 	ret = -ENOSPC;
1481 	if (!is_in_v2_mode() &&
1482 	    (cpumask_empty(cs->cpus_allowed) || nodes_empty(cs->mems_allowed)))
1483 		goto out_unlock;
1484 
1485 	cgroup_taskset_for_each(task, css, tset) {
1486 		ret = task_can_attach(task, cs->cpus_allowed);
1487 		if (ret)
1488 			goto out_unlock;
1489 		ret = security_task_setscheduler(task);
1490 		if (ret)
1491 			goto out_unlock;
1492 	}
1493 
1494 	/*
1495 	 * Mark attach is in progress.  This makes validate_change() fail
1496 	 * changes which zero cpus/mems_allowed.
1497 	 */
1498 	cs->attach_in_progress++;
1499 	ret = 0;
1500 out_unlock:
1501 	mutex_unlock(&cpuset_mutex);
1502 	return ret;
1503 }
1504 
cpuset_cancel_attach(struct cgroup_taskset * tset)1505 static void cpuset_cancel_attach(struct cgroup_taskset *tset)
1506 {
1507 	struct cgroup_subsys_state *css;
1508 	struct cpuset *cs;
1509 
1510 	cgroup_taskset_first(tset, &css);
1511 	cs = css_cs(css);
1512 
1513 	mutex_lock(&cpuset_mutex);
1514 	css_cs(css)->attach_in_progress--;
1515 	mutex_unlock(&cpuset_mutex);
1516 }
1517 
1518 /*
1519  * Protected by cpuset_mutex.  cpus_attach is used only by cpuset_attach()
1520  * but we can't allocate it dynamically there.  Define it global and
1521  * allocate from cpuset_init().
1522  */
1523 static cpumask_var_t cpus_attach;
1524 
cpuset_attach(struct cgroup_taskset * tset)1525 static void cpuset_attach(struct cgroup_taskset *tset)
1526 {
1527 	/* static buf protected by cpuset_mutex */
1528 	static nodemask_t cpuset_attach_nodemask_to;
1529 	struct task_struct *task;
1530 	struct task_struct *leader;
1531 	struct cgroup_subsys_state *css;
1532 	struct cpuset *cs;
1533 	struct cpuset *oldcs = cpuset_attach_old_cs;
1534 
1535 	cgroup_taskset_first(tset, &css);
1536 	cs = css_cs(css);
1537 
1538 	mutex_lock(&cpuset_mutex);
1539 
1540 	/* prepare for attach */
1541 	if (cs == &top_cpuset)
1542 		cpumask_copy(cpus_attach, cpu_possible_mask);
1543 	else
1544 		guarantee_online_cpus(cs, cpus_attach);
1545 
1546 	guarantee_online_mems(cs, &cpuset_attach_nodemask_to);
1547 
1548 	cgroup_taskset_for_each(task, css, tset) {
1549 		/*
1550 		 * can_attach beforehand should guarantee that this doesn't
1551 		 * fail.  TODO: have a better way to handle failure here
1552 		 */
1553 		WARN_ON_ONCE(set_cpus_allowed_ptr(task, cpus_attach));
1554 
1555 		cpuset_change_task_nodemask(task, &cpuset_attach_nodemask_to);
1556 		cpuset_update_task_spread_flag(cs, task);
1557 	}
1558 
1559 	/*
1560 	 * Change mm for all threadgroup leaders. This is expensive and may
1561 	 * sleep and should be moved outside migration path proper.
1562 	 */
1563 	cpuset_attach_nodemask_to = cs->effective_mems;
1564 	cgroup_taskset_for_each_leader(leader, css, tset) {
1565 		struct mm_struct *mm = get_task_mm(leader);
1566 
1567 		if (mm) {
1568 			mpol_rebind_mm(mm, &cpuset_attach_nodemask_to);
1569 
1570 			/*
1571 			 * old_mems_allowed is the same with mems_allowed
1572 			 * here, except if this task is being moved
1573 			 * automatically due to hotplug.  In that case
1574 			 * @mems_allowed has been updated and is empty, so
1575 			 * @old_mems_allowed is the right nodesets that we
1576 			 * migrate mm from.
1577 			 */
1578 			if (is_memory_migrate(cs))
1579 				cpuset_migrate_mm(mm, &oldcs->old_mems_allowed,
1580 						  &cpuset_attach_nodemask_to);
1581 			else
1582 				mmput(mm);
1583 		}
1584 	}
1585 
1586 	cs->old_mems_allowed = cpuset_attach_nodemask_to;
1587 
1588 	cs->attach_in_progress--;
1589 	if (!cs->attach_in_progress)
1590 		wake_up(&cpuset_attach_wq);
1591 
1592 	mutex_unlock(&cpuset_mutex);
1593 }
1594 
1595 /* The various types of files and directories in a cpuset file system */
1596 
1597 typedef enum {
1598 	FILE_MEMORY_MIGRATE,
1599 	FILE_CPULIST,
1600 	FILE_MEMLIST,
1601 	FILE_EFFECTIVE_CPULIST,
1602 	FILE_EFFECTIVE_MEMLIST,
1603 	FILE_CPU_EXCLUSIVE,
1604 	FILE_MEM_EXCLUSIVE,
1605 	FILE_MEM_HARDWALL,
1606 	FILE_SCHED_LOAD_BALANCE,
1607 	FILE_SCHED_RELAX_DOMAIN_LEVEL,
1608 	FILE_MEMORY_PRESSURE_ENABLED,
1609 	FILE_MEMORY_PRESSURE,
1610 	FILE_SPREAD_PAGE,
1611 	FILE_SPREAD_SLAB,
1612 } cpuset_filetype_t;
1613 
cpuset_write_u64(struct cgroup_subsys_state * css,struct cftype * cft,u64 val)1614 static int cpuset_write_u64(struct cgroup_subsys_state *css, struct cftype *cft,
1615 			    u64 val)
1616 {
1617 	struct cpuset *cs = css_cs(css);
1618 	cpuset_filetype_t type = cft->private;
1619 	int retval = 0;
1620 
1621 	mutex_lock(&cpuset_mutex);
1622 	if (!is_cpuset_online(cs)) {
1623 		retval = -ENODEV;
1624 		goto out_unlock;
1625 	}
1626 
1627 	switch (type) {
1628 	case FILE_CPU_EXCLUSIVE:
1629 		retval = update_flag(CS_CPU_EXCLUSIVE, cs, val);
1630 		break;
1631 	case FILE_MEM_EXCLUSIVE:
1632 		retval = update_flag(CS_MEM_EXCLUSIVE, cs, val);
1633 		break;
1634 	case FILE_MEM_HARDWALL:
1635 		retval = update_flag(CS_MEM_HARDWALL, cs, val);
1636 		break;
1637 	case FILE_SCHED_LOAD_BALANCE:
1638 		retval = update_flag(CS_SCHED_LOAD_BALANCE, cs, val);
1639 		break;
1640 	case FILE_MEMORY_MIGRATE:
1641 		retval = update_flag(CS_MEMORY_MIGRATE, cs, val);
1642 		break;
1643 	case FILE_MEMORY_PRESSURE_ENABLED:
1644 		cpuset_memory_pressure_enabled = !!val;
1645 		break;
1646 	case FILE_SPREAD_PAGE:
1647 		retval = update_flag(CS_SPREAD_PAGE, cs, val);
1648 		break;
1649 	case FILE_SPREAD_SLAB:
1650 		retval = update_flag(CS_SPREAD_SLAB, cs, val);
1651 		break;
1652 	default:
1653 		retval = -EINVAL;
1654 		break;
1655 	}
1656 out_unlock:
1657 	mutex_unlock(&cpuset_mutex);
1658 	return retval;
1659 }
1660 
cpuset_write_s64(struct cgroup_subsys_state * css,struct cftype * cft,s64 val)1661 static int cpuset_write_s64(struct cgroup_subsys_state *css, struct cftype *cft,
1662 			    s64 val)
1663 {
1664 	struct cpuset *cs = css_cs(css);
1665 	cpuset_filetype_t type = cft->private;
1666 	int retval = -ENODEV;
1667 
1668 	mutex_lock(&cpuset_mutex);
1669 	if (!is_cpuset_online(cs))
1670 		goto out_unlock;
1671 
1672 	switch (type) {
1673 	case FILE_SCHED_RELAX_DOMAIN_LEVEL:
1674 		retval = update_relax_domain_level(cs, val);
1675 		break;
1676 	default:
1677 		retval = -EINVAL;
1678 		break;
1679 	}
1680 out_unlock:
1681 	mutex_unlock(&cpuset_mutex);
1682 	return retval;
1683 }
1684 
1685 /*
1686  * Common handling for a write to a "cpus" or "mems" file.
1687  */
cpuset_write_resmask(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)1688 static ssize_t cpuset_write_resmask(struct kernfs_open_file *of,
1689 				    char *buf, size_t nbytes, loff_t off)
1690 {
1691 	struct cpuset *cs = css_cs(of_css(of));
1692 	struct cpuset *trialcs;
1693 	int retval = -ENODEV;
1694 
1695 	buf = strstrip(buf);
1696 
1697 	/*
1698 	 * CPU or memory hotunplug may leave @cs w/o any execution
1699 	 * resources, in which case the hotplug code asynchronously updates
1700 	 * configuration and transfers all tasks to the nearest ancestor
1701 	 * which can execute.
1702 	 *
1703 	 * As writes to "cpus" or "mems" may restore @cs's execution
1704 	 * resources, wait for the previously scheduled operations before
1705 	 * proceeding, so that we don't end up keep removing tasks added
1706 	 * after execution capability is restored.
1707 	 *
1708 	 * cpuset_hotplug_work calls back into cgroup core via
1709 	 * cgroup_transfer_tasks() and waiting for it from a cgroupfs
1710 	 * operation like this one can lead to a deadlock through kernfs
1711 	 * active_ref protection.  Let's break the protection.  Losing the
1712 	 * protection is okay as we check whether @cs is online after
1713 	 * grabbing cpuset_mutex anyway.  This only happens on the legacy
1714 	 * hierarchies.
1715 	 */
1716 	css_get(&cs->css);
1717 	kernfs_break_active_protection(of->kn);
1718 	flush_work(&cpuset_hotplug_work);
1719 
1720 	mutex_lock(&cpuset_mutex);
1721 	if (!is_cpuset_online(cs))
1722 		goto out_unlock;
1723 
1724 	trialcs = alloc_trial_cpuset(cs);
1725 	if (!trialcs) {
1726 		retval = -ENOMEM;
1727 		goto out_unlock;
1728 	}
1729 
1730 	switch (of_cft(of)->private) {
1731 	case FILE_CPULIST:
1732 		retval = update_cpumask(cs, trialcs, buf);
1733 		break;
1734 	case FILE_MEMLIST:
1735 		retval = update_nodemask(cs, trialcs, buf);
1736 		break;
1737 	default:
1738 		retval = -EINVAL;
1739 		break;
1740 	}
1741 
1742 	free_trial_cpuset(trialcs);
1743 out_unlock:
1744 	mutex_unlock(&cpuset_mutex);
1745 	kernfs_unbreak_active_protection(of->kn);
1746 	css_put(&cs->css);
1747 	flush_workqueue(cpuset_migrate_mm_wq);
1748 	return retval ?: nbytes;
1749 }
1750 
1751 /*
1752  * These ascii lists should be read in a single call, by using a user
1753  * buffer large enough to hold the entire map.  If read in smaller
1754  * chunks, there is no guarantee of atomicity.  Since the display format
1755  * used, list of ranges of sequential numbers, is variable length,
1756  * and since these maps can change value dynamically, one could read
1757  * gibberish by doing partial reads while a list was changing.
1758  */
cpuset_common_seq_show(struct seq_file * sf,void * v)1759 static int cpuset_common_seq_show(struct seq_file *sf, void *v)
1760 {
1761 	struct cpuset *cs = css_cs(seq_css(sf));
1762 	cpuset_filetype_t type = seq_cft(sf)->private;
1763 	int ret = 0;
1764 
1765 	spin_lock_irq(&callback_lock);
1766 
1767 	switch (type) {
1768 	case FILE_CPULIST:
1769 		seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->cpus_requested));
1770 		break;
1771 	case FILE_MEMLIST:
1772 		seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->mems_allowed));
1773 		break;
1774 	case FILE_EFFECTIVE_CPULIST:
1775 		seq_printf(sf, "%*pbl\n", cpumask_pr_args(cs->effective_cpus));
1776 		break;
1777 	case FILE_EFFECTIVE_MEMLIST:
1778 		seq_printf(sf, "%*pbl\n", nodemask_pr_args(&cs->effective_mems));
1779 		break;
1780 	default:
1781 		ret = -EINVAL;
1782 	}
1783 
1784 	spin_unlock_irq(&callback_lock);
1785 	return ret;
1786 }
1787 
cpuset_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)1788 static u64 cpuset_read_u64(struct cgroup_subsys_state *css, struct cftype *cft)
1789 {
1790 	struct cpuset *cs = css_cs(css);
1791 	cpuset_filetype_t type = cft->private;
1792 	switch (type) {
1793 	case FILE_CPU_EXCLUSIVE:
1794 		return is_cpu_exclusive(cs);
1795 	case FILE_MEM_EXCLUSIVE:
1796 		return is_mem_exclusive(cs);
1797 	case FILE_MEM_HARDWALL:
1798 		return is_mem_hardwall(cs);
1799 	case FILE_SCHED_LOAD_BALANCE:
1800 		return is_sched_load_balance(cs);
1801 	case FILE_MEMORY_MIGRATE:
1802 		return is_memory_migrate(cs);
1803 	case FILE_MEMORY_PRESSURE_ENABLED:
1804 		return cpuset_memory_pressure_enabled;
1805 	case FILE_MEMORY_PRESSURE:
1806 		return fmeter_getrate(&cs->fmeter);
1807 	case FILE_SPREAD_PAGE:
1808 		return is_spread_page(cs);
1809 	case FILE_SPREAD_SLAB:
1810 		return is_spread_slab(cs);
1811 	default:
1812 		BUG();
1813 	}
1814 
1815 	/* Unreachable but makes gcc happy */
1816 	return 0;
1817 }
1818 
cpuset_read_s64(struct cgroup_subsys_state * css,struct cftype * cft)1819 static s64 cpuset_read_s64(struct cgroup_subsys_state *css, struct cftype *cft)
1820 {
1821 	struct cpuset *cs = css_cs(css);
1822 	cpuset_filetype_t type = cft->private;
1823 	switch (type) {
1824 	case FILE_SCHED_RELAX_DOMAIN_LEVEL:
1825 		return cs->relax_domain_level;
1826 	default:
1827 		BUG();
1828 	}
1829 
1830 	/* Unrechable but makes gcc happy */
1831 	return 0;
1832 }
1833 
1834 
1835 /*
1836  * for the common functions, 'private' gives the type of file
1837  */
1838 
1839 static struct cftype files[] = {
1840 	{
1841 		.name = "cpus",
1842 		.seq_show = cpuset_common_seq_show,
1843 		.write = cpuset_write_resmask,
1844 		.max_write_len = (100U + 6 * NR_CPUS),
1845 		.private = FILE_CPULIST,
1846 	},
1847 
1848 	{
1849 		.name = "mems",
1850 		.seq_show = cpuset_common_seq_show,
1851 		.write = cpuset_write_resmask,
1852 		.max_write_len = (100U + 6 * MAX_NUMNODES),
1853 		.private = FILE_MEMLIST,
1854 	},
1855 
1856 	{
1857 		.name = "effective_cpus",
1858 		.seq_show = cpuset_common_seq_show,
1859 		.private = FILE_EFFECTIVE_CPULIST,
1860 	},
1861 
1862 	{
1863 		.name = "effective_mems",
1864 		.seq_show = cpuset_common_seq_show,
1865 		.private = FILE_EFFECTIVE_MEMLIST,
1866 	},
1867 
1868 	{
1869 		.name = "cpu_exclusive",
1870 		.read_u64 = cpuset_read_u64,
1871 		.write_u64 = cpuset_write_u64,
1872 		.private = FILE_CPU_EXCLUSIVE,
1873 	},
1874 
1875 	{
1876 		.name = "mem_exclusive",
1877 		.read_u64 = cpuset_read_u64,
1878 		.write_u64 = cpuset_write_u64,
1879 		.private = FILE_MEM_EXCLUSIVE,
1880 	},
1881 
1882 	{
1883 		.name = "mem_hardwall",
1884 		.read_u64 = cpuset_read_u64,
1885 		.write_u64 = cpuset_write_u64,
1886 		.private = FILE_MEM_HARDWALL,
1887 	},
1888 
1889 	{
1890 		.name = "sched_load_balance",
1891 		.read_u64 = cpuset_read_u64,
1892 		.write_u64 = cpuset_write_u64,
1893 		.private = FILE_SCHED_LOAD_BALANCE,
1894 	},
1895 
1896 	{
1897 		.name = "sched_relax_domain_level",
1898 		.read_s64 = cpuset_read_s64,
1899 		.write_s64 = cpuset_write_s64,
1900 		.private = FILE_SCHED_RELAX_DOMAIN_LEVEL,
1901 	},
1902 
1903 	{
1904 		.name = "memory_migrate",
1905 		.read_u64 = cpuset_read_u64,
1906 		.write_u64 = cpuset_write_u64,
1907 		.private = FILE_MEMORY_MIGRATE,
1908 	},
1909 
1910 	{
1911 		.name = "memory_pressure",
1912 		.read_u64 = cpuset_read_u64,
1913 		.private = FILE_MEMORY_PRESSURE,
1914 	},
1915 
1916 	{
1917 		.name = "memory_spread_page",
1918 		.read_u64 = cpuset_read_u64,
1919 		.write_u64 = cpuset_write_u64,
1920 		.private = FILE_SPREAD_PAGE,
1921 	},
1922 
1923 	{
1924 		.name = "memory_spread_slab",
1925 		.read_u64 = cpuset_read_u64,
1926 		.write_u64 = cpuset_write_u64,
1927 		.private = FILE_SPREAD_SLAB,
1928 	},
1929 
1930 	{
1931 		.name = "memory_pressure_enabled",
1932 		.flags = CFTYPE_ONLY_ON_ROOT,
1933 		.read_u64 = cpuset_read_u64,
1934 		.write_u64 = cpuset_write_u64,
1935 		.private = FILE_MEMORY_PRESSURE_ENABLED,
1936 	},
1937 
1938 	{ }	/* terminate */
1939 };
1940 
1941 /*
1942  *	cpuset_css_alloc - allocate a cpuset css
1943  *	cgrp:	control group that the new cpuset will be part of
1944  */
1945 
1946 static struct cgroup_subsys_state *
cpuset_css_alloc(struct cgroup_subsys_state * parent_css)1947 cpuset_css_alloc(struct cgroup_subsys_state *parent_css)
1948 {
1949 	struct cpuset *cs;
1950 
1951 	if (!parent_css)
1952 		return &top_cpuset.css;
1953 
1954 	cs = kzalloc(sizeof(*cs), GFP_KERNEL);
1955 	if (!cs)
1956 		return ERR_PTR(-ENOMEM);
1957 	if (!alloc_cpumask_var(&cs->cpus_allowed, GFP_KERNEL))
1958 		goto free_cs;
1959 	if (!alloc_cpumask_var(&cs->cpus_requested, GFP_KERNEL))
1960 		goto free_allowed;
1961 	if (!alloc_cpumask_var(&cs->effective_cpus, GFP_KERNEL))
1962 		goto free_requested;
1963 
1964 	set_bit(CS_SCHED_LOAD_BALANCE, &cs->flags);
1965 	cpumask_clear(cs->cpus_allowed);
1966 	cpumask_clear(cs->cpus_requested);
1967 	nodes_clear(cs->mems_allowed);
1968 	cpumask_clear(cs->effective_cpus);
1969 	nodes_clear(cs->effective_mems);
1970 	fmeter_init(&cs->fmeter);
1971 	cs->relax_domain_level = -1;
1972 
1973 	return &cs->css;
1974 
1975 free_requested:
1976 	free_cpumask_var(cs->cpus_requested);
1977 free_allowed:
1978 	free_cpumask_var(cs->cpus_allowed);
1979 free_cs:
1980 	kfree(cs);
1981 	return ERR_PTR(-ENOMEM);
1982 }
1983 
cpuset_css_online(struct cgroup_subsys_state * css)1984 static int cpuset_css_online(struct cgroup_subsys_state *css)
1985 {
1986 	struct cpuset *cs = css_cs(css);
1987 	struct cpuset *parent = parent_cs(cs);
1988 	struct cpuset *tmp_cs;
1989 	struct cgroup_subsys_state *pos_css;
1990 
1991 	if (!parent)
1992 		return 0;
1993 
1994 	mutex_lock(&cpuset_mutex);
1995 
1996 	set_bit(CS_ONLINE, &cs->flags);
1997 	if (is_spread_page(parent))
1998 		set_bit(CS_SPREAD_PAGE, &cs->flags);
1999 	if (is_spread_slab(parent))
2000 		set_bit(CS_SPREAD_SLAB, &cs->flags);
2001 
2002 	cpuset_inc();
2003 
2004 	spin_lock_irq(&callback_lock);
2005 	if (is_in_v2_mode()) {
2006 		cpumask_copy(cs->effective_cpus, parent->effective_cpus);
2007 		cs->effective_mems = parent->effective_mems;
2008 	}
2009 	spin_unlock_irq(&callback_lock);
2010 
2011 	if (!test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags))
2012 		goto out_unlock;
2013 
2014 	/*
2015 	 * Clone @parent's configuration if CGRP_CPUSET_CLONE_CHILDREN is
2016 	 * set.  This flag handling is implemented in cgroup core for
2017 	 * histrical reasons - the flag may be specified during mount.
2018 	 *
2019 	 * Currently, if any sibling cpusets have exclusive cpus or mem, we
2020 	 * refuse to clone the configuration - thereby refusing the task to
2021 	 * be entered, and as a result refusing the sys_unshare() or
2022 	 * clone() which initiated it.  If this becomes a problem for some
2023 	 * users who wish to allow that scenario, then this could be
2024 	 * changed to grant parent->cpus_allowed-sibling_cpus_exclusive
2025 	 * (and likewise for mems) to the new cgroup.
2026 	 */
2027 	rcu_read_lock();
2028 	cpuset_for_each_child(tmp_cs, pos_css, parent) {
2029 		if (is_mem_exclusive(tmp_cs) || is_cpu_exclusive(tmp_cs)) {
2030 			rcu_read_unlock();
2031 			goto out_unlock;
2032 		}
2033 	}
2034 	rcu_read_unlock();
2035 
2036 	spin_lock_irq(&callback_lock);
2037 	cs->mems_allowed = parent->mems_allowed;
2038 	cs->effective_mems = parent->mems_allowed;
2039 	cpumask_copy(cs->cpus_allowed, parent->cpus_allowed);
2040 	cpumask_copy(cs->cpus_requested, parent->cpus_requested);
2041 	cpumask_copy(cs->effective_cpus, parent->cpus_allowed);
2042 	spin_unlock_irq(&callback_lock);
2043 out_unlock:
2044 	mutex_unlock(&cpuset_mutex);
2045 	return 0;
2046 }
2047 
2048 /*
2049  * If the cpuset being removed has its flag 'sched_load_balance'
2050  * enabled, then simulate turning sched_load_balance off, which
2051  * will call rebuild_sched_domains_locked().
2052  */
2053 
cpuset_css_offline(struct cgroup_subsys_state * css)2054 static void cpuset_css_offline(struct cgroup_subsys_state *css)
2055 {
2056 	struct cpuset *cs = css_cs(css);
2057 
2058 	mutex_lock(&cpuset_mutex);
2059 
2060 	if (is_sched_load_balance(cs))
2061 		update_flag(CS_SCHED_LOAD_BALANCE, cs, 0);
2062 
2063 	cpuset_dec();
2064 	clear_bit(CS_ONLINE, &cs->flags);
2065 
2066 	mutex_unlock(&cpuset_mutex);
2067 }
2068 
cpuset_css_free(struct cgroup_subsys_state * css)2069 static void cpuset_css_free(struct cgroup_subsys_state *css)
2070 {
2071 	struct cpuset *cs = css_cs(css);
2072 
2073 	free_cpumask_var(cs->effective_cpus);
2074 	free_cpumask_var(cs->cpus_allowed);
2075 	free_cpumask_var(cs->cpus_requested);
2076 	kfree(cs);
2077 }
2078 
cpuset_bind(struct cgroup_subsys_state * root_css)2079 static void cpuset_bind(struct cgroup_subsys_state *root_css)
2080 {
2081 	mutex_lock(&cpuset_mutex);
2082 	spin_lock_irq(&callback_lock);
2083 
2084 	if (is_in_v2_mode()) {
2085 		cpumask_copy(top_cpuset.cpus_allowed, cpu_possible_mask);
2086 		top_cpuset.mems_allowed = node_possible_map;
2087 	} else {
2088 		cpumask_copy(top_cpuset.cpus_allowed,
2089 			     top_cpuset.effective_cpus);
2090 		top_cpuset.mems_allowed = top_cpuset.effective_mems;
2091 	}
2092 
2093 	spin_unlock_irq(&callback_lock);
2094 	mutex_unlock(&cpuset_mutex);
2095 }
2096 
2097 /*
2098  * Make sure the new task conform to the current state of its parent,
2099  * which could have been changed by cpuset just after it inherits the
2100  * state from the parent and before it sits on the cgroup's task list.
2101  */
cpuset_fork(struct task_struct * task)2102 static void cpuset_fork(struct task_struct *task)
2103 {
2104 	if (task_css_is_root(task, cpuset_cgrp_id))
2105 		return;
2106 
2107 	set_cpus_allowed_ptr(task, &current->cpus_allowed);
2108 	task->mems_allowed = current->mems_allowed;
2109 }
2110 
2111 struct cgroup_subsys cpuset_cgrp_subsys = {
2112 	.css_alloc	= cpuset_css_alloc,
2113 	.css_online	= cpuset_css_online,
2114 	.css_offline	= cpuset_css_offline,
2115 	.css_free	= cpuset_css_free,
2116 	.can_attach	= cpuset_can_attach,
2117 	.cancel_attach	= cpuset_cancel_attach,
2118 	.attach		= cpuset_attach,
2119 	.post_attach	= cpuset_post_attach,
2120 	.bind		= cpuset_bind,
2121 	.fork		= cpuset_fork,
2122 	.legacy_cftypes	= files,
2123 	.early_init	= true,
2124 };
2125 
2126 /**
2127  * cpuset_init - initialize cpusets at system boot
2128  *
2129  * Description: Initialize top_cpuset and the cpuset internal file system,
2130  **/
2131 
cpuset_init(void)2132 int __init cpuset_init(void)
2133 {
2134 	int err = 0;
2135 
2136 	BUG_ON(!alloc_cpumask_var(&top_cpuset.cpus_allowed, GFP_KERNEL));
2137 	BUG_ON(!alloc_cpumask_var(&top_cpuset.effective_cpus, GFP_KERNEL));
2138 	BUG_ON(!alloc_cpumask_var(&top_cpuset.cpus_requested, GFP_KERNEL));
2139 
2140 	cpumask_setall(top_cpuset.cpus_allowed);
2141 	cpumask_setall(top_cpuset.cpus_requested);
2142 	nodes_setall(top_cpuset.mems_allowed);
2143 	cpumask_setall(top_cpuset.effective_cpus);
2144 	nodes_setall(top_cpuset.effective_mems);
2145 
2146 	fmeter_init(&top_cpuset.fmeter);
2147 	set_bit(CS_SCHED_LOAD_BALANCE, &top_cpuset.flags);
2148 	top_cpuset.relax_domain_level = -1;
2149 
2150 	err = register_filesystem(&cpuset_fs_type);
2151 	if (err < 0)
2152 		return err;
2153 
2154 	BUG_ON(!alloc_cpumask_var(&cpus_attach, GFP_KERNEL));
2155 
2156 	return 0;
2157 }
2158 
2159 /*
2160  * If CPU and/or memory hotplug handlers, below, unplug any CPUs
2161  * or memory nodes, we need to walk over the cpuset hierarchy,
2162  * removing that CPU or node from all cpusets.  If this removes the
2163  * last CPU or node from a cpuset, then move the tasks in the empty
2164  * cpuset to its next-highest non-empty parent.
2165  */
remove_tasks_in_empty_cpuset(struct cpuset * cs)2166 static void remove_tasks_in_empty_cpuset(struct cpuset *cs)
2167 {
2168 	struct cpuset *parent;
2169 
2170 	/*
2171 	 * Find its next-highest non-empty parent, (top cpuset
2172 	 * has online cpus, so can't be empty).
2173 	 */
2174 	parent = parent_cs(cs);
2175 	while (cpumask_empty(parent->cpus_allowed) ||
2176 			nodes_empty(parent->mems_allowed))
2177 		parent = parent_cs(parent);
2178 
2179 	if (cgroup_transfer_tasks(parent->css.cgroup, cs->css.cgroup)) {
2180 		pr_err("cpuset: failed to transfer tasks out of empty cpuset ");
2181 		pr_cont_cgroup_name(cs->css.cgroup);
2182 		pr_cont("\n");
2183 	}
2184 }
2185 
2186 static void
hotplug_update_tasks_legacy(struct cpuset * cs,struct cpumask * new_cpus,nodemask_t * new_mems,bool cpus_updated,bool mems_updated)2187 hotplug_update_tasks_legacy(struct cpuset *cs,
2188 			    struct cpumask *new_cpus, nodemask_t *new_mems,
2189 			    bool cpus_updated, bool mems_updated)
2190 {
2191 	bool is_empty;
2192 
2193 	spin_lock_irq(&callback_lock);
2194 	cpumask_copy(cs->cpus_allowed, new_cpus);
2195 	cpumask_copy(cs->effective_cpus, new_cpus);
2196 	cs->mems_allowed = *new_mems;
2197 	cs->effective_mems = *new_mems;
2198 	spin_unlock_irq(&callback_lock);
2199 
2200 	/*
2201 	 * Don't call update_tasks_cpumask() if the cpuset becomes empty,
2202 	 * as the tasks will be migratecd to an ancestor.
2203 	 */
2204 	if (cpus_updated && !cpumask_empty(cs->cpus_allowed))
2205 		update_tasks_cpumask(cs);
2206 	if (mems_updated && !nodes_empty(cs->mems_allowed))
2207 		update_tasks_nodemask(cs);
2208 
2209 	is_empty = cpumask_empty(cs->cpus_allowed) ||
2210 		   nodes_empty(cs->mems_allowed);
2211 
2212 	mutex_unlock(&cpuset_mutex);
2213 
2214 	/*
2215 	 * Move tasks to the nearest ancestor with execution resources,
2216 	 * This is full cgroup operation which will also call back into
2217 	 * cpuset. Should be done outside any lock.
2218 	 */
2219 	if (is_empty)
2220 		remove_tasks_in_empty_cpuset(cs);
2221 
2222 	mutex_lock(&cpuset_mutex);
2223 }
2224 
2225 static void
hotplug_update_tasks(struct cpuset * cs,struct cpumask * new_cpus,nodemask_t * new_mems,bool cpus_updated,bool mems_updated)2226 hotplug_update_tasks(struct cpuset *cs,
2227 		     struct cpumask *new_cpus, nodemask_t *new_mems,
2228 		     bool cpus_updated, bool mems_updated)
2229 {
2230 	if (cpumask_empty(new_cpus))
2231 		cpumask_copy(new_cpus, parent_cs(cs)->effective_cpus);
2232 	if (nodes_empty(*new_mems))
2233 		*new_mems = parent_cs(cs)->effective_mems;
2234 
2235 	spin_lock_irq(&callback_lock);
2236 	cpumask_copy(cs->effective_cpus, new_cpus);
2237 	cs->effective_mems = *new_mems;
2238 	spin_unlock_irq(&callback_lock);
2239 
2240 	if (cpus_updated)
2241 		update_tasks_cpumask(cs);
2242 	if (mems_updated)
2243 		update_tasks_nodemask(cs);
2244 }
2245 
2246 /**
2247  * cpuset_hotplug_update_tasks - update tasks in a cpuset for hotunplug
2248  * @cs: cpuset in interest
2249  *
2250  * Compare @cs's cpu and mem masks against top_cpuset and if some have gone
2251  * offline, update @cs accordingly.  If @cs ends up with no CPU or memory,
2252  * all its tasks are moved to the nearest ancestor with both resources.
2253  */
cpuset_hotplug_update_tasks(struct cpuset * cs)2254 static void cpuset_hotplug_update_tasks(struct cpuset *cs)
2255 {
2256 	static cpumask_t new_cpus;
2257 	static nodemask_t new_mems;
2258 	bool cpus_updated;
2259 	bool mems_updated;
2260 retry:
2261 	wait_event(cpuset_attach_wq, cs->attach_in_progress == 0);
2262 
2263 	mutex_lock(&cpuset_mutex);
2264 
2265 	/*
2266 	 * We have raced with task attaching. We wait until attaching
2267 	 * is finished, so we won't attach a task to an empty cpuset.
2268 	 */
2269 	if (cs->attach_in_progress) {
2270 		mutex_unlock(&cpuset_mutex);
2271 		goto retry;
2272 	}
2273 
2274 	cpumask_and(&new_cpus, cs->cpus_requested, parent_cs(cs)->effective_cpus);
2275 	nodes_and(new_mems, cs->mems_allowed, parent_cs(cs)->effective_mems);
2276 
2277 	cpus_updated = !cpumask_equal(&new_cpus, cs->effective_cpus);
2278 	mems_updated = !nodes_equal(new_mems, cs->effective_mems);
2279 
2280 	if (is_in_v2_mode())
2281 		hotplug_update_tasks(cs, &new_cpus, &new_mems,
2282 				     cpus_updated, mems_updated);
2283 	else
2284 		hotplug_update_tasks_legacy(cs, &new_cpus, &new_mems,
2285 					    cpus_updated, mems_updated);
2286 
2287 	mutex_unlock(&cpuset_mutex);
2288 }
2289 
2290 static bool force_rebuild;
2291 
cpuset_force_rebuild(void)2292 void cpuset_force_rebuild(void)
2293 {
2294 	force_rebuild = true;
2295 }
2296 
2297 /**
2298  * cpuset_hotplug_workfn - handle CPU/memory hotunplug for a cpuset
2299  *
2300  * This function is called after either CPU or memory configuration has
2301  * changed and updates cpuset accordingly.  The top_cpuset is always
2302  * synchronized to cpu_active_mask and N_MEMORY, which is necessary in
2303  * order to make cpusets transparent (of no affect) on systems that are
2304  * actively using CPU hotplug but making no active use of cpusets.
2305  *
2306  * Non-root cpusets are only affected by offlining.  If any CPUs or memory
2307  * nodes have been taken down, cpuset_hotplug_update_tasks() is invoked on
2308  * all descendants.
2309  *
2310  * Note that CPU offlining during suspend is ignored.  We don't modify
2311  * cpusets across suspend/resume cycles at all.
2312  */
cpuset_hotplug_workfn(struct work_struct * work)2313 static void cpuset_hotplug_workfn(struct work_struct *work)
2314 {
2315 	static cpumask_t new_cpus;
2316 	static nodemask_t new_mems;
2317 	bool cpus_updated, mems_updated;
2318 	bool on_dfl = is_in_v2_mode();
2319 
2320 	mutex_lock(&cpuset_mutex);
2321 
2322 	/* fetch the available cpus/mems and find out which changed how */
2323 	cpumask_copy(&new_cpus, cpu_active_mask);
2324 	new_mems = node_states[N_MEMORY];
2325 
2326 	cpus_updated = !cpumask_equal(top_cpuset.effective_cpus, &new_cpus);
2327 	mems_updated = !nodes_equal(top_cpuset.effective_mems, new_mems);
2328 
2329 	/* synchronize cpus_allowed to cpu_active_mask */
2330 	if (cpus_updated) {
2331 		spin_lock_irq(&callback_lock);
2332 		if (!on_dfl)
2333 			cpumask_copy(top_cpuset.cpus_allowed, &new_cpus);
2334 		cpumask_copy(top_cpuset.effective_cpus, &new_cpus);
2335 		spin_unlock_irq(&callback_lock);
2336 		/* we don't mess with cpumasks of tasks in top_cpuset */
2337 	}
2338 
2339 	/* synchronize mems_allowed to N_MEMORY */
2340 	if (mems_updated) {
2341 		spin_lock_irq(&callback_lock);
2342 		if (!on_dfl)
2343 			top_cpuset.mems_allowed = new_mems;
2344 		top_cpuset.effective_mems = new_mems;
2345 		spin_unlock_irq(&callback_lock);
2346 		update_tasks_nodemask(&top_cpuset);
2347 	}
2348 
2349 	mutex_unlock(&cpuset_mutex);
2350 
2351 	/* if cpus or mems changed, we need to propagate to descendants */
2352 	if (cpus_updated || mems_updated) {
2353 		struct cpuset *cs;
2354 		struct cgroup_subsys_state *pos_css;
2355 
2356 		rcu_read_lock();
2357 		cpuset_for_each_descendant_pre(cs, pos_css, &top_cpuset) {
2358 			if (cs == &top_cpuset || !css_tryget_online(&cs->css))
2359 				continue;
2360 			rcu_read_unlock();
2361 
2362 			cpuset_hotplug_update_tasks(cs);
2363 
2364 			rcu_read_lock();
2365 			css_put(&cs->css);
2366 		}
2367 		rcu_read_unlock();
2368 	}
2369 
2370 	/* rebuild sched domains if cpus_allowed has changed */
2371 	if (cpus_updated || force_rebuild) {
2372 		force_rebuild = false;
2373 		rebuild_sched_domains();
2374 	}
2375 }
2376 
cpuset_update_active_cpus(void)2377 void cpuset_update_active_cpus(void)
2378 {
2379 	/*
2380 	 * We're inside cpu hotplug critical region which usually nests
2381 	 * inside cgroup synchronization.  Bounce actual hotplug processing
2382 	 * to a work item to avoid reverse locking order.
2383 	 */
2384 	schedule_work(&cpuset_hotplug_work);
2385 }
2386 
cpuset_wait_for_hotplug(void)2387 void cpuset_wait_for_hotplug(void)
2388 {
2389 	flush_work(&cpuset_hotplug_work);
2390 }
2391 
2392 /*
2393  * Keep top_cpuset.mems_allowed tracking node_states[N_MEMORY].
2394  * Call this routine anytime after node_states[N_MEMORY] changes.
2395  * See cpuset_update_active_cpus() for CPU hotplug handling.
2396  */
cpuset_track_online_nodes(struct notifier_block * self,unsigned long action,void * arg)2397 static int cpuset_track_online_nodes(struct notifier_block *self,
2398 				unsigned long action, void *arg)
2399 {
2400 	schedule_work(&cpuset_hotplug_work);
2401 	return NOTIFY_OK;
2402 }
2403 
2404 static struct notifier_block cpuset_track_online_nodes_nb = {
2405 	.notifier_call = cpuset_track_online_nodes,
2406 	.priority = 10,		/* ??! */
2407 };
2408 
2409 /**
2410  * cpuset_init_smp - initialize cpus_allowed
2411  *
2412  * Description: Finish top cpuset after cpu, node maps are initialized
2413  */
cpuset_init_smp(void)2414 void __init cpuset_init_smp(void)
2415 {
2416 	cpumask_copy(top_cpuset.cpus_allowed, cpu_active_mask);
2417 	top_cpuset.mems_allowed = node_states[N_MEMORY];
2418 	top_cpuset.old_mems_allowed = top_cpuset.mems_allowed;
2419 
2420 	cpumask_copy(top_cpuset.effective_cpus, cpu_active_mask);
2421 	top_cpuset.effective_mems = node_states[N_MEMORY];
2422 
2423 	register_hotmemory_notifier(&cpuset_track_online_nodes_nb);
2424 
2425 	cpuset_migrate_mm_wq = alloc_ordered_workqueue("cpuset_migrate_mm", 0);
2426 	BUG_ON(!cpuset_migrate_mm_wq);
2427 }
2428 
2429 /**
2430  * cpuset_cpus_allowed - return cpus_allowed mask from a tasks cpuset.
2431  * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
2432  * @pmask: pointer to struct cpumask variable to receive cpus_allowed set.
2433  *
2434  * Description: Returns the cpumask_var_t cpus_allowed of the cpuset
2435  * attached to the specified @tsk.  Guaranteed to return some non-empty
2436  * subset of cpu_online_mask, even if this means going outside the
2437  * tasks cpuset.
2438  **/
2439 
cpuset_cpus_allowed(struct task_struct * tsk,struct cpumask * pmask)2440 void cpuset_cpus_allowed(struct task_struct *tsk, struct cpumask *pmask)
2441 {
2442 	unsigned long flags;
2443 
2444 	spin_lock_irqsave(&callback_lock, flags);
2445 	rcu_read_lock();
2446 	guarantee_online_cpus(task_cs(tsk), pmask);
2447 	rcu_read_unlock();
2448 	spin_unlock_irqrestore(&callback_lock, flags);
2449 }
2450 
2451 /**
2452  * cpuset_cpus_allowed_fallback - final fallback before complete catastrophe.
2453  * @tsk: pointer to task_struct with which the scheduler is struggling
2454  *
2455  * Description: In the case that the scheduler cannot find an allowed cpu in
2456  * tsk->cpus_allowed, we fall back to task_cs(tsk)->cpus_allowed. In legacy
2457  * mode however, this value is the same as task_cs(tsk)->effective_cpus,
2458  * which will not contain a sane cpumask during cases such as cpu hotplugging.
2459  * This is the absolute last resort for the scheduler and it is only used if
2460  * _every_ other avenue has been traveled.
2461  **/
2462 
cpuset_cpus_allowed_fallback(struct task_struct * tsk)2463 void cpuset_cpus_allowed_fallback(struct task_struct *tsk)
2464 {
2465 	rcu_read_lock();
2466 	do_set_cpus_allowed(tsk, is_in_v2_mode() ?
2467 		task_cs(tsk)->cpus_allowed : cpu_possible_mask);
2468 	rcu_read_unlock();
2469 
2470 	/*
2471 	 * We own tsk->cpus_allowed, nobody can change it under us.
2472 	 *
2473 	 * But we used cs && cs->cpus_allowed lockless and thus can
2474 	 * race with cgroup_attach_task() or update_cpumask() and get
2475 	 * the wrong tsk->cpus_allowed. However, both cases imply the
2476 	 * subsequent cpuset_change_cpumask()->set_cpus_allowed_ptr()
2477 	 * which takes task_rq_lock().
2478 	 *
2479 	 * If we are called after it dropped the lock we must see all
2480 	 * changes in tsk_cs()->cpus_allowed. Otherwise we can temporary
2481 	 * set any mask even if it is not right from task_cs() pov,
2482 	 * the pending set_cpus_allowed_ptr() will fix things.
2483 	 *
2484 	 * select_fallback_rq() will fix things ups and set cpu_possible_mask
2485 	 * if required.
2486 	 */
2487 }
2488 
cpuset_init_current_mems_allowed(void)2489 void __init cpuset_init_current_mems_allowed(void)
2490 {
2491 	nodes_setall(current->mems_allowed);
2492 }
2493 
2494 /**
2495  * cpuset_mems_allowed - return mems_allowed mask from a tasks cpuset.
2496  * @tsk: pointer to task_struct from which to obtain cpuset->mems_allowed.
2497  *
2498  * Description: Returns the nodemask_t mems_allowed of the cpuset
2499  * attached to the specified @tsk.  Guaranteed to return some non-empty
2500  * subset of node_states[N_MEMORY], even if this means going outside the
2501  * tasks cpuset.
2502  **/
2503 
cpuset_mems_allowed(struct task_struct * tsk)2504 nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
2505 {
2506 	nodemask_t mask;
2507 	unsigned long flags;
2508 
2509 	spin_lock_irqsave(&callback_lock, flags);
2510 	rcu_read_lock();
2511 	guarantee_online_mems(task_cs(tsk), &mask);
2512 	rcu_read_unlock();
2513 	spin_unlock_irqrestore(&callback_lock, flags);
2514 
2515 	return mask;
2516 }
2517 
2518 /**
2519  * cpuset_nodemask_valid_mems_allowed - check nodemask vs. curremt mems_allowed
2520  * @nodemask: the nodemask to be checked
2521  *
2522  * Are any of the nodes in the nodemask allowed in current->mems_allowed?
2523  */
cpuset_nodemask_valid_mems_allowed(nodemask_t * nodemask)2524 int cpuset_nodemask_valid_mems_allowed(nodemask_t *nodemask)
2525 {
2526 	return nodes_intersects(*nodemask, current->mems_allowed);
2527 }
2528 
2529 /*
2530  * nearest_hardwall_ancestor() - Returns the nearest mem_exclusive or
2531  * mem_hardwall ancestor to the specified cpuset.  Call holding
2532  * callback_lock.  If no ancestor is mem_exclusive or mem_hardwall
2533  * (an unusual configuration), then returns the root cpuset.
2534  */
nearest_hardwall_ancestor(struct cpuset * cs)2535 static struct cpuset *nearest_hardwall_ancestor(struct cpuset *cs)
2536 {
2537 	while (!(is_mem_exclusive(cs) || is_mem_hardwall(cs)) && parent_cs(cs))
2538 		cs = parent_cs(cs);
2539 	return cs;
2540 }
2541 
2542 /**
2543  * cpuset_node_allowed - Can we allocate on a memory node?
2544  * @node: is this an allowed node?
2545  * @gfp_mask: memory allocation flags
2546  *
2547  * If we're in interrupt, yes, we can always allocate.  If @node is set in
2548  * current's mems_allowed, yes.  If it's not a __GFP_HARDWALL request and this
2549  * node is set in the nearest hardwalled cpuset ancestor to current's cpuset,
2550  * yes.  If current has access to memory reserves as an oom victim, yes.
2551  * Otherwise, no.
2552  *
2553  * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
2554  * and do not allow allocations outside the current tasks cpuset
2555  * unless the task has been OOM killed.
2556  * GFP_KERNEL allocations are not so marked, so can escape to the
2557  * nearest enclosing hardwalled ancestor cpuset.
2558  *
2559  * Scanning up parent cpusets requires callback_lock.  The
2560  * __alloc_pages() routine only calls here with __GFP_HARDWALL bit
2561  * _not_ set if it's a GFP_KERNEL allocation, and all nodes in the
2562  * current tasks mems_allowed came up empty on the first pass over
2563  * the zonelist.  So only GFP_KERNEL allocations, if all nodes in the
2564  * cpuset are short of memory, might require taking the callback_lock.
2565  *
2566  * The first call here from mm/page_alloc:get_page_from_freelist()
2567  * has __GFP_HARDWALL set in gfp_mask, enforcing hardwall cpusets,
2568  * so no allocation on a node outside the cpuset is allowed (unless
2569  * in interrupt, of course).
2570  *
2571  * The second pass through get_page_from_freelist() doesn't even call
2572  * here for GFP_ATOMIC calls.  For those calls, the __alloc_pages()
2573  * variable 'wait' is not set, and the bit ALLOC_CPUSET is not set
2574  * in alloc_flags.  That logic and the checks below have the combined
2575  * affect that:
2576  *	in_interrupt - any node ok (current task context irrelevant)
2577  *	GFP_ATOMIC   - any node ok
2578  *	tsk_is_oom_victim   - any node ok
2579  *	GFP_KERNEL   - any node in enclosing hardwalled cpuset ok
2580  *	GFP_USER     - only nodes in current tasks mems allowed ok.
2581  */
__cpuset_node_allowed(int node,gfp_t gfp_mask)2582 bool __cpuset_node_allowed(int node, gfp_t gfp_mask)
2583 {
2584 	struct cpuset *cs;		/* current cpuset ancestors */
2585 	int allowed;			/* is allocation in zone z allowed? */
2586 	unsigned long flags;
2587 
2588 	if (in_interrupt())
2589 		return true;
2590 	if (node_isset(node, current->mems_allowed))
2591 		return true;
2592 	/*
2593 	 * Allow tasks that have access to memory reserves because they have
2594 	 * been OOM killed to get memory anywhere.
2595 	 */
2596 	if (unlikely(tsk_is_oom_victim(current)))
2597 		return true;
2598 	if (gfp_mask & __GFP_HARDWALL)	/* If hardwall request, stop here */
2599 		return false;
2600 
2601 	if (current->flags & PF_EXITING) /* Let dying task have memory */
2602 		return true;
2603 
2604 	/* Not hardwall and node outside mems_allowed: scan up cpusets */
2605 	spin_lock_irqsave(&callback_lock, flags);
2606 
2607 	rcu_read_lock();
2608 	cs = nearest_hardwall_ancestor(task_cs(current));
2609 	allowed = node_isset(node, cs->mems_allowed);
2610 	rcu_read_unlock();
2611 
2612 	spin_unlock_irqrestore(&callback_lock, flags);
2613 	return allowed;
2614 }
2615 
2616 /**
2617  * cpuset_mem_spread_node() - On which node to begin search for a file page
2618  * cpuset_slab_spread_node() - On which node to begin search for a slab page
2619  *
2620  * If a task is marked PF_SPREAD_PAGE or PF_SPREAD_SLAB (as for
2621  * tasks in a cpuset with is_spread_page or is_spread_slab set),
2622  * and if the memory allocation used cpuset_mem_spread_node()
2623  * to determine on which node to start looking, as it will for
2624  * certain page cache or slab cache pages such as used for file
2625  * system buffers and inode caches, then instead of starting on the
2626  * local node to look for a free page, rather spread the starting
2627  * node around the tasks mems_allowed nodes.
2628  *
2629  * We don't have to worry about the returned node being offline
2630  * because "it can't happen", and even if it did, it would be ok.
2631  *
2632  * The routines calling guarantee_online_mems() are careful to
2633  * only set nodes in task->mems_allowed that are online.  So it
2634  * should not be possible for the following code to return an
2635  * offline node.  But if it did, that would be ok, as this routine
2636  * is not returning the node where the allocation must be, only
2637  * the node where the search should start.  The zonelist passed to
2638  * __alloc_pages() will include all nodes.  If the slab allocator
2639  * is passed an offline node, it will fall back to the local node.
2640  * See kmem_cache_alloc_node().
2641  */
2642 
cpuset_spread_node(int * rotor)2643 static int cpuset_spread_node(int *rotor)
2644 {
2645 	return *rotor = next_node_in(*rotor, current->mems_allowed);
2646 }
2647 
cpuset_mem_spread_node(void)2648 int cpuset_mem_spread_node(void)
2649 {
2650 	if (current->cpuset_mem_spread_rotor == NUMA_NO_NODE)
2651 		current->cpuset_mem_spread_rotor =
2652 			node_random(&current->mems_allowed);
2653 
2654 	return cpuset_spread_node(&current->cpuset_mem_spread_rotor);
2655 }
2656 
cpuset_slab_spread_node(void)2657 int cpuset_slab_spread_node(void)
2658 {
2659 	if (current->cpuset_slab_spread_rotor == NUMA_NO_NODE)
2660 		current->cpuset_slab_spread_rotor =
2661 			node_random(&current->mems_allowed);
2662 
2663 	return cpuset_spread_node(&current->cpuset_slab_spread_rotor);
2664 }
2665 
2666 EXPORT_SYMBOL_GPL(cpuset_mem_spread_node);
2667 
2668 /**
2669  * cpuset_mems_allowed_intersects - Does @tsk1's mems_allowed intersect @tsk2's?
2670  * @tsk1: pointer to task_struct of some task.
2671  * @tsk2: pointer to task_struct of some other task.
2672  *
2673  * Description: Return true if @tsk1's mems_allowed intersects the
2674  * mems_allowed of @tsk2.  Used by the OOM killer to determine if
2675  * one of the task's memory usage might impact the memory available
2676  * to the other.
2677  **/
2678 
cpuset_mems_allowed_intersects(const struct task_struct * tsk1,const struct task_struct * tsk2)2679 int cpuset_mems_allowed_intersects(const struct task_struct *tsk1,
2680 				   const struct task_struct *tsk2)
2681 {
2682 	return nodes_intersects(tsk1->mems_allowed, tsk2->mems_allowed);
2683 }
2684 
2685 /**
2686  * cpuset_print_current_mems_allowed - prints current's cpuset and mems_allowed
2687  *
2688  * Description: Prints current's name, cpuset name, and cached copy of its
2689  * mems_allowed to the kernel log.
2690  */
cpuset_print_current_mems_allowed(void)2691 void cpuset_print_current_mems_allowed(void)
2692 {
2693 	struct cgroup *cgrp;
2694 
2695 	rcu_read_lock();
2696 
2697 	cgrp = task_cs(current)->css.cgroup;
2698 	pr_info("%s cpuset=", current->comm);
2699 	pr_cont_cgroup_name(cgrp);
2700 	pr_cont(" mems_allowed=%*pbl\n",
2701 		nodemask_pr_args(&current->mems_allowed));
2702 
2703 	rcu_read_unlock();
2704 }
2705 
2706 /*
2707  * Collection of memory_pressure is suppressed unless
2708  * this flag is enabled by writing "1" to the special
2709  * cpuset file 'memory_pressure_enabled' in the root cpuset.
2710  */
2711 
2712 int cpuset_memory_pressure_enabled __read_mostly;
2713 
2714 /**
2715  * cpuset_memory_pressure_bump - keep stats of per-cpuset reclaims.
2716  *
2717  * Keep a running average of the rate of synchronous (direct)
2718  * page reclaim efforts initiated by tasks in each cpuset.
2719  *
2720  * This represents the rate at which some task in the cpuset
2721  * ran low on memory on all nodes it was allowed to use, and
2722  * had to enter the kernels page reclaim code in an effort to
2723  * create more free memory by tossing clean pages or swapping
2724  * or writing dirty pages.
2725  *
2726  * Display to user space in the per-cpuset read-only file
2727  * "memory_pressure".  Value displayed is an integer
2728  * representing the recent rate of entry into the synchronous
2729  * (direct) page reclaim by any task attached to the cpuset.
2730  **/
2731 
__cpuset_memory_pressure_bump(void)2732 void __cpuset_memory_pressure_bump(void)
2733 {
2734 	rcu_read_lock();
2735 	fmeter_markevent(&task_cs(current)->fmeter);
2736 	rcu_read_unlock();
2737 }
2738 
2739 #ifdef CONFIG_PROC_PID_CPUSET
2740 /*
2741  * proc_cpuset_show()
2742  *  - Print tasks cpuset path into seq_file.
2743  *  - Used for /proc/<pid>/cpuset.
2744  *  - No need to task_lock(tsk) on this tsk->cpuset reference, as it
2745  *    doesn't really matter if tsk->cpuset changes after we read it,
2746  *    and we take cpuset_mutex, keeping cpuset_attach() from changing it
2747  *    anyway.
2748  */
proc_cpuset_show(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * tsk)2749 int proc_cpuset_show(struct seq_file *m, struct pid_namespace *ns,
2750 		     struct pid *pid, struct task_struct *tsk)
2751 {
2752 	char *buf;
2753 	struct cgroup_subsys_state *css;
2754 	int retval;
2755 
2756 	retval = -ENOMEM;
2757 	buf = kmalloc(PATH_MAX, GFP_KERNEL);
2758 	if (!buf)
2759 		goto out;
2760 
2761 	css = task_get_css(tsk, cpuset_cgrp_id);
2762 	retval = cgroup_path_ns(css->cgroup, buf, PATH_MAX,
2763 				current->nsproxy->cgroup_ns);
2764 	css_put(css);
2765 	if (retval >= PATH_MAX)
2766 		retval = -ENAMETOOLONG;
2767 	if (retval < 0)
2768 		goto out_free;
2769 	seq_puts(m, buf);
2770 	seq_putc(m, '\n');
2771 	retval = 0;
2772 out_free:
2773 	kfree(buf);
2774 out:
2775 	return retval;
2776 }
2777 #endif /* CONFIG_PROC_PID_CPUSET */
2778 
2779 /* Display task mems_allowed in /proc/<pid>/status file. */
cpuset_task_status_allowed(struct seq_file * m,struct task_struct * task)2780 void cpuset_task_status_allowed(struct seq_file *m, struct task_struct *task)
2781 {
2782 	seq_printf(m, "Mems_allowed:\t%*pb\n",
2783 		   nodemask_pr_args(&task->mems_allowed));
2784 	seq_printf(m, "Mems_allowed_list:\t%*pbl\n",
2785 		   nodemask_pr_args(&task->mems_allowed));
2786 }
2787