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