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