]> bbs.cooldavid.org Git - net-next-2.6.git/blame - kernel/cpuset.c
Group short-lived and reclaimable kernel allocations
[net-next-2.6.git] / kernel / cpuset.c
CommitLineData
1da177e4
LT
1/*
2 * kernel/cpuset.c
3 *
4 * Processor and Memory placement constraints for sets of tasks.
5 *
6 * Copyright (C) 2003 BULL SA.
825a46af 7 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
1da177e4
LT
8 *
9 * Portions derived from Patrick Mochel's sysfs code.
10 * sysfs is Copyright (c) 2001-3 Patrick Mochel
1da177e4 11 *
825a46af 12 * 2003-10-10 Written by Simon Derr.
1da177e4 13 * 2003-10-22 Updates by Stephen Hemminger.
825a46af 14 * 2004 May-July Rework by Paul Jackson.
1da177e4
LT
15 *
16 * This file is subject to the terms and conditions of the GNU General Public
17 * License. See the file COPYING in the main directory of the Linux
18 * distribution for more details.
19 */
20
1da177e4
LT
21#include <linux/cpu.h>
22#include <linux/cpumask.h>
23#include <linux/cpuset.h>
24#include <linux/err.h>
25#include <linux/errno.h>
26#include <linux/file.h>
27#include <linux/fs.h>
28#include <linux/init.h>
29#include <linux/interrupt.h>
30#include <linux/kernel.h>
31#include <linux/kmod.h>
32#include <linux/list.h>
68860ec1 33#include <linux/mempolicy.h>
1da177e4
LT
34#include <linux/mm.h>
35#include <linux/module.h>
36#include <linux/mount.h>
37#include <linux/namei.h>
38#include <linux/pagemap.h>
39#include <linux/proc_fs.h>
6b9c2603 40#include <linux/rcupdate.h>
1da177e4
LT
41#include <linux/sched.h>
42#include <linux/seq_file.h>
22fb52dd 43#include <linux/security.h>
1da177e4 44#include <linux/slab.h>
1da177e4
LT
45#include <linux/spinlock.h>
46#include <linux/stat.h>
47#include <linux/string.h>
48#include <linux/time.h>
49#include <linux/backing-dev.h>
50#include <linux/sort.h>
51
52#include <asm/uaccess.h>
53#include <asm/atomic.h>
3d3f26a7 54#include <linux/mutex.h>
1da177e4 55
c5b2aff8 56#define CPUSET_SUPER_MAGIC 0x27e0eb
1da177e4 57
202f72d5
PJ
58/*
59 * Tracks how many cpusets are currently defined in system.
60 * When there is only one cpuset (the root cpuset) we can
61 * short circuit some hooks.
62 */
7edc5962 63int number_of_cpusets __read_mostly;
202f72d5 64
3e0d98b9
PJ
65/* See "Frequency meter" comments, below. */
66
67struct fmeter {
68 int cnt; /* unprocessed events count */
69 int val; /* most recent output value */
70 time_t time; /* clock (secs) when val computed */
71 spinlock_t lock; /* guards read or write of above */
72};
73
1da177e4
LT
74struct cpuset {
75 unsigned long flags; /* "unsigned long" so bitops work */
76 cpumask_t cpus_allowed; /* CPUs allowed to tasks in cpuset */
77 nodemask_t mems_allowed; /* Memory Nodes allowed to tasks */
78
053199ed
PJ
79 /*
80 * Count is atomic so can incr (fork) or decr (exit) without a lock.
81 */
1da177e4
LT
82 atomic_t count; /* count tasks using this cpuset */
83
84 /*
85 * We link our 'sibling' struct into our parents 'children'.
86 * Our children link their 'sibling' into our 'children'.
87 */
88 struct list_head sibling; /* my parents children */
89 struct list_head children; /* my children */
90
91 struct cpuset *parent; /* my parent */
92 struct dentry *dentry; /* cpuset fs entry */
93
94 /*
95 * Copy of global cpuset_mems_generation as of the most
96 * recent time this cpuset changed its mems_allowed.
97 */
3e0d98b9
PJ
98 int mems_generation;
99
100 struct fmeter fmeter; /* memory_pressure filter */
1da177e4
LT
101};
102
103/* bits in struct cpuset flags field */
104typedef enum {
105 CS_CPU_EXCLUSIVE,
106 CS_MEM_EXCLUSIVE,
45b07ef3 107 CS_MEMORY_MIGRATE,
1da177e4 108 CS_REMOVED,
825a46af
PJ
109 CS_NOTIFY_ON_RELEASE,
110 CS_SPREAD_PAGE,
111 CS_SPREAD_SLAB,
1da177e4
LT
112} cpuset_flagbits_t;
113
114/* convenient tests for these bits */
115static inline int is_cpu_exclusive(const struct cpuset *cs)
116{
7b5b9ef0 117 return test_bit(CS_CPU_EXCLUSIVE, &cs->flags);
1da177e4
LT
118}
119
120static inline int is_mem_exclusive(const struct cpuset *cs)
121{
7b5b9ef0 122 return test_bit(CS_MEM_EXCLUSIVE, &cs->flags);
1da177e4
LT
123}
124
125static inline int is_removed(const struct cpuset *cs)
126{
7b5b9ef0 127 return test_bit(CS_REMOVED, &cs->flags);
1da177e4
LT
128}
129
130static inline int notify_on_release(const struct cpuset *cs)
131{
7b5b9ef0 132 return test_bit(CS_NOTIFY_ON_RELEASE, &cs->flags);
1da177e4
LT
133}
134
45b07ef3
PJ
135static inline int is_memory_migrate(const struct cpuset *cs)
136{
7b5b9ef0 137 return test_bit(CS_MEMORY_MIGRATE, &cs->flags);
45b07ef3
PJ
138}
139
825a46af
PJ
140static inline int is_spread_page(const struct cpuset *cs)
141{
142 return test_bit(CS_SPREAD_PAGE, &cs->flags);
143}
144
145static inline int is_spread_slab(const struct cpuset *cs)
146{
147 return test_bit(CS_SPREAD_SLAB, &cs->flags);
148}
149
1da177e4 150/*
151a4420 151 * Increment this integer everytime any cpuset changes its
1da177e4
LT
152 * mems_allowed value. Users of cpusets can track this generation
153 * number, and avoid having to lock and reload mems_allowed unless
154 * the cpuset they're using changes generation.
155 *
156 * A single, global generation is needed because attach_task() could
157 * reattach a task to a different cpuset, which must not have its
158 * generation numbers aliased with those of that tasks previous cpuset.
159 *
160 * Generations are needed for mems_allowed because one task cannot
161 * modify anothers memory placement. So we must enable every task,
162 * on every visit to __alloc_pages(), to efficiently check whether
163 * its current->cpuset->mems_allowed has changed, requiring an update
164 * of its current->mems_allowed.
151a4420
PJ
165 *
166 * Since cpuset_mems_generation is guarded by manage_mutex,
167 * there is no need to mark it atomic.
1da177e4 168 */
151a4420 169static int cpuset_mems_generation;
1da177e4
LT
170
171static struct cpuset top_cpuset = {
172 .flags = ((1 << CS_CPU_EXCLUSIVE) | (1 << CS_MEM_EXCLUSIVE)),
173 .cpus_allowed = CPU_MASK_ALL,
174 .mems_allowed = NODE_MASK_ALL,
175 .count = ATOMIC_INIT(0),
176 .sibling = LIST_HEAD_INIT(top_cpuset.sibling),
177 .children = LIST_HEAD_INIT(top_cpuset.children),
1da177e4
LT
178};
179
180static struct vfsmount *cpuset_mount;
3e0d98b9 181static struct super_block *cpuset_sb;
1da177e4
LT
182
183/*
3d3f26a7
IM
184 * We have two global cpuset mutexes below. They can nest.
185 * It is ok to first take manage_mutex, then nest callback_mutex. We also
053199ed
PJ
186 * require taking task_lock() when dereferencing a tasks cpuset pointer.
187 * See "The task_lock() exception", at the end of this comment.
188 *
3d3f26a7
IM
189 * A task must hold both mutexes to modify cpusets. If a task
190 * holds manage_mutex, then it blocks others wanting that mutex,
191 * ensuring that it is the only task able to also acquire callback_mutex
053199ed
PJ
192 * and be able to modify cpusets. It can perform various checks on
193 * the cpuset structure first, knowing nothing will change. It can
3d3f26a7 194 * also allocate memory while just holding manage_mutex. While it is
053199ed 195 * performing these checks, various callback routines can briefly
3d3f26a7
IM
196 * acquire callback_mutex to query cpusets. Once it is ready to make
197 * the changes, it takes callback_mutex, blocking everyone else.
053199ed
PJ
198 *
199 * Calls to the kernel memory allocator can not be made while holding
3d3f26a7 200 * callback_mutex, as that would risk double tripping on callback_mutex
053199ed
PJ
201 * from one of the callbacks into the cpuset code from within
202 * __alloc_pages().
203 *
3d3f26a7 204 * If a task is only holding callback_mutex, then it has read-only
053199ed
PJ
205 * access to cpusets.
206 *
207 * The task_struct fields mems_allowed and mems_generation may only
208 * be accessed in the context of that task, so require no locks.
209 *
210 * Any task can increment and decrement the count field without lock.
3d3f26a7 211 * So in general, code holding manage_mutex or callback_mutex can't rely
053199ed 212 * on the count field not changing. However, if the count goes to
3d3f26a7 213 * zero, then only attach_task(), which holds both mutexes, can
053199ed
PJ
214 * increment it again. Because a count of zero means that no tasks
215 * are currently attached, therefore there is no way a task attached
216 * to that cpuset can fork (the other way to increment the count).
3d3f26a7 217 * So code holding manage_mutex or callback_mutex can safely assume that
053199ed 218 * if the count is zero, it will stay zero. Similarly, if a task
3d3f26a7 219 * holds manage_mutex or callback_mutex on a cpuset with zero count, it
053199ed 220 * knows that the cpuset won't be removed, as cpuset_rmdir() needs
3d3f26a7 221 * both of those mutexes.
053199ed
PJ
222 *
223 * The cpuset_common_file_write handler for operations that modify
3d3f26a7 224 * the cpuset hierarchy holds manage_mutex across the entire operation,
053199ed
PJ
225 * single threading all such cpuset modifications across the system.
226 *
3d3f26a7 227 * The cpuset_common_file_read() handlers only hold callback_mutex across
053199ed
PJ
228 * small pieces of code, such as when reading out possibly multi-word
229 * cpumasks and nodemasks.
230 *
231 * The fork and exit callbacks cpuset_fork() and cpuset_exit(), don't
3d3f26a7 232 * (usually) take either mutex. These are the two most performance
053199ed 233 * critical pieces of code here. The exception occurs on cpuset_exit(),
3d3f26a7 234 * when a task in a notify_on_release cpuset exits. Then manage_mutex
2efe86b8 235 * is taken, and if the cpuset count is zero, a usermode call made
1da177e4
LT
236 * to /sbin/cpuset_release_agent with the name of the cpuset (path
237 * relative to the root of cpuset file system) as the argument.
238 *
053199ed
PJ
239 * A cpuset can only be deleted if both its 'count' of using tasks
240 * is zero, and its list of 'children' cpusets is empty. Since all
241 * tasks in the system use _some_ cpuset, and since there is always at
f400e198 242 * least one task in the system (init), therefore, top_cpuset
053199ed
PJ
243 * always has either children cpusets and/or using tasks. So we don't
244 * need a special hack to ensure that top_cpuset cannot be deleted.
245 *
246 * The above "Tale of Two Semaphores" would be complete, but for:
247 *
248 * The task_lock() exception
249 *
250 * The need for this exception arises from the action of attach_task(),
251 * which overwrites one tasks cpuset pointer with another. It does
3d3f26a7 252 * so using both mutexes, however there are several performance
053199ed 253 * critical places that need to reference task->cpuset without the
3d3f26a7 254 * expense of grabbing a system global mutex. Therefore except as
053199ed
PJ
255 * noted below, when dereferencing or, as in attach_task(), modifying
256 * a tasks cpuset pointer we use task_lock(), which acts on a spinlock
257 * (task->alloc_lock) already in the task_struct routinely used for
258 * such matters.
6b9c2603
PJ
259 *
260 * P.S. One more locking exception. RCU is used to guard the
261 * update of a tasks cpuset pointer by attach_task() and the
262 * access of task->cpuset->mems_generation via that pointer in
263 * the routine cpuset_update_task_memory_state().
1da177e4
LT
264 */
265
3d3f26a7
IM
266static DEFINE_MUTEX(manage_mutex);
267static DEFINE_MUTEX(callback_mutex);
4247bdc6 268
1da177e4
LT
269/*
270 * A couple of forward declarations required, due to cyclic reference loop:
271 * cpuset_mkdir -> cpuset_create -> cpuset_populate_dir -> cpuset_add_file
272 * -> cpuset_create_file -> cpuset_dir_inode_operations -> cpuset_mkdir.
273 */
274
275static int cpuset_mkdir(struct inode *dir, struct dentry *dentry, int mode);
276static int cpuset_rmdir(struct inode *unused_dir, struct dentry *dentry);
277
278static struct backing_dev_info cpuset_backing_dev_info = {
279 .ra_pages = 0, /* No readahead */
280 .capabilities = BDI_CAP_NO_ACCT_DIRTY | BDI_CAP_NO_WRITEBACK,
281};
282
283static struct inode *cpuset_new_inode(mode_t mode)
284{
285 struct inode *inode = new_inode(cpuset_sb);
286
287 if (inode) {
288 inode->i_mode = mode;
289 inode->i_uid = current->fsuid;
290 inode->i_gid = current->fsgid;
1da177e4
LT
291 inode->i_blocks = 0;
292 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
293 inode->i_mapping->backing_dev_info = &cpuset_backing_dev_info;
294 }
295 return inode;
296}
297
298static void cpuset_diput(struct dentry *dentry, struct inode *inode)
299{
300 /* is dentry a directory ? if so, kfree() associated cpuset */
301 if (S_ISDIR(inode->i_mode)) {
302 struct cpuset *cs = dentry->d_fsdata;
303 BUG_ON(!(is_removed(cs)));
304 kfree(cs);
305 }
306 iput(inode);
307}
308
309static struct dentry_operations cpuset_dops = {
310 .d_iput = cpuset_diput,
311};
312
313static struct dentry *cpuset_get_dentry(struct dentry *parent, const char *name)
314{
5f45f1a7 315 struct dentry *d = lookup_one_len(name, parent, strlen(name));
1da177e4
LT
316 if (!IS_ERR(d))
317 d->d_op = &cpuset_dops;
318 return d;
319}
320
321static void remove_dir(struct dentry *d)
322{
323 struct dentry *parent = dget(d->d_parent);
324
325 d_delete(d);
326 simple_rmdir(parent->d_inode, d);
327 dput(parent);
328}
329
330/*
331 * NOTE : the dentry must have been dget()'ed
332 */
333static void cpuset_d_remove_dir(struct dentry *dentry)
334{
335 struct list_head *node;
336
337 spin_lock(&dcache_lock);
338 node = dentry->d_subdirs.next;
339 while (node != &dentry->d_subdirs) {
5160ee6f 340 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
1da177e4
LT
341 list_del_init(node);
342 if (d->d_inode) {
343 d = dget_locked(d);
344 spin_unlock(&dcache_lock);
345 d_delete(d);
346 simple_unlink(dentry->d_inode, d);
347 dput(d);
348 spin_lock(&dcache_lock);
349 }
350 node = dentry->d_subdirs.next;
351 }
5160ee6f 352 list_del_init(&dentry->d_u.d_child);
1da177e4
LT
353 spin_unlock(&dcache_lock);
354 remove_dir(dentry);
355}
356
357static struct super_operations cpuset_ops = {
358 .statfs = simple_statfs,
359 .drop_inode = generic_delete_inode,
360};
361
362static int cpuset_fill_super(struct super_block *sb, void *unused_data,
363 int unused_silent)
364{
365 struct inode *inode;
366 struct dentry *root;
367
368 sb->s_blocksize = PAGE_CACHE_SIZE;
369 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
370 sb->s_magic = CPUSET_SUPER_MAGIC;
371 sb->s_op = &cpuset_ops;
372 cpuset_sb = sb;
373
374 inode = cpuset_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR);
375 if (inode) {
376 inode->i_op = &simple_dir_inode_operations;
377 inode->i_fop = &simple_dir_operations;
378 /* directories start off with i_nlink == 2 (for "." entry) */
d8c76e6f 379 inc_nlink(inode);
1da177e4
LT
380 } else {
381 return -ENOMEM;
382 }
383
384 root = d_alloc_root(inode);
385 if (!root) {
386 iput(inode);
387 return -ENOMEM;
388 }
389 sb->s_root = root;
390 return 0;
391}
392
454e2398
DH
393static int cpuset_get_sb(struct file_system_type *fs_type,
394 int flags, const char *unused_dev_name,
395 void *data, struct vfsmount *mnt)
1da177e4 396{
454e2398 397 return get_sb_single(fs_type, flags, data, cpuset_fill_super, mnt);
1da177e4
LT
398}
399
400static struct file_system_type cpuset_fs_type = {
401 .name = "cpuset",
402 .get_sb = cpuset_get_sb,
403 .kill_sb = kill_litter_super,
404};
405
406/* struct cftype:
407 *
408 * The files in the cpuset filesystem mostly have a very simple read/write
409 * handling, some common function will take care of it. Nevertheless some cases
410 * (read tasks) are special and therefore I define this structure for every
411 * kind of file.
412 *
413 *
414 * When reading/writing to a file:
a7a005fd
JS
415 * - the cpuset to use in file->f_path.dentry->d_parent->d_fsdata
416 * - the 'cftype' of the file is file->f_path.dentry->d_fsdata
1da177e4
LT
417 */
418
419struct cftype {
420 char *name;
421 int private;
422 int (*open) (struct inode *inode, struct file *file);
423 ssize_t (*read) (struct file *file, char __user *buf, size_t nbytes,
424 loff_t *ppos);
425 int (*write) (struct file *file, const char __user *buf, size_t nbytes,
426 loff_t *ppos);
427 int (*release) (struct inode *inode, struct file *file);
428};
429
430static inline struct cpuset *__d_cs(struct dentry *dentry)
431{
432 return dentry->d_fsdata;
433}
434
435static inline struct cftype *__d_cft(struct dentry *dentry)
436{
437 return dentry->d_fsdata;
438}
439
440/*
3d3f26a7 441 * Call with manage_mutex held. Writes path of cpuset into buf.
1da177e4
LT
442 * Returns 0 on success, -errno on error.
443 */
444
445static int cpuset_path(const struct cpuset *cs, char *buf, int buflen)
446{
447 char *start;
448
449 start = buf + buflen;
450
451 *--start = '\0';
452 for (;;) {
453 int len = cs->dentry->d_name.len;
454 if ((start -= len) < buf)
455 return -ENAMETOOLONG;
456 memcpy(start, cs->dentry->d_name.name, len);
457 cs = cs->parent;
458 if (!cs)
459 break;
460 if (!cs->parent)
461 continue;
462 if (--start < buf)
463 return -ENAMETOOLONG;
464 *start = '/';
465 }
466 memmove(buf, start, buf + buflen - start);
467 return 0;
468}
469
470/*
471 * Notify userspace when a cpuset is released, by running
472 * /sbin/cpuset_release_agent with the name of the cpuset (path
473 * relative to the root of cpuset file system) as the argument.
474 *
475 * Most likely, this user command will try to rmdir this cpuset.
476 *
477 * This races with the possibility that some other task will be
478 * attached to this cpuset before it is removed, or that some other
479 * user task will 'mkdir' a child cpuset of this cpuset. That's ok.
480 * The presumed 'rmdir' will fail quietly if this cpuset is no longer
481 * unused, and this cpuset will be reprieved from its death sentence,
482 * to continue to serve a useful existence. Next time it's released,
483 * we will get notified again, if it still has 'notify_on_release' set.
484 *
3077a260
PJ
485 * The final arg to call_usermodehelper() is 0, which means don't
486 * wait. The separate /sbin/cpuset_release_agent task is forked by
487 * call_usermodehelper(), then control in this thread returns here,
488 * without waiting for the release agent task. We don't bother to
489 * wait because the caller of this routine has no use for the exit
490 * status of the /sbin/cpuset_release_agent task, so no sense holding
491 * our caller up for that.
492 *
3d3f26a7 493 * When we had only one cpuset mutex, we had to call this
053199ed
PJ
494 * without holding it, to avoid deadlock when call_usermodehelper()
495 * allocated memory. With two locks, we could now call this while
3d3f26a7
IM
496 * holding manage_mutex, but we still don't, so as to minimize
497 * the time manage_mutex is held.
1da177e4
LT
498 */
499
3077a260 500static void cpuset_release_agent(const char *pathbuf)
1da177e4
LT
501{
502 char *argv[3], *envp[3];
503 int i;
504
3077a260
PJ
505 if (!pathbuf)
506 return;
507
1da177e4
LT
508 i = 0;
509 argv[i++] = "/sbin/cpuset_release_agent";
3077a260 510 argv[i++] = (char *)pathbuf;
1da177e4
LT
511 argv[i] = NULL;
512
513 i = 0;
514 /* minimal command environment */
515 envp[i++] = "HOME=/";
516 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
517 envp[i] = NULL;
518
86313c48 519 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3077a260 520 kfree(pathbuf);
1da177e4
LT
521}
522
523/*
524 * Either cs->count of using tasks transitioned to zero, or the
525 * cs->children list of child cpusets just became empty. If this
526 * cs is notify_on_release() and now both the user count is zero and
3077a260
PJ
527 * the list of children is empty, prepare cpuset path in a kmalloc'd
528 * buffer, to be returned via ppathbuf, so that the caller can invoke
3d3f26a7
IM
529 * cpuset_release_agent() with it later on, once manage_mutex is dropped.
530 * Call here with manage_mutex held.
3077a260
PJ
531 *
532 * This check_for_release() routine is responsible for kmalloc'ing
533 * pathbuf. The above cpuset_release_agent() is responsible for
534 * kfree'ing pathbuf. The caller of these routines is responsible
535 * for providing a pathbuf pointer, initialized to NULL, then
3d3f26a7
IM
536 * calling check_for_release() with manage_mutex held and the address
537 * of the pathbuf pointer, then dropping manage_mutex, then calling
3077a260 538 * cpuset_release_agent() with pathbuf, as set by check_for_release().
1da177e4
LT
539 */
540
3077a260 541static void check_for_release(struct cpuset *cs, char **ppathbuf)
1da177e4
LT
542{
543 if (notify_on_release(cs) && atomic_read(&cs->count) == 0 &&
544 list_empty(&cs->children)) {
545 char *buf;
546
547 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
548 if (!buf)
549 return;
550 if (cpuset_path(cs, buf, PAGE_SIZE) < 0)
3077a260
PJ
551 kfree(buf);
552 else
553 *ppathbuf = buf;
1da177e4
LT
554 }
555}
556
557/*
558 * Return in *pmask the portion of a cpusets's cpus_allowed that
559 * are online. If none are online, walk up the cpuset hierarchy
560 * until we find one that does have some online cpus. If we get
561 * all the way to the top and still haven't found any online cpus,
562 * return cpu_online_map. Or if passed a NULL cs from an exit'ing
563 * task, return cpu_online_map.
564 *
565 * One way or another, we guarantee to return some non-empty subset
566 * of cpu_online_map.
567 *
3d3f26a7 568 * Call with callback_mutex held.
1da177e4
LT
569 */
570
571static void guarantee_online_cpus(const struct cpuset *cs, cpumask_t *pmask)
572{
573 while (cs && !cpus_intersects(cs->cpus_allowed, cpu_online_map))
574 cs = cs->parent;
575 if (cs)
576 cpus_and(*pmask, cs->cpus_allowed, cpu_online_map);
577 else
578 *pmask = cpu_online_map;
579 BUG_ON(!cpus_intersects(*pmask, cpu_online_map));
580}
581
582/*
583 * Return in *pmask the portion of a cpusets's mems_allowed that
0e1e7c7a
CL
584 * are online, with memory. If none are online with memory, walk
585 * up the cpuset hierarchy until we find one that does have some
586 * online mems. If we get all the way to the top and still haven't
587 * found any online mems, return node_states[N_HIGH_MEMORY].
1da177e4
LT
588 *
589 * One way or another, we guarantee to return some non-empty subset
0e1e7c7a 590 * of node_states[N_HIGH_MEMORY].
1da177e4 591 *
3d3f26a7 592 * Call with callback_mutex held.
1da177e4
LT
593 */
594
595static void guarantee_online_mems(const struct cpuset *cs, nodemask_t *pmask)
596{
0e1e7c7a
CL
597 while (cs && !nodes_intersects(cs->mems_allowed,
598 node_states[N_HIGH_MEMORY]))
1da177e4
LT
599 cs = cs->parent;
600 if (cs)
0e1e7c7a
CL
601 nodes_and(*pmask, cs->mems_allowed,
602 node_states[N_HIGH_MEMORY]);
1da177e4 603 else
0e1e7c7a
CL
604 *pmask = node_states[N_HIGH_MEMORY];
605 BUG_ON(!nodes_intersects(*pmask, node_states[N_HIGH_MEMORY]));
1da177e4
LT
606}
607
cf2a473c
PJ
608/**
609 * cpuset_update_task_memory_state - update task memory placement
610 *
611 * If the current tasks cpusets mems_allowed changed behind our
612 * backs, update current->mems_allowed, mems_generation and task NUMA
613 * mempolicy to the new value.
053199ed 614 *
cf2a473c
PJ
615 * Task mempolicy is updated by rebinding it relative to the
616 * current->cpuset if a task has its memory placement changed.
617 * Do not call this routine if in_interrupt().
618 *
4a01c8d5
PJ
619 * Call without callback_mutex or task_lock() held. May be
620 * called with or without manage_mutex held. Thanks in part to
621 * 'the_top_cpuset_hack', the tasks cpuset pointer will never
622 * be NULL. This routine also might acquire callback_mutex and
cf2a473c 623 * current->mm->mmap_sem during call.
053199ed 624 *
6b9c2603
PJ
625 * Reading current->cpuset->mems_generation doesn't need task_lock
626 * to guard the current->cpuset derefence, because it is guarded
627 * from concurrent freeing of current->cpuset by attach_task(),
628 * using RCU.
629 *
630 * The rcu_dereference() is technically probably not needed,
631 * as I don't actually mind if I see a new cpuset pointer but
632 * an old value of mems_generation. However this really only
633 * matters on alpha systems using cpusets heavily. If I dropped
634 * that rcu_dereference(), it would save them a memory barrier.
635 * For all other arch's, rcu_dereference is a no-op anyway, and for
636 * alpha systems not using cpusets, another planned optimization,
637 * avoiding the rcu critical section for tasks in the root cpuset
638 * which is statically allocated, so can't vanish, will make this
639 * irrelevant. Better to use RCU as intended, than to engage in
640 * some cute trick to save a memory barrier that is impossible to
641 * test, for alpha systems using cpusets heavily, which might not
642 * even exist.
053199ed
PJ
643 *
644 * This routine is needed to update the per-task mems_allowed data,
645 * within the tasks context, when it is trying to allocate memory
646 * (in various mm/mempolicy.c routines) and notices that some other
647 * task has been modifying its cpuset.
1da177e4
LT
648 */
649
fe85a998 650void cpuset_update_task_memory_state(void)
1da177e4 651{
053199ed 652 int my_cpusets_mem_gen;
cf2a473c 653 struct task_struct *tsk = current;
6b9c2603 654 struct cpuset *cs;
053199ed 655
03a285f5
PJ
656 if (tsk->cpuset == &top_cpuset) {
657 /* Don't need rcu for top_cpuset. It's never freed. */
658 my_cpusets_mem_gen = top_cpuset.mems_generation;
659 } else {
660 rcu_read_lock();
661 cs = rcu_dereference(tsk->cpuset);
662 my_cpusets_mem_gen = cs->mems_generation;
663 rcu_read_unlock();
664 }
1da177e4 665
cf2a473c 666 if (my_cpusets_mem_gen != tsk->cpuset_mems_generation) {
3d3f26a7 667 mutex_lock(&callback_mutex);
cf2a473c
PJ
668 task_lock(tsk);
669 cs = tsk->cpuset; /* Maybe changed when task not locked */
cf2a473c
PJ
670 guarantee_online_mems(cs, &tsk->mems_allowed);
671 tsk->cpuset_mems_generation = cs->mems_generation;
825a46af
PJ
672 if (is_spread_page(cs))
673 tsk->flags |= PF_SPREAD_PAGE;
674 else
675 tsk->flags &= ~PF_SPREAD_PAGE;
676 if (is_spread_slab(cs))
677 tsk->flags |= PF_SPREAD_SLAB;
678 else
679 tsk->flags &= ~PF_SPREAD_SLAB;
cf2a473c 680 task_unlock(tsk);
3d3f26a7 681 mutex_unlock(&callback_mutex);
74cb2155 682 mpol_rebind_task(tsk, &tsk->mems_allowed);
1da177e4
LT
683 }
684}
685
686/*
687 * is_cpuset_subset(p, q) - Is cpuset p a subset of cpuset q?
688 *
689 * One cpuset is a subset of another if all its allowed CPUs and
690 * Memory Nodes are a subset of the other, and its exclusive flags
3d3f26a7 691 * are only set if the other's are set. Call holding manage_mutex.
1da177e4
LT
692 */
693
694static int is_cpuset_subset(const struct cpuset *p, const struct cpuset *q)
695{
696 return cpus_subset(p->cpus_allowed, q->cpus_allowed) &&
697 nodes_subset(p->mems_allowed, q->mems_allowed) &&
698 is_cpu_exclusive(p) <= is_cpu_exclusive(q) &&
699 is_mem_exclusive(p) <= is_mem_exclusive(q);
700}
701
702/*
703 * validate_change() - Used to validate that any proposed cpuset change
704 * follows the structural rules for cpusets.
705 *
706 * If we replaced the flag and mask values of the current cpuset
707 * (cur) with those values in the trial cpuset (trial), would
708 * our various subset and exclusive rules still be valid? Presumes
3d3f26a7 709 * manage_mutex held.
1da177e4
LT
710 *
711 * 'cur' is the address of an actual, in-use cpuset. Operations
712 * such as list traversal that depend on the actual address of the
713 * cpuset in the list must use cur below, not trial.
714 *
715 * 'trial' is the address of bulk structure copy of cur, with
716 * perhaps one or more of the fields cpus_allowed, mems_allowed,
717 * or flags changed to new, trial values.
718 *
719 * Return 0 if valid, -errno if not.
720 */
721
722static int validate_change(const struct cpuset *cur, const struct cpuset *trial)
723{
724 struct cpuset *c, *par;
725
726 /* Each of our child cpusets must be a subset of us */
727 list_for_each_entry(c, &cur->children, sibling) {
728 if (!is_cpuset_subset(c, trial))
729 return -EBUSY;
730 }
731
732 /* Remaining checks don't apply to root cpuset */
69604067 733 if (cur == &top_cpuset)
1da177e4
LT
734 return 0;
735
69604067
PJ
736 par = cur->parent;
737
1da177e4
LT
738 /* We must be a subset of our parent cpuset */
739 if (!is_cpuset_subset(trial, par))
740 return -EACCES;
741
742 /* If either I or some sibling (!= me) is exclusive, we can't overlap */
743 list_for_each_entry(c, &par->children, sibling) {
744 if ((is_cpu_exclusive(trial) || is_cpu_exclusive(c)) &&
745 c != cur &&
746 cpus_intersects(trial->cpus_allowed, c->cpus_allowed))
747 return -EINVAL;
748 if ((is_mem_exclusive(trial) || is_mem_exclusive(c)) &&
749 c != cur &&
750 nodes_intersects(trial->mems_allowed, c->mems_allowed))
751 return -EINVAL;
752 }
753
754 return 0;
755}
756
85d7b949
DG
757/*
758 * For a given cpuset cur, partition the system as follows
759 * a. All cpus in the parent cpuset's cpus_allowed that are not part of any
760 * exclusive child cpusets
761 * b. All cpus in the current cpuset's cpus_allowed that are not part of any
762 * exclusive child cpusets
763 * Build these two partitions by calling partition_sched_domains
764 *
3d3f26a7 765 * Call with manage_mutex held. May nest a call to the
85d7b949 766 * lock_cpu_hotplug()/unlock_cpu_hotplug() pair.
abb5a5cc
PJ
767 * Must not be called holding callback_mutex, because we must
768 * not call lock_cpu_hotplug() while holding callback_mutex.
85d7b949 769 */
212d6d22 770
85d7b949
DG
771static void update_cpu_domains(struct cpuset *cur)
772{
773 struct cpuset *c, *par = cur->parent;
774 cpumask_t pspan, cspan;
775
776 if (par == NULL || cpus_empty(cur->cpus_allowed))
777 return;
778
779 /*
780 * Get all cpus from parent's cpus_allowed not part of exclusive
781 * children
782 */
783 pspan = par->cpus_allowed;
784 list_for_each_entry(c, &par->children, sibling) {
785 if (is_cpu_exclusive(c))
786 cpus_andnot(pspan, pspan, c->cpus_allowed);
787 }
abb5a5cc 788 if (!is_cpu_exclusive(cur)) {
85d7b949
DG
789 cpus_or(pspan, pspan, cur->cpus_allowed);
790 if (cpus_equal(pspan, cur->cpus_allowed))
791 return;
792 cspan = CPU_MASK_NONE;
793 } else {
794 if (cpus_empty(pspan))
795 return;
796 cspan = cur->cpus_allowed;
797 /*
798 * Get all cpus from current cpuset's cpus_allowed not part
799 * of exclusive children
800 */
801 list_for_each_entry(c, &cur->children, sibling) {
802 if (is_cpu_exclusive(c))
803 cpus_andnot(cspan, cspan, c->cpus_allowed);
804 }
805 }
806
807 lock_cpu_hotplug();
808 partition_sched_domains(&pspan, &cspan);
809 unlock_cpu_hotplug();
810}
811
053199ed 812/*
3d3f26a7 813 * Call with manage_mutex held. May take callback_mutex during call.
053199ed
PJ
814 */
815
1da177e4
LT
816static int update_cpumask(struct cpuset *cs, char *buf)
817{
818 struct cpuset trialcs;
85d7b949 819 int retval, cpus_unchanged;
1da177e4 820
4c4d50f7
PJ
821 /* top_cpuset.cpus_allowed tracks cpu_online_map; it's read-only */
822 if (cs == &top_cpuset)
823 return -EACCES;
824
1da177e4 825 trialcs = *cs;
6f7f02e7
DR
826
827 /*
828 * We allow a cpuset's cpus_allowed to be empty; if it has attached
829 * tasks, we'll catch it later when we validate the change and return
830 * -ENOSPC.
831 */
832 if (!buf[0] || (buf[0] == '\n' && !buf[1])) {
833 cpus_clear(trialcs.cpus_allowed);
834 } else {
835 retval = cpulist_parse(buf, trialcs.cpus_allowed);
836 if (retval < 0)
837 return retval;
838 }
1da177e4 839 cpus_and(trialcs.cpus_allowed, trialcs.cpus_allowed, cpu_online_map);
6f7f02e7
DR
840 /* cpus_allowed cannot be empty for a cpuset with attached tasks. */
841 if (atomic_read(&cs->count) && cpus_empty(trialcs.cpus_allowed))
1da177e4
LT
842 return -ENOSPC;
843 retval = validate_change(cs, &trialcs);
85d7b949
DG
844 if (retval < 0)
845 return retval;
846 cpus_unchanged = cpus_equal(cs->cpus_allowed, trialcs.cpus_allowed);
3d3f26a7 847 mutex_lock(&callback_mutex);
85d7b949 848 cs->cpus_allowed = trialcs.cpus_allowed;
3d3f26a7 849 mutex_unlock(&callback_mutex);
85d7b949
DG
850 if (is_cpu_exclusive(cs) && !cpus_unchanged)
851 update_cpu_domains(cs);
852 return 0;
1da177e4
LT
853}
854
e4e364e8
PJ
855/*
856 * cpuset_migrate_mm
857 *
858 * Migrate memory region from one set of nodes to another.
859 *
860 * Temporarilly set tasks mems_allowed to target nodes of migration,
861 * so that the migration code can allocate pages on these nodes.
862 *
863 * Call holding manage_mutex, so our current->cpuset won't change
864 * during this call, as manage_mutex holds off any attach_task()
865 * calls. Therefore we don't need to take task_lock around the
866 * call to guarantee_online_mems(), as we know no one is changing
867 * our tasks cpuset.
868 *
869 * Hold callback_mutex around the two modifications of our tasks
870 * mems_allowed to synchronize with cpuset_mems_allowed().
871 *
872 * While the mm_struct we are migrating is typically from some
873 * other task, the task_struct mems_allowed that we are hacking
874 * is for our current task, which must allocate new pages for that
875 * migrating memory region.
876 *
877 * We call cpuset_update_task_memory_state() before hacking
878 * our tasks mems_allowed, so that we are assured of being in
879 * sync with our tasks cpuset, and in particular, callbacks to
880 * cpuset_update_task_memory_state() from nested page allocations
881 * won't see any mismatch of our cpuset and task mems_generation
882 * values, so won't overwrite our hacked tasks mems_allowed
883 * nodemask.
884 */
885
886static void cpuset_migrate_mm(struct mm_struct *mm, const nodemask_t *from,
887 const nodemask_t *to)
888{
889 struct task_struct *tsk = current;
890
891 cpuset_update_task_memory_state();
892
893 mutex_lock(&callback_mutex);
894 tsk->mems_allowed = *to;
895 mutex_unlock(&callback_mutex);
896
897 do_migrate_pages(mm, from, to, MPOL_MF_MOVE_ALL);
898
899 mutex_lock(&callback_mutex);
900 guarantee_online_mems(tsk->cpuset, &tsk->mems_allowed);
901 mutex_unlock(&callback_mutex);
902}
903
053199ed 904/*
4225399a
PJ
905 * Handle user request to change the 'mems' memory placement
906 * of a cpuset. Needs to validate the request, update the
907 * cpusets mems_allowed and mems_generation, and for each
04c19fa6
PJ
908 * task in the cpuset, rebind any vma mempolicies and if
909 * the cpuset is marked 'memory_migrate', migrate the tasks
910 * pages to the new memory.
4225399a 911 *
3d3f26a7 912 * Call with manage_mutex held. May take callback_mutex during call.
4225399a
PJ
913 * Will take tasklist_lock, scan tasklist for tasks in cpuset cs,
914 * lock each such tasks mm->mmap_sem, scan its vma's and rebind
915 * their mempolicies to the cpusets new mems_allowed.
053199ed
PJ
916 */
917
1da177e4
LT
918static int update_nodemask(struct cpuset *cs, char *buf)
919{
920 struct cpuset trialcs;
04c19fa6 921 nodemask_t oldmem;
4225399a
PJ
922 struct task_struct *g, *p;
923 struct mm_struct **mmarray;
924 int i, n, ntasks;
04c19fa6 925 int migrate;
4225399a 926 int fudge;
1da177e4
LT
927 int retval;
928
0e1e7c7a
CL
929 /*
930 * top_cpuset.mems_allowed tracks node_stats[N_HIGH_MEMORY];
931 * it's read-only
932 */
38837fc7
PJ
933 if (cs == &top_cpuset)
934 return -EACCES;
935
1da177e4 936 trialcs = *cs;
6f7f02e7
DR
937
938 /*
939 * We allow a cpuset's mems_allowed to be empty; if it has attached
940 * tasks, we'll catch it later when we validate the change and return
941 * -ENOSPC.
942 */
943 if (!buf[0] || (buf[0] == '\n' && !buf[1])) {
944 nodes_clear(trialcs.mems_allowed);
945 } else {
946 retval = nodelist_parse(buf, trialcs.mems_allowed);
947 if (retval < 0)
948 goto done;
0e1e7c7a
CL
949 if (!nodes_intersects(trialcs.mems_allowed,
950 node_states[N_HIGH_MEMORY])) {
951 /*
952 * error if only memoryless nodes specified.
953 */
954 retval = -ENOSPC;
955 goto done;
956 }
6f7f02e7 957 }
0e1e7c7a
CL
958 /*
959 * Exclude memoryless nodes. We know that trialcs.mems_allowed
960 * contains at least one node with memory.
961 */
962 nodes_and(trialcs.mems_allowed, trialcs.mems_allowed,
963 node_states[N_HIGH_MEMORY]);
04c19fa6
PJ
964 oldmem = cs->mems_allowed;
965 if (nodes_equal(oldmem, trialcs.mems_allowed)) {
966 retval = 0; /* Too easy - nothing to do */
967 goto done;
968 }
6f7f02e7
DR
969 /* mems_allowed cannot be empty for a cpuset with attached tasks. */
970 if (atomic_read(&cs->count) && nodes_empty(trialcs.mems_allowed)) {
59dac16f
PJ
971 retval = -ENOSPC;
972 goto done;
1da177e4 973 }
59dac16f
PJ
974 retval = validate_change(cs, &trialcs);
975 if (retval < 0)
976 goto done;
977
3d3f26a7 978 mutex_lock(&callback_mutex);
59dac16f 979 cs->mems_allowed = trialcs.mems_allowed;
151a4420 980 cs->mems_generation = cpuset_mems_generation++;
3d3f26a7 981 mutex_unlock(&callback_mutex);
59dac16f 982
4225399a
PJ
983 set_cpuset_being_rebound(cs); /* causes mpol_copy() rebind */
984
985 fudge = 10; /* spare mmarray[] slots */
986 fudge += cpus_weight(cs->cpus_allowed); /* imagine one fork-bomb/cpu */
987 retval = -ENOMEM;
988
989 /*
990 * Allocate mmarray[] to hold mm reference for each task
991 * in cpuset cs. Can't kmalloc GFP_KERNEL while holding
992 * tasklist_lock. We could use GFP_ATOMIC, but with a
993 * few more lines of code, we can retry until we get a big
994 * enough mmarray[] w/o using GFP_ATOMIC.
995 */
996 while (1) {
997 ntasks = atomic_read(&cs->count); /* guess */
998 ntasks += fudge;
999 mmarray = kmalloc(ntasks * sizeof(*mmarray), GFP_KERNEL);
1000 if (!mmarray)
1001 goto done;
c2aef333 1002 read_lock(&tasklist_lock); /* block fork */
4225399a
PJ
1003 if (atomic_read(&cs->count) <= ntasks)
1004 break; /* got enough */
c2aef333 1005 read_unlock(&tasklist_lock); /* try again */
4225399a
PJ
1006 kfree(mmarray);
1007 }
1008
1009 n = 0;
1010
1011 /* Load up mmarray[] with mm reference for each task in cpuset. */
1012 do_each_thread(g, p) {
1013 struct mm_struct *mm;
1014
1015 if (n >= ntasks) {
1016 printk(KERN_WARNING
1017 "Cpuset mempolicy rebind incomplete.\n");
1018 continue;
1019 }
1020 if (p->cpuset != cs)
1021 continue;
1022 mm = get_task_mm(p);
1023 if (!mm)
1024 continue;
1025 mmarray[n++] = mm;
1026 } while_each_thread(g, p);
c2aef333 1027 read_unlock(&tasklist_lock);
4225399a
PJ
1028
1029 /*
1030 * Now that we've dropped the tasklist spinlock, we can
1031 * rebind the vma mempolicies of each mm in mmarray[] to their
1032 * new cpuset, and release that mm. The mpol_rebind_mm()
1033 * call takes mmap_sem, which we couldn't take while holding
1034 * tasklist_lock. Forks can happen again now - the mpol_copy()
1035 * cpuset_being_rebound check will catch such forks, and rebind
1036 * their vma mempolicies too. Because we still hold the global
3d3f26a7 1037 * cpuset manage_mutex, we know that no other rebind effort will
4225399a
PJ
1038 * be contending for the global variable cpuset_being_rebound.
1039 * It's ok if we rebind the same mm twice; mpol_rebind_mm()
04c19fa6 1040 * is idempotent. Also migrate pages in each mm to new nodes.
4225399a 1041 */
04c19fa6 1042 migrate = is_memory_migrate(cs);
4225399a
PJ
1043 for (i = 0; i < n; i++) {
1044 struct mm_struct *mm = mmarray[i];
1045
1046 mpol_rebind_mm(mm, &cs->mems_allowed);
e4e364e8
PJ
1047 if (migrate)
1048 cpuset_migrate_mm(mm, &oldmem, &cs->mems_allowed);
4225399a
PJ
1049 mmput(mm);
1050 }
1051
1052 /* We're done rebinding vma's to this cpusets new mems_allowed. */
1053 kfree(mmarray);
1054 set_cpuset_being_rebound(NULL);
1055 retval = 0;
59dac16f 1056done:
1da177e4
LT
1057 return retval;
1058}
1059
3e0d98b9 1060/*
3d3f26a7 1061 * Call with manage_mutex held.
3e0d98b9
PJ
1062 */
1063
1064static int update_memory_pressure_enabled(struct cpuset *cs, char *buf)
1065{
1066 if (simple_strtoul(buf, NULL, 10) != 0)
1067 cpuset_memory_pressure_enabled = 1;
1068 else
1069 cpuset_memory_pressure_enabled = 0;
1070 return 0;
1071}
1072
1da177e4
LT
1073/*
1074 * update_flag - read a 0 or a 1 in a file and update associated flag
1075 * bit: the bit to update (CS_CPU_EXCLUSIVE, CS_MEM_EXCLUSIVE,
825a46af
PJ
1076 * CS_NOTIFY_ON_RELEASE, CS_MEMORY_MIGRATE,
1077 * CS_SPREAD_PAGE, CS_SPREAD_SLAB)
1da177e4
LT
1078 * cs: the cpuset to update
1079 * buf: the buffer where we read the 0 or 1
053199ed 1080 *
3d3f26a7 1081 * Call with manage_mutex held.
1da177e4
LT
1082 */
1083
1084static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs, char *buf)
1085{
1086 int turning_on;
1087 struct cpuset trialcs;
85d7b949 1088 int err, cpu_exclusive_changed;
1da177e4
LT
1089
1090 turning_on = (simple_strtoul(buf, NULL, 10) != 0);
1091
1092 trialcs = *cs;
1093 if (turning_on)
1094 set_bit(bit, &trialcs.flags);
1095 else
1096 clear_bit(bit, &trialcs.flags);
1097
1098 err = validate_change(cs, &trialcs);
85d7b949
DG
1099 if (err < 0)
1100 return err;
1101 cpu_exclusive_changed =
1102 (is_cpu_exclusive(cs) != is_cpu_exclusive(&trialcs));
3d3f26a7 1103 mutex_lock(&callback_mutex);
69604067 1104 cs->flags = trialcs.flags;
3d3f26a7 1105 mutex_unlock(&callback_mutex);
85d7b949
DG
1106
1107 if (cpu_exclusive_changed)
1108 update_cpu_domains(cs);
1109 return 0;
1da177e4
LT
1110}
1111
3e0d98b9 1112/*
80f7228b 1113 * Frequency meter - How fast is some event occurring?
3e0d98b9
PJ
1114 *
1115 * These routines manage a digitally filtered, constant time based,
1116 * event frequency meter. There are four routines:
1117 * fmeter_init() - initialize a frequency meter.
1118 * fmeter_markevent() - called each time the event happens.
1119 * fmeter_getrate() - returns the recent rate of such events.
1120 * fmeter_update() - internal routine used to update fmeter.
1121 *
1122 * A common data structure is passed to each of these routines,
1123 * which is used to keep track of the state required to manage the
1124 * frequency meter and its digital filter.
1125 *
1126 * The filter works on the number of events marked per unit time.
1127 * The filter is single-pole low-pass recursive (IIR). The time unit
1128 * is 1 second. Arithmetic is done using 32-bit integers scaled to
1129 * simulate 3 decimal digits of precision (multiplied by 1000).
1130 *
1131 * With an FM_COEF of 933, and a time base of 1 second, the filter
1132 * has a half-life of 10 seconds, meaning that if the events quit
1133 * happening, then the rate returned from the fmeter_getrate()
1134 * will be cut in half each 10 seconds, until it converges to zero.
1135 *
1136 * It is not worth doing a real infinitely recursive filter. If more
1137 * than FM_MAXTICKS ticks have elapsed since the last filter event,
1138 * just compute FM_MAXTICKS ticks worth, by which point the level
1139 * will be stable.
1140 *
1141 * Limit the count of unprocessed events to FM_MAXCNT, so as to avoid
1142 * arithmetic overflow in the fmeter_update() routine.
1143 *
1144 * Given the simple 32 bit integer arithmetic used, this meter works
1145 * best for reporting rates between one per millisecond (msec) and
1146 * one per 32 (approx) seconds. At constant rates faster than one
1147 * per msec it maxes out at values just under 1,000,000. At constant
1148 * rates between one per msec, and one per second it will stabilize
1149 * to a value N*1000, where N is the rate of events per second.
1150 * At constant rates between one per second and one per 32 seconds,
1151 * it will be choppy, moving up on the seconds that have an event,
1152 * and then decaying until the next event. At rates slower than
1153 * about one in 32 seconds, it decays all the way back to zero between
1154 * each event.
1155 */
1156
1157#define FM_COEF 933 /* coefficient for half-life of 10 secs */
1158#define FM_MAXTICKS ((time_t)99) /* useless computing more ticks than this */
1159#define FM_MAXCNT 1000000 /* limit cnt to avoid overflow */
1160#define FM_SCALE 1000 /* faux fixed point scale */
1161
1162/* Initialize a frequency meter */
1163static void fmeter_init(struct fmeter *fmp)
1164{
1165 fmp->cnt = 0;
1166 fmp->val = 0;
1167 fmp->time = 0;
1168 spin_lock_init(&fmp->lock);
1169}
1170
1171/* Internal meter update - process cnt events and update value */
1172static void fmeter_update(struct fmeter *fmp)
1173{
1174 time_t now = get_seconds();
1175 time_t ticks = now - fmp->time;
1176
1177 if (ticks == 0)
1178 return;
1179
1180 ticks = min(FM_MAXTICKS, ticks);
1181 while (ticks-- > 0)
1182 fmp->val = (FM_COEF * fmp->val) / FM_SCALE;
1183 fmp->time = now;
1184
1185 fmp->val += ((FM_SCALE - FM_COEF) * fmp->cnt) / FM_SCALE;
1186 fmp->cnt = 0;
1187}
1188
1189/* Process any previous ticks, then bump cnt by one (times scale). */
1190static void fmeter_markevent(struct fmeter *fmp)
1191{
1192 spin_lock(&fmp->lock);
1193 fmeter_update(fmp);
1194 fmp->cnt = min(FM_MAXCNT, fmp->cnt + FM_SCALE);
1195 spin_unlock(&fmp->lock);
1196}
1197
1198/* Process any previous ticks, then return current value. */
1199static int fmeter_getrate(struct fmeter *fmp)
1200{
1201 int val;
1202
1203 spin_lock(&fmp->lock);
1204 fmeter_update(fmp);
1205 val = fmp->val;
1206 spin_unlock(&fmp->lock);
1207 return val;
1208}
1209
053199ed
PJ
1210/*
1211 * Attack task specified by pid in 'pidbuf' to cpuset 'cs', possibly
1212 * writing the path of the old cpuset in 'ppathbuf' if it needs to be
1213 * notified on release.
1214 *
3d3f26a7 1215 * Call holding manage_mutex. May take callback_mutex and task_lock of
053199ed
PJ
1216 * the task 'pid' during call.
1217 */
1218
3077a260 1219static int attach_task(struct cpuset *cs, char *pidbuf, char **ppathbuf)
1da177e4
LT
1220{
1221 pid_t pid;
1222 struct task_struct *tsk;
1223 struct cpuset *oldcs;
1224 cpumask_t cpus;
45b07ef3 1225 nodemask_t from, to;
4225399a 1226 struct mm_struct *mm;
22fb52dd 1227 int retval;
1da177e4 1228
3077a260 1229 if (sscanf(pidbuf, "%d", &pid) != 1)
1da177e4
LT
1230 return -EIO;
1231 if (cpus_empty(cs->cpus_allowed) || nodes_empty(cs->mems_allowed))
1232 return -ENOSPC;
1233
1234 if (pid) {
1235 read_lock(&tasklist_lock);
1236
1237 tsk = find_task_by_pid(pid);
053199ed 1238 if (!tsk || tsk->flags & PF_EXITING) {
1da177e4
LT
1239 read_unlock(&tasklist_lock);
1240 return -ESRCH;
1241 }
1242
1243 get_task_struct(tsk);
1244 read_unlock(&tasklist_lock);
1245
1246 if ((current->euid) && (current->euid != tsk->uid)
1247 && (current->euid != tsk->suid)) {
1248 put_task_struct(tsk);
1249 return -EACCES;
1250 }
1251 } else {
1252 tsk = current;
1253 get_task_struct(tsk);
1254 }
1255
22fb52dd
DQ
1256 retval = security_task_setscheduler(tsk, 0, NULL);
1257 if (retval) {
1258 put_task_struct(tsk);
1259 return retval;
1260 }
1261
3d3f26a7 1262 mutex_lock(&callback_mutex);
053199ed 1263
1da177e4
LT
1264 task_lock(tsk);
1265 oldcs = tsk->cpuset;
181b6480
PJ
1266 /*
1267 * After getting 'oldcs' cpuset ptr, be sure still not exiting.
1268 * If 'oldcs' might be the top_cpuset due to the_top_cpuset_hack
1269 * then fail this attach_task(), to avoid breaking top_cpuset.count.
1270 */
1271 if (tsk->flags & PF_EXITING) {
1da177e4 1272 task_unlock(tsk);
3d3f26a7 1273 mutex_unlock(&callback_mutex);
1da177e4
LT
1274 put_task_struct(tsk);
1275 return -ESRCH;
1276 }
1277 atomic_inc(&cs->count);
6b9c2603 1278 rcu_assign_pointer(tsk->cpuset, cs);
1da177e4
LT
1279 task_unlock(tsk);
1280
1281 guarantee_online_cpus(cs, &cpus);
1282 set_cpus_allowed(tsk, cpus);
1283
45b07ef3
PJ
1284 from = oldcs->mems_allowed;
1285 to = cs->mems_allowed;
1286
3d3f26a7 1287 mutex_unlock(&callback_mutex);
4225399a
PJ
1288
1289 mm = get_task_mm(tsk);
1290 if (mm) {
1291 mpol_rebind_mm(mm, &to);
2741a559 1292 if (is_memory_migrate(cs))
e4e364e8 1293 cpuset_migrate_mm(mm, &from, &to);
4225399a
PJ
1294 mmput(mm);
1295 }
1296
1da177e4 1297 put_task_struct(tsk);
6b9c2603 1298 synchronize_rcu();
1da177e4 1299 if (atomic_dec_and_test(&oldcs->count))
3077a260 1300 check_for_release(oldcs, ppathbuf);
1da177e4
LT
1301 return 0;
1302}
1303
1304/* The various types of files and directories in a cpuset file system */
1305
1306typedef enum {
1307 FILE_ROOT,
1308 FILE_DIR,
45b07ef3 1309 FILE_MEMORY_MIGRATE,
1da177e4
LT
1310 FILE_CPULIST,
1311 FILE_MEMLIST,
1312 FILE_CPU_EXCLUSIVE,
1313 FILE_MEM_EXCLUSIVE,
1314 FILE_NOTIFY_ON_RELEASE,
3e0d98b9
PJ
1315 FILE_MEMORY_PRESSURE_ENABLED,
1316 FILE_MEMORY_PRESSURE,
825a46af
PJ
1317 FILE_SPREAD_PAGE,
1318 FILE_SPREAD_SLAB,
1da177e4
LT
1319 FILE_TASKLIST,
1320} cpuset_filetype_t;
1321
d3ed11c3
PM
1322static ssize_t cpuset_common_file_write(struct file *file,
1323 const char __user *userbuf,
1da177e4
LT
1324 size_t nbytes, loff_t *unused_ppos)
1325{
a7a005fd
JS
1326 struct cpuset *cs = __d_cs(file->f_path.dentry->d_parent);
1327 struct cftype *cft = __d_cft(file->f_path.dentry);
1da177e4
LT
1328 cpuset_filetype_t type = cft->private;
1329 char *buffer;
3077a260 1330 char *pathbuf = NULL;
1da177e4
LT
1331 int retval = 0;
1332
1333 /* Crude upper limit on largest legitimate cpulist user might write. */
d3ed11c3 1334 if (nbytes > 100 + 6 * max(NR_CPUS, MAX_NUMNODES))
1da177e4
LT
1335 return -E2BIG;
1336
1337 /* +1 for nul-terminator */
1338 if ((buffer = kmalloc(nbytes + 1, GFP_KERNEL)) == 0)
1339 return -ENOMEM;
1340
1341 if (copy_from_user(buffer, userbuf, nbytes)) {
1342 retval = -EFAULT;
1343 goto out1;
1344 }
1345 buffer[nbytes] = 0; /* nul-terminate */
1346
3d3f26a7 1347 mutex_lock(&manage_mutex);
1da177e4
LT
1348
1349 if (is_removed(cs)) {
1350 retval = -ENODEV;
1351 goto out2;
1352 }
1353
1354 switch (type) {
1355 case FILE_CPULIST:
1356 retval = update_cpumask(cs, buffer);
1357 break;
1358 case FILE_MEMLIST:
1359 retval = update_nodemask(cs, buffer);
1360 break;
1361 case FILE_CPU_EXCLUSIVE:
1362 retval = update_flag(CS_CPU_EXCLUSIVE, cs, buffer);
1363 break;
1364 case FILE_MEM_EXCLUSIVE:
1365 retval = update_flag(CS_MEM_EXCLUSIVE, cs, buffer);
1366 break;
1367 case FILE_NOTIFY_ON_RELEASE:
1368 retval = update_flag(CS_NOTIFY_ON_RELEASE, cs, buffer);
1369 break;
45b07ef3
PJ
1370 case FILE_MEMORY_MIGRATE:
1371 retval = update_flag(CS_MEMORY_MIGRATE, cs, buffer);
1372 break;
3e0d98b9
PJ
1373 case FILE_MEMORY_PRESSURE_ENABLED:
1374 retval = update_memory_pressure_enabled(cs, buffer);
1375 break;
1376 case FILE_MEMORY_PRESSURE:
1377 retval = -EACCES;
1378 break;
825a46af
PJ
1379 case FILE_SPREAD_PAGE:
1380 retval = update_flag(CS_SPREAD_PAGE, cs, buffer);
151a4420 1381 cs->mems_generation = cpuset_mems_generation++;
825a46af
PJ
1382 break;
1383 case FILE_SPREAD_SLAB:
1384 retval = update_flag(CS_SPREAD_SLAB, cs, buffer);
151a4420 1385 cs->mems_generation = cpuset_mems_generation++;
825a46af 1386 break;
1da177e4 1387 case FILE_TASKLIST:
3077a260 1388 retval = attach_task(cs, buffer, &pathbuf);
1da177e4
LT
1389 break;
1390 default:
1391 retval = -EINVAL;
1392 goto out2;
1393 }
1394
1395 if (retval == 0)
1396 retval = nbytes;
1397out2:
3d3f26a7 1398 mutex_unlock(&manage_mutex);
3077a260 1399 cpuset_release_agent(pathbuf);
1da177e4
LT
1400out1:
1401 kfree(buffer);
1402 return retval;
1403}
1404
1405static ssize_t cpuset_file_write(struct file *file, const char __user *buf,
1406 size_t nbytes, loff_t *ppos)
1407{
1408 ssize_t retval = 0;
a7a005fd 1409 struct cftype *cft = __d_cft(file->f_path.dentry);
1da177e4
LT
1410 if (!cft)
1411 return -ENODEV;
1412
1413 /* special function ? */
1414 if (cft->write)
1415 retval = cft->write(file, buf, nbytes, ppos);
1416 else
1417 retval = cpuset_common_file_write(file, buf, nbytes, ppos);
1418
1419 return retval;
1420}
1421
1422/*
1423 * These ascii lists should be read in a single call, by using a user
1424 * buffer large enough to hold the entire map. If read in smaller
1425 * chunks, there is no guarantee of atomicity. Since the display format
1426 * used, list of ranges of sequential numbers, is variable length,
1427 * and since these maps can change value dynamically, one could read
1428 * gibberish by doing partial reads while a list was changing.
1429 * A single large read to a buffer that crosses a page boundary is
1430 * ok, because the result being copied to user land is not recomputed
1431 * across a page fault.
1432 */
1433
1434static int cpuset_sprintf_cpulist(char *page, struct cpuset *cs)
1435{
1436 cpumask_t mask;
1437
3d3f26a7 1438 mutex_lock(&callback_mutex);
1da177e4 1439 mask = cs->cpus_allowed;
3d3f26a7 1440 mutex_unlock(&callback_mutex);
1da177e4
LT
1441
1442 return cpulist_scnprintf(page, PAGE_SIZE, mask);
1443}
1444
1445static int cpuset_sprintf_memlist(char *page, struct cpuset *cs)
1446{
1447 nodemask_t mask;
1448
3d3f26a7 1449 mutex_lock(&callback_mutex);
1da177e4 1450 mask = cs->mems_allowed;
3d3f26a7 1451 mutex_unlock(&callback_mutex);
1da177e4
LT
1452
1453 return nodelist_scnprintf(page, PAGE_SIZE, mask);
1454}
1455
1456static ssize_t cpuset_common_file_read(struct file *file, char __user *buf,
1457 size_t nbytes, loff_t *ppos)
1458{
a7a005fd
JS
1459 struct cftype *cft = __d_cft(file->f_path.dentry);
1460 struct cpuset *cs = __d_cs(file->f_path.dentry->d_parent);
1da177e4
LT
1461 cpuset_filetype_t type = cft->private;
1462 char *page;
1463 ssize_t retval = 0;
1464 char *s;
1da177e4 1465
e12ba74d 1466 if (!(page = (char *)__get_free_page(GFP_TEMPORARY)))
1da177e4
LT
1467 return -ENOMEM;
1468
1469 s = page;
1470
1471 switch (type) {
1472 case FILE_CPULIST:
1473 s += cpuset_sprintf_cpulist(s, cs);
1474 break;
1475 case FILE_MEMLIST:
1476 s += cpuset_sprintf_memlist(s, cs);
1477 break;
1478 case FILE_CPU_EXCLUSIVE:
1479 *s++ = is_cpu_exclusive(cs) ? '1' : '0';
1480 break;
1481 case FILE_MEM_EXCLUSIVE:
1482 *s++ = is_mem_exclusive(cs) ? '1' : '0';
1483 break;
1484 case FILE_NOTIFY_ON_RELEASE:
1485 *s++ = notify_on_release(cs) ? '1' : '0';
1486 break;
45b07ef3
PJ
1487 case FILE_MEMORY_MIGRATE:
1488 *s++ = is_memory_migrate(cs) ? '1' : '0';
1489 break;
3e0d98b9
PJ
1490 case FILE_MEMORY_PRESSURE_ENABLED:
1491 *s++ = cpuset_memory_pressure_enabled ? '1' : '0';
1492 break;
1493 case FILE_MEMORY_PRESSURE:
1494 s += sprintf(s, "%d", fmeter_getrate(&cs->fmeter));
1495 break;
825a46af
PJ
1496 case FILE_SPREAD_PAGE:
1497 *s++ = is_spread_page(cs) ? '1' : '0';
1498 break;
1499 case FILE_SPREAD_SLAB:
1500 *s++ = is_spread_slab(cs) ? '1' : '0';
1501 break;
1da177e4
LT
1502 default:
1503 retval = -EINVAL;
1504 goto out;
1505 }
1506 *s++ = '\n';
1da177e4 1507
eacaa1f5 1508 retval = simple_read_from_buffer(buf, nbytes, ppos, page, s - page);
1da177e4
LT
1509out:
1510 free_page((unsigned long)page);
1511 return retval;
1512}
1513
1514static ssize_t cpuset_file_read(struct file *file, char __user *buf, size_t nbytes,
1515 loff_t *ppos)
1516{
1517 ssize_t retval = 0;
a7a005fd 1518 struct cftype *cft = __d_cft(file->f_path.dentry);
1da177e4
LT
1519 if (!cft)
1520 return -ENODEV;
1521
1522 /* special function ? */
1523 if (cft->read)
1524 retval = cft->read(file, buf, nbytes, ppos);
1525 else
1526 retval = cpuset_common_file_read(file, buf, nbytes, ppos);
1527
1528 return retval;
1529}
1530
1531static int cpuset_file_open(struct inode *inode, struct file *file)
1532{
1533 int err;
1534 struct cftype *cft;
1535
1536 err = generic_file_open(inode, file);
1537 if (err)
1538 return err;
1539
a7a005fd 1540 cft = __d_cft(file->f_path.dentry);
1da177e4
LT
1541 if (!cft)
1542 return -ENODEV;
1543 if (cft->open)
1544 err = cft->open(inode, file);
1545 else
1546 err = 0;
1547
1548 return err;
1549}
1550
1551static int cpuset_file_release(struct inode *inode, struct file *file)
1552{
a7a005fd 1553 struct cftype *cft = __d_cft(file->f_path.dentry);
1da177e4
LT
1554 if (cft->release)
1555 return cft->release(inode, file);
1556 return 0;
1557}
1558
18a19cb3
PJ
1559/*
1560 * cpuset_rename - Only allow simple rename of directories in place.
1561 */
1562static int cpuset_rename(struct inode *old_dir, struct dentry *old_dentry,
1563 struct inode *new_dir, struct dentry *new_dentry)
1564{
1565 if (!S_ISDIR(old_dentry->d_inode->i_mode))
1566 return -ENOTDIR;
1567 if (new_dentry->d_inode)
1568 return -EEXIST;
1569 if (old_dir != new_dir)
1570 return -EIO;
1571 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1572}
1573
15ad7cdc 1574static const struct file_operations cpuset_file_operations = {
1da177e4
LT
1575 .read = cpuset_file_read,
1576 .write = cpuset_file_write,
1577 .llseek = generic_file_llseek,
1578 .open = cpuset_file_open,
1579 .release = cpuset_file_release,
1580};
1581
92e1d5be 1582static const struct inode_operations cpuset_dir_inode_operations = {
1da177e4
LT
1583 .lookup = simple_lookup,
1584 .mkdir = cpuset_mkdir,
1585 .rmdir = cpuset_rmdir,
18a19cb3 1586 .rename = cpuset_rename,
1da177e4
LT
1587};
1588
1589static int cpuset_create_file(struct dentry *dentry, int mode)
1590{
1591 struct inode *inode;
1592
1593 if (!dentry)
1594 return -ENOENT;
1595 if (dentry->d_inode)
1596 return -EEXIST;
1597
1598 inode = cpuset_new_inode(mode);
1599 if (!inode)
1600 return -ENOMEM;
1601
1602 if (S_ISDIR(mode)) {
1603 inode->i_op = &cpuset_dir_inode_operations;
1604 inode->i_fop = &simple_dir_operations;
1605
1606 /* start off with i_nlink == 2 (for "." entry) */
d8c76e6f 1607 inc_nlink(inode);
1da177e4
LT
1608 } else if (S_ISREG(mode)) {
1609 inode->i_size = 0;
1610 inode->i_fop = &cpuset_file_operations;
1611 }
1612
1613 d_instantiate(dentry, inode);
1614 dget(dentry); /* Extra count - pin the dentry in core */
1615 return 0;
1616}
1617
1618/*
1619 * cpuset_create_dir - create a directory for an object.
c5b2aff8 1620 * cs: the cpuset we create the directory for.
1da177e4
LT
1621 * It must have a valid ->parent field
1622 * And we are going to fill its ->dentry field.
1623 * name: The name to give to the cpuset directory. Will be copied.
1624 * mode: mode to set on new directory.
1625 */
1626
1627static int cpuset_create_dir(struct cpuset *cs, const char *name, int mode)
1628{
1629 struct dentry *dentry = NULL;
1630 struct dentry *parent;
1631 int error = 0;
1632
1633 parent = cs->parent->dentry;
1634 dentry = cpuset_get_dentry(parent, name);
1635 if (IS_ERR(dentry))
1636 return PTR_ERR(dentry);
1637 error = cpuset_create_file(dentry, S_IFDIR | mode);
1638 if (!error) {
1639 dentry->d_fsdata = cs;
d8c76e6f 1640 inc_nlink(parent->d_inode);
1da177e4
LT
1641 cs->dentry = dentry;
1642 }
1643 dput(dentry);
1644
1645 return error;
1646}
1647
1648static int cpuset_add_file(struct dentry *dir, const struct cftype *cft)
1649{
1650 struct dentry *dentry;
1651 int error;
1652
1b1dcc1b 1653 mutex_lock(&dir->d_inode->i_mutex);
1da177e4
LT
1654 dentry = cpuset_get_dentry(dir, cft->name);
1655 if (!IS_ERR(dentry)) {
1656 error = cpuset_create_file(dentry, 0644 | S_IFREG);
1657 if (!error)
1658 dentry->d_fsdata = (void *)cft;
1659 dput(dentry);
1660 } else
1661 error = PTR_ERR(dentry);
1b1dcc1b 1662 mutex_unlock(&dir->d_inode->i_mutex);
1da177e4
LT
1663 return error;
1664}
1665
1666/*
1667 * Stuff for reading the 'tasks' file.
1668 *
1669 * Reading this file can return large amounts of data if a cpuset has
1670 * *lots* of attached tasks. So it may need several calls to read(),
1671 * but we cannot guarantee that the information we produce is correct
1672 * unless we produce it entirely atomically.
1673 *
1674 * Upon tasks file open(), a struct ctr_struct is allocated, that
1675 * will have a pointer to an array (also allocated here). The struct
1676 * ctr_struct * is stored in file->private_data. Its resources will
1677 * be freed by release() when the file is closed. The array is used
1678 * to sprintf the PIDs and then used by read().
1679 */
1680
1681/* cpusets_tasks_read array */
1682
1683struct ctr_struct {
1684 char *buf;
1685 int bufsz;
1686};
1687
1688/*
1689 * Load into 'pidarray' up to 'npids' of the tasks using cpuset 'cs'.
053199ed
PJ
1690 * Return actual number of pids loaded. No need to task_lock(p)
1691 * when reading out p->cpuset, as we don't really care if it changes
1692 * on the next cycle, and we are not going to try to dereference it.
1da177e4 1693 */
858119e1 1694static int pid_array_load(pid_t *pidarray, int npids, struct cpuset *cs)
1da177e4
LT
1695{
1696 int n = 0;
1697 struct task_struct *g, *p;
1698
1699 read_lock(&tasklist_lock);
1700
1701 do_each_thread(g, p) {
1702 if (p->cpuset == cs) {
1da177e4
LT
1703 if (unlikely(n == npids))
1704 goto array_full;
3e903e7b 1705 pidarray[n++] = p->pid;
1da177e4
LT
1706 }
1707 } while_each_thread(g, p);
1708
1709array_full:
1710 read_unlock(&tasklist_lock);
1711 return n;
1712}
1713
1714static int cmppid(const void *a, const void *b)
1715{
1716 return *(pid_t *)a - *(pid_t *)b;
1717}
1718
1719/*
1720 * Convert array 'a' of 'npids' pid_t's to a string of newline separated
1721 * decimal pids in 'buf'. Don't write more than 'sz' chars, but return
1722 * count 'cnt' of how many chars would be written if buf were large enough.
1723 */
1724static int pid_array_to_buf(char *buf, int sz, pid_t *a, int npids)
1725{
1726 int cnt = 0;
1727 int i;
1728
1729 for (i = 0; i < npids; i++)
1730 cnt += snprintf(buf + cnt, max(sz - cnt, 0), "%d\n", a[i]);
1731 return cnt;
1732}
1733
053199ed
PJ
1734/*
1735 * Handle an open on 'tasks' file. Prepare a buffer listing the
1736 * process id's of tasks currently attached to the cpuset being opened.
1737 *
3d3f26a7 1738 * Does not require any specific cpuset mutexes, and does not take any.
053199ed 1739 */
1da177e4
LT
1740static int cpuset_tasks_open(struct inode *unused, struct file *file)
1741{
a7a005fd 1742 struct cpuset *cs = __d_cs(file->f_path.dentry->d_parent);
1da177e4
LT
1743 struct ctr_struct *ctr;
1744 pid_t *pidarray;
1745 int npids;
1746 char c;
1747
1748 if (!(file->f_mode & FMODE_READ))
1749 return 0;
1750
1751 ctr = kmalloc(sizeof(*ctr), GFP_KERNEL);
1752 if (!ctr)
1753 goto err0;
1754
1755 /*
1756 * If cpuset gets more users after we read count, we won't have
1757 * enough space - tough. This race is indistinguishable to the
1758 * caller from the case that the additional cpuset users didn't
1759 * show up until sometime later on.
1760 */
1761 npids = atomic_read(&cs->count);
1762 pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
1763 if (!pidarray)
1764 goto err1;
1765
1766 npids = pid_array_load(pidarray, npids, cs);
1767 sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
1768
1769 /* Call pid_array_to_buf() twice, first just to get bufsz */
1770 ctr->bufsz = pid_array_to_buf(&c, sizeof(c), pidarray, npids) + 1;
1771 ctr->buf = kmalloc(ctr->bufsz, GFP_KERNEL);
1772 if (!ctr->buf)
1773 goto err2;
1774 ctr->bufsz = pid_array_to_buf(ctr->buf, ctr->bufsz, pidarray, npids);
1775
1776 kfree(pidarray);
1777 file->private_data = ctr;
1778 return 0;
1779
1780err2:
1781 kfree(pidarray);
1782err1:
1783 kfree(ctr);
1784err0:
1785 return -ENOMEM;
1786}
1787
1788static ssize_t cpuset_tasks_read(struct file *file, char __user *buf,
1789 size_t nbytes, loff_t *ppos)
1790{
1791 struct ctr_struct *ctr = file->private_data;
1792
85badbdf 1793 return simple_read_from_buffer(buf, nbytes, ppos, ctr->buf, ctr->bufsz);
1da177e4
LT
1794}
1795
1796static int cpuset_tasks_release(struct inode *unused_inode, struct file *file)
1797{
1798 struct ctr_struct *ctr;
1799
1800 if (file->f_mode & FMODE_READ) {
1801 ctr = file->private_data;
1802 kfree(ctr->buf);
1803 kfree(ctr);
1804 }
1805 return 0;
1806}
1807
1808/*
1809 * for the common functions, 'private' gives the type of file
1810 */
1811
1812static struct cftype cft_tasks = {
1813 .name = "tasks",
1814 .open = cpuset_tasks_open,
1815 .read = cpuset_tasks_read,
1816 .release = cpuset_tasks_release,
1817 .private = FILE_TASKLIST,
1818};
1819
1820static struct cftype cft_cpus = {
1821 .name = "cpus",
1822 .private = FILE_CPULIST,
1823};
1824
1825static struct cftype cft_mems = {
1826 .name = "mems",
1827 .private = FILE_MEMLIST,
1828};
1829
1830static struct cftype cft_cpu_exclusive = {
1831 .name = "cpu_exclusive",
1832 .private = FILE_CPU_EXCLUSIVE,
1833};
1834
1835static struct cftype cft_mem_exclusive = {
1836 .name = "mem_exclusive",
1837 .private = FILE_MEM_EXCLUSIVE,
1838};
1839
1840static struct cftype cft_notify_on_release = {
1841 .name = "notify_on_release",
1842 .private = FILE_NOTIFY_ON_RELEASE,
1843};
1844
45b07ef3
PJ
1845static struct cftype cft_memory_migrate = {
1846 .name = "memory_migrate",
1847 .private = FILE_MEMORY_MIGRATE,
1848};
1849
3e0d98b9
PJ
1850static struct cftype cft_memory_pressure_enabled = {
1851 .name = "memory_pressure_enabled",
1852 .private = FILE_MEMORY_PRESSURE_ENABLED,
1853};
1854
1855static struct cftype cft_memory_pressure = {
1856 .name = "memory_pressure",
1857 .private = FILE_MEMORY_PRESSURE,
1858};
1859
825a46af
PJ
1860static struct cftype cft_spread_page = {
1861 .name = "memory_spread_page",
1862 .private = FILE_SPREAD_PAGE,
1863};
1864
1865static struct cftype cft_spread_slab = {
1866 .name = "memory_spread_slab",
1867 .private = FILE_SPREAD_SLAB,
1868};
1869
1da177e4
LT
1870static int cpuset_populate_dir(struct dentry *cs_dentry)
1871{
1872 int err;
1873
1874 if ((err = cpuset_add_file(cs_dentry, &cft_cpus)) < 0)
1875 return err;
1876 if ((err = cpuset_add_file(cs_dentry, &cft_mems)) < 0)
1877 return err;
1878 if ((err = cpuset_add_file(cs_dentry, &cft_cpu_exclusive)) < 0)
1879 return err;
1880 if ((err = cpuset_add_file(cs_dentry, &cft_mem_exclusive)) < 0)
1881 return err;
1882 if ((err = cpuset_add_file(cs_dentry, &cft_notify_on_release)) < 0)
1883 return err;
45b07ef3
PJ
1884 if ((err = cpuset_add_file(cs_dentry, &cft_memory_migrate)) < 0)
1885 return err;
3e0d98b9
PJ
1886 if ((err = cpuset_add_file(cs_dentry, &cft_memory_pressure)) < 0)
1887 return err;
825a46af
PJ
1888 if ((err = cpuset_add_file(cs_dentry, &cft_spread_page)) < 0)
1889 return err;
1890 if ((err = cpuset_add_file(cs_dentry, &cft_spread_slab)) < 0)
1891 return err;
1da177e4
LT
1892 if ((err = cpuset_add_file(cs_dentry, &cft_tasks)) < 0)
1893 return err;
1894 return 0;
1895}
1896
1897/*
1898 * cpuset_create - create a cpuset
1899 * parent: cpuset that will be parent of the new cpuset.
1900 * name: name of the new cpuset. Will be strcpy'ed.
1901 * mode: mode to set on new inode
1902 *
3d3f26a7 1903 * Must be called with the mutex on the parent inode held
1da177e4
LT
1904 */
1905
1906static long cpuset_create(struct cpuset *parent, const char *name, int mode)
1907{
1908 struct cpuset *cs;
1909 int err;
1910
1911 cs = kmalloc(sizeof(*cs), GFP_KERNEL);
1912 if (!cs)
1913 return -ENOMEM;
1914
3d3f26a7 1915 mutex_lock(&manage_mutex);
cf2a473c 1916 cpuset_update_task_memory_state();
1da177e4
LT
1917 cs->flags = 0;
1918 if (notify_on_release(parent))
1919 set_bit(CS_NOTIFY_ON_RELEASE, &cs->flags);
825a46af
PJ
1920 if (is_spread_page(parent))
1921 set_bit(CS_SPREAD_PAGE, &cs->flags);
1922 if (is_spread_slab(parent))
1923 set_bit(CS_SPREAD_SLAB, &cs->flags);
1da177e4
LT
1924 cs->cpus_allowed = CPU_MASK_NONE;
1925 cs->mems_allowed = NODE_MASK_NONE;
1926 atomic_set(&cs->count, 0);
1927 INIT_LIST_HEAD(&cs->sibling);
1928 INIT_LIST_HEAD(&cs->children);
151a4420 1929 cs->mems_generation = cpuset_mems_generation++;
3e0d98b9 1930 fmeter_init(&cs->fmeter);
1da177e4
LT
1931
1932 cs->parent = parent;
1933
3d3f26a7 1934 mutex_lock(&callback_mutex);
1da177e4 1935 list_add(&cs->sibling, &cs->parent->children);
202f72d5 1936 number_of_cpusets++;
3d3f26a7 1937 mutex_unlock(&callback_mutex);
1da177e4
LT
1938
1939 err = cpuset_create_dir(cs, name, mode);
1940 if (err < 0)
1941 goto err;
1942
1943 /*
3d3f26a7 1944 * Release manage_mutex before cpuset_populate_dir() because it
1b1dcc1b 1945 * will down() this new directory's i_mutex and if we race with
1da177e4
LT
1946 * another mkdir, we might deadlock.
1947 */
3d3f26a7 1948 mutex_unlock(&manage_mutex);
1da177e4
LT
1949
1950 err = cpuset_populate_dir(cs->dentry);
1951 /* If err < 0, we have a half-filled directory - oh well ;) */
1952 return 0;
1953err:
1954 list_del(&cs->sibling);
3d3f26a7 1955 mutex_unlock(&manage_mutex);
1da177e4
LT
1956 kfree(cs);
1957 return err;
1958}
1959
1960static int cpuset_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1961{
1962 struct cpuset *c_parent = dentry->d_parent->d_fsdata;
1963
1b1dcc1b 1964 /* the vfs holds inode->i_mutex already */
1da177e4
LT
1965 return cpuset_create(c_parent, dentry->d_name.name, mode | S_IFDIR);
1966}
1967
abb5a5cc
PJ
1968/*
1969 * Locking note on the strange update_flag() call below:
1970 *
1971 * If the cpuset being removed is marked cpu_exclusive, then simulate
1972 * turning cpu_exclusive off, which will call update_cpu_domains().
1973 * The lock_cpu_hotplug() call in update_cpu_domains() must not be
1974 * made while holding callback_mutex. Elsewhere the kernel nests
1975 * callback_mutex inside lock_cpu_hotplug() calls. So the reverse
1976 * nesting would risk an ABBA deadlock.
1977 */
1978
1da177e4
LT
1979static int cpuset_rmdir(struct inode *unused_dir, struct dentry *dentry)
1980{
1981 struct cpuset *cs = dentry->d_fsdata;
1982 struct dentry *d;
1983 struct cpuset *parent;
3077a260 1984 char *pathbuf = NULL;
1da177e4 1985
1b1dcc1b 1986 /* the vfs holds both inode->i_mutex already */
1da177e4 1987
3d3f26a7 1988 mutex_lock(&manage_mutex);
cf2a473c 1989 cpuset_update_task_memory_state();
1da177e4 1990 if (atomic_read(&cs->count) > 0) {
3d3f26a7 1991 mutex_unlock(&manage_mutex);
1da177e4
LT
1992 return -EBUSY;
1993 }
1994 if (!list_empty(&cs->children)) {
3d3f26a7 1995 mutex_unlock(&manage_mutex);
1da177e4
LT
1996 return -EBUSY;
1997 }
abb5a5cc
PJ
1998 if (is_cpu_exclusive(cs)) {
1999 int retval = update_flag(CS_CPU_EXCLUSIVE, cs, "0");
2000 if (retval < 0) {
2001 mutex_unlock(&manage_mutex);
2002 return retval;
2003 }
2004 }
1da177e4 2005 parent = cs->parent;
3d3f26a7 2006 mutex_lock(&callback_mutex);
1da177e4
LT
2007 set_bit(CS_REMOVED, &cs->flags);
2008 list_del(&cs->sibling); /* delete my sibling from parent->children */
85d7b949 2009 spin_lock(&cs->dentry->d_lock);
1da177e4
LT
2010 d = dget(cs->dentry);
2011 cs->dentry = NULL;
2012 spin_unlock(&d->d_lock);
2013 cpuset_d_remove_dir(d);
2014 dput(d);
202f72d5 2015 number_of_cpusets--;
3d3f26a7 2016 mutex_unlock(&callback_mutex);
053199ed
PJ
2017 if (list_empty(&parent->children))
2018 check_for_release(parent, &pathbuf);
3d3f26a7 2019 mutex_unlock(&manage_mutex);
3077a260 2020 cpuset_release_agent(pathbuf);
1da177e4
LT
2021 return 0;
2022}
2023
c417f024
PJ
2024/*
2025 * cpuset_init_early - just enough so that the calls to
2026 * cpuset_update_task_memory_state() in early init code
2027 * are harmless.
2028 */
2029
2030int __init cpuset_init_early(void)
2031{
2032 struct task_struct *tsk = current;
2033
2034 tsk->cpuset = &top_cpuset;
151a4420 2035 tsk->cpuset->mems_generation = cpuset_mems_generation++;
c417f024
PJ
2036 return 0;
2037}
2038
1da177e4
LT
2039/**
2040 * cpuset_init - initialize cpusets at system boot
2041 *
2042 * Description: Initialize top_cpuset and the cpuset internal file system,
2043 **/
2044
2045int __init cpuset_init(void)
2046{
2047 struct dentry *root;
2048 int err;
2049
2050 top_cpuset.cpus_allowed = CPU_MASK_ALL;
2051 top_cpuset.mems_allowed = NODE_MASK_ALL;
2052
3e0d98b9 2053 fmeter_init(&top_cpuset.fmeter);
151a4420 2054 top_cpuset.mems_generation = cpuset_mems_generation++;
1da177e4
LT
2055
2056 init_task.cpuset = &top_cpuset;
2057
2058 err = register_filesystem(&cpuset_fs_type);
2059 if (err < 0)
2060 goto out;
2061 cpuset_mount = kern_mount(&cpuset_fs_type);
2062 if (IS_ERR(cpuset_mount)) {
2063 printk(KERN_ERR "cpuset: could not mount!\n");
2064 err = PTR_ERR(cpuset_mount);
2065 cpuset_mount = NULL;
2066 goto out;
2067 }
2068 root = cpuset_mount->mnt_sb->s_root;
2069 root->d_fsdata = &top_cpuset;
d8c76e6f 2070 inc_nlink(root->d_inode);
1da177e4
LT
2071 top_cpuset.dentry = root;
2072 root->d_inode->i_op = &cpuset_dir_inode_operations;
202f72d5 2073 number_of_cpusets = 1;
1da177e4 2074 err = cpuset_populate_dir(root);
3e0d98b9
PJ
2075 /* memory_pressure_enabled is in root cpuset only */
2076 if (err == 0)
2077 err = cpuset_add_file(root, &cft_memory_pressure_enabled);
1da177e4
LT
2078out:
2079 return err;
2080}
2081
b1aac8bb
PJ
2082/*
2083 * If common_cpu_mem_hotplug_unplug(), below, unplugs any CPUs
2084 * or memory nodes, we need to walk over the cpuset hierarchy,
2085 * removing that CPU or node from all cpusets. If this removes the
2086 * last CPU or node from a cpuset, then the guarantee_online_cpus()
2087 * or guarantee_online_mems() code will use that emptied cpusets
2088 * parent online CPUs or nodes. Cpusets that were already empty of
2089 * CPUs or nodes are left empty.
2090 *
2091 * This routine is intentionally inefficient in a couple of regards.
2092 * It will check all cpusets in a subtree even if the top cpuset of
2093 * the subtree has no offline CPUs or nodes. It checks both CPUs and
2094 * nodes, even though the caller could have been coded to know that
2095 * only one of CPUs or nodes needed to be checked on a given call.
2096 * This was done to minimize text size rather than cpu cycles.
2097 *
2098 * Call with both manage_mutex and callback_mutex held.
2099 *
2100 * Recursive, on depth of cpuset subtree.
2101 */
2102
2103static void guarantee_online_cpus_mems_in_subtree(const struct cpuset *cur)
2104{
2105 struct cpuset *c;
2106
2107 /* Each of our child cpusets mems must be online */
2108 list_for_each_entry(c, &cur->children, sibling) {
2109 guarantee_online_cpus_mems_in_subtree(c);
2110 if (!cpus_empty(c->cpus_allowed))
2111 guarantee_online_cpus(c, &c->cpus_allowed);
2112 if (!nodes_empty(c->mems_allowed))
2113 guarantee_online_mems(c, &c->mems_allowed);
2114 }
2115}
2116
2117/*
2118 * The cpus_allowed and mems_allowed nodemasks in the top_cpuset track
0e1e7c7a
CL
2119 * cpu_online_map and node_states[N_HIGH_MEMORY]. Force the top cpuset to
2120 * track what's online after any CPU or memory node hotplug or unplug
2121 * event.
b1aac8bb
PJ
2122 *
2123 * To ensure that we don't remove a CPU or node from the top cpuset
2124 * that is currently in use by a child cpuset (which would violate
2125 * the rule that cpusets must be subsets of their parent), we first
2126 * call the recursive routine guarantee_online_cpus_mems_in_subtree().
2127 *
2128 * Since there are two callers of this routine, one for CPU hotplug
2129 * events and one for memory node hotplug events, we could have coded
2130 * two separate routines here. We code it as a single common routine
2131 * in order to minimize text size.
2132 */
2133
2134static void common_cpu_mem_hotplug_unplug(void)
2135{
2136 mutex_lock(&manage_mutex);
2137 mutex_lock(&callback_mutex);
2138
2139 guarantee_online_cpus_mems_in_subtree(&top_cpuset);
2140 top_cpuset.cpus_allowed = cpu_online_map;
0e1e7c7a 2141 top_cpuset.mems_allowed = node_states[N_HIGH_MEMORY];
b1aac8bb
PJ
2142
2143 mutex_unlock(&callback_mutex);
2144 mutex_unlock(&manage_mutex);
2145}
b1aac8bb 2146
4c4d50f7
PJ
2147/*
2148 * The top_cpuset tracks what CPUs and Memory Nodes are online,
2149 * period. This is necessary in order to make cpusets transparent
2150 * (of no affect) on systems that are actively using CPU hotplug
2151 * but making no active use of cpusets.
2152 *
38837fc7
PJ
2153 * This routine ensures that top_cpuset.cpus_allowed tracks
2154 * cpu_online_map on each CPU hotplug (cpuhp) event.
4c4d50f7
PJ
2155 */
2156
4c4d50f7
PJ
2157static int cpuset_handle_cpuhp(struct notifier_block *nb,
2158 unsigned long phase, void *cpu)
2159{
ac076758
AK
2160 if (phase == CPU_DYING || phase == CPU_DYING_FROZEN)
2161 return NOTIFY_DONE;
2162
b1aac8bb 2163 common_cpu_mem_hotplug_unplug();
4c4d50f7
PJ
2164 return 0;
2165}
4c4d50f7 2166
b1aac8bb 2167#ifdef CONFIG_MEMORY_HOTPLUG
38837fc7 2168/*
0e1e7c7a
CL
2169 * Keep top_cpuset.mems_allowed tracking node_states[N_HIGH_MEMORY].
2170 * Call this routine anytime after you change
2171 * node_states[N_HIGH_MEMORY].
38837fc7
PJ
2172 * See also the previous routine cpuset_handle_cpuhp().
2173 */
2174
1af98928 2175void cpuset_track_online_nodes(void)
38837fc7 2176{
b1aac8bb 2177 common_cpu_mem_hotplug_unplug();
38837fc7
PJ
2178}
2179#endif
2180
1da177e4
LT
2181/**
2182 * cpuset_init_smp - initialize cpus_allowed
2183 *
2184 * Description: Finish top cpuset after cpu, node maps are initialized
2185 **/
2186
2187void __init cpuset_init_smp(void)
2188{
2189 top_cpuset.cpus_allowed = cpu_online_map;
0e1e7c7a 2190 top_cpuset.mems_allowed = node_states[N_HIGH_MEMORY];
4c4d50f7
PJ
2191
2192 hotcpu_notifier(cpuset_handle_cpuhp, 0);
1da177e4
LT
2193}
2194
2195/**
2196 * cpuset_fork - attach newly forked task to its parents cpuset.
d9fd8a6d 2197 * @tsk: pointer to task_struct of forking parent process.
1da177e4 2198 *
053199ed
PJ
2199 * Description: A task inherits its parent's cpuset at fork().
2200 *
2201 * A pointer to the shared cpuset was automatically copied in fork.c
2202 * by dup_task_struct(). However, we ignore that copy, since it was
2203 * not made under the protection of task_lock(), so might no longer be
2204 * a valid cpuset pointer. attach_task() might have already changed
2205 * current->cpuset, allowing the previously referenced cpuset to
2206 * be removed and freed. Instead, we task_lock(current) and copy
2207 * its present value of current->cpuset for our freshly forked child.
2208 *
2209 * At the point that cpuset_fork() is called, 'current' is the parent
2210 * task, and the passed argument 'child' points to the child task.
1da177e4
LT
2211 **/
2212
053199ed 2213void cpuset_fork(struct task_struct *child)
1da177e4 2214{
053199ed
PJ
2215 task_lock(current);
2216 child->cpuset = current->cpuset;
2217 atomic_inc(&child->cpuset->count);
2218 task_unlock(current);
1da177e4
LT
2219}
2220
2221/**
2222 * cpuset_exit - detach cpuset from exiting task
2223 * @tsk: pointer to task_struct of exiting process
2224 *
2225 * Description: Detach cpuset from @tsk and release it.
2226 *
053199ed 2227 * Note that cpusets marked notify_on_release force every task in
3d3f26a7 2228 * them to take the global manage_mutex mutex when exiting.
053199ed
PJ
2229 * This could impact scaling on very large systems. Be reluctant to
2230 * use notify_on_release cpusets where very high task exit scaling
2231 * is required on large systems.
2232 *
2233 * Don't even think about derefencing 'cs' after the cpuset use count
3d3f26a7
IM
2234 * goes to zero, except inside a critical section guarded by manage_mutex
2235 * or callback_mutex. Otherwise a zero cpuset use count is a license to
053199ed
PJ
2236 * any other task to nuke the cpuset immediately, via cpuset_rmdir().
2237 *
3d3f26a7
IM
2238 * This routine has to take manage_mutex, not callback_mutex, because
2239 * it is holding that mutex while calling check_for_release(),
2240 * which calls kmalloc(), so can't be called holding callback_mutex().
053199ed 2241 *
8488bc35 2242 * the_top_cpuset_hack:
06fed338
PJ
2243 *
2244 * Set the exiting tasks cpuset to the root cpuset (top_cpuset).
2245 *
2246 * Don't leave a task unable to allocate memory, as that is an
2247 * accident waiting to happen should someone add a callout in
2248 * do_exit() after the cpuset_exit() call that might allocate.
2249 * If a task tries to allocate memory with an invalid cpuset,
2250 * it will oops in cpuset_update_task_memory_state().
2251 *
2252 * We call cpuset_exit() while the task is still competent to
2253 * handle notify_on_release(), then leave the task attached to
2254 * the root cpuset (top_cpuset) for the remainder of its exit.
2255 *
2256 * To do this properly, we would increment the reference count on
2257 * top_cpuset, and near the very end of the kernel/exit.c do_exit()
2258 * code we would add a second cpuset function call, to drop that
2259 * reference. This would just create an unnecessary hot spot on
2260 * the top_cpuset reference count, to no avail.
2261 *
2262 * Normally, holding a reference to a cpuset without bumping its
2263 * count is unsafe. The cpuset could go away, or someone could
2264 * attach us to a different cpuset, decrementing the count on
2265 * the first cpuset that we never incremented. But in this case,
2266 * top_cpuset isn't going away, and either task has PF_EXITING set,
2267 * which wards off any attach_task() attempts, or task is a failed
2268 * fork, never visible to attach_task.
2269 *
2270 * Another way to do this would be to set the cpuset pointer
2271 * to NULL here, and check in cpuset_update_task_memory_state()
2272 * for a NULL pointer. This hack avoids that NULL check, for no
2273 * cost (other than this way too long comment ;).
1da177e4
LT
2274 **/
2275
2276void cpuset_exit(struct task_struct *tsk)
2277{
2278 struct cpuset *cs;
2279
dd9037a2 2280 task_lock(current);
1da177e4 2281 cs = tsk->cpuset;
8488bc35 2282 tsk->cpuset = &top_cpuset; /* the_top_cpuset_hack - see above */
dd9037a2 2283 task_unlock(current);
1da177e4 2284
2efe86b8 2285 if (notify_on_release(cs)) {
3077a260
PJ
2286 char *pathbuf = NULL;
2287
3d3f26a7 2288 mutex_lock(&manage_mutex);
2efe86b8 2289 if (atomic_dec_and_test(&cs->count))
3077a260 2290 check_for_release(cs, &pathbuf);
3d3f26a7 2291 mutex_unlock(&manage_mutex);
3077a260 2292 cpuset_release_agent(pathbuf);
2efe86b8
PJ
2293 } else {
2294 atomic_dec(&cs->count);
1da177e4
LT
2295 }
2296}
2297
2298/**
2299 * cpuset_cpus_allowed - return cpus_allowed mask from a tasks cpuset.
2300 * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
2301 *
2302 * Description: Returns the cpumask_t cpus_allowed of the cpuset
2303 * attached to the specified @tsk. Guaranteed to return some non-empty
2304 * subset of cpu_online_map, even if this means going outside the
2305 * tasks cpuset.
2306 **/
2307
909d75a3 2308cpumask_t cpuset_cpus_allowed(struct task_struct *tsk)
1da177e4
LT
2309{
2310 cpumask_t mask;
2311
3d3f26a7 2312 mutex_lock(&callback_mutex);
909d75a3 2313 task_lock(tsk);
1da177e4 2314 guarantee_online_cpus(tsk->cpuset, &mask);
909d75a3 2315 task_unlock(tsk);
3d3f26a7 2316 mutex_unlock(&callback_mutex);
1da177e4
LT
2317
2318 return mask;
2319}
2320
2321void cpuset_init_current_mems_allowed(void)
2322{
2323 current->mems_allowed = NODE_MASK_ALL;
2324}
2325
909d75a3
PJ
2326/**
2327 * cpuset_mems_allowed - return mems_allowed mask from a tasks cpuset.
2328 * @tsk: pointer to task_struct from which to obtain cpuset->mems_allowed.
2329 *
2330 * Description: Returns the nodemask_t mems_allowed of the cpuset
2331 * attached to the specified @tsk. Guaranteed to return some non-empty
0e1e7c7a 2332 * subset of node_states[N_HIGH_MEMORY], even if this means going outside the
909d75a3
PJ
2333 * tasks cpuset.
2334 **/
2335
2336nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
2337{
2338 nodemask_t mask;
2339
3d3f26a7 2340 mutex_lock(&callback_mutex);
909d75a3
PJ
2341 task_lock(tsk);
2342 guarantee_online_mems(tsk->cpuset, &mask);
2343 task_unlock(tsk);
3d3f26a7 2344 mutex_unlock(&callback_mutex);
909d75a3
PJ
2345
2346 return mask;
2347}
2348
d9fd8a6d
RD
2349/**
2350 * cpuset_zonelist_valid_mems_allowed - check zonelist vs. curremt mems_allowed
2351 * @zl: the zonelist to be checked
2352 *
1da177e4
LT
2353 * Are any of the nodes on zonelist zl allowed in current->mems_allowed?
2354 */
2355int cpuset_zonelist_valid_mems_allowed(struct zonelist *zl)
2356{
2357 int i;
2358
2359 for (i = 0; zl->zones[i]; i++) {
89fa3024 2360 int nid = zone_to_nid(zl->zones[i]);
1da177e4
LT
2361
2362 if (node_isset(nid, current->mems_allowed))
2363 return 1;
2364 }
2365 return 0;
2366}
2367
9bf2229f
PJ
2368/*
2369 * nearest_exclusive_ancestor() - Returns the nearest mem_exclusive
3d3f26a7 2370 * ancestor to the specified cpuset. Call holding callback_mutex.
9bf2229f
PJ
2371 * If no ancestor is mem_exclusive (an unusual configuration), then
2372 * returns the root cpuset.
2373 */
2374static const struct cpuset *nearest_exclusive_ancestor(const struct cpuset *cs)
2375{
2376 while (!is_mem_exclusive(cs) && cs->parent)
2377 cs = cs->parent;
2378 return cs;
2379}
2380
d9fd8a6d 2381/**
02a0e53d 2382 * cpuset_zone_allowed_softwall - Can we allocate on zone z's memory node?
9bf2229f 2383 * @z: is this zone on an allowed node?
02a0e53d 2384 * @gfp_mask: memory allocation flags
d9fd8a6d 2385 *
02a0e53d
PJ
2386 * If we're in interrupt, yes, we can always allocate. If
2387 * __GFP_THISNODE is set, yes, we can always allocate. If zone
9bf2229f
PJ
2388 * z's node is in our tasks mems_allowed, yes. If it's not a
2389 * __GFP_HARDWALL request and this zone's nodes is in the nearest
2390 * mem_exclusive cpuset ancestor to this tasks cpuset, yes.
c596d9f3
DR
2391 * If the task has been OOM killed and has access to memory reserves
2392 * as specified by the TIF_MEMDIE flag, yes.
9bf2229f
PJ
2393 * Otherwise, no.
2394 *
02a0e53d
PJ
2395 * If __GFP_HARDWALL is set, cpuset_zone_allowed_softwall()
2396 * reduces to cpuset_zone_allowed_hardwall(). Otherwise,
2397 * cpuset_zone_allowed_softwall() might sleep, and might allow a zone
2398 * from an enclosing cpuset.
2399 *
2400 * cpuset_zone_allowed_hardwall() only handles the simpler case of
2401 * hardwall cpusets, and never sleeps.
2402 *
2403 * The __GFP_THISNODE placement logic is really handled elsewhere,
2404 * by forcibly using a zonelist starting at a specified node, and by
2405 * (in get_page_from_freelist()) refusing to consider the zones for
2406 * any node on the zonelist except the first. By the time any such
2407 * calls get to this routine, we should just shut up and say 'yes'.
2408 *
9bf2229f 2409 * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
c596d9f3
DR
2410 * and do not allow allocations outside the current tasks cpuset
2411 * unless the task has been OOM killed as is marked TIF_MEMDIE.
9bf2229f 2412 * GFP_KERNEL allocations are not so marked, so can escape to the
02a0e53d 2413 * nearest enclosing mem_exclusive ancestor cpuset.
9bf2229f 2414 *
02a0e53d
PJ
2415 * Scanning up parent cpusets requires callback_mutex. The
2416 * __alloc_pages() routine only calls here with __GFP_HARDWALL bit
2417 * _not_ set if it's a GFP_KERNEL allocation, and all nodes in the
2418 * current tasks mems_allowed came up empty on the first pass over
2419 * the zonelist. So only GFP_KERNEL allocations, if all nodes in the
2420 * cpuset are short of memory, might require taking the callback_mutex
2421 * mutex.
9bf2229f 2422 *
36be57ff 2423 * The first call here from mm/page_alloc:get_page_from_freelist()
02a0e53d
PJ
2424 * has __GFP_HARDWALL set in gfp_mask, enforcing hardwall cpusets,
2425 * so no allocation on a node outside the cpuset is allowed (unless
2426 * in interrupt, of course).
36be57ff
PJ
2427 *
2428 * The second pass through get_page_from_freelist() doesn't even call
2429 * here for GFP_ATOMIC calls. For those calls, the __alloc_pages()
2430 * variable 'wait' is not set, and the bit ALLOC_CPUSET is not set
2431 * in alloc_flags. That logic and the checks below have the combined
2432 * affect that:
9bf2229f
PJ
2433 * in_interrupt - any node ok (current task context irrelevant)
2434 * GFP_ATOMIC - any node ok
c596d9f3 2435 * TIF_MEMDIE - any node ok
9bf2229f
PJ
2436 * GFP_KERNEL - any node in enclosing mem_exclusive cpuset ok
2437 * GFP_USER - only nodes in current tasks mems allowed ok.
36be57ff
PJ
2438 *
2439 * Rule:
02a0e53d 2440 * Don't call cpuset_zone_allowed_softwall if you can't sleep, unless you
36be57ff
PJ
2441 * pass in the __GFP_HARDWALL flag set in gfp_flag, which disables
2442 * the code that might scan up ancestor cpusets and sleep.
02a0e53d 2443 */
9bf2229f 2444
02a0e53d 2445int __cpuset_zone_allowed_softwall(struct zone *z, gfp_t gfp_mask)
1da177e4 2446{
9bf2229f
PJ
2447 int node; /* node that zone z is on */
2448 const struct cpuset *cs; /* current cpuset ancestors */
29afd49b 2449 int allowed; /* is allocation in zone z allowed? */
9bf2229f 2450
9b819d20 2451 if (in_interrupt() || (gfp_mask & __GFP_THISNODE))
9bf2229f 2452 return 1;
89fa3024 2453 node = zone_to_nid(z);
92d1dbd2 2454 might_sleep_if(!(gfp_mask & __GFP_HARDWALL));
9bf2229f
PJ
2455 if (node_isset(node, current->mems_allowed))
2456 return 1;
c596d9f3
DR
2457 /*
2458 * Allow tasks that have access to memory reserves because they have
2459 * been OOM killed to get memory anywhere.
2460 */
2461 if (unlikely(test_thread_flag(TIF_MEMDIE)))
2462 return 1;
9bf2229f
PJ
2463 if (gfp_mask & __GFP_HARDWALL) /* If hardwall request, stop here */
2464 return 0;
2465
5563e770
BP
2466 if (current->flags & PF_EXITING) /* Let dying task have memory */
2467 return 1;
2468
9bf2229f 2469 /* Not hardwall and node outside mems_allowed: scan up cpusets */
3d3f26a7 2470 mutex_lock(&callback_mutex);
053199ed 2471
053199ed
PJ
2472 task_lock(current);
2473 cs = nearest_exclusive_ancestor(current->cpuset);
2474 task_unlock(current);
2475
9bf2229f 2476 allowed = node_isset(node, cs->mems_allowed);
3d3f26a7 2477 mutex_unlock(&callback_mutex);
9bf2229f 2478 return allowed;
1da177e4
LT
2479}
2480
02a0e53d
PJ
2481/*
2482 * cpuset_zone_allowed_hardwall - Can we allocate on zone z's memory node?
2483 * @z: is this zone on an allowed node?
2484 * @gfp_mask: memory allocation flags
2485 *
2486 * If we're in interrupt, yes, we can always allocate.
2487 * If __GFP_THISNODE is set, yes, we can always allocate. If zone
c596d9f3
DR
2488 * z's node is in our tasks mems_allowed, yes. If the task has been
2489 * OOM killed and has access to memory reserves as specified by the
2490 * TIF_MEMDIE flag, yes. Otherwise, no.
02a0e53d
PJ
2491 *
2492 * The __GFP_THISNODE placement logic is really handled elsewhere,
2493 * by forcibly using a zonelist starting at a specified node, and by
2494 * (in get_page_from_freelist()) refusing to consider the zones for
2495 * any node on the zonelist except the first. By the time any such
2496 * calls get to this routine, we should just shut up and say 'yes'.
2497 *
2498 * Unlike the cpuset_zone_allowed_softwall() variant, above,
2499 * this variant requires that the zone be in the current tasks
2500 * mems_allowed or that we're in interrupt. It does not scan up the
2501 * cpuset hierarchy for the nearest enclosing mem_exclusive cpuset.
2502 * It never sleeps.
2503 */
2504
2505int __cpuset_zone_allowed_hardwall(struct zone *z, gfp_t gfp_mask)
2506{
2507 int node; /* node that zone z is on */
2508
2509 if (in_interrupt() || (gfp_mask & __GFP_THISNODE))
2510 return 1;
2511 node = zone_to_nid(z);
2512 if (node_isset(node, current->mems_allowed))
2513 return 1;
c596d9f3
DR
2514 /*
2515 * Allow tasks that have access to memory reserves because they have
2516 * been OOM killed to get memory anywhere.
2517 */
2518 if (unlikely(test_thread_flag(TIF_MEMDIE)))
2519 return 1;
02a0e53d
PJ
2520 return 0;
2521}
2522
505970b9
PJ
2523/**
2524 * cpuset_lock - lock out any changes to cpuset structures
2525 *
3d3f26a7 2526 * The out of memory (oom) code needs to mutex_lock cpusets
505970b9 2527 * from being changed while it scans the tasklist looking for a
3d3f26a7 2528 * task in an overlapping cpuset. Expose callback_mutex via this
505970b9
PJ
2529 * cpuset_lock() routine, so the oom code can lock it, before
2530 * locking the task list. The tasklist_lock is a spinlock, so
3d3f26a7 2531 * must be taken inside callback_mutex.
505970b9
PJ
2532 */
2533
2534void cpuset_lock(void)
2535{
3d3f26a7 2536 mutex_lock(&callback_mutex);
505970b9
PJ
2537}
2538
2539/**
2540 * cpuset_unlock - release lock on cpuset changes
2541 *
2542 * Undo the lock taken in a previous cpuset_lock() call.
2543 */
2544
2545void cpuset_unlock(void)
2546{
3d3f26a7 2547 mutex_unlock(&callback_mutex);
505970b9
PJ
2548}
2549
825a46af
PJ
2550/**
2551 * cpuset_mem_spread_node() - On which node to begin search for a page
2552 *
2553 * If a task is marked PF_SPREAD_PAGE or PF_SPREAD_SLAB (as for
2554 * tasks in a cpuset with is_spread_page or is_spread_slab set),
2555 * and if the memory allocation used cpuset_mem_spread_node()
2556 * to determine on which node to start looking, as it will for
2557 * certain page cache or slab cache pages such as used for file
2558 * system buffers and inode caches, then instead of starting on the
2559 * local node to look for a free page, rather spread the starting
2560 * node around the tasks mems_allowed nodes.
2561 *
2562 * We don't have to worry about the returned node being offline
2563 * because "it can't happen", and even if it did, it would be ok.
2564 *
2565 * The routines calling guarantee_online_mems() are careful to
2566 * only set nodes in task->mems_allowed that are online. So it
2567 * should not be possible for the following code to return an
2568 * offline node. But if it did, that would be ok, as this routine
2569 * is not returning the node where the allocation must be, only
2570 * the node where the search should start. The zonelist passed to
2571 * __alloc_pages() will include all nodes. If the slab allocator
2572 * is passed an offline node, it will fall back to the local node.
2573 * See kmem_cache_alloc_node().
2574 */
2575
2576int cpuset_mem_spread_node(void)
2577{
2578 int node;
2579
2580 node = next_node(current->cpuset_mem_spread_rotor, current->mems_allowed);
2581 if (node == MAX_NUMNODES)
2582 node = first_node(current->mems_allowed);
2583 current->cpuset_mem_spread_rotor = node;
2584 return node;
2585}
2586EXPORT_SYMBOL_GPL(cpuset_mem_spread_node);
2587
ef08e3b4
PJ
2588/**
2589 * cpuset_excl_nodes_overlap - Do we overlap @p's mem_exclusive ancestors?
2590 * @p: pointer to task_struct of some other task.
2591 *
2592 * Description: Return true if the nearest mem_exclusive ancestor
2593 * cpusets of tasks @p and current overlap. Used by oom killer to
2594 * determine if task @p's memory usage might impact the memory
2595 * available to the current task.
2596 *
3d3f26a7 2597 * Call while holding callback_mutex.
ef08e3b4
PJ
2598 **/
2599
2600int cpuset_excl_nodes_overlap(const struct task_struct *p)
2601{
2602 const struct cpuset *cs1, *cs2; /* my and p's cpuset ancestors */
0d673a5a 2603 int overlap = 1; /* do cpusets overlap? */
ef08e3b4 2604
053199ed
PJ
2605 task_lock(current);
2606 if (current->flags & PF_EXITING) {
2607 task_unlock(current);
2608 goto done;
2609 }
2610 cs1 = nearest_exclusive_ancestor(current->cpuset);
2611 task_unlock(current);
2612
2613 task_lock((struct task_struct *)p);
2614 if (p->flags & PF_EXITING) {
2615 task_unlock((struct task_struct *)p);
2616 goto done;
2617 }
2618 cs2 = nearest_exclusive_ancestor(p->cpuset);
2619 task_unlock((struct task_struct *)p);
2620
ef08e3b4
PJ
2621 overlap = nodes_intersects(cs1->mems_allowed, cs2->mems_allowed);
2622done:
ef08e3b4
PJ
2623 return overlap;
2624}
2625
3e0d98b9
PJ
2626/*
2627 * Collection of memory_pressure is suppressed unless
2628 * this flag is enabled by writing "1" to the special
2629 * cpuset file 'memory_pressure_enabled' in the root cpuset.
2630 */
2631
c5b2aff8 2632int cpuset_memory_pressure_enabled __read_mostly;
3e0d98b9
PJ
2633
2634/**
2635 * cpuset_memory_pressure_bump - keep stats of per-cpuset reclaims.
2636 *
2637 * Keep a running average of the rate of synchronous (direct)
2638 * page reclaim efforts initiated by tasks in each cpuset.
2639 *
2640 * This represents the rate at which some task in the cpuset
2641 * ran low on memory on all nodes it was allowed to use, and
2642 * had to enter the kernels page reclaim code in an effort to
2643 * create more free memory by tossing clean pages or swapping
2644 * or writing dirty pages.
2645 *
2646 * Display to user space in the per-cpuset read-only file
2647 * "memory_pressure". Value displayed is an integer
2648 * representing the recent rate of entry into the synchronous
2649 * (direct) page reclaim by any task attached to the cpuset.
2650 **/
2651
2652void __cpuset_memory_pressure_bump(void)
2653{
2654 struct cpuset *cs;
2655
2656 task_lock(current);
2657 cs = current->cpuset;
2658 fmeter_markevent(&cs->fmeter);
2659 task_unlock(current);
2660}
2661
1da177e4
LT
2662/*
2663 * proc_cpuset_show()
2664 * - Print tasks cpuset path into seq_file.
2665 * - Used for /proc/<pid>/cpuset.
053199ed
PJ
2666 * - No need to task_lock(tsk) on this tsk->cpuset reference, as it
2667 * doesn't really matter if tsk->cpuset changes after we read it,
3d3f26a7 2668 * and we take manage_mutex, keeping attach_task() from changing it
8488bc35
PJ
2669 * anyway. No need to check that tsk->cpuset != NULL, thanks to
2670 * the_top_cpuset_hack in cpuset_exit(), which sets an exiting tasks
2671 * cpuset to top_cpuset.
1da177e4 2672 */
1da177e4
LT
2673static int proc_cpuset_show(struct seq_file *m, void *v)
2674{
13b41b09 2675 struct pid *pid;
1da177e4
LT
2676 struct task_struct *tsk;
2677 char *buf;
99f89551 2678 int retval;
1da177e4 2679
99f89551 2680 retval = -ENOMEM;
1da177e4
LT
2681 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
2682 if (!buf)
99f89551
EB
2683 goto out;
2684
2685 retval = -ESRCH;
13b41b09
EB
2686 pid = m->private;
2687 tsk = get_pid_task(pid, PIDTYPE_PID);
99f89551
EB
2688 if (!tsk)
2689 goto out_free;
1da177e4 2690
99f89551 2691 retval = -EINVAL;
3d3f26a7 2692 mutex_lock(&manage_mutex);
99f89551 2693
8488bc35 2694 retval = cpuset_path(tsk->cpuset, buf, PAGE_SIZE);
1da177e4 2695 if (retval < 0)
99f89551 2696 goto out_unlock;
1da177e4
LT
2697 seq_puts(m, buf);
2698 seq_putc(m, '\n');
99f89551 2699out_unlock:
3d3f26a7 2700 mutex_unlock(&manage_mutex);
99f89551
EB
2701 put_task_struct(tsk);
2702out_free:
1da177e4 2703 kfree(buf);
99f89551 2704out:
1da177e4
LT
2705 return retval;
2706}
2707
2708static int cpuset_open(struct inode *inode, struct file *file)
2709{
13b41b09
EB
2710 struct pid *pid = PROC_I(inode)->pid;
2711 return single_open(file, proc_cpuset_show, pid);
1da177e4
LT
2712}
2713
9a32144e 2714const struct file_operations proc_cpuset_operations = {
1da177e4
LT
2715 .open = cpuset_open,
2716 .read = seq_read,
2717 .llseek = seq_lseek,
2718 .release = single_release,
2719};
2720
2721/* Display task cpus_allowed, mems_allowed in /proc/<pid>/status file. */
2722char *cpuset_task_status_allowed(struct task_struct *task, char *buffer)
2723{
2724 buffer += sprintf(buffer, "Cpus_allowed:\t");
2725 buffer += cpumask_scnprintf(buffer, PAGE_SIZE, task->cpus_allowed);
2726 buffer += sprintf(buffer, "\n");
2727 buffer += sprintf(buffer, "Mems_allowed:\t");
2728 buffer += nodemask_scnprintf(buffer, PAGE_SIZE, task->mems_allowed);
2729 buffer += sprintf(buffer, "\n");
2730 return buffer;
2731}