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