cgroups: revert "cgroups: fix pid namespace bug"
[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_rwsem(&cgrp->pids_mutex);
1125 }
1126
1127 static void init_cgroup_root(struct cgroupfs_root *root)
1128 {
1129         struct cgroup *cgrp = &root->top_cgroup;
1130         INIT_LIST_HEAD(&root->subsys_list);
1131         INIT_LIST_HEAD(&root->root_list);
1132         root->number_of_cgroups = 1;
1133         cgrp->root = root;
1134         cgrp->top_cgroup = cgrp;
1135         init_cgroup_housekeeping(cgrp);
1136 }
1137
1138 static bool init_root_id(struct cgroupfs_root *root)
1139 {
1140         int ret = 0;
1141
1142         do {
1143                 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1144                         return false;
1145                 spin_lock(&hierarchy_id_lock);
1146                 /* Try to allocate the next unused ID */
1147                 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1148                                         &root->hierarchy_id);
1149                 if (ret == -ENOSPC)
1150                         /* Try again starting from 0 */
1151                         ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1152                 if (!ret) {
1153                         next_hierarchy_id = root->hierarchy_id + 1;
1154                 } else if (ret != -EAGAIN) {
1155                         /* Can only get here if the 31-bit IDR is full ... */
1156                         BUG_ON(ret);
1157                 }
1158                 spin_unlock(&hierarchy_id_lock);
1159         } while (ret);
1160         return true;
1161 }
1162
1163 static int cgroup_test_super(struct super_block *sb, void *data)
1164 {
1165         struct cgroup_sb_opts *opts = data;
1166         struct cgroupfs_root *root = sb->s_fs_info;
1167
1168         /* If we asked for a name then it must match */
1169         if (opts->name && strcmp(opts->name, root->name))
1170                 return 0;
1171
1172         /*
1173          * If we asked for subsystems (or explicitly for no
1174          * subsystems) then they must match
1175          */
1176         if ((opts->subsys_bits || opts->none)
1177             && (opts->subsys_bits != root->subsys_bits))
1178                 return 0;
1179
1180         return 1;
1181 }
1182
1183 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1184 {
1185         struct cgroupfs_root *root;
1186
1187         if (!opts->subsys_bits && !opts->none)
1188                 return NULL;
1189
1190         root = kzalloc(sizeof(*root), GFP_KERNEL);
1191         if (!root)
1192                 return ERR_PTR(-ENOMEM);
1193
1194         if (!init_root_id(root)) {
1195                 kfree(root);
1196                 return ERR_PTR(-ENOMEM);
1197         }
1198         init_cgroup_root(root);
1199
1200         root->subsys_bits = opts->subsys_bits;
1201         root->flags = opts->flags;
1202         if (opts->release_agent)
1203                 strcpy(root->release_agent_path, opts->release_agent);
1204         if (opts->name)
1205                 strcpy(root->name, opts->name);
1206         return root;
1207 }
1208
1209 static void cgroup_drop_root(struct cgroupfs_root *root)
1210 {
1211         if (!root)
1212                 return;
1213
1214         BUG_ON(!root->hierarchy_id);
1215         spin_lock(&hierarchy_id_lock);
1216         ida_remove(&hierarchy_ida, root->hierarchy_id);
1217         spin_unlock(&hierarchy_id_lock);
1218         kfree(root);
1219 }
1220
1221 static int cgroup_set_super(struct super_block *sb, void *data)
1222 {
1223         int ret;
1224         struct cgroup_sb_opts *opts = data;
1225
1226         /* If we don't have a new root, we can't set up a new sb */
1227         if (!opts->new_root)
1228                 return -EINVAL;
1229
1230         BUG_ON(!opts->subsys_bits && !opts->none);
1231
1232         ret = set_anon_super(sb, NULL);
1233         if (ret)
1234                 return ret;
1235
1236         sb->s_fs_info = opts->new_root;
1237         opts->new_root->sb = sb;
1238
1239         sb->s_blocksize = PAGE_CACHE_SIZE;
1240         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1241         sb->s_magic = CGROUP_SUPER_MAGIC;
1242         sb->s_op = &cgroup_ops;
1243
1244         return 0;
1245 }
1246
1247 static int cgroup_get_rootdir(struct super_block *sb)
1248 {
1249         struct inode *inode =
1250                 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1251         struct dentry *dentry;
1252
1253         if (!inode)
1254                 return -ENOMEM;
1255
1256         inode->i_fop = &simple_dir_operations;
1257         inode->i_op = &cgroup_dir_inode_operations;
1258         /* directories start off with i_nlink == 2 (for "." entry) */
1259         inc_nlink(inode);
1260         dentry = d_alloc_root(inode);
1261         if (!dentry) {
1262                 iput(inode);
1263                 return -ENOMEM;
1264         }
1265         sb->s_root = dentry;
1266         return 0;
1267 }
1268
1269 static int cgroup_get_sb(struct file_system_type *fs_type,
1270                          int flags, const char *unused_dev_name,
1271                          void *data, struct vfsmount *mnt)
1272 {
1273         struct cgroup_sb_opts opts;
1274         struct cgroupfs_root *root;
1275         int ret = 0;
1276         struct super_block *sb;
1277         struct cgroupfs_root *new_root;
1278
1279         /* First find the desired set of subsystems */
1280         ret = parse_cgroupfs_options(data, &opts);
1281         if (ret)
1282                 goto out_err;
1283
1284         /*
1285          * Allocate a new cgroup root. We may not need it if we're
1286          * reusing an existing hierarchy.
1287          */
1288         new_root = cgroup_root_from_opts(&opts);
1289         if (IS_ERR(new_root)) {
1290                 ret = PTR_ERR(new_root);
1291                 goto out_err;
1292         }
1293         opts.new_root = new_root;
1294
1295         /* Locate an existing or new sb for this hierarchy */
1296         sb = sget(fs_type, cgroup_test_super, cgroup_set_super, &opts);
1297         if (IS_ERR(sb)) {
1298                 ret = PTR_ERR(sb);
1299                 cgroup_drop_root(opts.new_root);
1300                 goto out_err;
1301         }
1302
1303         root = sb->s_fs_info;
1304         BUG_ON(!root);
1305         if (root == opts.new_root) {
1306                 /* We used the new root structure, so this is a new hierarchy */
1307                 struct list_head tmp_cg_links;
1308                 struct cgroup *root_cgrp = &root->top_cgroup;
1309                 struct inode *inode;
1310                 struct cgroupfs_root *existing_root;
1311                 int i;
1312
1313                 BUG_ON(sb->s_root != NULL);
1314
1315                 ret = cgroup_get_rootdir(sb);
1316                 if (ret)
1317                         goto drop_new_super;
1318                 inode = sb->s_root->d_inode;
1319
1320                 mutex_lock(&inode->i_mutex);
1321                 mutex_lock(&cgroup_mutex);
1322
1323                 if (strlen(root->name)) {
1324                         /* Check for name clashes with existing mounts */
1325                         for_each_active_root(existing_root) {
1326                                 if (!strcmp(existing_root->name, root->name)) {
1327                                         ret = -EBUSY;
1328                                         mutex_unlock(&cgroup_mutex);
1329                                         mutex_unlock(&inode->i_mutex);
1330                                         goto drop_new_super;
1331                                 }
1332                         }
1333                 }
1334
1335                 /*
1336                  * We're accessing css_set_count without locking
1337                  * css_set_lock here, but that's OK - it can only be
1338                  * increased by someone holding cgroup_lock, and
1339                  * that's us. The worst that can happen is that we
1340                  * have some link structures left over
1341                  */
1342                 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1343                 if (ret) {
1344                         mutex_unlock(&cgroup_mutex);
1345                         mutex_unlock(&inode->i_mutex);
1346                         goto drop_new_super;
1347                 }
1348
1349                 ret = rebind_subsystems(root, root->subsys_bits);
1350                 if (ret == -EBUSY) {
1351                         mutex_unlock(&cgroup_mutex);
1352                         mutex_unlock(&inode->i_mutex);
1353                         free_cg_links(&tmp_cg_links);
1354                         goto drop_new_super;
1355                 }
1356
1357                 /* EBUSY should be the only error here */
1358                 BUG_ON(ret);
1359
1360                 list_add(&root->root_list, &roots);
1361                 root_count++;
1362
1363                 sb->s_root->d_fsdata = root_cgrp;
1364                 root->top_cgroup.dentry = sb->s_root;
1365
1366                 /* Link the top cgroup in this hierarchy into all
1367                  * the css_set objects */
1368                 write_lock(&css_set_lock);
1369                 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1370                         struct hlist_head *hhead = &css_set_table[i];
1371                         struct hlist_node *node;
1372                         struct css_set *cg;
1373
1374                         hlist_for_each_entry(cg, node, hhead, hlist)
1375                                 link_css_set(&tmp_cg_links, cg, root_cgrp);
1376                 }
1377                 write_unlock(&css_set_lock);
1378
1379                 free_cg_links(&tmp_cg_links);
1380
1381                 BUG_ON(!list_empty(&root_cgrp->sibling));
1382                 BUG_ON(!list_empty(&root_cgrp->children));
1383                 BUG_ON(root->number_of_cgroups != 1);
1384
1385                 cgroup_populate_dir(root_cgrp);
1386                 mutex_unlock(&cgroup_mutex);
1387                 mutex_unlock(&inode->i_mutex);
1388         } else {
1389                 /*
1390                  * We re-used an existing hierarchy - the new root (if
1391                  * any) is not needed
1392                  */
1393                 cgroup_drop_root(opts.new_root);
1394         }
1395
1396         simple_set_mnt(mnt, sb);
1397         kfree(opts.release_agent);
1398         kfree(opts.name);
1399         return 0;
1400
1401  drop_new_super:
1402         deactivate_locked_super(sb);
1403  out_err:
1404         kfree(opts.release_agent);
1405         kfree(opts.name);
1406
1407         return ret;
1408 }
1409
1410 static void cgroup_kill_sb(struct super_block *sb) {
1411         struct cgroupfs_root *root = sb->s_fs_info;
1412         struct cgroup *cgrp = &root->top_cgroup;
1413         int ret;
1414         struct cg_cgroup_link *link;
1415         struct cg_cgroup_link *saved_link;
1416
1417         BUG_ON(!root);
1418
1419         BUG_ON(root->number_of_cgroups != 1);
1420         BUG_ON(!list_empty(&cgrp->children));
1421         BUG_ON(!list_empty(&cgrp->sibling));
1422
1423         mutex_lock(&cgroup_mutex);
1424
1425         /* Rebind all subsystems back to the default hierarchy */
1426         ret = rebind_subsystems(root, 0);
1427         /* Shouldn't be able to fail ... */
1428         BUG_ON(ret);
1429
1430         /*
1431          * Release all the links from css_sets to this hierarchy's
1432          * root cgroup
1433          */
1434         write_lock(&css_set_lock);
1435
1436         list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1437                                  cgrp_link_list) {
1438                 list_del(&link->cg_link_list);
1439                 list_del(&link->cgrp_link_list);
1440                 kfree(link);
1441         }
1442         write_unlock(&css_set_lock);
1443
1444         if (!list_empty(&root->root_list)) {
1445                 list_del(&root->root_list);
1446                 root_count--;
1447         }
1448
1449         mutex_unlock(&cgroup_mutex);
1450
1451         kill_litter_super(sb);
1452         cgroup_drop_root(root);
1453 }
1454
1455 static struct file_system_type cgroup_fs_type = {
1456         .name = "cgroup",
1457         .get_sb = cgroup_get_sb,
1458         .kill_sb = cgroup_kill_sb,
1459 };
1460
1461 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1462 {
1463         return dentry->d_fsdata;
1464 }
1465
1466 static inline struct cftype *__d_cft(struct dentry *dentry)
1467 {
1468         return dentry->d_fsdata;
1469 }
1470
1471 /**
1472  * cgroup_path - generate the path of a cgroup
1473  * @cgrp: the cgroup in question
1474  * @buf: the buffer to write the path into
1475  * @buflen: the length of the buffer
1476  *
1477  * Called with cgroup_mutex held or else with an RCU-protected cgroup
1478  * reference.  Writes path of cgroup into buf.  Returns 0 on success,
1479  * -errno on error.
1480  */
1481 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1482 {
1483         char *start;
1484         struct dentry *dentry = rcu_dereference(cgrp->dentry);
1485
1486         if (!dentry || cgrp == dummytop) {
1487                 /*
1488                  * Inactive subsystems have no dentry for their root
1489                  * cgroup
1490                  */
1491                 strcpy(buf, "/");
1492                 return 0;
1493         }
1494
1495         start = buf + buflen;
1496
1497         *--start = '\0';
1498         for (;;) {
1499                 int len = dentry->d_name.len;
1500                 if ((start -= len) < buf)
1501                         return -ENAMETOOLONG;
1502                 memcpy(start, cgrp->dentry->d_name.name, len);
1503                 cgrp = cgrp->parent;
1504                 if (!cgrp)
1505                         break;
1506                 dentry = rcu_dereference(cgrp->dentry);
1507                 if (!cgrp->parent)
1508                         continue;
1509                 if (--start < buf)
1510                         return -ENAMETOOLONG;
1511                 *start = '/';
1512         }
1513         memmove(buf, start, buf + buflen - start);
1514         return 0;
1515 }
1516
1517 /**
1518  * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1519  * @cgrp: the cgroup the task is attaching to
1520  * @tsk: the task to be attached
1521  *
1522  * Call holding cgroup_mutex. May take task_lock of
1523  * the task 'tsk' during call.
1524  */
1525 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1526 {
1527         int retval = 0;
1528         struct cgroup_subsys *ss;
1529         struct cgroup *oldcgrp;
1530         struct css_set *cg;
1531         struct css_set *newcg;
1532         struct cgroupfs_root *root = cgrp->root;
1533
1534         /* Nothing to do if the task is already in that cgroup */
1535         oldcgrp = task_cgroup_from_root(tsk, root);
1536         if (cgrp == oldcgrp)
1537                 return 0;
1538
1539         for_each_subsys(root, ss) {
1540                 if (ss->can_attach) {
1541                         retval = ss->can_attach(ss, cgrp, tsk);
1542                         if (retval)
1543                                 return retval;
1544                 }
1545         }
1546
1547         task_lock(tsk);
1548         cg = tsk->cgroups;
1549         get_css_set(cg);
1550         task_unlock(tsk);
1551         /*
1552          * Locate or allocate a new css_set for this task,
1553          * based on its final set of cgroups
1554          */
1555         newcg = find_css_set(cg, cgrp);
1556         put_css_set(cg);
1557         if (!newcg)
1558                 return -ENOMEM;
1559
1560         task_lock(tsk);
1561         if (tsk->flags & PF_EXITING) {
1562                 task_unlock(tsk);
1563                 put_css_set(newcg);
1564                 return -ESRCH;
1565         }
1566         rcu_assign_pointer(tsk->cgroups, newcg);
1567         task_unlock(tsk);
1568
1569         /* Update the css_set linked lists if we're using them */
1570         write_lock(&css_set_lock);
1571         if (!list_empty(&tsk->cg_list)) {
1572                 list_del(&tsk->cg_list);
1573                 list_add(&tsk->cg_list, &newcg->tasks);
1574         }
1575         write_unlock(&css_set_lock);
1576
1577         for_each_subsys(root, ss) {
1578                 if (ss->attach)
1579                         ss->attach(ss, cgrp, oldcgrp, tsk);
1580         }
1581         set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1582         synchronize_rcu();
1583         put_css_set(cg);
1584
1585         /*
1586          * wake up rmdir() waiter. the rmdir should fail since the cgroup
1587          * is no longer empty.
1588          */
1589         cgroup_wakeup_rmdir_waiter(cgrp);
1590         return 0;
1591 }
1592
1593 /*
1594  * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
1595  * held. May take task_lock of task
1596  */
1597 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
1598 {
1599         struct task_struct *tsk;
1600         const struct cred *cred = current_cred(), *tcred;
1601         int ret;
1602
1603         if (pid) {
1604                 rcu_read_lock();
1605                 tsk = find_task_by_vpid(pid);
1606                 if (!tsk || tsk->flags & PF_EXITING) {
1607                         rcu_read_unlock();
1608                         return -ESRCH;
1609                 }
1610
1611                 tcred = __task_cred(tsk);
1612                 if (cred->euid &&
1613                     cred->euid != tcred->uid &&
1614                     cred->euid != tcred->suid) {
1615                         rcu_read_unlock();
1616                         return -EACCES;
1617                 }
1618                 get_task_struct(tsk);
1619                 rcu_read_unlock();
1620         } else {
1621                 tsk = current;
1622                 get_task_struct(tsk);
1623         }
1624
1625         ret = cgroup_attach_task(cgrp, tsk);
1626         put_task_struct(tsk);
1627         return ret;
1628 }
1629
1630 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
1631 {
1632         int ret;
1633         if (!cgroup_lock_live_group(cgrp))
1634                 return -ENODEV;
1635         ret = attach_task_by_pid(cgrp, pid);
1636         cgroup_unlock();
1637         return ret;
1638 }
1639
1640 /* The various types of files and directories in a cgroup file system */
1641 enum cgroup_filetype {
1642         FILE_ROOT,
1643         FILE_DIR,
1644         FILE_TASKLIST,
1645         FILE_NOTIFY_ON_RELEASE,
1646         FILE_RELEASE_AGENT,
1647 };
1648
1649 /**
1650  * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1651  * @cgrp: the cgroup to be checked for liveness
1652  *
1653  * On success, returns true; the lock should be later released with
1654  * cgroup_unlock(). On failure returns false with no lock held.
1655  */
1656 bool cgroup_lock_live_group(struct cgroup *cgrp)
1657 {
1658         mutex_lock(&cgroup_mutex);
1659         if (cgroup_is_removed(cgrp)) {
1660                 mutex_unlock(&cgroup_mutex);
1661                 return false;
1662         }
1663         return true;
1664 }
1665
1666 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1667                                       const char *buffer)
1668 {
1669         BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1670         if (!cgroup_lock_live_group(cgrp))
1671                 return -ENODEV;
1672         strcpy(cgrp->root->release_agent_path, buffer);
1673         cgroup_unlock();
1674         return 0;
1675 }
1676
1677 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1678                                      struct seq_file *seq)
1679 {
1680         if (!cgroup_lock_live_group(cgrp))
1681                 return -ENODEV;
1682         seq_puts(seq, cgrp->root->release_agent_path);
1683         seq_putc(seq, '\n');
1684         cgroup_unlock();
1685         return 0;
1686 }
1687
1688 /* A buffer size big enough for numbers or short strings */
1689 #define CGROUP_LOCAL_BUFFER_SIZE 64
1690
1691 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1692                                 struct file *file,
1693                                 const char __user *userbuf,
1694                                 size_t nbytes, loff_t *unused_ppos)
1695 {
1696         char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1697         int retval = 0;
1698         char *end;
1699
1700         if (!nbytes)
1701                 return -EINVAL;
1702         if (nbytes >= sizeof(buffer))
1703                 return -E2BIG;
1704         if (copy_from_user(buffer, userbuf, nbytes))
1705                 return -EFAULT;
1706
1707         buffer[nbytes] = 0;     /* nul-terminate */
1708         strstrip(buffer);
1709         if (cft->write_u64) {
1710                 u64 val = simple_strtoull(buffer, &end, 0);
1711                 if (*end)
1712                         return -EINVAL;
1713                 retval = cft->write_u64(cgrp, cft, val);
1714         } else {
1715                 s64 val = simple_strtoll(buffer, &end, 0);
1716                 if (*end)
1717                         return -EINVAL;
1718                 retval = cft->write_s64(cgrp, cft, val);
1719         }
1720         if (!retval)
1721                 retval = nbytes;
1722         return retval;
1723 }
1724
1725 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1726                                    struct file *file,
1727                                    const char __user *userbuf,
1728                                    size_t nbytes, loff_t *unused_ppos)
1729 {
1730         char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1731         int retval = 0;
1732         size_t max_bytes = cft->max_write_len;
1733         char *buffer = local_buffer;
1734
1735         if (!max_bytes)
1736                 max_bytes = sizeof(local_buffer) - 1;
1737         if (nbytes >= max_bytes)
1738                 return -E2BIG;
1739         /* Allocate a dynamic buffer if we need one */
1740         if (nbytes >= sizeof(local_buffer)) {
1741                 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1742                 if (buffer == NULL)
1743                         return -ENOMEM;
1744         }
1745         if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
1746                 retval = -EFAULT;
1747                 goto out;
1748         }
1749
1750         buffer[nbytes] = 0;     /* nul-terminate */
1751         strstrip(buffer);
1752         retval = cft->write_string(cgrp, cft, buffer);
1753         if (!retval)
1754                 retval = nbytes;
1755 out:
1756         if (buffer != local_buffer)
1757                 kfree(buffer);
1758         return retval;
1759 }
1760
1761 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1762                                                 size_t nbytes, loff_t *ppos)
1763 {
1764         struct cftype *cft = __d_cft(file->f_dentry);
1765         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1766
1767         if (cgroup_is_removed(cgrp))
1768                 return -ENODEV;
1769         if (cft->write)
1770                 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1771         if (cft->write_u64 || cft->write_s64)
1772                 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1773         if (cft->write_string)
1774                 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1775         if (cft->trigger) {
1776                 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1777                 return ret ? ret : nbytes;
1778         }
1779         return -EINVAL;
1780 }
1781
1782 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1783                                struct file *file,
1784                                char __user *buf, size_t nbytes,
1785                                loff_t *ppos)
1786 {
1787         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1788         u64 val = cft->read_u64(cgrp, cft);
1789         int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1790
1791         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1792 }
1793
1794 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1795                                struct file *file,
1796                                char __user *buf, size_t nbytes,
1797                                loff_t *ppos)
1798 {
1799         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1800         s64 val = cft->read_s64(cgrp, cft);
1801         int len = sprintf(tmp, "%lld\n", (long long) val);
1802
1803         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1804 }
1805
1806 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1807                                    size_t nbytes, loff_t *ppos)
1808 {
1809         struct cftype *cft = __d_cft(file->f_dentry);
1810         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1811
1812         if (cgroup_is_removed(cgrp))
1813                 return -ENODEV;
1814
1815         if (cft->read)
1816                 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1817         if (cft->read_u64)
1818                 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1819         if (cft->read_s64)
1820                 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1821         return -EINVAL;
1822 }
1823
1824 /*
1825  * seqfile ops/methods for returning structured data. Currently just
1826  * supports string->u64 maps, but can be extended in future.
1827  */
1828
1829 struct cgroup_seqfile_state {
1830         struct cftype *cft;
1831         struct cgroup *cgroup;
1832 };
1833
1834 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1835 {
1836         struct seq_file *sf = cb->state;
1837         return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1838 }
1839
1840 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1841 {
1842         struct cgroup_seqfile_state *state = m->private;
1843         struct cftype *cft = state->cft;
1844         if (cft->read_map) {
1845                 struct cgroup_map_cb cb = {
1846                         .fill = cgroup_map_add,
1847                         .state = m,
1848                 };
1849                 return cft->read_map(state->cgroup, cft, &cb);
1850         }
1851         return cft->read_seq_string(state->cgroup, cft, m);
1852 }
1853
1854 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
1855 {
1856         struct seq_file *seq = file->private_data;
1857         kfree(seq->private);
1858         return single_release(inode, file);
1859 }
1860
1861 static struct file_operations cgroup_seqfile_operations = {
1862         .read = seq_read,
1863         .write = cgroup_file_write,
1864         .llseek = seq_lseek,
1865         .release = cgroup_seqfile_release,
1866 };
1867
1868 static int cgroup_file_open(struct inode *inode, struct file *file)
1869 {
1870         int err;
1871         struct cftype *cft;
1872
1873         err = generic_file_open(inode, file);
1874         if (err)
1875                 return err;
1876         cft = __d_cft(file->f_dentry);
1877
1878         if (cft->read_map || cft->read_seq_string) {
1879                 struct cgroup_seqfile_state *state =
1880                         kzalloc(sizeof(*state), GFP_USER);
1881                 if (!state)
1882                         return -ENOMEM;
1883                 state->cft = cft;
1884                 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
1885                 file->f_op = &cgroup_seqfile_operations;
1886                 err = single_open(file, cgroup_seqfile_show, state);
1887                 if (err < 0)
1888                         kfree(state);
1889         } else if (cft->open)
1890                 err = cft->open(inode, file);
1891         else
1892                 err = 0;
1893
1894         return err;
1895 }
1896
1897 static int cgroup_file_release(struct inode *inode, struct file *file)
1898 {
1899         struct cftype *cft = __d_cft(file->f_dentry);
1900         if (cft->release)
1901                 return cft->release(inode, file);
1902         return 0;
1903 }
1904
1905 /*
1906  * cgroup_rename - Only allow simple rename of directories in place.
1907  */
1908 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
1909                             struct inode *new_dir, struct dentry *new_dentry)
1910 {
1911         if (!S_ISDIR(old_dentry->d_inode->i_mode))
1912                 return -ENOTDIR;
1913         if (new_dentry->d_inode)
1914                 return -EEXIST;
1915         if (old_dir != new_dir)
1916                 return -EIO;
1917         return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1918 }
1919
1920 static struct file_operations cgroup_file_operations = {
1921         .read = cgroup_file_read,
1922         .write = cgroup_file_write,
1923         .llseek = generic_file_llseek,
1924         .open = cgroup_file_open,
1925         .release = cgroup_file_release,
1926 };
1927
1928 static const struct inode_operations cgroup_dir_inode_operations = {
1929         .lookup = simple_lookup,
1930         .mkdir = cgroup_mkdir,
1931         .rmdir = cgroup_rmdir,
1932         .rename = cgroup_rename,
1933 };
1934
1935 static int cgroup_create_file(struct dentry *dentry, mode_t mode,
1936                                 struct super_block *sb)
1937 {
1938         static const struct dentry_operations cgroup_dops = {
1939                 .d_iput = cgroup_diput,
1940         };
1941
1942         struct inode *inode;
1943
1944         if (!dentry)
1945                 return -ENOENT;
1946         if (dentry->d_inode)
1947                 return -EEXIST;
1948
1949         inode = cgroup_new_inode(mode, sb);
1950         if (!inode)
1951                 return -ENOMEM;
1952
1953         if (S_ISDIR(mode)) {
1954                 inode->i_op = &cgroup_dir_inode_operations;
1955                 inode->i_fop = &simple_dir_operations;
1956
1957                 /* start off with i_nlink == 2 (for "." entry) */
1958                 inc_nlink(inode);
1959
1960                 /* start with the directory inode held, so that we can
1961                  * populate it without racing with another mkdir */
1962                 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
1963         } else if (S_ISREG(mode)) {
1964                 inode->i_size = 0;
1965                 inode->i_fop = &cgroup_file_operations;
1966         }
1967         dentry->d_op = &cgroup_dops;
1968         d_instantiate(dentry, inode);
1969         dget(dentry);   /* Extra count - pin the dentry in core */
1970         return 0;
1971 }
1972
1973 /*
1974  * cgroup_create_dir - create a directory for an object.
1975  * @cgrp: the cgroup we create the directory for. It must have a valid
1976  *        ->parent field. And we are going to fill its ->dentry field.
1977  * @dentry: dentry of the new cgroup
1978  * @mode: mode to set on new directory.
1979  */
1980 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
1981                                 mode_t mode)
1982 {
1983         struct dentry *parent;
1984         int error = 0;
1985
1986         parent = cgrp->parent->dentry;
1987         error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
1988         if (!error) {
1989                 dentry->d_fsdata = cgrp;
1990                 inc_nlink(parent->d_inode);
1991                 rcu_assign_pointer(cgrp->dentry, dentry);
1992                 dget(dentry);
1993         }
1994         dput(dentry);
1995
1996         return error;
1997 }
1998
1999 /**
2000  * cgroup_file_mode - deduce file mode of a control file
2001  * @cft: the control file in question
2002  *
2003  * returns cft->mode if ->mode is not 0
2004  * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2005  * returns S_IRUGO if it has only a read handler
2006  * returns S_IWUSR if it has only a write hander
2007  */
2008 static mode_t cgroup_file_mode(const struct cftype *cft)
2009 {
2010         mode_t mode = 0;
2011
2012         if (cft->mode)
2013                 return cft->mode;
2014
2015         if (cft->read || cft->read_u64 || cft->read_s64 ||
2016             cft->read_map || cft->read_seq_string)
2017                 mode |= S_IRUGO;
2018
2019         if (cft->write || cft->write_u64 || cft->write_s64 ||
2020             cft->write_string || cft->trigger)
2021                 mode |= S_IWUSR;
2022
2023         return mode;
2024 }
2025
2026 int cgroup_add_file(struct cgroup *cgrp,
2027                        struct cgroup_subsys *subsys,
2028                        const struct cftype *cft)
2029 {
2030         struct dentry *dir = cgrp->dentry;
2031         struct dentry *dentry;
2032         int error;
2033         mode_t mode;
2034
2035         char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2036         if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2037                 strcpy(name, subsys->name);
2038                 strcat(name, ".");
2039         }
2040         strcat(name, cft->name);
2041         BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2042         dentry = lookup_one_len(name, dir, strlen(name));
2043         if (!IS_ERR(dentry)) {
2044                 mode = cgroup_file_mode(cft);
2045                 error = cgroup_create_file(dentry, mode | S_IFREG,
2046                                                 cgrp->root->sb);
2047                 if (!error)
2048                         dentry->d_fsdata = (void *)cft;
2049                 dput(dentry);
2050         } else
2051                 error = PTR_ERR(dentry);
2052         return error;
2053 }
2054
2055 int cgroup_add_files(struct cgroup *cgrp,
2056                         struct cgroup_subsys *subsys,
2057                         const struct cftype cft[],
2058                         int count)
2059 {
2060         int i, err;
2061         for (i = 0; i < count; i++) {
2062                 err = cgroup_add_file(cgrp, subsys, &cft[i]);
2063                 if (err)
2064                         return err;
2065         }
2066         return 0;
2067 }
2068
2069 /**
2070  * cgroup_task_count - count the number of tasks in a cgroup.
2071  * @cgrp: the cgroup in question
2072  *
2073  * Return the number of tasks in the cgroup.
2074  */
2075 int cgroup_task_count(const struct cgroup *cgrp)
2076 {
2077         int count = 0;
2078         struct cg_cgroup_link *link;
2079
2080         read_lock(&css_set_lock);
2081         list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2082                 count += atomic_read(&link->cg->refcount);
2083         }
2084         read_unlock(&css_set_lock);
2085         return count;
2086 }
2087
2088 /*
2089  * Advance a list_head iterator.  The iterator should be positioned at
2090  * the start of a css_set
2091  */
2092 static void cgroup_advance_iter(struct cgroup *cgrp,
2093                                 struct cgroup_iter *it)
2094 {
2095         struct list_head *l = it->cg_link;
2096         struct cg_cgroup_link *link;
2097         struct css_set *cg;
2098
2099         /* Advance to the next non-empty css_set */
2100         do {
2101                 l = l->next;
2102                 if (l == &cgrp->css_sets) {
2103                         it->cg_link = NULL;
2104                         return;
2105                 }
2106                 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2107                 cg = link->cg;
2108         } while (list_empty(&cg->tasks));
2109         it->cg_link = l;
2110         it->task = cg->tasks.next;
2111 }
2112
2113 /*
2114  * To reduce the fork() overhead for systems that are not actually
2115  * using their cgroups capability, we don't maintain the lists running
2116  * through each css_set to its tasks until we see the list actually
2117  * used - in other words after the first call to cgroup_iter_start().
2118  *
2119  * The tasklist_lock is not held here, as do_each_thread() and
2120  * while_each_thread() are protected by RCU.
2121  */
2122 static void cgroup_enable_task_cg_lists(void)
2123 {
2124         struct task_struct *p, *g;
2125         write_lock(&css_set_lock);
2126         use_task_css_set_links = 1;
2127         do_each_thread(g, p) {
2128                 task_lock(p);
2129                 /*
2130                  * We should check if the process is exiting, otherwise
2131                  * it will race with cgroup_exit() in that the list
2132                  * entry won't be deleted though the process has exited.
2133                  */
2134                 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2135                         list_add(&p->cg_list, &p->cgroups->tasks);
2136                 task_unlock(p);
2137         } while_each_thread(g, p);
2138         write_unlock(&css_set_lock);
2139 }
2140
2141 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
2142 {
2143         /*
2144          * The first time anyone tries to iterate across a cgroup,
2145          * we need to enable the list linking each css_set to its
2146          * tasks, and fix up all existing tasks.
2147          */
2148         if (!use_task_css_set_links)
2149                 cgroup_enable_task_cg_lists();
2150
2151         read_lock(&css_set_lock);
2152         it->cg_link = &cgrp->css_sets;
2153         cgroup_advance_iter(cgrp, it);
2154 }
2155
2156 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
2157                                         struct cgroup_iter *it)
2158 {
2159         struct task_struct *res;
2160         struct list_head *l = it->task;
2161         struct cg_cgroup_link *link;
2162
2163         /* If the iterator cg is NULL, we have no tasks */
2164         if (!it->cg_link)
2165                 return NULL;
2166         res = list_entry(l, struct task_struct, cg_list);
2167         /* Advance iterator to find next entry */
2168         l = l->next;
2169         link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
2170         if (l == &link->cg->tasks) {
2171                 /* We reached the end of this task list - move on to
2172                  * the next cg_cgroup_link */
2173                 cgroup_advance_iter(cgrp, it);
2174         } else {
2175                 it->task = l;
2176         }
2177         return res;
2178 }
2179
2180 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
2181 {
2182         read_unlock(&css_set_lock);
2183 }
2184
2185 static inline int started_after_time(struct task_struct *t1,
2186                                      struct timespec *time,
2187                                      struct task_struct *t2)
2188 {
2189         int start_diff = timespec_compare(&t1->start_time, time);
2190         if (start_diff > 0) {
2191                 return 1;
2192         } else if (start_diff < 0) {
2193                 return 0;
2194         } else {
2195                 /*
2196                  * Arbitrarily, if two processes started at the same
2197                  * time, we'll say that the lower pointer value
2198                  * started first. Note that t2 may have exited by now
2199                  * so this may not be a valid pointer any longer, but
2200                  * that's fine - it still serves to distinguish
2201                  * between two tasks started (effectively) simultaneously.
2202                  */
2203                 return t1 > t2;
2204         }
2205 }
2206
2207 /*
2208  * This function is a callback from heap_insert() and is used to order
2209  * the heap.
2210  * In this case we order the heap in descending task start time.
2211  */
2212 static inline int started_after(void *p1, void *p2)
2213 {
2214         struct task_struct *t1 = p1;
2215         struct task_struct *t2 = p2;
2216         return started_after_time(t1, &t2->start_time, t2);
2217 }
2218
2219 /**
2220  * cgroup_scan_tasks - iterate though all the tasks in a cgroup
2221  * @scan: struct cgroup_scanner containing arguments for the scan
2222  *
2223  * Arguments include pointers to callback functions test_task() and
2224  * process_task().
2225  * Iterate through all the tasks in a cgroup, calling test_task() for each,
2226  * and if it returns true, call process_task() for it also.
2227  * The test_task pointer may be NULL, meaning always true (select all tasks).
2228  * Effectively duplicates cgroup_iter_{start,next,end}()
2229  * but does not lock css_set_lock for the call to process_task().
2230  * The struct cgroup_scanner may be embedded in any structure of the caller's
2231  * creation.
2232  * It is guaranteed that process_task() will act on every task that
2233  * is a member of the cgroup for the duration of this call. This
2234  * function may or may not call process_task() for tasks that exit
2235  * or move to a different cgroup during the call, or are forked or
2236  * move into the cgroup during the call.
2237  *
2238  * Note that test_task() may be called with locks held, and may in some
2239  * situations be called multiple times for the same task, so it should
2240  * be cheap.
2241  * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
2242  * pre-allocated and will be used for heap operations (and its "gt" member will
2243  * be overwritten), else a temporary heap will be used (allocation of which
2244  * may cause this function to fail).
2245  */
2246 int cgroup_scan_tasks(struct cgroup_scanner *scan)
2247 {
2248         int retval, i;
2249         struct cgroup_iter it;
2250         struct task_struct *p, *dropped;
2251         /* Never dereference latest_task, since it's not refcounted */
2252         struct task_struct *latest_task = NULL;
2253         struct ptr_heap tmp_heap;
2254         struct ptr_heap *heap;
2255         struct timespec latest_time = { 0, 0 };
2256
2257         if (scan->heap) {
2258                 /* The caller supplied our heap and pre-allocated its memory */
2259                 heap = scan->heap;
2260                 heap->gt = &started_after;
2261         } else {
2262                 /* We need to allocate our own heap memory */
2263                 heap = &tmp_heap;
2264                 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2265                 if (retval)
2266                         /* cannot allocate the heap */
2267                         return retval;
2268         }
2269
2270  again:
2271         /*
2272          * Scan tasks in the cgroup, using the scanner's "test_task" callback
2273          * to determine which are of interest, and using the scanner's
2274          * "process_task" callback to process any of them that need an update.
2275          * Since we don't want to hold any locks during the task updates,
2276          * gather tasks to be processed in a heap structure.
2277          * The heap is sorted by descending task start time.
2278          * If the statically-sized heap fills up, we overflow tasks that
2279          * started later, and in future iterations only consider tasks that
2280          * started after the latest task in the previous pass. This
2281          * guarantees forward progress and that we don't miss any tasks.
2282          */
2283         heap->size = 0;
2284         cgroup_iter_start(scan->cg, &it);
2285         while ((p = cgroup_iter_next(scan->cg, &it))) {
2286                 /*
2287                  * Only affect tasks that qualify per the caller's callback,
2288                  * if he provided one
2289                  */
2290                 if (scan->test_task && !scan->test_task(p, scan))
2291                         continue;
2292                 /*
2293                  * Only process tasks that started after the last task
2294                  * we processed
2295                  */
2296                 if (!started_after_time(p, &latest_time, latest_task))
2297                         continue;
2298                 dropped = heap_insert(heap, p);
2299                 if (dropped == NULL) {
2300                         /*
2301                          * The new task was inserted; the heap wasn't
2302                          * previously full
2303                          */
2304                         get_task_struct(p);
2305                 } else if (dropped != p) {
2306                         /*
2307                          * The new task was inserted, and pushed out a
2308                          * different task
2309                          */
2310                         get_task_struct(p);
2311                         put_task_struct(dropped);
2312                 }
2313                 /*
2314                  * Else the new task was newer than anything already in
2315                  * the heap and wasn't inserted
2316                  */
2317         }
2318         cgroup_iter_end(scan->cg, &it);
2319
2320         if (heap->size) {
2321                 for (i = 0; i < heap->size; i++) {
2322                         struct task_struct *q = heap->ptrs[i];
2323                         if (i == 0) {
2324                                 latest_time = q->start_time;
2325                                 latest_task = q;
2326                         }
2327                         /* Process the task per the caller's callback */
2328                         scan->process_task(q, scan);
2329                         put_task_struct(q);
2330                 }
2331                 /*
2332                  * If we had to process any tasks at all, scan again
2333                  * in case some of them were in the middle of forking
2334                  * children that didn't get processed.
2335                  * Not the most efficient way to do it, but it avoids
2336                  * having to take callback_mutex in the fork path
2337                  */
2338                 goto again;
2339         }
2340         if (heap == &tmp_heap)
2341                 heap_free(&tmp_heap);
2342         return 0;
2343 }
2344
2345 /*
2346  * Stuff for reading the 'tasks' file.
2347  *
2348  * Reading this file can return large amounts of data if a cgroup has
2349  * *lots* of attached tasks. So it may need several calls to read(),
2350  * but we cannot guarantee that the information we produce is correct
2351  * unless we produce it entirely atomically.
2352  *
2353  */
2354
2355 /*
2356  * Load into 'pidarray' up to 'npids' of the tasks using cgroup
2357  * 'cgrp'.  Return actual number of pids loaded.  No need to
2358  * task_lock(p) when reading out p->cgroup, since we're in an RCU
2359  * read section, so the css_set can't go away, and is
2360  * immutable after creation.
2361  */
2362 static int pid_array_load(pid_t *pidarray, int npids, struct cgroup *cgrp)
2363 {
2364         int n = 0, pid;
2365         struct cgroup_iter it;
2366         struct task_struct *tsk;
2367         cgroup_iter_start(cgrp, &it);
2368         while ((tsk = cgroup_iter_next(cgrp, &it))) {
2369                 if (unlikely(n == npids))
2370                         break;
2371                 pid = task_pid_vnr(tsk);
2372                 if (pid > 0)
2373                         pidarray[n++] = pid;
2374         }
2375         cgroup_iter_end(cgrp, &it);
2376         return n;
2377 }
2378
2379 /**
2380  * cgroupstats_build - build and fill cgroupstats
2381  * @stats: cgroupstats to fill information into
2382  * @dentry: A dentry entry belonging to the cgroup for which stats have
2383  * been requested.
2384  *
2385  * Build and fill cgroupstats so that taskstats can export it to user
2386  * space.
2387  */
2388 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2389 {
2390         int ret = -EINVAL;
2391         struct cgroup *cgrp;
2392         struct cgroup_iter it;
2393         struct task_struct *tsk;
2394
2395         /*
2396          * Validate dentry by checking the superblock operations,
2397          * and make sure it's a directory.
2398          */
2399         if (dentry->d_sb->s_op != &cgroup_ops ||
2400             !S_ISDIR(dentry->d_inode->i_mode))
2401                  goto err;
2402
2403         ret = 0;
2404         cgrp = dentry->d_fsdata;
2405
2406         cgroup_iter_start(cgrp, &it);
2407         while ((tsk = cgroup_iter_next(cgrp, &it))) {
2408                 switch (tsk->state) {
2409                 case TASK_RUNNING:
2410                         stats->nr_running++;
2411                         break;
2412                 case TASK_INTERRUPTIBLE:
2413                         stats->nr_sleeping++;
2414                         break;
2415                 case TASK_UNINTERRUPTIBLE:
2416                         stats->nr_uninterruptible++;
2417                         break;
2418                 case TASK_STOPPED:
2419                         stats->nr_stopped++;
2420                         break;
2421                 default:
2422                         if (delayacct_is_task_waiting_on_io(tsk))
2423                                 stats->nr_io_wait++;
2424                         break;
2425                 }
2426         }
2427         cgroup_iter_end(cgrp, &it);
2428
2429 err:
2430         return ret;
2431 }
2432
2433 static int cmppid(const void *a, const void *b)
2434 {
2435         return *(pid_t *)a - *(pid_t *)b;
2436 }
2437
2438
2439 /*
2440  * seq_file methods for the "tasks" file. The seq_file position is the
2441  * next pid to display; the seq_file iterator is a pointer to the pid
2442  * in the cgroup->tasks_pids array.
2443  */
2444
2445 static void *cgroup_tasks_start(struct seq_file *s, loff_t *pos)
2446 {
2447         /*
2448          * Initially we receive a position value that corresponds to
2449          * one more than the last pid shown (or 0 on the first call or
2450          * after a seek to the start). Use a binary-search to find the
2451          * next pid to display, if any
2452          */
2453         struct cgroup *cgrp = s->private;
2454         int index = 0, pid = *pos;
2455         int *iter;
2456
2457         down_read(&cgrp->pids_mutex);
2458         if (pid) {
2459                 int end = cgrp->pids_length;
2460
2461                 while (index < end) {
2462                         int mid = (index + end) / 2;
2463                         if (cgrp->tasks_pids[mid] == pid) {
2464                                 index = mid;
2465                                 break;
2466                         } else if (cgrp->tasks_pids[mid] <= pid)
2467                                 index = mid + 1;
2468                         else
2469                                 end = mid;
2470                 }
2471         }
2472         /* If we're off the end of the array, we're done */
2473         if (index >= cgrp->pids_length)
2474                 return NULL;
2475         /* Update the abstract position to be the actual pid that we found */
2476         iter = cgrp->tasks_pids + index;
2477         *pos = *iter;
2478         return iter;
2479 }
2480
2481 static void cgroup_tasks_stop(struct seq_file *s, void *v)
2482 {
2483         struct cgroup *cgrp = s->private;
2484         up_read(&cgrp->pids_mutex);
2485 }
2486
2487 static void *cgroup_tasks_next(struct seq_file *s, void *v, loff_t *pos)
2488 {
2489         struct cgroup *cgrp = s->private;
2490         int *p = v;
2491         int *end = cgrp->tasks_pids + cgrp->pids_length;
2492
2493         /*
2494          * Advance to the next pid in the array. If this goes off the
2495          * end, we're done
2496          */
2497         p++;
2498         if (p >= end) {
2499                 return NULL;
2500         } else {
2501                 *pos = *p;
2502                 return p;
2503         }
2504 }
2505
2506 static int cgroup_tasks_show(struct seq_file *s, void *v)
2507 {
2508         return seq_printf(s, "%d\n", *(int *)v);
2509 }
2510
2511 static const struct seq_operations cgroup_tasks_seq_operations = {
2512         .start = cgroup_tasks_start,
2513         .stop = cgroup_tasks_stop,
2514         .next = cgroup_tasks_next,
2515         .show = cgroup_tasks_show,
2516 };
2517
2518 static void release_cgroup_pid_array(struct cgroup *cgrp)
2519 {
2520         down_write(&cgrp->pids_mutex);
2521         BUG_ON(!cgrp->pids_use_count);
2522         if (!--cgrp->pids_use_count) {
2523                 kfree(cgrp->tasks_pids);
2524                 cgrp->tasks_pids = NULL;
2525                 cgrp->pids_length = 0;
2526         }
2527         up_write(&cgrp->pids_mutex);
2528 }
2529
2530 static int cgroup_tasks_release(struct inode *inode, struct file *file)
2531 {
2532         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2533
2534         if (!(file->f_mode & FMODE_READ))
2535                 return 0;
2536
2537         release_cgroup_pid_array(cgrp);
2538         return seq_release(inode, file);
2539 }
2540
2541 static struct file_operations cgroup_tasks_operations = {
2542         .read = seq_read,
2543         .llseek = seq_lseek,
2544         .write = cgroup_file_write,
2545         .release = cgroup_tasks_release,
2546 };
2547
2548 /*
2549  * Handle an open on 'tasks' file.  Prepare an array containing the
2550  * process id's of tasks currently attached to the cgroup being opened.
2551  */
2552
2553 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2554 {
2555         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2556         pid_t *pidarray;
2557         int npids;
2558         int retval;
2559
2560         /* Nothing to do for write-only files */
2561         if (!(file->f_mode & FMODE_READ))
2562                 return 0;
2563
2564         /*
2565          * If cgroup gets more users after we read count, we won't have
2566          * enough space - tough.  This race is indistinguishable to the
2567          * caller from the case that the additional cgroup users didn't
2568          * show up until sometime later on.
2569          */
2570         npids = cgroup_task_count(cgrp);
2571         pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
2572         if (!pidarray)
2573                 return -ENOMEM;
2574         npids = pid_array_load(pidarray, npids, cgrp);
2575         sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
2576
2577         /*
2578          * Store the array in the cgroup, freeing the old
2579          * array if necessary
2580          */
2581         down_write(&cgrp->pids_mutex);
2582         kfree(cgrp->tasks_pids);
2583         cgrp->tasks_pids = pidarray;
2584         cgrp->pids_length = npids;
2585         cgrp->pids_use_count++;
2586         up_write(&cgrp->pids_mutex);
2587
2588         file->f_op = &cgroup_tasks_operations;
2589
2590         retval = seq_open(file, &cgroup_tasks_seq_operations);
2591         if (retval) {
2592                 release_cgroup_pid_array(cgrp);
2593                 return retval;
2594         }
2595         ((struct seq_file *)file->private_data)->private = cgrp;
2596         return 0;
2597 }
2598
2599 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2600                                             struct cftype *cft)
2601 {
2602         return notify_on_release(cgrp);
2603 }
2604
2605 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2606                                           struct cftype *cft,
2607                                           u64 val)
2608 {
2609         clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2610         if (val)
2611                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2612         else
2613                 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2614         return 0;
2615 }
2616
2617 /*
2618  * for the common functions, 'private' gives the type of file
2619  */
2620 static struct cftype files[] = {
2621         {
2622                 .name = "tasks",
2623                 .open = cgroup_tasks_open,
2624                 .write_u64 = cgroup_tasks_write,
2625                 .release = cgroup_tasks_release,
2626                 .private = FILE_TASKLIST,
2627                 .mode = S_IRUGO | S_IWUSR,
2628         },
2629
2630         {
2631                 .name = "notify_on_release",
2632                 .read_u64 = cgroup_read_notify_on_release,
2633                 .write_u64 = cgroup_write_notify_on_release,
2634                 .private = FILE_NOTIFY_ON_RELEASE,
2635         },
2636 };
2637
2638 static struct cftype cft_release_agent = {
2639         .name = "release_agent",
2640         .read_seq_string = cgroup_release_agent_show,
2641         .write_string = cgroup_release_agent_write,
2642         .max_write_len = PATH_MAX,
2643         .private = FILE_RELEASE_AGENT,
2644 };
2645
2646 static int cgroup_populate_dir(struct cgroup *cgrp)
2647 {
2648         int err;
2649         struct cgroup_subsys *ss;
2650
2651         /* First clear out any existing files */
2652         cgroup_clear_directory(cgrp->dentry);
2653
2654         err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2655         if (err < 0)
2656                 return err;
2657
2658         if (cgrp == cgrp->top_cgroup) {
2659                 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2660                         return err;
2661         }
2662
2663         for_each_subsys(cgrp->root, ss) {
2664                 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2665                         return err;
2666         }
2667         /* This cgroup is ready now */
2668         for_each_subsys(cgrp->root, ss) {
2669                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2670                 /*
2671                  * Update id->css pointer and make this css visible from
2672                  * CSS ID functions. This pointer will be dereferened
2673                  * from RCU-read-side without locks.
2674                  */
2675                 if (css->id)
2676                         rcu_assign_pointer(css->id->css, css);
2677         }
2678
2679         return 0;
2680 }
2681
2682 static void init_cgroup_css(struct cgroup_subsys_state *css,
2683                                struct cgroup_subsys *ss,
2684                                struct cgroup *cgrp)
2685 {
2686         css->cgroup = cgrp;
2687         atomic_set(&css->refcnt, 1);
2688         css->flags = 0;
2689         css->id = NULL;
2690         if (cgrp == dummytop)
2691                 set_bit(CSS_ROOT, &css->flags);
2692         BUG_ON(cgrp->subsys[ss->subsys_id]);
2693         cgrp->subsys[ss->subsys_id] = css;
2694 }
2695
2696 static void cgroup_lock_hierarchy(struct cgroupfs_root *root)
2697 {
2698         /* We need to take each hierarchy_mutex in a consistent order */
2699         int i;
2700
2701         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2702                 struct cgroup_subsys *ss = subsys[i];
2703                 if (ss->root == root)
2704                         mutex_lock(&ss->hierarchy_mutex);
2705         }
2706 }
2707
2708 static void cgroup_unlock_hierarchy(struct cgroupfs_root *root)
2709 {
2710         int i;
2711
2712         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2713                 struct cgroup_subsys *ss = subsys[i];
2714                 if (ss->root == root)
2715                         mutex_unlock(&ss->hierarchy_mutex);
2716         }
2717 }
2718
2719 /*
2720  * cgroup_create - create a cgroup
2721  * @parent: cgroup that will be parent of the new cgroup
2722  * @dentry: dentry of the new cgroup
2723  * @mode: mode to set on new inode
2724  *
2725  * Must be called with the mutex on the parent inode held
2726  */
2727 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
2728                              mode_t mode)
2729 {
2730         struct cgroup *cgrp;
2731         struct cgroupfs_root *root = parent->root;
2732         int err = 0;
2733         struct cgroup_subsys *ss;
2734         struct super_block *sb = root->sb;
2735
2736         cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
2737         if (!cgrp)
2738                 return -ENOMEM;
2739
2740         /* Grab a reference on the superblock so the hierarchy doesn't
2741          * get deleted on unmount if there are child cgroups.  This
2742          * can be done outside cgroup_mutex, since the sb can't
2743          * disappear while someone has an open control file on the
2744          * fs */
2745         atomic_inc(&sb->s_active);
2746
2747         mutex_lock(&cgroup_mutex);
2748
2749         init_cgroup_housekeeping(cgrp);
2750
2751         cgrp->parent = parent;
2752         cgrp->root = parent->root;
2753         cgrp->top_cgroup = parent->top_cgroup;
2754
2755         if (notify_on_release(parent))
2756                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2757
2758         for_each_subsys(root, ss) {
2759                 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
2760                 if (IS_ERR(css)) {
2761                         err = PTR_ERR(css);
2762                         goto err_destroy;
2763                 }
2764                 init_cgroup_css(css, ss, cgrp);
2765                 if (ss->use_id)
2766                         if (alloc_css_id(ss, parent, cgrp))
2767                                 goto err_destroy;
2768                 /* At error, ->destroy() callback has to free assigned ID. */
2769         }
2770
2771         cgroup_lock_hierarchy(root);
2772         list_add(&cgrp->sibling, &cgrp->parent->children);
2773         cgroup_unlock_hierarchy(root);
2774         root->number_of_cgroups++;
2775
2776         err = cgroup_create_dir(cgrp, dentry, mode);
2777         if (err < 0)
2778                 goto err_remove;
2779
2780         /* The cgroup directory was pre-locked for us */
2781         BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
2782
2783         err = cgroup_populate_dir(cgrp);
2784         /* If err < 0, we have a half-filled directory - oh well ;) */
2785
2786         mutex_unlock(&cgroup_mutex);
2787         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
2788
2789         return 0;
2790
2791  err_remove:
2792
2793         cgroup_lock_hierarchy(root);
2794         list_del(&cgrp->sibling);
2795         cgroup_unlock_hierarchy(root);
2796         root->number_of_cgroups--;
2797
2798  err_destroy:
2799
2800         for_each_subsys(root, ss) {
2801                 if (cgrp->subsys[ss->subsys_id])
2802                         ss->destroy(ss, cgrp);
2803         }
2804
2805         mutex_unlock(&cgroup_mutex);
2806
2807         /* Release the reference count that we took on the superblock */
2808         deactivate_super(sb);
2809
2810         kfree(cgrp);
2811         return err;
2812 }
2813
2814 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2815 {
2816         struct cgroup *c_parent = dentry->d_parent->d_fsdata;
2817
2818         /* the vfs holds inode->i_mutex already */
2819         return cgroup_create(c_parent, dentry, mode | S_IFDIR);
2820 }
2821
2822 static int cgroup_has_css_refs(struct cgroup *cgrp)
2823 {
2824         /* Check the reference count on each subsystem. Since we
2825          * already established that there are no tasks in the
2826          * cgroup, if the css refcount is also 1, then there should
2827          * be no outstanding references, so the subsystem is safe to
2828          * destroy. We scan across all subsystems rather than using
2829          * the per-hierarchy linked list of mounted subsystems since
2830          * we can be called via check_for_release() with no
2831          * synchronization other than RCU, and the subsystem linked
2832          * list isn't RCU-safe */
2833         int i;
2834         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2835                 struct cgroup_subsys *ss = subsys[i];
2836                 struct cgroup_subsys_state *css;
2837                 /* Skip subsystems not in this hierarchy */
2838                 if (ss->root != cgrp->root)
2839                         continue;
2840                 css = cgrp->subsys[ss->subsys_id];
2841                 /* When called from check_for_release() it's possible
2842                  * that by this point the cgroup has been removed
2843                  * and the css deleted. But a false-positive doesn't
2844                  * matter, since it can only happen if the cgroup
2845                  * has been deleted and hence no longer needs the
2846                  * release agent to be called anyway. */
2847                 if (css && (atomic_read(&css->refcnt) > 1))
2848                         return 1;
2849         }
2850         return 0;
2851 }
2852
2853 /*
2854  * Atomically mark all (or else none) of the cgroup's CSS objects as
2855  * CSS_REMOVED. Return true on success, or false if the cgroup has
2856  * busy subsystems. Call with cgroup_mutex held
2857  */
2858
2859 static int cgroup_clear_css_refs(struct cgroup *cgrp)
2860 {
2861         struct cgroup_subsys *ss;
2862         unsigned long flags;
2863         bool failed = false;
2864         local_irq_save(flags);
2865         for_each_subsys(cgrp->root, ss) {
2866                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2867                 int refcnt;
2868                 while (1) {
2869                         /* We can only remove a CSS with a refcnt==1 */
2870                         refcnt = atomic_read(&css->refcnt);
2871                         if (refcnt > 1) {
2872                                 failed = true;
2873                                 goto done;
2874                         }
2875                         BUG_ON(!refcnt);
2876                         /*
2877                          * Drop the refcnt to 0 while we check other
2878                          * subsystems. This will cause any racing
2879                          * css_tryget() to spin until we set the
2880                          * CSS_REMOVED bits or abort
2881                          */
2882                         if (atomic_cmpxchg(&css->refcnt, refcnt, 0) == refcnt)
2883                                 break;
2884                         cpu_relax();
2885                 }
2886         }
2887  done:
2888         for_each_subsys(cgrp->root, ss) {
2889                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2890                 if (failed) {
2891                         /*
2892                          * Restore old refcnt if we previously managed
2893                          * to clear it from 1 to 0
2894                          */
2895                         if (!atomic_read(&css->refcnt))
2896                                 atomic_set(&css->refcnt, 1);
2897                 } else {
2898                         /* Commit the fact that the CSS is removed */
2899                         set_bit(CSS_REMOVED, &css->flags);
2900                 }
2901         }
2902         local_irq_restore(flags);
2903         return !failed;
2904 }
2905
2906 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
2907 {
2908         struct cgroup *cgrp = dentry->d_fsdata;
2909         struct dentry *d;
2910         struct cgroup *parent;
2911         DEFINE_WAIT(wait);
2912         int ret;
2913
2914         /* the vfs holds both inode->i_mutex already */
2915 again:
2916         mutex_lock(&cgroup_mutex);
2917         if (atomic_read(&cgrp->count) != 0) {
2918                 mutex_unlock(&cgroup_mutex);
2919                 return -EBUSY;
2920         }
2921         if (!list_empty(&cgrp->children)) {
2922                 mutex_unlock(&cgroup_mutex);
2923                 return -EBUSY;
2924         }
2925         mutex_unlock(&cgroup_mutex);
2926
2927         /*
2928          * In general, subsystem has no css->refcnt after pre_destroy(). But
2929          * in racy cases, subsystem may have to get css->refcnt after
2930          * pre_destroy() and it makes rmdir return with -EBUSY. This sometimes
2931          * make rmdir return -EBUSY too often. To avoid that, we use waitqueue
2932          * for cgroup's rmdir. CGRP_WAIT_ON_RMDIR is for synchronizing rmdir
2933          * and subsystem's reference count handling. Please see css_get/put
2934          * and css_tryget() and cgroup_wakeup_rmdir_waiter() implementation.
2935          */
2936         set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2937
2938         /*
2939          * Call pre_destroy handlers of subsys. Notify subsystems
2940          * that rmdir() request comes.
2941          */
2942         ret = cgroup_call_pre_destroy(cgrp);
2943         if (ret) {
2944                 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2945                 return ret;
2946         }
2947
2948         mutex_lock(&cgroup_mutex);
2949         parent = cgrp->parent;
2950         if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
2951                 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2952                 mutex_unlock(&cgroup_mutex);
2953                 return -EBUSY;
2954         }
2955         prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
2956         if (!cgroup_clear_css_refs(cgrp)) {
2957                 mutex_unlock(&cgroup_mutex);
2958                 /*
2959                  * Because someone may call cgroup_wakeup_rmdir_waiter() before
2960                  * prepare_to_wait(), we need to check this flag.
2961                  */
2962                 if (test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))
2963                         schedule();
2964                 finish_wait(&cgroup_rmdir_waitq, &wait);
2965                 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2966                 if (signal_pending(current))
2967                         return -EINTR;
2968                 goto again;
2969         }
2970         /* NO css_tryget() can success after here. */
2971         finish_wait(&cgroup_rmdir_waitq, &wait);
2972         clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2973
2974         spin_lock(&release_list_lock);
2975         set_bit(CGRP_REMOVED, &cgrp->flags);
2976         if (!list_empty(&cgrp->release_list))
2977                 list_del(&cgrp->release_list);
2978         spin_unlock(&release_list_lock);
2979
2980         cgroup_lock_hierarchy(cgrp->root);
2981         /* delete this cgroup from parent->children */
2982         list_del(&cgrp->sibling);
2983         cgroup_unlock_hierarchy(cgrp->root);
2984
2985         spin_lock(&cgrp->dentry->d_lock);
2986         d = dget(cgrp->dentry);
2987         spin_unlock(&d->d_lock);
2988
2989         cgroup_d_remove_dir(d);
2990         dput(d);
2991
2992         set_bit(CGRP_RELEASABLE, &parent->flags);
2993         check_for_release(parent);
2994
2995         mutex_unlock(&cgroup_mutex);
2996         return 0;
2997 }
2998
2999 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
3000 {
3001         struct cgroup_subsys_state *css;
3002
3003         printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
3004
3005         /* Create the top cgroup state for this subsystem */
3006         list_add(&ss->sibling, &rootnode.subsys_list);
3007         ss->root = &rootnode;
3008         css = ss->create(ss, dummytop);
3009         /* We don't handle early failures gracefully */
3010         BUG_ON(IS_ERR(css));
3011         init_cgroup_css(css, ss, dummytop);
3012
3013         /* Update the init_css_set to contain a subsys
3014          * pointer to this state - since the subsystem is
3015          * newly registered, all tasks and hence the
3016          * init_css_set is in the subsystem's top cgroup. */
3017         init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
3018
3019         need_forkexit_callback |= ss->fork || ss->exit;
3020
3021         /* At system boot, before all subsystems have been
3022          * registered, no tasks have been forked, so we don't
3023          * need to invoke fork callbacks here. */
3024         BUG_ON(!list_empty(&init_task.tasks));
3025
3026         mutex_init(&ss->hierarchy_mutex);
3027         lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
3028         ss->active = 1;
3029 }
3030
3031 /**
3032  * cgroup_init_early - cgroup initialization at system boot
3033  *
3034  * Initialize cgroups at system boot, and initialize any
3035  * subsystems that request early init.
3036  */
3037 int __init cgroup_init_early(void)
3038 {
3039         int i;
3040         atomic_set(&init_css_set.refcount, 1);
3041         INIT_LIST_HEAD(&init_css_set.cg_links);
3042         INIT_LIST_HEAD(&init_css_set.tasks);
3043         INIT_HLIST_NODE(&init_css_set.hlist);
3044         css_set_count = 1;
3045         init_cgroup_root(&rootnode);
3046         root_count = 1;
3047         init_task.cgroups = &init_css_set;
3048
3049         init_css_set_link.cg = &init_css_set;
3050         init_css_set_link.cgrp = dummytop;
3051         list_add(&init_css_set_link.cgrp_link_list,
3052                  &rootnode.top_cgroup.css_sets);
3053         list_add(&init_css_set_link.cg_link_list,
3054                  &init_css_set.cg_links);
3055
3056         for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
3057                 INIT_HLIST_HEAD(&css_set_table[i]);
3058
3059         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3060                 struct cgroup_subsys *ss = subsys[i];
3061
3062                 BUG_ON(!ss->name);
3063                 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
3064                 BUG_ON(!ss->create);
3065                 BUG_ON(!ss->destroy);
3066                 if (ss->subsys_id != i) {
3067                         printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
3068                                ss->name, ss->subsys_id);
3069                         BUG();
3070                 }
3071
3072                 if (ss->early_init)
3073                         cgroup_init_subsys(ss);
3074         }
3075         return 0;
3076 }
3077
3078 /**
3079  * cgroup_init - cgroup initialization
3080  *
3081  * Register cgroup filesystem and /proc file, and initialize
3082  * any subsystems that didn't request early init.
3083  */
3084 int __init cgroup_init(void)
3085 {
3086         int err;
3087         int i;
3088         struct hlist_head *hhead;
3089
3090         err = bdi_init(&cgroup_backing_dev_info);
3091         if (err)
3092                 return err;
3093
3094         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3095                 struct cgroup_subsys *ss = subsys[i];
3096                 if (!ss->early_init)
3097                         cgroup_init_subsys(ss);
3098                 if (ss->use_id)
3099                         cgroup_subsys_init_idr(ss);
3100         }
3101
3102         /* Add init_css_set to the hash table */
3103         hhead = css_set_hash(init_css_set.subsys);
3104         hlist_add_head(&init_css_set.hlist, hhead);
3105         BUG_ON(!init_root_id(&rootnode));
3106         err = register_filesystem(&cgroup_fs_type);
3107         if (err < 0)
3108                 goto out;
3109
3110         proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
3111
3112 out:
3113         if (err)
3114                 bdi_destroy(&cgroup_backing_dev_info);
3115
3116         return err;
3117 }
3118
3119 /*
3120  * proc_cgroup_show()
3121  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
3122  *  - Used for /proc/<pid>/cgroup.
3123  *  - No need to task_lock(tsk) on this tsk->cgroup reference, as it
3124  *    doesn't really matter if tsk->cgroup changes after we read it,
3125  *    and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
3126  *    anyway.  No need to check that tsk->cgroup != NULL, thanks to
3127  *    the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
3128  *    cgroup to top_cgroup.
3129  */
3130
3131 /* TODO: Use a proper seq_file iterator */
3132 static int proc_cgroup_show(struct seq_file *m, void *v)
3133 {
3134         struct pid *pid;
3135         struct task_struct *tsk;
3136         char *buf;
3137         int retval;
3138         struct cgroupfs_root *root;
3139
3140         retval = -ENOMEM;
3141         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3142         if (!buf)
3143                 goto out;
3144
3145         retval = -ESRCH;
3146         pid = m->private;
3147         tsk = get_pid_task(pid, PIDTYPE_PID);
3148         if (!tsk)
3149                 goto out_free;
3150
3151         retval = 0;
3152
3153         mutex_lock(&cgroup_mutex);
3154
3155         for_each_active_root(root) {
3156                 struct cgroup_subsys *ss;
3157                 struct cgroup *cgrp;
3158                 int count = 0;
3159
3160                 seq_printf(m, "%d:", root->hierarchy_id);
3161                 for_each_subsys(root, ss)
3162                         seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
3163                 if (strlen(root->name))
3164                         seq_printf(m, "%sname=%s", count ? "," : "",
3165                                    root->name);
3166                 seq_putc(m, ':');
3167                 cgrp = task_cgroup_from_root(tsk, root);
3168                 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
3169                 if (retval < 0)
3170                         goto out_unlock;
3171                 seq_puts(m, buf);
3172                 seq_putc(m, '\n');
3173         }
3174
3175 out_unlock:
3176         mutex_unlock(&cgroup_mutex);
3177         put_task_struct(tsk);
3178 out_free:
3179         kfree(buf);
3180 out:
3181         return retval;
3182 }
3183
3184 static int cgroup_open(struct inode *inode, struct file *file)
3185 {
3186         struct pid *pid = PROC_I(inode)->pid;
3187         return single_open(file, proc_cgroup_show, pid);
3188 }
3189
3190 struct file_operations proc_cgroup_operations = {
3191         .open           = cgroup_open,
3192         .read           = seq_read,
3193         .llseek         = seq_lseek,
3194         .release        = single_release,
3195 };
3196
3197 /* Display information about each subsystem and each hierarchy */
3198 static int proc_cgroupstats_show(struct seq_file *m, void *v)
3199 {
3200         int i;
3201
3202         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
3203         mutex_lock(&cgroup_mutex);
3204         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3205                 struct cgroup_subsys *ss = subsys[i];
3206                 seq_printf(m, "%s\t%d\t%d\t%d\n",
3207                            ss->name, ss->root->hierarchy_id,
3208                            ss->root->number_of_cgroups, !ss->disabled);
3209         }
3210         mutex_unlock(&cgroup_mutex);
3211         return 0;
3212 }
3213
3214 static int cgroupstats_open(struct inode *inode, struct file *file)
3215 {
3216         return single_open(file, proc_cgroupstats_show, NULL);
3217 }
3218
3219 static struct file_operations proc_cgroupstats_operations = {
3220         .open = cgroupstats_open,
3221         .read = seq_read,
3222         .llseek = seq_lseek,
3223         .release = single_release,
3224 };
3225
3226 /**
3227  * cgroup_fork - attach newly forked task to its parents cgroup.
3228  * @child: pointer to task_struct of forking parent process.
3229  *
3230  * Description: A task inherits its parent's cgroup at fork().
3231  *
3232  * A pointer to the shared css_set was automatically copied in
3233  * fork.c by dup_task_struct().  However, we ignore that copy, since
3234  * it was not made under the protection of RCU or cgroup_mutex, so
3235  * might no longer be a valid cgroup pointer.  cgroup_attach_task() might
3236  * have already changed current->cgroups, allowing the previously
3237  * referenced cgroup group to be removed and freed.
3238  *
3239  * At the point that cgroup_fork() is called, 'current' is the parent
3240  * task, and the passed argument 'child' points to the child task.
3241  */
3242 void cgroup_fork(struct task_struct *child)
3243 {
3244         task_lock(current);
3245         child->cgroups = current->cgroups;
3246         get_css_set(child->cgroups);
3247         task_unlock(current);
3248         INIT_LIST_HEAD(&child->cg_list);
3249 }
3250
3251 /**
3252  * cgroup_fork_callbacks - run fork callbacks
3253  * @child: the new task
3254  *
3255  * Called on a new task very soon before adding it to the
3256  * tasklist. No need to take any locks since no-one can
3257  * be operating on this task.
3258  */
3259 void cgroup_fork_callbacks(struct task_struct *child)
3260 {
3261         if (need_forkexit_callback) {
3262                 int i;
3263                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3264                         struct cgroup_subsys *ss = subsys[i];
3265                         if (ss->fork)
3266                                 ss->fork(ss, child);
3267                 }
3268         }
3269 }
3270
3271 /**
3272  * cgroup_post_fork - called on a new task after adding it to the task list
3273  * @child: the task in question
3274  *
3275  * Adds the task to the list running through its css_set if necessary.
3276  * Has to be after the task is visible on the task list in case we race
3277  * with the first call to cgroup_iter_start() - to guarantee that the
3278  * new task ends up on its list.
3279  */
3280 void cgroup_post_fork(struct task_struct *child)
3281 {
3282         if (use_task_css_set_links) {
3283                 write_lock(&css_set_lock);
3284                 task_lock(child);
3285                 if (list_empty(&child->cg_list))
3286                         list_add(&child->cg_list, &child->cgroups->tasks);
3287                 task_unlock(child);
3288                 write_unlock(&css_set_lock);
3289         }
3290 }
3291 /**
3292  * cgroup_exit - detach cgroup from exiting task
3293  * @tsk: pointer to task_struct of exiting process
3294  * @run_callback: run exit callbacks?
3295  *
3296  * Description: Detach cgroup from @tsk and release it.
3297  *
3298  * Note that cgroups marked notify_on_release force every task in
3299  * them to take the global cgroup_mutex mutex when exiting.
3300  * This could impact scaling on very large systems.  Be reluctant to
3301  * use notify_on_release cgroups where very high task exit scaling
3302  * is required on large systems.
3303  *
3304  * the_top_cgroup_hack:
3305  *
3306  *    Set the exiting tasks cgroup to the root cgroup (top_cgroup).
3307  *
3308  *    We call cgroup_exit() while the task is still competent to
3309  *    handle notify_on_release(), then leave the task attached to the
3310  *    root cgroup in each hierarchy for the remainder of its exit.
3311  *
3312  *    To do this properly, we would increment the reference count on
3313  *    top_cgroup, and near the very end of the kernel/exit.c do_exit()
3314  *    code we would add a second cgroup function call, to drop that
3315  *    reference.  This would just create an unnecessary hot spot on
3316  *    the top_cgroup reference count, to no avail.
3317  *
3318  *    Normally, holding a reference to a cgroup without bumping its
3319  *    count is unsafe.   The cgroup could go away, or someone could
3320  *    attach us to a different cgroup, decrementing the count on
3321  *    the first cgroup that we never incremented.  But in this case,
3322  *    top_cgroup isn't going away, and either task has PF_EXITING set,
3323  *    which wards off any cgroup_attach_task() attempts, or task is a failed
3324  *    fork, never visible to cgroup_attach_task.
3325  */
3326 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
3327 {
3328         int i;
3329         struct css_set *cg;
3330
3331         if (run_callbacks && need_forkexit_callback) {
3332                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3333                         struct cgroup_subsys *ss = subsys[i];
3334                         if (ss->exit)
3335                                 ss->exit(ss, tsk);
3336                 }
3337         }
3338
3339         /*
3340          * Unlink from the css_set task list if necessary.
3341          * Optimistically check cg_list before taking
3342          * css_set_lock
3343          */
3344         if (!list_empty(&tsk->cg_list)) {
3345                 write_lock(&css_set_lock);
3346                 if (!list_empty(&tsk->cg_list))
3347                         list_del(&tsk->cg_list);
3348                 write_unlock(&css_set_lock);
3349         }
3350
3351         /* Reassign the task to the init_css_set. */
3352         task_lock(tsk);
3353         cg = tsk->cgroups;
3354         tsk->cgroups = &init_css_set;
3355         task_unlock(tsk);
3356         if (cg)
3357                 put_css_set_taskexit(cg);
3358 }
3359
3360 /**
3361  * cgroup_clone - clone the cgroup the given subsystem is attached to
3362  * @tsk: the task to be moved
3363  * @subsys: the given subsystem
3364  * @nodename: the name for the new cgroup
3365  *
3366  * Duplicate the current cgroup in the hierarchy that the given
3367  * subsystem is attached to, and move this task into the new
3368  * child.
3369  */
3370 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
3371                                                         char *nodename)
3372 {
3373         struct dentry *dentry;
3374         int ret = 0;
3375         struct cgroup *parent, *child;
3376         struct inode *inode;
3377         struct css_set *cg;
3378         struct cgroupfs_root *root;
3379         struct cgroup_subsys *ss;
3380
3381         /* We shouldn't be called by an unregistered subsystem */
3382         BUG_ON(!subsys->active);
3383
3384         /* First figure out what hierarchy and cgroup we're dealing
3385          * with, and pin them so we can drop cgroup_mutex */
3386         mutex_lock(&cgroup_mutex);
3387  again:
3388         root = subsys->root;
3389         if (root == &rootnode) {
3390                 mutex_unlock(&cgroup_mutex);
3391                 return 0;
3392         }
3393
3394         /* Pin the hierarchy */
3395         if (!atomic_inc_not_zero(&root->sb->s_active)) {
3396                 /* We race with the final deactivate_super() */
3397                 mutex_unlock(&cgroup_mutex);
3398                 return 0;
3399         }
3400
3401         /* Keep the cgroup alive */
3402         task_lock(tsk);
3403         parent = task_cgroup(tsk, subsys->subsys_id);
3404         cg = tsk->cgroups;
3405         get_css_set(cg);
3406         task_unlock(tsk);
3407
3408         mutex_unlock(&cgroup_mutex);
3409
3410         /* Now do the VFS work to create a cgroup */
3411         inode = parent->dentry->d_inode;
3412
3413         /* Hold the parent directory mutex across this operation to
3414          * stop anyone else deleting the new cgroup */
3415         mutex_lock(&inode->i_mutex);
3416         dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
3417         if (IS_ERR(dentry)) {
3418                 printk(KERN_INFO
3419                        "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
3420                        PTR_ERR(dentry));
3421                 ret = PTR_ERR(dentry);
3422                 goto out_release;
3423         }
3424
3425         /* Create the cgroup directory, which also creates the cgroup */
3426         ret = vfs_mkdir(inode, dentry, 0755);
3427         child = __d_cgrp(dentry);
3428         dput(dentry);
3429         if (ret) {
3430                 printk(KERN_INFO
3431                        "Failed to create cgroup %s: %d\n", nodename,
3432                        ret);
3433                 goto out_release;
3434         }
3435
3436         /* The cgroup now exists. Retake cgroup_mutex and check
3437          * that we're still in the same state that we thought we
3438          * were. */
3439         mutex_lock(&cgroup_mutex);
3440         if ((root != subsys->root) ||
3441             (parent != task_cgroup(tsk, subsys->subsys_id))) {
3442                 /* Aargh, we raced ... */
3443                 mutex_unlock(&inode->i_mutex);
3444                 put_css_set(cg);
3445
3446                 deactivate_super(root->sb);
3447                 /* The cgroup is still accessible in the VFS, but
3448                  * we're not going to try to rmdir() it at this
3449                  * point. */
3450                 printk(KERN_INFO
3451                        "Race in cgroup_clone() - leaking cgroup %s\n",
3452                        nodename);
3453                 goto again;
3454         }
3455
3456         /* do any required auto-setup */
3457         for_each_subsys(root, ss) {
3458                 if (ss->post_clone)
3459                         ss->post_clone(ss, child);
3460         }
3461
3462         /* All seems fine. Finish by moving the task into the new cgroup */
3463         ret = cgroup_attach_task(child, tsk);
3464         mutex_unlock(&cgroup_mutex);
3465
3466  out_release:
3467         mutex_unlock(&inode->i_mutex);
3468
3469         mutex_lock(&cgroup_mutex);
3470         put_css_set(cg);
3471         mutex_unlock(&cgroup_mutex);
3472         deactivate_super(root->sb);
3473         return ret;
3474 }
3475
3476 /**
3477  * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
3478  * @cgrp: the cgroup in question
3479  * @task: the task in question
3480  *
3481  * See if @cgrp is a descendant of @task's cgroup in the appropriate
3482  * hierarchy.
3483  *
3484  * If we are sending in dummytop, then presumably we are creating
3485  * the top cgroup in the subsystem.
3486  *
3487  * Called only by the ns (nsproxy) cgroup.
3488  */
3489 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
3490 {
3491         int ret;
3492         struct cgroup *target;
3493
3494         if (cgrp == dummytop)
3495                 return 1;
3496
3497         target = task_cgroup_from_root(task, cgrp->root);
3498         while (cgrp != target && cgrp!= cgrp->top_cgroup)
3499                 cgrp = cgrp->parent;
3500         ret = (cgrp == target);
3501         return ret;
3502 }
3503
3504 static void check_for_release(struct cgroup *cgrp)
3505 {
3506         /* All of these checks rely on RCU to keep the cgroup
3507          * structure alive */
3508         if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
3509             && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
3510                 /* Control Group is currently removeable. If it's not
3511                  * already queued for a userspace notification, queue
3512                  * it now */
3513                 int need_schedule_work = 0;
3514                 spin_lock(&release_list_lock);
3515                 if (!cgroup_is_removed(cgrp) &&
3516                     list_empty(&cgrp->release_list)) {
3517                         list_add(&cgrp->release_list, &release_list);
3518                         need_schedule_work = 1;
3519                 }
3520                 spin_unlock(&release_list_lock);
3521                 if (need_schedule_work)
3522                         schedule_work(&release_agent_work);
3523         }
3524 }
3525
3526 void __css_put(struct cgroup_subsys_state *css)
3527 {
3528         struct cgroup *cgrp = css->cgroup;
3529         rcu_read_lock();
3530         if (atomic_dec_return(&css->refcnt) == 1) {
3531                 if (notify_on_release(cgrp)) {
3532                         set_bit(CGRP_RELEASABLE, &cgrp->flags);
3533                         check_for_release(cgrp);
3534                 }
3535                 cgroup_wakeup_rmdir_waiter(cgrp);
3536         }
3537         rcu_read_unlock();
3538 }
3539
3540 /*
3541  * Notify userspace when a cgroup is released, by running the
3542  * configured release agent with the name of the cgroup (path
3543  * relative to the root of cgroup file system) as the argument.
3544  *
3545  * Most likely, this user command will try to rmdir this cgroup.
3546  *
3547  * This races with the possibility that some other task will be
3548  * attached to this cgroup before it is removed, or that some other
3549  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
3550  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
3551  * unused, and this cgroup will be reprieved from its death sentence,
3552  * to continue to serve a useful existence.  Next time it's released,
3553  * we will get notified again, if it still has 'notify_on_release' set.
3554  *
3555  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
3556  * means only wait until the task is successfully execve()'d.  The
3557  * separate release agent task is forked by call_usermodehelper(),
3558  * then control in this thread returns here, without waiting for the
3559  * release agent task.  We don't bother to wait because the caller of
3560  * this routine has no use for the exit status of the release agent
3561  * task, so no sense holding our caller up for that.
3562  */
3563 static void cgroup_release_agent(struct work_struct *work)
3564 {
3565         BUG_ON(work != &release_agent_work);
3566         mutex_lock(&cgroup_mutex);
3567         spin_lock(&release_list_lock);
3568         while (!list_empty(&release_list)) {
3569                 char *argv[3], *envp[3];
3570                 int i;
3571                 char *pathbuf = NULL, *agentbuf = NULL;
3572                 struct cgroup *cgrp = list_entry(release_list.next,
3573                                                     struct cgroup,
3574                                                     release_list);
3575                 list_del_init(&cgrp->release_list);
3576                 spin_unlock(&release_list_lock);
3577                 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3578                 if (!pathbuf)
3579                         goto continue_free;
3580                 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
3581                         goto continue_free;
3582                 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
3583                 if (!agentbuf)
3584                         goto continue_free;
3585
3586                 i = 0;
3587                 argv[i++] = agentbuf;
3588                 argv[i++] = pathbuf;
3589                 argv[i] = NULL;
3590
3591                 i = 0;
3592                 /* minimal command environment */
3593                 envp[i++] = "HOME=/";
3594                 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3595                 envp[i] = NULL;
3596
3597                 /* Drop the lock while we invoke the usermode helper,
3598                  * since the exec could involve hitting disk and hence
3599                  * be a slow process */
3600                 mutex_unlock(&cgroup_mutex);
3601                 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3602                 mutex_lock(&cgroup_mutex);
3603  continue_free:
3604                 kfree(pathbuf);
3605                 kfree(agentbuf);
3606                 spin_lock(&release_list_lock);
3607         }
3608         spin_unlock(&release_list_lock);
3609         mutex_unlock(&cgroup_mutex);
3610 }
3611
3612 static int __init cgroup_disable(char *str)
3613 {
3614         int i;
3615         char *token;
3616
3617         while ((token = strsep(&str, ",")) != NULL) {
3618                 if (!*token)
3619                         continue;
3620
3621                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3622                         struct cgroup_subsys *ss = subsys[i];
3623
3624                         if (!strcmp(token, ss->name)) {
3625                                 ss->disabled = 1;
3626                                 printk(KERN_INFO "Disabling %s control group"
3627                                         " subsystem\n", ss->name);
3628                                 break;
3629                         }
3630                 }
3631         }
3632         return 1;
3633 }
3634 __setup("cgroup_disable=", cgroup_disable);
3635
3636 /*
3637  * Functons for CSS ID.
3638  */
3639
3640 /*
3641  *To get ID other than 0, this should be called when !cgroup_is_removed().
3642  */
3643 unsigned short css_id(struct cgroup_subsys_state *css)
3644 {
3645         struct css_id *cssid = rcu_dereference(css->id);
3646
3647         if (cssid)
3648                 return cssid->id;
3649         return 0;
3650 }
3651
3652 unsigned short css_depth(struct cgroup_subsys_state *css)
3653 {
3654         struct css_id *cssid = rcu_dereference(css->id);
3655
3656         if (cssid)
3657                 return cssid->depth;
3658         return 0;
3659 }
3660
3661 bool css_is_ancestor(struct cgroup_subsys_state *child,
3662                     const struct cgroup_subsys_state *root)
3663 {
3664         struct css_id *child_id = rcu_dereference(child->id);
3665         struct css_id *root_id = rcu_dereference(root->id);
3666
3667         if (!child_id || !root_id || (child_id->depth < root_id->depth))
3668                 return false;
3669         return child_id->stack[root_id->depth] == root_id->id;
3670 }
3671
3672 static void __free_css_id_cb(struct rcu_head *head)
3673 {
3674         struct css_id *id;
3675
3676         id = container_of(head, struct css_id, rcu_head);
3677         kfree(id);
3678 }
3679
3680 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
3681 {
3682         struct css_id *id = css->id;
3683         /* When this is called before css_id initialization, id can be NULL */
3684         if (!id)
3685                 return;
3686
3687         BUG_ON(!ss->use_id);
3688
3689         rcu_assign_pointer(id->css, NULL);
3690         rcu_assign_pointer(css->id, NULL);
3691         spin_lock(&ss->id_lock);
3692         idr_remove(&ss->idr, id->id);
3693         spin_unlock(&ss->id_lock);
3694         call_rcu(&id->rcu_head, __free_css_id_cb);
3695 }
3696
3697 /*
3698  * This is called by init or create(). Then, calls to this function are
3699  * always serialized (By cgroup_mutex() at create()).
3700  */
3701
3702 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
3703 {
3704         struct css_id *newid;
3705         int myid, error, size;
3706
3707         BUG_ON(!ss->use_id);
3708
3709         size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
3710         newid = kzalloc(size, GFP_KERNEL);
3711         if (!newid)
3712                 return ERR_PTR(-ENOMEM);
3713         /* get id */
3714         if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
3715                 error = -ENOMEM;
3716                 goto err_out;
3717         }
3718         spin_lock(&ss->id_lock);
3719         /* Don't use 0. allocates an ID of 1-65535 */
3720         error = idr_get_new_above(&ss->idr, newid, 1, &myid);
3721         spin_unlock(&ss->id_lock);
3722
3723         /* Returns error when there are no free spaces for new ID.*/
3724         if (error) {
3725                 error = -ENOSPC;
3726                 goto err_out;
3727         }
3728         if (myid > CSS_ID_MAX)
3729                 goto remove_idr;
3730
3731         newid->id = myid;
3732         newid->depth = depth;
3733         return newid;
3734 remove_idr:
3735         error = -ENOSPC;
3736         spin_lock(&ss->id_lock);
3737         idr_remove(&ss->idr, myid);
3738         spin_unlock(&ss->id_lock);
3739 err_out:
3740         kfree(newid);
3741         return ERR_PTR(error);
3742
3743 }
3744
3745 static int __init cgroup_subsys_init_idr(struct cgroup_subsys *ss)
3746 {
3747         struct css_id *newid;
3748         struct cgroup_subsys_state *rootcss;
3749
3750         spin_lock_init(&ss->id_lock);
3751         idr_init(&ss->idr);
3752
3753         rootcss = init_css_set.subsys[ss->subsys_id];
3754         newid = get_new_cssid(ss, 0);
3755         if (IS_ERR(newid))
3756                 return PTR_ERR(newid);
3757
3758         newid->stack[0] = newid->id;
3759         newid->css = rootcss;
3760         rootcss->id = newid;
3761         return 0;
3762 }
3763
3764 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
3765                         struct cgroup *child)
3766 {
3767         int subsys_id, i, depth = 0;
3768         struct cgroup_subsys_state *parent_css, *child_css;
3769         struct css_id *child_id, *parent_id = NULL;
3770
3771         subsys_id = ss->subsys_id;
3772         parent_css = parent->subsys[subsys_id];
3773         child_css = child->subsys[subsys_id];
3774         depth = css_depth(parent_css) + 1;
3775         parent_id = parent_css->id;
3776
3777         child_id = get_new_cssid(ss, depth);
3778         if (IS_ERR(child_id))
3779                 return PTR_ERR(child_id);
3780
3781         for (i = 0; i < depth; i++)
3782                 child_id->stack[i] = parent_id->stack[i];
3783         child_id->stack[depth] = child_id->id;
3784         /*
3785          * child_id->css pointer will be set after this cgroup is available
3786          * see cgroup_populate_dir()
3787          */
3788         rcu_assign_pointer(child_css->id, child_id);
3789
3790         return 0;
3791 }
3792
3793 /**
3794  * css_lookup - lookup css by id
3795  * @ss: cgroup subsys to be looked into.
3796  * @id: the id
3797  *
3798  * Returns pointer to cgroup_subsys_state if there is valid one with id.
3799  * NULL if not. Should be called under rcu_read_lock()
3800  */
3801 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
3802 {
3803         struct css_id *cssid = NULL;
3804
3805         BUG_ON(!ss->use_id);
3806         cssid = idr_find(&ss->idr, id);
3807
3808         if (unlikely(!cssid))
3809                 return NULL;
3810
3811         return rcu_dereference(cssid->css);
3812 }
3813
3814 /**
3815  * css_get_next - lookup next cgroup under specified hierarchy.
3816  * @ss: pointer to subsystem
3817  * @id: current position of iteration.
3818  * @root: pointer to css. search tree under this.
3819  * @foundid: position of found object.
3820  *
3821  * Search next css under the specified hierarchy of rootid. Calling under
3822  * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
3823  */
3824 struct cgroup_subsys_state *
3825 css_get_next(struct cgroup_subsys *ss, int id,
3826              struct cgroup_subsys_state *root, int *foundid)
3827 {
3828         struct cgroup_subsys_state *ret = NULL;
3829         struct css_id *tmp;
3830         int tmpid;
3831         int rootid = css_id(root);
3832         int depth = css_depth(root);
3833
3834         if (!rootid)
3835                 return NULL;
3836
3837         BUG_ON(!ss->use_id);
3838         /* fill start point for scan */
3839         tmpid = id;
3840         while (1) {
3841                 /*
3842                  * scan next entry from bitmap(tree), tmpid is updated after
3843                  * idr_get_next().
3844                  */
3845                 spin_lock(&ss->id_lock);
3846                 tmp = idr_get_next(&ss->idr, &tmpid);
3847                 spin_unlock(&ss->id_lock);
3848
3849                 if (!tmp)
3850                         break;
3851                 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
3852                         ret = rcu_dereference(tmp->css);
3853                         if (ret) {
3854                                 *foundid = tmpid;
3855                                 break;
3856                         }
3857                 }
3858                 /* continue to scan from next id */
3859                 tmpid = tmpid + 1;
3860         }
3861         return ret;
3862 }
3863
3864 #ifdef CONFIG_CGROUP_DEBUG
3865 static struct cgroup_subsys_state *debug_create(struct cgroup_subsys *ss,
3866                                                    struct cgroup *cont)
3867 {
3868         struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
3869
3870         if (!css)
3871                 return ERR_PTR(-ENOMEM);
3872
3873         return css;
3874 }
3875
3876 static void debug_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
3877 {
3878         kfree(cont->subsys[debug_subsys_id]);
3879 }
3880
3881 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
3882 {
3883         return atomic_read(&cont->count);
3884 }
3885
3886 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
3887 {
3888         return cgroup_task_count(cont);
3889 }
3890
3891 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
3892 {
3893         return (u64)(unsigned long)current->cgroups;
3894 }
3895
3896 static u64 current_css_set_refcount_read(struct cgroup *cont,
3897                                            struct cftype *cft)
3898 {
3899         u64 count;
3900
3901         rcu_read_lock();
3902         count = atomic_read(&current->cgroups->refcount);
3903         rcu_read_unlock();
3904         return count;
3905 }
3906
3907 static int current_css_set_cg_links_read(struct cgroup *cont,
3908                                          struct cftype *cft,
3909                                          struct seq_file *seq)
3910 {
3911         struct cg_cgroup_link *link;
3912         struct css_set *cg;
3913
3914         read_lock(&css_set_lock);
3915         rcu_read_lock();
3916         cg = rcu_dereference(current->cgroups);
3917         list_for_each_entry(link, &cg->cg_links, cg_link_list) {
3918                 struct cgroup *c = link->cgrp;
3919                 const char *name;
3920
3921                 if (c->dentry)
3922                         name = c->dentry->d_name.name;
3923                 else
3924                         name = "?";
3925                 seq_printf(seq, "Root %d group %s\n",
3926                            c->root->hierarchy_id, name);
3927         }
3928         rcu_read_unlock();
3929         read_unlock(&css_set_lock);
3930         return 0;
3931 }
3932
3933 #define MAX_TASKS_SHOWN_PER_CSS 25
3934 static int cgroup_css_links_read(struct cgroup *cont,
3935                                  struct cftype *cft,
3936                                  struct seq_file *seq)
3937 {
3938         struct cg_cgroup_link *link;
3939
3940         read_lock(&css_set_lock);
3941         list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
3942                 struct css_set *cg = link->cg;
3943                 struct task_struct *task;
3944                 int count = 0;
3945                 seq_printf(seq, "css_set %p\n", cg);
3946                 list_for_each_entry(task, &cg->tasks, cg_list) {
3947                         if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
3948                                 seq_puts(seq, "  ...\n");
3949                                 break;
3950                         } else {
3951                                 seq_printf(seq, "  task %d\n",
3952                                            task_pid_vnr(task));
3953                         }
3954                 }
3955         }
3956         read_unlock(&css_set_lock);
3957         return 0;
3958 }
3959
3960 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
3961 {
3962         return test_bit(CGRP_RELEASABLE, &cgrp->flags);
3963 }
3964
3965 static struct cftype debug_files[] =  {
3966         {
3967                 .name = "cgroup_refcount",
3968                 .read_u64 = cgroup_refcount_read,
3969         },
3970         {
3971                 .name = "taskcount",
3972                 .read_u64 = debug_taskcount_read,
3973         },
3974
3975         {
3976                 .name = "current_css_set",
3977                 .read_u64 = current_css_set_read,
3978         },
3979
3980         {
3981                 .name = "current_css_set_refcount",
3982                 .read_u64 = current_css_set_refcount_read,
3983         },
3984
3985         {
3986                 .name = "current_css_set_cg_links",
3987                 .read_seq_string = current_css_set_cg_links_read,
3988         },
3989
3990         {
3991                 .name = "cgroup_css_links",
3992                 .read_seq_string = cgroup_css_links_read,
3993         },
3994
3995         {
3996                 .name = "releasable",
3997                 .read_u64 = releasable_read,
3998         },
3999 };
4000
4001 static int debug_populate(struct cgroup_subsys *ss, struct cgroup *cont)
4002 {
4003         return cgroup_add_files(cont, ss, debug_files,
4004                                 ARRAY_SIZE(debug_files));
4005 }
4006
4007 struct cgroup_subsys debug_subsys = {
4008         .name = "debug",
4009         .create = debug_create,
4010         .destroy = debug_destroy,
4011         .populate = debug_populate,
4012         .subsys_id = debug_subsys_id,
4013 };
4014 #endif /* CONFIG_CGROUP_DEBUG */