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