Merge branch 'master' of /home/tglx/work/mtd/git/linux-2.6.git/
[sfrench/cifs-2.6.git] / kernel / cpuset.c
1 /*
2  *  kernel/cpuset.c
3  *
4  *  Processor and Memory placement constraints for sets of tasks.
5  *
6  *  Copyright (C) 2003 BULL SA.
7  *  Copyright (C) 2004 Silicon Graphics, Inc.
8  *
9  *  Portions derived from Patrick Mochel's sysfs code.
10  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
11  *  Portions Copyright (c) 2004 Silicon Graphics, Inc.
12  *
13  *  2003-10-10 Written by Simon Derr <simon.derr@bull.net>
14  *  2003-10-22 Updates by Stephen Hemminger.
15  *  2004 May-July Rework by Paul Jackson <pj@sgi.com>
16  *
17  *  This file is subject to the terms and conditions of the GNU General Public
18  *  License.  See the file COPYING in the main directory of the Linux
19  *  distribution for more details.
20  */
21
22 #include <linux/config.h>
23 #include <linux/cpu.h>
24 #include <linux/cpumask.h>
25 #include <linux/cpuset.h>
26 #include <linux/err.h>
27 #include <linux/errno.h>
28 #include <linux/file.h>
29 #include <linux/fs.h>
30 #include <linux/init.h>
31 #include <linux/interrupt.h>
32 #include <linux/kernel.h>
33 #include <linux/kmod.h>
34 #include <linux/list.h>
35 #include <linux/mempolicy.h>
36 #include <linux/mm.h>
37 #include <linux/module.h>
38 #include <linux/mount.h>
39 #include <linux/namei.h>
40 #include <linux/pagemap.h>
41 #include <linux/proc_fs.h>
42 #include <linux/sched.h>
43 #include <linux/seq_file.h>
44 #include <linux/slab.h>
45 #include <linux/smp_lock.h>
46 #include <linux/spinlock.h>
47 #include <linux/stat.h>
48 #include <linux/string.h>
49 #include <linux/time.h>
50 #include <linux/backing-dev.h>
51 #include <linux/sort.h>
52
53 #include <asm/uaccess.h>
54 #include <asm/atomic.h>
55 #include <asm/semaphore.h>
56
57 #define CPUSET_SUPER_MAGIC              0x27e0eb
58
59 struct cpuset {
60         unsigned long flags;            /* "unsigned long" so bitops work */
61         cpumask_t cpus_allowed;         /* CPUs allowed to tasks in cpuset */
62         nodemask_t mems_allowed;        /* Memory Nodes allowed to tasks */
63
64         /*
65          * Count is atomic so can incr (fork) or decr (exit) without a lock.
66          */
67         atomic_t count;                 /* count tasks using this cpuset */
68
69         /*
70          * We link our 'sibling' struct into our parents 'children'.
71          * Our children link their 'sibling' into our 'children'.
72          */
73         struct list_head sibling;       /* my parents children */
74         struct list_head children;      /* my children */
75
76         struct cpuset *parent;          /* my parent */
77         struct dentry *dentry;          /* cpuset fs entry */
78
79         /*
80          * Copy of global cpuset_mems_generation as of the most
81          * recent time this cpuset changed its mems_allowed.
82          */
83          int mems_generation;
84 };
85
86 /* bits in struct cpuset flags field */
87 typedef enum {
88         CS_CPU_EXCLUSIVE,
89         CS_MEM_EXCLUSIVE,
90         CS_REMOVED,
91         CS_NOTIFY_ON_RELEASE
92 } cpuset_flagbits_t;
93
94 /* convenient tests for these bits */
95 static inline int is_cpu_exclusive(const struct cpuset *cs)
96 {
97         return !!test_bit(CS_CPU_EXCLUSIVE, &cs->flags);
98 }
99
100 static inline int is_mem_exclusive(const struct cpuset *cs)
101 {
102         return !!test_bit(CS_MEM_EXCLUSIVE, &cs->flags);
103 }
104
105 static inline int is_removed(const struct cpuset *cs)
106 {
107         return !!test_bit(CS_REMOVED, &cs->flags);
108 }
109
110 static inline int notify_on_release(const struct cpuset *cs)
111 {
112         return !!test_bit(CS_NOTIFY_ON_RELEASE, &cs->flags);
113 }
114
115 /*
116  * Increment this atomic integer everytime any cpuset changes its
117  * mems_allowed value.  Users of cpusets can track this generation
118  * number, and avoid having to lock and reload mems_allowed unless
119  * the cpuset they're using changes generation.
120  *
121  * A single, global generation is needed because attach_task() could
122  * reattach a task to a different cpuset, which must not have its
123  * generation numbers aliased with those of that tasks previous cpuset.
124  *
125  * Generations are needed for mems_allowed because one task cannot
126  * modify anothers memory placement.  So we must enable every task,
127  * on every visit to __alloc_pages(), to efficiently check whether
128  * its current->cpuset->mems_allowed has changed, requiring an update
129  * of its current->mems_allowed.
130  */
131 static atomic_t cpuset_mems_generation = ATOMIC_INIT(1);
132
133 static struct cpuset top_cpuset = {
134         .flags = ((1 << CS_CPU_EXCLUSIVE) | (1 << CS_MEM_EXCLUSIVE)),
135         .cpus_allowed = CPU_MASK_ALL,
136         .mems_allowed = NODE_MASK_ALL,
137         .count = ATOMIC_INIT(0),
138         .sibling = LIST_HEAD_INIT(top_cpuset.sibling),
139         .children = LIST_HEAD_INIT(top_cpuset.children),
140         .parent = NULL,
141         .dentry = NULL,
142         .mems_generation = 0,
143 };
144
145 static struct vfsmount *cpuset_mount;
146 static struct super_block *cpuset_sb = NULL;
147
148 /*
149  * We have two global cpuset semaphores below.  They can nest.
150  * It is ok to first take manage_sem, then nest callback_sem.  We also
151  * require taking task_lock() when dereferencing a tasks cpuset pointer.
152  * See "The task_lock() exception", at the end of this comment.
153  *
154  * A task must hold both semaphores to modify cpusets.  If a task
155  * holds manage_sem, then it blocks others wanting that semaphore,
156  * ensuring that it is the only task able to also acquire callback_sem
157  * and be able to modify cpusets.  It can perform various checks on
158  * the cpuset structure first, knowing nothing will change.  It can
159  * also allocate memory while just holding manage_sem.  While it is
160  * performing these checks, various callback routines can briefly
161  * acquire callback_sem to query cpusets.  Once it is ready to make
162  * the changes, it takes callback_sem, blocking everyone else.
163  *
164  * Calls to the kernel memory allocator can not be made while holding
165  * callback_sem, as that would risk double tripping on callback_sem
166  * from one of the callbacks into the cpuset code from within
167  * __alloc_pages().
168  *
169  * If a task is only holding callback_sem, then it has read-only
170  * access to cpusets.
171  *
172  * The task_struct fields mems_allowed and mems_generation may only
173  * be accessed in the context of that task, so require no locks.
174  *
175  * Any task can increment and decrement the count field without lock.
176  * So in general, code holding manage_sem or callback_sem can't rely
177  * on the count field not changing.  However, if the count goes to
178  * zero, then only attach_task(), which holds both semaphores, can
179  * increment it again.  Because a count of zero means that no tasks
180  * are currently attached, therefore there is no way a task attached
181  * to that cpuset can fork (the other way to increment the count).
182  * So code holding manage_sem or callback_sem can safely assume that
183  * if the count is zero, it will stay zero.  Similarly, if a task
184  * holds manage_sem or callback_sem on a cpuset with zero count, it
185  * knows that the cpuset won't be removed, as cpuset_rmdir() needs
186  * both of those semaphores.
187  *
188  * A possible optimization to improve parallelism would be to make
189  * callback_sem a R/W semaphore (rwsem), allowing the callback routines
190  * to proceed in parallel, with read access, until the holder of
191  * manage_sem needed to take this rwsem for exclusive write access
192  * and modify some cpusets.
193  *
194  * The cpuset_common_file_write handler for operations that modify
195  * the cpuset hierarchy holds manage_sem across the entire operation,
196  * single threading all such cpuset modifications across the system.
197  *
198  * The cpuset_common_file_read() handlers only hold callback_sem across
199  * small pieces of code, such as when reading out possibly multi-word
200  * cpumasks and nodemasks.
201  *
202  * The fork and exit callbacks cpuset_fork() and cpuset_exit(), don't
203  * (usually) take either semaphore.  These are the two most performance
204  * critical pieces of code here.  The exception occurs on cpuset_exit(),
205  * when a task in a notify_on_release cpuset exits.  Then manage_sem
206  * is taken, and if the cpuset count is zero, a usermode call made
207  * to /sbin/cpuset_release_agent with the name of the cpuset (path
208  * relative to the root of cpuset file system) as the argument.
209  *
210  * A cpuset can only be deleted if both its 'count' of using tasks
211  * is zero, and its list of 'children' cpusets is empty.  Since all
212  * tasks in the system use _some_ cpuset, and since there is always at
213  * least one task in the system (init, pid == 1), therefore, top_cpuset
214  * always has either children cpusets and/or using tasks.  So we don't
215  * need a special hack to ensure that top_cpuset cannot be deleted.
216  *
217  * The above "Tale of Two Semaphores" would be complete, but for:
218  *
219  *      The task_lock() exception
220  *
221  * The need for this exception arises from the action of attach_task(),
222  * which overwrites one tasks cpuset pointer with another.  It does
223  * so using both semaphores, however there are several performance
224  * critical places that need to reference task->cpuset without the
225  * expense of grabbing a system global semaphore.  Therefore except as
226  * noted below, when dereferencing or, as in attach_task(), modifying
227  * a tasks cpuset pointer we use task_lock(), which acts on a spinlock
228  * (task->alloc_lock) already in the task_struct routinely used for
229  * such matters.
230  */
231
232 static DECLARE_MUTEX(manage_sem);
233 static DECLARE_MUTEX(callback_sem);
234
235 /*
236  * A couple of forward declarations required, due to cyclic reference loop:
237  *  cpuset_mkdir -> cpuset_create -> cpuset_populate_dir -> cpuset_add_file
238  *  -> cpuset_create_file -> cpuset_dir_inode_operations -> cpuset_mkdir.
239  */
240
241 static int cpuset_mkdir(struct inode *dir, struct dentry *dentry, int mode);
242 static int cpuset_rmdir(struct inode *unused_dir, struct dentry *dentry);
243
244 static struct backing_dev_info cpuset_backing_dev_info = {
245         .ra_pages = 0,          /* No readahead */
246         .capabilities   = BDI_CAP_NO_ACCT_DIRTY | BDI_CAP_NO_WRITEBACK,
247 };
248
249 static struct inode *cpuset_new_inode(mode_t mode)
250 {
251         struct inode *inode = new_inode(cpuset_sb);
252
253         if (inode) {
254                 inode->i_mode = mode;
255                 inode->i_uid = current->fsuid;
256                 inode->i_gid = current->fsgid;
257                 inode->i_blksize = PAGE_CACHE_SIZE;
258                 inode->i_blocks = 0;
259                 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
260                 inode->i_mapping->backing_dev_info = &cpuset_backing_dev_info;
261         }
262         return inode;
263 }
264
265 static void cpuset_diput(struct dentry *dentry, struct inode *inode)
266 {
267         /* is dentry a directory ? if so, kfree() associated cpuset */
268         if (S_ISDIR(inode->i_mode)) {
269                 struct cpuset *cs = dentry->d_fsdata;
270                 BUG_ON(!(is_removed(cs)));
271                 kfree(cs);
272         }
273         iput(inode);
274 }
275
276 static struct dentry_operations cpuset_dops = {
277         .d_iput = cpuset_diput,
278 };
279
280 static struct dentry *cpuset_get_dentry(struct dentry *parent, const char *name)
281 {
282         struct dentry *d = lookup_one_len(name, parent, strlen(name));
283         if (!IS_ERR(d))
284                 d->d_op = &cpuset_dops;
285         return d;
286 }
287
288 static void remove_dir(struct dentry *d)
289 {
290         struct dentry *parent = dget(d->d_parent);
291
292         d_delete(d);
293         simple_rmdir(parent->d_inode, d);
294         dput(parent);
295 }
296
297 /*
298  * NOTE : the dentry must have been dget()'ed
299  */
300 static void cpuset_d_remove_dir(struct dentry *dentry)
301 {
302         struct list_head *node;
303
304         spin_lock(&dcache_lock);
305         node = dentry->d_subdirs.next;
306         while (node != &dentry->d_subdirs) {
307                 struct dentry *d = list_entry(node, struct dentry, d_child);
308                 list_del_init(node);
309                 if (d->d_inode) {
310                         d = dget_locked(d);
311                         spin_unlock(&dcache_lock);
312                         d_delete(d);
313                         simple_unlink(dentry->d_inode, d);
314                         dput(d);
315                         spin_lock(&dcache_lock);
316                 }
317                 node = dentry->d_subdirs.next;
318         }
319         list_del_init(&dentry->d_child);
320         spin_unlock(&dcache_lock);
321         remove_dir(dentry);
322 }
323
324 static struct super_operations cpuset_ops = {
325         .statfs = simple_statfs,
326         .drop_inode = generic_delete_inode,
327 };
328
329 static int cpuset_fill_super(struct super_block *sb, void *unused_data,
330                                                         int unused_silent)
331 {
332         struct inode *inode;
333         struct dentry *root;
334
335         sb->s_blocksize = PAGE_CACHE_SIZE;
336         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
337         sb->s_magic = CPUSET_SUPER_MAGIC;
338         sb->s_op = &cpuset_ops;
339         cpuset_sb = sb;
340
341         inode = cpuset_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR);
342         if (inode) {
343                 inode->i_op = &simple_dir_inode_operations;
344                 inode->i_fop = &simple_dir_operations;
345                 /* directories start off with i_nlink == 2 (for "." entry) */
346                 inode->i_nlink++;
347         } else {
348                 return -ENOMEM;
349         }
350
351         root = d_alloc_root(inode);
352         if (!root) {
353                 iput(inode);
354                 return -ENOMEM;
355         }
356         sb->s_root = root;
357         return 0;
358 }
359
360 static struct super_block *cpuset_get_sb(struct file_system_type *fs_type,
361                                         int flags, const char *unused_dev_name,
362                                         void *data)
363 {
364         return get_sb_single(fs_type, flags, data, cpuset_fill_super);
365 }
366
367 static struct file_system_type cpuset_fs_type = {
368         .name = "cpuset",
369         .get_sb = cpuset_get_sb,
370         .kill_sb = kill_litter_super,
371 };
372
373 /* struct cftype:
374  *
375  * The files in the cpuset filesystem mostly have a very simple read/write
376  * handling, some common function will take care of it. Nevertheless some cases
377  * (read tasks) are special and therefore I define this structure for every
378  * kind of file.
379  *
380  *
381  * When reading/writing to a file:
382  *      - the cpuset to use in file->f_dentry->d_parent->d_fsdata
383  *      - the 'cftype' of the file is file->f_dentry->d_fsdata
384  */
385
386 struct cftype {
387         char *name;
388         int private;
389         int (*open) (struct inode *inode, struct file *file);
390         ssize_t (*read) (struct file *file, char __user *buf, size_t nbytes,
391                                                         loff_t *ppos);
392         int (*write) (struct file *file, const char __user *buf, size_t nbytes,
393                                                         loff_t *ppos);
394         int (*release) (struct inode *inode, struct file *file);
395 };
396
397 static inline struct cpuset *__d_cs(struct dentry *dentry)
398 {
399         return dentry->d_fsdata;
400 }
401
402 static inline struct cftype *__d_cft(struct dentry *dentry)
403 {
404         return dentry->d_fsdata;
405 }
406
407 /*
408  * Call with manage_sem held.  Writes path of cpuset into buf.
409  * Returns 0 on success, -errno on error.
410  */
411
412 static int cpuset_path(const struct cpuset *cs, char *buf, int buflen)
413 {
414         char *start;
415
416         start = buf + buflen;
417
418         *--start = '\0';
419         for (;;) {
420                 int len = cs->dentry->d_name.len;
421                 if ((start -= len) < buf)
422                         return -ENAMETOOLONG;
423                 memcpy(start, cs->dentry->d_name.name, len);
424                 cs = cs->parent;
425                 if (!cs)
426                         break;
427                 if (!cs->parent)
428                         continue;
429                 if (--start < buf)
430                         return -ENAMETOOLONG;
431                 *start = '/';
432         }
433         memmove(buf, start, buf + buflen - start);
434         return 0;
435 }
436
437 /*
438  * Notify userspace when a cpuset is released, by running
439  * /sbin/cpuset_release_agent with the name of the cpuset (path
440  * relative to the root of cpuset file system) as the argument.
441  *
442  * Most likely, this user command will try to rmdir this cpuset.
443  *
444  * This races with the possibility that some other task will be
445  * attached to this cpuset before it is removed, or that some other
446  * user task will 'mkdir' a child cpuset of this cpuset.  That's ok.
447  * The presumed 'rmdir' will fail quietly if this cpuset is no longer
448  * unused, and this cpuset will be reprieved from its death sentence,
449  * to continue to serve a useful existence.  Next time it's released,
450  * we will get notified again, if it still has 'notify_on_release' set.
451  *
452  * The final arg to call_usermodehelper() is 0, which means don't
453  * wait.  The separate /sbin/cpuset_release_agent task is forked by
454  * call_usermodehelper(), then control in this thread returns here,
455  * without waiting for the release agent task.  We don't bother to
456  * wait because the caller of this routine has no use for the exit
457  * status of the /sbin/cpuset_release_agent task, so no sense holding
458  * our caller up for that.
459  *
460  * When we had only one cpuset semaphore, we had to call this
461  * without holding it, to avoid deadlock when call_usermodehelper()
462  * allocated memory.  With two locks, we could now call this while
463  * holding manage_sem, but we still don't, so as to minimize
464  * the time manage_sem is held.
465  */
466
467 static void cpuset_release_agent(const char *pathbuf)
468 {
469         char *argv[3], *envp[3];
470         int i;
471
472         if (!pathbuf)
473                 return;
474
475         i = 0;
476         argv[i++] = "/sbin/cpuset_release_agent";
477         argv[i++] = (char *)pathbuf;
478         argv[i] = NULL;
479
480         i = 0;
481         /* minimal command environment */
482         envp[i++] = "HOME=/";
483         envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
484         envp[i] = NULL;
485
486         call_usermodehelper(argv[0], argv, envp, 0);
487         kfree(pathbuf);
488 }
489
490 /*
491  * Either cs->count of using tasks transitioned to zero, or the
492  * cs->children list of child cpusets just became empty.  If this
493  * cs is notify_on_release() and now both the user count is zero and
494  * the list of children is empty, prepare cpuset path in a kmalloc'd
495  * buffer, to be returned via ppathbuf, so that the caller can invoke
496  * cpuset_release_agent() with it later on, once manage_sem is dropped.
497  * Call here with manage_sem held.
498  *
499  * This check_for_release() routine is responsible for kmalloc'ing
500  * pathbuf.  The above cpuset_release_agent() is responsible for
501  * kfree'ing pathbuf.  The caller of these routines is responsible
502  * for providing a pathbuf pointer, initialized to NULL, then
503  * calling check_for_release() with manage_sem held and the address
504  * of the pathbuf pointer, then dropping manage_sem, then calling
505  * cpuset_release_agent() with pathbuf, as set by check_for_release().
506  */
507
508 static void check_for_release(struct cpuset *cs, char **ppathbuf)
509 {
510         if (notify_on_release(cs) && atomic_read(&cs->count) == 0 &&
511             list_empty(&cs->children)) {
512                 char *buf;
513
514                 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
515                 if (!buf)
516                         return;
517                 if (cpuset_path(cs, buf, PAGE_SIZE) < 0)
518                         kfree(buf);
519                 else
520                         *ppathbuf = buf;
521         }
522 }
523
524 /*
525  * Return in *pmask the portion of a cpusets's cpus_allowed that
526  * are online.  If none are online, walk up the cpuset hierarchy
527  * until we find one that does have some online cpus.  If we get
528  * all the way to the top and still haven't found any online cpus,
529  * return cpu_online_map.  Or if passed a NULL cs from an exit'ing
530  * task, return cpu_online_map.
531  *
532  * One way or another, we guarantee to return some non-empty subset
533  * of cpu_online_map.
534  *
535  * Call with callback_sem held.
536  */
537
538 static void guarantee_online_cpus(const struct cpuset *cs, cpumask_t *pmask)
539 {
540         while (cs && !cpus_intersects(cs->cpus_allowed, cpu_online_map))
541                 cs = cs->parent;
542         if (cs)
543                 cpus_and(*pmask, cs->cpus_allowed, cpu_online_map);
544         else
545                 *pmask = cpu_online_map;
546         BUG_ON(!cpus_intersects(*pmask, cpu_online_map));
547 }
548
549 /*
550  * Return in *pmask the portion of a cpusets's mems_allowed that
551  * are online.  If none are online, walk up the cpuset hierarchy
552  * until we find one that does have some online mems.  If we get
553  * all the way to the top and still haven't found any online mems,
554  * return node_online_map.
555  *
556  * One way or another, we guarantee to return some non-empty subset
557  * of node_online_map.
558  *
559  * Call with callback_sem held.
560  */
561
562 static void guarantee_online_mems(const struct cpuset *cs, nodemask_t *pmask)
563 {
564         while (cs && !nodes_intersects(cs->mems_allowed, node_online_map))
565                 cs = cs->parent;
566         if (cs)
567                 nodes_and(*pmask, cs->mems_allowed, node_online_map);
568         else
569                 *pmask = node_online_map;
570         BUG_ON(!nodes_intersects(*pmask, node_online_map));
571 }
572
573 /*
574  * Refresh current tasks mems_allowed and mems_generation from current
575  * tasks cpuset.
576  *
577  * Call without callback_sem or task_lock() held.  May be called with
578  * or without manage_sem held.  Will acquire task_lock() and might
579  * acquire callback_sem during call.
580  *
581  * The task_lock() is required to dereference current->cpuset safely.
582  * Without it, we could pick up the pointer value of current->cpuset
583  * in one instruction, and then attach_task could give us a different
584  * cpuset, and then the cpuset we had could be removed and freed,
585  * and then on our next instruction, we could dereference a no longer
586  * valid cpuset pointer to get its mems_generation field.
587  *
588  * This routine is needed to update the per-task mems_allowed data,
589  * within the tasks context, when it is trying to allocate memory
590  * (in various mm/mempolicy.c routines) and notices that some other
591  * task has been modifying its cpuset.
592  */
593
594 static void refresh_mems(void)
595 {
596         int my_cpusets_mem_gen;
597
598         task_lock(current);
599         my_cpusets_mem_gen = current->cpuset->mems_generation;
600         task_unlock(current);
601
602         if (current->cpuset_mems_generation != my_cpusets_mem_gen) {
603                 struct cpuset *cs;
604                 nodemask_t oldmem = current->mems_allowed;
605
606                 down(&callback_sem);
607                 task_lock(current);
608                 cs = current->cpuset;
609                 guarantee_online_mems(cs, &current->mems_allowed);
610                 current->cpuset_mems_generation = cs->mems_generation;
611                 task_unlock(current);
612                 up(&callback_sem);
613                 if (!nodes_equal(oldmem, current->mems_allowed))
614                         numa_policy_rebind(&oldmem, &current->mems_allowed);
615         }
616 }
617
618 /*
619  * is_cpuset_subset(p, q) - Is cpuset p a subset of cpuset q?
620  *
621  * One cpuset is a subset of another if all its allowed CPUs and
622  * Memory Nodes are a subset of the other, and its exclusive flags
623  * are only set if the other's are set.  Call holding manage_sem.
624  */
625
626 static int is_cpuset_subset(const struct cpuset *p, const struct cpuset *q)
627 {
628         return  cpus_subset(p->cpus_allowed, q->cpus_allowed) &&
629                 nodes_subset(p->mems_allowed, q->mems_allowed) &&
630                 is_cpu_exclusive(p) <= is_cpu_exclusive(q) &&
631                 is_mem_exclusive(p) <= is_mem_exclusive(q);
632 }
633
634 /*
635  * validate_change() - Used to validate that any proposed cpuset change
636  *                     follows the structural rules for cpusets.
637  *
638  * If we replaced the flag and mask values of the current cpuset
639  * (cur) with those values in the trial cpuset (trial), would
640  * our various subset and exclusive rules still be valid?  Presumes
641  * manage_sem held.
642  *
643  * 'cur' is the address of an actual, in-use cpuset.  Operations
644  * such as list traversal that depend on the actual address of the
645  * cpuset in the list must use cur below, not trial.
646  *
647  * 'trial' is the address of bulk structure copy of cur, with
648  * perhaps one or more of the fields cpus_allowed, mems_allowed,
649  * or flags changed to new, trial values.
650  *
651  * Return 0 if valid, -errno if not.
652  */
653
654 static int validate_change(const struct cpuset *cur, const struct cpuset *trial)
655 {
656         struct cpuset *c, *par;
657
658         /* Each of our child cpusets must be a subset of us */
659         list_for_each_entry(c, &cur->children, sibling) {
660                 if (!is_cpuset_subset(c, trial))
661                         return -EBUSY;
662         }
663
664         /* Remaining checks don't apply to root cpuset */
665         if ((par = cur->parent) == NULL)
666                 return 0;
667
668         /* We must be a subset of our parent cpuset */
669         if (!is_cpuset_subset(trial, par))
670                 return -EACCES;
671
672         /* If either I or some sibling (!= me) is exclusive, we can't overlap */
673         list_for_each_entry(c, &par->children, sibling) {
674                 if ((is_cpu_exclusive(trial) || is_cpu_exclusive(c)) &&
675                     c != cur &&
676                     cpus_intersects(trial->cpus_allowed, c->cpus_allowed))
677                         return -EINVAL;
678                 if ((is_mem_exclusive(trial) || is_mem_exclusive(c)) &&
679                     c != cur &&
680                     nodes_intersects(trial->mems_allowed, c->mems_allowed))
681                         return -EINVAL;
682         }
683
684         return 0;
685 }
686
687 /*
688  * For a given cpuset cur, partition the system as follows
689  * a. All cpus in the parent cpuset's cpus_allowed that are not part of any
690  *    exclusive child cpusets
691  * b. All cpus in the current cpuset's cpus_allowed that are not part of any
692  *    exclusive child cpusets
693  * Build these two partitions by calling partition_sched_domains
694  *
695  * Call with manage_sem held.  May nest a call to the
696  * lock_cpu_hotplug()/unlock_cpu_hotplug() pair.
697  */
698
699 static void update_cpu_domains(struct cpuset *cur)
700 {
701         struct cpuset *c, *par = cur->parent;
702         cpumask_t pspan, cspan;
703
704         if (par == NULL || cpus_empty(cur->cpus_allowed))
705                 return;
706
707         /*
708          * Get all cpus from parent's cpus_allowed not part of exclusive
709          * children
710          */
711         pspan = par->cpus_allowed;
712         list_for_each_entry(c, &par->children, sibling) {
713                 if (is_cpu_exclusive(c))
714                         cpus_andnot(pspan, pspan, c->cpus_allowed);
715         }
716         if (is_removed(cur) || !is_cpu_exclusive(cur)) {
717                 cpus_or(pspan, pspan, cur->cpus_allowed);
718                 if (cpus_equal(pspan, cur->cpus_allowed))
719                         return;
720                 cspan = CPU_MASK_NONE;
721         } else {
722                 if (cpus_empty(pspan))
723                         return;
724                 cspan = cur->cpus_allowed;
725                 /*
726                  * Get all cpus from current cpuset's cpus_allowed not part
727                  * of exclusive children
728                  */
729                 list_for_each_entry(c, &cur->children, sibling) {
730                         if (is_cpu_exclusive(c))
731                                 cpus_andnot(cspan, cspan, c->cpus_allowed);
732                 }
733         }
734
735         lock_cpu_hotplug();
736         partition_sched_domains(&pspan, &cspan);
737         unlock_cpu_hotplug();
738 }
739
740 /*
741  * Call with manage_sem held.  May take callback_sem during call.
742  */
743
744 static int update_cpumask(struct cpuset *cs, char *buf)
745 {
746         struct cpuset trialcs;
747         int retval, cpus_unchanged;
748
749         trialcs = *cs;
750         retval = cpulist_parse(buf, trialcs.cpus_allowed);
751         if (retval < 0)
752                 return retval;
753         cpus_and(trialcs.cpus_allowed, trialcs.cpus_allowed, cpu_online_map);
754         if (cpus_empty(trialcs.cpus_allowed))
755                 return -ENOSPC;
756         retval = validate_change(cs, &trialcs);
757         if (retval < 0)
758                 return retval;
759         cpus_unchanged = cpus_equal(cs->cpus_allowed, trialcs.cpus_allowed);
760         down(&callback_sem);
761         cs->cpus_allowed = trialcs.cpus_allowed;
762         up(&callback_sem);
763         if (is_cpu_exclusive(cs) && !cpus_unchanged)
764                 update_cpu_domains(cs);
765         return 0;
766 }
767
768 /*
769  * Call with manage_sem held.  May take callback_sem during call.
770  */
771
772 static int update_nodemask(struct cpuset *cs, char *buf)
773 {
774         struct cpuset trialcs;
775         int retval;
776
777         trialcs = *cs;
778         retval = nodelist_parse(buf, trialcs.mems_allowed);
779         if (retval < 0)
780                 return retval;
781         nodes_and(trialcs.mems_allowed, trialcs.mems_allowed, node_online_map);
782         if (nodes_empty(trialcs.mems_allowed))
783                 return -ENOSPC;
784         retval = validate_change(cs, &trialcs);
785         if (retval == 0) {
786                 down(&callback_sem);
787                 cs->mems_allowed = trialcs.mems_allowed;
788                 atomic_inc(&cpuset_mems_generation);
789                 cs->mems_generation = atomic_read(&cpuset_mems_generation);
790                 up(&callback_sem);
791         }
792         return retval;
793 }
794
795 /*
796  * update_flag - read a 0 or a 1 in a file and update associated flag
797  * bit: the bit to update (CS_CPU_EXCLUSIVE, CS_MEM_EXCLUSIVE,
798  *                                              CS_NOTIFY_ON_RELEASE)
799  * cs:  the cpuset to update
800  * buf: the buffer where we read the 0 or 1
801  *
802  * Call with manage_sem held.
803  */
804
805 static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs, char *buf)
806 {
807         int turning_on;
808         struct cpuset trialcs;
809         int err, cpu_exclusive_changed;
810
811         turning_on = (simple_strtoul(buf, NULL, 10) != 0);
812
813         trialcs = *cs;
814         if (turning_on)
815                 set_bit(bit, &trialcs.flags);
816         else
817                 clear_bit(bit, &trialcs.flags);
818
819         err = validate_change(cs, &trialcs);
820         if (err < 0)
821                 return err;
822         cpu_exclusive_changed =
823                 (is_cpu_exclusive(cs) != is_cpu_exclusive(&trialcs));
824         down(&callback_sem);
825         if (turning_on)
826                 set_bit(bit, &cs->flags);
827         else
828                 clear_bit(bit, &cs->flags);
829         up(&callback_sem);
830
831         if (cpu_exclusive_changed)
832                 update_cpu_domains(cs);
833         return 0;
834 }
835
836 /*
837  * Attack task specified by pid in 'pidbuf' to cpuset 'cs', possibly
838  * writing the path of the old cpuset in 'ppathbuf' if it needs to be
839  * notified on release.
840  *
841  * Call holding manage_sem.  May take callback_sem and task_lock of
842  * the task 'pid' during call.
843  */
844
845 static int attach_task(struct cpuset *cs, char *pidbuf, char **ppathbuf)
846 {
847         pid_t pid;
848         struct task_struct *tsk;
849         struct cpuset *oldcs;
850         cpumask_t cpus;
851
852         if (sscanf(pidbuf, "%d", &pid) != 1)
853                 return -EIO;
854         if (cpus_empty(cs->cpus_allowed) || nodes_empty(cs->mems_allowed))
855                 return -ENOSPC;
856
857         if (pid) {
858                 read_lock(&tasklist_lock);
859
860                 tsk = find_task_by_pid(pid);
861                 if (!tsk || tsk->flags & PF_EXITING) {
862                         read_unlock(&tasklist_lock);
863                         return -ESRCH;
864                 }
865
866                 get_task_struct(tsk);
867                 read_unlock(&tasklist_lock);
868
869                 if ((current->euid) && (current->euid != tsk->uid)
870                     && (current->euid != tsk->suid)) {
871                         put_task_struct(tsk);
872                         return -EACCES;
873                 }
874         } else {
875                 tsk = current;
876                 get_task_struct(tsk);
877         }
878
879         down(&callback_sem);
880
881         task_lock(tsk);
882         oldcs = tsk->cpuset;
883         if (!oldcs) {
884                 task_unlock(tsk);
885                 up(&callback_sem);
886                 put_task_struct(tsk);
887                 return -ESRCH;
888         }
889         atomic_inc(&cs->count);
890         tsk->cpuset = cs;
891         task_unlock(tsk);
892
893         guarantee_online_cpus(cs, &cpus);
894         set_cpus_allowed(tsk, cpus);
895
896         up(&callback_sem);
897         put_task_struct(tsk);
898         if (atomic_dec_and_test(&oldcs->count))
899                 check_for_release(oldcs, ppathbuf);
900         return 0;
901 }
902
903 /* The various types of files and directories in a cpuset file system */
904
905 typedef enum {
906         FILE_ROOT,
907         FILE_DIR,
908         FILE_CPULIST,
909         FILE_MEMLIST,
910         FILE_CPU_EXCLUSIVE,
911         FILE_MEM_EXCLUSIVE,
912         FILE_NOTIFY_ON_RELEASE,
913         FILE_TASKLIST,
914 } cpuset_filetype_t;
915
916 static ssize_t cpuset_common_file_write(struct file *file, const char __user *userbuf,
917                                         size_t nbytes, loff_t *unused_ppos)
918 {
919         struct cpuset *cs = __d_cs(file->f_dentry->d_parent);
920         struct cftype *cft = __d_cft(file->f_dentry);
921         cpuset_filetype_t type = cft->private;
922         char *buffer;
923         char *pathbuf = NULL;
924         int retval = 0;
925
926         /* Crude upper limit on largest legitimate cpulist user might write. */
927         if (nbytes > 100 + 6 * NR_CPUS)
928                 return -E2BIG;
929
930         /* +1 for nul-terminator */
931         if ((buffer = kmalloc(nbytes + 1, GFP_KERNEL)) == 0)
932                 return -ENOMEM;
933
934         if (copy_from_user(buffer, userbuf, nbytes)) {
935                 retval = -EFAULT;
936                 goto out1;
937         }
938         buffer[nbytes] = 0;     /* nul-terminate */
939
940         down(&manage_sem);
941
942         if (is_removed(cs)) {
943                 retval = -ENODEV;
944                 goto out2;
945         }
946
947         switch (type) {
948         case FILE_CPULIST:
949                 retval = update_cpumask(cs, buffer);
950                 break;
951         case FILE_MEMLIST:
952                 retval = update_nodemask(cs, buffer);
953                 break;
954         case FILE_CPU_EXCLUSIVE:
955                 retval = update_flag(CS_CPU_EXCLUSIVE, cs, buffer);
956                 break;
957         case FILE_MEM_EXCLUSIVE:
958                 retval = update_flag(CS_MEM_EXCLUSIVE, cs, buffer);
959                 break;
960         case FILE_NOTIFY_ON_RELEASE:
961                 retval = update_flag(CS_NOTIFY_ON_RELEASE, cs, buffer);
962                 break;
963         case FILE_TASKLIST:
964                 retval = attach_task(cs, buffer, &pathbuf);
965                 break;
966         default:
967                 retval = -EINVAL;
968                 goto out2;
969         }
970
971         if (retval == 0)
972                 retval = nbytes;
973 out2:
974         up(&manage_sem);
975         cpuset_release_agent(pathbuf);
976 out1:
977         kfree(buffer);
978         return retval;
979 }
980
981 static ssize_t cpuset_file_write(struct file *file, const char __user *buf,
982                                                 size_t nbytes, loff_t *ppos)
983 {
984         ssize_t retval = 0;
985         struct cftype *cft = __d_cft(file->f_dentry);
986         if (!cft)
987                 return -ENODEV;
988
989         /* special function ? */
990         if (cft->write)
991                 retval = cft->write(file, buf, nbytes, ppos);
992         else
993                 retval = cpuset_common_file_write(file, buf, nbytes, ppos);
994
995         return retval;
996 }
997
998 /*
999  * These ascii lists should be read in a single call, by using a user
1000  * buffer large enough to hold the entire map.  If read in smaller
1001  * chunks, there is no guarantee of atomicity.  Since the display format
1002  * used, list of ranges of sequential numbers, is variable length,
1003  * and since these maps can change value dynamically, one could read
1004  * gibberish by doing partial reads while a list was changing.
1005  * A single large read to a buffer that crosses a page boundary is
1006  * ok, because the result being copied to user land is not recomputed
1007  * across a page fault.
1008  */
1009
1010 static int cpuset_sprintf_cpulist(char *page, struct cpuset *cs)
1011 {
1012         cpumask_t mask;
1013
1014         down(&callback_sem);
1015         mask = cs->cpus_allowed;
1016         up(&callback_sem);
1017
1018         return cpulist_scnprintf(page, PAGE_SIZE, mask);
1019 }
1020
1021 static int cpuset_sprintf_memlist(char *page, struct cpuset *cs)
1022 {
1023         nodemask_t mask;
1024
1025         down(&callback_sem);
1026         mask = cs->mems_allowed;
1027         up(&callback_sem);
1028
1029         return nodelist_scnprintf(page, PAGE_SIZE, mask);
1030 }
1031
1032 static ssize_t cpuset_common_file_read(struct file *file, char __user *buf,
1033                                 size_t nbytes, loff_t *ppos)
1034 {
1035         struct cftype *cft = __d_cft(file->f_dentry);
1036         struct cpuset *cs = __d_cs(file->f_dentry->d_parent);
1037         cpuset_filetype_t type = cft->private;
1038         char *page;
1039         ssize_t retval = 0;
1040         char *s;
1041
1042         if (!(page = (char *)__get_free_page(GFP_KERNEL)))
1043                 return -ENOMEM;
1044
1045         s = page;
1046
1047         switch (type) {
1048         case FILE_CPULIST:
1049                 s += cpuset_sprintf_cpulist(s, cs);
1050                 break;
1051         case FILE_MEMLIST:
1052                 s += cpuset_sprintf_memlist(s, cs);
1053                 break;
1054         case FILE_CPU_EXCLUSIVE:
1055                 *s++ = is_cpu_exclusive(cs) ? '1' : '0';
1056                 break;
1057         case FILE_MEM_EXCLUSIVE:
1058                 *s++ = is_mem_exclusive(cs) ? '1' : '0';
1059                 break;
1060         case FILE_NOTIFY_ON_RELEASE:
1061                 *s++ = notify_on_release(cs) ? '1' : '0';
1062                 break;
1063         default:
1064                 retval = -EINVAL;
1065                 goto out;
1066         }
1067         *s++ = '\n';
1068
1069         retval = simple_read_from_buffer(buf, nbytes, ppos, page, s - page);
1070 out:
1071         free_page((unsigned long)page);
1072         return retval;
1073 }
1074
1075 static ssize_t cpuset_file_read(struct file *file, char __user *buf, size_t nbytes,
1076                                                                 loff_t *ppos)
1077 {
1078         ssize_t retval = 0;
1079         struct cftype *cft = __d_cft(file->f_dentry);
1080         if (!cft)
1081                 return -ENODEV;
1082
1083         /* special function ? */
1084         if (cft->read)
1085                 retval = cft->read(file, buf, nbytes, ppos);
1086         else
1087                 retval = cpuset_common_file_read(file, buf, nbytes, ppos);
1088
1089         return retval;
1090 }
1091
1092 static int cpuset_file_open(struct inode *inode, struct file *file)
1093 {
1094         int err;
1095         struct cftype *cft;
1096
1097         err = generic_file_open(inode, file);
1098         if (err)
1099                 return err;
1100
1101         cft = __d_cft(file->f_dentry);
1102         if (!cft)
1103                 return -ENODEV;
1104         if (cft->open)
1105                 err = cft->open(inode, file);
1106         else
1107                 err = 0;
1108
1109         return err;
1110 }
1111
1112 static int cpuset_file_release(struct inode *inode, struct file *file)
1113 {
1114         struct cftype *cft = __d_cft(file->f_dentry);
1115         if (cft->release)
1116                 return cft->release(inode, file);
1117         return 0;
1118 }
1119
1120 /*
1121  * cpuset_rename - Only allow simple rename of directories in place.
1122  */
1123 static int cpuset_rename(struct inode *old_dir, struct dentry *old_dentry,
1124                   struct inode *new_dir, struct dentry *new_dentry)
1125 {
1126         if (!S_ISDIR(old_dentry->d_inode->i_mode))
1127                 return -ENOTDIR;
1128         if (new_dentry->d_inode)
1129                 return -EEXIST;
1130         if (old_dir != new_dir)
1131                 return -EIO;
1132         return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1133 }
1134
1135 static struct file_operations cpuset_file_operations = {
1136         .read = cpuset_file_read,
1137         .write = cpuset_file_write,
1138         .llseek = generic_file_llseek,
1139         .open = cpuset_file_open,
1140         .release = cpuset_file_release,
1141 };
1142
1143 static struct inode_operations cpuset_dir_inode_operations = {
1144         .lookup = simple_lookup,
1145         .mkdir = cpuset_mkdir,
1146         .rmdir = cpuset_rmdir,
1147         .rename = cpuset_rename,
1148 };
1149
1150 static int cpuset_create_file(struct dentry *dentry, int mode)
1151 {
1152         struct inode *inode;
1153
1154         if (!dentry)
1155                 return -ENOENT;
1156         if (dentry->d_inode)
1157                 return -EEXIST;
1158
1159         inode = cpuset_new_inode(mode);
1160         if (!inode)
1161                 return -ENOMEM;
1162
1163         if (S_ISDIR(mode)) {
1164                 inode->i_op = &cpuset_dir_inode_operations;
1165                 inode->i_fop = &simple_dir_operations;
1166
1167                 /* start off with i_nlink == 2 (for "." entry) */
1168                 inode->i_nlink++;
1169         } else if (S_ISREG(mode)) {
1170                 inode->i_size = 0;
1171                 inode->i_fop = &cpuset_file_operations;
1172         }
1173
1174         d_instantiate(dentry, inode);
1175         dget(dentry);   /* Extra count - pin the dentry in core */
1176         return 0;
1177 }
1178
1179 /*
1180  *      cpuset_create_dir - create a directory for an object.
1181  *      cs:     the cpuset we create the directory for.
1182  *              It must have a valid ->parent field
1183  *              And we are going to fill its ->dentry field.
1184  *      name:   The name to give to the cpuset directory. Will be copied.
1185  *      mode:   mode to set on new directory.
1186  */
1187
1188 static int cpuset_create_dir(struct cpuset *cs, const char *name, int mode)
1189 {
1190         struct dentry *dentry = NULL;
1191         struct dentry *parent;
1192         int error = 0;
1193
1194         parent = cs->parent->dentry;
1195         dentry = cpuset_get_dentry(parent, name);
1196         if (IS_ERR(dentry))
1197                 return PTR_ERR(dentry);
1198         error = cpuset_create_file(dentry, S_IFDIR | mode);
1199         if (!error) {
1200                 dentry->d_fsdata = cs;
1201                 parent->d_inode->i_nlink++;
1202                 cs->dentry = dentry;
1203         }
1204         dput(dentry);
1205
1206         return error;
1207 }
1208
1209 static int cpuset_add_file(struct dentry *dir, const struct cftype *cft)
1210 {
1211         struct dentry *dentry;
1212         int error;
1213
1214         down(&dir->d_inode->i_sem);
1215         dentry = cpuset_get_dentry(dir, cft->name);
1216         if (!IS_ERR(dentry)) {
1217                 error = cpuset_create_file(dentry, 0644 | S_IFREG);
1218                 if (!error)
1219                         dentry->d_fsdata = (void *)cft;
1220                 dput(dentry);
1221         } else
1222                 error = PTR_ERR(dentry);
1223         up(&dir->d_inode->i_sem);
1224         return error;
1225 }
1226
1227 /*
1228  * Stuff for reading the 'tasks' file.
1229  *
1230  * Reading this file can return large amounts of data if a cpuset has
1231  * *lots* of attached tasks. So it may need several calls to read(),
1232  * but we cannot guarantee that the information we produce is correct
1233  * unless we produce it entirely atomically.
1234  *
1235  * Upon tasks file open(), a struct ctr_struct is allocated, that
1236  * will have a pointer to an array (also allocated here).  The struct
1237  * ctr_struct * is stored in file->private_data.  Its resources will
1238  * be freed by release() when the file is closed.  The array is used
1239  * to sprintf the PIDs and then used by read().
1240  */
1241
1242 /* cpusets_tasks_read array */
1243
1244 struct ctr_struct {
1245         char *buf;
1246         int bufsz;
1247 };
1248
1249 /*
1250  * Load into 'pidarray' up to 'npids' of the tasks using cpuset 'cs'.
1251  * Return actual number of pids loaded.  No need to task_lock(p)
1252  * when reading out p->cpuset, as we don't really care if it changes
1253  * on the next cycle, and we are not going to try to dereference it.
1254  */
1255 static inline int pid_array_load(pid_t *pidarray, int npids, struct cpuset *cs)
1256 {
1257         int n = 0;
1258         struct task_struct *g, *p;
1259
1260         read_lock(&tasklist_lock);
1261
1262         do_each_thread(g, p) {
1263                 if (p->cpuset == cs) {
1264                         pidarray[n++] = p->pid;
1265                         if (unlikely(n == npids))
1266                                 goto array_full;
1267                 }
1268         } while_each_thread(g, p);
1269
1270 array_full:
1271         read_unlock(&tasklist_lock);
1272         return n;
1273 }
1274
1275 static int cmppid(const void *a, const void *b)
1276 {
1277         return *(pid_t *)a - *(pid_t *)b;
1278 }
1279
1280 /*
1281  * Convert array 'a' of 'npids' pid_t's to a string of newline separated
1282  * decimal pids in 'buf'.  Don't write more than 'sz' chars, but return
1283  * count 'cnt' of how many chars would be written if buf were large enough.
1284  */
1285 static int pid_array_to_buf(char *buf, int sz, pid_t *a, int npids)
1286 {
1287         int cnt = 0;
1288         int i;
1289
1290         for (i = 0; i < npids; i++)
1291                 cnt += snprintf(buf + cnt, max(sz - cnt, 0), "%d\n", a[i]);
1292         return cnt;
1293 }
1294
1295 /*
1296  * Handle an open on 'tasks' file.  Prepare a buffer listing the
1297  * process id's of tasks currently attached to the cpuset being opened.
1298  *
1299  * Does not require any specific cpuset semaphores, and does not take any.
1300  */
1301 static int cpuset_tasks_open(struct inode *unused, struct file *file)
1302 {
1303         struct cpuset *cs = __d_cs(file->f_dentry->d_parent);
1304         struct ctr_struct *ctr;
1305         pid_t *pidarray;
1306         int npids;
1307         char c;
1308
1309         if (!(file->f_mode & FMODE_READ))
1310                 return 0;
1311
1312         ctr = kmalloc(sizeof(*ctr), GFP_KERNEL);
1313         if (!ctr)
1314                 goto err0;
1315
1316         /*
1317          * If cpuset gets more users after we read count, we won't have
1318          * enough space - tough.  This race is indistinguishable to the
1319          * caller from the case that the additional cpuset users didn't
1320          * show up until sometime later on.
1321          */
1322         npids = atomic_read(&cs->count);
1323         pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
1324         if (!pidarray)
1325                 goto err1;
1326
1327         npids = pid_array_load(pidarray, npids, cs);
1328         sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
1329
1330         /* Call pid_array_to_buf() twice, first just to get bufsz */
1331         ctr->bufsz = pid_array_to_buf(&c, sizeof(c), pidarray, npids) + 1;
1332         ctr->buf = kmalloc(ctr->bufsz, GFP_KERNEL);
1333         if (!ctr->buf)
1334                 goto err2;
1335         ctr->bufsz = pid_array_to_buf(ctr->buf, ctr->bufsz, pidarray, npids);
1336
1337         kfree(pidarray);
1338         file->private_data = ctr;
1339         return 0;
1340
1341 err2:
1342         kfree(pidarray);
1343 err1:
1344         kfree(ctr);
1345 err0:
1346         return -ENOMEM;
1347 }
1348
1349 static ssize_t cpuset_tasks_read(struct file *file, char __user *buf,
1350                                                 size_t nbytes, loff_t *ppos)
1351 {
1352         struct ctr_struct *ctr = file->private_data;
1353
1354         if (*ppos + nbytes > ctr->bufsz)
1355                 nbytes = ctr->bufsz - *ppos;
1356         if (copy_to_user(buf, ctr->buf + *ppos, nbytes))
1357                 return -EFAULT;
1358         *ppos += nbytes;
1359         return nbytes;
1360 }
1361
1362 static int cpuset_tasks_release(struct inode *unused_inode, struct file *file)
1363 {
1364         struct ctr_struct *ctr;
1365
1366         if (file->f_mode & FMODE_READ) {
1367                 ctr = file->private_data;
1368                 kfree(ctr->buf);
1369                 kfree(ctr);
1370         }
1371         return 0;
1372 }
1373
1374 /*
1375  * for the common functions, 'private' gives the type of file
1376  */
1377
1378 static struct cftype cft_tasks = {
1379         .name = "tasks",
1380         .open = cpuset_tasks_open,
1381         .read = cpuset_tasks_read,
1382         .release = cpuset_tasks_release,
1383         .private = FILE_TASKLIST,
1384 };
1385
1386 static struct cftype cft_cpus = {
1387         .name = "cpus",
1388         .private = FILE_CPULIST,
1389 };
1390
1391 static struct cftype cft_mems = {
1392         .name = "mems",
1393         .private = FILE_MEMLIST,
1394 };
1395
1396 static struct cftype cft_cpu_exclusive = {
1397         .name = "cpu_exclusive",
1398         .private = FILE_CPU_EXCLUSIVE,
1399 };
1400
1401 static struct cftype cft_mem_exclusive = {
1402         .name = "mem_exclusive",
1403         .private = FILE_MEM_EXCLUSIVE,
1404 };
1405
1406 static struct cftype cft_notify_on_release = {
1407         .name = "notify_on_release",
1408         .private = FILE_NOTIFY_ON_RELEASE,
1409 };
1410
1411 static int cpuset_populate_dir(struct dentry *cs_dentry)
1412 {
1413         int err;
1414
1415         if ((err = cpuset_add_file(cs_dentry, &cft_cpus)) < 0)
1416                 return err;
1417         if ((err = cpuset_add_file(cs_dentry, &cft_mems)) < 0)
1418                 return err;
1419         if ((err = cpuset_add_file(cs_dentry, &cft_cpu_exclusive)) < 0)
1420                 return err;
1421         if ((err = cpuset_add_file(cs_dentry, &cft_mem_exclusive)) < 0)
1422                 return err;
1423         if ((err = cpuset_add_file(cs_dentry, &cft_notify_on_release)) < 0)
1424                 return err;
1425         if ((err = cpuset_add_file(cs_dentry, &cft_tasks)) < 0)
1426                 return err;
1427         return 0;
1428 }
1429
1430 /*
1431  *      cpuset_create - create a cpuset
1432  *      parent: cpuset that will be parent of the new cpuset.
1433  *      name:           name of the new cpuset. Will be strcpy'ed.
1434  *      mode:           mode to set on new inode
1435  *
1436  *      Must be called with the semaphore on the parent inode held
1437  */
1438
1439 static long cpuset_create(struct cpuset *parent, const char *name, int mode)
1440 {
1441         struct cpuset *cs;
1442         int err;
1443
1444         cs = kmalloc(sizeof(*cs), GFP_KERNEL);
1445         if (!cs)
1446                 return -ENOMEM;
1447
1448         down(&manage_sem);
1449         refresh_mems();
1450         cs->flags = 0;
1451         if (notify_on_release(parent))
1452                 set_bit(CS_NOTIFY_ON_RELEASE, &cs->flags);
1453         cs->cpus_allowed = CPU_MASK_NONE;
1454         cs->mems_allowed = NODE_MASK_NONE;
1455         atomic_set(&cs->count, 0);
1456         INIT_LIST_HEAD(&cs->sibling);
1457         INIT_LIST_HEAD(&cs->children);
1458         atomic_inc(&cpuset_mems_generation);
1459         cs->mems_generation = atomic_read(&cpuset_mems_generation);
1460
1461         cs->parent = parent;
1462
1463         down(&callback_sem);
1464         list_add(&cs->sibling, &cs->parent->children);
1465         up(&callback_sem);
1466
1467         err = cpuset_create_dir(cs, name, mode);
1468         if (err < 0)
1469                 goto err;
1470
1471         /*
1472          * Release manage_sem before cpuset_populate_dir() because it
1473          * will down() this new directory's i_sem and if we race with
1474          * another mkdir, we might deadlock.
1475          */
1476         up(&manage_sem);
1477
1478         err = cpuset_populate_dir(cs->dentry);
1479         /* If err < 0, we have a half-filled directory - oh well ;) */
1480         return 0;
1481 err:
1482         list_del(&cs->sibling);
1483         up(&manage_sem);
1484         kfree(cs);
1485         return err;
1486 }
1487
1488 static int cpuset_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1489 {
1490         struct cpuset *c_parent = dentry->d_parent->d_fsdata;
1491
1492         /* the vfs holds inode->i_sem already */
1493         return cpuset_create(c_parent, dentry->d_name.name, mode | S_IFDIR);
1494 }
1495
1496 static int cpuset_rmdir(struct inode *unused_dir, struct dentry *dentry)
1497 {
1498         struct cpuset *cs = dentry->d_fsdata;
1499         struct dentry *d;
1500         struct cpuset *parent;
1501         char *pathbuf = NULL;
1502
1503         /* the vfs holds both inode->i_sem already */
1504
1505         down(&manage_sem);
1506         refresh_mems();
1507         if (atomic_read(&cs->count) > 0) {
1508                 up(&manage_sem);
1509                 return -EBUSY;
1510         }
1511         if (!list_empty(&cs->children)) {
1512                 up(&manage_sem);
1513                 return -EBUSY;
1514         }
1515         parent = cs->parent;
1516         down(&callback_sem);
1517         set_bit(CS_REMOVED, &cs->flags);
1518         if (is_cpu_exclusive(cs))
1519                 update_cpu_domains(cs);
1520         list_del(&cs->sibling); /* delete my sibling from parent->children */
1521         spin_lock(&cs->dentry->d_lock);
1522         d = dget(cs->dentry);
1523         cs->dentry = NULL;
1524         spin_unlock(&d->d_lock);
1525         cpuset_d_remove_dir(d);
1526         dput(d);
1527         up(&callback_sem);
1528         if (list_empty(&parent->children))
1529                 check_for_release(parent, &pathbuf);
1530         up(&manage_sem);
1531         cpuset_release_agent(pathbuf);
1532         return 0;
1533 }
1534
1535 /**
1536  * cpuset_init - initialize cpusets at system boot
1537  *
1538  * Description: Initialize top_cpuset and the cpuset internal file system,
1539  **/
1540
1541 int __init cpuset_init(void)
1542 {
1543         struct dentry *root;
1544         int err;
1545
1546         top_cpuset.cpus_allowed = CPU_MASK_ALL;
1547         top_cpuset.mems_allowed = NODE_MASK_ALL;
1548
1549         atomic_inc(&cpuset_mems_generation);
1550         top_cpuset.mems_generation = atomic_read(&cpuset_mems_generation);
1551
1552         init_task.cpuset = &top_cpuset;
1553
1554         err = register_filesystem(&cpuset_fs_type);
1555         if (err < 0)
1556                 goto out;
1557         cpuset_mount = kern_mount(&cpuset_fs_type);
1558         if (IS_ERR(cpuset_mount)) {
1559                 printk(KERN_ERR "cpuset: could not mount!\n");
1560                 err = PTR_ERR(cpuset_mount);
1561                 cpuset_mount = NULL;
1562                 goto out;
1563         }
1564         root = cpuset_mount->mnt_sb->s_root;
1565         root->d_fsdata = &top_cpuset;
1566         root->d_inode->i_nlink++;
1567         top_cpuset.dentry = root;
1568         root->d_inode->i_op = &cpuset_dir_inode_operations;
1569         err = cpuset_populate_dir(root);
1570 out:
1571         return err;
1572 }
1573
1574 /**
1575  * cpuset_init_smp - initialize cpus_allowed
1576  *
1577  * Description: Finish top cpuset after cpu, node maps are initialized
1578  **/
1579
1580 void __init cpuset_init_smp(void)
1581 {
1582         top_cpuset.cpus_allowed = cpu_online_map;
1583         top_cpuset.mems_allowed = node_online_map;
1584 }
1585
1586 /**
1587  * cpuset_fork - attach newly forked task to its parents cpuset.
1588  * @tsk: pointer to task_struct of forking parent process.
1589  *
1590  * Description: A task inherits its parent's cpuset at fork().
1591  *
1592  * A pointer to the shared cpuset was automatically copied in fork.c
1593  * by dup_task_struct().  However, we ignore that copy, since it was
1594  * not made under the protection of task_lock(), so might no longer be
1595  * a valid cpuset pointer.  attach_task() might have already changed
1596  * current->cpuset, allowing the previously referenced cpuset to
1597  * be removed and freed.  Instead, we task_lock(current) and copy
1598  * its present value of current->cpuset for our freshly forked child.
1599  *
1600  * At the point that cpuset_fork() is called, 'current' is the parent
1601  * task, and the passed argument 'child' points to the child task.
1602  **/
1603
1604 void cpuset_fork(struct task_struct *child)
1605 {
1606         task_lock(current);
1607         child->cpuset = current->cpuset;
1608         atomic_inc(&child->cpuset->count);
1609         task_unlock(current);
1610 }
1611
1612 /**
1613  * cpuset_exit - detach cpuset from exiting task
1614  * @tsk: pointer to task_struct of exiting process
1615  *
1616  * Description: Detach cpuset from @tsk and release it.
1617  *
1618  * Note that cpusets marked notify_on_release force every task in
1619  * them to take the global manage_sem semaphore when exiting.
1620  * This could impact scaling on very large systems.  Be reluctant to
1621  * use notify_on_release cpusets where very high task exit scaling
1622  * is required on large systems.
1623  *
1624  * Don't even think about derefencing 'cs' after the cpuset use count
1625  * goes to zero, except inside a critical section guarded by manage_sem
1626  * or callback_sem.   Otherwise a zero cpuset use count is a license to
1627  * any other task to nuke the cpuset immediately, via cpuset_rmdir().
1628  *
1629  * This routine has to take manage_sem, not callback_sem, because
1630  * it is holding that semaphore while calling check_for_release(),
1631  * which calls kmalloc(), so can't be called holding callback__sem().
1632  *
1633  * We don't need to task_lock() this reference to tsk->cpuset,
1634  * because tsk is already marked PF_EXITING, so attach_task() won't
1635  * mess with it.
1636  **/
1637
1638 void cpuset_exit(struct task_struct *tsk)
1639 {
1640         struct cpuset *cs;
1641
1642         BUG_ON(!(tsk->flags & PF_EXITING));
1643
1644         cs = tsk->cpuset;
1645         tsk->cpuset = NULL;
1646
1647         if (notify_on_release(cs)) {
1648                 char *pathbuf = NULL;
1649
1650                 down(&manage_sem);
1651                 if (atomic_dec_and_test(&cs->count))
1652                         check_for_release(cs, &pathbuf);
1653                 up(&manage_sem);
1654                 cpuset_release_agent(pathbuf);
1655         } else {
1656                 atomic_dec(&cs->count);
1657         }
1658 }
1659
1660 /**
1661  * cpuset_cpus_allowed - return cpus_allowed mask from a tasks cpuset.
1662  * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
1663  *
1664  * Description: Returns the cpumask_t cpus_allowed of the cpuset
1665  * attached to the specified @tsk.  Guaranteed to return some non-empty
1666  * subset of cpu_online_map, even if this means going outside the
1667  * tasks cpuset.
1668  **/
1669
1670 cpumask_t cpuset_cpus_allowed(const struct task_struct *tsk)
1671 {
1672         cpumask_t mask;
1673
1674         down(&callback_sem);
1675         task_lock((struct task_struct *)tsk);
1676         guarantee_online_cpus(tsk->cpuset, &mask);
1677         task_unlock((struct task_struct *)tsk);
1678         up(&callback_sem);
1679
1680         return mask;
1681 }
1682
1683 void cpuset_init_current_mems_allowed(void)
1684 {
1685         current->mems_allowed = NODE_MASK_ALL;
1686 }
1687
1688 /**
1689  * cpuset_update_current_mems_allowed - update mems parameters to new values
1690  *
1691  * If the current tasks cpusets mems_allowed changed behind our backs,
1692  * update current->mems_allowed and mems_generation to the new value.
1693  * Do not call this routine if in_interrupt().
1694  *
1695  * Call without callback_sem or task_lock() held.  May be called
1696  * with or without manage_sem held.  Unless exiting, it will acquire
1697  * task_lock().  Also might acquire callback_sem during call to
1698  * refresh_mems().
1699  */
1700
1701 void cpuset_update_current_mems_allowed(void)
1702 {
1703         struct cpuset *cs;
1704         int need_to_refresh = 0;
1705
1706         task_lock(current);
1707         cs = current->cpuset;
1708         if (!cs)
1709                 goto done;
1710         if (current->cpuset_mems_generation != cs->mems_generation)
1711                 need_to_refresh = 1;
1712 done:
1713         task_unlock(current);
1714         if (need_to_refresh)
1715                 refresh_mems();
1716 }
1717
1718 /**
1719  * cpuset_restrict_to_mems_allowed - limit nodes to current mems_allowed
1720  * @nodes: pointer to a node bitmap that is and-ed with mems_allowed
1721  */
1722 void cpuset_restrict_to_mems_allowed(unsigned long *nodes)
1723 {
1724         bitmap_and(nodes, nodes, nodes_addr(current->mems_allowed),
1725                                                         MAX_NUMNODES);
1726 }
1727
1728 /**
1729  * cpuset_zonelist_valid_mems_allowed - check zonelist vs. curremt mems_allowed
1730  * @zl: the zonelist to be checked
1731  *
1732  * Are any of the nodes on zonelist zl allowed in current->mems_allowed?
1733  */
1734 int cpuset_zonelist_valid_mems_allowed(struct zonelist *zl)
1735 {
1736         int i;
1737
1738         for (i = 0; zl->zones[i]; i++) {
1739                 int nid = zl->zones[i]->zone_pgdat->node_id;
1740
1741                 if (node_isset(nid, current->mems_allowed))
1742                         return 1;
1743         }
1744         return 0;
1745 }
1746
1747 /*
1748  * nearest_exclusive_ancestor() - Returns the nearest mem_exclusive
1749  * ancestor to the specified cpuset.  Call holding callback_sem.
1750  * If no ancestor is mem_exclusive (an unusual configuration), then
1751  * returns the root cpuset.
1752  */
1753 static const struct cpuset *nearest_exclusive_ancestor(const struct cpuset *cs)
1754 {
1755         while (!is_mem_exclusive(cs) && cs->parent)
1756                 cs = cs->parent;
1757         return cs;
1758 }
1759
1760 /**
1761  * cpuset_zone_allowed - Can we allocate memory on zone z's memory node?
1762  * @z: is this zone on an allowed node?
1763  * @gfp_mask: memory allocation flags (we use __GFP_HARDWALL)
1764  *
1765  * If we're in interrupt, yes, we can always allocate.  If zone
1766  * z's node is in our tasks mems_allowed, yes.  If it's not a
1767  * __GFP_HARDWALL request and this zone's nodes is in the nearest
1768  * mem_exclusive cpuset ancestor to this tasks cpuset, yes.
1769  * Otherwise, no.
1770  *
1771  * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
1772  * and do not allow allocations outside the current tasks cpuset.
1773  * GFP_KERNEL allocations are not so marked, so can escape to the
1774  * nearest mem_exclusive ancestor cpuset.
1775  *
1776  * Scanning up parent cpusets requires callback_sem.  The __alloc_pages()
1777  * routine only calls here with __GFP_HARDWALL bit _not_ set if
1778  * it's a GFP_KERNEL allocation, and all nodes in the current tasks
1779  * mems_allowed came up empty on the first pass over the zonelist.
1780  * So only GFP_KERNEL allocations, if all nodes in the cpuset are
1781  * short of memory, might require taking the callback_sem semaphore.
1782  *
1783  * The first loop over the zonelist in mm/page_alloc.c:__alloc_pages()
1784  * calls here with __GFP_HARDWALL always set in gfp_mask, enforcing
1785  * hardwall cpusets - no allocation on a node outside the cpuset is
1786  * allowed (unless in interrupt, of course).
1787  *
1788  * The second loop doesn't even call here for GFP_ATOMIC requests
1789  * (if the __alloc_pages() local variable 'wait' is set).  That check
1790  * and the checks below have the combined affect in the second loop of
1791  * the __alloc_pages() routine that:
1792  *      in_interrupt - any node ok (current task context irrelevant)
1793  *      GFP_ATOMIC   - any node ok
1794  *      GFP_KERNEL   - any node in enclosing mem_exclusive cpuset ok
1795  *      GFP_USER     - only nodes in current tasks mems allowed ok.
1796  **/
1797
1798 int cpuset_zone_allowed(struct zone *z, gfp_t gfp_mask)
1799 {
1800         int node;                       /* node that zone z is on */
1801         const struct cpuset *cs;        /* current cpuset ancestors */
1802         int allowed = 1;                /* is allocation in zone z allowed? */
1803
1804         if (in_interrupt())
1805                 return 1;
1806         node = z->zone_pgdat->node_id;
1807         if (node_isset(node, current->mems_allowed))
1808                 return 1;
1809         if (gfp_mask & __GFP_HARDWALL)  /* If hardwall request, stop here */
1810                 return 0;
1811
1812         /* Not hardwall and node outside mems_allowed: scan up cpusets */
1813         down(&callback_sem);
1814
1815         if (current->flags & PF_EXITING) /* Let dying task have memory */
1816                 return 1;
1817         task_lock(current);
1818         cs = nearest_exclusive_ancestor(current->cpuset);
1819         task_unlock(current);
1820
1821         allowed = node_isset(node, cs->mems_allowed);
1822         up(&callback_sem);
1823         return allowed;
1824 }
1825
1826 /**
1827  * cpuset_excl_nodes_overlap - Do we overlap @p's mem_exclusive ancestors?
1828  * @p: pointer to task_struct of some other task.
1829  *
1830  * Description: Return true if the nearest mem_exclusive ancestor
1831  * cpusets of tasks @p and current overlap.  Used by oom killer to
1832  * determine if task @p's memory usage might impact the memory
1833  * available to the current task.
1834  *
1835  * Acquires callback_sem - not suitable for calling from a fast path.
1836  **/
1837
1838 int cpuset_excl_nodes_overlap(const struct task_struct *p)
1839 {
1840         const struct cpuset *cs1, *cs2; /* my and p's cpuset ancestors */
1841         int overlap = 0;                /* do cpusets overlap? */
1842
1843         down(&callback_sem);
1844
1845         task_lock(current);
1846         if (current->flags & PF_EXITING) {
1847                 task_unlock(current);
1848                 goto done;
1849         }
1850         cs1 = nearest_exclusive_ancestor(current->cpuset);
1851         task_unlock(current);
1852
1853         task_lock((struct task_struct *)p);
1854         if (p->flags & PF_EXITING) {
1855                 task_unlock((struct task_struct *)p);
1856                 goto done;
1857         }
1858         cs2 = nearest_exclusive_ancestor(p->cpuset);
1859         task_unlock((struct task_struct *)p);
1860
1861         overlap = nodes_intersects(cs1->mems_allowed, cs2->mems_allowed);
1862 done:
1863         up(&callback_sem);
1864
1865         return overlap;
1866 }
1867
1868 /*
1869  * proc_cpuset_show()
1870  *  - Print tasks cpuset path into seq_file.
1871  *  - Used for /proc/<pid>/cpuset.
1872  *  - No need to task_lock(tsk) on this tsk->cpuset reference, as it
1873  *    doesn't really matter if tsk->cpuset changes after we read it,
1874  *    and we take manage_sem, keeping attach_task() from changing it
1875  *    anyway.
1876  */
1877
1878 static int proc_cpuset_show(struct seq_file *m, void *v)
1879 {
1880         struct cpuset *cs;
1881         struct task_struct *tsk;
1882         char *buf;
1883         int retval = 0;
1884
1885         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
1886         if (!buf)
1887                 return -ENOMEM;
1888
1889         tsk = m->private;
1890         down(&manage_sem);
1891         cs = tsk->cpuset;
1892         if (!cs) {
1893                 retval = -EINVAL;
1894                 goto out;
1895         }
1896
1897         retval = cpuset_path(cs, buf, PAGE_SIZE);
1898         if (retval < 0)
1899                 goto out;
1900         seq_puts(m, buf);
1901         seq_putc(m, '\n');
1902 out:
1903         up(&manage_sem);
1904         kfree(buf);
1905         return retval;
1906 }
1907
1908 static int cpuset_open(struct inode *inode, struct file *file)
1909 {
1910         struct task_struct *tsk = PROC_I(inode)->task;
1911         return single_open(file, proc_cpuset_show, tsk);
1912 }
1913
1914 struct file_operations proc_cpuset_operations = {
1915         .open           = cpuset_open,
1916         .read           = seq_read,
1917         .llseek         = seq_lseek,
1918         .release        = single_release,
1919 };
1920
1921 /* Display task cpus_allowed, mems_allowed in /proc/<pid>/status file. */
1922 char *cpuset_task_status_allowed(struct task_struct *task, char *buffer)
1923 {
1924         buffer += sprintf(buffer, "Cpus_allowed:\t");
1925         buffer += cpumask_scnprintf(buffer, PAGE_SIZE, task->cpus_allowed);
1926         buffer += sprintf(buffer, "\n");
1927         buffer += sprintf(buffer, "Mems_allowed:\t");
1928         buffer += nodemask_scnprintf(buffer, PAGE_SIZE, task->mems_allowed);
1929         buffer += sprintf(buffer, "\n");
1930         return buffer;
1931 }