zero i_uid/i_gid on inode allocation
[safe/jmp/linux-2.6] / kernel / cgroup.c
1 /*
2  *  Generic process-grouping system.
3  *
4  *  Based originally on the cpuset system, extracted by Paul Menage
5  *  Copyright (C) 2006 Google, Inc
6  *
7  *  Copyright notices from the original cpuset code:
8  *  --------------------------------------------------
9  *  Copyright (C) 2003 BULL SA.
10  *  Copyright (C) 2004-2006 Silicon Graphics, Inc.
11  *
12  *  Portions derived from Patrick Mochel's sysfs code.
13  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
14  *
15  *  2003-10-10 Written by Simon Derr.
16  *  2003-10-22 Updates by Stephen Hemminger.
17  *  2004 May-July Rework by Paul Jackson.
18  *  ---------------------------------------------------
19  *
20  *  This file is subject to the terms and conditions of the GNU General Public
21  *  License.  See the file COPYING in the main directory of the Linux
22  *  distribution for more details.
23  */
24
25 #include <linux/cgroup.h>
26 #include <linux/errno.h>
27 #include <linux/fs.h>
28 #include <linux/kernel.h>
29 #include <linux/list.h>
30 #include <linux/mm.h>
31 #include <linux/mutex.h>
32 #include <linux/mount.h>
33 #include <linux/pagemap.h>
34 #include <linux/proc_fs.h>
35 #include <linux/rcupdate.h>
36 #include <linux/sched.h>
37 #include <linux/backing-dev.h>
38 #include <linux/seq_file.h>
39 #include <linux/slab.h>
40 #include <linux/magic.h>
41 #include <linux/spinlock.h>
42 #include <linux/string.h>
43 #include <linux/sort.h>
44 #include <linux/kmod.h>
45 #include <linux/delayacct.h>
46 #include <linux/cgroupstats.h>
47 #include <linux/hash.h>
48 #include <linux/namei.h>
49
50 #include <asm/atomic.h>
51
52 static DEFINE_MUTEX(cgroup_mutex);
53
54 /* Generate an array of cgroup subsystem pointers */
55 #define SUBSYS(_x) &_x ## _subsys,
56
57 static struct cgroup_subsys *subsys[] = {
58 #include <linux/cgroup_subsys.h>
59 };
60
61 /*
62  * A cgroupfs_root represents the root of a cgroup hierarchy,
63  * and may be associated with a superblock to form an active
64  * hierarchy
65  */
66 struct cgroupfs_root {
67         struct super_block *sb;
68
69         /*
70          * The bitmask of subsystems intended to be attached to this
71          * hierarchy
72          */
73         unsigned long subsys_bits;
74
75         /* The bitmask of subsystems currently attached to this hierarchy */
76         unsigned long actual_subsys_bits;
77
78         /* A list running through the attached subsystems */
79         struct list_head subsys_list;
80
81         /* The root cgroup for this hierarchy */
82         struct cgroup top_cgroup;
83
84         /* Tracks how many cgroups are currently defined in hierarchy.*/
85         int number_of_cgroups;
86
87         /* A list running through the mounted hierarchies */
88         struct list_head root_list;
89
90         /* Hierarchy-specific flags */
91         unsigned long flags;
92
93         /* The path to use for release notifications. */
94         char release_agent_path[PATH_MAX];
95 };
96
97
98 /*
99  * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
100  * subsystems that are otherwise unattached - it never has more than a
101  * single cgroup, and all tasks are part of that cgroup.
102  */
103 static struct cgroupfs_root rootnode;
104
105 /* The list of hierarchy roots */
106
107 static LIST_HEAD(roots);
108 static int root_count;
109
110 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
111 #define dummytop (&rootnode.top_cgroup)
112
113 /* This flag indicates whether tasks in the fork and exit paths should
114  * check for fork/exit handlers to call. This avoids us having to do
115  * extra work in the fork/exit path if none of the subsystems need to
116  * be called.
117  */
118 static int need_forkexit_callback __read_mostly;
119 static int need_mm_owner_callback __read_mostly;
120
121 /* convenient tests for these bits */
122 inline int cgroup_is_removed(const struct cgroup *cgrp)
123 {
124         return test_bit(CGRP_REMOVED, &cgrp->flags);
125 }
126
127 /* bits in struct cgroupfs_root flags field */
128 enum {
129         ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
130 };
131
132 static int cgroup_is_releasable(const struct cgroup *cgrp)
133 {
134         const int bits =
135                 (1 << CGRP_RELEASABLE) |
136                 (1 << CGRP_NOTIFY_ON_RELEASE);
137         return (cgrp->flags & bits) == bits;
138 }
139
140 static int notify_on_release(const struct cgroup *cgrp)
141 {
142         return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
143 }
144
145 /*
146  * for_each_subsys() allows you to iterate on each subsystem attached to
147  * an active hierarchy
148  */
149 #define for_each_subsys(_root, _ss) \
150 list_for_each_entry(_ss, &_root->subsys_list, sibling)
151
152 /* for_each_root() allows you to iterate across the active hierarchies */
153 #define for_each_root(_root) \
154 list_for_each_entry(_root, &roots, root_list)
155
156 /* the list of cgroups eligible for automatic release. Protected by
157  * release_list_lock */
158 static LIST_HEAD(release_list);
159 static DEFINE_SPINLOCK(release_list_lock);
160 static void cgroup_release_agent(struct work_struct *work);
161 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
162 static void check_for_release(struct cgroup *cgrp);
163
164 /* Link structure for associating css_set objects with cgroups */
165 struct cg_cgroup_link {
166         /*
167          * List running through cg_cgroup_links associated with a
168          * cgroup, anchored on cgroup->css_sets
169          */
170         struct list_head cgrp_link_list;
171         /*
172          * List running through cg_cgroup_links pointing at a
173          * single css_set object, anchored on css_set->cg_links
174          */
175         struct list_head cg_link_list;
176         struct css_set *cg;
177 };
178
179 /* The default css_set - used by init and its children prior to any
180  * hierarchies being mounted. It contains a pointer to the root state
181  * for each subsystem. Also used to anchor the list of css_sets. Not
182  * reference-counted, to improve performance when child cgroups
183  * haven't been created.
184  */
185
186 static struct css_set init_css_set;
187 static struct cg_cgroup_link init_css_set_link;
188
189 /* css_set_lock protects the list of css_set objects, and the
190  * chain of tasks off each css_set.  Nests outside task->alloc_lock
191  * due to cgroup_iter_start() */
192 static DEFINE_RWLOCK(css_set_lock);
193 static int css_set_count;
194
195 /* hash table for cgroup groups. This improves the performance to
196  * find an existing css_set */
197 #define CSS_SET_HASH_BITS       7
198 #define CSS_SET_TABLE_SIZE      (1 << CSS_SET_HASH_BITS)
199 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
200
201 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
202 {
203         int i;
204         int index;
205         unsigned long tmp = 0UL;
206
207         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
208                 tmp += (unsigned long)css[i];
209         tmp = (tmp >> 16) ^ tmp;
210
211         index = hash_long(tmp, CSS_SET_HASH_BITS);
212
213         return &css_set_table[index];
214 }
215
216 /* We don't maintain the lists running through each css_set to its
217  * task until after the first call to cgroup_iter_start(). This
218  * reduces the fork()/exit() overhead for people who have cgroups
219  * compiled into their kernel but not actually in use */
220 static int use_task_css_set_links __read_mostly;
221
222 /* When we create or destroy a css_set, the operation simply
223  * takes/releases a reference count on all the cgroups referenced
224  * by subsystems in this css_set. This can end up multiple-counting
225  * some cgroups, but that's OK - the ref-count is just a
226  * busy/not-busy indicator; ensuring that we only count each cgroup
227  * once would require taking a global lock to ensure that no
228  * subsystems moved between hierarchies while we were doing so.
229  *
230  * Possible TODO: decide at boot time based on the number of
231  * registered subsystems and the number of CPUs or NUMA nodes whether
232  * it's better for performance to ref-count every subsystem, or to
233  * take a global lock and only add one ref count to each hierarchy.
234  */
235
236 /*
237  * unlink a css_set from the list and free it
238  */
239 static void unlink_css_set(struct css_set *cg)
240 {
241         struct cg_cgroup_link *link;
242         struct cg_cgroup_link *saved_link;
243
244         hlist_del(&cg->hlist);
245         css_set_count--;
246
247         list_for_each_entry_safe(link, saved_link, &cg->cg_links,
248                                  cg_link_list) {
249                 list_del(&link->cg_link_list);
250                 list_del(&link->cgrp_link_list);
251                 kfree(link);
252         }
253 }
254
255 static void __put_css_set(struct css_set *cg, int taskexit)
256 {
257         int i;
258         /*
259          * Ensure that the refcount doesn't hit zero while any readers
260          * can see it. Similar to atomic_dec_and_lock(), but for an
261          * rwlock
262          */
263         if (atomic_add_unless(&cg->refcount, -1, 1))
264                 return;
265         write_lock(&css_set_lock);
266         if (!atomic_dec_and_test(&cg->refcount)) {
267                 write_unlock(&css_set_lock);
268                 return;
269         }
270         unlink_css_set(cg);
271         write_unlock(&css_set_lock);
272
273         rcu_read_lock();
274         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
275                 struct cgroup *cgrp = cg->subsys[i]->cgroup;
276                 if (atomic_dec_and_test(&cgrp->count) &&
277                     notify_on_release(cgrp)) {
278                         if (taskexit)
279                                 set_bit(CGRP_RELEASABLE, &cgrp->flags);
280                         check_for_release(cgrp);
281                 }
282         }
283         rcu_read_unlock();
284         kfree(cg);
285 }
286
287 /*
288  * refcounted get/put for css_set objects
289  */
290 static inline void get_css_set(struct css_set *cg)
291 {
292         atomic_inc(&cg->refcount);
293 }
294
295 static inline void put_css_set(struct css_set *cg)
296 {
297         __put_css_set(cg, 0);
298 }
299
300 static inline void put_css_set_taskexit(struct css_set *cg)
301 {
302         __put_css_set(cg, 1);
303 }
304
305 /*
306  * find_existing_css_set() is a helper for
307  * find_css_set(), and checks to see whether an existing
308  * css_set is suitable.
309  *
310  * oldcg: the cgroup group that we're using before the cgroup
311  * transition
312  *
313  * cgrp: the cgroup that we're moving into
314  *
315  * template: location in which to build the desired set of subsystem
316  * state objects for the new cgroup group
317  */
318 static struct css_set *find_existing_css_set(
319         struct css_set *oldcg,
320         struct cgroup *cgrp,
321         struct cgroup_subsys_state *template[])
322 {
323         int i;
324         struct cgroupfs_root *root = cgrp->root;
325         struct hlist_head *hhead;
326         struct hlist_node *node;
327         struct css_set *cg;
328
329         /* Built the set of subsystem state objects that we want to
330          * see in the new css_set */
331         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
332                 if (root->subsys_bits & (1UL << i)) {
333                         /* Subsystem is in this hierarchy. So we want
334                          * the subsystem state from the new
335                          * cgroup */
336                         template[i] = cgrp->subsys[i];
337                 } else {
338                         /* Subsystem is not in this hierarchy, so we
339                          * don't want to change the subsystem state */
340                         template[i] = oldcg->subsys[i];
341                 }
342         }
343
344         hhead = css_set_hash(template);
345         hlist_for_each_entry(cg, node, hhead, hlist) {
346                 if (!memcmp(template, cg->subsys, sizeof(cg->subsys))) {
347                         /* All subsystems matched */
348                         return cg;
349                 }
350         }
351
352         /* No existing cgroup group matched */
353         return NULL;
354 }
355
356 static void free_cg_links(struct list_head *tmp)
357 {
358         struct cg_cgroup_link *link;
359         struct cg_cgroup_link *saved_link;
360
361         list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
362                 list_del(&link->cgrp_link_list);
363                 kfree(link);
364         }
365 }
366
367 /*
368  * allocate_cg_links() allocates "count" cg_cgroup_link structures
369  * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
370  * success or a negative error
371  */
372 static int allocate_cg_links(int count, struct list_head *tmp)
373 {
374         struct cg_cgroup_link *link;
375         int i;
376         INIT_LIST_HEAD(tmp);
377         for (i = 0; i < count; i++) {
378                 link = kmalloc(sizeof(*link), GFP_KERNEL);
379                 if (!link) {
380                         free_cg_links(tmp);
381                         return -ENOMEM;
382                 }
383                 list_add(&link->cgrp_link_list, tmp);
384         }
385         return 0;
386 }
387
388 /*
389  * find_css_set() takes an existing cgroup group and a
390  * cgroup object, and returns a css_set object that's
391  * equivalent to the old group, but with the given cgroup
392  * substituted into the appropriate hierarchy. Must be called with
393  * cgroup_mutex held
394  */
395 static struct css_set *find_css_set(
396         struct css_set *oldcg, struct cgroup *cgrp)
397 {
398         struct css_set *res;
399         struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
400         int i;
401
402         struct list_head tmp_cg_links;
403         struct cg_cgroup_link *link;
404
405         struct hlist_head *hhead;
406
407         /* First see if we already have a cgroup group that matches
408          * the desired set */
409         read_lock(&css_set_lock);
410         res = find_existing_css_set(oldcg, cgrp, template);
411         if (res)
412                 get_css_set(res);
413         read_unlock(&css_set_lock);
414
415         if (res)
416                 return res;
417
418         res = kmalloc(sizeof(*res), GFP_KERNEL);
419         if (!res)
420                 return NULL;
421
422         /* Allocate all the cg_cgroup_link objects that we'll need */
423         if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
424                 kfree(res);
425                 return NULL;
426         }
427
428         atomic_set(&res->refcount, 1);
429         INIT_LIST_HEAD(&res->cg_links);
430         INIT_LIST_HEAD(&res->tasks);
431         INIT_HLIST_NODE(&res->hlist);
432
433         /* Copy the set of subsystem state objects generated in
434          * find_existing_css_set() */
435         memcpy(res->subsys, template, sizeof(res->subsys));
436
437         write_lock(&css_set_lock);
438         /* Add reference counts and links from the new css_set. */
439         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
440                 struct cgroup *cgrp = res->subsys[i]->cgroup;
441                 struct cgroup_subsys *ss = subsys[i];
442                 atomic_inc(&cgrp->count);
443                 /*
444                  * We want to add a link once per cgroup, so we
445                  * only do it for the first subsystem in each
446                  * hierarchy
447                  */
448                 if (ss->root->subsys_list.next == &ss->sibling) {
449                         BUG_ON(list_empty(&tmp_cg_links));
450                         link = list_entry(tmp_cg_links.next,
451                                           struct cg_cgroup_link,
452                                           cgrp_link_list);
453                         list_del(&link->cgrp_link_list);
454                         list_add(&link->cgrp_link_list, &cgrp->css_sets);
455                         link->cg = res;
456                         list_add(&link->cg_link_list, &res->cg_links);
457                 }
458         }
459         if (list_empty(&rootnode.subsys_list)) {
460                 link = list_entry(tmp_cg_links.next,
461                                   struct cg_cgroup_link,
462                                   cgrp_link_list);
463                 list_del(&link->cgrp_link_list);
464                 list_add(&link->cgrp_link_list, &dummytop->css_sets);
465                 link->cg = res;
466                 list_add(&link->cg_link_list, &res->cg_links);
467         }
468
469         BUG_ON(!list_empty(&tmp_cg_links));
470
471         css_set_count++;
472
473         /* Add this cgroup group to the hash table */
474         hhead = css_set_hash(res->subsys);
475         hlist_add_head(&res->hlist, hhead);
476
477         write_unlock(&css_set_lock);
478
479         return res;
480 }
481
482 /*
483  * There is one global cgroup mutex. We also require taking
484  * task_lock() when dereferencing a task's cgroup subsys pointers.
485  * See "The task_lock() exception", at the end of this comment.
486  *
487  * A task must hold cgroup_mutex to modify cgroups.
488  *
489  * Any task can increment and decrement the count field without lock.
490  * So in general, code holding cgroup_mutex can't rely on the count
491  * field not changing.  However, if the count goes to zero, then only
492  * cgroup_attach_task() can increment it again.  Because a count of zero
493  * means that no tasks are currently attached, therefore there is no
494  * way a task attached to that cgroup can fork (the other way to
495  * increment the count).  So code holding cgroup_mutex can safely
496  * assume that if the count is zero, it will stay zero. Similarly, if
497  * a task holds cgroup_mutex on a cgroup with zero count, it
498  * knows that the cgroup won't be removed, as cgroup_rmdir()
499  * needs that mutex.
500  *
501  * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
502  * (usually) take cgroup_mutex.  These are the two most performance
503  * critical pieces of code here.  The exception occurs on cgroup_exit(),
504  * when a task in a notify_on_release cgroup exits.  Then cgroup_mutex
505  * is taken, and if the cgroup count is zero, a usermode call made
506  * to the release agent with the name of the cgroup (path relative to
507  * the root of cgroup file system) as the argument.
508  *
509  * A cgroup can only be deleted if both its 'count' of using tasks
510  * is zero, and its list of 'children' cgroups is empty.  Since all
511  * tasks in the system use _some_ cgroup, and since there is always at
512  * least one task in the system (init, pid == 1), therefore, top_cgroup
513  * always has either children cgroups and/or using tasks.  So we don't
514  * need a special hack to ensure that top_cgroup cannot be deleted.
515  *
516  *      The task_lock() exception
517  *
518  * The need for this exception arises from the action of
519  * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
520  * another.  It does so using cgroup_mutex, however there are
521  * several performance critical places that need to reference
522  * task->cgroup without the expense of grabbing a system global
523  * mutex.  Therefore except as noted below, when dereferencing or, as
524  * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
525  * task_lock(), which acts on a spinlock (task->alloc_lock) already in
526  * the task_struct routinely used for such matters.
527  *
528  * P.S.  One more locking exception.  RCU is used to guard the
529  * update of a tasks cgroup pointer by cgroup_attach_task()
530  */
531
532 /**
533  * cgroup_lock - lock out any changes to cgroup structures
534  *
535  */
536 void cgroup_lock(void)
537 {
538         mutex_lock(&cgroup_mutex);
539 }
540
541 /**
542  * cgroup_unlock - release lock on cgroup changes
543  *
544  * Undo the lock taken in a previous cgroup_lock() call.
545  */
546 void cgroup_unlock(void)
547 {
548         mutex_unlock(&cgroup_mutex);
549 }
550
551 /*
552  * A couple of forward declarations required, due to cyclic reference loop:
553  * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
554  * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
555  * -> cgroup_mkdir.
556  */
557
558 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
559 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
560 static int cgroup_populate_dir(struct cgroup *cgrp);
561 static struct inode_operations cgroup_dir_inode_operations;
562 static struct file_operations proc_cgroupstats_operations;
563
564 static struct backing_dev_info cgroup_backing_dev_info = {
565         .capabilities   = BDI_CAP_NO_ACCT_AND_WRITEBACK,
566 };
567
568 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
569 {
570         struct inode *inode = new_inode(sb);
571
572         if (inode) {
573                 inode->i_mode = mode;
574                 inode->i_uid = current_fsuid();
575                 inode->i_gid = current_fsgid();
576                 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
577                 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
578         }
579         return inode;
580 }
581
582 /*
583  * Call subsys's pre_destroy handler.
584  * This is called before css refcnt check.
585  */
586 static void cgroup_call_pre_destroy(struct cgroup *cgrp)
587 {
588         struct cgroup_subsys *ss;
589         for_each_subsys(cgrp->root, ss)
590                 if (ss->pre_destroy && cgrp->subsys[ss->subsys_id])
591                         ss->pre_destroy(ss, cgrp);
592         return;
593 }
594
595 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
596 {
597         /* is dentry a directory ? if so, kfree() associated cgroup */
598         if (S_ISDIR(inode->i_mode)) {
599                 struct cgroup *cgrp = dentry->d_fsdata;
600                 struct cgroup_subsys *ss;
601                 BUG_ON(!(cgroup_is_removed(cgrp)));
602                 /* It's possible for external users to be holding css
603                  * reference counts on a cgroup; css_put() needs to
604                  * be able to access the cgroup after decrementing
605                  * the reference count in order to know if it needs to
606                  * queue the cgroup to be handled by the release
607                  * agent */
608                 synchronize_rcu();
609
610                 mutex_lock(&cgroup_mutex);
611                 /*
612                  * Release the subsystem state objects.
613                  */
614                 for_each_subsys(cgrp->root, ss) {
615                         if (cgrp->subsys[ss->subsys_id])
616                                 ss->destroy(ss, cgrp);
617                 }
618
619                 cgrp->root->number_of_cgroups--;
620                 mutex_unlock(&cgroup_mutex);
621
622                 /* Drop the active superblock reference that we took when we
623                  * created the cgroup */
624                 deactivate_super(cgrp->root->sb);
625
626                 kfree(cgrp);
627         }
628         iput(inode);
629 }
630
631 static void remove_dir(struct dentry *d)
632 {
633         struct dentry *parent = dget(d->d_parent);
634
635         d_delete(d);
636         simple_rmdir(parent->d_inode, d);
637         dput(parent);
638 }
639
640 static void cgroup_clear_directory(struct dentry *dentry)
641 {
642         struct list_head *node;
643
644         BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
645         spin_lock(&dcache_lock);
646         node = dentry->d_subdirs.next;
647         while (node != &dentry->d_subdirs) {
648                 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
649                 list_del_init(node);
650                 if (d->d_inode) {
651                         /* This should never be called on a cgroup
652                          * directory with child cgroups */
653                         BUG_ON(d->d_inode->i_mode & S_IFDIR);
654                         d = dget_locked(d);
655                         spin_unlock(&dcache_lock);
656                         d_delete(d);
657                         simple_unlink(dentry->d_inode, d);
658                         dput(d);
659                         spin_lock(&dcache_lock);
660                 }
661                 node = dentry->d_subdirs.next;
662         }
663         spin_unlock(&dcache_lock);
664 }
665
666 /*
667  * NOTE : the dentry must have been dget()'ed
668  */
669 static void cgroup_d_remove_dir(struct dentry *dentry)
670 {
671         cgroup_clear_directory(dentry);
672
673         spin_lock(&dcache_lock);
674         list_del_init(&dentry->d_u.d_child);
675         spin_unlock(&dcache_lock);
676         remove_dir(dentry);
677 }
678
679 static int rebind_subsystems(struct cgroupfs_root *root,
680                               unsigned long final_bits)
681 {
682         unsigned long added_bits, removed_bits;
683         struct cgroup *cgrp = &root->top_cgroup;
684         int i;
685
686         removed_bits = root->actual_subsys_bits & ~final_bits;
687         added_bits = final_bits & ~root->actual_subsys_bits;
688         /* Check that any added subsystems are currently free */
689         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
690                 unsigned long bit = 1UL << i;
691                 struct cgroup_subsys *ss = subsys[i];
692                 if (!(bit & added_bits))
693                         continue;
694                 if (ss->root != &rootnode) {
695                         /* Subsystem isn't free */
696                         return -EBUSY;
697                 }
698         }
699
700         /* Currently we don't handle adding/removing subsystems when
701          * any child cgroups exist. This is theoretically supportable
702          * but involves complex error handling, so it's being left until
703          * later */
704         if (root->number_of_cgroups > 1)
705                 return -EBUSY;
706
707         /* Process each subsystem */
708         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
709                 struct cgroup_subsys *ss = subsys[i];
710                 unsigned long bit = 1UL << i;
711                 if (bit & added_bits) {
712                         /* We're binding this subsystem to this hierarchy */
713                         BUG_ON(cgrp->subsys[i]);
714                         BUG_ON(!dummytop->subsys[i]);
715                         BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
716                         cgrp->subsys[i] = dummytop->subsys[i];
717                         cgrp->subsys[i]->cgroup = cgrp;
718                         list_add(&ss->sibling, &root->subsys_list);
719                         rcu_assign_pointer(ss->root, root);
720                         if (ss->bind)
721                                 ss->bind(ss, cgrp);
722
723                 } else if (bit & removed_bits) {
724                         /* We're removing this subsystem */
725                         BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
726                         BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
727                         if (ss->bind)
728                                 ss->bind(ss, dummytop);
729                         dummytop->subsys[i]->cgroup = dummytop;
730                         cgrp->subsys[i] = NULL;
731                         rcu_assign_pointer(subsys[i]->root, &rootnode);
732                         list_del(&ss->sibling);
733                 } else if (bit & final_bits) {
734                         /* Subsystem state should already exist */
735                         BUG_ON(!cgrp->subsys[i]);
736                 } else {
737                         /* Subsystem state shouldn't exist */
738                         BUG_ON(cgrp->subsys[i]);
739                 }
740         }
741         root->subsys_bits = root->actual_subsys_bits = final_bits;
742         synchronize_rcu();
743
744         return 0;
745 }
746
747 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
748 {
749         struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
750         struct cgroup_subsys *ss;
751
752         mutex_lock(&cgroup_mutex);
753         for_each_subsys(root, ss)
754                 seq_printf(seq, ",%s", ss->name);
755         if (test_bit(ROOT_NOPREFIX, &root->flags))
756                 seq_puts(seq, ",noprefix");
757         if (strlen(root->release_agent_path))
758                 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
759         mutex_unlock(&cgroup_mutex);
760         return 0;
761 }
762
763 struct cgroup_sb_opts {
764         unsigned long subsys_bits;
765         unsigned long flags;
766         char *release_agent;
767 };
768
769 /* Convert a hierarchy specifier into a bitmask of subsystems and
770  * flags. */
771 static int parse_cgroupfs_options(char *data,
772                                      struct cgroup_sb_opts *opts)
773 {
774         char *token, *o = data ?: "all";
775
776         opts->subsys_bits = 0;
777         opts->flags = 0;
778         opts->release_agent = NULL;
779
780         while ((token = strsep(&o, ",")) != NULL) {
781                 if (!*token)
782                         return -EINVAL;
783                 if (!strcmp(token, "all")) {
784                         /* Add all non-disabled subsystems */
785                         int i;
786                         opts->subsys_bits = 0;
787                         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
788                                 struct cgroup_subsys *ss = subsys[i];
789                                 if (!ss->disabled)
790                                         opts->subsys_bits |= 1ul << i;
791                         }
792                 } else if (!strcmp(token, "noprefix")) {
793                         set_bit(ROOT_NOPREFIX, &opts->flags);
794                 } else if (!strncmp(token, "release_agent=", 14)) {
795                         /* Specifying two release agents is forbidden */
796                         if (opts->release_agent)
797                                 return -EINVAL;
798                         opts->release_agent = kzalloc(PATH_MAX, GFP_KERNEL);
799                         if (!opts->release_agent)
800                                 return -ENOMEM;
801                         strncpy(opts->release_agent, token + 14, PATH_MAX - 1);
802                         opts->release_agent[PATH_MAX - 1] = 0;
803                 } else {
804                         struct cgroup_subsys *ss;
805                         int i;
806                         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
807                                 ss = subsys[i];
808                                 if (!strcmp(token, ss->name)) {
809                                         if (!ss->disabled)
810                                                 set_bit(i, &opts->subsys_bits);
811                                         break;
812                                 }
813                         }
814                         if (i == CGROUP_SUBSYS_COUNT)
815                                 return -ENOENT;
816                 }
817         }
818
819         /* We can't have an empty hierarchy */
820         if (!opts->subsys_bits)
821                 return -EINVAL;
822
823         return 0;
824 }
825
826 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
827 {
828         int ret = 0;
829         struct cgroupfs_root *root = sb->s_fs_info;
830         struct cgroup *cgrp = &root->top_cgroup;
831         struct cgroup_sb_opts opts;
832
833         mutex_lock(&cgrp->dentry->d_inode->i_mutex);
834         mutex_lock(&cgroup_mutex);
835
836         /* See what subsystems are wanted */
837         ret = parse_cgroupfs_options(data, &opts);
838         if (ret)
839                 goto out_unlock;
840
841         /* Don't allow flags to change at remount */
842         if (opts.flags != root->flags) {
843                 ret = -EINVAL;
844                 goto out_unlock;
845         }
846
847         ret = rebind_subsystems(root, opts.subsys_bits);
848
849         /* (re)populate subsystem files */
850         if (!ret)
851                 cgroup_populate_dir(cgrp);
852
853         if (opts.release_agent)
854                 strcpy(root->release_agent_path, opts.release_agent);
855  out_unlock:
856         if (opts.release_agent)
857                 kfree(opts.release_agent);
858         mutex_unlock(&cgroup_mutex);
859         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
860         return ret;
861 }
862
863 static struct super_operations cgroup_ops = {
864         .statfs = simple_statfs,
865         .drop_inode = generic_delete_inode,
866         .show_options = cgroup_show_options,
867         .remount_fs = cgroup_remount,
868 };
869
870 static void init_cgroup_housekeeping(struct cgroup *cgrp)
871 {
872         INIT_LIST_HEAD(&cgrp->sibling);
873         INIT_LIST_HEAD(&cgrp->children);
874         INIT_LIST_HEAD(&cgrp->css_sets);
875         INIT_LIST_HEAD(&cgrp->release_list);
876         init_rwsem(&cgrp->pids_mutex);
877 }
878 static void init_cgroup_root(struct cgroupfs_root *root)
879 {
880         struct cgroup *cgrp = &root->top_cgroup;
881         INIT_LIST_HEAD(&root->subsys_list);
882         INIT_LIST_HEAD(&root->root_list);
883         root->number_of_cgroups = 1;
884         cgrp->root = root;
885         cgrp->top_cgroup = cgrp;
886         init_cgroup_housekeeping(cgrp);
887 }
888
889 static int cgroup_test_super(struct super_block *sb, void *data)
890 {
891         struct cgroupfs_root *new = data;
892         struct cgroupfs_root *root = sb->s_fs_info;
893
894         /* First check subsystems */
895         if (new->subsys_bits != root->subsys_bits)
896             return 0;
897
898         /* Next check flags */
899         if (new->flags != root->flags)
900                 return 0;
901
902         return 1;
903 }
904
905 static int cgroup_set_super(struct super_block *sb, void *data)
906 {
907         int ret;
908         struct cgroupfs_root *root = data;
909
910         ret = set_anon_super(sb, NULL);
911         if (ret)
912                 return ret;
913
914         sb->s_fs_info = root;
915         root->sb = sb;
916
917         sb->s_blocksize = PAGE_CACHE_SIZE;
918         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
919         sb->s_magic = CGROUP_SUPER_MAGIC;
920         sb->s_op = &cgroup_ops;
921
922         return 0;
923 }
924
925 static int cgroup_get_rootdir(struct super_block *sb)
926 {
927         struct inode *inode =
928                 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
929         struct dentry *dentry;
930
931         if (!inode)
932                 return -ENOMEM;
933
934         inode->i_fop = &simple_dir_operations;
935         inode->i_op = &cgroup_dir_inode_operations;
936         /* directories start off with i_nlink == 2 (for "." entry) */
937         inc_nlink(inode);
938         dentry = d_alloc_root(inode);
939         if (!dentry) {
940                 iput(inode);
941                 return -ENOMEM;
942         }
943         sb->s_root = dentry;
944         return 0;
945 }
946
947 static int cgroup_get_sb(struct file_system_type *fs_type,
948                          int flags, const char *unused_dev_name,
949                          void *data, struct vfsmount *mnt)
950 {
951         struct cgroup_sb_opts opts;
952         int ret = 0;
953         struct super_block *sb;
954         struct cgroupfs_root *root;
955         struct list_head tmp_cg_links;
956
957         /* First find the desired set of subsystems */
958         ret = parse_cgroupfs_options(data, &opts);
959         if (ret) {
960                 if (opts.release_agent)
961                         kfree(opts.release_agent);
962                 return ret;
963         }
964
965         root = kzalloc(sizeof(*root), GFP_KERNEL);
966         if (!root) {
967                 if (opts.release_agent)
968                         kfree(opts.release_agent);
969                 return -ENOMEM;
970         }
971
972         init_cgroup_root(root);
973         root->subsys_bits = opts.subsys_bits;
974         root->flags = opts.flags;
975         if (opts.release_agent) {
976                 strcpy(root->release_agent_path, opts.release_agent);
977                 kfree(opts.release_agent);
978         }
979
980         sb = sget(fs_type, cgroup_test_super, cgroup_set_super, root);
981
982         if (IS_ERR(sb)) {
983                 kfree(root);
984                 return PTR_ERR(sb);
985         }
986
987         if (sb->s_fs_info != root) {
988                 /* Reusing an existing superblock */
989                 BUG_ON(sb->s_root == NULL);
990                 kfree(root);
991                 root = NULL;
992         } else {
993                 /* New superblock */
994                 struct cgroup *cgrp = &root->top_cgroup;
995                 struct inode *inode;
996                 int i;
997
998                 BUG_ON(sb->s_root != NULL);
999
1000                 ret = cgroup_get_rootdir(sb);
1001                 if (ret)
1002                         goto drop_new_super;
1003                 inode = sb->s_root->d_inode;
1004
1005                 mutex_lock(&inode->i_mutex);
1006                 mutex_lock(&cgroup_mutex);
1007
1008                 /*
1009                  * We're accessing css_set_count without locking
1010                  * css_set_lock here, but that's OK - it can only be
1011                  * increased by someone holding cgroup_lock, and
1012                  * that's us. The worst that can happen is that we
1013                  * have some link structures left over
1014                  */
1015                 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1016                 if (ret) {
1017                         mutex_unlock(&cgroup_mutex);
1018                         mutex_unlock(&inode->i_mutex);
1019                         goto drop_new_super;
1020                 }
1021
1022                 ret = rebind_subsystems(root, root->subsys_bits);
1023                 if (ret == -EBUSY) {
1024                         mutex_unlock(&cgroup_mutex);
1025                         mutex_unlock(&inode->i_mutex);
1026                         goto free_cg_links;
1027                 }
1028
1029                 /* EBUSY should be the only error here */
1030                 BUG_ON(ret);
1031
1032                 list_add(&root->root_list, &roots);
1033                 root_count++;
1034
1035                 sb->s_root->d_fsdata = &root->top_cgroup;
1036                 root->top_cgroup.dentry = sb->s_root;
1037
1038                 /* Link the top cgroup in this hierarchy into all
1039                  * the css_set objects */
1040                 write_lock(&css_set_lock);
1041                 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1042                         struct hlist_head *hhead = &css_set_table[i];
1043                         struct hlist_node *node;
1044                         struct css_set *cg;
1045
1046                         hlist_for_each_entry(cg, node, hhead, hlist) {
1047                                 struct cg_cgroup_link *link;
1048
1049                                 BUG_ON(list_empty(&tmp_cg_links));
1050                                 link = list_entry(tmp_cg_links.next,
1051                                                   struct cg_cgroup_link,
1052                                                   cgrp_link_list);
1053                                 list_del(&link->cgrp_link_list);
1054                                 link->cg = cg;
1055                                 list_add(&link->cgrp_link_list,
1056                                          &root->top_cgroup.css_sets);
1057                                 list_add(&link->cg_link_list, &cg->cg_links);
1058                         }
1059                 }
1060                 write_unlock(&css_set_lock);
1061
1062                 free_cg_links(&tmp_cg_links);
1063
1064                 BUG_ON(!list_empty(&cgrp->sibling));
1065                 BUG_ON(!list_empty(&cgrp->children));
1066                 BUG_ON(root->number_of_cgroups != 1);
1067
1068                 cgroup_populate_dir(cgrp);
1069                 mutex_unlock(&inode->i_mutex);
1070                 mutex_unlock(&cgroup_mutex);
1071         }
1072
1073         return simple_set_mnt(mnt, sb);
1074
1075  free_cg_links:
1076         free_cg_links(&tmp_cg_links);
1077  drop_new_super:
1078         up_write(&sb->s_umount);
1079         deactivate_super(sb);
1080         return ret;
1081 }
1082
1083 static void cgroup_kill_sb(struct super_block *sb) {
1084         struct cgroupfs_root *root = sb->s_fs_info;
1085         struct cgroup *cgrp = &root->top_cgroup;
1086         int ret;
1087         struct cg_cgroup_link *link;
1088         struct cg_cgroup_link *saved_link;
1089
1090         BUG_ON(!root);
1091
1092         BUG_ON(root->number_of_cgroups != 1);
1093         BUG_ON(!list_empty(&cgrp->children));
1094         BUG_ON(!list_empty(&cgrp->sibling));
1095
1096         mutex_lock(&cgroup_mutex);
1097
1098         /* Rebind all subsystems back to the default hierarchy */
1099         ret = rebind_subsystems(root, 0);
1100         /* Shouldn't be able to fail ... */
1101         BUG_ON(ret);
1102
1103         /*
1104          * Release all the links from css_sets to this hierarchy's
1105          * root cgroup
1106          */
1107         write_lock(&css_set_lock);
1108
1109         list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1110                                  cgrp_link_list) {
1111                 list_del(&link->cg_link_list);
1112                 list_del(&link->cgrp_link_list);
1113                 kfree(link);
1114         }
1115         write_unlock(&css_set_lock);
1116
1117         if (!list_empty(&root->root_list)) {
1118                 list_del(&root->root_list);
1119                 root_count--;
1120         }
1121         mutex_unlock(&cgroup_mutex);
1122
1123         kfree(root);
1124         kill_litter_super(sb);
1125 }
1126
1127 static struct file_system_type cgroup_fs_type = {
1128         .name = "cgroup",
1129         .get_sb = cgroup_get_sb,
1130         .kill_sb = cgroup_kill_sb,
1131 };
1132
1133 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1134 {
1135         return dentry->d_fsdata;
1136 }
1137
1138 static inline struct cftype *__d_cft(struct dentry *dentry)
1139 {
1140         return dentry->d_fsdata;
1141 }
1142
1143 /**
1144  * cgroup_path - generate the path of a cgroup
1145  * @cgrp: the cgroup in question
1146  * @buf: the buffer to write the path into
1147  * @buflen: the length of the buffer
1148  *
1149  * Called with cgroup_mutex held. Writes path of cgroup into buf.
1150  * Returns 0 on success, -errno on error.
1151  */
1152 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1153 {
1154         char *start;
1155
1156         if (cgrp == dummytop) {
1157                 /*
1158                  * Inactive subsystems have no dentry for their root
1159                  * cgroup
1160                  */
1161                 strcpy(buf, "/");
1162                 return 0;
1163         }
1164
1165         start = buf + buflen;
1166
1167         *--start = '\0';
1168         for (;;) {
1169                 int len = cgrp->dentry->d_name.len;
1170                 if ((start -= len) < buf)
1171                         return -ENAMETOOLONG;
1172                 memcpy(start, cgrp->dentry->d_name.name, len);
1173                 cgrp = cgrp->parent;
1174                 if (!cgrp)
1175                         break;
1176                 if (!cgrp->parent)
1177                         continue;
1178                 if (--start < buf)
1179                         return -ENAMETOOLONG;
1180                 *start = '/';
1181         }
1182         memmove(buf, start, buf + buflen - start);
1183         return 0;
1184 }
1185
1186 /*
1187  * Return the first subsystem attached to a cgroup's hierarchy, and
1188  * its subsystem id.
1189  */
1190
1191 static void get_first_subsys(const struct cgroup *cgrp,
1192                         struct cgroup_subsys_state **css, int *subsys_id)
1193 {
1194         const struct cgroupfs_root *root = cgrp->root;
1195         const struct cgroup_subsys *test_ss;
1196         BUG_ON(list_empty(&root->subsys_list));
1197         test_ss = list_entry(root->subsys_list.next,
1198                              struct cgroup_subsys, sibling);
1199         if (css) {
1200                 *css = cgrp->subsys[test_ss->subsys_id];
1201                 BUG_ON(!*css);
1202         }
1203         if (subsys_id)
1204                 *subsys_id = test_ss->subsys_id;
1205 }
1206
1207 /**
1208  * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1209  * @cgrp: the cgroup the task is attaching to
1210  * @tsk: the task to be attached
1211  *
1212  * Call holding cgroup_mutex. May take task_lock of
1213  * the task 'tsk' during call.
1214  */
1215 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1216 {
1217         int retval = 0;
1218         struct cgroup_subsys *ss;
1219         struct cgroup *oldcgrp;
1220         struct css_set *cg = tsk->cgroups;
1221         struct css_set *newcg;
1222         struct cgroupfs_root *root = cgrp->root;
1223         int subsys_id;
1224
1225         get_first_subsys(cgrp, NULL, &subsys_id);
1226
1227         /* Nothing to do if the task is already in that cgroup */
1228         oldcgrp = task_cgroup(tsk, subsys_id);
1229         if (cgrp == oldcgrp)
1230                 return 0;
1231
1232         for_each_subsys(root, ss) {
1233                 if (ss->can_attach) {
1234                         retval = ss->can_attach(ss, cgrp, tsk);
1235                         if (retval)
1236                                 return retval;
1237                 }
1238         }
1239
1240         /*
1241          * Locate or allocate a new css_set for this task,
1242          * based on its final set of cgroups
1243          */
1244         newcg = find_css_set(cg, cgrp);
1245         if (!newcg)
1246                 return -ENOMEM;
1247
1248         task_lock(tsk);
1249         if (tsk->flags & PF_EXITING) {
1250                 task_unlock(tsk);
1251                 put_css_set(newcg);
1252                 return -ESRCH;
1253         }
1254         rcu_assign_pointer(tsk->cgroups, newcg);
1255         task_unlock(tsk);
1256
1257         /* Update the css_set linked lists if we're using them */
1258         write_lock(&css_set_lock);
1259         if (!list_empty(&tsk->cg_list)) {
1260                 list_del(&tsk->cg_list);
1261                 list_add(&tsk->cg_list, &newcg->tasks);
1262         }
1263         write_unlock(&css_set_lock);
1264
1265         for_each_subsys(root, ss) {
1266                 if (ss->attach)
1267                         ss->attach(ss, cgrp, oldcgrp, tsk);
1268         }
1269         set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1270         synchronize_rcu();
1271         put_css_set(cg);
1272         return 0;
1273 }
1274
1275 /*
1276  * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
1277  * held. May take task_lock of task
1278  */
1279 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
1280 {
1281         struct task_struct *tsk;
1282         const struct cred *cred = current_cred(), *tcred;
1283         int ret;
1284
1285         if (pid) {
1286                 rcu_read_lock();
1287                 tsk = find_task_by_vpid(pid);
1288                 if (!tsk || tsk->flags & PF_EXITING) {
1289                         rcu_read_unlock();
1290                         return -ESRCH;
1291                 }
1292
1293                 tcred = __task_cred(tsk);
1294                 if (cred->euid &&
1295                     cred->euid != tcred->uid &&
1296                     cred->euid != tcred->suid) {
1297                         rcu_read_unlock();
1298                         return -EACCES;
1299                 }
1300                 get_task_struct(tsk);
1301                 rcu_read_unlock();
1302         } else {
1303                 tsk = current;
1304                 get_task_struct(tsk);
1305         }
1306
1307         ret = cgroup_attach_task(cgrp, tsk);
1308         put_task_struct(tsk);
1309         return ret;
1310 }
1311
1312 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
1313 {
1314         int ret;
1315         if (!cgroup_lock_live_group(cgrp))
1316                 return -ENODEV;
1317         ret = attach_task_by_pid(cgrp, pid);
1318         cgroup_unlock();
1319         return ret;
1320 }
1321
1322 /* The various types of files and directories in a cgroup file system */
1323 enum cgroup_filetype {
1324         FILE_ROOT,
1325         FILE_DIR,
1326         FILE_TASKLIST,
1327         FILE_NOTIFY_ON_RELEASE,
1328         FILE_RELEASE_AGENT,
1329 };
1330
1331 /**
1332  * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1333  * @cgrp: the cgroup to be checked for liveness
1334  *
1335  * On success, returns true; the lock should be later released with
1336  * cgroup_unlock(). On failure returns false with no lock held.
1337  */
1338 bool cgroup_lock_live_group(struct cgroup *cgrp)
1339 {
1340         mutex_lock(&cgroup_mutex);
1341         if (cgroup_is_removed(cgrp)) {
1342                 mutex_unlock(&cgroup_mutex);
1343                 return false;
1344         }
1345         return true;
1346 }
1347
1348 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1349                                       const char *buffer)
1350 {
1351         BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1352         if (!cgroup_lock_live_group(cgrp))
1353                 return -ENODEV;
1354         strcpy(cgrp->root->release_agent_path, buffer);
1355         cgroup_unlock();
1356         return 0;
1357 }
1358
1359 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1360                                      struct seq_file *seq)
1361 {
1362         if (!cgroup_lock_live_group(cgrp))
1363                 return -ENODEV;
1364         seq_puts(seq, cgrp->root->release_agent_path);
1365         seq_putc(seq, '\n');
1366         cgroup_unlock();
1367         return 0;
1368 }
1369
1370 /* A buffer size big enough for numbers or short strings */
1371 #define CGROUP_LOCAL_BUFFER_SIZE 64
1372
1373 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1374                                 struct file *file,
1375                                 const char __user *userbuf,
1376                                 size_t nbytes, loff_t *unused_ppos)
1377 {
1378         char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1379         int retval = 0;
1380         char *end;
1381
1382         if (!nbytes)
1383                 return -EINVAL;
1384         if (nbytes >= sizeof(buffer))
1385                 return -E2BIG;
1386         if (copy_from_user(buffer, userbuf, nbytes))
1387                 return -EFAULT;
1388
1389         buffer[nbytes] = 0;     /* nul-terminate */
1390         strstrip(buffer);
1391         if (cft->write_u64) {
1392                 u64 val = simple_strtoull(buffer, &end, 0);
1393                 if (*end)
1394                         return -EINVAL;
1395                 retval = cft->write_u64(cgrp, cft, val);
1396         } else {
1397                 s64 val = simple_strtoll(buffer, &end, 0);
1398                 if (*end)
1399                         return -EINVAL;
1400                 retval = cft->write_s64(cgrp, cft, val);
1401         }
1402         if (!retval)
1403                 retval = nbytes;
1404         return retval;
1405 }
1406
1407 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1408                                    struct file *file,
1409                                    const char __user *userbuf,
1410                                    size_t nbytes, loff_t *unused_ppos)
1411 {
1412         char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1413         int retval = 0;
1414         size_t max_bytes = cft->max_write_len;
1415         char *buffer = local_buffer;
1416
1417         if (!max_bytes)
1418                 max_bytes = sizeof(local_buffer) - 1;
1419         if (nbytes >= max_bytes)
1420                 return -E2BIG;
1421         /* Allocate a dynamic buffer if we need one */
1422         if (nbytes >= sizeof(local_buffer)) {
1423                 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1424                 if (buffer == NULL)
1425                         return -ENOMEM;
1426         }
1427         if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
1428                 retval = -EFAULT;
1429                 goto out;
1430         }
1431
1432         buffer[nbytes] = 0;     /* nul-terminate */
1433         strstrip(buffer);
1434         retval = cft->write_string(cgrp, cft, buffer);
1435         if (!retval)
1436                 retval = nbytes;
1437 out:
1438         if (buffer != local_buffer)
1439                 kfree(buffer);
1440         return retval;
1441 }
1442
1443 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1444                                                 size_t nbytes, loff_t *ppos)
1445 {
1446         struct cftype *cft = __d_cft(file->f_dentry);
1447         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1448
1449         if (!cft || cgroup_is_removed(cgrp))
1450                 return -ENODEV;
1451         if (cft->write)
1452                 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1453         if (cft->write_u64 || cft->write_s64)
1454                 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1455         if (cft->write_string)
1456                 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1457         if (cft->trigger) {
1458                 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1459                 return ret ? ret : nbytes;
1460         }
1461         return -EINVAL;
1462 }
1463
1464 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1465                                struct file *file,
1466                                char __user *buf, size_t nbytes,
1467                                loff_t *ppos)
1468 {
1469         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1470         u64 val = cft->read_u64(cgrp, cft);
1471         int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1472
1473         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1474 }
1475
1476 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1477                                struct file *file,
1478                                char __user *buf, size_t nbytes,
1479                                loff_t *ppos)
1480 {
1481         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1482         s64 val = cft->read_s64(cgrp, cft);
1483         int len = sprintf(tmp, "%lld\n", (long long) val);
1484
1485         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1486 }
1487
1488 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1489                                    size_t nbytes, loff_t *ppos)
1490 {
1491         struct cftype *cft = __d_cft(file->f_dentry);
1492         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1493
1494         if (!cft || cgroup_is_removed(cgrp))
1495                 return -ENODEV;
1496
1497         if (cft->read)
1498                 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1499         if (cft->read_u64)
1500                 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1501         if (cft->read_s64)
1502                 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1503         return -EINVAL;
1504 }
1505
1506 /*
1507  * seqfile ops/methods for returning structured data. Currently just
1508  * supports string->u64 maps, but can be extended in future.
1509  */
1510
1511 struct cgroup_seqfile_state {
1512         struct cftype *cft;
1513         struct cgroup *cgroup;
1514 };
1515
1516 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1517 {
1518         struct seq_file *sf = cb->state;
1519         return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1520 }
1521
1522 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1523 {
1524         struct cgroup_seqfile_state *state = m->private;
1525         struct cftype *cft = state->cft;
1526         if (cft->read_map) {
1527                 struct cgroup_map_cb cb = {
1528                         .fill = cgroup_map_add,
1529                         .state = m,
1530                 };
1531                 return cft->read_map(state->cgroup, cft, &cb);
1532         }
1533         return cft->read_seq_string(state->cgroup, cft, m);
1534 }
1535
1536 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
1537 {
1538         struct seq_file *seq = file->private_data;
1539         kfree(seq->private);
1540         return single_release(inode, file);
1541 }
1542
1543 static struct file_operations cgroup_seqfile_operations = {
1544         .read = seq_read,
1545         .write = cgroup_file_write,
1546         .llseek = seq_lseek,
1547         .release = cgroup_seqfile_release,
1548 };
1549
1550 static int cgroup_file_open(struct inode *inode, struct file *file)
1551 {
1552         int err;
1553         struct cftype *cft;
1554
1555         err = generic_file_open(inode, file);
1556         if (err)
1557                 return err;
1558
1559         cft = __d_cft(file->f_dentry);
1560         if (!cft)
1561                 return -ENODEV;
1562         if (cft->read_map || cft->read_seq_string) {
1563                 struct cgroup_seqfile_state *state =
1564                         kzalloc(sizeof(*state), GFP_USER);
1565                 if (!state)
1566                         return -ENOMEM;
1567                 state->cft = cft;
1568                 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
1569                 file->f_op = &cgroup_seqfile_operations;
1570                 err = single_open(file, cgroup_seqfile_show, state);
1571                 if (err < 0)
1572                         kfree(state);
1573         } else if (cft->open)
1574                 err = cft->open(inode, file);
1575         else
1576                 err = 0;
1577
1578         return err;
1579 }
1580
1581 static int cgroup_file_release(struct inode *inode, struct file *file)
1582 {
1583         struct cftype *cft = __d_cft(file->f_dentry);
1584         if (cft->release)
1585                 return cft->release(inode, file);
1586         return 0;
1587 }
1588
1589 /*
1590  * cgroup_rename - Only allow simple rename of directories in place.
1591  */
1592 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
1593                             struct inode *new_dir, struct dentry *new_dentry)
1594 {
1595         if (!S_ISDIR(old_dentry->d_inode->i_mode))
1596                 return -ENOTDIR;
1597         if (new_dentry->d_inode)
1598                 return -EEXIST;
1599         if (old_dir != new_dir)
1600                 return -EIO;
1601         return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1602 }
1603
1604 static struct file_operations cgroup_file_operations = {
1605         .read = cgroup_file_read,
1606         .write = cgroup_file_write,
1607         .llseek = generic_file_llseek,
1608         .open = cgroup_file_open,
1609         .release = cgroup_file_release,
1610 };
1611
1612 static struct inode_operations cgroup_dir_inode_operations = {
1613         .lookup = simple_lookup,
1614         .mkdir = cgroup_mkdir,
1615         .rmdir = cgroup_rmdir,
1616         .rename = cgroup_rename,
1617 };
1618
1619 static int cgroup_create_file(struct dentry *dentry, int mode,
1620                                 struct super_block *sb)
1621 {
1622         static struct dentry_operations cgroup_dops = {
1623                 .d_iput = cgroup_diput,
1624         };
1625
1626         struct inode *inode;
1627
1628         if (!dentry)
1629                 return -ENOENT;
1630         if (dentry->d_inode)
1631                 return -EEXIST;
1632
1633         inode = cgroup_new_inode(mode, sb);
1634         if (!inode)
1635                 return -ENOMEM;
1636
1637         if (S_ISDIR(mode)) {
1638                 inode->i_op = &cgroup_dir_inode_operations;
1639                 inode->i_fop = &simple_dir_operations;
1640
1641                 /* start off with i_nlink == 2 (for "." entry) */
1642                 inc_nlink(inode);
1643
1644                 /* start with the directory inode held, so that we can
1645                  * populate it without racing with another mkdir */
1646                 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
1647         } else if (S_ISREG(mode)) {
1648                 inode->i_size = 0;
1649                 inode->i_fop = &cgroup_file_operations;
1650         }
1651         dentry->d_op = &cgroup_dops;
1652         d_instantiate(dentry, inode);
1653         dget(dentry);   /* Extra count - pin the dentry in core */
1654         return 0;
1655 }
1656
1657 /*
1658  * cgroup_create_dir - create a directory for an object.
1659  * @cgrp: the cgroup we create the directory for. It must have a valid
1660  *        ->parent field. And we are going to fill its ->dentry field.
1661  * @dentry: dentry of the new cgroup
1662  * @mode: mode to set on new directory.
1663  */
1664 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
1665                                 int mode)
1666 {
1667         struct dentry *parent;
1668         int error = 0;
1669
1670         parent = cgrp->parent->dentry;
1671         error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
1672         if (!error) {
1673                 dentry->d_fsdata = cgrp;
1674                 inc_nlink(parent->d_inode);
1675                 cgrp->dentry = dentry;
1676                 dget(dentry);
1677         }
1678         dput(dentry);
1679
1680         return error;
1681 }
1682
1683 int cgroup_add_file(struct cgroup *cgrp,
1684                        struct cgroup_subsys *subsys,
1685                        const struct cftype *cft)
1686 {
1687         struct dentry *dir = cgrp->dentry;
1688         struct dentry *dentry;
1689         int error;
1690
1691         char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
1692         if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
1693                 strcpy(name, subsys->name);
1694                 strcat(name, ".");
1695         }
1696         strcat(name, cft->name);
1697         BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
1698         dentry = lookup_one_len(name, dir, strlen(name));
1699         if (!IS_ERR(dentry)) {
1700                 error = cgroup_create_file(dentry, 0644 | S_IFREG,
1701                                                 cgrp->root->sb);
1702                 if (!error)
1703                         dentry->d_fsdata = (void *)cft;
1704                 dput(dentry);
1705         } else
1706                 error = PTR_ERR(dentry);
1707         return error;
1708 }
1709
1710 int cgroup_add_files(struct cgroup *cgrp,
1711                         struct cgroup_subsys *subsys,
1712                         const struct cftype cft[],
1713                         int count)
1714 {
1715         int i, err;
1716         for (i = 0; i < count; i++) {
1717                 err = cgroup_add_file(cgrp, subsys, &cft[i]);
1718                 if (err)
1719                         return err;
1720         }
1721         return 0;
1722 }
1723
1724 /**
1725  * cgroup_task_count - count the number of tasks in a cgroup.
1726  * @cgrp: the cgroup in question
1727  *
1728  * Return the number of tasks in the cgroup.
1729  */
1730 int cgroup_task_count(const struct cgroup *cgrp)
1731 {
1732         int count = 0;
1733         struct cg_cgroup_link *link;
1734
1735         read_lock(&css_set_lock);
1736         list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
1737                 count += atomic_read(&link->cg->refcount);
1738         }
1739         read_unlock(&css_set_lock);
1740         return count;
1741 }
1742
1743 /*
1744  * Advance a list_head iterator.  The iterator should be positioned at
1745  * the start of a css_set
1746  */
1747 static void cgroup_advance_iter(struct cgroup *cgrp,
1748                                           struct cgroup_iter *it)
1749 {
1750         struct list_head *l = it->cg_link;
1751         struct cg_cgroup_link *link;
1752         struct css_set *cg;
1753
1754         /* Advance to the next non-empty css_set */
1755         do {
1756                 l = l->next;
1757                 if (l == &cgrp->css_sets) {
1758                         it->cg_link = NULL;
1759                         return;
1760                 }
1761                 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
1762                 cg = link->cg;
1763         } while (list_empty(&cg->tasks));
1764         it->cg_link = l;
1765         it->task = cg->tasks.next;
1766 }
1767
1768 /*
1769  * To reduce the fork() overhead for systems that are not actually
1770  * using their cgroups capability, we don't maintain the lists running
1771  * through each css_set to its tasks until we see the list actually
1772  * used - in other words after the first call to cgroup_iter_start().
1773  *
1774  * The tasklist_lock is not held here, as do_each_thread() and
1775  * while_each_thread() are protected by RCU.
1776  */
1777 static void cgroup_enable_task_cg_lists(void)
1778 {
1779         struct task_struct *p, *g;
1780         write_lock(&css_set_lock);
1781         use_task_css_set_links = 1;
1782         do_each_thread(g, p) {
1783                 task_lock(p);
1784                 /*
1785                  * We should check if the process is exiting, otherwise
1786                  * it will race with cgroup_exit() in that the list
1787                  * entry won't be deleted though the process has exited.
1788                  */
1789                 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
1790                         list_add(&p->cg_list, &p->cgroups->tasks);
1791                 task_unlock(p);
1792         } while_each_thread(g, p);
1793         write_unlock(&css_set_lock);
1794 }
1795
1796 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
1797 {
1798         /*
1799          * The first time anyone tries to iterate across a cgroup,
1800          * we need to enable the list linking each css_set to its
1801          * tasks, and fix up all existing tasks.
1802          */
1803         if (!use_task_css_set_links)
1804                 cgroup_enable_task_cg_lists();
1805
1806         read_lock(&css_set_lock);
1807         it->cg_link = &cgrp->css_sets;
1808         cgroup_advance_iter(cgrp, it);
1809 }
1810
1811 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
1812                                         struct cgroup_iter *it)
1813 {
1814         struct task_struct *res;
1815         struct list_head *l = it->task;
1816
1817         /* If the iterator cg is NULL, we have no tasks */
1818         if (!it->cg_link)
1819                 return NULL;
1820         res = list_entry(l, struct task_struct, cg_list);
1821         /* Advance iterator to find next entry */
1822         l = l->next;
1823         if (l == &res->cgroups->tasks) {
1824                 /* We reached the end of this task list - move on to
1825                  * the next cg_cgroup_link */
1826                 cgroup_advance_iter(cgrp, it);
1827         } else {
1828                 it->task = l;
1829         }
1830         return res;
1831 }
1832
1833 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
1834 {
1835         read_unlock(&css_set_lock);
1836 }
1837
1838 static inline int started_after_time(struct task_struct *t1,
1839                                      struct timespec *time,
1840                                      struct task_struct *t2)
1841 {
1842         int start_diff = timespec_compare(&t1->start_time, time);
1843         if (start_diff > 0) {
1844                 return 1;
1845         } else if (start_diff < 0) {
1846                 return 0;
1847         } else {
1848                 /*
1849                  * Arbitrarily, if two processes started at the same
1850                  * time, we'll say that the lower pointer value
1851                  * started first. Note that t2 may have exited by now
1852                  * so this may not be a valid pointer any longer, but
1853                  * that's fine - it still serves to distinguish
1854                  * between two tasks started (effectively) simultaneously.
1855                  */
1856                 return t1 > t2;
1857         }
1858 }
1859
1860 /*
1861  * This function is a callback from heap_insert() and is used to order
1862  * the heap.
1863  * In this case we order the heap in descending task start time.
1864  */
1865 static inline int started_after(void *p1, void *p2)
1866 {
1867         struct task_struct *t1 = p1;
1868         struct task_struct *t2 = p2;
1869         return started_after_time(t1, &t2->start_time, t2);
1870 }
1871
1872 /**
1873  * cgroup_scan_tasks - iterate though all the tasks in a cgroup
1874  * @scan: struct cgroup_scanner containing arguments for the scan
1875  *
1876  * Arguments include pointers to callback functions test_task() and
1877  * process_task().
1878  * Iterate through all the tasks in a cgroup, calling test_task() for each,
1879  * and if it returns true, call process_task() for it also.
1880  * The test_task pointer may be NULL, meaning always true (select all tasks).
1881  * Effectively duplicates cgroup_iter_{start,next,end}()
1882  * but does not lock css_set_lock for the call to process_task().
1883  * The struct cgroup_scanner may be embedded in any structure of the caller's
1884  * creation.
1885  * It is guaranteed that process_task() will act on every task that
1886  * is a member of the cgroup for the duration of this call. This
1887  * function may or may not call process_task() for tasks that exit
1888  * or move to a different cgroup during the call, or are forked or
1889  * move into the cgroup during the call.
1890  *
1891  * Note that test_task() may be called with locks held, and may in some
1892  * situations be called multiple times for the same task, so it should
1893  * be cheap.
1894  * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
1895  * pre-allocated and will be used for heap operations (and its "gt" member will
1896  * be overwritten), else a temporary heap will be used (allocation of which
1897  * may cause this function to fail).
1898  */
1899 int cgroup_scan_tasks(struct cgroup_scanner *scan)
1900 {
1901         int retval, i;
1902         struct cgroup_iter it;
1903         struct task_struct *p, *dropped;
1904         /* Never dereference latest_task, since it's not refcounted */
1905         struct task_struct *latest_task = NULL;
1906         struct ptr_heap tmp_heap;
1907         struct ptr_heap *heap;
1908         struct timespec latest_time = { 0, 0 };
1909
1910         if (scan->heap) {
1911                 /* The caller supplied our heap and pre-allocated its memory */
1912                 heap = scan->heap;
1913                 heap->gt = &started_after;
1914         } else {
1915                 /* We need to allocate our own heap memory */
1916                 heap = &tmp_heap;
1917                 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
1918                 if (retval)
1919                         /* cannot allocate the heap */
1920                         return retval;
1921         }
1922
1923  again:
1924         /*
1925          * Scan tasks in the cgroup, using the scanner's "test_task" callback
1926          * to determine which are of interest, and using the scanner's
1927          * "process_task" callback to process any of them that need an update.
1928          * Since we don't want to hold any locks during the task updates,
1929          * gather tasks to be processed in a heap structure.
1930          * The heap is sorted by descending task start time.
1931          * If the statically-sized heap fills up, we overflow tasks that
1932          * started later, and in future iterations only consider tasks that
1933          * started after the latest task in the previous pass. This
1934          * guarantees forward progress and that we don't miss any tasks.
1935          */
1936         heap->size = 0;
1937         cgroup_iter_start(scan->cg, &it);
1938         while ((p = cgroup_iter_next(scan->cg, &it))) {
1939                 /*
1940                  * Only affect tasks that qualify per the caller's callback,
1941                  * if he provided one
1942                  */
1943                 if (scan->test_task && !scan->test_task(p, scan))
1944                         continue;
1945                 /*
1946                  * Only process tasks that started after the last task
1947                  * we processed
1948                  */
1949                 if (!started_after_time(p, &latest_time, latest_task))
1950                         continue;
1951                 dropped = heap_insert(heap, p);
1952                 if (dropped == NULL) {
1953                         /*
1954                          * The new task was inserted; the heap wasn't
1955                          * previously full
1956                          */
1957                         get_task_struct(p);
1958                 } else if (dropped != p) {
1959                         /*
1960                          * The new task was inserted, and pushed out a
1961                          * different task
1962                          */
1963                         get_task_struct(p);
1964                         put_task_struct(dropped);
1965                 }
1966                 /*
1967                  * Else the new task was newer than anything already in
1968                  * the heap and wasn't inserted
1969                  */
1970         }
1971         cgroup_iter_end(scan->cg, &it);
1972
1973         if (heap->size) {
1974                 for (i = 0; i < heap->size; i++) {
1975                         struct task_struct *q = heap->ptrs[i];
1976                         if (i == 0) {
1977                                 latest_time = q->start_time;
1978                                 latest_task = q;
1979                         }
1980                         /* Process the task per the caller's callback */
1981                         scan->process_task(q, scan);
1982                         put_task_struct(q);
1983                 }
1984                 /*
1985                  * If we had to process any tasks at all, scan again
1986                  * in case some of them were in the middle of forking
1987                  * children that didn't get processed.
1988                  * Not the most efficient way to do it, but it avoids
1989                  * having to take callback_mutex in the fork path
1990                  */
1991                 goto again;
1992         }
1993         if (heap == &tmp_heap)
1994                 heap_free(&tmp_heap);
1995         return 0;
1996 }
1997
1998 /*
1999  * Stuff for reading the 'tasks' file.
2000  *
2001  * Reading this file can return large amounts of data if a cgroup has
2002  * *lots* of attached tasks. So it may need several calls to read(),
2003  * but we cannot guarantee that the information we produce is correct
2004  * unless we produce it entirely atomically.
2005  *
2006  */
2007
2008 /*
2009  * Load into 'pidarray' up to 'npids' of the tasks using cgroup
2010  * 'cgrp'.  Return actual number of pids loaded.  No need to
2011  * task_lock(p) when reading out p->cgroup, since we're in an RCU
2012  * read section, so the css_set can't go away, and is
2013  * immutable after creation.
2014  */
2015 static int pid_array_load(pid_t *pidarray, int npids, struct cgroup *cgrp)
2016 {
2017         int n = 0;
2018         struct cgroup_iter it;
2019         struct task_struct *tsk;
2020         cgroup_iter_start(cgrp, &it);
2021         while ((tsk = cgroup_iter_next(cgrp, &it))) {
2022                 if (unlikely(n == npids))
2023                         break;
2024                 pidarray[n++] = task_pid_vnr(tsk);
2025         }
2026         cgroup_iter_end(cgrp, &it);
2027         return n;
2028 }
2029
2030 /**
2031  * cgroupstats_build - build and fill cgroupstats
2032  * @stats: cgroupstats to fill information into
2033  * @dentry: A dentry entry belonging to the cgroup for which stats have
2034  * been requested.
2035  *
2036  * Build and fill cgroupstats so that taskstats can export it to user
2037  * space.
2038  */
2039 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2040 {
2041         int ret = -EINVAL;
2042         struct cgroup *cgrp;
2043         struct cgroup_iter it;
2044         struct task_struct *tsk;
2045
2046         /*
2047          * Validate dentry by checking the superblock operations,
2048          * and make sure it's a directory.
2049          */
2050         if (dentry->d_sb->s_op != &cgroup_ops ||
2051             !S_ISDIR(dentry->d_inode->i_mode))
2052                  goto err;
2053
2054         ret = 0;
2055         cgrp = dentry->d_fsdata;
2056         rcu_read_lock();
2057
2058         cgroup_iter_start(cgrp, &it);
2059         while ((tsk = cgroup_iter_next(cgrp, &it))) {
2060                 switch (tsk->state) {
2061                 case TASK_RUNNING:
2062                         stats->nr_running++;
2063                         break;
2064                 case TASK_INTERRUPTIBLE:
2065                         stats->nr_sleeping++;
2066                         break;
2067                 case TASK_UNINTERRUPTIBLE:
2068                         stats->nr_uninterruptible++;
2069                         break;
2070                 case TASK_STOPPED:
2071                         stats->nr_stopped++;
2072                         break;
2073                 default:
2074                         if (delayacct_is_task_waiting_on_io(tsk))
2075                                 stats->nr_io_wait++;
2076                         break;
2077                 }
2078         }
2079         cgroup_iter_end(cgrp, &it);
2080
2081         rcu_read_unlock();
2082 err:
2083         return ret;
2084 }
2085
2086 static int cmppid(const void *a, const void *b)
2087 {
2088         return *(pid_t *)a - *(pid_t *)b;
2089 }
2090
2091
2092 /*
2093  * seq_file methods for the "tasks" file. The seq_file position is the
2094  * next pid to display; the seq_file iterator is a pointer to the pid
2095  * in the cgroup->tasks_pids array.
2096  */
2097
2098 static void *cgroup_tasks_start(struct seq_file *s, loff_t *pos)
2099 {
2100         /*
2101          * Initially we receive a position value that corresponds to
2102          * one more than the last pid shown (or 0 on the first call or
2103          * after a seek to the start). Use a binary-search to find the
2104          * next pid to display, if any
2105          */
2106         struct cgroup *cgrp = s->private;
2107         int index = 0, pid = *pos;
2108         int *iter;
2109
2110         down_read(&cgrp->pids_mutex);
2111         if (pid) {
2112                 int end = cgrp->pids_length;
2113
2114                 while (index < end) {
2115                         int mid = (index + end) / 2;
2116                         if (cgrp->tasks_pids[mid] == pid) {
2117                                 index = mid;
2118                                 break;
2119                         } else if (cgrp->tasks_pids[mid] <= pid)
2120                                 index = mid + 1;
2121                         else
2122                                 end = mid;
2123                 }
2124         }
2125         /* If we're off the end of the array, we're done */
2126         if (index >= cgrp->pids_length)
2127                 return NULL;
2128         /* Update the abstract position to be the actual pid that we found */
2129         iter = cgrp->tasks_pids + index;
2130         *pos = *iter;
2131         return iter;
2132 }
2133
2134 static void cgroup_tasks_stop(struct seq_file *s, void *v)
2135 {
2136         struct cgroup *cgrp = s->private;
2137         up_read(&cgrp->pids_mutex);
2138 }
2139
2140 static void *cgroup_tasks_next(struct seq_file *s, void *v, loff_t *pos)
2141 {
2142         struct cgroup *cgrp = s->private;
2143         int *p = v;
2144         int *end = cgrp->tasks_pids + cgrp->pids_length;
2145
2146         /*
2147          * Advance to the next pid in the array. If this goes off the
2148          * end, we're done
2149          */
2150         p++;
2151         if (p >= end) {
2152                 return NULL;
2153         } else {
2154                 *pos = *p;
2155                 return p;
2156         }
2157 }
2158
2159 static int cgroup_tasks_show(struct seq_file *s, void *v)
2160 {
2161         return seq_printf(s, "%d\n", *(int *)v);
2162 }
2163
2164 static struct seq_operations cgroup_tasks_seq_operations = {
2165         .start = cgroup_tasks_start,
2166         .stop = cgroup_tasks_stop,
2167         .next = cgroup_tasks_next,
2168         .show = cgroup_tasks_show,
2169 };
2170
2171 static void release_cgroup_pid_array(struct cgroup *cgrp)
2172 {
2173         down_write(&cgrp->pids_mutex);
2174         BUG_ON(!cgrp->pids_use_count);
2175         if (!--cgrp->pids_use_count) {
2176                 kfree(cgrp->tasks_pids);
2177                 cgrp->tasks_pids = NULL;
2178                 cgrp->pids_length = 0;
2179         }
2180         up_write(&cgrp->pids_mutex);
2181 }
2182
2183 static int cgroup_tasks_release(struct inode *inode, struct file *file)
2184 {
2185         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2186
2187         if (!(file->f_mode & FMODE_READ))
2188                 return 0;
2189
2190         release_cgroup_pid_array(cgrp);
2191         return seq_release(inode, file);
2192 }
2193
2194 static struct file_operations cgroup_tasks_operations = {
2195         .read = seq_read,
2196         .llseek = seq_lseek,
2197         .write = cgroup_file_write,
2198         .release = cgroup_tasks_release,
2199 };
2200
2201 /*
2202  * Handle an open on 'tasks' file.  Prepare an array containing the
2203  * process id's of tasks currently attached to the cgroup being opened.
2204  */
2205
2206 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2207 {
2208         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2209         pid_t *pidarray;
2210         int npids;
2211         int retval;
2212
2213         /* Nothing to do for write-only files */
2214         if (!(file->f_mode & FMODE_READ))
2215                 return 0;
2216
2217         /*
2218          * If cgroup gets more users after we read count, we won't have
2219          * enough space - tough.  This race is indistinguishable to the
2220          * caller from the case that the additional cgroup users didn't
2221          * show up until sometime later on.
2222          */
2223         npids = cgroup_task_count(cgrp);
2224         pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
2225         if (!pidarray)
2226                 return -ENOMEM;
2227         npids = pid_array_load(pidarray, npids, cgrp);
2228         sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
2229
2230         /*
2231          * Store the array in the cgroup, freeing the old
2232          * array if necessary
2233          */
2234         down_write(&cgrp->pids_mutex);
2235         kfree(cgrp->tasks_pids);
2236         cgrp->tasks_pids = pidarray;
2237         cgrp->pids_length = npids;
2238         cgrp->pids_use_count++;
2239         up_write(&cgrp->pids_mutex);
2240
2241         file->f_op = &cgroup_tasks_operations;
2242
2243         retval = seq_open(file, &cgroup_tasks_seq_operations);
2244         if (retval) {
2245                 release_cgroup_pid_array(cgrp);
2246                 return retval;
2247         }
2248         ((struct seq_file *)file->private_data)->private = cgrp;
2249         return 0;
2250 }
2251
2252 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2253                                             struct cftype *cft)
2254 {
2255         return notify_on_release(cgrp);
2256 }
2257
2258 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2259                                           struct cftype *cft,
2260                                           u64 val)
2261 {
2262         clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2263         if (val)
2264                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2265         else
2266                 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2267         return 0;
2268 }
2269
2270 /*
2271  * for the common functions, 'private' gives the type of file
2272  */
2273 static struct cftype files[] = {
2274         {
2275                 .name = "tasks",
2276                 .open = cgroup_tasks_open,
2277                 .write_u64 = cgroup_tasks_write,
2278                 .release = cgroup_tasks_release,
2279                 .private = FILE_TASKLIST,
2280         },
2281
2282         {
2283                 .name = "notify_on_release",
2284                 .read_u64 = cgroup_read_notify_on_release,
2285                 .write_u64 = cgroup_write_notify_on_release,
2286                 .private = FILE_NOTIFY_ON_RELEASE,
2287         },
2288 };
2289
2290 static struct cftype cft_release_agent = {
2291         .name = "release_agent",
2292         .read_seq_string = cgroup_release_agent_show,
2293         .write_string = cgroup_release_agent_write,
2294         .max_write_len = PATH_MAX,
2295         .private = FILE_RELEASE_AGENT,
2296 };
2297
2298 static int cgroup_populate_dir(struct cgroup *cgrp)
2299 {
2300         int err;
2301         struct cgroup_subsys *ss;
2302
2303         /* First clear out any existing files */
2304         cgroup_clear_directory(cgrp->dentry);
2305
2306         err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2307         if (err < 0)
2308                 return err;
2309
2310         if (cgrp == cgrp->top_cgroup) {
2311                 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2312                         return err;
2313         }
2314
2315         for_each_subsys(cgrp->root, ss) {
2316                 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2317                         return err;
2318         }
2319
2320         return 0;
2321 }
2322
2323 static void init_cgroup_css(struct cgroup_subsys_state *css,
2324                                struct cgroup_subsys *ss,
2325                                struct cgroup *cgrp)
2326 {
2327         css->cgroup = cgrp;
2328         atomic_set(&css->refcnt, 0);
2329         css->flags = 0;
2330         if (cgrp == dummytop)
2331                 set_bit(CSS_ROOT, &css->flags);
2332         BUG_ON(cgrp->subsys[ss->subsys_id]);
2333         cgrp->subsys[ss->subsys_id] = css;
2334 }
2335
2336 /*
2337  * cgroup_create - create a cgroup
2338  * @parent: cgroup that will be parent of the new cgroup
2339  * @dentry: dentry of the new cgroup
2340  * @mode: mode to set on new inode
2341  *
2342  * Must be called with the mutex on the parent inode held
2343  */
2344 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
2345                              int mode)
2346 {
2347         struct cgroup *cgrp;
2348         struct cgroupfs_root *root = parent->root;
2349         int err = 0;
2350         struct cgroup_subsys *ss;
2351         struct super_block *sb = root->sb;
2352
2353         cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
2354         if (!cgrp)
2355                 return -ENOMEM;
2356
2357         /* Grab a reference on the superblock so the hierarchy doesn't
2358          * get deleted on unmount if there are child cgroups.  This
2359          * can be done outside cgroup_mutex, since the sb can't
2360          * disappear while someone has an open control file on the
2361          * fs */
2362         atomic_inc(&sb->s_active);
2363
2364         mutex_lock(&cgroup_mutex);
2365
2366         init_cgroup_housekeeping(cgrp);
2367
2368         cgrp->parent = parent;
2369         cgrp->root = parent->root;
2370         cgrp->top_cgroup = parent->top_cgroup;
2371
2372         if (notify_on_release(parent))
2373                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2374
2375         for_each_subsys(root, ss) {
2376                 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
2377                 if (IS_ERR(css)) {
2378                         err = PTR_ERR(css);
2379                         goto err_destroy;
2380                 }
2381                 init_cgroup_css(css, ss, cgrp);
2382         }
2383
2384         list_add(&cgrp->sibling, &cgrp->parent->children);
2385         root->number_of_cgroups++;
2386
2387         err = cgroup_create_dir(cgrp, dentry, mode);
2388         if (err < 0)
2389                 goto err_remove;
2390
2391         /* The cgroup directory was pre-locked for us */
2392         BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
2393
2394         err = cgroup_populate_dir(cgrp);
2395         /* If err < 0, we have a half-filled directory - oh well ;) */
2396
2397         mutex_unlock(&cgroup_mutex);
2398         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
2399
2400         return 0;
2401
2402  err_remove:
2403
2404         list_del(&cgrp->sibling);
2405         root->number_of_cgroups--;
2406
2407  err_destroy:
2408
2409         for_each_subsys(root, ss) {
2410                 if (cgrp->subsys[ss->subsys_id])
2411                         ss->destroy(ss, cgrp);
2412         }
2413
2414         mutex_unlock(&cgroup_mutex);
2415
2416         /* Release the reference count that we took on the superblock */
2417         deactivate_super(sb);
2418
2419         kfree(cgrp);
2420         return err;
2421 }
2422
2423 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2424 {
2425         struct cgroup *c_parent = dentry->d_parent->d_fsdata;
2426
2427         /* the vfs holds inode->i_mutex already */
2428         return cgroup_create(c_parent, dentry, mode | S_IFDIR);
2429 }
2430
2431 static int cgroup_has_css_refs(struct cgroup *cgrp)
2432 {
2433         /* Check the reference count on each subsystem. Since we
2434          * already established that there are no tasks in the
2435          * cgroup, if the css refcount is also 0, then there should
2436          * be no outstanding references, so the subsystem is safe to
2437          * destroy. We scan across all subsystems rather than using
2438          * the per-hierarchy linked list of mounted subsystems since
2439          * we can be called via check_for_release() with no
2440          * synchronization other than RCU, and the subsystem linked
2441          * list isn't RCU-safe */
2442         int i;
2443         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2444                 struct cgroup_subsys *ss = subsys[i];
2445                 struct cgroup_subsys_state *css;
2446                 /* Skip subsystems not in this hierarchy */
2447                 if (ss->root != cgrp->root)
2448                         continue;
2449                 css = cgrp->subsys[ss->subsys_id];
2450                 /* When called from check_for_release() it's possible
2451                  * that by this point the cgroup has been removed
2452                  * and the css deleted. But a false-positive doesn't
2453                  * matter, since it can only happen if the cgroup
2454                  * has been deleted and hence no longer needs the
2455                  * release agent to be called anyway. */
2456                 if (css && atomic_read(&css->refcnt))
2457                         return 1;
2458         }
2459         return 0;
2460 }
2461
2462 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
2463 {
2464         struct cgroup *cgrp = dentry->d_fsdata;
2465         struct dentry *d;
2466         struct cgroup *parent;
2467         struct super_block *sb;
2468         struct cgroupfs_root *root;
2469
2470         /* the vfs holds both inode->i_mutex already */
2471
2472         mutex_lock(&cgroup_mutex);
2473         if (atomic_read(&cgrp->count) != 0) {
2474                 mutex_unlock(&cgroup_mutex);
2475                 return -EBUSY;
2476         }
2477         if (!list_empty(&cgrp->children)) {
2478                 mutex_unlock(&cgroup_mutex);
2479                 return -EBUSY;
2480         }
2481         mutex_unlock(&cgroup_mutex);
2482
2483         /*
2484          * Call pre_destroy handlers of subsys. Notify subsystems
2485          * that rmdir() request comes.
2486          */
2487         cgroup_call_pre_destroy(cgrp);
2488
2489         mutex_lock(&cgroup_mutex);
2490         parent = cgrp->parent;
2491         root = cgrp->root;
2492         sb = root->sb;
2493
2494         if (atomic_read(&cgrp->count)
2495             || !list_empty(&cgrp->children)
2496             || cgroup_has_css_refs(cgrp)) {
2497                 mutex_unlock(&cgroup_mutex);
2498                 return -EBUSY;
2499         }
2500
2501         spin_lock(&release_list_lock);
2502         set_bit(CGRP_REMOVED, &cgrp->flags);
2503         if (!list_empty(&cgrp->release_list))
2504                 list_del(&cgrp->release_list);
2505         spin_unlock(&release_list_lock);
2506         /* delete my sibling from parent->children */
2507         list_del(&cgrp->sibling);
2508         spin_lock(&cgrp->dentry->d_lock);
2509         d = dget(cgrp->dentry);
2510         spin_unlock(&d->d_lock);
2511
2512         cgroup_d_remove_dir(d);
2513         dput(d);
2514
2515         set_bit(CGRP_RELEASABLE, &parent->flags);
2516         check_for_release(parent);
2517
2518         mutex_unlock(&cgroup_mutex);
2519         return 0;
2520 }
2521
2522 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
2523 {
2524         struct cgroup_subsys_state *css;
2525
2526         printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
2527
2528         /* Create the top cgroup state for this subsystem */
2529         ss->root = &rootnode;
2530         css = ss->create(ss, dummytop);
2531         /* We don't handle early failures gracefully */
2532         BUG_ON(IS_ERR(css));
2533         init_cgroup_css(css, ss, dummytop);
2534
2535         /* Update the init_css_set to contain a subsys
2536          * pointer to this state - since the subsystem is
2537          * newly registered, all tasks and hence the
2538          * init_css_set is in the subsystem's top cgroup. */
2539         init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
2540
2541         need_forkexit_callback |= ss->fork || ss->exit;
2542         need_mm_owner_callback |= !!ss->mm_owner_changed;
2543
2544         /* At system boot, before all subsystems have been
2545          * registered, no tasks have been forked, so we don't
2546          * need to invoke fork callbacks here. */
2547         BUG_ON(!list_empty(&init_task.tasks));
2548
2549         ss->active = 1;
2550 }
2551
2552 /**
2553  * cgroup_init_early - cgroup initialization at system boot
2554  *
2555  * Initialize cgroups at system boot, and initialize any
2556  * subsystems that request early init.
2557  */
2558 int __init cgroup_init_early(void)
2559 {
2560         int i;
2561         atomic_set(&init_css_set.refcount, 1);
2562         INIT_LIST_HEAD(&init_css_set.cg_links);
2563         INIT_LIST_HEAD(&init_css_set.tasks);
2564         INIT_HLIST_NODE(&init_css_set.hlist);
2565         css_set_count = 1;
2566         init_cgroup_root(&rootnode);
2567         list_add(&rootnode.root_list, &roots);
2568         root_count = 1;
2569         init_task.cgroups = &init_css_set;
2570
2571         init_css_set_link.cg = &init_css_set;
2572         list_add(&init_css_set_link.cgrp_link_list,
2573                  &rootnode.top_cgroup.css_sets);
2574         list_add(&init_css_set_link.cg_link_list,
2575                  &init_css_set.cg_links);
2576
2577         for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
2578                 INIT_HLIST_HEAD(&css_set_table[i]);
2579
2580         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2581                 struct cgroup_subsys *ss = subsys[i];
2582
2583                 BUG_ON(!ss->name);
2584                 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
2585                 BUG_ON(!ss->create);
2586                 BUG_ON(!ss->destroy);
2587                 if (ss->subsys_id != i) {
2588                         printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
2589                                ss->name, ss->subsys_id);
2590                         BUG();
2591                 }
2592
2593                 if (ss->early_init)
2594                         cgroup_init_subsys(ss);
2595         }
2596         return 0;
2597 }
2598
2599 /**
2600  * cgroup_init - cgroup initialization
2601  *
2602  * Register cgroup filesystem and /proc file, and initialize
2603  * any subsystems that didn't request early init.
2604  */
2605 int __init cgroup_init(void)
2606 {
2607         int err;
2608         int i;
2609         struct hlist_head *hhead;
2610
2611         err = bdi_init(&cgroup_backing_dev_info);
2612         if (err)
2613                 return err;
2614
2615         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2616                 struct cgroup_subsys *ss = subsys[i];
2617                 if (!ss->early_init)
2618                         cgroup_init_subsys(ss);
2619         }
2620
2621         /* Add init_css_set to the hash table */
2622         hhead = css_set_hash(init_css_set.subsys);
2623         hlist_add_head(&init_css_set.hlist, hhead);
2624
2625         err = register_filesystem(&cgroup_fs_type);
2626         if (err < 0)
2627                 goto out;
2628
2629         proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
2630
2631 out:
2632         if (err)
2633                 bdi_destroy(&cgroup_backing_dev_info);
2634
2635         return err;
2636 }
2637
2638 /*
2639  * proc_cgroup_show()
2640  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
2641  *  - Used for /proc/<pid>/cgroup.
2642  *  - No need to task_lock(tsk) on this tsk->cgroup reference, as it
2643  *    doesn't really matter if tsk->cgroup changes after we read it,
2644  *    and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
2645  *    anyway.  No need to check that tsk->cgroup != NULL, thanks to
2646  *    the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
2647  *    cgroup to top_cgroup.
2648  */
2649
2650 /* TODO: Use a proper seq_file iterator */
2651 static int proc_cgroup_show(struct seq_file *m, void *v)
2652 {
2653         struct pid *pid;
2654         struct task_struct *tsk;
2655         char *buf;
2656         int retval;
2657         struct cgroupfs_root *root;
2658
2659         retval = -ENOMEM;
2660         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
2661         if (!buf)
2662                 goto out;
2663
2664         retval = -ESRCH;
2665         pid = m->private;
2666         tsk = get_pid_task(pid, PIDTYPE_PID);
2667         if (!tsk)
2668                 goto out_free;
2669
2670         retval = 0;
2671
2672         mutex_lock(&cgroup_mutex);
2673
2674         for_each_root(root) {
2675                 struct cgroup_subsys *ss;
2676                 struct cgroup *cgrp;
2677                 int subsys_id;
2678                 int count = 0;
2679
2680                 /* Skip this hierarchy if it has no active subsystems */
2681                 if (!root->actual_subsys_bits)
2682                         continue;
2683                 seq_printf(m, "%lu:", root->subsys_bits);
2684                 for_each_subsys(root, ss)
2685                         seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
2686                 seq_putc(m, ':');
2687                 get_first_subsys(&root->top_cgroup, NULL, &subsys_id);
2688                 cgrp = task_cgroup(tsk, subsys_id);
2689                 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
2690                 if (retval < 0)
2691                         goto out_unlock;
2692                 seq_puts(m, buf);
2693                 seq_putc(m, '\n');
2694         }
2695
2696 out_unlock:
2697         mutex_unlock(&cgroup_mutex);
2698         put_task_struct(tsk);
2699 out_free:
2700         kfree(buf);
2701 out:
2702         return retval;
2703 }
2704
2705 static int cgroup_open(struct inode *inode, struct file *file)
2706 {
2707         struct pid *pid = PROC_I(inode)->pid;
2708         return single_open(file, proc_cgroup_show, pid);
2709 }
2710
2711 struct file_operations proc_cgroup_operations = {
2712         .open           = cgroup_open,
2713         .read           = seq_read,
2714         .llseek         = seq_lseek,
2715         .release        = single_release,
2716 };
2717
2718 /* Display information about each subsystem and each hierarchy */
2719 static int proc_cgroupstats_show(struct seq_file *m, void *v)
2720 {
2721         int i;
2722
2723         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
2724         mutex_lock(&cgroup_mutex);
2725         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2726                 struct cgroup_subsys *ss = subsys[i];
2727                 seq_printf(m, "%s\t%lu\t%d\t%d\n",
2728                            ss->name, ss->root->subsys_bits,
2729                            ss->root->number_of_cgroups, !ss->disabled);
2730         }
2731         mutex_unlock(&cgroup_mutex);
2732         return 0;
2733 }
2734
2735 static int cgroupstats_open(struct inode *inode, struct file *file)
2736 {
2737         return single_open(file, proc_cgroupstats_show, NULL);
2738 }
2739
2740 static struct file_operations proc_cgroupstats_operations = {
2741         .open = cgroupstats_open,
2742         .read = seq_read,
2743         .llseek = seq_lseek,
2744         .release = single_release,
2745 };
2746
2747 /**
2748  * cgroup_fork - attach newly forked task to its parents cgroup.
2749  * @child: pointer to task_struct of forking parent process.
2750  *
2751  * Description: A task inherits its parent's cgroup at fork().
2752  *
2753  * A pointer to the shared css_set was automatically copied in
2754  * fork.c by dup_task_struct().  However, we ignore that copy, since
2755  * it was not made under the protection of RCU or cgroup_mutex, so
2756  * might no longer be a valid cgroup pointer.  cgroup_attach_task() might
2757  * have already changed current->cgroups, allowing the previously
2758  * referenced cgroup group to be removed and freed.
2759  *
2760  * At the point that cgroup_fork() is called, 'current' is the parent
2761  * task, and the passed argument 'child' points to the child task.
2762  */
2763 void cgroup_fork(struct task_struct *child)
2764 {
2765         task_lock(current);
2766         child->cgroups = current->cgroups;
2767         get_css_set(child->cgroups);
2768         task_unlock(current);
2769         INIT_LIST_HEAD(&child->cg_list);
2770 }
2771
2772 /**
2773  * cgroup_fork_callbacks - run fork callbacks
2774  * @child: the new task
2775  *
2776  * Called on a new task very soon before adding it to the
2777  * tasklist. No need to take any locks since no-one can
2778  * be operating on this task.
2779  */
2780 void cgroup_fork_callbacks(struct task_struct *child)
2781 {
2782         if (need_forkexit_callback) {
2783                 int i;
2784                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2785                         struct cgroup_subsys *ss = subsys[i];
2786                         if (ss->fork)
2787                                 ss->fork(ss, child);
2788                 }
2789         }
2790 }
2791
2792 #ifdef CONFIG_MM_OWNER
2793 /**
2794  * cgroup_mm_owner_callbacks - run callbacks when the mm->owner changes
2795  * @p: the new owner
2796  *
2797  * Called on every change to mm->owner. mm_init_owner() does not
2798  * invoke this routine, since it assigns the mm->owner the first time
2799  * and does not change it.
2800  *
2801  * The callbacks are invoked with mmap_sem held in read mode.
2802  */
2803 void cgroup_mm_owner_callbacks(struct task_struct *old, struct task_struct *new)
2804 {
2805         struct cgroup *oldcgrp, *newcgrp = NULL;
2806
2807         if (need_mm_owner_callback) {
2808                 int i;
2809                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2810                         struct cgroup_subsys *ss = subsys[i];
2811                         oldcgrp = task_cgroup(old, ss->subsys_id);
2812                         if (new)
2813                                 newcgrp = task_cgroup(new, ss->subsys_id);
2814                         if (oldcgrp == newcgrp)
2815                                 continue;
2816                         if (ss->mm_owner_changed)
2817                                 ss->mm_owner_changed(ss, oldcgrp, newcgrp, new);
2818                 }
2819         }
2820 }
2821 #endif /* CONFIG_MM_OWNER */
2822
2823 /**
2824  * cgroup_post_fork - called on a new task after adding it to the task list
2825  * @child: the task in question
2826  *
2827  * Adds the task to the list running through its css_set if necessary.
2828  * Has to be after the task is visible on the task list in case we race
2829  * with the first call to cgroup_iter_start() - to guarantee that the
2830  * new task ends up on its list.
2831  */
2832 void cgroup_post_fork(struct task_struct *child)
2833 {
2834         if (use_task_css_set_links) {
2835                 write_lock(&css_set_lock);
2836                 if (list_empty(&child->cg_list))
2837                         list_add(&child->cg_list, &child->cgroups->tasks);
2838                 write_unlock(&css_set_lock);
2839         }
2840 }
2841 /**
2842  * cgroup_exit - detach cgroup from exiting task
2843  * @tsk: pointer to task_struct of exiting process
2844  * @run_callback: run exit callbacks?
2845  *
2846  * Description: Detach cgroup from @tsk and release it.
2847  *
2848  * Note that cgroups marked notify_on_release force every task in
2849  * them to take the global cgroup_mutex mutex when exiting.
2850  * This could impact scaling on very large systems.  Be reluctant to
2851  * use notify_on_release cgroups where very high task exit scaling
2852  * is required on large systems.
2853  *
2854  * the_top_cgroup_hack:
2855  *
2856  *    Set the exiting tasks cgroup to the root cgroup (top_cgroup).
2857  *
2858  *    We call cgroup_exit() while the task is still competent to
2859  *    handle notify_on_release(), then leave the task attached to the
2860  *    root cgroup in each hierarchy for the remainder of its exit.
2861  *
2862  *    To do this properly, we would increment the reference count on
2863  *    top_cgroup, and near the very end of the kernel/exit.c do_exit()
2864  *    code we would add a second cgroup function call, to drop that
2865  *    reference.  This would just create an unnecessary hot spot on
2866  *    the top_cgroup reference count, to no avail.
2867  *
2868  *    Normally, holding a reference to a cgroup without bumping its
2869  *    count is unsafe.   The cgroup could go away, or someone could
2870  *    attach us to a different cgroup, decrementing the count on
2871  *    the first cgroup that we never incremented.  But in this case,
2872  *    top_cgroup isn't going away, and either task has PF_EXITING set,
2873  *    which wards off any cgroup_attach_task() attempts, or task is a failed
2874  *    fork, never visible to cgroup_attach_task.
2875  */
2876 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
2877 {
2878         int i;
2879         struct css_set *cg;
2880
2881         if (run_callbacks && need_forkexit_callback) {
2882                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2883                         struct cgroup_subsys *ss = subsys[i];
2884                         if (ss->exit)
2885                                 ss->exit(ss, tsk);
2886                 }
2887         }
2888
2889         /*
2890          * Unlink from the css_set task list if necessary.
2891          * Optimistically check cg_list before taking
2892          * css_set_lock
2893          */
2894         if (!list_empty(&tsk->cg_list)) {
2895                 write_lock(&css_set_lock);
2896                 if (!list_empty(&tsk->cg_list))
2897                         list_del(&tsk->cg_list);
2898                 write_unlock(&css_set_lock);
2899         }
2900
2901         /* Reassign the task to the init_css_set. */
2902         task_lock(tsk);
2903         cg = tsk->cgroups;
2904         tsk->cgroups = &init_css_set;
2905         task_unlock(tsk);
2906         if (cg)
2907                 put_css_set_taskexit(cg);
2908 }
2909
2910 /**
2911  * cgroup_clone - clone the cgroup the given subsystem is attached to
2912  * @tsk: the task to be moved
2913  * @subsys: the given subsystem
2914  * @nodename: the name for the new cgroup
2915  *
2916  * Duplicate the current cgroup in the hierarchy that the given
2917  * subsystem is attached to, and move this task into the new
2918  * child.
2919  */
2920 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
2921                                                         char *nodename)
2922 {
2923         struct dentry *dentry;
2924         int ret = 0;
2925         struct cgroup *parent, *child;
2926         struct inode *inode;
2927         struct css_set *cg;
2928         struct cgroupfs_root *root;
2929         struct cgroup_subsys *ss;
2930
2931         /* We shouldn't be called by an unregistered subsystem */
2932         BUG_ON(!subsys->active);
2933
2934         /* First figure out what hierarchy and cgroup we're dealing
2935          * with, and pin them so we can drop cgroup_mutex */
2936         mutex_lock(&cgroup_mutex);
2937  again:
2938         root = subsys->root;
2939         if (root == &rootnode) {
2940                 mutex_unlock(&cgroup_mutex);
2941                 return 0;
2942         }
2943         cg = tsk->cgroups;
2944         parent = task_cgroup(tsk, subsys->subsys_id);
2945
2946         /* Pin the hierarchy */
2947         atomic_inc(&parent->root->sb->s_active);
2948
2949         /* Keep the cgroup alive */
2950         get_css_set(cg);
2951         mutex_unlock(&cgroup_mutex);
2952
2953         /* Now do the VFS work to create a cgroup */
2954         inode = parent->dentry->d_inode;
2955
2956         /* Hold the parent directory mutex across this operation to
2957          * stop anyone else deleting the new cgroup */
2958         mutex_lock(&inode->i_mutex);
2959         dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
2960         if (IS_ERR(dentry)) {
2961                 printk(KERN_INFO
2962                        "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
2963                        PTR_ERR(dentry));
2964                 ret = PTR_ERR(dentry);
2965                 goto out_release;
2966         }
2967
2968         /* Create the cgroup directory, which also creates the cgroup */
2969         ret = vfs_mkdir(inode, dentry, S_IFDIR | 0755);
2970         child = __d_cgrp(dentry);
2971         dput(dentry);
2972         if (ret) {
2973                 printk(KERN_INFO
2974                        "Failed to create cgroup %s: %d\n", nodename,
2975                        ret);
2976                 goto out_release;
2977         }
2978
2979         if (!child) {
2980                 printk(KERN_INFO
2981                        "Couldn't find new cgroup %s\n", nodename);
2982                 ret = -ENOMEM;
2983                 goto out_release;
2984         }
2985
2986         /* The cgroup now exists. Retake cgroup_mutex and check
2987          * that we're still in the same state that we thought we
2988          * were. */
2989         mutex_lock(&cgroup_mutex);
2990         if ((root != subsys->root) ||
2991             (parent != task_cgroup(tsk, subsys->subsys_id))) {
2992                 /* Aargh, we raced ... */
2993                 mutex_unlock(&inode->i_mutex);
2994                 put_css_set(cg);
2995
2996                 deactivate_super(parent->root->sb);
2997                 /* The cgroup is still accessible in the VFS, but
2998                  * we're not going to try to rmdir() it at this
2999                  * point. */
3000                 printk(KERN_INFO
3001                        "Race in cgroup_clone() - leaking cgroup %s\n",
3002                        nodename);
3003                 goto again;
3004         }
3005
3006         /* do any required auto-setup */
3007         for_each_subsys(root, ss) {
3008                 if (ss->post_clone)
3009                         ss->post_clone(ss, child);
3010         }
3011
3012         /* All seems fine. Finish by moving the task into the new cgroup */
3013         ret = cgroup_attach_task(child, tsk);
3014         mutex_unlock(&cgroup_mutex);
3015
3016  out_release:
3017         mutex_unlock(&inode->i_mutex);
3018
3019         mutex_lock(&cgroup_mutex);
3020         put_css_set(cg);
3021         mutex_unlock(&cgroup_mutex);
3022         deactivate_super(parent->root->sb);
3023         return ret;
3024 }
3025
3026 /**
3027  * cgroup_is_descendant - see if @cgrp is a descendant of current task's cgrp
3028  * @cgrp: the cgroup in question
3029  *
3030  * See if @cgrp is a descendant of the current task's cgroup in
3031  * the appropriate hierarchy.
3032  *
3033  * If we are sending in dummytop, then presumably we are creating
3034  * the top cgroup in the subsystem.
3035  *
3036  * Called only by the ns (nsproxy) cgroup.
3037  */
3038 int cgroup_is_descendant(const struct cgroup *cgrp)
3039 {
3040         int ret;
3041         struct cgroup *target;
3042         int subsys_id;
3043
3044         if (cgrp == dummytop)
3045                 return 1;
3046
3047         get_first_subsys(cgrp, NULL, &subsys_id);
3048         target = task_cgroup(current, subsys_id);
3049         while (cgrp != target && cgrp!= cgrp->top_cgroup)
3050                 cgrp = cgrp->parent;
3051         ret = (cgrp == target);
3052         return ret;
3053 }
3054
3055 static void check_for_release(struct cgroup *cgrp)
3056 {
3057         /* All of these checks rely on RCU to keep the cgroup
3058          * structure alive */
3059         if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
3060             && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
3061                 /* Control Group is currently removeable. If it's not
3062                  * already queued for a userspace notification, queue
3063                  * it now */
3064                 int need_schedule_work = 0;
3065                 spin_lock(&release_list_lock);
3066                 if (!cgroup_is_removed(cgrp) &&
3067                     list_empty(&cgrp->release_list)) {
3068                         list_add(&cgrp->release_list, &release_list);
3069                         need_schedule_work = 1;
3070                 }
3071                 spin_unlock(&release_list_lock);
3072                 if (need_schedule_work)
3073                         schedule_work(&release_agent_work);
3074         }
3075 }
3076
3077 void __css_put(struct cgroup_subsys_state *css)
3078 {
3079         struct cgroup *cgrp = css->cgroup;
3080         rcu_read_lock();
3081         if (atomic_dec_and_test(&css->refcnt) && notify_on_release(cgrp)) {
3082                 set_bit(CGRP_RELEASABLE, &cgrp->flags);
3083                 check_for_release(cgrp);
3084         }
3085         rcu_read_unlock();
3086 }
3087
3088 /*
3089  * Notify userspace when a cgroup is released, by running the
3090  * configured release agent with the name of the cgroup (path
3091  * relative to the root of cgroup file system) as the argument.
3092  *
3093  * Most likely, this user command will try to rmdir this cgroup.
3094  *
3095  * This races with the possibility that some other task will be
3096  * attached to this cgroup before it is removed, or that some other
3097  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
3098  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
3099  * unused, and this cgroup will be reprieved from its death sentence,
3100  * to continue to serve a useful existence.  Next time it's released,
3101  * we will get notified again, if it still has 'notify_on_release' set.
3102  *
3103  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
3104  * means only wait until the task is successfully execve()'d.  The
3105  * separate release agent task is forked by call_usermodehelper(),
3106  * then control in this thread returns here, without waiting for the
3107  * release agent task.  We don't bother to wait because the caller of
3108  * this routine has no use for the exit status of the release agent
3109  * task, so no sense holding our caller up for that.
3110  */
3111 static void cgroup_release_agent(struct work_struct *work)
3112 {
3113         BUG_ON(work != &release_agent_work);
3114         mutex_lock(&cgroup_mutex);
3115         spin_lock(&release_list_lock);
3116         while (!list_empty(&release_list)) {
3117                 char *argv[3], *envp[3];
3118                 int i;
3119                 char *pathbuf = NULL, *agentbuf = NULL;
3120                 struct cgroup *cgrp = list_entry(release_list.next,
3121                                                     struct cgroup,
3122                                                     release_list);
3123                 list_del_init(&cgrp->release_list);
3124                 spin_unlock(&release_list_lock);
3125                 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3126                 if (!pathbuf)
3127                         goto continue_free;
3128                 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
3129                         goto continue_free;
3130                 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
3131                 if (!agentbuf)
3132                         goto continue_free;
3133
3134                 i = 0;
3135                 argv[i++] = agentbuf;
3136                 argv[i++] = pathbuf;
3137                 argv[i] = NULL;
3138
3139                 i = 0;
3140                 /* minimal command environment */
3141                 envp[i++] = "HOME=/";
3142                 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3143                 envp[i] = NULL;
3144
3145                 /* Drop the lock while we invoke the usermode helper,
3146                  * since the exec could involve hitting disk and hence
3147                  * be a slow process */
3148                 mutex_unlock(&cgroup_mutex);
3149                 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3150                 mutex_lock(&cgroup_mutex);
3151  continue_free:
3152                 kfree(pathbuf);
3153                 kfree(agentbuf);
3154                 spin_lock(&release_list_lock);
3155         }
3156         spin_unlock(&release_list_lock);
3157         mutex_unlock(&cgroup_mutex);
3158 }
3159
3160 static int __init cgroup_disable(char *str)
3161 {
3162         int i;
3163         char *token;
3164
3165         while ((token = strsep(&str, ",")) != NULL) {
3166                 if (!*token)
3167                         continue;
3168
3169                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3170                         struct cgroup_subsys *ss = subsys[i];
3171
3172                         if (!strcmp(token, ss->name)) {
3173                                 ss->disabled = 1;
3174                                 printk(KERN_INFO "Disabling %s control group"
3175                                         " subsystem\n", ss->name);
3176                                 break;
3177                         }
3178                 }
3179         }
3180         return 1;
3181 }
3182 __setup("cgroup_disable=", cgroup_disable);