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