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