header cleaning: don't include smp_lock.h when not used
[safe/jmp/linux-2.6] / 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, 0);
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.  If none are online, walk up the cpuset hierarchy
585  * until we find one that does have some online mems.  If we get
586  * all the way to the top and still haven't found any online mems,
587  * return node_online_map.
588  *
589  * One way or another, we guarantee to return some non-empty subset
590  * of node_online_map.
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, node_online_map))
598                 cs = cs->parent;
599         if (cs)
600                 nodes_and(*pmask, cs->mems_allowed, node_online_map);
601         else
602                 *pmask = node_online_map;
603         BUG_ON(!nodes_intersects(*pmask, node_online_map));
604 }
605
606 /**
607  * cpuset_update_task_memory_state - update task memory placement
608  *
609  * If the current tasks cpusets mems_allowed changed behind our
610  * backs, update current->mems_allowed, mems_generation and task NUMA
611  * mempolicy to the new value.
612  *
613  * Task mempolicy is updated by rebinding it relative to the
614  * current->cpuset if a task has its memory placement changed.
615  * Do not call this routine if in_interrupt().
616  *
617  * Call without callback_mutex or task_lock() held.  May be
618  * called with or without manage_mutex held.  Thanks in part to
619  * 'the_top_cpuset_hack', the tasks cpuset pointer will never
620  * be NULL.  This routine also might acquire callback_mutex and
621  * current->mm->mmap_sem during call.
622  *
623  * Reading current->cpuset->mems_generation doesn't need task_lock
624  * to guard the current->cpuset derefence, because it is guarded
625  * from concurrent freeing of current->cpuset by attach_task(),
626  * using RCU.
627  *
628  * The rcu_dereference() is technically probably not needed,
629  * as I don't actually mind if I see a new cpuset pointer but
630  * an old value of mems_generation.  However this really only
631  * matters on alpha systems using cpusets heavily.  If I dropped
632  * that rcu_dereference(), it would save them a memory barrier.
633  * For all other arch's, rcu_dereference is a no-op anyway, and for
634  * alpha systems not using cpusets, another planned optimization,
635  * avoiding the rcu critical section for tasks in the root cpuset
636  * which is statically allocated, so can't vanish, will make this
637  * irrelevant.  Better to use RCU as intended, than to engage in
638  * some cute trick to save a memory barrier that is impossible to
639  * test, for alpha systems using cpusets heavily, which might not
640  * even exist.
641  *
642  * This routine is needed to update the per-task mems_allowed data,
643  * within the tasks context, when it is trying to allocate memory
644  * (in various mm/mempolicy.c routines) and notices that some other
645  * task has been modifying its cpuset.
646  */
647
648 void cpuset_update_task_memory_state(void)
649 {
650         int my_cpusets_mem_gen;
651         struct task_struct *tsk = current;
652         struct cpuset *cs;
653
654         if (tsk->cpuset == &top_cpuset) {
655                 /* Don't need rcu for top_cpuset.  It's never freed. */
656                 my_cpusets_mem_gen = top_cpuset.mems_generation;
657         } else {
658                 rcu_read_lock();
659                 cs = rcu_dereference(tsk->cpuset);
660                 my_cpusets_mem_gen = cs->mems_generation;
661                 rcu_read_unlock();
662         }
663
664         if (my_cpusets_mem_gen != tsk->cpuset_mems_generation) {
665                 mutex_lock(&callback_mutex);
666                 task_lock(tsk);
667                 cs = tsk->cpuset;       /* Maybe changed when task not locked */
668                 guarantee_online_mems(cs, &tsk->mems_allowed);
669                 tsk->cpuset_mems_generation = cs->mems_generation;
670                 if (is_spread_page(cs))
671                         tsk->flags |= PF_SPREAD_PAGE;
672                 else
673                         tsk->flags &= ~PF_SPREAD_PAGE;
674                 if (is_spread_slab(cs))
675                         tsk->flags |= PF_SPREAD_SLAB;
676                 else
677                         tsk->flags &= ~PF_SPREAD_SLAB;
678                 task_unlock(tsk);
679                 mutex_unlock(&callback_mutex);
680                 mpol_rebind_task(tsk, &tsk->mems_allowed);
681         }
682 }
683
684 /*
685  * is_cpuset_subset(p, q) - Is cpuset p a subset of cpuset q?
686  *
687  * One cpuset is a subset of another if all its allowed CPUs and
688  * Memory Nodes are a subset of the other, and its exclusive flags
689  * are only set if the other's are set.  Call holding manage_mutex.
690  */
691
692 static int is_cpuset_subset(const struct cpuset *p, const struct cpuset *q)
693 {
694         return  cpus_subset(p->cpus_allowed, q->cpus_allowed) &&
695                 nodes_subset(p->mems_allowed, q->mems_allowed) &&
696                 is_cpu_exclusive(p) <= is_cpu_exclusive(q) &&
697                 is_mem_exclusive(p) <= is_mem_exclusive(q);
698 }
699
700 /*
701  * validate_change() - Used to validate that any proposed cpuset change
702  *                     follows the structural rules for cpusets.
703  *
704  * If we replaced the flag and mask values of the current cpuset
705  * (cur) with those values in the trial cpuset (trial), would
706  * our various subset and exclusive rules still be valid?  Presumes
707  * manage_mutex held.
708  *
709  * 'cur' is the address of an actual, in-use cpuset.  Operations
710  * such as list traversal that depend on the actual address of the
711  * cpuset in the list must use cur below, not trial.
712  *
713  * 'trial' is the address of bulk structure copy of cur, with
714  * perhaps one or more of the fields cpus_allowed, mems_allowed,
715  * or flags changed to new, trial values.
716  *
717  * Return 0 if valid, -errno if not.
718  */
719
720 static int validate_change(const struct cpuset *cur, const struct cpuset *trial)
721 {
722         struct cpuset *c, *par;
723
724         /* Each of our child cpusets must be a subset of us */
725         list_for_each_entry(c, &cur->children, sibling) {
726                 if (!is_cpuset_subset(c, trial))
727                         return -EBUSY;
728         }
729
730         /* Remaining checks don't apply to root cpuset */
731         if (cur == &top_cpuset)
732                 return 0;
733
734         par = cur->parent;
735
736         /* We must be a subset of our parent cpuset */
737         if (!is_cpuset_subset(trial, par))
738                 return -EACCES;
739
740         /* If either I or some sibling (!= me) is exclusive, we can't overlap */
741         list_for_each_entry(c, &par->children, sibling) {
742                 if ((is_cpu_exclusive(trial) || is_cpu_exclusive(c)) &&
743                     c != cur &&
744                     cpus_intersects(trial->cpus_allowed, c->cpus_allowed))
745                         return -EINVAL;
746                 if ((is_mem_exclusive(trial) || is_mem_exclusive(c)) &&
747                     c != cur &&
748                     nodes_intersects(trial->mems_allowed, c->mems_allowed))
749                         return -EINVAL;
750         }
751
752         return 0;
753 }
754
755 /*
756  * For a given cpuset cur, partition the system as follows
757  * a. All cpus in the parent cpuset's cpus_allowed that are not part of any
758  *    exclusive child cpusets
759  * b. All cpus in the current cpuset's cpus_allowed that are not part of any
760  *    exclusive child cpusets
761  * Build these two partitions by calling partition_sched_domains
762  *
763  * Call with manage_mutex held.  May nest a call to the
764  * lock_cpu_hotplug()/unlock_cpu_hotplug() pair.
765  * Must not be called holding callback_mutex, because we must
766  * not call lock_cpu_hotplug() while holding callback_mutex.
767  */
768
769 static void update_cpu_domains(struct cpuset *cur)
770 {
771         struct cpuset *c, *par = cur->parent;
772         cpumask_t pspan, cspan;
773
774         if (par == NULL || cpus_empty(cur->cpus_allowed))
775                 return;
776
777         /*
778          * Get all cpus from parent's cpus_allowed not part of exclusive
779          * children
780          */
781         pspan = par->cpus_allowed;
782         list_for_each_entry(c, &par->children, sibling) {
783                 if (is_cpu_exclusive(c))
784                         cpus_andnot(pspan, pspan, c->cpus_allowed);
785         }
786         if (!is_cpu_exclusive(cur)) {
787                 cpus_or(pspan, pspan, cur->cpus_allowed);
788                 if (cpus_equal(pspan, cur->cpus_allowed))
789                         return;
790                 cspan = CPU_MASK_NONE;
791         } else {
792                 if (cpus_empty(pspan))
793                         return;
794                 cspan = cur->cpus_allowed;
795                 /*
796                  * Get all cpus from current cpuset's cpus_allowed not part
797                  * of exclusive children
798                  */
799                 list_for_each_entry(c, &cur->children, sibling) {
800                         if (is_cpu_exclusive(c))
801                                 cpus_andnot(cspan, cspan, c->cpus_allowed);
802                 }
803         }
804
805         lock_cpu_hotplug();
806         partition_sched_domains(&pspan, &cspan);
807         unlock_cpu_hotplug();
808 }
809
810 /*
811  * Call with manage_mutex held.  May take callback_mutex during call.
812  */
813
814 static int update_cpumask(struct cpuset *cs, char *buf)
815 {
816         struct cpuset trialcs;
817         int retval, cpus_unchanged;
818
819         /* top_cpuset.cpus_allowed tracks cpu_online_map; it's read-only */
820         if (cs == &top_cpuset)
821                 return -EACCES;
822
823         trialcs = *cs;
824         retval = cpulist_parse(buf, trialcs.cpus_allowed);
825         if (retval < 0)
826                 return retval;
827         cpus_and(trialcs.cpus_allowed, trialcs.cpus_allowed, cpu_online_map);
828         if (cpus_empty(trialcs.cpus_allowed))
829                 return -ENOSPC;
830         retval = validate_change(cs, &trialcs);
831         if (retval < 0)
832                 return retval;
833         cpus_unchanged = cpus_equal(cs->cpus_allowed, trialcs.cpus_allowed);
834         mutex_lock(&callback_mutex);
835         cs->cpus_allowed = trialcs.cpus_allowed;
836         mutex_unlock(&callback_mutex);
837         if (is_cpu_exclusive(cs) && !cpus_unchanged)
838                 update_cpu_domains(cs);
839         return 0;
840 }
841
842 /*
843  * cpuset_migrate_mm
844  *
845  *    Migrate memory region from one set of nodes to another.
846  *
847  *    Temporarilly set tasks mems_allowed to target nodes of migration,
848  *    so that the migration code can allocate pages on these nodes.
849  *
850  *    Call holding manage_mutex, so our current->cpuset won't change
851  *    during this call, as manage_mutex holds off any attach_task()
852  *    calls.  Therefore we don't need to take task_lock around the
853  *    call to guarantee_online_mems(), as we know no one is changing
854  *    our tasks cpuset.
855  *
856  *    Hold callback_mutex around the two modifications of our tasks
857  *    mems_allowed to synchronize with cpuset_mems_allowed().
858  *
859  *    While the mm_struct we are migrating is typically from some
860  *    other task, the task_struct mems_allowed that we are hacking
861  *    is for our current task, which must allocate new pages for that
862  *    migrating memory region.
863  *
864  *    We call cpuset_update_task_memory_state() before hacking
865  *    our tasks mems_allowed, so that we are assured of being in
866  *    sync with our tasks cpuset, and in particular, callbacks to
867  *    cpuset_update_task_memory_state() from nested page allocations
868  *    won't see any mismatch of our cpuset and task mems_generation
869  *    values, so won't overwrite our hacked tasks mems_allowed
870  *    nodemask.
871  */
872
873 static void cpuset_migrate_mm(struct mm_struct *mm, const nodemask_t *from,
874                                                         const nodemask_t *to)
875 {
876         struct task_struct *tsk = current;
877
878         cpuset_update_task_memory_state();
879
880         mutex_lock(&callback_mutex);
881         tsk->mems_allowed = *to;
882         mutex_unlock(&callback_mutex);
883
884         do_migrate_pages(mm, from, to, MPOL_MF_MOVE_ALL);
885
886         mutex_lock(&callback_mutex);
887         guarantee_online_mems(tsk->cpuset, &tsk->mems_allowed);
888         mutex_unlock(&callback_mutex);
889 }
890
891 /*
892  * Handle user request to change the 'mems' memory placement
893  * of a cpuset.  Needs to validate the request, update the
894  * cpusets mems_allowed and mems_generation, and for each
895  * task in the cpuset, rebind any vma mempolicies and if
896  * the cpuset is marked 'memory_migrate', migrate the tasks
897  * pages to the new memory.
898  *
899  * Call with manage_mutex held.  May take callback_mutex during call.
900  * Will take tasklist_lock, scan tasklist for tasks in cpuset cs,
901  * lock each such tasks mm->mmap_sem, scan its vma's and rebind
902  * their mempolicies to the cpusets new mems_allowed.
903  */
904
905 static int update_nodemask(struct cpuset *cs, char *buf)
906 {
907         struct cpuset trialcs;
908         nodemask_t oldmem;
909         struct task_struct *g, *p;
910         struct mm_struct **mmarray;
911         int i, n, ntasks;
912         int migrate;
913         int fudge;
914         int retval;
915
916         /* top_cpuset.mems_allowed tracks node_online_map; it's read-only */
917         if (cs == &top_cpuset)
918                 return -EACCES;
919
920         trialcs = *cs;
921         retval = nodelist_parse(buf, trialcs.mems_allowed);
922         if (retval < 0)
923                 goto done;
924         nodes_and(trialcs.mems_allowed, trialcs.mems_allowed, node_online_map);
925         oldmem = cs->mems_allowed;
926         if (nodes_equal(oldmem, trialcs.mems_allowed)) {
927                 retval = 0;             /* Too easy - nothing to do */
928                 goto done;
929         }
930         if (nodes_empty(trialcs.mems_allowed)) {
931                 retval = -ENOSPC;
932                 goto done;
933         }
934         retval = validate_change(cs, &trialcs);
935         if (retval < 0)
936                 goto done;
937
938         mutex_lock(&callback_mutex);
939         cs->mems_allowed = trialcs.mems_allowed;
940         cs->mems_generation = cpuset_mems_generation++;
941         mutex_unlock(&callback_mutex);
942
943         set_cpuset_being_rebound(cs);           /* causes mpol_copy() rebind */
944
945         fudge = 10;                             /* spare mmarray[] slots */
946         fudge += cpus_weight(cs->cpus_allowed); /* imagine one fork-bomb/cpu */
947         retval = -ENOMEM;
948
949         /*
950          * Allocate mmarray[] to hold mm reference for each task
951          * in cpuset cs.  Can't kmalloc GFP_KERNEL while holding
952          * tasklist_lock.  We could use GFP_ATOMIC, but with a
953          * few more lines of code, we can retry until we get a big
954          * enough mmarray[] w/o using GFP_ATOMIC.
955          */
956         while (1) {
957                 ntasks = atomic_read(&cs->count);       /* guess */
958                 ntasks += fudge;
959                 mmarray = kmalloc(ntasks * sizeof(*mmarray), GFP_KERNEL);
960                 if (!mmarray)
961                         goto done;
962                 write_lock_irq(&tasklist_lock);         /* block fork */
963                 if (atomic_read(&cs->count) <= ntasks)
964                         break;                          /* got enough */
965                 write_unlock_irq(&tasklist_lock);       /* try again */
966                 kfree(mmarray);
967         }
968
969         n = 0;
970
971         /* Load up mmarray[] with mm reference for each task in cpuset. */
972         do_each_thread(g, p) {
973                 struct mm_struct *mm;
974
975                 if (n >= ntasks) {
976                         printk(KERN_WARNING
977                                 "Cpuset mempolicy rebind incomplete.\n");
978                         continue;
979                 }
980                 if (p->cpuset != cs)
981                         continue;
982                 mm = get_task_mm(p);
983                 if (!mm)
984                         continue;
985                 mmarray[n++] = mm;
986         } while_each_thread(g, p);
987         write_unlock_irq(&tasklist_lock);
988
989         /*
990          * Now that we've dropped the tasklist spinlock, we can
991          * rebind the vma mempolicies of each mm in mmarray[] to their
992          * new cpuset, and release that mm.  The mpol_rebind_mm()
993          * call takes mmap_sem, which we couldn't take while holding
994          * tasklist_lock.  Forks can happen again now - the mpol_copy()
995          * cpuset_being_rebound check will catch such forks, and rebind
996          * their vma mempolicies too.  Because we still hold the global
997          * cpuset manage_mutex, we know that no other rebind effort will
998          * be contending for the global variable cpuset_being_rebound.
999          * It's ok if we rebind the same mm twice; mpol_rebind_mm()
1000          * is idempotent.  Also migrate pages in each mm to new nodes.
1001          */
1002         migrate = is_memory_migrate(cs);
1003         for (i = 0; i < n; i++) {
1004                 struct mm_struct *mm = mmarray[i];
1005
1006                 mpol_rebind_mm(mm, &cs->mems_allowed);
1007                 if (migrate)
1008                         cpuset_migrate_mm(mm, &oldmem, &cs->mems_allowed);
1009                 mmput(mm);
1010         }
1011
1012         /* We're done rebinding vma's to this cpusets new mems_allowed. */
1013         kfree(mmarray);
1014         set_cpuset_being_rebound(NULL);
1015         retval = 0;
1016 done:
1017         return retval;
1018 }
1019
1020 /*
1021  * Call with manage_mutex held.
1022  */
1023
1024 static int update_memory_pressure_enabled(struct cpuset *cs, char *buf)
1025 {
1026         if (simple_strtoul(buf, NULL, 10) != 0)
1027                 cpuset_memory_pressure_enabled = 1;
1028         else
1029                 cpuset_memory_pressure_enabled = 0;
1030         return 0;
1031 }
1032
1033 /*
1034  * update_flag - read a 0 or a 1 in a file and update associated flag
1035  * bit: the bit to update (CS_CPU_EXCLUSIVE, CS_MEM_EXCLUSIVE,
1036  *                              CS_NOTIFY_ON_RELEASE, CS_MEMORY_MIGRATE,
1037  *                              CS_SPREAD_PAGE, CS_SPREAD_SLAB)
1038  * cs:  the cpuset to update
1039  * buf: the buffer where we read the 0 or 1
1040  *
1041  * Call with manage_mutex held.
1042  */
1043
1044 static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs, char *buf)
1045 {
1046         int turning_on;
1047         struct cpuset trialcs;
1048         int err, cpu_exclusive_changed;
1049
1050         turning_on = (simple_strtoul(buf, NULL, 10) != 0);
1051
1052         trialcs = *cs;
1053         if (turning_on)
1054                 set_bit(bit, &trialcs.flags);
1055         else
1056                 clear_bit(bit, &trialcs.flags);
1057
1058         err = validate_change(cs, &trialcs);
1059         if (err < 0)
1060                 return err;
1061         cpu_exclusive_changed =
1062                 (is_cpu_exclusive(cs) != is_cpu_exclusive(&trialcs));
1063         mutex_lock(&callback_mutex);
1064         cs->flags = trialcs.flags;
1065         mutex_unlock(&callback_mutex);
1066
1067         if (cpu_exclusive_changed)
1068                 update_cpu_domains(cs);
1069         return 0;
1070 }
1071
1072 /*
1073  * Frequency meter - How fast is some event occurring?
1074  *
1075  * These routines manage a digitally filtered, constant time based,
1076  * event frequency meter.  There are four routines:
1077  *   fmeter_init() - initialize a frequency meter.
1078  *   fmeter_markevent() - called each time the event happens.
1079  *   fmeter_getrate() - returns the recent rate of such events.
1080  *   fmeter_update() - internal routine used to update fmeter.
1081  *
1082  * A common data structure is passed to each of these routines,
1083  * which is used to keep track of the state required to manage the
1084  * frequency meter and its digital filter.
1085  *
1086  * The filter works on the number of events marked per unit time.
1087  * The filter is single-pole low-pass recursive (IIR).  The time unit
1088  * is 1 second.  Arithmetic is done using 32-bit integers scaled to
1089  * simulate 3 decimal digits of precision (multiplied by 1000).
1090  *
1091  * With an FM_COEF of 933, and a time base of 1 second, the filter
1092  * has a half-life of 10 seconds, meaning that if the events quit
1093  * happening, then the rate returned from the fmeter_getrate()
1094  * will be cut in half each 10 seconds, until it converges to zero.
1095  *
1096  * It is not worth doing a real infinitely recursive filter.  If more
1097  * than FM_MAXTICKS ticks have elapsed since the last filter event,
1098  * just compute FM_MAXTICKS ticks worth, by which point the level
1099  * will be stable.
1100  *
1101  * Limit the count of unprocessed events to FM_MAXCNT, so as to avoid
1102  * arithmetic overflow in the fmeter_update() routine.
1103  *
1104  * Given the simple 32 bit integer arithmetic used, this meter works
1105  * best for reporting rates between one per millisecond (msec) and
1106  * one per 32 (approx) seconds.  At constant rates faster than one
1107  * per msec it maxes out at values just under 1,000,000.  At constant
1108  * rates between one per msec, and one per second it will stabilize
1109  * to a value N*1000, where N is the rate of events per second.
1110  * At constant rates between one per second and one per 32 seconds,
1111  * it will be choppy, moving up on the seconds that have an event,
1112  * and then decaying until the next event.  At rates slower than
1113  * about one in 32 seconds, it decays all the way back to zero between
1114  * each event.
1115  */
1116
1117 #define FM_COEF 933             /* coefficient for half-life of 10 secs */
1118 #define FM_MAXTICKS ((time_t)99) /* useless computing more ticks than this */
1119 #define FM_MAXCNT 1000000       /* limit cnt to avoid overflow */
1120 #define FM_SCALE 1000           /* faux fixed point scale */
1121
1122 /* Initialize a frequency meter */
1123 static void fmeter_init(struct fmeter *fmp)
1124 {
1125         fmp->cnt = 0;
1126         fmp->val = 0;
1127         fmp->time = 0;
1128         spin_lock_init(&fmp->lock);
1129 }
1130
1131 /* Internal meter update - process cnt events and update value */
1132 static void fmeter_update(struct fmeter *fmp)
1133 {
1134         time_t now = get_seconds();
1135         time_t ticks = now - fmp->time;
1136
1137         if (ticks == 0)
1138                 return;
1139
1140         ticks = min(FM_MAXTICKS, ticks);
1141         while (ticks-- > 0)
1142                 fmp->val = (FM_COEF * fmp->val) / FM_SCALE;
1143         fmp->time = now;
1144
1145         fmp->val += ((FM_SCALE - FM_COEF) * fmp->cnt) / FM_SCALE;
1146         fmp->cnt = 0;
1147 }
1148
1149 /* Process any previous ticks, then bump cnt by one (times scale). */
1150 static void fmeter_markevent(struct fmeter *fmp)
1151 {
1152         spin_lock(&fmp->lock);
1153         fmeter_update(fmp);
1154         fmp->cnt = min(FM_MAXCNT, fmp->cnt + FM_SCALE);
1155         spin_unlock(&fmp->lock);
1156 }
1157
1158 /* Process any previous ticks, then return current value. */
1159 static int fmeter_getrate(struct fmeter *fmp)
1160 {
1161         int val;
1162
1163         spin_lock(&fmp->lock);
1164         fmeter_update(fmp);
1165         val = fmp->val;
1166         spin_unlock(&fmp->lock);
1167         return val;
1168 }
1169
1170 /*
1171  * Attack task specified by pid in 'pidbuf' to cpuset 'cs', possibly
1172  * writing the path of the old cpuset in 'ppathbuf' if it needs to be
1173  * notified on release.
1174  *
1175  * Call holding manage_mutex.  May take callback_mutex and task_lock of
1176  * the task 'pid' during call.
1177  */
1178
1179 static int attach_task(struct cpuset *cs, char *pidbuf, char **ppathbuf)
1180 {
1181         pid_t pid;
1182         struct task_struct *tsk;
1183         struct cpuset *oldcs;
1184         cpumask_t cpus;
1185         nodemask_t from, to;
1186         struct mm_struct *mm;
1187         int retval;
1188
1189         if (sscanf(pidbuf, "%d", &pid) != 1)
1190                 return -EIO;
1191         if (cpus_empty(cs->cpus_allowed) || nodes_empty(cs->mems_allowed))
1192                 return -ENOSPC;
1193
1194         if (pid) {
1195                 read_lock(&tasklist_lock);
1196
1197                 tsk = find_task_by_pid(pid);
1198                 if (!tsk || tsk->flags & PF_EXITING) {
1199                         read_unlock(&tasklist_lock);
1200                         return -ESRCH;
1201                 }
1202
1203                 get_task_struct(tsk);
1204                 read_unlock(&tasklist_lock);
1205
1206                 if ((current->euid) && (current->euid != tsk->uid)
1207                     && (current->euid != tsk->suid)) {
1208                         put_task_struct(tsk);
1209                         return -EACCES;
1210                 }
1211         } else {
1212                 tsk = current;
1213                 get_task_struct(tsk);
1214         }
1215
1216         retval = security_task_setscheduler(tsk, 0, NULL);
1217         if (retval) {
1218                 put_task_struct(tsk);
1219                 return retval;
1220         }
1221
1222         mutex_lock(&callback_mutex);
1223
1224         task_lock(tsk);
1225         oldcs = tsk->cpuset;
1226         /*
1227          * After getting 'oldcs' cpuset ptr, be sure still not exiting.
1228          * If 'oldcs' might be the top_cpuset due to the_top_cpuset_hack
1229          * then fail this attach_task(), to avoid breaking top_cpuset.count.
1230          */
1231         if (tsk->flags & PF_EXITING) {
1232                 task_unlock(tsk);
1233                 mutex_unlock(&callback_mutex);
1234                 put_task_struct(tsk);
1235                 return -ESRCH;
1236         }
1237         atomic_inc(&cs->count);
1238         rcu_assign_pointer(tsk->cpuset, cs);
1239         task_unlock(tsk);
1240
1241         guarantee_online_cpus(cs, &cpus);
1242         set_cpus_allowed(tsk, cpus);
1243
1244         from = oldcs->mems_allowed;
1245         to = cs->mems_allowed;
1246
1247         mutex_unlock(&callback_mutex);
1248
1249         mm = get_task_mm(tsk);
1250         if (mm) {
1251                 mpol_rebind_mm(mm, &to);
1252                 if (is_memory_migrate(cs))
1253                         cpuset_migrate_mm(mm, &from, &to);
1254                 mmput(mm);
1255         }
1256
1257         put_task_struct(tsk);
1258         synchronize_rcu();
1259         if (atomic_dec_and_test(&oldcs->count))
1260                 check_for_release(oldcs, ppathbuf);
1261         return 0;
1262 }
1263
1264 /* The various types of files and directories in a cpuset file system */
1265
1266 typedef enum {
1267         FILE_ROOT,
1268         FILE_DIR,
1269         FILE_MEMORY_MIGRATE,
1270         FILE_CPULIST,
1271         FILE_MEMLIST,
1272         FILE_CPU_EXCLUSIVE,
1273         FILE_MEM_EXCLUSIVE,
1274         FILE_NOTIFY_ON_RELEASE,
1275         FILE_MEMORY_PRESSURE_ENABLED,
1276         FILE_MEMORY_PRESSURE,
1277         FILE_SPREAD_PAGE,
1278         FILE_SPREAD_SLAB,
1279         FILE_TASKLIST,
1280 } cpuset_filetype_t;
1281
1282 static ssize_t cpuset_common_file_write(struct file *file,
1283                                         const char __user *userbuf,
1284                                         size_t nbytes, loff_t *unused_ppos)
1285 {
1286         struct cpuset *cs = __d_cs(file->f_path.dentry->d_parent);
1287         struct cftype *cft = __d_cft(file->f_path.dentry);
1288         cpuset_filetype_t type = cft->private;
1289         char *buffer;
1290         char *pathbuf = NULL;
1291         int retval = 0;
1292
1293         /* Crude upper limit on largest legitimate cpulist user might write. */
1294         if (nbytes > 100 + 6 * max(NR_CPUS, MAX_NUMNODES))
1295                 return -E2BIG;
1296
1297         /* +1 for nul-terminator */
1298         if ((buffer = kmalloc(nbytes + 1, GFP_KERNEL)) == 0)
1299                 return -ENOMEM;
1300
1301         if (copy_from_user(buffer, userbuf, nbytes)) {
1302                 retval = -EFAULT;
1303                 goto out1;
1304         }
1305         buffer[nbytes] = 0;     /* nul-terminate */
1306
1307         mutex_lock(&manage_mutex);
1308
1309         if (is_removed(cs)) {
1310                 retval = -ENODEV;
1311                 goto out2;
1312         }
1313
1314         switch (type) {
1315         case FILE_CPULIST:
1316                 retval = update_cpumask(cs, buffer);
1317                 break;
1318         case FILE_MEMLIST:
1319                 retval = update_nodemask(cs, buffer);
1320                 break;
1321         case FILE_CPU_EXCLUSIVE:
1322                 retval = update_flag(CS_CPU_EXCLUSIVE, cs, buffer);
1323                 break;
1324         case FILE_MEM_EXCLUSIVE:
1325                 retval = update_flag(CS_MEM_EXCLUSIVE, cs, buffer);
1326                 break;
1327         case FILE_NOTIFY_ON_RELEASE:
1328                 retval = update_flag(CS_NOTIFY_ON_RELEASE, cs, buffer);
1329                 break;
1330         case FILE_MEMORY_MIGRATE:
1331                 retval = update_flag(CS_MEMORY_MIGRATE, cs, buffer);
1332                 break;
1333         case FILE_MEMORY_PRESSURE_ENABLED:
1334                 retval = update_memory_pressure_enabled(cs, buffer);
1335                 break;
1336         case FILE_MEMORY_PRESSURE:
1337                 retval = -EACCES;
1338                 break;
1339         case FILE_SPREAD_PAGE:
1340                 retval = update_flag(CS_SPREAD_PAGE, cs, buffer);
1341                 cs->mems_generation = cpuset_mems_generation++;
1342                 break;
1343         case FILE_SPREAD_SLAB:
1344                 retval = update_flag(CS_SPREAD_SLAB, cs, buffer);
1345                 cs->mems_generation = cpuset_mems_generation++;
1346                 break;
1347         case FILE_TASKLIST:
1348                 retval = attach_task(cs, buffer, &pathbuf);
1349                 break;
1350         default:
1351                 retval = -EINVAL;
1352                 goto out2;
1353         }
1354
1355         if (retval == 0)
1356                 retval = nbytes;
1357 out2:
1358         mutex_unlock(&manage_mutex);
1359         cpuset_release_agent(pathbuf);
1360 out1:
1361         kfree(buffer);
1362         return retval;
1363 }
1364
1365 static ssize_t cpuset_file_write(struct file *file, const char __user *buf,
1366                                                 size_t nbytes, loff_t *ppos)
1367 {
1368         ssize_t retval = 0;
1369         struct cftype *cft = __d_cft(file->f_path.dentry);
1370         if (!cft)
1371                 return -ENODEV;
1372
1373         /* special function ? */
1374         if (cft->write)
1375                 retval = cft->write(file, buf, nbytes, ppos);
1376         else
1377                 retval = cpuset_common_file_write(file, buf, nbytes, ppos);
1378
1379         return retval;
1380 }
1381
1382 /*
1383  * These ascii lists should be read in a single call, by using a user
1384  * buffer large enough to hold the entire map.  If read in smaller
1385  * chunks, there is no guarantee of atomicity.  Since the display format
1386  * used, list of ranges of sequential numbers, is variable length,
1387  * and since these maps can change value dynamically, one could read
1388  * gibberish by doing partial reads while a list was changing.
1389  * A single large read to a buffer that crosses a page boundary is
1390  * ok, because the result being copied to user land is not recomputed
1391  * across a page fault.
1392  */
1393
1394 static int cpuset_sprintf_cpulist(char *page, struct cpuset *cs)
1395 {
1396         cpumask_t mask;
1397
1398         mutex_lock(&callback_mutex);
1399         mask = cs->cpus_allowed;
1400         mutex_unlock(&callback_mutex);
1401
1402         return cpulist_scnprintf(page, PAGE_SIZE, mask);
1403 }
1404
1405 static int cpuset_sprintf_memlist(char *page, struct cpuset *cs)
1406 {
1407         nodemask_t mask;
1408
1409         mutex_lock(&callback_mutex);
1410         mask = cs->mems_allowed;
1411         mutex_unlock(&callback_mutex);
1412
1413         return nodelist_scnprintf(page, PAGE_SIZE, mask);
1414 }
1415
1416 static ssize_t cpuset_common_file_read(struct file *file, char __user *buf,
1417                                 size_t nbytes, loff_t *ppos)
1418 {
1419         struct cftype *cft = __d_cft(file->f_path.dentry);
1420         struct cpuset *cs = __d_cs(file->f_path.dentry->d_parent);
1421         cpuset_filetype_t type = cft->private;
1422         char *page;
1423         ssize_t retval = 0;
1424         char *s;
1425
1426         if (!(page = (char *)__get_free_page(GFP_KERNEL)))
1427                 return -ENOMEM;
1428
1429         s = page;
1430
1431         switch (type) {
1432         case FILE_CPULIST:
1433                 s += cpuset_sprintf_cpulist(s, cs);
1434                 break;
1435         case FILE_MEMLIST:
1436                 s += cpuset_sprintf_memlist(s, cs);
1437                 break;
1438         case FILE_CPU_EXCLUSIVE:
1439                 *s++ = is_cpu_exclusive(cs) ? '1' : '0';
1440                 break;
1441         case FILE_MEM_EXCLUSIVE:
1442                 *s++ = is_mem_exclusive(cs) ? '1' : '0';
1443                 break;
1444         case FILE_NOTIFY_ON_RELEASE:
1445                 *s++ = notify_on_release(cs) ? '1' : '0';
1446                 break;
1447         case FILE_MEMORY_MIGRATE:
1448                 *s++ = is_memory_migrate(cs) ? '1' : '0';
1449                 break;
1450         case FILE_MEMORY_PRESSURE_ENABLED:
1451                 *s++ = cpuset_memory_pressure_enabled ? '1' : '0';
1452                 break;
1453         case FILE_MEMORY_PRESSURE:
1454                 s += sprintf(s, "%d", fmeter_getrate(&cs->fmeter));
1455                 break;
1456         case FILE_SPREAD_PAGE:
1457                 *s++ = is_spread_page(cs) ? '1' : '0';
1458                 break;
1459         case FILE_SPREAD_SLAB:
1460                 *s++ = is_spread_slab(cs) ? '1' : '0';
1461                 break;
1462         default:
1463                 retval = -EINVAL;
1464                 goto out;
1465         }
1466         *s++ = '\n';
1467
1468         retval = simple_read_from_buffer(buf, nbytes, ppos, page, s - page);
1469 out:
1470         free_page((unsigned long)page);
1471         return retval;
1472 }
1473
1474 static ssize_t cpuset_file_read(struct file *file, char __user *buf, size_t nbytes,
1475                                                                 loff_t *ppos)
1476 {
1477         ssize_t retval = 0;
1478         struct cftype *cft = __d_cft(file->f_path.dentry);
1479         if (!cft)
1480                 return -ENODEV;
1481
1482         /* special function ? */
1483         if (cft->read)
1484                 retval = cft->read(file, buf, nbytes, ppos);
1485         else
1486                 retval = cpuset_common_file_read(file, buf, nbytes, ppos);
1487
1488         return retval;
1489 }
1490
1491 static int cpuset_file_open(struct inode *inode, struct file *file)
1492 {
1493         int err;
1494         struct cftype *cft;
1495
1496         err = generic_file_open(inode, file);
1497         if (err)
1498                 return err;
1499
1500         cft = __d_cft(file->f_path.dentry);
1501         if (!cft)
1502                 return -ENODEV;
1503         if (cft->open)
1504                 err = cft->open(inode, file);
1505         else
1506                 err = 0;
1507
1508         return err;
1509 }
1510
1511 static int cpuset_file_release(struct inode *inode, struct file *file)
1512 {
1513         struct cftype *cft = __d_cft(file->f_path.dentry);
1514         if (cft->release)
1515                 return cft->release(inode, file);
1516         return 0;
1517 }
1518
1519 /*
1520  * cpuset_rename - Only allow simple rename of directories in place.
1521  */
1522 static int cpuset_rename(struct inode *old_dir, struct dentry *old_dentry,
1523                   struct inode *new_dir, struct dentry *new_dentry)
1524 {
1525         if (!S_ISDIR(old_dentry->d_inode->i_mode))
1526                 return -ENOTDIR;
1527         if (new_dentry->d_inode)
1528                 return -EEXIST;
1529         if (old_dir != new_dir)
1530                 return -EIO;
1531         return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1532 }
1533
1534 static const struct file_operations cpuset_file_operations = {
1535         .read = cpuset_file_read,
1536         .write = cpuset_file_write,
1537         .llseek = generic_file_llseek,
1538         .open = cpuset_file_open,
1539         .release = cpuset_file_release,
1540 };
1541
1542 static const struct inode_operations cpuset_dir_inode_operations = {
1543         .lookup = simple_lookup,
1544         .mkdir = cpuset_mkdir,
1545         .rmdir = cpuset_rmdir,
1546         .rename = cpuset_rename,
1547 };
1548
1549 static int cpuset_create_file(struct dentry *dentry, int mode)
1550 {
1551         struct inode *inode;
1552
1553         if (!dentry)
1554                 return -ENOENT;
1555         if (dentry->d_inode)
1556                 return -EEXIST;
1557
1558         inode = cpuset_new_inode(mode);
1559         if (!inode)
1560                 return -ENOMEM;
1561
1562         if (S_ISDIR(mode)) {
1563                 inode->i_op = &cpuset_dir_inode_operations;
1564                 inode->i_fop = &simple_dir_operations;
1565
1566                 /* start off with i_nlink == 2 (for "." entry) */
1567                 inc_nlink(inode);
1568         } else if (S_ISREG(mode)) {
1569                 inode->i_size = 0;
1570                 inode->i_fop = &cpuset_file_operations;
1571         }
1572
1573         d_instantiate(dentry, inode);
1574         dget(dentry);   /* Extra count - pin the dentry in core */
1575         return 0;
1576 }
1577
1578 /*
1579  *      cpuset_create_dir - create a directory for an object.
1580  *      cs:     the cpuset we create the directory for.
1581  *              It must have a valid ->parent field
1582  *              And we are going to fill its ->dentry field.
1583  *      name:   The name to give to the cpuset directory. Will be copied.
1584  *      mode:   mode to set on new directory.
1585  */
1586
1587 static int cpuset_create_dir(struct cpuset *cs, const char *name, int mode)
1588 {
1589         struct dentry *dentry = NULL;
1590         struct dentry *parent;
1591         int error = 0;
1592
1593         parent = cs->parent->dentry;
1594         dentry = cpuset_get_dentry(parent, name);
1595         if (IS_ERR(dentry))
1596                 return PTR_ERR(dentry);
1597         error = cpuset_create_file(dentry, S_IFDIR | mode);
1598         if (!error) {
1599                 dentry->d_fsdata = cs;
1600                 inc_nlink(parent->d_inode);
1601                 cs->dentry = dentry;
1602         }
1603         dput(dentry);
1604
1605         return error;
1606 }
1607
1608 static int cpuset_add_file(struct dentry *dir, const struct cftype *cft)
1609 {
1610         struct dentry *dentry;
1611         int error;
1612
1613         mutex_lock(&dir->d_inode->i_mutex);
1614         dentry = cpuset_get_dentry(dir, cft->name);
1615         if (!IS_ERR(dentry)) {
1616                 error = cpuset_create_file(dentry, 0644 | S_IFREG);
1617                 if (!error)
1618                         dentry->d_fsdata = (void *)cft;
1619                 dput(dentry);
1620         } else
1621                 error = PTR_ERR(dentry);
1622         mutex_unlock(&dir->d_inode->i_mutex);
1623         return error;
1624 }
1625
1626 /*
1627  * Stuff for reading the 'tasks' file.
1628  *
1629  * Reading this file can return large amounts of data if a cpuset has
1630  * *lots* of attached tasks. So it may need several calls to read(),
1631  * but we cannot guarantee that the information we produce is correct
1632  * unless we produce it entirely atomically.
1633  *
1634  * Upon tasks file open(), a struct ctr_struct is allocated, that
1635  * will have a pointer to an array (also allocated here).  The struct
1636  * ctr_struct * is stored in file->private_data.  Its resources will
1637  * be freed by release() when the file is closed.  The array is used
1638  * to sprintf the PIDs and then used by read().
1639  */
1640
1641 /* cpusets_tasks_read array */
1642
1643 struct ctr_struct {
1644         char *buf;
1645         int bufsz;
1646 };
1647
1648 /*
1649  * Load into 'pidarray' up to 'npids' of the tasks using cpuset 'cs'.
1650  * Return actual number of pids loaded.  No need to task_lock(p)
1651  * when reading out p->cpuset, as we don't really care if it changes
1652  * on the next cycle, and we are not going to try to dereference it.
1653  */
1654 static int pid_array_load(pid_t *pidarray, int npids, struct cpuset *cs)
1655 {
1656         int n = 0;
1657         struct task_struct *g, *p;
1658
1659         read_lock(&tasklist_lock);
1660
1661         do_each_thread(g, p) {
1662                 if (p->cpuset == cs) {
1663                         pidarray[n++] = p->pid;
1664                         if (unlikely(n == npids))
1665                                 goto array_full;
1666                 }
1667         } while_each_thread(g, p);
1668
1669 array_full:
1670         read_unlock(&tasklist_lock);
1671         return n;
1672 }
1673
1674 static int cmppid(const void *a, const void *b)
1675 {
1676         return *(pid_t *)a - *(pid_t *)b;
1677 }
1678
1679 /*
1680  * Convert array 'a' of 'npids' pid_t's to a string of newline separated
1681  * decimal pids in 'buf'.  Don't write more than 'sz' chars, but return
1682  * count 'cnt' of how many chars would be written if buf were large enough.
1683  */
1684 static int pid_array_to_buf(char *buf, int sz, pid_t *a, int npids)
1685 {
1686         int cnt = 0;
1687         int i;
1688
1689         for (i = 0; i < npids; i++)
1690                 cnt += snprintf(buf + cnt, max(sz - cnt, 0), "%d\n", a[i]);
1691         return cnt;
1692 }
1693
1694 /*
1695  * Handle an open on 'tasks' file.  Prepare a buffer listing the
1696  * process id's of tasks currently attached to the cpuset being opened.
1697  *
1698  * Does not require any specific cpuset mutexes, and does not take any.
1699  */
1700 static int cpuset_tasks_open(struct inode *unused, struct file *file)
1701 {
1702         struct cpuset *cs = __d_cs(file->f_path.dentry->d_parent);
1703         struct ctr_struct *ctr;
1704         pid_t *pidarray;
1705         int npids;
1706         char c;
1707
1708         if (!(file->f_mode & FMODE_READ))
1709                 return 0;
1710
1711         ctr = kmalloc(sizeof(*ctr), GFP_KERNEL);
1712         if (!ctr)
1713                 goto err0;
1714
1715         /*
1716          * If cpuset gets more users after we read count, we won't have
1717          * enough space - tough.  This race is indistinguishable to the
1718          * caller from the case that the additional cpuset users didn't
1719          * show up until sometime later on.
1720          */
1721         npids = atomic_read(&cs->count);
1722         pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
1723         if (!pidarray)
1724                 goto err1;
1725
1726         npids = pid_array_load(pidarray, npids, cs);
1727         sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
1728
1729         /* Call pid_array_to_buf() twice, first just to get bufsz */
1730         ctr->bufsz = pid_array_to_buf(&c, sizeof(c), pidarray, npids) + 1;
1731         ctr->buf = kmalloc(ctr->bufsz, GFP_KERNEL);
1732         if (!ctr->buf)
1733                 goto err2;
1734         ctr->bufsz = pid_array_to_buf(ctr->buf, ctr->bufsz, pidarray, npids);
1735
1736         kfree(pidarray);
1737         file->private_data = ctr;
1738         return 0;
1739
1740 err2:
1741         kfree(pidarray);
1742 err1:
1743         kfree(ctr);
1744 err0:
1745         return -ENOMEM;
1746 }
1747
1748 static ssize_t cpuset_tasks_read(struct file *file, char __user *buf,
1749                                                 size_t nbytes, loff_t *ppos)
1750 {
1751         struct ctr_struct *ctr = file->private_data;
1752
1753         if (*ppos + nbytes > ctr->bufsz)
1754                 nbytes = ctr->bufsz - *ppos;
1755         if (copy_to_user(buf, ctr->buf + *ppos, nbytes))
1756                 return -EFAULT;
1757         *ppos += nbytes;
1758         return nbytes;
1759 }
1760
1761 static int cpuset_tasks_release(struct inode *unused_inode, struct file *file)
1762 {
1763         struct ctr_struct *ctr;
1764
1765         if (file->f_mode & FMODE_READ) {
1766                 ctr = file->private_data;
1767                 kfree(ctr->buf);
1768                 kfree(ctr);
1769         }
1770         return 0;
1771 }
1772
1773 /*
1774  * for the common functions, 'private' gives the type of file
1775  */
1776
1777 static struct cftype cft_tasks = {
1778         .name = "tasks",
1779         .open = cpuset_tasks_open,
1780         .read = cpuset_tasks_read,
1781         .release = cpuset_tasks_release,
1782         .private = FILE_TASKLIST,
1783 };
1784
1785 static struct cftype cft_cpus = {
1786         .name = "cpus",
1787         .private = FILE_CPULIST,
1788 };
1789
1790 static struct cftype cft_mems = {
1791         .name = "mems",
1792         .private = FILE_MEMLIST,
1793 };
1794
1795 static struct cftype cft_cpu_exclusive = {
1796         .name = "cpu_exclusive",
1797         .private = FILE_CPU_EXCLUSIVE,
1798 };
1799
1800 static struct cftype cft_mem_exclusive = {
1801         .name = "mem_exclusive",
1802         .private = FILE_MEM_EXCLUSIVE,
1803 };
1804
1805 static struct cftype cft_notify_on_release = {
1806         .name = "notify_on_release",
1807         .private = FILE_NOTIFY_ON_RELEASE,
1808 };
1809
1810 static struct cftype cft_memory_migrate = {
1811         .name = "memory_migrate",
1812         .private = FILE_MEMORY_MIGRATE,
1813 };
1814
1815 static struct cftype cft_memory_pressure_enabled = {
1816         .name = "memory_pressure_enabled",
1817         .private = FILE_MEMORY_PRESSURE_ENABLED,
1818 };
1819
1820 static struct cftype cft_memory_pressure = {
1821         .name = "memory_pressure",
1822         .private = FILE_MEMORY_PRESSURE,
1823 };
1824
1825 static struct cftype cft_spread_page = {
1826         .name = "memory_spread_page",
1827         .private = FILE_SPREAD_PAGE,
1828 };
1829
1830 static struct cftype cft_spread_slab = {
1831         .name = "memory_spread_slab",
1832         .private = FILE_SPREAD_SLAB,
1833 };
1834
1835 static int cpuset_populate_dir(struct dentry *cs_dentry)
1836 {
1837         int err;
1838
1839         if ((err = cpuset_add_file(cs_dentry, &cft_cpus)) < 0)
1840                 return err;
1841         if ((err = cpuset_add_file(cs_dentry, &cft_mems)) < 0)
1842                 return err;
1843         if ((err = cpuset_add_file(cs_dentry, &cft_cpu_exclusive)) < 0)
1844                 return err;
1845         if ((err = cpuset_add_file(cs_dentry, &cft_mem_exclusive)) < 0)
1846                 return err;
1847         if ((err = cpuset_add_file(cs_dentry, &cft_notify_on_release)) < 0)
1848                 return err;
1849         if ((err = cpuset_add_file(cs_dentry, &cft_memory_migrate)) < 0)
1850                 return err;
1851         if ((err = cpuset_add_file(cs_dentry, &cft_memory_pressure)) < 0)
1852                 return err;
1853         if ((err = cpuset_add_file(cs_dentry, &cft_spread_page)) < 0)
1854                 return err;
1855         if ((err = cpuset_add_file(cs_dentry, &cft_spread_slab)) < 0)
1856                 return err;
1857         if ((err = cpuset_add_file(cs_dentry, &cft_tasks)) < 0)
1858                 return err;
1859         return 0;
1860 }
1861
1862 /*
1863  *      cpuset_create - create a cpuset
1864  *      parent: cpuset that will be parent of the new cpuset.
1865  *      name:           name of the new cpuset. Will be strcpy'ed.
1866  *      mode:           mode to set on new inode
1867  *
1868  *      Must be called with the mutex on the parent inode held
1869  */
1870
1871 static long cpuset_create(struct cpuset *parent, const char *name, int mode)
1872 {
1873         struct cpuset *cs;
1874         int err;
1875
1876         cs = kmalloc(sizeof(*cs), GFP_KERNEL);
1877         if (!cs)
1878                 return -ENOMEM;
1879
1880         mutex_lock(&manage_mutex);
1881         cpuset_update_task_memory_state();
1882         cs->flags = 0;
1883         if (notify_on_release(parent))
1884                 set_bit(CS_NOTIFY_ON_RELEASE, &cs->flags);
1885         if (is_spread_page(parent))
1886                 set_bit(CS_SPREAD_PAGE, &cs->flags);
1887         if (is_spread_slab(parent))
1888                 set_bit(CS_SPREAD_SLAB, &cs->flags);
1889         cs->cpus_allowed = CPU_MASK_NONE;
1890         cs->mems_allowed = NODE_MASK_NONE;
1891         atomic_set(&cs->count, 0);
1892         INIT_LIST_HEAD(&cs->sibling);
1893         INIT_LIST_HEAD(&cs->children);
1894         cs->mems_generation = cpuset_mems_generation++;
1895         fmeter_init(&cs->fmeter);
1896
1897         cs->parent = parent;
1898
1899         mutex_lock(&callback_mutex);
1900         list_add(&cs->sibling, &cs->parent->children);
1901         number_of_cpusets++;
1902         mutex_unlock(&callback_mutex);
1903
1904         err = cpuset_create_dir(cs, name, mode);
1905         if (err < 0)
1906                 goto err;
1907
1908         /*
1909          * Release manage_mutex before cpuset_populate_dir() because it
1910          * will down() this new directory's i_mutex and if we race with
1911          * another mkdir, we might deadlock.
1912          */
1913         mutex_unlock(&manage_mutex);
1914
1915         err = cpuset_populate_dir(cs->dentry);
1916         /* If err < 0, we have a half-filled directory - oh well ;) */
1917         return 0;
1918 err:
1919         list_del(&cs->sibling);
1920         mutex_unlock(&manage_mutex);
1921         kfree(cs);
1922         return err;
1923 }
1924
1925 static int cpuset_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1926 {
1927         struct cpuset *c_parent = dentry->d_parent->d_fsdata;
1928
1929         /* the vfs holds inode->i_mutex already */
1930         return cpuset_create(c_parent, dentry->d_name.name, mode | S_IFDIR);
1931 }
1932
1933 /*
1934  * Locking note on the strange update_flag() call below:
1935  *
1936  * If the cpuset being removed is marked cpu_exclusive, then simulate
1937  * turning cpu_exclusive off, which will call update_cpu_domains().
1938  * The lock_cpu_hotplug() call in update_cpu_domains() must not be
1939  * made while holding callback_mutex.  Elsewhere the kernel nests
1940  * callback_mutex inside lock_cpu_hotplug() calls.  So the reverse
1941  * nesting would risk an ABBA deadlock.
1942  */
1943
1944 static int cpuset_rmdir(struct inode *unused_dir, struct dentry *dentry)
1945 {
1946         struct cpuset *cs = dentry->d_fsdata;
1947         struct dentry *d;
1948         struct cpuset *parent;
1949         char *pathbuf = NULL;
1950
1951         /* the vfs holds both inode->i_mutex already */
1952
1953         mutex_lock(&manage_mutex);
1954         cpuset_update_task_memory_state();
1955         if (atomic_read(&cs->count) > 0) {
1956                 mutex_unlock(&manage_mutex);
1957                 return -EBUSY;
1958         }
1959         if (!list_empty(&cs->children)) {
1960                 mutex_unlock(&manage_mutex);
1961                 return -EBUSY;
1962         }
1963         if (is_cpu_exclusive(cs)) {
1964                 int retval = update_flag(CS_CPU_EXCLUSIVE, cs, "0");
1965                 if (retval < 0) {
1966                         mutex_unlock(&manage_mutex);
1967                         return retval;
1968                 }
1969         }
1970         parent = cs->parent;
1971         mutex_lock(&callback_mutex);
1972         set_bit(CS_REMOVED, &cs->flags);
1973         list_del(&cs->sibling); /* delete my sibling from parent->children */
1974         spin_lock(&cs->dentry->d_lock);
1975         d = dget(cs->dentry);
1976         cs->dentry = NULL;
1977         spin_unlock(&d->d_lock);
1978         cpuset_d_remove_dir(d);
1979         dput(d);
1980         number_of_cpusets--;
1981         mutex_unlock(&callback_mutex);
1982         if (list_empty(&parent->children))
1983                 check_for_release(parent, &pathbuf);
1984         mutex_unlock(&manage_mutex);
1985         cpuset_release_agent(pathbuf);
1986         return 0;
1987 }
1988
1989 /*
1990  * cpuset_init_early - just enough so that the calls to
1991  * cpuset_update_task_memory_state() in early init code
1992  * are harmless.
1993  */
1994
1995 int __init cpuset_init_early(void)
1996 {
1997         struct task_struct *tsk = current;
1998
1999         tsk->cpuset = &top_cpuset;
2000         tsk->cpuset->mems_generation = cpuset_mems_generation++;
2001         return 0;
2002 }
2003
2004 /**
2005  * cpuset_init - initialize cpusets at system boot
2006  *
2007  * Description: Initialize top_cpuset and the cpuset internal file system,
2008  **/
2009
2010 int __init cpuset_init(void)
2011 {
2012         struct dentry *root;
2013         int err;
2014
2015         top_cpuset.cpus_allowed = CPU_MASK_ALL;
2016         top_cpuset.mems_allowed = NODE_MASK_ALL;
2017
2018         fmeter_init(&top_cpuset.fmeter);
2019         top_cpuset.mems_generation = cpuset_mems_generation++;
2020
2021         init_task.cpuset = &top_cpuset;
2022
2023         err = register_filesystem(&cpuset_fs_type);
2024         if (err < 0)
2025                 goto out;
2026         cpuset_mount = kern_mount(&cpuset_fs_type);
2027         if (IS_ERR(cpuset_mount)) {
2028                 printk(KERN_ERR "cpuset: could not mount!\n");
2029                 err = PTR_ERR(cpuset_mount);
2030                 cpuset_mount = NULL;
2031                 goto out;
2032         }
2033         root = cpuset_mount->mnt_sb->s_root;
2034         root->d_fsdata = &top_cpuset;
2035         inc_nlink(root->d_inode);
2036         top_cpuset.dentry = root;
2037         root->d_inode->i_op = &cpuset_dir_inode_operations;
2038         number_of_cpusets = 1;
2039         err = cpuset_populate_dir(root);
2040         /* memory_pressure_enabled is in root cpuset only */
2041         if (err == 0)
2042                 err = cpuset_add_file(root, &cft_memory_pressure_enabled);
2043 out:
2044         return err;
2045 }
2046
2047 /*
2048  * If common_cpu_mem_hotplug_unplug(), below, unplugs any CPUs
2049  * or memory nodes, we need to walk over the cpuset hierarchy,
2050  * removing that CPU or node from all cpusets.  If this removes the
2051  * last CPU or node from a cpuset, then the guarantee_online_cpus()
2052  * or guarantee_online_mems() code will use that emptied cpusets
2053  * parent online CPUs or nodes.  Cpusets that were already empty of
2054  * CPUs or nodes are left empty.
2055  *
2056  * This routine is intentionally inefficient in a couple of regards.
2057  * It will check all cpusets in a subtree even if the top cpuset of
2058  * the subtree has no offline CPUs or nodes.  It checks both CPUs and
2059  * nodes, even though the caller could have been coded to know that
2060  * only one of CPUs or nodes needed to be checked on a given call.
2061  * This was done to minimize text size rather than cpu cycles.
2062  *
2063  * Call with both manage_mutex and callback_mutex held.
2064  *
2065  * Recursive, on depth of cpuset subtree.
2066  */
2067
2068 static void guarantee_online_cpus_mems_in_subtree(const struct cpuset *cur)
2069 {
2070         struct cpuset *c;
2071
2072         /* Each of our child cpusets mems must be online */
2073         list_for_each_entry(c, &cur->children, sibling) {
2074                 guarantee_online_cpus_mems_in_subtree(c);
2075                 if (!cpus_empty(c->cpus_allowed))
2076                         guarantee_online_cpus(c, &c->cpus_allowed);
2077                 if (!nodes_empty(c->mems_allowed))
2078                         guarantee_online_mems(c, &c->mems_allowed);
2079         }
2080 }
2081
2082 /*
2083  * The cpus_allowed and mems_allowed nodemasks in the top_cpuset track
2084  * cpu_online_map and node_online_map.  Force the top cpuset to track
2085  * whats online after any CPU or memory node hotplug or unplug event.
2086  *
2087  * To ensure that we don't remove a CPU or node from the top cpuset
2088  * that is currently in use by a child cpuset (which would violate
2089  * the rule that cpusets must be subsets of their parent), we first
2090  * call the recursive routine guarantee_online_cpus_mems_in_subtree().
2091  *
2092  * Since there are two callers of this routine, one for CPU hotplug
2093  * events and one for memory node hotplug events, we could have coded
2094  * two separate routines here.  We code it as a single common routine
2095  * in order to minimize text size.
2096  */
2097
2098 static void common_cpu_mem_hotplug_unplug(void)
2099 {
2100         mutex_lock(&manage_mutex);
2101         mutex_lock(&callback_mutex);
2102
2103         guarantee_online_cpus_mems_in_subtree(&top_cpuset);
2104         top_cpuset.cpus_allowed = cpu_online_map;
2105         top_cpuset.mems_allowed = node_online_map;
2106
2107         mutex_unlock(&callback_mutex);
2108         mutex_unlock(&manage_mutex);
2109 }
2110
2111 /*
2112  * The top_cpuset tracks what CPUs and Memory Nodes are online,
2113  * period.  This is necessary in order to make cpusets transparent
2114  * (of no affect) on systems that are actively using CPU hotplug
2115  * but making no active use of cpusets.
2116  *
2117  * This routine ensures that top_cpuset.cpus_allowed tracks
2118  * cpu_online_map on each CPU hotplug (cpuhp) event.
2119  */
2120
2121 static int cpuset_handle_cpuhp(struct notifier_block *nb,
2122                                 unsigned long phase, void *cpu)
2123 {
2124         common_cpu_mem_hotplug_unplug();
2125         return 0;
2126 }
2127
2128 #ifdef CONFIG_MEMORY_HOTPLUG
2129 /*
2130  * Keep top_cpuset.mems_allowed tracking node_online_map.
2131  * Call this routine anytime after you change node_online_map.
2132  * See also the previous routine cpuset_handle_cpuhp().
2133  */
2134
2135 void cpuset_track_online_nodes(void)
2136 {
2137         common_cpu_mem_hotplug_unplug();
2138 }
2139 #endif
2140
2141 /**
2142  * cpuset_init_smp - initialize cpus_allowed
2143  *
2144  * Description: Finish top cpuset after cpu, node maps are initialized
2145  **/
2146
2147 void __init cpuset_init_smp(void)
2148 {
2149         top_cpuset.cpus_allowed = cpu_online_map;
2150         top_cpuset.mems_allowed = node_online_map;
2151
2152         hotcpu_notifier(cpuset_handle_cpuhp, 0);
2153 }
2154
2155 /**
2156  * cpuset_fork - attach newly forked task to its parents cpuset.
2157  * @tsk: pointer to task_struct of forking parent process.
2158  *
2159  * Description: A task inherits its parent's cpuset at fork().
2160  *
2161  * A pointer to the shared cpuset was automatically copied in fork.c
2162  * by dup_task_struct().  However, we ignore that copy, since it was
2163  * not made under the protection of task_lock(), so might no longer be
2164  * a valid cpuset pointer.  attach_task() might have already changed
2165  * current->cpuset, allowing the previously referenced cpuset to
2166  * be removed and freed.  Instead, we task_lock(current) and copy
2167  * its present value of current->cpuset for our freshly forked child.
2168  *
2169  * At the point that cpuset_fork() is called, 'current' is the parent
2170  * task, and the passed argument 'child' points to the child task.
2171  **/
2172
2173 void cpuset_fork(struct task_struct *child)
2174 {
2175         task_lock(current);
2176         child->cpuset = current->cpuset;
2177         atomic_inc(&child->cpuset->count);
2178         task_unlock(current);
2179 }
2180
2181 /**
2182  * cpuset_exit - detach cpuset from exiting task
2183  * @tsk: pointer to task_struct of exiting process
2184  *
2185  * Description: Detach cpuset from @tsk and release it.
2186  *
2187  * Note that cpusets marked notify_on_release force every task in
2188  * them to take the global manage_mutex mutex when exiting.
2189  * This could impact scaling on very large systems.  Be reluctant to
2190  * use notify_on_release cpusets where very high task exit scaling
2191  * is required on large systems.
2192  *
2193  * Don't even think about derefencing 'cs' after the cpuset use count
2194  * goes to zero, except inside a critical section guarded by manage_mutex
2195  * or callback_mutex.   Otherwise a zero cpuset use count is a license to
2196  * any other task to nuke the cpuset immediately, via cpuset_rmdir().
2197  *
2198  * This routine has to take manage_mutex, not callback_mutex, because
2199  * it is holding that mutex while calling check_for_release(),
2200  * which calls kmalloc(), so can't be called holding callback_mutex().
2201  *
2202  * the_top_cpuset_hack:
2203  *
2204  *    Set the exiting tasks cpuset to the root cpuset (top_cpuset).
2205  *
2206  *    Don't leave a task unable to allocate memory, as that is an
2207  *    accident waiting to happen should someone add a callout in
2208  *    do_exit() after the cpuset_exit() call that might allocate.
2209  *    If a task tries to allocate memory with an invalid cpuset,
2210  *    it will oops in cpuset_update_task_memory_state().
2211  *
2212  *    We call cpuset_exit() while the task is still competent to
2213  *    handle notify_on_release(), then leave the task attached to
2214  *    the root cpuset (top_cpuset) for the remainder of its exit.
2215  *
2216  *    To do this properly, we would increment the reference count on
2217  *    top_cpuset, and near the very end of the kernel/exit.c do_exit()
2218  *    code we would add a second cpuset function call, to drop that
2219  *    reference.  This would just create an unnecessary hot spot on
2220  *    the top_cpuset reference count, to no avail.
2221  *
2222  *    Normally, holding a reference to a cpuset without bumping its
2223  *    count is unsafe.   The cpuset could go away, or someone could
2224  *    attach us to a different cpuset, decrementing the count on
2225  *    the first cpuset that we never incremented.  But in this case,
2226  *    top_cpuset isn't going away, and either task has PF_EXITING set,
2227  *    which wards off any attach_task() attempts, or task is a failed
2228  *    fork, never visible to attach_task.
2229  *
2230  *    Another way to do this would be to set the cpuset pointer
2231  *    to NULL here, and check in cpuset_update_task_memory_state()
2232  *    for a NULL pointer.  This hack avoids that NULL check, for no
2233  *    cost (other than this way too long comment ;).
2234  **/
2235
2236 void cpuset_exit(struct task_struct *tsk)
2237 {
2238         struct cpuset *cs;
2239
2240         task_lock(current);
2241         cs = tsk->cpuset;
2242         tsk->cpuset = &top_cpuset;      /* the_top_cpuset_hack - see above */
2243         task_unlock(current);
2244
2245         if (notify_on_release(cs)) {
2246                 char *pathbuf = NULL;
2247
2248                 mutex_lock(&manage_mutex);
2249                 if (atomic_dec_and_test(&cs->count))
2250                         check_for_release(cs, &pathbuf);
2251                 mutex_unlock(&manage_mutex);
2252                 cpuset_release_agent(pathbuf);
2253         } else {
2254                 atomic_dec(&cs->count);
2255         }
2256 }
2257
2258 /**
2259  * cpuset_cpus_allowed - return cpus_allowed mask from a tasks cpuset.
2260  * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
2261  *
2262  * Description: Returns the cpumask_t cpus_allowed of the cpuset
2263  * attached to the specified @tsk.  Guaranteed to return some non-empty
2264  * subset of cpu_online_map, even if this means going outside the
2265  * tasks cpuset.
2266  **/
2267
2268 cpumask_t cpuset_cpus_allowed(struct task_struct *tsk)
2269 {
2270         cpumask_t mask;
2271
2272         mutex_lock(&callback_mutex);
2273         task_lock(tsk);
2274         guarantee_online_cpus(tsk->cpuset, &mask);
2275         task_unlock(tsk);
2276         mutex_unlock(&callback_mutex);
2277
2278         return mask;
2279 }
2280
2281 void cpuset_init_current_mems_allowed(void)
2282 {
2283         current->mems_allowed = NODE_MASK_ALL;
2284 }
2285
2286 /**
2287  * cpuset_mems_allowed - return mems_allowed mask from a tasks cpuset.
2288  * @tsk: pointer to task_struct from which to obtain cpuset->mems_allowed.
2289  *
2290  * Description: Returns the nodemask_t mems_allowed of the cpuset
2291  * attached to the specified @tsk.  Guaranteed to return some non-empty
2292  * subset of node_online_map, even if this means going outside the
2293  * tasks cpuset.
2294  **/
2295
2296 nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
2297 {
2298         nodemask_t mask;
2299
2300         mutex_lock(&callback_mutex);
2301         task_lock(tsk);
2302         guarantee_online_mems(tsk->cpuset, &mask);
2303         task_unlock(tsk);
2304         mutex_unlock(&callback_mutex);
2305
2306         return mask;
2307 }
2308
2309 /**
2310  * cpuset_zonelist_valid_mems_allowed - check zonelist vs. curremt mems_allowed
2311  * @zl: the zonelist to be checked
2312  *
2313  * Are any of the nodes on zonelist zl allowed in current->mems_allowed?
2314  */
2315 int cpuset_zonelist_valid_mems_allowed(struct zonelist *zl)
2316 {
2317         int i;
2318
2319         for (i = 0; zl->zones[i]; i++) {
2320                 int nid = zone_to_nid(zl->zones[i]);
2321
2322                 if (node_isset(nid, current->mems_allowed))
2323                         return 1;
2324         }
2325         return 0;
2326 }
2327
2328 /*
2329  * nearest_exclusive_ancestor() - Returns the nearest mem_exclusive
2330  * ancestor to the specified cpuset.  Call holding callback_mutex.
2331  * If no ancestor is mem_exclusive (an unusual configuration), then
2332  * returns the root cpuset.
2333  */
2334 static const struct cpuset *nearest_exclusive_ancestor(const struct cpuset *cs)
2335 {
2336         while (!is_mem_exclusive(cs) && cs->parent)
2337                 cs = cs->parent;
2338         return cs;
2339 }
2340
2341 /**
2342  * cpuset_zone_allowed_softwall - Can we allocate on zone z's memory node?
2343  * @z: is this zone on an allowed node?
2344  * @gfp_mask: memory allocation flags
2345  *
2346  * If we're in interrupt, yes, we can always allocate.  If
2347  * __GFP_THISNODE is set, yes, we can always allocate.  If zone
2348  * z's node is in our tasks mems_allowed, yes.  If it's not a
2349  * __GFP_HARDWALL request and this zone's nodes is in the nearest
2350  * mem_exclusive cpuset ancestor to this tasks cpuset, yes.
2351  * If the task has been OOM killed and has access to memory reserves
2352  * as specified by the TIF_MEMDIE flag, yes.
2353  * Otherwise, no.
2354  *
2355  * If __GFP_HARDWALL is set, cpuset_zone_allowed_softwall()
2356  * reduces to cpuset_zone_allowed_hardwall().  Otherwise,
2357  * cpuset_zone_allowed_softwall() might sleep, and might allow a zone
2358  * from an enclosing cpuset.
2359  *
2360  * cpuset_zone_allowed_hardwall() only handles the simpler case of
2361  * hardwall cpusets, and never sleeps.
2362  *
2363  * The __GFP_THISNODE placement logic is really handled elsewhere,
2364  * by forcibly using a zonelist starting at a specified node, and by
2365  * (in get_page_from_freelist()) refusing to consider the zones for
2366  * any node on the zonelist except the first.  By the time any such
2367  * calls get to this routine, we should just shut up and say 'yes'.
2368  *
2369  * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
2370  * and do not allow allocations outside the current tasks cpuset
2371  * unless the task has been OOM killed as is marked TIF_MEMDIE.
2372  * GFP_KERNEL allocations are not so marked, so can escape to the
2373  * nearest enclosing mem_exclusive ancestor cpuset.
2374  *
2375  * Scanning up parent cpusets requires callback_mutex.  The
2376  * __alloc_pages() routine only calls here with __GFP_HARDWALL bit
2377  * _not_ set if it's a GFP_KERNEL allocation, and all nodes in the
2378  * current tasks mems_allowed came up empty on the first pass over
2379  * the zonelist.  So only GFP_KERNEL allocations, if all nodes in the
2380  * cpuset are short of memory, might require taking the callback_mutex
2381  * mutex.
2382  *
2383  * The first call here from mm/page_alloc:get_page_from_freelist()
2384  * has __GFP_HARDWALL set in gfp_mask, enforcing hardwall cpusets,
2385  * so no allocation on a node outside the cpuset is allowed (unless
2386  * in interrupt, of course).
2387  *
2388  * The second pass through get_page_from_freelist() doesn't even call
2389  * here for GFP_ATOMIC calls.  For those calls, the __alloc_pages()
2390  * variable 'wait' is not set, and the bit ALLOC_CPUSET is not set
2391  * in alloc_flags.  That logic and the checks below have the combined
2392  * affect that:
2393  *      in_interrupt - any node ok (current task context irrelevant)
2394  *      GFP_ATOMIC   - any node ok
2395  *      TIF_MEMDIE   - any node ok
2396  *      GFP_KERNEL   - any node in enclosing mem_exclusive cpuset ok
2397  *      GFP_USER     - only nodes in current tasks mems allowed ok.
2398  *
2399  * Rule:
2400  *    Don't call cpuset_zone_allowed_softwall if you can't sleep, unless you
2401  *    pass in the __GFP_HARDWALL flag set in gfp_flag, which disables
2402  *    the code that might scan up ancestor cpusets and sleep.
2403  */
2404
2405 int __cpuset_zone_allowed_softwall(struct zone *z, gfp_t gfp_mask)
2406 {
2407         int node;                       /* node that zone z is on */
2408         const struct cpuset *cs;        /* current cpuset ancestors */
2409         int allowed;                    /* is allocation in zone z allowed? */
2410
2411         if (in_interrupt() || (gfp_mask & __GFP_THISNODE))
2412                 return 1;
2413         node = zone_to_nid(z);
2414         might_sleep_if(!(gfp_mask & __GFP_HARDWALL));
2415         if (node_isset(node, current->mems_allowed))
2416                 return 1;
2417         /*
2418          * Allow tasks that have access to memory reserves because they have
2419          * been OOM killed to get memory anywhere.
2420          */
2421         if (unlikely(test_thread_flag(TIF_MEMDIE)))
2422                 return 1;
2423         if (gfp_mask & __GFP_HARDWALL)  /* If hardwall request, stop here */
2424                 return 0;
2425
2426         if (current->flags & PF_EXITING) /* Let dying task have memory */
2427                 return 1;
2428
2429         /* Not hardwall and node outside mems_allowed: scan up cpusets */
2430         mutex_lock(&callback_mutex);
2431
2432         task_lock(current);
2433         cs = nearest_exclusive_ancestor(current->cpuset);
2434         task_unlock(current);
2435
2436         allowed = node_isset(node, cs->mems_allowed);
2437         mutex_unlock(&callback_mutex);
2438         return allowed;
2439 }
2440
2441 /*
2442  * cpuset_zone_allowed_hardwall - Can we allocate on zone z's memory node?
2443  * @z: is this zone on an allowed node?
2444  * @gfp_mask: memory allocation flags
2445  *
2446  * If we're in interrupt, yes, we can always allocate.
2447  * If __GFP_THISNODE is set, yes, we can always allocate.  If zone
2448  * z's node is in our tasks mems_allowed, yes.   If the task has been
2449  * OOM killed and has access to memory reserves as specified by the
2450  * TIF_MEMDIE flag, yes.  Otherwise, no.
2451  *
2452  * The __GFP_THISNODE placement logic is really handled elsewhere,
2453  * by forcibly using a zonelist starting at a specified node, and by
2454  * (in get_page_from_freelist()) refusing to consider the zones for
2455  * any node on the zonelist except the first.  By the time any such
2456  * calls get to this routine, we should just shut up and say 'yes'.
2457  *
2458  * Unlike the cpuset_zone_allowed_softwall() variant, above,
2459  * this variant requires that the zone be in the current tasks
2460  * mems_allowed or that we're in interrupt.  It does not scan up the
2461  * cpuset hierarchy for the nearest enclosing mem_exclusive cpuset.
2462  * It never sleeps.
2463  */
2464
2465 int __cpuset_zone_allowed_hardwall(struct zone *z, gfp_t gfp_mask)
2466 {
2467         int node;                       /* node that zone z is on */
2468
2469         if (in_interrupt() || (gfp_mask & __GFP_THISNODE))
2470                 return 1;
2471         node = zone_to_nid(z);
2472         if (node_isset(node, current->mems_allowed))
2473                 return 1;
2474         /*
2475          * Allow tasks that have access to memory reserves because they have
2476          * been OOM killed to get memory anywhere.
2477          */
2478         if (unlikely(test_thread_flag(TIF_MEMDIE)))
2479                 return 1;
2480         return 0;
2481 }
2482
2483 /**
2484  * cpuset_lock - lock out any changes to cpuset structures
2485  *
2486  * The out of memory (oom) code needs to mutex_lock cpusets
2487  * from being changed while it scans the tasklist looking for a
2488  * task in an overlapping cpuset.  Expose callback_mutex via this
2489  * cpuset_lock() routine, so the oom code can lock it, before
2490  * locking the task list.  The tasklist_lock is a spinlock, so
2491  * must be taken inside callback_mutex.
2492  */
2493
2494 void cpuset_lock(void)
2495 {
2496         mutex_lock(&callback_mutex);
2497 }
2498
2499 /**
2500  * cpuset_unlock - release lock on cpuset changes
2501  *
2502  * Undo the lock taken in a previous cpuset_lock() call.
2503  */
2504
2505 void cpuset_unlock(void)
2506 {
2507         mutex_unlock(&callback_mutex);
2508 }
2509
2510 /**
2511  * cpuset_mem_spread_node() - On which node to begin search for a page
2512  *
2513  * If a task is marked PF_SPREAD_PAGE or PF_SPREAD_SLAB (as for
2514  * tasks in a cpuset with is_spread_page or is_spread_slab set),
2515  * and if the memory allocation used cpuset_mem_spread_node()
2516  * to determine on which node to start looking, as it will for
2517  * certain page cache or slab cache pages such as used for file
2518  * system buffers and inode caches, then instead of starting on the
2519  * local node to look for a free page, rather spread the starting
2520  * node around the tasks mems_allowed nodes.
2521  *
2522  * We don't have to worry about the returned node being offline
2523  * because "it can't happen", and even if it did, it would be ok.
2524  *
2525  * The routines calling guarantee_online_mems() are careful to
2526  * only set nodes in task->mems_allowed that are online.  So it
2527  * should not be possible for the following code to return an
2528  * offline node.  But if it did, that would be ok, as this routine
2529  * is not returning the node where the allocation must be, only
2530  * the node where the search should start.  The zonelist passed to
2531  * __alloc_pages() will include all nodes.  If the slab allocator
2532  * is passed an offline node, it will fall back to the local node.
2533  * See kmem_cache_alloc_node().
2534  */
2535
2536 int cpuset_mem_spread_node(void)
2537 {
2538         int node;
2539
2540         node = next_node(current->cpuset_mem_spread_rotor, current->mems_allowed);
2541         if (node == MAX_NUMNODES)
2542                 node = first_node(current->mems_allowed);
2543         current->cpuset_mem_spread_rotor = node;
2544         return node;
2545 }
2546 EXPORT_SYMBOL_GPL(cpuset_mem_spread_node);
2547
2548 /**
2549  * cpuset_excl_nodes_overlap - Do we overlap @p's mem_exclusive ancestors?
2550  * @p: pointer to task_struct of some other task.
2551  *
2552  * Description: Return true if the nearest mem_exclusive ancestor
2553  * cpusets of tasks @p and current overlap.  Used by oom killer to
2554  * determine if task @p's memory usage might impact the memory
2555  * available to the current task.
2556  *
2557  * Call while holding callback_mutex.
2558  **/
2559
2560 int cpuset_excl_nodes_overlap(const struct task_struct *p)
2561 {
2562         const struct cpuset *cs1, *cs2; /* my and p's cpuset ancestors */
2563         int overlap = 1;                /* do cpusets overlap? */
2564
2565         task_lock(current);
2566         if (current->flags & PF_EXITING) {
2567                 task_unlock(current);
2568                 goto done;
2569         }
2570         cs1 = nearest_exclusive_ancestor(current->cpuset);
2571         task_unlock(current);
2572
2573         task_lock((struct task_struct *)p);
2574         if (p->flags & PF_EXITING) {
2575                 task_unlock((struct task_struct *)p);
2576                 goto done;
2577         }
2578         cs2 = nearest_exclusive_ancestor(p->cpuset);
2579         task_unlock((struct task_struct *)p);
2580
2581         overlap = nodes_intersects(cs1->mems_allowed, cs2->mems_allowed);
2582 done:
2583         return overlap;
2584 }
2585
2586 /*
2587  * Collection of memory_pressure is suppressed unless
2588  * this flag is enabled by writing "1" to the special
2589  * cpuset file 'memory_pressure_enabled' in the root cpuset.
2590  */
2591
2592 int cpuset_memory_pressure_enabled __read_mostly;
2593
2594 /**
2595  * cpuset_memory_pressure_bump - keep stats of per-cpuset reclaims.
2596  *
2597  * Keep a running average of the rate of synchronous (direct)
2598  * page reclaim efforts initiated by tasks in each cpuset.
2599  *
2600  * This represents the rate at which some task in the cpuset
2601  * ran low on memory on all nodes it was allowed to use, and
2602  * had to enter the kernels page reclaim code in an effort to
2603  * create more free memory by tossing clean pages or swapping
2604  * or writing dirty pages.
2605  *
2606  * Display to user space in the per-cpuset read-only file
2607  * "memory_pressure".  Value displayed is an integer
2608  * representing the recent rate of entry into the synchronous
2609  * (direct) page reclaim by any task attached to the cpuset.
2610  **/
2611
2612 void __cpuset_memory_pressure_bump(void)
2613 {
2614         struct cpuset *cs;
2615
2616         task_lock(current);
2617         cs = current->cpuset;
2618         fmeter_markevent(&cs->fmeter);
2619         task_unlock(current);
2620 }
2621
2622 /*
2623  * proc_cpuset_show()
2624  *  - Print tasks cpuset path into seq_file.
2625  *  - Used for /proc/<pid>/cpuset.
2626  *  - No need to task_lock(tsk) on this tsk->cpuset reference, as it
2627  *    doesn't really matter if tsk->cpuset changes after we read it,
2628  *    and we take manage_mutex, keeping attach_task() from changing it
2629  *    anyway.  No need to check that tsk->cpuset != NULL, thanks to
2630  *    the_top_cpuset_hack in cpuset_exit(), which sets an exiting tasks
2631  *    cpuset to top_cpuset.
2632  */
2633 static int proc_cpuset_show(struct seq_file *m, void *v)
2634 {
2635         struct pid *pid;
2636         struct task_struct *tsk;
2637         char *buf;
2638         int retval;
2639
2640         retval = -ENOMEM;
2641         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
2642         if (!buf)
2643                 goto out;
2644
2645         retval = -ESRCH;
2646         pid = m->private;
2647         tsk = get_pid_task(pid, PIDTYPE_PID);
2648         if (!tsk)
2649                 goto out_free;
2650
2651         retval = -EINVAL;
2652         mutex_lock(&manage_mutex);
2653
2654         retval = cpuset_path(tsk->cpuset, buf, PAGE_SIZE);
2655         if (retval < 0)
2656                 goto out_unlock;
2657         seq_puts(m, buf);
2658         seq_putc(m, '\n');
2659 out_unlock:
2660         mutex_unlock(&manage_mutex);
2661         put_task_struct(tsk);
2662 out_free:
2663         kfree(buf);
2664 out:
2665         return retval;
2666 }
2667
2668 static int cpuset_open(struct inode *inode, struct file *file)
2669 {
2670         struct pid *pid = PROC_I(inode)->pid;
2671         return single_open(file, proc_cpuset_show, pid);
2672 }
2673
2674 const struct file_operations proc_cpuset_operations = {
2675         .open           = cpuset_open,
2676         .read           = seq_read,
2677         .llseek         = seq_lseek,
2678         .release        = single_release,
2679 };
2680
2681 /* Display task cpus_allowed, mems_allowed in /proc/<pid>/status file. */
2682 char *cpuset_task_status_allowed(struct task_struct *task, char *buffer)
2683 {
2684         buffer += sprintf(buffer, "Cpus_allowed:\t");
2685         buffer += cpumask_scnprintf(buffer, PAGE_SIZE, task->cpus_allowed);
2686         buffer += sprintf(buffer, "\n");
2687         buffer += sprintf(buffer, "Mems_allowed:\t");
2688         buffer += nodemask_scnprintf(buffer, PAGE_SIZE, task->mems_allowed);
2689         buffer += sprintf(buffer, "\n");
2690         return buffer;
2691 }