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