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