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