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