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