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