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