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