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