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