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