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