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