8b2daac4de8336f8c96ca13df3bebac15e2a51bd
[sfrench/cifs-2.6.git] / kernel / cpuset.c
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-2006 Silicon Graphics, Inc.
8  *
9  *  Portions derived from Patrick Mochel's sysfs code.
10  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
11  *
12  *  2003-10-10 Written by Simon Derr.
13  *  2003-10-22 Updates by Stephen Hemminger.
14  *  2004 May-July Rework by Paul Jackson.
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
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>
33 #include <linux/mempolicy.h>
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>
40 #include <linux/rcupdate.h>
41 #include <linux/sched.h>
42 #include <linux/seq_file.h>
43 #include <linux/security.h>
44 #include <linux/slab.h>
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>
54 #include <linux/mutex.h>
55
56 #define CPUSET_SUPER_MAGIC              0x27e0eb
57
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  */
63 int number_of_cpusets __read_mostly;
64
65 /* See "Frequency meter" comments, below. */
66
67 struct 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
74 struct 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
79         /*
80          * Count is atomic so can incr (fork) or decr (exit) without a lock.
81          */
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          */
98         int mems_generation;
99
100         struct fmeter fmeter;           /* memory_pressure filter */
101 };
102
103 /* bits in struct cpuset flags field */
104 typedef enum {
105         CS_CPU_EXCLUSIVE,
106         CS_MEM_EXCLUSIVE,
107         CS_MEMORY_MIGRATE,
108         CS_REMOVED,
109         CS_NOTIFY_ON_RELEASE,
110         CS_SPREAD_PAGE,
111         CS_SPREAD_SLAB,
112 } cpuset_flagbits_t;
113
114 /* convenient tests for these bits */
115 static inline int is_cpu_exclusive(const struct cpuset *cs)
116 {
117         return test_bit(CS_CPU_EXCLUSIVE, &cs->flags);
118 }
119
120 static inline int is_mem_exclusive(const struct cpuset *cs)
121 {
122         return test_bit(CS_MEM_EXCLUSIVE, &cs->flags);
123 }
124
125 static inline int is_removed(const struct cpuset *cs)
126 {
127         return test_bit(CS_REMOVED, &cs->flags);
128 }
129
130 static inline int notify_on_release(const struct cpuset *cs)
131 {
132         return test_bit(CS_NOTIFY_ON_RELEASE, &cs->flags);
133 }
134
135 static inline int is_memory_migrate(const struct cpuset *cs)
136 {
137         return test_bit(CS_MEMORY_MIGRATE, &cs->flags);
138 }
139
140 static inline int is_spread_page(const struct cpuset *cs)
141 {
142         return test_bit(CS_SPREAD_PAGE, &cs->flags);
143 }
144
145 static inline int is_spread_slab(const struct cpuset *cs)
146 {
147         return test_bit(CS_SPREAD_SLAB, &cs->flags);
148 }
149
150 /*
151  * Increment this integer everytime any cpuset changes its
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.
165  *
166  * Since cpuset_mems_generation is guarded by manage_mutex,
167  * there is no need to mark it atomic.
168  */
169 static int cpuset_mems_generation;
170
171 static 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),
178 };
179
180 static struct vfsmount *cpuset_mount;
181 static struct super_block *cpuset_sb;
182
183 /*
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
186  * require taking task_lock() when dereferencing a tasks cpuset pointer.
187  * See "The task_lock() exception", at the end of this comment.
188  *
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
192  * and be able to modify cpusets.  It can perform various checks on
193  * the cpuset structure first, knowing nothing will change.  It can
194  * also allocate memory while just holding manage_mutex.  While it is
195  * performing these checks, various callback routines can briefly
196  * acquire callback_mutex to query cpusets.  Once it is ready to make
197  * the changes, it takes callback_mutex, blocking everyone else.
198  *
199  * Calls to the kernel memory allocator can not be made while holding
200  * callback_mutex, as that would risk double tripping on callback_mutex
201  * from one of the callbacks into the cpuset code from within
202  * __alloc_pages().
203  *
204  * If a task is only holding callback_mutex, then it has read-only
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.
211  * So in general, code holding manage_mutex or callback_mutex can't rely
212  * on the count field not changing.  However, if the count goes to
213  * zero, then only attach_task(), which holds both mutexes, can
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).
217  * So code holding manage_mutex or callback_mutex can safely assume that
218  * if the count is zero, it will stay zero.  Similarly, if a task
219  * holds manage_mutex or callback_mutex on a cpuset with zero count, it
220  * knows that the cpuset won't be removed, as cpuset_rmdir() needs
221  * both of those mutexes.
222  *
223  * The cpuset_common_file_write handler for operations that modify
224  * the cpuset hierarchy holds manage_mutex across the entire operation,
225  * single threading all such cpuset modifications across the system.
226  *
227  * The cpuset_common_file_read() handlers only hold callback_mutex across
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
232  * (usually) take either mutex.  These are the two most performance
233  * critical pieces of code here.  The exception occurs on cpuset_exit(),
234  * when a task in a notify_on_release cpuset exits.  Then manage_mutex
235  * is taken, and if the cpuset count is zero, a usermode call made
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  *
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
242  * least one task in the system (init), therefore, top_cpuset
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
252  * so using both mutexes, however there are several performance
253  * critical places that need to reference task->cpuset without the
254  * expense of grabbing a system global mutex.  Therefore except as
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.
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().
264  */
265
266 static DEFINE_MUTEX(manage_mutex);
267 static DEFINE_MUTEX(callback_mutex);
268
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
275 static int cpuset_mkdir(struct inode *dir, struct dentry *dentry, int mode);
276 static int cpuset_rmdir(struct inode *unused_dir, struct dentry *dentry);
277
278 static 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
283 static 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;
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
298 static 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
309 static struct dentry_operations cpuset_dops = {
310         .d_iput = cpuset_diput,
311 };
312
313 static struct dentry *cpuset_get_dentry(struct dentry *parent, const char *name)
314 {
315         struct dentry *d = lookup_one_len(name, parent, strlen(name));
316         if (!IS_ERR(d))
317                 d->d_op = &cpuset_dops;
318         return d;
319 }
320
321 static 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  */
333 static 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) {
340                 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
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         }
352         list_del_init(&dentry->d_u.d_child);
353         spin_unlock(&dcache_lock);
354         remove_dir(dentry);
355 }
356
357 static struct super_operations cpuset_ops = {
358         .statfs = simple_statfs,
359         .drop_inode = generic_delete_inode,
360 };
361
362 static 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) */
379                 inc_nlink(inode);
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
393 static int cpuset_get_sb(struct file_system_type *fs_type,
394                          int flags, const char *unused_dev_name,
395                          void *data, struct vfsmount *mnt)
396 {
397         return get_sb_single(fs_type, flags, data, cpuset_fill_super, mnt);
398 }
399
400 static 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:
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
417  */
418
419 struct 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
430 static inline struct cpuset *__d_cs(struct dentry *dentry)
431 {
432         return dentry->d_fsdata;
433 }
434
435 static inline struct cftype *__d_cft(struct dentry *dentry)
436 {
437         return dentry->d_fsdata;
438 }
439
440 /*
441  * Call with manage_mutex held.  Writes path of cpuset into buf.
442  * Returns 0 on success, -errno on error.
443  */
444
445 static 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  *
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  *
493  * When we had only one cpuset mutex, we had to call this
494  * without holding it, to avoid deadlock when call_usermodehelper()
495  * allocated memory.  With two locks, we could now call this while
496  * holding manage_mutex, but we still don't, so as to minimize
497  * the time manage_mutex is held.
498  */
499
500 static void cpuset_release_agent(const char *pathbuf)
501 {
502         char *argv[3], *envp[3];
503         int i;
504
505         if (!pathbuf)
506                 return;
507
508         i = 0;
509         argv[i++] = "/sbin/cpuset_release_agent";
510         argv[i++] = (char *)pathbuf;
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
519         call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
520         kfree(pathbuf);
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
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
529  * cpuset_release_agent() with it later on, once manage_mutex is dropped.
530  * Call here with manage_mutex held.
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
536  * calling check_for_release() with manage_mutex held and the address
537  * of the pathbuf pointer, then dropping manage_mutex, then calling
538  * cpuset_release_agent() with pathbuf, as set by check_for_release().
539  */
540
541 static void check_for_release(struct cpuset *cs, char **ppathbuf)
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)
551                         kfree(buf);
552                 else
553                         *ppathbuf = buf;
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  *
568  * Call with callback_mutex held.
569  */
570
571 static 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
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].
588  *
589  * One way or another, we guarantee to return some non-empty subset
590  * of node_states[N_HIGH_MEMORY].
591  *
592  * Call with callback_mutex held.
593  */
594
595 static void guarantee_online_mems(const struct cpuset *cs, nodemask_t *pmask)
596 {
597         while (cs && !nodes_intersects(cs->mems_allowed,
598                                         node_states[N_HIGH_MEMORY]))
599                 cs = cs->parent;
600         if (cs)
601                 nodes_and(*pmask, cs->mems_allowed,
602                                         node_states[N_HIGH_MEMORY]);
603         else
604                 *pmask = node_states[N_HIGH_MEMORY];
605         BUG_ON(!nodes_intersects(*pmask, node_states[N_HIGH_MEMORY]));
606 }
607
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.
614  *
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  *
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
623  * current->mm->mmap_sem during call.
624  *
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.
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.
648  */
649
650 void cpuset_update_task_memory_state(void)
651 {
652         int my_cpusets_mem_gen;
653         struct task_struct *tsk = current;
654         struct cpuset *cs;
655
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         }
665
666         if (my_cpusets_mem_gen != tsk->cpuset_mems_generation) {
667                 mutex_lock(&callback_mutex);
668                 task_lock(tsk);
669                 cs = tsk->cpuset;       /* Maybe changed when task not locked */
670                 guarantee_online_mems(cs, &tsk->mems_allowed);
671                 tsk->cpuset_mems_generation = cs->mems_generation;
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;
680                 task_unlock(tsk);
681                 mutex_unlock(&callback_mutex);
682                 mpol_rebind_task(tsk, &tsk->mems_allowed);
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
691  * are only set if the other's are set.  Call holding manage_mutex.
692  */
693
694 static 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
709  * manage_mutex held.
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
722 static 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 */
733         if (cur == &top_cpuset)
734                 return 0;
735
736         par = cur->parent;
737
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
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  *
765  * Call with manage_mutex held.  May nest a call to the
766  * lock_cpu_hotplug()/unlock_cpu_hotplug() pair.
767  * Must not be called holding callback_mutex, because we must
768  * not call lock_cpu_hotplug() while holding callback_mutex.
769  */
770
771 static 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         }
788         if (!is_cpu_exclusive(cur)) {
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
812 /*
813  * Call with manage_mutex held.  May take callback_mutex during call.
814  */
815
816 static int update_cpumask(struct cpuset *cs, char *buf)
817 {
818         struct cpuset trialcs;
819         int retval, cpus_unchanged;
820
821         /* top_cpuset.cpus_allowed tracks cpu_online_map; it's read-only */
822         if (cs == &top_cpuset)
823                 return -EACCES;
824
825         trialcs = *cs;
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         }
839         cpus_and(trialcs.cpus_allowed, trialcs.cpus_allowed, cpu_online_map);
840         /* cpus_allowed cannot be empty for a cpuset with attached tasks. */
841         if (atomic_read(&cs->count) && cpus_empty(trialcs.cpus_allowed))
842                 return -ENOSPC;
843         retval = validate_change(cs, &trialcs);
844         if (retval < 0)
845                 return retval;
846         cpus_unchanged = cpus_equal(cs->cpus_allowed, trialcs.cpus_allowed);
847         mutex_lock(&callback_mutex);
848         cs->cpus_allowed = trialcs.cpus_allowed;
849         mutex_unlock(&callback_mutex);
850         if (is_cpu_exclusive(cs) && !cpus_unchanged)
851                 update_cpu_domains(cs);
852         return 0;
853 }
854
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
886 static 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
904 /*
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
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.
911  *
912  * Call with manage_mutex held.  May take callback_mutex during call.
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.
916  */
917
918 static int update_nodemask(struct cpuset *cs, char *buf)
919 {
920         struct cpuset trialcs;
921         nodemask_t oldmem;
922         struct task_struct *g, *p;
923         struct mm_struct **mmarray;
924         int i, n, ntasks;
925         int migrate;
926         int fudge;
927         int retval;
928
929         /*
930          * top_cpuset.mems_allowed tracks node_stats[N_HIGH_MEMORY];
931          * it's read-only
932          */
933         if (cs == &top_cpuset)
934                 return -EACCES;
935
936         trialcs = *cs;
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;
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                 }
957         }
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]);
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         }
969         /* mems_allowed cannot be empty for a cpuset with attached tasks. */
970         if (atomic_read(&cs->count) && nodes_empty(trialcs.mems_allowed)) {
971                 retval = -ENOSPC;
972                 goto done;
973         }
974         retval = validate_change(cs, &trialcs);
975         if (retval < 0)
976                 goto done;
977
978         mutex_lock(&callback_mutex);
979         cs->mems_allowed = trialcs.mems_allowed;
980         cs->mems_generation = cpuset_mems_generation++;
981         mutex_unlock(&callback_mutex);
982
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;
1002                 read_lock(&tasklist_lock);              /* block fork */
1003                 if (atomic_read(&cs->count) <= ntasks)
1004                         break;                          /* got enough */
1005                 read_unlock(&tasklist_lock);            /* try again */
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);
1027         read_unlock(&tasklist_lock);
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
1037          * cpuset manage_mutex, we know that no other rebind effort will
1038          * be contending for the global variable cpuset_being_rebound.
1039          * It's ok if we rebind the same mm twice; mpol_rebind_mm()
1040          * is idempotent.  Also migrate pages in each mm to new nodes.
1041          */
1042         migrate = is_memory_migrate(cs);
1043         for (i = 0; i < n; i++) {
1044                 struct mm_struct *mm = mmarray[i];
1045
1046                 mpol_rebind_mm(mm, &cs->mems_allowed);
1047                 if (migrate)
1048                         cpuset_migrate_mm(mm, &oldmem, &cs->mems_allowed);
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;
1056 done:
1057         return retval;
1058 }
1059
1060 /*
1061  * Call with manage_mutex held.
1062  */
1063
1064 static 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
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,
1076  *                              CS_NOTIFY_ON_RELEASE, CS_MEMORY_MIGRATE,
1077  *                              CS_SPREAD_PAGE, CS_SPREAD_SLAB)
1078  * cs:  the cpuset to update
1079  * buf: the buffer where we read the 0 or 1
1080  *
1081  * Call with manage_mutex held.
1082  */
1083
1084 static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs, char *buf)
1085 {
1086         int turning_on;
1087         struct cpuset trialcs;
1088         int err, cpu_exclusive_changed;
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);
1099         if (err < 0)
1100                 return err;
1101         cpu_exclusive_changed =
1102                 (is_cpu_exclusive(cs) != is_cpu_exclusive(&trialcs));
1103         mutex_lock(&callback_mutex);
1104         cs->flags = trialcs.flags;
1105         mutex_unlock(&callback_mutex);
1106
1107         if (cpu_exclusive_changed)
1108                 update_cpu_domains(cs);
1109         return 0;
1110 }
1111
1112 /*
1113  * Frequency meter - How fast is some event occurring?
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 */
1163 static 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 */
1172 static 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). */
1190 static 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. */
1199 static 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
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  *
1215  * Call holding manage_mutex.  May take callback_mutex and task_lock of
1216  * the task 'pid' during call.
1217  */
1218
1219 static int attach_task(struct cpuset *cs, char *pidbuf, char **ppathbuf)
1220 {
1221         pid_t pid;
1222         struct task_struct *tsk;
1223         struct cpuset *oldcs;
1224         cpumask_t cpus;
1225         nodemask_t from, to;
1226         struct mm_struct *mm;
1227         int retval;
1228
1229         if (sscanf(pidbuf, "%d", &pid) != 1)
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);
1238                 if (!tsk || tsk->flags & PF_EXITING) {
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
1256         retval = security_task_setscheduler(tsk, 0, NULL);
1257         if (retval) {
1258                 put_task_struct(tsk);
1259                 return retval;
1260         }
1261
1262         mutex_lock(&callback_mutex);
1263
1264         task_lock(tsk);
1265         oldcs = tsk->cpuset;
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) {
1272                 task_unlock(tsk);
1273                 mutex_unlock(&callback_mutex);
1274                 put_task_struct(tsk);
1275                 return -ESRCH;
1276         }
1277         atomic_inc(&cs->count);
1278         rcu_assign_pointer(tsk->cpuset, cs);
1279         task_unlock(tsk);
1280
1281         guarantee_online_cpus(cs, &cpus);
1282         set_cpus_allowed(tsk, cpus);
1283
1284         from = oldcs->mems_allowed;
1285         to = cs->mems_allowed;
1286
1287         mutex_unlock(&callback_mutex);
1288
1289         mm = get_task_mm(tsk);
1290         if (mm) {
1291                 mpol_rebind_mm(mm, &to);
1292                 if (is_memory_migrate(cs))
1293                         cpuset_migrate_mm(mm, &from, &to);
1294                 mmput(mm);
1295         }
1296
1297         put_task_struct(tsk);
1298         synchronize_rcu();
1299         if (atomic_dec_and_test(&oldcs->count))
1300                 check_for_release(oldcs, ppathbuf);
1301         return 0;
1302 }
1303
1304 /* The various types of files and directories in a cpuset file system */
1305
1306 typedef enum {
1307         FILE_ROOT,
1308         FILE_DIR,
1309         FILE_MEMORY_MIGRATE,
1310         FILE_CPULIST,
1311         FILE_MEMLIST,
1312         FILE_CPU_EXCLUSIVE,
1313         FILE_MEM_EXCLUSIVE,
1314         FILE_NOTIFY_ON_RELEASE,
1315         FILE_MEMORY_PRESSURE_ENABLED,
1316         FILE_MEMORY_PRESSURE,
1317         FILE_SPREAD_PAGE,
1318         FILE_SPREAD_SLAB,
1319         FILE_TASKLIST,
1320 } cpuset_filetype_t;
1321
1322 static ssize_t cpuset_common_file_write(struct file *file,
1323                                         const char __user *userbuf,
1324                                         size_t nbytes, loff_t *unused_ppos)
1325 {
1326         struct cpuset *cs = __d_cs(file->f_path.dentry->d_parent);
1327         struct cftype *cft = __d_cft(file->f_path.dentry);
1328         cpuset_filetype_t type = cft->private;
1329         char *buffer;
1330         char *pathbuf = NULL;
1331         int retval = 0;
1332
1333         /* Crude upper limit on largest legitimate cpulist user might write. */
1334         if (nbytes > 100 + 6 * max(NR_CPUS, MAX_NUMNODES))
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
1347         mutex_lock(&manage_mutex);
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;
1370         case FILE_MEMORY_MIGRATE:
1371                 retval = update_flag(CS_MEMORY_MIGRATE, cs, buffer);
1372                 break;
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;
1379         case FILE_SPREAD_PAGE:
1380                 retval = update_flag(CS_SPREAD_PAGE, cs, buffer);
1381                 cs->mems_generation = cpuset_mems_generation++;
1382                 break;
1383         case FILE_SPREAD_SLAB:
1384                 retval = update_flag(CS_SPREAD_SLAB, cs, buffer);
1385                 cs->mems_generation = cpuset_mems_generation++;
1386                 break;
1387         case FILE_TASKLIST:
1388                 retval = attach_task(cs, buffer, &pathbuf);
1389                 break;
1390         default:
1391                 retval = -EINVAL;
1392                 goto out2;
1393         }
1394
1395         if (retval == 0)
1396                 retval = nbytes;
1397 out2:
1398         mutex_unlock(&manage_mutex);
1399         cpuset_release_agent(pathbuf);
1400 out1:
1401         kfree(buffer);
1402         return retval;
1403 }
1404
1405 static 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;
1409         struct cftype *cft = __d_cft(file->f_path.dentry);
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
1434 static int cpuset_sprintf_cpulist(char *page, struct cpuset *cs)
1435 {
1436         cpumask_t mask;
1437
1438         mutex_lock(&callback_mutex);
1439         mask = cs->cpus_allowed;
1440         mutex_unlock(&callback_mutex);
1441
1442         return cpulist_scnprintf(page, PAGE_SIZE, mask);
1443 }
1444
1445 static int cpuset_sprintf_memlist(char *page, struct cpuset *cs)
1446 {
1447         nodemask_t mask;
1448
1449         mutex_lock(&callback_mutex);
1450         mask = cs->mems_allowed;
1451         mutex_unlock(&callback_mutex);
1452
1453         return nodelist_scnprintf(page, PAGE_SIZE, mask);
1454 }
1455
1456 static ssize_t cpuset_common_file_read(struct file *file, char __user *buf,
1457                                 size_t nbytes, loff_t *ppos)
1458 {
1459         struct cftype *cft = __d_cft(file->f_path.dentry);
1460         struct cpuset *cs = __d_cs(file->f_path.dentry->d_parent);
1461         cpuset_filetype_t type = cft->private;
1462         char *page;
1463         ssize_t retval = 0;
1464         char *s;
1465
1466         if (!(page = (char *)__get_free_page(GFP_KERNEL)))
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;
1487         case FILE_MEMORY_MIGRATE:
1488                 *s++ = is_memory_migrate(cs) ? '1' : '0';
1489                 break;
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;
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;
1502         default:
1503                 retval = -EINVAL;
1504                 goto out;
1505         }
1506         *s++ = '\n';
1507
1508         retval = simple_read_from_buffer(buf, nbytes, ppos, page, s - page);
1509 out:
1510         free_page((unsigned long)page);
1511         return retval;
1512 }
1513
1514 static ssize_t cpuset_file_read(struct file *file, char __user *buf, size_t nbytes,
1515                                                                 loff_t *ppos)
1516 {
1517         ssize_t retval = 0;
1518         struct cftype *cft = __d_cft(file->f_path.dentry);
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
1531 static 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
1540         cft = __d_cft(file->f_path.dentry);
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
1551 static int cpuset_file_release(struct inode *inode, struct file *file)
1552 {
1553         struct cftype *cft = __d_cft(file->f_path.dentry);
1554         if (cft->release)
1555                 return cft->release(inode, file);
1556         return 0;
1557 }
1558
1559 /*
1560  * cpuset_rename - Only allow simple rename of directories in place.
1561  */
1562 static 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
1574 static const struct file_operations cpuset_file_operations = {
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
1582 static const struct inode_operations cpuset_dir_inode_operations = {
1583         .lookup = simple_lookup,
1584         .mkdir = cpuset_mkdir,
1585         .rmdir = cpuset_rmdir,
1586         .rename = cpuset_rename,
1587 };
1588
1589 static 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) */
1607                 inc_nlink(inode);
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.
1620  *      cs:     the cpuset we create the directory for.
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
1627 static 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;
1640                 inc_nlink(parent->d_inode);
1641                 cs->dentry = dentry;
1642         }
1643         dput(dentry);
1644
1645         return error;
1646 }
1647
1648 static int cpuset_add_file(struct dentry *dir, const struct cftype *cft)
1649 {
1650         struct dentry *dentry;
1651         int error;
1652
1653         mutex_lock(&dir->d_inode->i_mutex);
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);
1662         mutex_unlock(&dir->d_inode->i_mutex);
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
1683 struct ctr_struct {
1684         char *buf;
1685         int bufsz;
1686 };
1687
1688 /*
1689  * Load into 'pidarray' up to 'npids' of the tasks using cpuset 'cs'.
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.
1693  */
1694 static int pid_array_load(pid_t *pidarray, int npids, struct cpuset *cs)
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) {
1703                         if (unlikely(n == npids))
1704                                 goto array_full;
1705                         pidarray[n++] = p->pid;
1706                 }
1707         } while_each_thread(g, p);
1708
1709 array_full:
1710         read_unlock(&tasklist_lock);
1711         return n;
1712 }
1713
1714 static 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  */
1724 static 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
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  *
1738  * Does not require any specific cpuset mutexes, and does not take any.
1739  */
1740 static int cpuset_tasks_open(struct inode *unused, struct file *file)
1741 {
1742         struct cpuset *cs = __d_cs(file->f_path.dentry->d_parent);
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
1780 err2:
1781         kfree(pidarray);
1782 err1:
1783         kfree(ctr);
1784 err0:
1785         return -ENOMEM;
1786 }
1787
1788 static 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
1793         return simple_read_from_buffer(buf, nbytes, ppos, ctr->buf, ctr->bufsz);
1794 }
1795
1796 static 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
1812 static 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
1820 static struct cftype cft_cpus = {
1821         .name = "cpus",
1822         .private = FILE_CPULIST,
1823 };
1824
1825 static struct cftype cft_mems = {
1826         .name = "mems",
1827         .private = FILE_MEMLIST,
1828 };
1829
1830 static struct cftype cft_cpu_exclusive = {
1831         .name = "cpu_exclusive",
1832         .private = FILE_CPU_EXCLUSIVE,
1833 };
1834
1835 static struct cftype cft_mem_exclusive = {
1836         .name = "mem_exclusive",
1837         .private = FILE_MEM_EXCLUSIVE,
1838 };
1839
1840 static struct cftype cft_notify_on_release = {
1841         .name = "notify_on_release",
1842         .private = FILE_NOTIFY_ON_RELEASE,
1843 };
1844
1845 static struct cftype cft_memory_migrate = {
1846         .name = "memory_migrate",
1847         .private = FILE_MEMORY_MIGRATE,
1848 };
1849
1850 static struct cftype cft_memory_pressure_enabled = {
1851         .name = "memory_pressure_enabled",
1852         .private = FILE_MEMORY_PRESSURE_ENABLED,
1853 };
1854
1855 static struct cftype cft_memory_pressure = {
1856         .name = "memory_pressure",
1857         .private = FILE_MEMORY_PRESSURE,
1858 };
1859
1860 static struct cftype cft_spread_page = {
1861         .name = "memory_spread_page",
1862         .private = FILE_SPREAD_PAGE,
1863 };
1864
1865 static struct cftype cft_spread_slab = {
1866         .name = "memory_spread_slab",
1867         .private = FILE_SPREAD_SLAB,
1868 };
1869
1870 static 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;
1884         if ((err = cpuset_add_file(cs_dentry, &cft_memory_migrate)) < 0)
1885                 return err;
1886         if ((err = cpuset_add_file(cs_dentry, &cft_memory_pressure)) < 0)
1887                 return err;
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;
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  *
1903  *      Must be called with the mutex on the parent inode held
1904  */
1905
1906 static 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
1915         mutex_lock(&manage_mutex);
1916         cpuset_update_task_memory_state();
1917         cs->flags = 0;
1918         if (notify_on_release(parent))
1919                 set_bit(CS_NOTIFY_ON_RELEASE, &cs->flags);
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);
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);
1929         cs->mems_generation = cpuset_mems_generation++;
1930         fmeter_init(&cs->fmeter);
1931
1932         cs->parent = parent;
1933
1934         mutex_lock(&callback_mutex);
1935         list_add(&cs->sibling, &cs->parent->children);
1936         number_of_cpusets++;
1937         mutex_unlock(&callback_mutex);
1938
1939         err = cpuset_create_dir(cs, name, mode);
1940         if (err < 0)
1941                 goto err;
1942
1943         /*
1944          * Release manage_mutex before cpuset_populate_dir() because it
1945          * will down() this new directory's i_mutex and if we race with
1946          * another mkdir, we might deadlock.
1947          */
1948         mutex_unlock(&manage_mutex);
1949
1950         err = cpuset_populate_dir(cs->dentry);
1951         /* If err < 0, we have a half-filled directory - oh well ;) */
1952         return 0;
1953 err:
1954         list_del(&cs->sibling);
1955         mutex_unlock(&manage_mutex);
1956         kfree(cs);
1957         return err;
1958 }
1959
1960 static int cpuset_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1961 {
1962         struct cpuset *c_parent = dentry->d_parent->d_fsdata;
1963
1964         /* the vfs holds inode->i_mutex already */
1965         return cpuset_create(c_parent, dentry->d_name.name, mode | S_IFDIR);
1966 }
1967
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
1979 static 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;
1984         char *pathbuf = NULL;
1985
1986         /* the vfs holds both inode->i_mutex already */
1987
1988         mutex_lock(&manage_mutex);
1989         cpuset_update_task_memory_state();
1990         if (atomic_read(&cs->count) > 0) {
1991                 mutex_unlock(&manage_mutex);
1992                 return -EBUSY;
1993         }
1994         if (!list_empty(&cs->children)) {
1995                 mutex_unlock(&manage_mutex);
1996                 return -EBUSY;
1997         }
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         }
2005         parent = cs->parent;
2006         mutex_lock(&callback_mutex);
2007         set_bit(CS_REMOVED, &cs->flags);
2008         list_del(&cs->sibling); /* delete my sibling from parent->children */
2009         spin_lock(&cs->dentry->d_lock);
2010         d = dget(cs->dentry);
2011         cs->dentry = NULL;
2012         spin_unlock(&d->d_lock);
2013         cpuset_d_remove_dir(d);
2014         dput(d);
2015         number_of_cpusets--;
2016         mutex_unlock(&callback_mutex);
2017         if (list_empty(&parent->children))
2018                 check_for_release(parent, &pathbuf);
2019         mutex_unlock(&manage_mutex);
2020         cpuset_release_agent(pathbuf);
2021         return 0;
2022 }
2023
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
2030 int __init cpuset_init_early(void)
2031 {
2032         struct task_struct *tsk = current;
2033
2034         tsk->cpuset = &top_cpuset;
2035         tsk->cpuset->mems_generation = cpuset_mems_generation++;
2036         return 0;
2037 }
2038
2039 /**
2040  * cpuset_init - initialize cpusets at system boot
2041  *
2042  * Description: Initialize top_cpuset and the cpuset internal file system,
2043  **/
2044
2045 int __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
2053         fmeter_init(&top_cpuset.fmeter);
2054         top_cpuset.mems_generation = cpuset_mems_generation++;
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;
2070         inc_nlink(root->d_inode);
2071         top_cpuset.dentry = root;
2072         root->d_inode->i_op = &cpuset_dir_inode_operations;
2073         number_of_cpusets = 1;
2074         err = cpuset_populate_dir(root);
2075         /* memory_pressure_enabled is in root cpuset only */
2076         if (err == 0)
2077                 err = cpuset_add_file(root, &cft_memory_pressure_enabled);
2078 out:
2079         return err;
2080 }
2081
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
2103 static 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
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.
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
2134 static 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;
2141         top_cpuset.mems_allowed = node_states[N_HIGH_MEMORY];
2142
2143         mutex_unlock(&callback_mutex);
2144         mutex_unlock(&manage_mutex);
2145 }
2146
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  *
2153  * This routine ensures that top_cpuset.cpus_allowed tracks
2154  * cpu_online_map on each CPU hotplug (cpuhp) event.
2155  */
2156
2157 static int cpuset_handle_cpuhp(struct notifier_block *nb,
2158                                 unsigned long phase, void *cpu)
2159 {
2160         if (phase == CPU_DYING || phase == CPU_DYING_FROZEN)
2161                 return NOTIFY_DONE;
2162
2163         common_cpu_mem_hotplug_unplug();
2164         return 0;
2165 }
2166
2167 #ifdef CONFIG_MEMORY_HOTPLUG
2168 /*
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].
2172  * See also the previous routine cpuset_handle_cpuhp().
2173  */
2174
2175 void cpuset_track_online_nodes(void)
2176 {
2177         common_cpu_mem_hotplug_unplug();
2178 }
2179 #endif
2180
2181 /**
2182  * cpuset_init_smp - initialize cpus_allowed
2183  *
2184  * Description: Finish top cpuset after cpu, node maps are initialized
2185  **/
2186
2187 void __init cpuset_init_smp(void)
2188 {
2189         top_cpuset.cpus_allowed = cpu_online_map;
2190         top_cpuset.mems_allowed = node_states[N_HIGH_MEMORY];
2191
2192         hotcpu_notifier(cpuset_handle_cpuhp, 0);
2193 }
2194
2195 /**
2196  * cpuset_fork - attach newly forked task to its parents cpuset.
2197  * @tsk: pointer to task_struct of forking parent process.
2198  *
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.
2211  **/
2212
2213 void cpuset_fork(struct task_struct *child)
2214 {
2215         task_lock(current);
2216         child->cpuset = current->cpuset;
2217         atomic_inc(&child->cpuset->count);
2218         task_unlock(current);
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  *
2227  * Note that cpusets marked notify_on_release force every task in
2228  * them to take the global manage_mutex mutex when exiting.
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
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
2236  * any other task to nuke the cpuset immediately, via cpuset_rmdir().
2237  *
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().
2241  *
2242  * the_top_cpuset_hack:
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 ;).
2274  **/
2275
2276 void cpuset_exit(struct task_struct *tsk)
2277 {
2278         struct cpuset *cs;
2279
2280         task_lock(current);
2281         cs = tsk->cpuset;
2282         tsk->cpuset = &top_cpuset;      /* the_top_cpuset_hack - see above */
2283         task_unlock(current);
2284
2285         if (notify_on_release(cs)) {
2286                 char *pathbuf = NULL;
2287
2288                 mutex_lock(&manage_mutex);
2289                 if (atomic_dec_and_test(&cs->count))
2290                         check_for_release(cs, &pathbuf);
2291                 mutex_unlock(&manage_mutex);
2292                 cpuset_release_agent(pathbuf);
2293         } else {
2294                 atomic_dec(&cs->count);
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
2308 cpumask_t cpuset_cpus_allowed(struct task_struct *tsk)
2309 {
2310         cpumask_t mask;
2311
2312         mutex_lock(&callback_mutex);
2313         task_lock(tsk);
2314         guarantee_online_cpus(tsk->cpuset, &mask);
2315         task_unlock(tsk);
2316         mutex_unlock(&callback_mutex);
2317
2318         return mask;
2319 }
2320
2321 void cpuset_init_current_mems_allowed(void)
2322 {
2323         current->mems_allowed = NODE_MASK_ALL;
2324 }
2325
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
2332  * subset of node_states[N_HIGH_MEMORY], even if this means going outside the
2333  * tasks cpuset.
2334  **/
2335
2336 nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
2337 {
2338         nodemask_t mask;
2339
2340         mutex_lock(&callback_mutex);
2341         task_lock(tsk);
2342         guarantee_online_mems(tsk->cpuset, &mask);
2343         task_unlock(tsk);
2344         mutex_unlock(&callback_mutex);
2345
2346         return mask;
2347 }
2348
2349 /**
2350  * cpuset_zonelist_valid_mems_allowed - check zonelist vs. curremt mems_allowed
2351  * @zl: the zonelist to be checked
2352  *
2353  * Are any of the nodes on zonelist zl allowed in current->mems_allowed?
2354  */
2355 int cpuset_zonelist_valid_mems_allowed(struct zonelist *zl)
2356 {
2357         int i;
2358
2359         for (i = 0; zl->zones[i]; i++) {
2360                 int nid = zone_to_nid(zl->zones[i]);
2361
2362                 if (node_isset(nid, current->mems_allowed))
2363                         return 1;
2364         }
2365         return 0;
2366 }
2367
2368 /*
2369  * nearest_exclusive_ancestor() - Returns the nearest mem_exclusive
2370  * ancestor to the specified cpuset.  Call holding callback_mutex.
2371  * If no ancestor is mem_exclusive (an unusual configuration), then
2372  * returns the root cpuset.
2373  */
2374 static 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
2381 /**
2382  * cpuset_zone_allowed_softwall - Can we allocate on zone z's memory node?
2383  * @z: is this zone on an allowed node?
2384  * @gfp_mask: memory allocation flags
2385  *
2386  * If we're in interrupt, yes, we can always allocate.  If
2387  * __GFP_THISNODE is set, yes, we can always allocate.  If zone
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.
2391  * If the task has been OOM killed and has access to memory reserves
2392  * as specified by the TIF_MEMDIE flag, yes.
2393  * Otherwise, no.
2394  *
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  *
2409  * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
2410  * and do not allow allocations outside the current tasks cpuset
2411  * unless the task has been OOM killed as is marked TIF_MEMDIE.
2412  * GFP_KERNEL allocations are not so marked, so can escape to the
2413  * nearest enclosing mem_exclusive ancestor cpuset.
2414  *
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.
2422  *
2423  * The first call here from mm/page_alloc:get_page_from_freelist()
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).
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:
2433  *      in_interrupt - any node ok (current task context irrelevant)
2434  *      GFP_ATOMIC   - any node ok
2435  *      TIF_MEMDIE   - any node ok
2436  *      GFP_KERNEL   - any node in enclosing mem_exclusive cpuset ok
2437  *      GFP_USER     - only nodes in current tasks mems allowed ok.
2438  *
2439  * Rule:
2440  *    Don't call cpuset_zone_allowed_softwall if you can't sleep, unless you
2441  *    pass in the __GFP_HARDWALL flag set in gfp_flag, which disables
2442  *    the code that might scan up ancestor cpusets and sleep.
2443  */
2444
2445 int __cpuset_zone_allowed_softwall(struct zone *z, gfp_t gfp_mask)
2446 {
2447         int node;                       /* node that zone z is on */
2448         const struct cpuset *cs;        /* current cpuset ancestors */
2449         int allowed;                    /* is allocation in zone z allowed? */
2450
2451         if (in_interrupt() || (gfp_mask & __GFP_THISNODE))
2452                 return 1;
2453         node = zone_to_nid(z);
2454         might_sleep_if(!(gfp_mask & __GFP_HARDWALL));
2455         if (node_isset(node, current->mems_allowed))
2456                 return 1;
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;
2463         if (gfp_mask & __GFP_HARDWALL)  /* If hardwall request, stop here */
2464                 return 0;
2465
2466         if (current->flags & PF_EXITING) /* Let dying task have memory */
2467                 return 1;
2468
2469         /* Not hardwall and node outside mems_allowed: scan up cpusets */
2470         mutex_lock(&callback_mutex);
2471
2472         task_lock(current);
2473         cs = nearest_exclusive_ancestor(current->cpuset);
2474         task_unlock(current);
2475
2476         allowed = node_isset(node, cs->mems_allowed);
2477         mutex_unlock(&callback_mutex);
2478         return allowed;
2479 }
2480
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
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.
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
2505 int __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;
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;
2520         return 0;
2521 }
2522
2523 /**
2524  * cpuset_lock - lock out any changes to cpuset structures
2525  *
2526  * The out of memory (oom) code needs to mutex_lock cpusets
2527  * from being changed while it scans the tasklist looking for a
2528  * task in an overlapping cpuset.  Expose callback_mutex via this
2529  * cpuset_lock() routine, so the oom code can lock it, before
2530  * locking the task list.  The tasklist_lock is a spinlock, so
2531  * must be taken inside callback_mutex.
2532  */
2533
2534 void cpuset_lock(void)
2535 {
2536         mutex_lock(&callback_mutex);
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
2545 void cpuset_unlock(void)
2546 {
2547         mutex_unlock(&callback_mutex);
2548 }
2549
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
2576 int 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 }
2586 EXPORT_SYMBOL_GPL(cpuset_mem_spread_node);
2587
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  *
2597  * Call while holding callback_mutex.
2598  **/
2599
2600 int cpuset_excl_nodes_overlap(const struct task_struct *p)
2601 {
2602         const struct cpuset *cs1, *cs2; /* my and p's cpuset ancestors */
2603         int overlap = 1;                /* do cpusets overlap? */
2604
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
2621         overlap = nodes_intersects(cs1->mems_allowed, cs2->mems_allowed);
2622 done:
2623         return overlap;
2624 }
2625
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
2632 int cpuset_memory_pressure_enabled __read_mostly;
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
2652 void __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
2662 /*
2663  * proc_cpuset_show()
2664  *  - Print tasks cpuset path into seq_file.
2665  *  - Used for /proc/<pid>/cpuset.
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,
2668  *    and we take manage_mutex, keeping attach_task() from changing it
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.
2672  */
2673 static int proc_cpuset_show(struct seq_file *m, void *v)
2674 {
2675         struct pid *pid;
2676         struct task_struct *tsk;
2677         char *buf;
2678         int retval;
2679
2680         retval = -ENOMEM;
2681         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
2682         if (!buf)
2683                 goto out;
2684
2685         retval = -ESRCH;
2686         pid = m->private;
2687         tsk = get_pid_task(pid, PIDTYPE_PID);
2688         if (!tsk)
2689                 goto out_free;
2690
2691         retval = -EINVAL;
2692         mutex_lock(&manage_mutex);
2693
2694         retval = cpuset_path(tsk->cpuset, buf, PAGE_SIZE);
2695         if (retval < 0)
2696                 goto out_unlock;
2697         seq_puts(m, buf);
2698         seq_putc(m, '\n');
2699 out_unlock:
2700         mutex_unlock(&manage_mutex);
2701         put_task_struct(tsk);
2702 out_free:
2703         kfree(buf);
2704 out:
2705         return retval;
2706 }
2707
2708 static int cpuset_open(struct inode *inode, struct file *file)
2709 {
2710         struct pid *pid = PROC_I(inode)->pid;
2711         return single_open(file, proc_cpuset_show, pid);
2712 }
2713
2714 const struct file_operations proc_cpuset_operations = {
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. */
2722 char *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 }