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