[PATCH] cpuset: numa_policy_rebind cleanup
[safe/jmp/linux-2.6] / 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  * cpuset_update_task_memory_state - update task memory placement
589  *
590  * If the current tasks cpusets mems_allowed changed behind our
591  * backs, update current->mems_allowed, mems_generation and task NUMA
592  * mempolicy to the new value.
593  *
594  * Task mempolicy is updated by rebinding it relative to the
595  * current->cpuset if a task has its memory placement changed.
596  * Do not call this routine if in_interrupt().
597  *
598  * Call without callback_sem or task_lock() held.  May be called
599  * with or without manage_sem held.  Except in early boot or
600  * an exiting task, when tsk->cpuset is NULL, this routine will
601  * acquire task_lock().  We don't need to use task_lock to guard
602  * against another task changing a non-NULL cpuset pointer to NULL,
603  * as that is only done by a task on itself, and if the current task
604  * is here, it is not simultaneously in the exit code NULL'ing its
605  * cpuset pointer.  This routine also might acquire callback_sem and
606  * current->mm->mmap_sem during call.
607  *
608  * The task_lock() is required to dereference current->cpuset safely.
609  * Without it, we could pick up the pointer value of current->cpuset
610  * in one instruction, and then attach_task could give us a different
611  * cpuset, and then the cpuset we had could be removed and freed,
612  * and then on our next instruction, we could dereference a no longer
613  * valid cpuset pointer to get its mems_generation field.
614  *
615  * This routine is needed to update the per-task mems_allowed data,
616  * within the tasks context, when it is trying to allocate memory
617  * (in various mm/mempolicy.c routines) and notices that some other
618  * task has been modifying its cpuset.
619  */
620
621 void cpuset_update_task_memory_state()
622 {
623         int my_cpusets_mem_gen;
624         struct task_struct *tsk = current;
625         struct cpuset *cs = tsk->cpuset;
626
627         if (unlikely(!cs))
628                 return;
629
630         task_lock(tsk);
631         my_cpusets_mem_gen = cs->mems_generation;
632         task_unlock(tsk);
633
634         if (my_cpusets_mem_gen != tsk->cpuset_mems_generation) {
635                 nodemask_t oldmem = tsk->mems_allowed;
636                 int migrate;
637
638                 down(&callback_sem);
639                 task_lock(tsk);
640                 cs = tsk->cpuset;       /* Maybe changed when task not locked */
641                 migrate = is_memory_migrate(cs);
642                 guarantee_online_mems(cs, &tsk->mems_allowed);
643                 tsk->cpuset_mems_generation = cs->mems_generation;
644                 task_unlock(tsk);
645                 up(&callback_sem);
646                 mpol_rebind_task(tsk, &tsk->mems_allowed);
647                 if (!nodes_equal(oldmem, tsk->mems_allowed)) {
648                         if (migrate) {
649                                 do_migrate_pages(tsk->mm, &oldmem,
650                                         &tsk->mems_allowed,
651                                         MPOL_MF_MOVE_ALL);
652                         }
653                 }
654         }
655 }
656
657 /*
658  * is_cpuset_subset(p, q) - Is cpuset p a subset of cpuset q?
659  *
660  * One cpuset is a subset of another if all its allowed CPUs and
661  * Memory Nodes are a subset of the other, and its exclusive flags
662  * are only set if the other's are set.  Call holding manage_sem.
663  */
664
665 static int is_cpuset_subset(const struct cpuset *p, const struct cpuset *q)
666 {
667         return  cpus_subset(p->cpus_allowed, q->cpus_allowed) &&
668                 nodes_subset(p->mems_allowed, q->mems_allowed) &&
669                 is_cpu_exclusive(p) <= is_cpu_exclusive(q) &&
670                 is_mem_exclusive(p) <= is_mem_exclusive(q);
671 }
672
673 /*
674  * validate_change() - Used to validate that any proposed cpuset change
675  *                     follows the structural rules for cpusets.
676  *
677  * If we replaced the flag and mask values of the current cpuset
678  * (cur) with those values in the trial cpuset (trial), would
679  * our various subset and exclusive rules still be valid?  Presumes
680  * manage_sem held.
681  *
682  * 'cur' is the address of an actual, in-use cpuset.  Operations
683  * such as list traversal that depend on the actual address of the
684  * cpuset in the list must use cur below, not trial.
685  *
686  * 'trial' is the address of bulk structure copy of cur, with
687  * perhaps one or more of the fields cpus_allowed, mems_allowed,
688  * or flags changed to new, trial values.
689  *
690  * Return 0 if valid, -errno if not.
691  */
692
693 static int validate_change(const struct cpuset *cur, const struct cpuset *trial)
694 {
695         struct cpuset *c, *par;
696
697         /* Each of our child cpusets must be a subset of us */
698         list_for_each_entry(c, &cur->children, sibling) {
699                 if (!is_cpuset_subset(c, trial))
700                         return -EBUSY;
701         }
702
703         /* Remaining checks don't apply to root cpuset */
704         if ((par = cur->parent) == NULL)
705                 return 0;
706
707         /* We must be a subset of our parent cpuset */
708         if (!is_cpuset_subset(trial, par))
709                 return -EACCES;
710
711         /* If either I or some sibling (!= me) is exclusive, we can't overlap */
712         list_for_each_entry(c, &par->children, sibling) {
713                 if ((is_cpu_exclusive(trial) || is_cpu_exclusive(c)) &&
714                     c != cur &&
715                     cpus_intersects(trial->cpus_allowed, c->cpus_allowed))
716                         return -EINVAL;
717                 if ((is_mem_exclusive(trial) || is_mem_exclusive(c)) &&
718                     c != cur &&
719                     nodes_intersects(trial->mems_allowed, c->mems_allowed))
720                         return -EINVAL;
721         }
722
723         return 0;
724 }
725
726 /*
727  * For a given cpuset cur, partition the system as follows
728  * a. All cpus in the parent cpuset's cpus_allowed that are not part of any
729  *    exclusive child cpusets
730  * b. All cpus in the current cpuset's cpus_allowed that are not part of any
731  *    exclusive child cpusets
732  * Build these two partitions by calling partition_sched_domains
733  *
734  * Call with manage_sem held.  May nest a call to the
735  * lock_cpu_hotplug()/unlock_cpu_hotplug() pair.
736  */
737
738 static void update_cpu_domains(struct cpuset *cur)
739 {
740         struct cpuset *c, *par = cur->parent;
741         cpumask_t pspan, cspan;
742
743         if (par == NULL || cpus_empty(cur->cpus_allowed))
744                 return;
745
746         /*
747          * Get all cpus from parent's cpus_allowed not part of exclusive
748          * children
749          */
750         pspan = par->cpus_allowed;
751         list_for_each_entry(c, &par->children, sibling) {
752                 if (is_cpu_exclusive(c))
753                         cpus_andnot(pspan, pspan, c->cpus_allowed);
754         }
755         if (is_removed(cur) || !is_cpu_exclusive(cur)) {
756                 cpus_or(pspan, pspan, cur->cpus_allowed);
757                 if (cpus_equal(pspan, cur->cpus_allowed))
758                         return;
759                 cspan = CPU_MASK_NONE;
760         } else {
761                 if (cpus_empty(pspan))
762                         return;
763                 cspan = cur->cpus_allowed;
764                 /*
765                  * Get all cpus from current cpuset's cpus_allowed not part
766                  * of exclusive children
767                  */
768                 list_for_each_entry(c, &cur->children, sibling) {
769                         if (is_cpu_exclusive(c))
770                                 cpus_andnot(cspan, cspan, c->cpus_allowed);
771                 }
772         }
773
774         lock_cpu_hotplug();
775         partition_sched_domains(&pspan, &cspan);
776         unlock_cpu_hotplug();
777 }
778
779 /*
780  * Call with manage_sem held.  May take callback_sem during call.
781  */
782
783 static int update_cpumask(struct cpuset *cs, char *buf)
784 {
785         struct cpuset trialcs;
786         int retval, cpus_unchanged;
787
788         trialcs = *cs;
789         retval = cpulist_parse(buf, trialcs.cpus_allowed);
790         if (retval < 0)
791                 return retval;
792         cpus_and(trialcs.cpus_allowed, trialcs.cpus_allowed, cpu_online_map);
793         if (cpus_empty(trialcs.cpus_allowed))
794                 return -ENOSPC;
795         retval = validate_change(cs, &trialcs);
796         if (retval < 0)
797                 return retval;
798         cpus_unchanged = cpus_equal(cs->cpus_allowed, trialcs.cpus_allowed);
799         down(&callback_sem);
800         cs->cpus_allowed = trialcs.cpus_allowed;
801         up(&callback_sem);
802         if (is_cpu_exclusive(cs) && !cpus_unchanged)
803                 update_cpu_domains(cs);
804         return 0;
805 }
806
807 /*
808  * Call with manage_sem held.  May take callback_sem during call.
809  */
810
811 static int update_nodemask(struct cpuset *cs, char *buf)
812 {
813         struct cpuset trialcs;
814         int retval;
815
816         trialcs = *cs;
817         retval = nodelist_parse(buf, trialcs.mems_allowed);
818         if (retval < 0)
819                 goto done;
820         nodes_and(trialcs.mems_allowed, trialcs.mems_allowed, node_online_map);
821         if (nodes_empty(trialcs.mems_allowed)) {
822                 retval = -ENOSPC;
823                 goto done;
824         }
825         retval = validate_change(cs, &trialcs);
826         if (retval < 0)
827                 goto done;
828
829         down(&callback_sem);
830         cs->mems_allowed = trialcs.mems_allowed;
831         atomic_inc(&cpuset_mems_generation);
832         cs->mems_generation = atomic_read(&cpuset_mems_generation);
833         up(&callback_sem);
834
835 done:
836         return retval;
837 }
838
839 /*
840  * Call with manage_sem held.
841  */
842
843 static int update_memory_pressure_enabled(struct cpuset *cs, char *buf)
844 {
845         if (simple_strtoul(buf, NULL, 10) != 0)
846                 cpuset_memory_pressure_enabled = 1;
847         else
848                 cpuset_memory_pressure_enabled = 0;
849         return 0;
850 }
851
852 /*
853  * update_flag - read a 0 or a 1 in a file and update associated flag
854  * bit: the bit to update (CS_CPU_EXCLUSIVE, CS_MEM_EXCLUSIVE,
855  *                              CS_NOTIFY_ON_RELEASE, CS_MEMORY_MIGRATE)
856  * cs:  the cpuset to update
857  * buf: the buffer where we read the 0 or 1
858  *
859  * Call with manage_sem held.
860  */
861
862 static int update_flag(cpuset_flagbits_t bit, struct cpuset *cs, char *buf)
863 {
864         int turning_on;
865         struct cpuset trialcs;
866         int err, cpu_exclusive_changed;
867
868         turning_on = (simple_strtoul(buf, NULL, 10) != 0);
869
870         trialcs = *cs;
871         if (turning_on)
872                 set_bit(bit, &trialcs.flags);
873         else
874                 clear_bit(bit, &trialcs.flags);
875
876         err = validate_change(cs, &trialcs);
877         if (err < 0)
878                 return err;
879         cpu_exclusive_changed =
880                 (is_cpu_exclusive(cs) != is_cpu_exclusive(&trialcs));
881         down(&callback_sem);
882         if (turning_on)
883                 set_bit(bit, &cs->flags);
884         else
885                 clear_bit(bit, &cs->flags);
886         up(&callback_sem);
887
888         if (cpu_exclusive_changed)
889                 update_cpu_domains(cs);
890         return 0;
891 }
892
893 /*
894  * Frequency meter - How fast is some event occuring?
895  *
896  * These routines manage a digitally filtered, constant time based,
897  * event frequency meter.  There are four routines:
898  *   fmeter_init() - initialize a frequency meter.
899  *   fmeter_markevent() - called each time the event happens.
900  *   fmeter_getrate() - returns the recent rate of such events.
901  *   fmeter_update() - internal routine used to update fmeter.
902  *
903  * A common data structure is passed to each of these routines,
904  * which is used to keep track of the state required to manage the
905  * frequency meter and its digital filter.
906  *
907  * The filter works on the number of events marked per unit time.
908  * The filter is single-pole low-pass recursive (IIR).  The time unit
909  * is 1 second.  Arithmetic is done using 32-bit integers scaled to
910  * simulate 3 decimal digits of precision (multiplied by 1000).
911  *
912  * With an FM_COEF of 933, and a time base of 1 second, the filter
913  * has a half-life of 10 seconds, meaning that if the events quit
914  * happening, then the rate returned from the fmeter_getrate()
915  * will be cut in half each 10 seconds, until it converges to zero.
916  *
917  * It is not worth doing a real infinitely recursive filter.  If more
918  * than FM_MAXTICKS ticks have elapsed since the last filter event,
919  * just compute FM_MAXTICKS ticks worth, by which point the level
920  * will be stable.
921  *
922  * Limit the count of unprocessed events to FM_MAXCNT, so as to avoid
923  * arithmetic overflow in the fmeter_update() routine.
924  *
925  * Given the simple 32 bit integer arithmetic used, this meter works
926  * best for reporting rates between one per millisecond (msec) and
927  * one per 32 (approx) seconds.  At constant rates faster than one
928  * per msec it maxes out at values just under 1,000,000.  At constant
929  * rates between one per msec, and one per second it will stabilize
930  * to a value N*1000, where N is the rate of events per second.
931  * At constant rates between one per second and one per 32 seconds,
932  * it will be choppy, moving up on the seconds that have an event,
933  * and then decaying until the next event.  At rates slower than
934  * about one in 32 seconds, it decays all the way back to zero between
935  * each event.
936  */
937
938 #define FM_COEF 933             /* coefficient for half-life of 10 secs */
939 #define FM_MAXTICKS ((time_t)99) /* useless computing more ticks than this */
940 #define FM_MAXCNT 1000000       /* limit cnt to avoid overflow */
941 #define FM_SCALE 1000           /* faux fixed point scale */
942
943 /* Initialize a frequency meter */
944 static void fmeter_init(struct fmeter *fmp)
945 {
946         fmp->cnt = 0;
947         fmp->val = 0;
948         fmp->time = 0;
949         spin_lock_init(&fmp->lock);
950 }
951
952 /* Internal meter update - process cnt events and update value */
953 static void fmeter_update(struct fmeter *fmp)
954 {
955         time_t now = get_seconds();
956         time_t ticks = now - fmp->time;
957
958         if (ticks == 0)
959                 return;
960
961         ticks = min(FM_MAXTICKS, ticks);
962         while (ticks-- > 0)
963                 fmp->val = (FM_COEF * fmp->val) / FM_SCALE;
964         fmp->time = now;
965
966         fmp->val += ((FM_SCALE - FM_COEF) * fmp->cnt) / FM_SCALE;
967         fmp->cnt = 0;
968 }
969
970 /* Process any previous ticks, then bump cnt by one (times scale). */
971 static void fmeter_markevent(struct fmeter *fmp)
972 {
973         spin_lock(&fmp->lock);
974         fmeter_update(fmp);
975         fmp->cnt = min(FM_MAXCNT, fmp->cnt + FM_SCALE);
976         spin_unlock(&fmp->lock);
977 }
978
979 /* Process any previous ticks, then return current value. */
980 static int fmeter_getrate(struct fmeter *fmp)
981 {
982         int val;
983
984         spin_lock(&fmp->lock);
985         fmeter_update(fmp);
986         val = fmp->val;
987         spin_unlock(&fmp->lock);
988         return val;
989 }
990
991 /*
992  * Attack task specified by pid in 'pidbuf' to cpuset 'cs', possibly
993  * writing the path of the old cpuset in 'ppathbuf' if it needs to be
994  * notified on release.
995  *
996  * Call holding manage_sem.  May take callback_sem and task_lock of
997  * the task 'pid' during call.
998  */
999
1000 static int attach_task(struct cpuset *cs, char *pidbuf, char **ppathbuf)
1001 {
1002         pid_t pid;
1003         struct task_struct *tsk;
1004         struct cpuset *oldcs;
1005         cpumask_t cpus;
1006         nodemask_t from, to;
1007
1008         if (sscanf(pidbuf, "%d", &pid) != 1)
1009                 return -EIO;
1010         if (cpus_empty(cs->cpus_allowed) || nodes_empty(cs->mems_allowed))
1011                 return -ENOSPC;
1012
1013         if (pid) {
1014                 read_lock(&tasklist_lock);
1015
1016                 tsk = find_task_by_pid(pid);
1017                 if (!tsk || tsk->flags & PF_EXITING) {
1018                         read_unlock(&tasklist_lock);
1019                         return -ESRCH;
1020                 }
1021
1022                 get_task_struct(tsk);
1023                 read_unlock(&tasklist_lock);
1024
1025                 if ((current->euid) && (current->euid != tsk->uid)
1026                     && (current->euid != tsk->suid)) {
1027                         put_task_struct(tsk);
1028                         return -EACCES;
1029                 }
1030         } else {
1031                 tsk = current;
1032                 get_task_struct(tsk);
1033         }
1034
1035         down(&callback_sem);
1036
1037         task_lock(tsk);
1038         oldcs = tsk->cpuset;
1039         if (!oldcs) {
1040                 task_unlock(tsk);
1041                 up(&callback_sem);
1042                 put_task_struct(tsk);
1043                 return -ESRCH;
1044         }
1045         atomic_inc(&cs->count);
1046         tsk->cpuset = cs;
1047         task_unlock(tsk);
1048
1049         guarantee_online_cpus(cs, &cpus);
1050         set_cpus_allowed(tsk, cpus);
1051
1052         from = oldcs->mems_allowed;
1053         to = cs->mems_allowed;
1054
1055         up(&callback_sem);
1056         if (is_memory_migrate(cs))
1057                 do_migrate_pages(tsk->mm, &from, &to, MPOL_MF_MOVE_ALL);
1058         put_task_struct(tsk);
1059         if (atomic_dec_and_test(&oldcs->count))
1060                 check_for_release(oldcs, ppathbuf);
1061         return 0;
1062 }
1063
1064 /* The various types of files and directories in a cpuset file system */
1065
1066 typedef enum {
1067         FILE_ROOT,
1068         FILE_DIR,
1069         FILE_MEMORY_MIGRATE,
1070         FILE_CPULIST,
1071         FILE_MEMLIST,
1072         FILE_CPU_EXCLUSIVE,
1073         FILE_MEM_EXCLUSIVE,
1074         FILE_NOTIFY_ON_RELEASE,
1075         FILE_MEMORY_PRESSURE_ENABLED,
1076         FILE_MEMORY_PRESSURE,
1077         FILE_TASKLIST,
1078 } cpuset_filetype_t;
1079
1080 static ssize_t cpuset_common_file_write(struct file *file, const char __user *userbuf,
1081                                         size_t nbytes, loff_t *unused_ppos)
1082 {
1083         struct cpuset *cs = __d_cs(file->f_dentry->d_parent);
1084         struct cftype *cft = __d_cft(file->f_dentry);
1085         cpuset_filetype_t type = cft->private;
1086         char *buffer;
1087         char *pathbuf = NULL;
1088         int retval = 0;
1089
1090         /* Crude upper limit on largest legitimate cpulist user might write. */
1091         if (nbytes > 100 + 6 * NR_CPUS)
1092                 return -E2BIG;
1093
1094         /* +1 for nul-terminator */
1095         if ((buffer = kmalloc(nbytes + 1, GFP_KERNEL)) == 0)
1096                 return -ENOMEM;
1097
1098         if (copy_from_user(buffer, userbuf, nbytes)) {
1099                 retval = -EFAULT;
1100                 goto out1;
1101         }
1102         buffer[nbytes] = 0;     /* nul-terminate */
1103
1104         down(&manage_sem);
1105
1106         if (is_removed(cs)) {
1107                 retval = -ENODEV;
1108                 goto out2;
1109         }
1110
1111         switch (type) {
1112         case FILE_CPULIST:
1113                 retval = update_cpumask(cs, buffer);
1114                 break;
1115         case FILE_MEMLIST:
1116                 retval = update_nodemask(cs, buffer);
1117                 break;
1118         case FILE_CPU_EXCLUSIVE:
1119                 retval = update_flag(CS_CPU_EXCLUSIVE, cs, buffer);
1120                 break;
1121         case FILE_MEM_EXCLUSIVE:
1122                 retval = update_flag(CS_MEM_EXCLUSIVE, cs, buffer);
1123                 break;
1124         case FILE_NOTIFY_ON_RELEASE:
1125                 retval = update_flag(CS_NOTIFY_ON_RELEASE, cs, buffer);
1126                 break;
1127         case FILE_MEMORY_MIGRATE:
1128                 retval = update_flag(CS_MEMORY_MIGRATE, cs, buffer);
1129                 break;
1130         case FILE_MEMORY_PRESSURE_ENABLED:
1131                 retval = update_memory_pressure_enabled(cs, buffer);
1132                 break;
1133         case FILE_MEMORY_PRESSURE:
1134                 retval = -EACCES;
1135                 break;
1136         case FILE_TASKLIST:
1137                 retval = attach_task(cs, buffer, &pathbuf);
1138                 break;
1139         default:
1140                 retval = -EINVAL;
1141                 goto out2;
1142         }
1143
1144         if (retval == 0)
1145                 retval = nbytes;
1146 out2:
1147         up(&manage_sem);
1148         cpuset_release_agent(pathbuf);
1149 out1:
1150         kfree(buffer);
1151         return retval;
1152 }
1153
1154 static ssize_t cpuset_file_write(struct file *file, const char __user *buf,
1155                                                 size_t nbytes, loff_t *ppos)
1156 {
1157         ssize_t retval = 0;
1158         struct cftype *cft = __d_cft(file->f_dentry);
1159         if (!cft)
1160                 return -ENODEV;
1161
1162         /* special function ? */
1163         if (cft->write)
1164                 retval = cft->write(file, buf, nbytes, ppos);
1165         else
1166                 retval = cpuset_common_file_write(file, buf, nbytes, ppos);
1167
1168         return retval;
1169 }
1170
1171 /*
1172  * These ascii lists should be read in a single call, by using a user
1173  * buffer large enough to hold the entire map.  If read in smaller
1174  * chunks, there is no guarantee of atomicity.  Since the display format
1175  * used, list of ranges of sequential numbers, is variable length,
1176  * and since these maps can change value dynamically, one could read
1177  * gibberish by doing partial reads while a list was changing.
1178  * A single large read to a buffer that crosses a page boundary is
1179  * ok, because the result being copied to user land is not recomputed
1180  * across a page fault.
1181  */
1182
1183 static int cpuset_sprintf_cpulist(char *page, struct cpuset *cs)
1184 {
1185         cpumask_t mask;
1186
1187         down(&callback_sem);
1188         mask = cs->cpus_allowed;
1189         up(&callback_sem);
1190
1191         return cpulist_scnprintf(page, PAGE_SIZE, mask);
1192 }
1193
1194 static int cpuset_sprintf_memlist(char *page, struct cpuset *cs)
1195 {
1196         nodemask_t mask;
1197
1198         down(&callback_sem);
1199         mask = cs->mems_allowed;
1200         up(&callback_sem);
1201
1202         return nodelist_scnprintf(page, PAGE_SIZE, mask);
1203 }
1204
1205 static ssize_t cpuset_common_file_read(struct file *file, char __user *buf,
1206                                 size_t nbytes, loff_t *ppos)
1207 {
1208         struct cftype *cft = __d_cft(file->f_dentry);
1209         struct cpuset *cs = __d_cs(file->f_dentry->d_parent);
1210         cpuset_filetype_t type = cft->private;
1211         char *page;
1212         ssize_t retval = 0;
1213         char *s;
1214
1215         if (!(page = (char *)__get_free_page(GFP_KERNEL)))
1216                 return -ENOMEM;
1217
1218         s = page;
1219
1220         switch (type) {
1221         case FILE_CPULIST:
1222                 s += cpuset_sprintf_cpulist(s, cs);
1223                 break;
1224         case FILE_MEMLIST:
1225                 s += cpuset_sprintf_memlist(s, cs);
1226                 break;
1227         case FILE_CPU_EXCLUSIVE:
1228                 *s++ = is_cpu_exclusive(cs) ? '1' : '0';
1229                 break;
1230         case FILE_MEM_EXCLUSIVE:
1231                 *s++ = is_mem_exclusive(cs) ? '1' : '0';
1232                 break;
1233         case FILE_NOTIFY_ON_RELEASE:
1234                 *s++ = notify_on_release(cs) ? '1' : '0';
1235                 break;
1236         case FILE_MEMORY_MIGRATE:
1237                 *s++ = is_memory_migrate(cs) ? '1' : '0';
1238                 break;
1239         case FILE_MEMORY_PRESSURE_ENABLED:
1240                 *s++ = cpuset_memory_pressure_enabled ? '1' : '0';
1241                 break;
1242         case FILE_MEMORY_PRESSURE:
1243                 s += sprintf(s, "%d", fmeter_getrate(&cs->fmeter));
1244                 break;
1245         default:
1246                 retval = -EINVAL;
1247                 goto out;
1248         }
1249         *s++ = '\n';
1250
1251         retval = simple_read_from_buffer(buf, nbytes, ppos, page, s - page);
1252 out:
1253         free_page((unsigned long)page);
1254         return retval;
1255 }
1256
1257 static ssize_t cpuset_file_read(struct file *file, char __user *buf, size_t nbytes,
1258                                                                 loff_t *ppos)
1259 {
1260         ssize_t retval = 0;
1261         struct cftype *cft = __d_cft(file->f_dentry);
1262         if (!cft)
1263                 return -ENODEV;
1264
1265         /* special function ? */
1266         if (cft->read)
1267                 retval = cft->read(file, buf, nbytes, ppos);
1268         else
1269                 retval = cpuset_common_file_read(file, buf, nbytes, ppos);
1270
1271         return retval;
1272 }
1273
1274 static int cpuset_file_open(struct inode *inode, struct file *file)
1275 {
1276         int err;
1277         struct cftype *cft;
1278
1279         err = generic_file_open(inode, file);
1280         if (err)
1281                 return err;
1282
1283         cft = __d_cft(file->f_dentry);
1284         if (!cft)
1285                 return -ENODEV;
1286         if (cft->open)
1287                 err = cft->open(inode, file);
1288         else
1289                 err = 0;
1290
1291         return err;
1292 }
1293
1294 static int cpuset_file_release(struct inode *inode, struct file *file)
1295 {
1296         struct cftype *cft = __d_cft(file->f_dentry);
1297         if (cft->release)
1298                 return cft->release(inode, file);
1299         return 0;
1300 }
1301
1302 /*
1303  * cpuset_rename - Only allow simple rename of directories in place.
1304  */
1305 static int cpuset_rename(struct inode *old_dir, struct dentry *old_dentry,
1306                   struct inode *new_dir, struct dentry *new_dentry)
1307 {
1308         if (!S_ISDIR(old_dentry->d_inode->i_mode))
1309                 return -ENOTDIR;
1310         if (new_dentry->d_inode)
1311                 return -EEXIST;
1312         if (old_dir != new_dir)
1313                 return -EIO;
1314         return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1315 }
1316
1317 static struct file_operations cpuset_file_operations = {
1318         .read = cpuset_file_read,
1319         .write = cpuset_file_write,
1320         .llseek = generic_file_llseek,
1321         .open = cpuset_file_open,
1322         .release = cpuset_file_release,
1323 };
1324
1325 static struct inode_operations cpuset_dir_inode_operations = {
1326         .lookup = simple_lookup,
1327         .mkdir = cpuset_mkdir,
1328         .rmdir = cpuset_rmdir,
1329         .rename = cpuset_rename,
1330 };
1331
1332 static int cpuset_create_file(struct dentry *dentry, int mode)
1333 {
1334         struct inode *inode;
1335
1336         if (!dentry)
1337                 return -ENOENT;
1338         if (dentry->d_inode)
1339                 return -EEXIST;
1340
1341         inode = cpuset_new_inode(mode);
1342         if (!inode)
1343                 return -ENOMEM;
1344
1345         if (S_ISDIR(mode)) {
1346                 inode->i_op = &cpuset_dir_inode_operations;
1347                 inode->i_fop = &simple_dir_operations;
1348
1349                 /* start off with i_nlink == 2 (for "." entry) */
1350                 inode->i_nlink++;
1351         } else if (S_ISREG(mode)) {
1352                 inode->i_size = 0;
1353                 inode->i_fop = &cpuset_file_operations;
1354         }
1355
1356         d_instantiate(dentry, inode);
1357         dget(dentry);   /* Extra count - pin the dentry in core */
1358         return 0;
1359 }
1360
1361 /*
1362  *      cpuset_create_dir - create a directory for an object.
1363  *      cs:     the cpuset we create the directory for.
1364  *              It must have a valid ->parent field
1365  *              And we are going to fill its ->dentry field.
1366  *      name:   The name to give to the cpuset directory. Will be copied.
1367  *      mode:   mode to set on new directory.
1368  */
1369
1370 static int cpuset_create_dir(struct cpuset *cs, const char *name, int mode)
1371 {
1372         struct dentry *dentry = NULL;
1373         struct dentry *parent;
1374         int error = 0;
1375
1376         parent = cs->parent->dentry;
1377         dentry = cpuset_get_dentry(parent, name);
1378         if (IS_ERR(dentry))
1379                 return PTR_ERR(dentry);
1380         error = cpuset_create_file(dentry, S_IFDIR | mode);
1381         if (!error) {
1382                 dentry->d_fsdata = cs;
1383                 parent->d_inode->i_nlink++;
1384                 cs->dentry = dentry;
1385         }
1386         dput(dentry);
1387
1388         return error;
1389 }
1390
1391 static int cpuset_add_file(struct dentry *dir, const struct cftype *cft)
1392 {
1393         struct dentry *dentry;
1394         int error;
1395
1396         down(&dir->d_inode->i_sem);
1397         dentry = cpuset_get_dentry(dir, cft->name);
1398         if (!IS_ERR(dentry)) {
1399                 error = cpuset_create_file(dentry, 0644 | S_IFREG);
1400                 if (!error)
1401                         dentry->d_fsdata = (void *)cft;
1402                 dput(dentry);
1403         } else
1404                 error = PTR_ERR(dentry);
1405         up(&dir->d_inode->i_sem);
1406         return error;
1407 }
1408
1409 /*
1410  * Stuff for reading the 'tasks' file.
1411  *
1412  * Reading this file can return large amounts of data if a cpuset has
1413  * *lots* of attached tasks. So it may need several calls to read(),
1414  * but we cannot guarantee that the information we produce is correct
1415  * unless we produce it entirely atomically.
1416  *
1417  * Upon tasks file open(), a struct ctr_struct is allocated, that
1418  * will have a pointer to an array (also allocated here).  The struct
1419  * ctr_struct * is stored in file->private_data.  Its resources will
1420  * be freed by release() when the file is closed.  The array is used
1421  * to sprintf the PIDs and then used by read().
1422  */
1423
1424 /* cpusets_tasks_read array */
1425
1426 struct ctr_struct {
1427         char *buf;
1428         int bufsz;
1429 };
1430
1431 /*
1432  * Load into 'pidarray' up to 'npids' of the tasks using cpuset 'cs'.
1433  * Return actual number of pids loaded.  No need to task_lock(p)
1434  * when reading out p->cpuset, as we don't really care if it changes
1435  * on the next cycle, and we are not going to try to dereference it.
1436  */
1437 static inline int pid_array_load(pid_t *pidarray, int npids, struct cpuset *cs)
1438 {
1439         int n = 0;
1440         struct task_struct *g, *p;
1441
1442         read_lock(&tasklist_lock);
1443
1444         do_each_thread(g, p) {
1445                 if (p->cpuset == cs) {
1446                         pidarray[n++] = p->pid;
1447                         if (unlikely(n == npids))
1448                                 goto array_full;
1449                 }
1450         } while_each_thread(g, p);
1451
1452 array_full:
1453         read_unlock(&tasklist_lock);
1454         return n;
1455 }
1456
1457 static int cmppid(const void *a, const void *b)
1458 {
1459         return *(pid_t *)a - *(pid_t *)b;
1460 }
1461
1462 /*
1463  * Convert array 'a' of 'npids' pid_t's to a string of newline separated
1464  * decimal pids in 'buf'.  Don't write more than 'sz' chars, but return
1465  * count 'cnt' of how many chars would be written if buf were large enough.
1466  */
1467 static int pid_array_to_buf(char *buf, int sz, pid_t *a, int npids)
1468 {
1469         int cnt = 0;
1470         int i;
1471
1472         for (i = 0; i < npids; i++)
1473                 cnt += snprintf(buf + cnt, max(sz - cnt, 0), "%d\n", a[i]);
1474         return cnt;
1475 }
1476
1477 /*
1478  * Handle an open on 'tasks' file.  Prepare a buffer listing the
1479  * process id's of tasks currently attached to the cpuset being opened.
1480  *
1481  * Does not require any specific cpuset semaphores, and does not take any.
1482  */
1483 static int cpuset_tasks_open(struct inode *unused, struct file *file)
1484 {
1485         struct cpuset *cs = __d_cs(file->f_dentry->d_parent);
1486         struct ctr_struct *ctr;
1487         pid_t *pidarray;
1488         int npids;
1489         char c;
1490
1491         if (!(file->f_mode & FMODE_READ))
1492                 return 0;
1493
1494         ctr = kmalloc(sizeof(*ctr), GFP_KERNEL);
1495         if (!ctr)
1496                 goto err0;
1497
1498         /*
1499          * If cpuset gets more users after we read count, we won't have
1500          * enough space - tough.  This race is indistinguishable to the
1501          * caller from the case that the additional cpuset users didn't
1502          * show up until sometime later on.
1503          */
1504         npids = atomic_read(&cs->count);
1505         pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
1506         if (!pidarray)
1507                 goto err1;
1508
1509         npids = pid_array_load(pidarray, npids, cs);
1510         sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
1511
1512         /* Call pid_array_to_buf() twice, first just to get bufsz */
1513         ctr->bufsz = pid_array_to_buf(&c, sizeof(c), pidarray, npids) + 1;
1514         ctr->buf = kmalloc(ctr->bufsz, GFP_KERNEL);
1515         if (!ctr->buf)
1516                 goto err2;
1517         ctr->bufsz = pid_array_to_buf(ctr->buf, ctr->bufsz, pidarray, npids);
1518
1519         kfree(pidarray);
1520         file->private_data = ctr;
1521         return 0;
1522
1523 err2:
1524         kfree(pidarray);
1525 err1:
1526         kfree(ctr);
1527 err0:
1528         return -ENOMEM;
1529 }
1530
1531 static ssize_t cpuset_tasks_read(struct file *file, char __user *buf,
1532                                                 size_t nbytes, loff_t *ppos)
1533 {
1534         struct ctr_struct *ctr = file->private_data;
1535
1536         if (*ppos + nbytes > ctr->bufsz)
1537                 nbytes = ctr->bufsz - *ppos;
1538         if (copy_to_user(buf, ctr->buf + *ppos, nbytes))
1539                 return -EFAULT;
1540         *ppos += nbytes;
1541         return nbytes;
1542 }
1543
1544 static int cpuset_tasks_release(struct inode *unused_inode, struct file *file)
1545 {
1546         struct ctr_struct *ctr;
1547
1548         if (file->f_mode & FMODE_READ) {
1549                 ctr = file->private_data;
1550                 kfree(ctr->buf);
1551                 kfree(ctr);
1552         }
1553         return 0;
1554 }
1555
1556 /*
1557  * for the common functions, 'private' gives the type of file
1558  */
1559
1560 static struct cftype cft_tasks = {
1561         .name = "tasks",
1562         .open = cpuset_tasks_open,
1563         .read = cpuset_tasks_read,
1564         .release = cpuset_tasks_release,
1565         .private = FILE_TASKLIST,
1566 };
1567
1568 static struct cftype cft_cpus = {
1569         .name = "cpus",
1570         .private = FILE_CPULIST,
1571 };
1572
1573 static struct cftype cft_mems = {
1574         .name = "mems",
1575         .private = FILE_MEMLIST,
1576 };
1577
1578 static struct cftype cft_cpu_exclusive = {
1579         .name = "cpu_exclusive",
1580         .private = FILE_CPU_EXCLUSIVE,
1581 };
1582
1583 static struct cftype cft_mem_exclusive = {
1584         .name = "mem_exclusive",
1585         .private = FILE_MEM_EXCLUSIVE,
1586 };
1587
1588 static struct cftype cft_notify_on_release = {
1589         .name = "notify_on_release",
1590         .private = FILE_NOTIFY_ON_RELEASE,
1591 };
1592
1593 static struct cftype cft_memory_migrate = {
1594         .name = "memory_migrate",
1595         .private = FILE_MEMORY_MIGRATE,
1596 };
1597
1598 static struct cftype cft_memory_pressure_enabled = {
1599         .name = "memory_pressure_enabled",
1600         .private = FILE_MEMORY_PRESSURE_ENABLED,
1601 };
1602
1603 static struct cftype cft_memory_pressure = {
1604         .name = "memory_pressure",
1605         .private = FILE_MEMORY_PRESSURE,
1606 };
1607
1608 static int cpuset_populate_dir(struct dentry *cs_dentry)
1609 {
1610         int err;
1611
1612         if ((err = cpuset_add_file(cs_dentry, &cft_cpus)) < 0)
1613                 return err;
1614         if ((err = cpuset_add_file(cs_dentry, &cft_mems)) < 0)
1615                 return err;
1616         if ((err = cpuset_add_file(cs_dentry, &cft_cpu_exclusive)) < 0)
1617                 return err;
1618         if ((err = cpuset_add_file(cs_dentry, &cft_mem_exclusive)) < 0)
1619                 return err;
1620         if ((err = cpuset_add_file(cs_dentry, &cft_notify_on_release)) < 0)
1621                 return err;
1622         if ((err = cpuset_add_file(cs_dentry, &cft_memory_migrate)) < 0)
1623                 return err;
1624         if ((err = cpuset_add_file(cs_dentry, &cft_memory_pressure)) < 0)
1625                 return err;
1626         if ((err = cpuset_add_file(cs_dentry, &cft_tasks)) < 0)
1627                 return err;
1628         return 0;
1629 }
1630
1631 /*
1632  *      cpuset_create - create a cpuset
1633  *      parent: cpuset that will be parent of the new cpuset.
1634  *      name:           name of the new cpuset. Will be strcpy'ed.
1635  *      mode:           mode to set on new inode
1636  *
1637  *      Must be called with the semaphore on the parent inode held
1638  */
1639
1640 static long cpuset_create(struct cpuset *parent, const char *name, int mode)
1641 {
1642         struct cpuset *cs;
1643         int err;
1644
1645         cs = kmalloc(sizeof(*cs), GFP_KERNEL);
1646         if (!cs)
1647                 return -ENOMEM;
1648
1649         down(&manage_sem);
1650         cpuset_update_task_memory_state();
1651         cs->flags = 0;
1652         if (notify_on_release(parent))
1653                 set_bit(CS_NOTIFY_ON_RELEASE, &cs->flags);
1654         cs->cpus_allowed = CPU_MASK_NONE;
1655         cs->mems_allowed = NODE_MASK_NONE;
1656         atomic_set(&cs->count, 0);
1657         INIT_LIST_HEAD(&cs->sibling);
1658         INIT_LIST_HEAD(&cs->children);
1659         atomic_inc(&cpuset_mems_generation);
1660         cs->mems_generation = atomic_read(&cpuset_mems_generation);
1661         fmeter_init(&cs->fmeter);
1662
1663         cs->parent = parent;
1664
1665         down(&callback_sem);
1666         list_add(&cs->sibling, &cs->parent->children);
1667         up(&callback_sem);
1668
1669         err = cpuset_create_dir(cs, name, mode);
1670         if (err < 0)
1671                 goto err;
1672
1673         /*
1674          * Release manage_sem before cpuset_populate_dir() because it
1675          * will down() this new directory's i_sem and if we race with
1676          * another mkdir, we might deadlock.
1677          */
1678         up(&manage_sem);
1679
1680         err = cpuset_populate_dir(cs->dentry);
1681         /* If err < 0, we have a half-filled directory - oh well ;) */
1682         return 0;
1683 err:
1684         list_del(&cs->sibling);
1685         up(&manage_sem);
1686         kfree(cs);
1687         return err;
1688 }
1689
1690 static int cpuset_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1691 {
1692         struct cpuset *c_parent = dentry->d_parent->d_fsdata;
1693
1694         /* the vfs holds inode->i_sem already */
1695         return cpuset_create(c_parent, dentry->d_name.name, mode | S_IFDIR);
1696 }
1697
1698 static int cpuset_rmdir(struct inode *unused_dir, struct dentry *dentry)
1699 {
1700         struct cpuset *cs = dentry->d_fsdata;
1701         struct dentry *d;
1702         struct cpuset *parent;
1703         char *pathbuf = NULL;
1704
1705         /* the vfs holds both inode->i_sem already */
1706
1707         down(&manage_sem);
1708         cpuset_update_task_memory_state();
1709         if (atomic_read(&cs->count) > 0) {
1710                 up(&manage_sem);
1711                 return -EBUSY;
1712         }
1713         if (!list_empty(&cs->children)) {
1714                 up(&manage_sem);
1715                 return -EBUSY;
1716         }
1717         parent = cs->parent;
1718         down(&callback_sem);
1719         set_bit(CS_REMOVED, &cs->flags);
1720         if (is_cpu_exclusive(cs))
1721                 update_cpu_domains(cs);
1722         list_del(&cs->sibling); /* delete my sibling from parent->children */
1723         spin_lock(&cs->dentry->d_lock);
1724         d = dget(cs->dentry);
1725         cs->dentry = NULL;
1726         spin_unlock(&d->d_lock);
1727         cpuset_d_remove_dir(d);
1728         dput(d);
1729         up(&callback_sem);
1730         if (list_empty(&parent->children))
1731                 check_for_release(parent, &pathbuf);
1732         up(&manage_sem);
1733         cpuset_release_agent(pathbuf);
1734         return 0;
1735 }
1736
1737 /**
1738  * cpuset_init - initialize cpusets at system boot
1739  *
1740  * Description: Initialize top_cpuset and the cpuset internal file system,
1741  **/
1742
1743 int __init cpuset_init(void)
1744 {
1745         struct dentry *root;
1746         int err;
1747
1748         top_cpuset.cpus_allowed = CPU_MASK_ALL;
1749         top_cpuset.mems_allowed = NODE_MASK_ALL;
1750
1751         fmeter_init(&top_cpuset.fmeter);
1752         atomic_inc(&cpuset_mems_generation);
1753         top_cpuset.mems_generation = atomic_read(&cpuset_mems_generation);
1754
1755         init_task.cpuset = &top_cpuset;
1756
1757         err = register_filesystem(&cpuset_fs_type);
1758         if (err < 0)
1759                 goto out;
1760         cpuset_mount = kern_mount(&cpuset_fs_type);
1761         if (IS_ERR(cpuset_mount)) {
1762                 printk(KERN_ERR "cpuset: could not mount!\n");
1763                 err = PTR_ERR(cpuset_mount);
1764                 cpuset_mount = NULL;
1765                 goto out;
1766         }
1767         root = cpuset_mount->mnt_sb->s_root;
1768         root->d_fsdata = &top_cpuset;
1769         root->d_inode->i_nlink++;
1770         top_cpuset.dentry = root;
1771         root->d_inode->i_op = &cpuset_dir_inode_operations;
1772         err = cpuset_populate_dir(root);
1773         /* memory_pressure_enabled is in root cpuset only */
1774         if (err == 0)
1775                 err = cpuset_add_file(root, &cft_memory_pressure_enabled);
1776 out:
1777         return err;
1778 }
1779
1780 /**
1781  * cpuset_init_smp - initialize cpus_allowed
1782  *
1783  * Description: Finish top cpuset after cpu, node maps are initialized
1784  **/
1785
1786 void __init cpuset_init_smp(void)
1787 {
1788         top_cpuset.cpus_allowed = cpu_online_map;
1789         top_cpuset.mems_allowed = node_online_map;
1790 }
1791
1792 /**
1793  * cpuset_fork - attach newly forked task to its parents cpuset.
1794  * @tsk: pointer to task_struct of forking parent process.
1795  *
1796  * Description: A task inherits its parent's cpuset at fork().
1797  *
1798  * A pointer to the shared cpuset was automatically copied in fork.c
1799  * by dup_task_struct().  However, we ignore that copy, since it was
1800  * not made under the protection of task_lock(), so might no longer be
1801  * a valid cpuset pointer.  attach_task() might have already changed
1802  * current->cpuset, allowing the previously referenced cpuset to
1803  * be removed and freed.  Instead, we task_lock(current) and copy
1804  * its present value of current->cpuset for our freshly forked child.
1805  *
1806  * At the point that cpuset_fork() is called, 'current' is the parent
1807  * task, and the passed argument 'child' points to the child task.
1808  **/
1809
1810 void cpuset_fork(struct task_struct *child)
1811 {
1812         task_lock(current);
1813         child->cpuset = current->cpuset;
1814         atomic_inc(&child->cpuset->count);
1815         task_unlock(current);
1816 }
1817
1818 /**
1819  * cpuset_exit - detach cpuset from exiting task
1820  * @tsk: pointer to task_struct of exiting process
1821  *
1822  * Description: Detach cpuset from @tsk and release it.
1823  *
1824  * Note that cpusets marked notify_on_release force every task in
1825  * them to take the global manage_sem semaphore when exiting.
1826  * This could impact scaling on very large systems.  Be reluctant to
1827  * use notify_on_release cpusets where very high task exit scaling
1828  * is required on large systems.
1829  *
1830  * Don't even think about derefencing 'cs' after the cpuset use count
1831  * goes to zero, except inside a critical section guarded by manage_sem
1832  * or callback_sem.   Otherwise a zero cpuset use count is a license to
1833  * any other task to nuke the cpuset immediately, via cpuset_rmdir().
1834  *
1835  * This routine has to take manage_sem, not callback_sem, because
1836  * it is holding that semaphore while calling check_for_release(),
1837  * which calls kmalloc(), so can't be called holding callback__sem().
1838  *
1839  * We don't need to task_lock() this reference to tsk->cpuset,
1840  * because tsk is already marked PF_EXITING, so attach_task() won't
1841  * mess with it, or task is a failed fork, never visible to attach_task.
1842  **/
1843
1844 void cpuset_exit(struct task_struct *tsk)
1845 {
1846         struct cpuset *cs;
1847
1848         cs = tsk->cpuset;
1849         tsk->cpuset = NULL;
1850
1851         if (notify_on_release(cs)) {
1852                 char *pathbuf = NULL;
1853
1854                 down(&manage_sem);
1855                 if (atomic_dec_and_test(&cs->count))
1856                         check_for_release(cs, &pathbuf);
1857                 up(&manage_sem);
1858                 cpuset_release_agent(pathbuf);
1859         } else {
1860                 atomic_dec(&cs->count);
1861         }
1862 }
1863
1864 /**
1865  * cpuset_cpus_allowed - return cpus_allowed mask from a tasks cpuset.
1866  * @tsk: pointer to task_struct from which to obtain cpuset->cpus_allowed.
1867  *
1868  * Description: Returns the cpumask_t cpus_allowed of the cpuset
1869  * attached to the specified @tsk.  Guaranteed to return some non-empty
1870  * subset of cpu_online_map, even if this means going outside the
1871  * tasks cpuset.
1872  **/
1873
1874 cpumask_t cpuset_cpus_allowed(struct task_struct *tsk)
1875 {
1876         cpumask_t mask;
1877
1878         down(&callback_sem);
1879         task_lock(tsk);
1880         guarantee_online_cpus(tsk->cpuset, &mask);
1881         task_unlock(tsk);
1882         up(&callback_sem);
1883
1884         return mask;
1885 }
1886
1887 void cpuset_init_current_mems_allowed(void)
1888 {
1889         current->mems_allowed = NODE_MASK_ALL;
1890 }
1891
1892 /**
1893  * cpuset_mems_allowed - return mems_allowed mask from a tasks cpuset.
1894  * @tsk: pointer to task_struct from which to obtain cpuset->mems_allowed.
1895  *
1896  * Description: Returns the nodemask_t mems_allowed of the cpuset
1897  * attached to the specified @tsk.  Guaranteed to return some non-empty
1898  * subset of node_online_map, even if this means going outside the
1899  * tasks cpuset.
1900  **/
1901
1902 nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
1903 {
1904         nodemask_t mask;
1905
1906         down(&callback_sem);
1907         task_lock(tsk);
1908         guarantee_online_mems(tsk->cpuset, &mask);
1909         task_unlock(tsk);
1910         up(&callback_sem);
1911
1912         return mask;
1913 }
1914
1915 /**
1916  * cpuset_zonelist_valid_mems_allowed - check zonelist vs. curremt mems_allowed
1917  * @zl: the zonelist to be checked
1918  *
1919  * Are any of the nodes on zonelist zl allowed in current->mems_allowed?
1920  */
1921 int cpuset_zonelist_valid_mems_allowed(struct zonelist *zl)
1922 {
1923         int i;
1924
1925         for (i = 0; zl->zones[i]; i++) {
1926                 int nid = zl->zones[i]->zone_pgdat->node_id;
1927
1928                 if (node_isset(nid, current->mems_allowed))
1929                         return 1;
1930         }
1931         return 0;
1932 }
1933
1934 /*
1935  * nearest_exclusive_ancestor() - Returns the nearest mem_exclusive
1936  * ancestor to the specified cpuset.  Call holding callback_sem.
1937  * If no ancestor is mem_exclusive (an unusual configuration), then
1938  * returns the root cpuset.
1939  */
1940 static const struct cpuset *nearest_exclusive_ancestor(const struct cpuset *cs)
1941 {
1942         while (!is_mem_exclusive(cs) && cs->parent)
1943                 cs = cs->parent;
1944         return cs;
1945 }
1946
1947 /**
1948  * cpuset_zone_allowed - Can we allocate memory on zone z's memory node?
1949  * @z: is this zone on an allowed node?
1950  * @gfp_mask: memory allocation flags (we use __GFP_HARDWALL)
1951  *
1952  * If we're in interrupt, yes, we can always allocate.  If zone
1953  * z's node is in our tasks mems_allowed, yes.  If it's not a
1954  * __GFP_HARDWALL request and this zone's nodes is in the nearest
1955  * mem_exclusive cpuset ancestor to this tasks cpuset, yes.
1956  * Otherwise, no.
1957  *
1958  * GFP_USER allocations are marked with the __GFP_HARDWALL bit,
1959  * and do not allow allocations outside the current tasks cpuset.
1960  * GFP_KERNEL allocations are not so marked, so can escape to the
1961  * nearest mem_exclusive ancestor cpuset.
1962  *
1963  * Scanning up parent cpusets requires callback_sem.  The __alloc_pages()
1964  * routine only calls here with __GFP_HARDWALL bit _not_ set if
1965  * it's a GFP_KERNEL allocation, and all nodes in the current tasks
1966  * mems_allowed came up empty on the first pass over the zonelist.
1967  * So only GFP_KERNEL allocations, if all nodes in the cpuset are
1968  * short of memory, might require taking the callback_sem semaphore.
1969  *
1970  * The first loop over the zonelist in mm/page_alloc.c:__alloc_pages()
1971  * calls here with __GFP_HARDWALL always set in gfp_mask, enforcing
1972  * hardwall cpusets - no allocation on a node outside the cpuset is
1973  * allowed (unless in interrupt, of course).
1974  *
1975  * The second loop doesn't even call here for GFP_ATOMIC requests
1976  * (if the __alloc_pages() local variable 'wait' is set).  That check
1977  * and the checks below have the combined affect in the second loop of
1978  * the __alloc_pages() routine that:
1979  *      in_interrupt - any node ok (current task context irrelevant)
1980  *      GFP_ATOMIC   - any node ok
1981  *      GFP_KERNEL   - any node in enclosing mem_exclusive cpuset ok
1982  *      GFP_USER     - only nodes in current tasks mems allowed ok.
1983  **/
1984
1985 int cpuset_zone_allowed(struct zone *z, gfp_t gfp_mask)
1986 {
1987         int node;                       /* node that zone z is on */
1988         const struct cpuset *cs;        /* current cpuset ancestors */
1989         int allowed = 1;                /* is allocation in zone z allowed? */
1990
1991         if (in_interrupt())
1992                 return 1;
1993         node = z->zone_pgdat->node_id;
1994         if (node_isset(node, current->mems_allowed))
1995                 return 1;
1996         if (gfp_mask & __GFP_HARDWALL)  /* If hardwall request, stop here */
1997                 return 0;
1998
1999         if (current->flags & PF_EXITING) /* Let dying task have memory */
2000                 return 1;
2001
2002         /* Not hardwall and node outside mems_allowed: scan up cpusets */
2003         down(&callback_sem);
2004
2005         task_lock(current);
2006         cs = nearest_exclusive_ancestor(current->cpuset);
2007         task_unlock(current);
2008
2009         allowed = node_isset(node, cs->mems_allowed);
2010         up(&callback_sem);
2011         return allowed;
2012 }
2013
2014 /**
2015  * cpuset_excl_nodes_overlap - Do we overlap @p's mem_exclusive ancestors?
2016  * @p: pointer to task_struct of some other task.
2017  *
2018  * Description: Return true if the nearest mem_exclusive ancestor
2019  * cpusets of tasks @p and current overlap.  Used by oom killer to
2020  * determine if task @p's memory usage might impact the memory
2021  * available to the current task.
2022  *
2023  * Acquires callback_sem - not suitable for calling from a fast path.
2024  **/
2025
2026 int cpuset_excl_nodes_overlap(const struct task_struct *p)
2027 {
2028         const struct cpuset *cs1, *cs2; /* my and p's cpuset ancestors */
2029         int overlap = 0;                /* do cpusets overlap? */
2030
2031         down(&callback_sem);
2032
2033         task_lock(current);
2034         if (current->flags & PF_EXITING) {
2035                 task_unlock(current);
2036                 goto done;
2037         }
2038         cs1 = nearest_exclusive_ancestor(current->cpuset);
2039         task_unlock(current);
2040
2041         task_lock((struct task_struct *)p);
2042         if (p->flags & PF_EXITING) {
2043                 task_unlock((struct task_struct *)p);
2044                 goto done;
2045         }
2046         cs2 = nearest_exclusive_ancestor(p->cpuset);
2047         task_unlock((struct task_struct *)p);
2048
2049         overlap = nodes_intersects(cs1->mems_allowed, cs2->mems_allowed);
2050 done:
2051         up(&callback_sem);
2052
2053         return overlap;
2054 }
2055
2056 /*
2057  * Collection of memory_pressure is suppressed unless
2058  * this flag is enabled by writing "1" to the special
2059  * cpuset file 'memory_pressure_enabled' in the root cpuset.
2060  */
2061
2062 int cpuset_memory_pressure_enabled __read_mostly;
2063
2064 /**
2065  * cpuset_memory_pressure_bump - keep stats of per-cpuset reclaims.
2066  *
2067  * Keep a running average of the rate of synchronous (direct)
2068  * page reclaim efforts initiated by tasks in each cpuset.
2069  *
2070  * This represents the rate at which some task in the cpuset
2071  * ran low on memory on all nodes it was allowed to use, and
2072  * had to enter the kernels page reclaim code in an effort to
2073  * create more free memory by tossing clean pages or swapping
2074  * or writing dirty pages.
2075  *
2076  * Display to user space in the per-cpuset read-only file
2077  * "memory_pressure".  Value displayed is an integer
2078  * representing the recent rate of entry into the synchronous
2079  * (direct) page reclaim by any task attached to the cpuset.
2080  **/
2081
2082 void __cpuset_memory_pressure_bump(void)
2083 {
2084         struct cpuset *cs;
2085
2086         task_lock(current);
2087         cs = current->cpuset;
2088         fmeter_markevent(&cs->fmeter);
2089         task_unlock(current);
2090 }
2091
2092 /*
2093  * proc_cpuset_show()
2094  *  - Print tasks cpuset path into seq_file.
2095  *  - Used for /proc/<pid>/cpuset.
2096  *  - No need to task_lock(tsk) on this tsk->cpuset reference, as it
2097  *    doesn't really matter if tsk->cpuset changes after we read it,
2098  *    and we take manage_sem, keeping attach_task() from changing it
2099  *    anyway.
2100  */
2101
2102 static int proc_cpuset_show(struct seq_file *m, void *v)
2103 {
2104         struct cpuset *cs;
2105         struct task_struct *tsk;
2106         char *buf;
2107         int retval = 0;
2108
2109         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
2110         if (!buf)
2111                 return -ENOMEM;
2112
2113         tsk = m->private;
2114         down(&manage_sem);
2115         cs = tsk->cpuset;
2116         if (!cs) {
2117                 retval = -EINVAL;
2118                 goto out;
2119         }
2120
2121         retval = cpuset_path(cs, buf, PAGE_SIZE);
2122         if (retval < 0)
2123                 goto out;
2124         seq_puts(m, buf);
2125         seq_putc(m, '\n');
2126 out:
2127         up(&manage_sem);
2128         kfree(buf);
2129         return retval;
2130 }
2131
2132 static int cpuset_open(struct inode *inode, struct file *file)
2133 {
2134         struct task_struct *tsk = PROC_I(inode)->task;
2135         return single_open(file, proc_cpuset_show, tsk);
2136 }
2137
2138 struct file_operations proc_cpuset_operations = {
2139         .open           = cpuset_open,
2140         .read           = seq_read,
2141         .llseek         = seq_lseek,
2142         .release        = single_release,
2143 };
2144
2145 /* Display task cpus_allowed, mems_allowed in /proc/<pid>/status file. */
2146 char *cpuset_task_status_allowed(struct task_struct *task, char *buffer)
2147 {
2148         buffer += sprintf(buffer, "Cpus_allowed:\t");
2149         buffer += cpumask_scnprintf(buffer, PAGE_SIZE, task->cpus_allowed);
2150         buffer += sprintf(buffer, "\n");
2151         buffer += sprintf(buffer, "Mems_allowed:\t");
2152         buffer += nodemask_scnprintf(buffer, PAGE_SIZE, task->mems_allowed);
2153         buffer += sprintf(buffer, "\n");
2154         return buffer;
2155 }