cgroup: initialize cgrp->allcg_node in init_cgroup_housekeeping()
[cascardo/linux.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->allcg_node);
1385         INIT_LIST_HEAD(&cgrp->release_list);
1386         INIT_LIST_HEAD(&cgrp->pidlists);
1387         mutex_init(&cgrp->pidlist_mutex);
1388         INIT_LIST_HEAD(&cgrp->event_list);
1389         spin_lock_init(&cgrp->event_list_lock);
1390         simple_xattrs_init(&cgrp->xattrs);
1391 }
1392
1393 static void init_cgroup_root(struct cgroupfs_root *root)
1394 {
1395         struct cgroup *cgrp = &root->top_cgroup;
1396
1397         INIT_LIST_HEAD(&root->subsys_list);
1398         INIT_LIST_HEAD(&root->root_list);
1399         INIT_LIST_HEAD(&root->allcg_list);
1400         root->number_of_cgroups = 1;
1401         cgrp->root = root;
1402         cgrp->top_cgroup = cgrp;
1403         list_add_tail(&cgrp->allcg_node, &root->allcg_list);
1404         init_cgroup_housekeeping(cgrp);
1405 }
1406
1407 static bool init_root_id(struct cgroupfs_root *root)
1408 {
1409         int ret = 0;
1410
1411         do {
1412                 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1413                         return false;
1414                 spin_lock(&hierarchy_id_lock);
1415                 /* Try to allocate the next unused ID */
1416                 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1417                                         &root->hierarchy_id);
1418                 if (ret == -ENOSPC)
1419                         /* Try again starting from 0 */
1420                         ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1421                 if (!ret) {
1422                         next_hierarchy_id = root->hierarchy_id + 1;
1423                 } else if (ret != -EAGAIN) {
1424                         /* Can only get here if the 31-bit IDR is full ... */
1425                         BUG_ON(ret);
1426                 }
1427                 spin_unlock(&hierarchy_id_lock);
1428         } while (ret);
1429         return true;
1430 }
1431
1432 static int cgroup_test_super(struct super_block *sb, void *data)
1433 {
1434         struct cgroup_sb_opts *opts = data;
1435         struct cgroupfs_root *root = sb->s_fs_info;
1436
1437         /* If we asked for a name then it must match */
1438         if (opts->name && strcmp(opts->name, root->name))
1439                 return 0;
1440
1441         /*
1442          * If we asked for subsystems (or explicitly for no
1443          * subsystems) then they must match
1444          */
1445         if ((opts->subsys_mask || opts->none)
1446             && (opts->subsys_mask != root->subsys_mask))
1447                 return 0;
1448
1449         return 1;
1450 }
1451
1452 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1453 {
1454         struct cgroupfs_root *root;
1455
1456         if (!opts->subsys_mask && !opts->none)
1457                 return NULL;
1458
1459         root = kzalloc(sizeof(*root), GFP_KERNEL);
1460         if (!root)
1461                 return ERR_PTR(-ENOMEM);
1462
1463         if (!init_root_id(root)) {
1464                 kfree(root);
1465                 return ERR_PTR(-ENOMEM);
1466         }
1467         init_cgroup_root(root);
1468
1469         root->subsys_mask = opts->subsys_mask;
1470         root->flags = opts->flags;
1471         if (opts->release_agent)
1472                 strcpy(root->release_agent_path, opts->release_agent);
1473         if (opts->name)
1474                 strcpy(root->name, opts->name);
1475         if (opts->clone_children)
1476                 set_bit(CGRP_CLONE_CHILDREN, &root->top_cgroup.flags);
1477         return root;
1478 }
1479
1480 static void cgroup_drop_root(struct cgroupfs_root *root)
1481 {
1482         if (!root)
1483                 return;
1484
1485         BUG_ON(!root->hierarchy_id);
1486         spin_lock(&hierarchy_id_lock);
1487         ida_remove(&hierarchy_ida, root->hierarchy_id);
1488         spin_unlock(&hierarchy_id_lock);
1489         kfree(root);
1490 }
1491
1492 static int cgroup_set_super(struct super_block *sb, void *data)
1493 {
1494         int ret;
1495         struct cgroup_sb_opts *opts = data;
1496
1497         /* If we don't have a new root, we can't set up a new sb */
1498         if (!opts->new_root)
1499                 return -EINVAL;
1500
1501         BUG_ON(!opts->subsys_mask && !opts->none);
1502
1503         ret = set_anon_super(sb, NULL);
1504         if (ret)
1505                 return ret;
1506
1507         sb->s_fs_info = opts->new_root;
1508         opts->new_root->sb = sb;
1509
1510         sb->s_blocksize = PAGE_CACHE_SIZE;
1511         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1512         sb->s_magic = CGROUP_SUPER_MAGIC;
1513         sb->s_op = &cgroup_ops;
1514
1515         return 0;
1516 }
1517
1518 static int cgroup_get_rootdir(struct super_block *sb)
1519 {
1520         static const struct dentry_operations cgroup_dops = {
1521                 .d_iput = cgroup_diput,
1522                 .d_delete = cgroup_delete,
1523         };
1524
1525         struct inode *inode =
1526                 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1527
1528         if (!inode)
1529                 return -ENOMEM;
1530
1531         inode->i_fop = &simple_dir_operations;
1532         inode->i_op = &cgroup_dir_inode_operations;
1533         /* directories start off with i_nlink == 2 (for "." entry) */
1534         inc_nlink(inode);
1535         sb->s_root = d_make_root(inode);
1536         if (!sb->s_root)
1537                 return -ENOMEM;
1538         /* for everything else we want ->d_op set */
1539         sb->s_d_op = &cgroup_dops;
1540         return 0;
1541 }
1542
1543 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1544                          int flags, const char *unused_dev_name,
1545                          void *data)
1546 {
1547         struct cgroup_sb_opts opts;
1548         struct cgroupfs_root *root;
1549         int ret = 0;
1550         struct super_block *sb;
1551         struct cgroupfs_root *new_root;
1552         struct inode *inode;
1553
1554         /* First find the desired set of subsystems */
1555         mutex_lock(&cgroup_mutex);
1556         ret = parse_cgroupfs_options(data, &opts);
1557         mutex_unlock(&cgroup_mutex);
1558         if (ret)
1559                 goto out_err;
1560
1561         /*
1562          * Allocate a new cgroup root. We may not need it if we're
1563          * reusing an existing hierarchy.
1564          */
1565         new_root = cgroup_root_from_opts(&opts);
1566         if (IS_ERR(new_root)) {
1567                 ret = PTR_ERR(new_root);
1568                 goto drop_modules;
1569         }
1570         opts.new_root = new_root;
1571
1572         /* Locate an existing or new sb for this hierarchy */
1573         sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1574         if (IS_ERR(sb)) {
1575                 ret = PTR_ERR(sb);
1576                 cgroup_drop_root(opts.new_root);
1577                 goto drop_modules;
1578         }
1579
1580         root = sb->s_fs_info;
1581         BUG_ON(!root);
1582         if (root == opts.new_root) {
1583                 /* We used the new root structure, so this is a new hierarchy */
1584                 struct list_head tmp_cg_links;
1585                 struct cgroup *root_cgrp = &root->top_cgroup;
1586                 struct cgroupfs_root *existing_root;
1587                 const struct cred *cred;
1588                 int i;
1589
1590                 BUG_ON(sb->s_root != NULL);
1591
1592                 ret = cgroup_get_rootdir(sb);
1593                 if (ret)
1594                         goto drop_new_super;
1595                 inode = sb->s_root->d_inode;
1596
1597                 mutex_lock(&inode->i_mutex);
1598                 mutex_lock(&cgroup_mutex);
1599                 mutex_lock(&cgroup_root_mutex);
1600
1601                 /* Check for name clashes with existing mounts */
1602                 ret = -EBUSY;
1603                 if (strlen(root->name))
1604                         for_each_active_root(existing_root)
1605                                 if (!strcmp(existing_root->name, root->name))
1606                                         goto unlock_drop;
1607
1608                 /*
1609                  * We're accessing css_set_count without locking
1610                  * css_set_lock here, but that's OK - it can only be
1611                  * increased by someone holding cgroup_lock, and
1612                  * that's us. The worst that can happen is that we
1613                  * have some link structures left over
1614                  */
1615                 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1616                 if (ret)
1617                         goto unlock_drop;
1618
1619                 ret = rebind_subsystems(root, root->subsys_mask);
1620                 if (ret == -EBUSY) {
1621                         free_cg_links(&tmp_cg_links);
1622                         goto unlock_drop;
1623                 }
1624                 /*
1625                  * There must be no failure case after here, since rebinding
1626                  * takes care of subsystems' refcounts, which are explicitly
1627                  * dropped in the failure exit path.
1628                  */
1629
1630                 /* EBUSY should be the only error here */
1631                 BUG_ON(ret);
1632
1633                 list_add(&root->root_list, &roots);
1634                 root_count++;
1635
1636                 sb->s_root->d_fsdata = root_cgrp;
1637                 root->top_cgroup.dentry = sb->s_root;
1638
1639                 /* Link the top cgroup in this hierarchy into all
1640                  * the css_set objects */
1641                 write_lock(&css_set_lock);
1642                 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1643                         struct hlist_head *hhead = &css_set_table[i];
1644                         struct hlist_node *node;
1645                         struct css_set *cg;
1646
1647                         hlist_for_each_entry(cg, node, hhead, hlist)
1648                                 link_css_set(&tmp_cg_links, cg, root_cgrp);
1649                 }
1650                 write_unlock(&css_set_lock);
1651
1652                 free_cg_links(&tmp_cg_links);
1653
1654                 BUG_ON(!list_empty(&root_cgrp->children));
1655                 BUG_ON(root->number_of_cgroups != 1);
1656
1657                 cred = override_creds(&init_cred);
1658                 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1659                 revert_creds(cred);
1660                 mutex_unlock(&cgroup_root_mutex);
1661                 mutex_unlock(&cgroup_mutex);
1662                 mutex_unlock(&inode->i_mutex);
1663         } else {
1664                 /*
1665                  * We re-used an existing hierarchy - the new root (if
1666                  * any) is not needed
1667                  */
1668                 cgroup_drop_root(opts.new_root);
1669                 /* no subsys rebinding, so refcounts don't change */
1670                 drop_parsed_module_refcounts(opts.subsys_mask);
1671         }
1672
1673         kfree(opts.release_agent);
1674         kfree(opts.name);
1675         return dget(sb->s_root);
1676
1677  unlock_drop:
1678         mutex_unlock(&cgroup_root_mutex);
1679         mutex_unlock(&cgroup_mutex);
1680         mutex_unlock(&inode->i_mutex);
1681  drop_new_super:
1682         deactivate_locked_super(sb);
1683  drop_modules:
1684         drop_parsed_module_refcounts(opts.subsys_mask);
1685  out_err:
1686         kfree(opts.release_agent);
1687         kfree(opts.name);
1688         return ERR_PTR(ret);
1689 }
1690
1691 static void cgroup_kill_sb(struct super_block *sb) {
1692         struct cgroupfs_root *root = sb->s_fs_info;
1693         struct cgroup *cgrp = &root->top_cgroup;
1694         int ret;
1695         struct cg_cgroup_link *link;
1696         struct cg_cgroup_link *saved_link;
1697
1698         BUG_ON(!root);
1699
1700         BUG_ON(root->number_of_cgroups != 1);
1701         BUG_ON(!list_empty(&cgrp->children));
1702
1703         mutex_lock(&cgroup_mutex);
1704         mutex_lock(&cgroup_root_mutex);
1705
1706         /* Rebind all subsystems back to the default hierarchy */
1707         ret = rebind_subsystems(root, 0);
1708         /* Shouldn't be able to fail ... */
1709         BUG_ON(ret);
1710
1711         /*
1712          * Release all the links from css_sets to this hierarchy's
1713          * root cgroup
1714          */
1715         write_lock(&css_set_lock);
1716
1717         list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1718                                  cgrp_link_list) {
1719                 list_del(&link->cg_link_list);
1720                 list_del(&link->cgrp_link_list);
1721                 kfree(link);
1722         }
1723         write_unlock(&css_set_lock);
1724
1725         if (!list_empty(&root->root_list)) {
1726                 list_del(&root->root_list);
1727                 root_count--;
1728         }
1729
1730         mutex_unlock(&cgroup_root_mutex);
1731         mutex_unlock(&cgroup_mutex);
1732
1733         simple_xattrs_free(&cgrp->xattrs);
1734
1735         kill_litter_super(sb);
1736         cgroup_drop_root(root);
1737 }
1738
1739 static struct file_system_type cgroup_fs_type = {
1740         .name = "cgroup",
1741         .mount = cgroup_mount,
1742         .kill_sb = cgroup_kill_sb,
1743 };
1744
1745 static struct kobject *cgroup_kobj;
1746
1747 /**
1748  * cgroup_path - generate the path of a cgroup
1749  * @cgrp: the cgroup in question
1750  * @buf: the buffer to write the path into
1751  * @buflen: the length of the buffer
1752  *
1753  * Called with cgroup_mutex held or else with an RCU-protected cgroup
1754  * reference.  Writes path of cgroup into buf.  Returns 0 on success,
1755  * -errno on error.
1756  */
1757 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1758 {
1759         char *start;
1760         struct dentry *dentry = rcu_dereference_check(cgrp->dentry,
1761                                                       cgroup_lock_is_held());
1762
1763         if (!dentry || cgrp == dummytop) {
1764                 /*
1765                  * Inactive subsystems have no dentry for their root
1766                  * cgroup
1767                  */
1768                 strcpy(buf, "/");
1769                 return 0;
1770         }
1771
1772         start = buf + buflen - 1;
1773
1774         *start = '\0';
1775         for (;;) {
1776                 int len = dentry->d_name.len;
1777
1778                 if ((start -= len) < buf)
1779                         return -ENAMETOOLONG;
1780                 memcpy(start, dentry->d_name.name, len);
1781                 cgrp = cgrp->parent;
1782                 if (!cgrp)
1783                         break;
1784
1785                 dentry = rcu_dereference_check(cgrp->dentry,
1786                                                cgroup_lock_is_held());
1787                 if (!cgrp->parent)
1788                         continue;
1789                 if (--start < buf)
1790                         return -ENAMETOOLONG;
1791                 *start = '/';
1792         }
1793         memmove(buf, start, buf + buflen - start);
1794         return 0;
1795 }
1796 EXPORT_SYMBOL_GPL(cgroup_path);
1797
1798 /*
1799  * Control Group taskset
1800  */
1801 struct task_and_cgroup {
1802         struct task_struct      *task;
1803         struct cgroup           *cgrp;
1804         struct css_set          *cg;
1805 };
1806
1807 struct cgroup_taskset {
1808         struct task_and_cgroup  single;
1809         struct flex_array       *tc_array;
1810         int                     tc_array_len;
1811         int                     idx;
1812         struct cgroup           *cur_cgrp;
1813 };
1814
1815 /**
1816  * cgroup_taskset_first - reset taskset and return the first task
1817  * @tset: taskset of interest
1818  *
1819  * @tset iteration is initialized and the first task is returned.
1820  */
1821 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1822 {
1823         if (tset->tc_array) {
1824                 tset->idx = 0;
1825                 return cgroup_taskset_next(tset);
1826         } else {
1827                 tset->cur_cgrp = tset->single.cgrp;
1828                 return tset->single.task;
1829         }
1830 }
1831 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1832
1833 /**
1834  * cgroup_taskset_next - iterate to the next task in taskset
1835  * @tset: taskset of interest
1836  *
1837  * Return the next task in @tset.  Iteration must have been initialized
1838  * with cgroup_taskset_first().
1839  */
1840 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1841 {
1842         struct task_and_cgroup *tc;
1843
1844         if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1845                 return NULL;
1846
1847         tc = flex_array_get(tset->tc_array, tset->idx++);
1848         tset->cur_cgrp = tc->cgrp;
1849         return tc->task;
1850 }
1851 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1852
1853 /**
1854  * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1855  * @tset: taskset of interest
1856  *
1857  * Return the cgroup for the current (last returned) task of @tset.  This
1858  * function must be preceded by either cgroup_taskset_first() or
1859  * cgroup_taskset_next().
1860  */
1861 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1862 {
1863         return tset->cur_cgrp;
1864 }
1865 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1866
1867 /**
1868  * cgroup_taskset_size - return the number of tasks in taskset
1869  * @tset: taskset of interest
1870  */
1871 int cgroup_taskset_size(struct cgroup_taskset *tset)
1872 {
1873         return tset->tc_array ? tset->tc_array_len : 1;
1874 }
1875 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1876
1877
1878 /*
1879  * cgroup_task_migrate - move a task from one cgroup to another.
1880  *
1881  * 'guarantee' is set if the caller promises that a new css_set for the task
1882  * will already exist. If not set, this function might sleep, and can fail with
1883  * -ENOMEM. Must be called with cgroup_mutex and threadgroup locked.
1884  */
1885 static void cgroup_task_migrate(struct cgroup *cgrp, struct cgroup *oldcgrp,
1886                                 struct task_struct *tsk, struct css_set *newcg)
1887 {
1888         struct css_set *oldcg;
1889
1890         /*
1891          * We are synchronized through threadgroup_lock() against PF_EXITING
1892          * setting such that we can't race against cgroup_exit() changing the
1893          * css_set to init_css_set and dropping the old one.
1894          */
1895         WARN_ON_ONCE(tsk->flags & PF_EXITING);
1896         oldcg = tsk->cgroups;
1897
1898         task_lock(tsk);
1899         rcu_assign_pointer(tsk->cgroups, newcg);
1900         task_unlock(tsk);
1901
1902         /* Update the css_set linked lists if we're using them */
1903         write_lock(&css_set_lock);
1904         if (!list_empty(&tsk->cg_list))
1905                 list_move(&tsk->cg_list, &newcg->tasks);
1906         write_unlock(&css_set_lock);
1907
1908         /*
1909          * We just gained a reference on oldcg by taking it from the task. As
1910          * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1911          * it here; it will be freed under RCU.
1912          */
1913         set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1914         put_css_set(oldcg);
1915 }
1916
1917 /**
1918  * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1919  * @cgrp: the cgroup the task is attaching to
1920  * @tsk: the task to be attached
1921  *
1922  * Call with cgroup_mutex and threadgroup locked. May take task_lock of
1923  * @tsk during call.
1924  */
1925 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1926 {
1927         int retval = 0;
1928         struct cgroup_subsys *ss, *failed_ss = NULL;
1929         struct cgroup *oldcgrp;
1930         struct cgroupfs_root *root = cgrp->root;
1931         struct cgroup_taskset tset = { };
1932         struct css_set *newcg;
1933
1934         /* @tsk either already exited or can't exit until the end */
1935         if (tsk->flags & PF_EXITING)
1936                 return -ESRCH;
1937
1938         /* Nothing to do if the task is already in that cgroup */
1939         oldcgrp = task_cgroup_from_root(tsk, root);
1940         if (cgrp == oldcgrp)
1941                 return 0;
1942
1943         tset.single.task = tsk;
1944         tset.single.cgrp = oldcgrp;
1945
1946         for_each_subsys(root, ss) {
1947                 if (ss->can_attach) {
1948                         retval = ss->can_attach(cgrp, &tset);
1949                         if (retval) {
1950                                 /*
1951                                  * Remember on which subsystem the can_attach()
1952                                  * failed, so that we only call cancel_attach()
1953                                  * against the subsystems whose can_attach()
1954                                  * succeeded. (See below)
1955                                  */
1956                                 failed_ss = ss;
1957                                 goto out;
1958                         }
1959                 }
1960         }
1961
1962         newcg = find_css_set(tsk->cgroups, cgrp);
1963         if (!newcg) {
1964                 retval = -ENOMEM;
1965                 goto out;
1966         }
1967
1968         cgroup_task_migrate(cgrp, oldcgrp, tsk, newcg);
1969
1970         for_each_subsys(root, ss) {
1971                 if (ss->attach)
1972                         ss->attach(cgrp, &tset);
1973         }
1974
1975         synchronize_rcu();
1976 out:
1977         if (retval) {
1978                 for_each_subsys(root, ss) {
1979                         if (ss == failed_ss)
1980                                 /*
1981                                  * This subsystem was the one that failed the
1982                                  * can_attach() check earlier, so we don't need
1983                                  * to call cancel_attach() against it or any
1984                                  * remaining subsystems.
1985                                  */
1986                                 break;
1987                         if (ss->cancel_attach)
1988                                 ss->cancel_attach(cgrp, &tset);
1989                 }
1990         }
1991         return retval;
1992 }
1993
1994 /**
1995  * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
1996  * @from: attach to all cgroups of a given task
1997  * @tsk: the task to be attached
1998  */
1999 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2000 {
2001         struct cgroupfs_root *root;
2002         int retval = 0;
2003
2004         cgroup_lock();
2005         for_each_active_root(root) {
2006                 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2007
2008                 retval = cgroup_attach_task(from_cg, tsk);
2009                 if (retval)
2010                         break;
2011         }
2012         cgroup_unlock();
2013
2014         return retval;
2015 }
2016 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2017
2018 /**
2019  * cgroup_attach_proc - attach all threads in a threadgroup to a cgroup
2020  * @cgrp: the cgroup to attach to
2021  * @leader: the threadgroup leader task_struct of the group to be attached
2022  *
2023  * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
2024  * task_lock of each thread in leader's threadgroup individually in turn.
2025  */
2026 static int cgroup_attach_proc(struct cgroup *cgrp, struct task_struct *leader)
2027 {
2028         int retval, i, group_size;
2029         struct cgroup_subsys *ss, *failed_ss = NULL;
2030         /* guaranteed to be initialized later, but the compiler needs this */
2031         struct cgroupfs_root *root = cgrp->root;
2032         /* threadgroup list cursor and array */
2033         struct task_struct *tsk;
2034         struct task_and_cgroup *tc;
2035         struct flex_array *group;
2036         struct cgroup_taskset tset = { };
2037
2038         /*
2039          * step 0: in order to do expensive, possibly blocking operations for
2040          * every thread, we cannot iterate the thread group list, since it needs
2041          * rcu or tasklist locked. instead, build an array of all threads in the
2042          * group - group_rwsem prevents new threads from appearing, and if
2043          * threads exit, this will just be an over-estimate.
2044          */
2045         group_size = get_nr_threads(leader);
2046         /* flex_array supports very large thread-groups better than kmalloc. */
2047         group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2048         if (!group)
2049                 return -ENOMEM;
2050         /* pre-allocate to guarantee space while iterating in rcu read-side. */
2051         retval = flex_array_prealloc(group, 0, group_size - 1, GFP_KERNEL);
2052         if (retval)
2053                 goto out_free_group_list;
2054
2055         tsk = leader;
2056         i = 0;
2057         /*
2058          * Prevent freeing of tasks while we take a snapshot. Tasks that are
2059          * already PF_EXITING could be freed from underneath us unless we
2060          * take an rcu_read_lock.
2061          */
2062         rcu_read_lock();
2063         do {
2064                 struct task_and_cgroup ent;
2065
2066                 /* @tsk either already exited or can't exit until the end */
2067                 if (tsk->flags & PF_EXITING)
2068                         continue;
2069
2070                 /* as per above, nr_threads may decrease, but not increase. */
2071                 BUG_ON(i >= group_size);
2072                 ent.task = tsk;
2073                 ent.cgrp = task_cgroup_from_root(tsk, root);
2074                 /* nothing to do if this task is already in the cgroup */
2075                 if (ent.cgrp == cgrp)
2076                         continue;
2077                 /*
2078                  * saying GFP_ATOMIC has no effect here because we did prealloc
2079                  * earlier, but it's good form to communicate our expectations.
2080                  */
2081                 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2082                 BUG_ON(retval != 0);
2083                 i++;
2084         } while_each_thread(leader, tsk);
2085         rcu_read_unlock();
2086         /* remember the number of threads in the array for later. */
2087         group_size = i;
2088         tset.tc_array = group;
2089         tset.tc_array_len = group_size;
2090
2091         /* methods shouldn't be called if no task is actually migrating */
2092         retval = 0;
2093         if (!group_size)
2094                 goto out_free_group_list;
2095
2096         /*
2097          * step 1: check that we can legitimately attach to the cgroup.
2098          */
2099         for_each_subsys(root, ss) {
2100                 if (ss->can_attach) {
2101                         retval = ss->can_attach(cgrp, &tset);
2102                         if (retval) {
2103                                 failed_ss = ss;
2104                                 goto out_cancel_attach;
2105                         }
2106                 }
2107         }
2108
2109         /*
2110          * step 2: make sure css_sets exist for all threads to be migrated.
2111          * we use find_css_set, which allocates a new one if necessary.
2112          */
2113         for (i = 0; i < group_size; i++) {
2114                 tc = flex_array_get(group, i);
2115                 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2116                 if (!tc->cg) {
2117                         retval = -ENOMEM;
2118                         goto out_put_css_set_refs;
2119                 }
2120         }
2121
2122         /*
2123          * step 3: now that we're guaranteed success wrt the css_sets,
2124          * proceed to move all tasks to the new cgroup.  There are no
2125          * failure cases after here, so this is the commit point.
2126          */
2127         for (i = 0; i < group_size; i++) {
2128                 tc = flex_array_get(group, i);
2129                 cgroup_task_migrate(cgrp, tc->cgrp, tc->task, tc->cg);
2130         }
2131         /* nothing is sensitive to fork() after this point. */
2132
2133         /*
2134          * step 4: do subsystem attach callbacks.
2135          */
2136         for_each_subsys(root, ss) {
2137                 if (ss->attach)
2138                         ss->attach(cgrp, &tset);
2139         }
2140
2141         /*
2142          * step 5: success! and cleanup
2143          */
2144         synchronize_rcu();
2145         retval = 0;
2146 out_put_css_set_refs:
2147         if (retval) {
2148                 for (i = 0; i < group_size; i++) {
2149                         tc = flex_array_get(group, i);
2150                         if (!tc->cg)
2151                                 break;
2152                         put_css_set(tc->cg);
2153                 }
2154         }
2155 out_cancel_attach:
2156         if (retval) {
2157                 for_each_subsys(root, ss) {
2158                         if (ss == failed_ss)
2159                                 break;
2160                         if (ss->cancel_attach)
2161                                 ss->cancel_attach(cgrp, &tset);
2162                 }
2163         }
2164 out_free_group_list:
2165         flex_array_free(group);
2166         return retval;
2167 }
2168
2169 /*
2170  * Find the task_struct of the task to attach by vpid and pass it along to the
2171  * function to attach either it or all tasks in its threadgroup. Will lock
2172  * cgroup_mutex and threadgroup; may take task_lock of task.
2173  */
2174 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2175 {
2176         struct task_struct *tsk;
2177         const struct cred *cred = current_cred(), *tcred;
2178         int ret;
2179
2180         if (!cgroup_lock_live_group(cgrp))
2181                 return -ENODEV;
2182
2183 retry_find_task:
2184         rcu_read_lock();
2185         if (pid) {
2186                 tsk = find_task_by_vpid(pid);
2187                 if (!tsk) {
2188                         rcu_read_unlock();
2189                         ret= -ESRCH;
2190                         goto out_unlock_cgroup;
2191                 }
2192                 /*
2193                  * even if we're attaching all tasks in the thread group, we
2194                  * only need to check permissions on one of them.
2195                  */
2196                 tcred = __task_cred(tsk);
2197                 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2198                     !uid_eq(cred->euid, tcred->uid) &&
2199                     !uid_eq(cred->euid, tcred->suid)) {
2200                         rcu_read_unlock();
2201                         ret = -EACCES;
2202                         goto out_unlock_cgroup;
2203                 }
2204         } else
2205                 tsk = current;
2206
2207         if (threadgroup)
2208                 tsk = tsk->group_leader;
2209
2210         /*
2211          * Workqueue threads may acquire PF_THREAD_BOUND and become
2212          * trapped in a cpuset, or RT worker may be born in a cgroup
2213          * with no rt_runtime allocated.  Just say no.
2214          */
2215         if (tsk == kthreadd_task || (tsk->flags & PF_THREAD_BOUND)) {
2216                 ret = -EINVAL;
2217                 rcu_read_unlock();
2218                 goto out_unlock_cgroup;
2219         }
2220
2221         get_task_struct(tsk);
2222         rcu_read_unlock();
2223
2224         threadgroup_lock(tsk);
2225         if (threadgroup) {
2226                 if (!thread_group_leader(tsk)) {
2227                         /*
2228                          * a race with de_thread from another thread's exec()
2229                          * may strip us of our leadership, if this happens,
2230                          * there is no choice but to throw this task away and
2231                          * try again; this is
2232                          * "double-double-toil-and-trouble-check locking".
2233                          */
2234                         threadgroup_unlock(tsk);
2235                         put_task_struct(tsk);
2236                         goto retry_find_task;
2237                 }
2238                 ret = cgroup_attach_proc(cgrp, tsk);
2239         } else
2240                 ret = cgroup_attach_task(cgrp, tsk);
2241         threadgroup_unlock(tsk);
2242
2243         put_task_struct(tsk);
2244 out_unlock_cgroup:
2245         cgroup_unlock();
2246         return ret;
2247 }
2248
2249 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2250 {
2251         return attach_task_by_pid(cgrp, pid, false);
2252 }
2253
2254 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2255 {
2256         return attach_task_by_pid(cgrp, tgid, true);
2257 }
2258
2259 /**
2260  * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
2261  * @cgrp: the cgroup to be checked for liveness
2262  *
2263  * On success, returns true; the lock should be later released with
2264  * cgroup_unlock(). On failure returns false with no lock held.
2265  */
2266 bool cgroup_lock_live_group(struct cgroup *cgrp)
2267 {
2268         mutex_lock(&cgroup_mutex);
2269         if (cgroup_is_removed(cgrp)) {
2270                 mutex_unlock(&cgroup_mutex);
2271                 return false;
2272         }
2273         return true;
2274 }
2275 EXPORT_SYMBOL_GPL(cgroup_lock_live_group);
2276
2277 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2278                                       const char *buffer)
2279 {
2280         BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2281         if (strlen(buffer) >= PATH_MAX)
2282                 return -EINVAL;
2283         if (!cgroup_lock_live_group(cgrp))
2284                 return -ENODEV;
2285         mutex_lock(&cgroup_root_mutex);
2286         strcpy(cgrp->root->release_agent_path, buffer);
2287         mutex_unlock(&cgroup_root_mutex);
2288         cgroup_unlock();
2289         return 0;
2290 }
2291
2292 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2293                                      struct seq_file *seq)
2294 {
2295         if (!cgroup_lock_live_group(cgrp))
2296                 return -ENODEV;
2297         seq_puts(seq, cgrp->root->release_agent_path);
2298         seq_putc(seq, '\n');
2299         cgroup_unlock();
2300         return 0;
2301 }
2302
2303 /* A buffer size big enough for numbers or short strings */
2304 #define CGROUP_LOCAL_BUFFER_SIZE 64
2305
2306 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2307                                 struct file *file,
2308                                 const char __user *userbuf,
2309                                 size_t nbytes, loff_t *unused_ppos)
2310 {
2311         char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2312         int retval = 0;
2313         char *end;
2314
2315         if (!nbytes)
2316                 return -EINVAL;
2317         if (nbytes >= sizeof(buffer))
2318                 return -E2BIG;
2319         if (copy_from_user(buffer, userbuf, nbytes))
2320                 return -EFAULT;
2321
2322         buffer[nbytes] = 0;     /* nul-terminate */
2323         if (cft->write_u64) {
2324                 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2325                 if (*end)
2326                         return -EINVAL;
2327                 retval = cft->write_u64(cgrp, cft, val);
2328         } else {
2329                 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2330                 if (*end)
2331                         return -EINVAL;
2332                 retval = cft->write_s64(cgrp, cft, val);
2333         }
2334         if (!retval)
2335                 retval = nbytes;
2336         return retval;
2337 }
2338
2339 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2340                                    struct file *file,
2341                                    const char __user *userbuf,
2342                                    size_t nbytes, loff_t *unused_ppos)
2343 {
2344         char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2345         int retval = 0;
2346         size_t max_bytes = cft->max_write_len;
2347         char *buffer = local_buffer;
2348
2349         if (!max_bytes)
2350                 max_bytes = sizeof(local_buffer) - 1;
2351         if (nbytes >= max_bytes)
2352                 return -E2BIG;
2353         /* Allocate a dynamic buffer if we need one */
2354         if (nbytes >= sizeof(local_buffer)) {
2355                 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2356                 if (buffer == NULL)
2357                         return -ENOMEM;
2358         }
2359         if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2360                 retval = -EFAULT;
2361                 goto out;
2362         }
2363
2364         buffer[nbytes] = 0;     /* nul-terminate */
2365         retval = cft->write_string(cgrp, cft, strstrip(buffer));
2366         if (!retval)
2367                 retval = nbytes;
2368 out:
2369         if (buffer != local_buffer)
2370                 kfree(buffer);
2371         return retval;
2372 }
2373
2374 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2375                                                 size_t nbytes, loff_t *ppos)
2376 {
2377         struct cftype *cft = __d_cft(file->f_dentry);
2378         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2379
2380         if (cgroup_is_removed(cgrp))
2381                 return -ENODEV;
2382         if (cft->write)
2383                 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2384         if (cft->write_u64 || cft->write_s64)
2385                 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2386         if (cft->write_string)
2387                 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2388         if (cft->trigger) {
2389                 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2390                 return ret ? ret : nbytes;
2391         }
2392         return -EINVAL;
2393 }
2394
2395 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2396                                struct file *file,
2397                                char __user *buf, size_t nbytes,
2398                                loff_t *ppos)
2399 {
2400         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2401         u64 val = cft->read_u64(cgrp, cft);
2402         int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2403
2404         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2405 }
2406
2407 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2408                                struct file *file,
2409                                char __user *buf, size_t nbytes,
2410                                loff_t *ppos)
2411 {
2412         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2413         s64 val = cft->read_s64(cgrp, cft);
2414         int len = sprintf(tmp, "%lld\n", (long long) val);
2415
2416         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2417 }
2418
2419 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2420                                    size_t nbytes, loff_t *ppos)
2421 {
2422         struct cftype *cft = __d_cft(file->f_dentry);
2423         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2424
2425         if (cgroup_is_removed(cgrp))
2426                 return -ENODEV;
2427
2428         if (cft->read)
2429                 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2430         if (cft->read_u64)
2431                 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2432         if (cft->read_s64)
2433                 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2434         return -EINVAL;
2435 }
2436
2437 /*
2438  * seqfile ops/methods for returning structured data. Currently just
2439  * supports string->u64 maps, but can be extended in future.
2440  */
2441
2442 struct cgroup_seqfile_state {
2443         struct cftype *cft;
2444         struct cgroup *cgroup;
2445 };
2446
2447 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2448 {
2449         struct seq_file *sf = cb->state;
2450         return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2451 }
2452
2453 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2454 {
2455         struct cgroup_seqfile_state *state = m->private;
2456         struct cftype *cft = state->cft;
2457         if (cft->read_map) {
2458                 struct cgroup_map_cb cb = {
2459                         .fill = cgroup_map_add,
2460                         .state = m,
2461                 };
2462                 return cft->read_map(state->cgroup, cft, &cb);
2463         }
2464         return cft->read_seq_string(state->cgroup, cft, m);
2465 }
2466
2467 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2468 {
2469         struct seq_file *seq = file->private_data;
2470         kfree(seq->private);
2471         return single_release(inode, file);
2472 }
2473
2474 static const struct file_operations cgroup_seqfile_operations = {
2475         .read = seq_read,
2476         .write = cgroup_file_write,
2477         .llseek = seq_lseek,
2478         .release = cgroup_seqfile_release,
2479 };
2480
2481 static int cgroup_file_open(struct inode *inode, struct file *file)
2482 {
2483         int err;
2484         struct cftype *cft;
2485
2486         err = generic_file_open(inode, file);
2487         if (err)
2488                 return err;
2489         cft = __d_cft(file->f_dentry);
2490
2491         if (cft->read_map || cft->read_seq_string) {
2492                 struct cgroup_seqfile_state *state =
2493                         kzalloc(sizeof(*state), GFP_USER);
2494                 if (!state)
2495                         return -ENOMEM;
2496                 state->cft = cft;
2497                 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2498                 file->f_op = &cgroup_seqfile_operations;
2499                 err = single_open(file, cgroup_seqfile_show, state);
2500                 if (err < 0)
2501                         kfree(state);
2502         } else if (cft->open)
2503                 err = cft->open(inode, file);
2504         else
2505                 err = 0;
2506
2507         return err;
2508 }
2509
2510 static int cgroup_file_release(struct inode *inode, struct file *file)
2511 {
2512         struct cftype *cft = __d_cft(file->f_dentry);
2513         if (cft->release)
2514                 return cft->release(inode, file);
2515         return 0;
2516 }
2517
2518 /*
2519  * cgroup_rename - Only allow simple rename of directories in place.
2520  */
2521 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2522                             struct inode *new_dir, struct dentry *new_dentry)
2523 {
2524         if (!S_ISDIR(old_dentry->d_inode->i_mode))
2525                 return -ENOTDIR;
2526         if (new_dentry->d_inode)
2527                 return -EEXIST;
2528         if (old_dir != new_dir)
2529                 return -EIO;
2530         return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2531 }
2532
2533 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2534 {
2535         if (S_ISDIR(dentry->d_inode->i_mode))
2536                 return &__d_cgrp(dentry)->xattrs;
2537         else
2538                 return &__d_cft(dentry)->xattrs;
2539 }
2540
2541 static inline int xattr_enabled(struct dentry *dentry)
2542 {
2543         struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2544         return test_bit(ROOT_XATTR, &root->flags);
2545 }
2546
2547 static bool is_valid_xattr(const char *name)
2548 {
2549         if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2550             !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2551                 return true;
2552         return false;
2553 }
2554
2555 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2556                            const void *val, size_t size, int flags)
2557 {
2558         if (!xattr_enabled(dentry))
2559                 return -EOPNOTSUPP;
2560         if (!is_valid_xattr(name))
2561                 return -EINVAL;
2562         return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2563 }
2564
2565 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2566 {
2567         if (!xattr_enabled(dentry))
2568                 return -EOPNOTSUPP;
2569         if (!is_valid_xattr(name))
2570                 return -EINVAL;
2571         return simple_xattr_remove(__d_xattrs(dentry), name);
2572 }
2573
2574 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2575                                void *buf, size_t size)
2576 {
2577         if (!xattr_enabled(dentry))
2578                 return -EOPNOTSUPP;
2579         if (!is_valid_xattr(name))
2580                 return -EINVAL;
2581         return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2582 }
2583
2584 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2585 {
2586         if (!xattr_enabled(dentry))
2587                 return -EOPNOTSUPP;
2588         return simple_xattr_list(__d_xattrs(dentry), buf, size);
2589 }
2590
2591 static const struct file_operations cgroup_file_operations = {
2592         .read = cgroup_file_read,
2593         .write = cgroup_file_write,
2594         .llseek = generic_file_llseek,
2595         .open = cgroup_file_open,
2596         .release = cgroup_file_release,
2597 };
2598
2599 static const struct inode_operations cgroup_file_inode_operations = {
2600         .setxattr = cgroup_setxattr,
2601         .getxattr = cgroup_getxattr,
2602         .listxattr = cgroup_listxattr,
2603         .removexattr = cgroup_removexattr,
2604 };
2605
2606 static const struct inode_operations cgroup_dir_inode_operations = {
2607         .lookup = cgroup_lookup,
2608         .mkdir = cgroup_mkdir,
2609         .rmdir = cgroup_rmdir,
2610         .rename = cgroup_rename,
2611         .setxattr = cgroup_setxattr,
2612         .getxattr = cgroup_getxattr,
2613         .listxattr = cgroup_listxattr,
2614         .removexattr = cgroup_removexattr,
2615 };
2616
2617 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2618 {
2619         if (dentry->d_name.len > NAME_MAX)
2620                 return ERR_PTR(-ENAMETOOLONG);
2621         d_add(dentry, NULL);
2622         return NULL;
2623 }
2624
2625 /*
2626  * Check if a file is a control file
2627  */
2628 static inline struct cftype *__file_cft(struct file *file)
2629 {
2630         if (file->f_dentry->d_inode->i_fop != &cgroup_file_operations)
2631                 return ERR_PTR(-EINVAL);
2632         return __d_cft(file->f_dentry);
2633 }
2634
2635 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2636                                 struct super_block *sb)
2637 {
2638         struct inode *inode;
2639
2640         if (!dentry)
2641                 return -ENOENT;
2642         if (dentry->d_inode)
2643                 return -EEXIST;
2644
2645         inode = cgroup_new_inode(mode, sb);
2646         if (!inode)
2647                 return -ENOMEM;
2648
2649         if (S_ISDIR(mode)) {
2650                 inode->i_op = &cgroup_dir_inode_operations;
2651                 inode->i_fop = &simple_dir_operations;
2652
2653                 /* start off with i_nlink == 2 (for "." entry) */
2654                 inc_nlink(inode);
2655
2656                 /* start with the directory inode held, so that we can
2657                  * populate it without racing with another mkdir */
2658                 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
2659         } else if (S_ISREG(mode)) {
2660                 inode->i_size = 0;
2661                 inode->i_fop = &cgroup_file_operations;
2662                 inode->i_op = &cgroup_file_inode_operations;
2663         }
2664         d_instantiate(dentry, inode);
2665         dget(dentry);   /* Extra count - pin the dentry in core */
2666         return 0;
2667 }
2668
2669 /*
2670  * cgroup_create_dir - create a directory for an object.
2671  * @cgrp: the cgroup we create the directory for. It must have a valid
2672  *        ->parent field. And we are going to fill its ->dentry field.
2673  * @dentry: dentry of the new cgroup
2674  * @mode: mode to set on new directory.
2675  */
2676 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
2677                                 umode_t mode)
2678 {
2679         struct dentry *parent;
2680         int error = 0;
2681
2682         parent = cgrp->parent->dentry;
2683         error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
2684         if (!error) {
2685                 dentry->d_fsdata = cgrp;
2686                 inc_nlink(parent->d_inode);
2687                 rcu_assign_pointer(cgrp->dentry, dentry);
2688         }
2689
2690         return error;
2691 }
2692
2693 /**
2694  * cgroup_file_mode - deduce file mode of a control file
2695  * @cft: the control file in question
2696  *
2697  * returns cft->mode if ->mode is not 0
2698  * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2699  * returns S_IRUGO if it has only a read handler
2700  * returns S_IWUSR if it has only a write hander
2701  */
2702 static umode_t cgroup_file_mode(const struct cftype *cft)
2703 {
2704         umode_t mode = 0;
2705
2706         if (cft->mode)
2707                 return cft->mode;
2708
2709         if (cft->read || cft->read_u64 || cft->read_s64 ||
2710             cft->read_map || cft->read_seq_string)
2711                 mode |= S_IRUGO;
2712
2713         if (cft->write || cft->write_u64 || cft->write_s64 ||
2714             cft->write_string || cft->trigger)
2715                 mode |= S_IWUSR;
2716
2717         return mode;
2718 }
2719
2720 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2721                            struct cftype *cft)
2722 {
2723         struct dentry *dir = cgrp->dentry;
2724         struct cgroup *parent = __d_cgrp(dir);
2725         struct dentry *dentry;
2726         struct cfent *cfe;
2727         int error;
2728         umode_t mode;
2729         char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2730
2731         simple_xattrs_init(&cft->xattrs);
2732
2733         /* does @cft->flags tell us to skip creation on @cgrp? */
2734         if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2735                 return 0;
2736         if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2737                 return 0;
2738
2739         if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2740                 strcpy(name, subsys->name);
2741                 strcat(name, ".");
2742         }
2743         strcat(name, cft->name);
2744
2745         BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2746
2747         cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2748         if (!cfe)
2749                 return -ENOMEM;
2750
2751         dentry = lookup_one_len(name, dir, strlen(name));
2752         if (IS_ERR(dentry)) {
2753                 error = PTR_ERR(dentry);
2754                 goto out;
2755         }
2756
2757         mode = cgroup_file_mode(cft);
2758         error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2759         if (!error) {
2760                 cfe->type = (void *)cft;
2761                 cfe->dentry = dentry;
2762                 dentry->d_fsdata = cfe;
2763                 list_add_tail(&cfe->node, &parent->files);
2764                 cfe = NULL;
2765         }
2766         dput(dentry);
2767 out:
2768         kfree(cfe);
2769         return error;
2770 }
2771
2772 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2773                               struct cftype cfts[], bool is_add)
2774 {
2775         struct cftype *cft;
2776         int err, ret = 0;
2777
2778         for (cft = cfts; cft->name[0] != '\0'; cft++) {
2779                 if (is_add)
2780                         err = cgroup_add_file(cgrp, subsys, cft);
2781                 else
2782                         err = cgroup_rm_file(cgrp, cft);
2783                 if (err) {
2784                         pr_warning("cgroup_addrm_files: failed to %s %s, err=%d\n",
2785                                    is_add ? "add" : "remove", cft->name, err);
2786                         ret = err;
2787                 }
2788         }
2789         return ret;
2790 }
2791
2792 static DEFINE_MUTEX(cgroup_cft_mutex);
2793
2794 static void cgroup_cfts_prepare(void)
2795         __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2796 {
2797         /*
2798          * Thanks to the entanglement with vfs inode locking, we can't walk
2799          * the existing cgroups under cgroup_mutex and create files.
2800          * Instead, we increment reference on all cgroups and build list of
2801          * them using @cgrp->cft_q_node.  Grab cgroup_cft_mutex to ensure
2802          * exclusive access to the field.
2803          */
2804         mutex_lock(&cgroup_cft_mutex);
2805         mutex_lock(&cgroup_mutex);
2806 }
2807
2808 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2809                                struct cftype *cfts, bool is_add)
2810         __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2811 {
2812         LIST_HEAD(pending);
2813         struct cgroup *cgrp, *n;
2814
2815         /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2816         if (cfts && ss->root != &rootnode) {
2817                 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2818                         dget(cgrp->dentry);
2819                         list_add_tail(&cgrp->cft_q_node, &pending);
2820                 }
2821         }
2822
2823         mutex_unlock(&cgroup_mutex);
2824
2825         /*
2826          * All new cgroups will see @cfts update on @ss->cftsets.  Add/rm
2827          * files for all cgroups which were created before.
2828          */
2829         list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2830                 struct inode *inode = cgrp->dentry->d_inode;
2831
2832                 mutex_lock(&inode->i_mutex);
2833                 mutex_lock(&cgroup_mutex);
2834                 if (!cgroup_is_removed(cgrp))
2835                         cgroup_addrm_files(cgrp, ss, cfts, is_add);
2836                 mutex_unlock(&cgroup_mutex);
2837                 mutex_unlock(&inode->i_mutex);
2838
2839                 list_del_init(&cgrp->cft_q_node);
2840                 dput(cgrp->dentry);
2841         }
2842
2843         mutex_unlock(&cgroup_cft_mutex);
2844 }
2845
2846 /**
2847  * cgroup_add_cftypes - add an array of cftypes to a subsystem
2848  * @ss: target cgroup subsystem
2849  * @cfts: zero-length name terminated array of cftypes
2850  *
2851  * Register @cfts to @ss.  Files described by @cfts are created for all
2852  * existing cgroups to which @ss is attached and all future cgroups will
2853  * have them too.  This function can be called anytime whether @ss is
2854  * attached or not.
2855  *
2856  * Returns 0 on successful registration, -errno on failure.  Note that this
2857  * function currently returns 0 as long as @cfts registration is successful
2858  * even if some file creation attempts on existing cgroups fail.
2859  */
2860 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2861 {
2862         struct cftype_set *set;
2863
2864         set = kzalloc(sizeof(*set), GFP_KERNEL);
2865         if (!set)
2866                 return -ENOMEM;
2867
2868         cgroup_cfts_prepare();
2869         set->cfts = cfts;
2870         list_add_tail(&set->node, &ss->cftsets);
2871         cgroup_cfts_commit(ss, cfts, true);
2872
2873         return 0;
2874 }
2875 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2876
2877 /**
2878  * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2879  * @ss: target cgroup subsystem
2880  * @cfts: zero-length name terminated array of cftypes
2881  *
2882  * Unregister @cfts from @ss.  Files described by @cfts are removed from
2883  * all existing cgroups to which @ss is attached and all future cgroups
2884  * won't have them either.  This function can be called anytime whether @ss
2885  * is attached or not.
2886  *
2887  * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2888  * registered with @ss.
2889  */
2890 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2891 {
2892         struct cftype_set *set;
2893
2894         cgroup_cfts_prepare();
2895
2896         list_for_each_entry(set, &ss->cftsets, node) {
2897                 if (set->cfts == cfts) {
2898                         list_del_init(&set->node);
2899                         cgroup_cfts_commit(ss, cfts, false);
2900                         return 0;
2901                 }
2902         }
2903
2904         cgroup_cfts_commit(ss, NULL, false);
2905         return -ENOENT;
2906 }
2907
2908 /**
2909  * cgroup_task_count - count the number of tasks in a cgroup.
2910  * @cgrp: the cgroup in question
2911  *
2912  * Return the number of tasks in the cgroup.
2913  */
2914 int cgroup_task_count(const struct cgroup *cgrp)
2915 {
2916         int count = 0;
2917         struct cg_cgroup_link *link;
2918
2919         read_lock(&css_set_lock);
2920         list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2921                 count += atomic_read(&link->cg->refcount);
2922         }
2923         read_unlock(&css_set_lock);
2924         return count;
2925 }
2926
2927 /*
2928  * Advance a list_head iterator.  The iterator should be positioned at
2929  * the start of a css_set
2930  */
2931 static void cgroup_advance_iter(struct cgroup *cgrp,
2932                                 struct cgroup_iter *it)
2933 {
2934         struct list_head *l = it->cg_link;
2935         struct cg_cgroup_link *link;
2936         struct css_set *cg;
2937
2938         /* Advance to the next non-empty css_set */
2939         do {
2940                 l = l->next;
2941                 if (l == &cgrp->css_sets) {
2942                         it->cg_link = NULL;
2943                         return;
2944                 }
2945                 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2946                 cg = link->cg;
2947         } while (list_empty(&cg->tasks));
2948         it->cg_link = l;
2949         it->task = cg->tasks.next;
2950 }
2951
2952 /*
2953  * To reduce the fork() overhead for systems that are not actually
2954  * using their cgroups capability, we don't maintain the lists running
2955  * through each css_set to its tasks until we see the list actually
2956  * used - in other words after the first call to cgroup_iter_start().
2957  */
2958 static void cgroup_enable_task_cg_lists(void)
2959 {
2960         struct task_struct *p, *g;
2961         write_lock(&css_set_lock);
2962         use_task_css_set_links = 1;
2963         /*
2964          * We need tasklist_lock because RCU is not safe against
2965          * while_each_thread(). Besides, a forking task that has passed
2966          * cgroup_post_fork() without seeing use_task_css_set_links = 1
2967          * is not guaranteed to have its child immediately visible in the
2968          * tasklist if we walk through it with RCU.
2969          */
2970         read_lock(&tasklist_lock);
2971         do_each_thread(g, p) {
2972                 task_lock(p);
2973                 /*
2974                  * We should check if the process is exiting, otherwise
2975                  * it will race with cgroup_exit() in that the list
2976                  * entry won't be deleted though the process has exited.
2977                  */
2978                 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2979                         list_add(&p->cg_list, &p->cgroups->tasks);
2980                 task_unlock(p);
2981         } while_each_thread(g, p);
2982         read_unlock(&tasklist_lock);
2983         write_unlock(&css_set_lock);
2984 }
2985
2986 /**
2987  * cgroup_next_descendant_pre - find the next descendant for pre-order walk
2988  * @pos: the current position (%NULL to initiate traversal)
2989  * @cgroup: cgroup whose descendants to walk
2990  *
2991  * To be used by cgroup_for_each_descendant_pre().  Find the next
2992  * descendant to visit for pre-order traversal of @cgroup's descendants.
2993  */
2994 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
2995                                           struct cgroup *cgroup)
2996 {
2997         struct cgroup *next;
2998
2999         WARN_ON_ONCE(!rcu_read_lock_held());
3000
3001         /* if first iteration, pretend we just visited @cgroup */
3002         if (!pos) {
3003                 if (list_empty(&cgroup->children))
3004                         return NULL;
3005                 pos = cgroup;
3006         }
3007
3008         /* visit the first child if exists */
3009         next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
3010         if (next)
3011                 return next;
3012
3013         /* no child, visit my or the closest ancestor's next sibling */
3014         do {
3015                 next = list_entry_rcu(pos->sibling.next, struct cgroup,
3016                                       sibling);
3017                 if (&next->sibling != &pos->parent->children)
3018                         return next;
3019
3020                 pos = pos->parent;
3021         } while (pos != cgroup);
3022
3023         return NULL;
3024 }
3025 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
3026
3027 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3028 {
3029         struct cgroup *last;
3030
3031         do {
3032                 last = pos;
3033                 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3034                                              sibling);
3035         } while (pos);
3036
3037         return last;
3038 }
3039
3040 /**
3041  * cgroup_next_descendant_post - find the next descendant for post-order walk
3042  * @pos: the current position (%NULL to initiate traversal)
3043  * @cgroup: cgroup whose descendants to walk
3044  *
3045  * To be used by cgroup_for_each_descendant_post().  Find the next
3046  * descendant to visit for post-order traversal of @cgroup's descendants.
3047  */
3048 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3049                                            struct cgroup *cgroup)
3050 {
3051         struct cgroup *next;
3052
3053         WARN_ON_ONCE(!rcu_read_lock_held());
3054
3055         /* if first iteration, visit the leftmost descendant */
3056         if (!pos) {
3057                 next = cgroup_leftmost_descendant(cgroup);
3058                 return next != cgroup ? next : NULL;
3059         }
3060
3061         /* if there's an unvisited sibling, visit its leftmost descendant */
3062         next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3063         if (&next->sibling != &pos->parent->children)
3064                 return cgroup_leftmost_descendant(next);
3065
3066         /* no sibling left, visit parent */
3067         next = pos->parent;
3068         return next != cgroup ? next : NULL;
3069 }
3070 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3071
3072 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3073         __acquires(css_set_lock)
3074 {
3075         /*
3076          * The first time anyone tries to iterate across a cgroup,
3077          * we need to enable the list linking each css_set to its
3078          * tasks, and fix up all existing tasks.
3079          */
3080         if (!use_task_css_set_links)
3081                 cgroup_enable_task_cg_lists();
3082
3083         read_lock(&css_set_lock);
3084         it->cg_link = &cgrp->css_sets;
3085         cgroup_advance_iter(cgrp, it);
3086 }
3087
3088 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3089                                         struct cgroup_iter *it)
3090 {
3091         struct task_struct *res;
3092         struct list_head *l = it->task;
3093         struct cg_cgroup_link *link;
3094
3095         /* If the iterator cg is NULL, we have no tasks */
3096         if (!it->cg_link)
3097                 return NULL;
3098         res = list_entry(l, struct task_struct, cg_list);
3099         /* Advance iterator to find next entry */
3100         l = l->next;
3101         link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3102         if (l == &link->cg->tasks) {
3103                 /* We reached the end of this task list - move on to
3104                  * the next cg_cgroup_link */
3105                 cgroup_advance_iter(cgrp, it);
3106         } else {
3107                 it->task = l;
3108         }
3109         return res;
3110 }
3111
3112 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3113         __releases(css_set_lock)
3114 {
3115         read_unlock(&css_set_lock);
3116 }
3117
3118 static inline int started_after_time(struct task_struct *t1,
3119                                      struct timespec *time,
3120                                      struct task_struct *t2)
3121 {
3122         int start_diff = timespec_compare(&t1->start_time, time);
3123         if (start_diff > 0) {
3124                 return 1;
3125         } else if (start_diff < 0) {
3126                 return 0;
3127         } else {
3128                 /*
3129                  * Arbitrarily, if two processes started at the same
3130                  * time, we'll say that the lower pointer value
3131                  * started first. Note that t2 may have exited by now
3132                  * so this may not be a valid pointer any longer, but
3133                  * that's fine - it still serves to distinguish
3134                  * between two tasks started (effectively) simultaneously.
3135                  */
3136                 return t1 > t2;
3137         }
3138 }
3139
3140 /*
3141  * This function is a callback from heap_insert() and is used to order
3142  * the heap.
3143  * In this case we order the heap in descending task start time.
3144  */
3145 static inline int started_after(void *p1, void *p2)
3146 {
3147         struct task_struct *t1 = p1;
3148         struct task_struct *t2 = p2;
3149         return started_after_time(t1, &t2->start_time, t2);
3150 }
3151
3152 /**
3153  * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3154  * @scan: struct cgroup_scanner containing arguments for the scan
3155  *
3156  * Arguments include pointers to callback functions test_task() and
3157  * process_task().
3158  * Iterate through all the tasks in a cgroup, calling test_task() for each,
3159  * and if it returns true, call process_task() for it also.
3160  * The test_task pointer may be NULL, meaning always true (select all tasks).
3161  * Effectively duplicates cgroup_iter_{start,next,end}()
3162  * but does not lock css_set_lock for the call to process_task().
3163  * The struct cgroup_scanner may be embedded in any structure of the caller's
3164  * creation.
3165  * It is guaranteed that process_task() will act on every task that
3166  * is a member of the cgroup for the duration of this call. This
3167  * function may or may not call process_task() for tasks that exit
3168  * or move to a different cgroup during the call, or are forked or
3169  * move into the cgroup during the call.
3170  *
3171  * Note that test_task() may be called with locks held, and may in some
3172  * situations be called multiple times for the same task, so it should
3173  * be cheap.
3174  * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3175  * pre-allocated and will be used for heap operations (and its "gt" member will
3176  * be overwritten), else a temporary heap will be used (allocation of which
3177  * may cause this function to fail).
3178  */
3179 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3180 {
3181         int retval, i;
3182         struct cgroup_iter it;
3183         struct task_struct *p, *dropped;
3184         /* Never dereference latest_task, since it's not refcounted */
3185         struct task_struct *latest_task = NULL;
3186         struct ptr_heap tmp_heap;
3187         struct ptr_heap *heap;
3188         struct timespec latest_time = { 0, 0 };
3189
3190         if (scan->heap) {
3191                 /* The caller supplied our heap and pre-allocated its memory */
3192                 heap = scan->heap;
3193                 heap->gt = &started_after;
3194         } else {
3195                 /* We need to allocate our own heap memory */
3196                 heap = &tmp_heap;
3197                 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3198                 if (retval)
3199                         /* cannot allocate the heap */
3200                         return retval;
3201         }
3202
3203  again:
3204         /*
3205          * Scan tasks in the cgroup, using the scanner's "test_task" callback
3206          * to determine which are of interest, and using the scanner's
3207          * "process_task" callback to process any of them that need an update.
3208          * Since we don't want to hold any locks during the task updates,
3209          * gather tasks to be processed in a heap structure.
3210          * The heap is sorted by descending task start time.
3211          * If the statically-sized heap fills up, we overflow tasks that
3212          * started later, and in future iterations only consider tasks that
3213          * started after the latest task in the previous pass. This
3214          * guarantees forward progress and that we don't miss any tasks.
3215          */
3216         heap->size = 0;
3217         cgroup_iter_start(scan->cg, &it);
3218         while ((p = cgroup_iter_next(scan->cg, &it))) {
3219                 /*
3220                  * Only affect tasks that qualify per the caller's callback,
3221                  * if he provided one
3222                  */
3223                 if (scan->test_task && !scan->test_task(p, scan))
3224                         continue;
3225                 /*
3226                  * Only process tasks that started after the last task
3227                  * we processed
3228                  */
3229                 if (!started_after_time(p, &latest_time, latest_task))
3230                         continue;
3231                 dropped = heap_insert(heap, p);
3232                 if (dropped == NULL) {
3233                         /*
3234                          * The new task was inserted; the heap wasn't
3235                          * previously full
3236                          */
3237                         get_task_struct(p);
3238                 } else if (dropped != p) {
3239                         /*
3240                          * The new task was inserted, and pushed out a
3241                          * different task
3242                          */
3243                         get_task_struct(p);
3244                         put_task_struct(dropped);
3245                 }
3246                 /*
3247                  * Else the new task was newer than anything already in
3248                  * the heap and wasn't inserted
3249                  */
3250         }
3251         cgroup_iter_end(scan->cg, &it);
3252
3253         if (heap->size) {
3254                 for (i = 0; i < heap->size; i++) {
3255                         struct task_struct *q = heap->ptrs[i];
3256                         if (i == 0) {
3257                                 latest_time = q->start_time;
3258                                 latest_task = q;
3259                         }
3260                         /* Process the task per the caller's callback */
3261                         scan->process_task(q, scan);
3262                         put_task_struct(q);
3263                 }
3264                 /*
3265                  * If we had to process any tasks at all, scan again
3266                  * in case some of them were in the middle of forking
3267                  * children that didn't get processed.
3268                  * Not the most efficient way to do it, but it avoids
3269                  * having to take callback_mutex in the fork path
3270                  */
3271                 goto again;
3272         }
3273         if (heap == &tmp_heap)
3274                 heap_free(&tmp_heap);
3275         return 0;
3276 }
3277
3278 /*
3279  * Stuff for reading the 'tasks'/'procs' files.
3280  *
3281  * Reading this file can return large amounts of data if a cgroup has
3282  * *lots* of attached tasks. So it may need several calls to read(),
3283  * but we cannot guarantee that the information we produce is correct
3284  * unless we produce it entirely atomically.
3285  *
3286  */
3287
3288 /* which pidlist file are we talking about? */
3289 enum cgroup_filetype {
3290         CGROUP_FILE_PROCS,
3291         CGROUP_FILE_TASKS,
3292 };
3293
3294 /*
3295  * A pidlist is a list of pids that virtually represents the contents of one
3296  * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3297  * a pair (one each for procs, tasks) for each pid namespace that's relevant
3298  * to the cgroup.
3299  */
3300 struct cgroup_pidlist {
3301         /*
3302          * used to find which pidlist is wanted. doesn't change as long as
3303          * this particular list stays in the list.
3304         */
3305         struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3306         /* array of xids */
3307         pid_t *list;
3308         /* how many elements the above list has */
3309         int length;
3310         /* how many files are using the current array */
3311         int use_count;
3312         /* each of these stored in a list by its cgroup */
3313         struct list_head links;
3314         /* pointer to the cgroup we belong to, for list removal purposes */
3315         struct cgroup *owner;
3316         /* protects the other fields */
3317         struct rw_semaphore mutex;
3318 };
3319
3320 /*
3321  * The following two functions "fix" the issue where there are more pids
3322  * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3323  * TODO: replace with a kernel-wide solution to this problem
3324  */
3325 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3326 static void *pidlist_allocate(int count)
3327 {
3328         if (PIDLIST_TOO_LARGE(count))
3329                 return vmalloc(count * sizeof(pid_t));
3330         else
3331                 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3332 }
3333 static void pidlist_free(void *p)
3334 {
3335         if (is_vmalloc_addr(p))
3336                 vfree(p);
3337         else
3338                 kfree(p);
3339 }
3340 static void *pidlist_resize(void *p, int newcount)
3341 {
3342         void *newlist;
3343         /* note: if new alloc fails, old p will still be valid either way */
3344         if (is_vmalloc_addr(p)) {
3345                 newlist = vmalloc(newcount * sizeof(pid_t));
3346                 if (!newlist)
3347                         return NULL;
3348                 memcpy(newlist, p, newcount * sizeof(pid_t));
3349                 vfree(p);
3350         } else {
3351                 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
3352         }
3353         return newlist;
3354 }
3355
3356 /*
3357  * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3358  * If the new stripped list is sufficiently smaller and there's enough memory
3359  * to allocate a new buffer, will let go of the unneeded memory. Returns the
3360  * number of unique elements.
3361  */
3362 /* is the size difference enough that we should re-allocate the array? */
3363 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
3364 static int pidlist_uniq(pid_t **p, int length)
3365 {
3366         int src, dest = 1;
3367         pid_t *list = *p;
3368         pid_t *newlist;
3369
3370         /*
3371          * we presume the 0th element is unique, so i starts at 1. trivial
3372          * edge cases first; no work needs to be done for either
3373          */
3374         if (length == 0 || length == 1)
3375                 return length;
3376         /* src and dest walk down the list; dest counts unique elements */
3377         for (src = 1; src < length; src++) {
3378                 /* find next unique element */
3379                 while (list[src] == list[src-1]) {
3380                         src++;
3381                         if (src == length)
3382                                 goto after;
3383                 }
3384                 /* dest always points to where the next unique element goes */
3385                 list[dest] = list[src];
3386                 dest++;
3387         }
3388 after:
3389         /*
3390          * if the length difference is large enough, we want to allocate a
3391          * smaller buffer to save memory. if this fails due to out of memory,
3392          * we'll just stay with what we've got.
3393          */
3394         if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
3395                 newlist = pidlist_resize(list, dest);
3396                 if (newlist)
3397                         *p = newlist;
3398         }
3399         return dest;
3400 }
3401
3402 static int cmppid(const void *a, const void *b)
3403 {
3404         return *(pid_t *)a - *(pid_t *)b;
3405 }
3406
3407 /*
3408  * find the appropriate pidlist for our purpose (given procs vs tasks)
3409  * returns with the lock on that pidlist already held, and takes care
3410  * of the use count, or returns NULL with no locks held if we're out of
3411  * memory.
3412  */
3413 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3414                                                   enum cgroup_filetype type)
3415 {
3416         struct cgroup_pidlist *l;
3417         /* don't need task_nsproxy() if we're looking at ourself */
3418         struct pid_namespace *ns = current->nsproxy->pid_ns;
3419
3420         /*
3421          * We can't drop the pidlist_mutex before taking the l->mutex in case
3422          * the last ref-holder is trying to remove l from the list at the same
3423          * time. Holding the pidlist_mutex precludes somebody taking whichever
3424          * list we find out from under us - compare release_pid_array().
3425          */
3426         mutex_lock(&cgrp->pidlist_mutex);
3427         list_for_each_entry(l, &cgrp->pidlists, links) {
3428                 if (l->key.type == type && l->key.ns == ns) {
3429                         /* make sure l doesn't vanish out from under us */
3430                         down_write(&l->mutex);
3431                         mutex_unlock(&cgrp->pidlist_mutex);
3432                         return l;
3433                 }
3434         }
3435         /* entry not found; create a new one */
3436         l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3437         if (!l) {
3438                 mutex_unlock(&cgrp->pidlist_mutex);
3439                 return l;
3440         }
3441         init_rwsem(&l->mutex);
3442         down_write(&l->mutex);
3443         l->key.type = type;
3444         l->key.ns = get_pid_ns(ns);
3445         l->use_count = 0; /* don't increment here */
3446         l->list = NULL;
3447         l->owner = cgrp;
3448         list_add(&l->links, &cgrp->pidlists);
3449         mutex_unlock(&cgrp->pidlist_mutex);
3450         return l;
3451 }
3452
3453 /*
3454  * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3455  */
3456 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3457                               struct cgroup_pidlist **lp)
3458 {
3459         pid_t *array;
3460         int length;
3461         int pid, n = 0; /* used for populating the array */
3462         struct cgroup_iter it;
3463         struct task_struct *tsk;
3464         struct cgroup_pidlist *l;
3465
3466         /*
3467          * If cgroup gets more users after we read count, we won't have
3468          * enough space - tough.  This race is indistinguishable to the
3469          * caller from the case that the additional cgroup users didn't
3470          * show up until sometime later on.
3471          */
3472         length = cgroup_task_count(cgrp);
3473         array = pidlist_allocate(length);
3474         if (!array)
3475                 return -ENOMEM;
3476         /* now, populate the array */
3477         cgroup_iter_start(cgrp, &it);
3478         while ((tsk = cgroup_iter_next(cgrp, &it))) {
3479                 if (unlikely(n == length))
3480                         break;
3481                 /* get tgid or pid for procs or tasks file respectively */
3482                 if (type == CGROUP_FILE_PROCS)
3483                         pid = task_tgid_vnr(tsk);
3484                 else
3485                         pid = task_pid_vnr(tsk);
3486                 if (pid > 0) /* make sure to only use valid results */
3487                         array[n++] = pid;
3488         }
3489         cgroup_iter_end(cgrp, &it);
3490         length = n;
3491         /* now sort & (if procs) strip out duplicates */
3492         sort(array, length, sizeof(pid_t), cmppid, NULL);
3493         if (type == CGROUP_FILE_PROCS)
3494                 length = pidlist_uniq(&array, length);
3495         l = cgroup_pidlist_find(cgrp, type);
3496         if (!l) {
3497                 pidlist_free(array);
3498                 return -ENOMEM;
3499         }
3500         /* store array, freeing old if necessary - lock already held */
3501         pidlist_free(l->list);
3502         l->list = array;
3503         l->length = length;
3504         l->use_count++;
3505         up_write(&l->mutex);
3506         *lp = l;
3507         return 0;
3508 }
3509
3510 /**
3511  * cgroupstats_build - build and fill cgroupstats
3512  * @stats: cgroupstats to fill information into
3513  * @dentry: A dentry entry belonging to the cgroup for which stats have
3514  * been requested.
3515  *
3516  * Build and fill cgroupstats so that taskstats can export it to user
3517  * space.
3518  */
3519 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3520 {
3521         int ret = -EINVAL;
3522         struct cgroup *cgrp;
3523         struct cgroup_iter it;
3524         struct task_struct *tsk;
3525
3526         /*
3527          * Validate dentry by checking the superblock operations,
3528          * and make sure it's a directory.
3529          */
3530         if (dentry->d_sb->s_op != &cgroup_ops ||
3531             !S_ISDIR(dentry->d_inode->i_mode))
3532                  goto err;
3533
3534         ret = 0;
3535         cgrp = dentry->d_fsdata;
3536
3537         cgroup_iter_start(cgrp, &it);
3538         while ((tsk = cgroup_iter_next(cgrp, &it))) {
3539                 switch (tsk->state) {
3540                 case TASK_RUNNING:
3541                         stats->nr_running++;
3542                         break;
3543                 case TASK_INTERRUPTIBLE:
3544                         stats->nr_sleeping++;
3545                         break;
3546                 case TASK_UNINTERRUPTIBLE:
3547                         stats->nr_uninterruptible++;
3548                         break;
3549                 case TASK_STOPPED:
3550                         stats->nr_stopped++;
3551                         break;
3552                 default:
3553                         if (delayacct_is_task_waiting_on_io(tsk))
3554                                 stats->nr_io_wait++;
3555                         break;
3556                 }
3557         }
3558         cgroup_iter_end(cgrp, &it);
3559
3560 err:
3561         return ret;
3562 }
3563
3564
3565 /*
3566  * seq_file methods for the tasks/procs files. The seq_file position is the
3567  * next pid to display; the seq_file iterator is a pointer to the pid
3568  * in the cgroup->l->list array.
3569  */
3570
3571 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3572 {
3573         /*
3574          * Initially we receive a position value that corresponds to
3575          * one more than the last pid shown (or 0 on the first call or
3576          * after a seek to the start). Use a binary-search to find the
3577          * next pid to display, if any
3578          */
3579         struct cgroup_pidlist *l = s->private;
3580         int index = 0, pid = *pos;
3581         int *iter;
3582
3583         down_read(&l->mutex);
3584         if (pid) {
3585                 int end = l->length;
3586
3587                 while (index < end) {
3588                         int mid = (index + end) / 2;
3589                         if (l->list[mid] == pid) {
3590                                 index = mid;
3591                                 break;
3592                         } else if (l->list[mid] <= pid)
3593                                 index = mid + 1;
3594                         else
3595                                 end = mid;
3596                 }
3597         }
3598         /* If we're off the end of the array, we're done */
3599         if (index >= l->length)
3600                 return NULL;
3601         /* Update the abstract position to be the actual pid that we found */
3602         iter = l->list + index;
3603         *pos = *iter;
3604         return iter;
3605 }
3606
3607 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3608 {
3609         struct cgroup_pidlist *l = s->private;
3610         up_read(&l->mutex);
3611 }
3612
3613 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3614 {
3615         struct cgroup_pidlist *l = s->private;
3616         pid_t *p = v;
3617         pid_t *end = l->list + l->length;
3618         /*
3619          * Advance to the next pid in the array. If this goes off the
3620          * end, we're done
3621          */
3622         p++;
3623         if (p >= end) {
3624                 return NULL;
3625         } else {
3626                 *pos = *p;
3627                 return p;
3628         }
3629 }
3630
3631 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3632 {
3633         return seq_printf(s, "%d\n", *(int *)v);
3634 }
3635
3636 /*
3637  * seq_operations functions for iterating on pidlists through seq_file -
3638  * independent of whether it's tasks or procs
3639  */
3640 static const struct seq_operations cgroup_pidlist_seq_operations = {
3641         .start = cgroup_pidlist_start,
3642         .stop = cgroup_pidlist_stop,
3643         .next = cgroup_pidlist_next,
3644         .show = cgroup_pidlist_show,
3645 };
3646
3647 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3648 {
3649         /*
3650          * the case where we're the last user of this particular pidlist will
3651          * have us remove it from the cgroup's list, which entails taking the
3652          * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3653          * pidlist_mutex, we have to take pidlist_mutex first.
3654          */
3655         mutex_lock(&l->owner->pidlist_mutex);
3656         down_write(&l->mutex);
3657         BUG_ON(!l->use_count);
3658         if (!--l->use_count) {
3659                 /* we're the last user if refcount is 0; remove and free */
3660                 list_del(&l->links);
3661                 mutex_unlock(&l->owner->pidlist_mutex);
3662                 pidlist_free(l->list);
3663                 put_pid_ns(l->key.ns);
3664                 up_write(&l->mutex);
3665                 kfree(l);
3666                 return;
3667         }
3668         mutex_unlock(&l->owner->pidlist_mutex);
3669         up_write(&l->mutex);
3670 }
3671
3672 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3673 {
3674         struct cgroup_pidlist *l;
3675         if (!(file->f_mode & FMODE_READ))
3676                 return 0;
3677         /*
3678          * the seq_file will only be initialized if the file was opened for
3679          * reading; hence we check if it's not null only in that case.
3680          */
3681         l = ((struct seq_file *)file->private_data)->private;
3682         cgroup_release_pid_array(l);
3683         return seq_release(inode, file);
3684 }
3685
3686 static const struct file_operations cgroup_pidlist_operations = {
3687         .read = seq_read,
3688         .llseek = seq_lseek,
3689         .write = cgroup_file_write,
3690         .release = cgroup_pidlist_release,
3691 };
3692
3693 /*
3694  * The following functions handle opens on a file that displays a pidlist
3695  * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3696  * in the cgroup.
3697  */
3698 /* helper function for the two below it */
3699 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3700 {
3701         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3702         struct cgroup_pidlist *l;
3703         int retval;
3704
3705         /* Nothing to do for write-only files */
3706         if (!(file->f_mode & FMODE_READ))
3707                 return 0;
3708
3709         /* have the array populated */
3710         retval = pidlist_array_load(cgrp, type, &l);
3711         if (retval)
3712                 return retval;
3713         /* configure file information */
3714         file->f_op = &cgroup_pidlist_operations;
3715
3716         retval = seq_open(file, &cgroup_pidlist_seq_operations);
3717         if (retval) {
3718                 cgroup_release_pid_array(l);
3719                 return retval;
3720         }
3721         ((struct seq_file *)file->private_data)->private = l;
3722         return 0;
3723 }
3724 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3725 {
3726         return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3727 }
3728 static int cgroup_procs_open(struct inode *unused, struct file *file)
3729 {
3730         return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3731 }
3732
3733 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3734                                             struct cftype *cft)
3735 {
3736         return notify_on_release(cgrp);
3737 }
3738
3739 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3740                                           struct cftype *cft,
3741                                           u64 val)
3742 {
3743         clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3744         if (val)
3745                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3746         else
3747                 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3748         return 0;
3749 }
3750
3751 /*
3752  * Unregister event and free resources.
3753  *
3754  * Gets called from workqueue.
3755  */
3756 static void cgroup_event_remove(struct work_struct *work)
3757 {
3758         struct cgroup_event *event = container_of(work, struct cgroup_event,
3759                         remove);
3760         struct cgroup *cgrp = event->cgrp;
3761
3762         event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3763
3764         eventfd_ctx_put(event->eventfd);
3765         kfree(event);
3766         dput(cgrp->dentry);
3767 }
3768
3769 /*
3770  * Gets called on POLLHUP on eventfd when user closes it.
3771  *
3772  * Called with wqh->lock held and interrupts disabled.
3773  */
3774 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3775                 int sync, void *key)
3776 {
3777         struct cgroup_event *event = container_of(wait,
3778                         struct cgroup_event, wait);
3779         struct cgroup *cgrp = event->cgrp;
3780         unsigned long flags = (unsigned long)key;
3781
3782         if (flags & POLLHUP) {
3783                 __remove_wait_queue(event->wqh, &event->wait);
3784                 spin_lock(&cgrp->event_list_lock);
3785                 list_del(&event->list);
3786                 spin_unlock(&cgrp->event_list_lock);
3787                 /*
3788                  * We are in atomic context, but cgroup_event_remove() may
3789                  * sleep, so we have to call it in workqueue.
3790                  */
3791                 schedule_work(&event->remove);
3792         }
3793
3794         return 0;
3795 }
3796
3797 static void cgroup_event_ptable_queue_proc(struct file *file,
3798                 wait_queue_head_t *wqh, poll_table *pt)
3799 {
3800         struct cgroup_event *event = container_of(pt,
3801                         struct cgroup_event, pt);
3802
3803         event->wqh = wqh;
3804         add_wait_queue(wqh, &event->wait);
3805 }
3806
3807 /*
3808  * Parse input and register new cgroup event handler.
3809  *
3810  * Input must be in format '<event_fd> <control_fd> <args>'.
3811  * Interpretation of args is defined by control file implementation.
3812  */
3813 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3814                                       const char *buffer)
3815 {
3816         struct cgroup_event *event = NULL;
3817         unsigned int efd, cfd;
3818         struct file *efile = NULL;
3819         struct file *cfile = NULL;
3820         char *endp;
3821         int ret;
3822
3823         efd = simple_strtoul(buffer, &endp, 10);
3824         if (*endp != ' ')
3825                 return -EINVAL;
3826         buffer = endp + 1;
3827
3828         cfd = simple_strtoul(buffer, &endp, 10);
3829         if ((*endp != ' ') && (*endp != '\0'))
3830                 return -EINVAL;
3831         buffer = endp + 1;
3832
3833         event = kzalloc(sizeof(*event), GFP_KERNEL);
3834         if (!event)
3835                 return -ENOMEM;
3836         event->cgrp = cgrp;
3837         INIT_LIST_HEAD(&event->list);
3838         init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3839         init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3840         INIT_WORK(&event->remove, cgroup_event_remove);
3841
3842         efile = eventfd_fget(efd);
3843         if (IS_ERR(efile)) {
3844                 ret = PTR_ERR(efile);
3845                 goto fail;
3846         }
3847
3848         event->eventfd = eventfd_ctx_fileget(efile);
3849         if (IS_ERR(event->eventfd)) {
3850                 ret = PTR_ERR(event->eventfd);
3851                 goto fail;
3852         }
3853
3854         cfile = fget(cfd);
3855         if (!cfile) {
3856                 ret = -EBADF;
3857                 goto fail;
3858         }
3859
3860         /* the process need read permission on control file */
3861         /* AV: shouldn't we check that it's been opened for read instead? */
3862         ret = inode_permission(cfile->f_path.dentry->d_inode, MAY_READ);
3863         if (ret < 0)
3864                 goto fail;
3865
3866         event->cft = __file_cft(cfile);
3867         if (IS_ERR(event->cft)) {
3868                 ret = PTR_ERR(event->cft);
3869                 goto fail;
3870         }
3871
3872         if (!event->cft->register_event || !event->cft->unregister_event) {
3873                 ret = -EINVAL;
3874                 goto fail;
3875         }
3876
3877         ret = event->cft->register_event(cgrp, event->cft,
3878                         event->eventfd, buffer);
3879         if (ret)
3880                 goto fail;
3881
3882         if (efile->f_op->poll(efile, &event->pt) & POLLHUP) {
3883                 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3884                 ret = 0;
3885                 goto fail;
3886         }
3887
3888         /*
3889          * Events should be removed after rmdir of cgroup directory, but before
3890          * destroying subsystem state objects. Let's take reference to cgroup
3891          * directory dentry to do that.
3892          */
3893         dget(cgrp->dentry);
3894
3895         spin_lock(&cgrp->event_list_lock);
3896         list_add(&event->list, &cgrp->event_list);
3897         spin_unlock(&cgrp->event_list_lock);
3898
3899         fput(cfile);
3900         fput(efile);
3901
3902         return 0;
3903
3904 fail:
3905         if (cfile)
3906                 fput(cfile);
3907
3908         if (event && event->eventfd && !IS_ERR(event->eventfd))
3909                 eventfd_ctx_put(event->eventfd);
3910
3911         if (!IS_ERR_OR_NULL(efile))
3912                 fput(efile);
3913
3914         kfree(event);
3915
3916         return ret;
3917 }
3918
3919 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
3920                                     struct cftype *cft)
3921 {
3922         return clone_children(cgrp);
3923 }
3924
3925 static int cgroup_clone_children_write(struct cgroup *cgrp,
3926                                      struct cftype *cft,
3927                                      u64 val)
3928 {
3929         if (val)
3930                 set_bit(CGRP_CLONE_CHILDREN, &cgrp->flags);
3931         else
3932                 clear_bit(CGRP_CLONE_CHILDREN, &cgrp->flags);
3933         return 0;
3934 }
3935
3936 /*
3937  * for the common functions, 'private' gives the type of file
3938  */
3939 /* for hysterical raisins, we can't put this on the older files */
3940 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3941 static struct cftype files[] = {
3942         {
3943                 .name = "tasks",
3944                 .open = cgroup_tasks_open,
3945                 .write_u64 = cgroup_tasks_write,
3946                 .release = cgroup_pidlist_release,
3947                 .mode = S_IRUGO | S_IWUSR,
3948         },
3949         {
3950                 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
3951                 .open = cgroup_procs_open,
3952                 .write_u64 = cgroup_procs_write,
3953                 .release = cgroup_pidlist_release,
3954                 .mode = S_IRUGO | S_IWUSR,
3955         },
3956         {
3957                 .name = "notify_on_release",
3958                 .read_u64 = cgroup_read_notify_on_release,
3959                 .write_u64 = cgroup_write_notify_on_release,
3960         },
3961         {
3962                 .name = CGROUP_FILE_GENERIC_PREFIX "event_control",
3963                 .write_string = cgroup_write_event_control,
3964                 .mode = S_IWUGO,
3965         },
3966         {
3967                 .name = "cgroup.clone_children",
3968                 .read_u64 = cgroup_clone_children_read,
3969                 .write_u64 = cgroup_clone_children_write,
3970         },
3971         {
3972                 .name = "release_agent",
3973                 .flags = CFTYPE_ONLY_ON_ROOT,
3974                 .read_seq_string = cgroup_release_agent_show,
3975                 .write_string = cgroup_release_agent_write,
3976                 .max_write_len = PATH_MAX,
3977         },
3978         { }     /* terminate */
3979 };
3980
3981 /**
3982  * cgroup_populate_dir - selectively creation of files in a directory
3983  * @cgrp: target cgroup
3984  * @base_files: true if the base files should be added
3985  * @subsys_mask: mask of the subsystem ids whose files should be added
3986  */
3987 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
3988                                unsigned long subsys_mask)
3989 {
3990         int err;
3991         struct cgroup_subsys *ss;
3992
3993         if (base_files) {
3994                 err = cgroup_addrm_files(cgrp, NULL, files, true);
3995                 if (err < 0)
3996                         return err;
3997         }
3998
3999         /* process cftsets of each subsystem */
4000         for_each_subsys(cgrp->root, ss) {
4001                 struct cftype_set *set;
4002                 if (!test_bit(ss->subsys_id, &subsys_mask))
4003                         continue;
4004
4005                 list_for_each_entry(set, &ss->cftsets, node)
4006                         cgroup_addrm_files(cgrp, ss, set->cfts, true);
4007         }
4008
4009         /* This cgroup is ready now */
4010         for_each_subsys(cgrp->root, ss) {
4011                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4012                 /*
4013                  * Update id->css pointer and make this css visible from
4014                  * CSS ID functions. This pointer will be dereferened
4015                  * from RCU-read-side without locks.
4016                  */
4017                 if (css->id)
4018                         rcu_assign_pointer(css->id->css, css);
4019         }
4020
4021         return 0;
4022 }
4023
4024 static void css_dput_fn(struct work_struct *work)
4025 {
4026         struct cgroup_subsys_state *css =
4027                 container_of(work, struct cgroup_subsys_state, dput_work);
4028         struct dentry *dentry = css->cgroup->dentry;
4029         struct super_block *sb = dentry->d_sb;
4030
4031         atomic_inc(&sb->s_active);
4032         dput(dentry);
4033         deactivate_super(sb);
4034 }
4035
4036 static void init_cgroup_css(struct cgroup_subsys_state *css,
4037                                struct cgroup_subsys *ss,
4038                                struct cgroup *cgrp)
4039 {
4040         css->cgroup = cgrp;
4041         atomic_set(&css->refcnt, 1);
4042         css->flags = 0;
4043         css->id = NULL;
4044         if (cgrp == dummytop)
4045                 set_bit(CSS_ROOT, &css->flags);
4046         BUG_ON(cgrp->subsys[ss->subsys_id]);
4047         cgrp->subsys[ss->subsys_id] = css;
4048
4049         /*
4050          * css holds an extra ref to @cgrp->dentry which is put on the last
4051          * css_put().  dput() requires process context, which css_put() may
4052          * be called without.  @css->dput_work will be used to invoke
4053          * dput() asynchronously from css_put().
4054          */
4055         INIT_WORK(&css->dput_work, css_dput_fn);
4056 }
4057
4058 /*
4059  * cgroup_create - create a cgroup
4060  * @parent: cgroup that will be parent of the new cgroup
4061  * @dentry: dentry of the new cgroup
4062  * @mode: mode to set on new inode
4063  *
4064  * Must be called with the mutex on the parent inode held
4065  */
4066 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4067                              umode_t mode)
4068 {
4069         struct cgroup *cgrp;
4070         struct cgroupfs_root *root = parent->root;
4071         int err = 0;
4072         struct cgroup_subsys *ss;
4073         struct super_block *sb = root->sb;
4074
4075         cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4076         if (!cgrp)
4077                 return -ENOMEM;
4078
4079         /*
4080          * Only live parents can have children.  Note that the liveliness
4081          * check isn't strictly necessary because cgroup_mkdir() and
4082          * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4083          * anyway so that locking is contained inside cgroup proper and we
4084          * don't get nasty surprises if we ever grow another caller.
4085          */
4086         if (!cgroup_lock_live_group(parent)) {
4087                 err = -ENODEV;
4088                 goto err_free;
4089         }
4090
4091         /* Grab a reference on the superblock so the hierarchy doesn't
4092          * get deleted on unmount if there are child cgroups.  This
4093          * can be done outside cgroup_mutex, since the sb can't
4094          * disappear while someone has an open control file on the
4095          * fs */
4096         atomic_inc(&sb->s_active);
4097
4098         init_cgroup_housekeeping(cgrp);
4099
4100         cgrp->parent = parent;
4101         cgrp->root = parent->root;
4102         cgrp->top_cgroup = parent->top_cgroup;
4103
4104         if (notify_on_release(parent))
4105                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4106
4107         if (clone_children(parent))
4108                 set_bit(CGRP_CLONE_CHILDREN, &cgrp->flags);
4109
4110         for_each_subsys(root, ss) {
4111                 struct cgroup_subsys_state *css;
4112
4113                 css = ss->create(cgrp);
4114                 if (IS_ERR(css)) {
4115                         err = PTR_ERR(css);
4116                         goto err_destroy;
4117                 }
4118                 init_cgroup_css(css, ss, cgrp);
4119                 if (ss->use_id) {
4120                         err = alloc_css_id(ss, parent, cgrp);
4121                         if (err)
4122                                 goto err_destroy;
4123                 }
4124                 /* At error, ->destroy() callback has to free assigned ID. */
4125                 if (clone_children(parent) && ss->post_clone)
4126                         ss->post_clone(cgrp);
4127
4128                 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4129                     parent->parent) {
4130                         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",
4131                                    current->comm, current->pid, ss->name);
4132                         if (!strcmp(ss->name, "memory"))
4133                                 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4134                         ss->warned_broken_hierarchy = true;
4135                 }
4136         }
4137
4138         list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4139         root->number_of_cgroups++;
4140
4141         err = cgroup_create_dir(cgrp, dentry, mode);
4142         if (err < 0)
4143                 goto err_remove;
4144
4145         for_each_subsys(root, ss) {
4146                 /* each css holds a ref to the cgroup's dentry */
4147                 dget(dentry);
4148
4149                 /* creation succeeded, notify subsystems */
4150                 if (ss->post_create)
4151                         ss->post_create(cgrp);
4152         }
4153
4154         /* The cgroup directory was pre-locked for us */
4155         BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
4156
4157         list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4158
4159         err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4160         /* If err < 0, we have a half-filled directory - oh well ;) */
4161
4162         mutex_unlock(&cgroup_mutex);
4163         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4164
4165         return 0;
4166
4167  err_remove:
4168
4169         list_del_rcu(&cgrp->sibling);
4170         root->number_of_cgroups--;
4171
4172  err_destroy:
4173
4174         for_each_subsys(root, ss) {
4175                 if (cgrp->subsys[ss->subsys_id])
4176                         ss->destroy(cgrp);
4177         }
4178
4179         mutex_unlock(&cgroup_mutex);
4180
4181         /* Release the reference count that we took on the superblock */
4182         deactivate_super(sb);
4183 err_free:
4184         kfree(cgrp);
4185         return err;
4186 }
4187
4188 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4189 {
4190         struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4191
4192         /* the vfs holds inode->i_mutex already */
4193         return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4194 }
4195
4196 /*
4197  * Check the reference count on each subsystem. Since we already
4198  * established that there are no tasks in the cgroup, if the css refcount
4199  * is also 1, then there should be no outstanding references, so the
4200  * subsystem is safe to destroy. We scan across all subsystems rather than
4201  * using the per-hierarchy linked list of mounted subsystems since we can
4202  * be called via check_for_release() with no synchronization other than
4203  * RCU, and the subsystem linked list isn't RCU-safe.
4204  */
4205 static int cgroup_has_css_refs(struct cgroup *cgrp)
4206 {
4207         int i;
4208
4209         /*
4210          * We won't need to lock the subsys array, because the subsystems
4211          * we're concerned about aren't going anywhere since our cgroup root
4212          * has a reference on them.
4213          */
4214         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4215                 struct cgroup_subsys *ss = subsys[i];
4216                 struct cgroup_subsys_state *css;
4217
4218                 /* Skip subsystems not present or not in this hierarchy */
4219                 if (ss == NULL || ss->root != cgrp->root)
4220                         continue;
4221
4222                 css = cgrp->subsys[ss->subsys_id];
4223                 /*
4224                  * When called from check_for_release() it's possible
4225                  * that by this point the cgroup has been removed
4226                  * and the css deleted. But a false-positive doesn't
4227                  * matter, since it can only happen if the cgroup
4228                  * has been deleted and hence no longer needs the
4229                  * release agent to be called anyway.
4230                  */
4231                 if (css && css_refcnt(css) > 1)
4232                         return 1;
4233         }
4234         return 0;
4235 }
4236
4237 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4238 {
4239         struct cgroup *cgrp = dentry->d_fsdata;
4240         struct dentry *d;
4241         struct cgroup *parent;
4242         DEFINE_WAIT(wait);
4243         struct cgroup_event *event, *tmp;
4244         struct cgroup_subsys *ss;
4245
4246         /* the vfs holds both inode->i_mutex already */
4247         mutex_lock(&cgroup_mutex);
4248         parent = cgrp->parent;
4249         if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
4250                 mutex_unlock(&cgroup_mutex);
4251                 return -EBUSY;
4252         }
4253
4254         /*
4255          * Block new css_tryget() by deactivating refcnt and mark @cgrp
4256          * removed.  This makes future css_tryget() and child creation
4257          * attempts fail thus maintaining the removal conditions verified
4258          * above.
4259          */
4260         for_each_subsys(cgrp->root, ss) {
4261                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4262
4263                 WARN_ON(atomic_read(&css->refcnt) < 0);
4264                 atomic_add(CSS_DEACT_BIAS, &css->refcnt);
4265         }
4266         set_bit(CGRP_REMOVED, &cgrp->flags);
4267
4268         /*
4269          * Tell subsystems to initate destruction.  pre_destroy() should be
4270          * called with cgroup_mutex unlocked.  See 3fa59dfbc3 ("cgroup: fix
4271          * potential deadlock in pre_destroy") for details.
4272          */
4273         mutex_unlock(&cgroup_mutex);
4274         for_each_subsys(cgrp->root, ss)
4275                 if (ss->pre_destroy)
4276                         ss->pre_destroy(cgrp);
4277         mutex_lock(&cgroup_mutex);
4278
4279         /*
4280          * Put all the base refs.  Each css holds an extra reference to the
4281          * cgroup's dentry and cgroup removal proceeds regardless of css
4282          * refs.  On the last put of each css, whenever that may be, the
4283          * extra dentry ref is put so that dentry destruction happens only
4284          * after all css's are released.
4285          */
4286         for_each_subsys(cgrp->root, ss)
4287                 css_put(cgrp->subsys[ss->subsys_id]);
4288
4289         raw_spin_lock(&release_list_lock);
4290         if (!list_empty(&cgrp->release_list))
4291                 list_del_init(&cgrp->release_list);
4292         raw_spin_unlock(&release_list_lock);
4293
4294         /* delete this cgroup from parent->children */
4295         list_del_rcu(&cgrp->sibling);
4296
4297         list_del_init(&cgrp->allcg_node);
4298
4299         d = dget(cgrp->dentry);
4300
4301         cgroup_d_remove_dir(d);
4302         dput(d);
4303
4304         set_bit(CGRP_RELEASABLE, &parent->flags);
4305         check_for_release(parent);
4306
4307         /*
4308          * Unregister events and notify userspace.
4309          * Notify userspace about cgroup removing only after rmdir of cgroup
4310          * directory to avoid race between userspace and kernelspace
4311          */
4312         spin_lock(&cgrp->event_list_lock);
4313         list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4314                 list_del(&event->list);
4315                 remove_wait_queue(event->wqh, &event->wait);
4316                 eventfd_signal(event->eventfd, 1);
4317                 schedule_work(&event->remove);
4318         }
4319         spin_unlock(&cgrp->event_list_lock);
4320
4321         mutex_unlock(&cgroup_mutex);
4322         return 0;
4323 }
4324
4325 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4326 {
4327         INIT_LIST_HEAD(&ss->cftsets);
4328
4329         /*
4330          * base_cftset is embedded in subsys itself, no need to worry about
4331          * deregistration.
4332          */
4333         if (ss->base_cftypes) {
4334                 ss->base_cftset.cfts = ss->base_cftypes;
4335                 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4336         }
4337 }
4338
4339 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4340 {
4341         struct cgroup_subsys_state *css;
4342
4343         printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4344
4345         /* init base cftset */
4346         cgroup_init_cftsets(ss);
4347
4348         /* Create the top cgroup state for this subsystem */
4349         list_add(&ss->sibling, &rootnode.subsys_list);
4350         ss->root = &rootnode;
4351         css = ss->create(dummytop);
4352         /* We don't handle early failures gracefully */
4353         BUG_ON(IS_ERR(css));
4354         init_cgroup_css(css, ss, dummytop);
4355
4356         /* Update the init_css_set to contain a subsys
4357          * pointer to this state - since the subsystem is
4358          * newly registered, all tasks and hence the
4359          * init_css_set is in the subsystem's top cgroup. */
4360         init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
4361
4362         need_forkexit_callback |= ss->fork || ss->exit;
4363
4364         /* At system boot, before all subsystems have been
4365          * registered, no tasks have been forked, so we don't
4366          * need to invoke fork callbacks here. */
4367         BUG_ON(!list_empty(&init_task.tasks));
4368
4369         ss->active = 1;
4370
4371         if (ss->post_create)
4372                 ss->post_create(&ss->root->top_cgroup);
4373
4374         /* this function shouldn't be used with modular subsystems, since they
4375          * need to register a subsys_id, among other things */
4376         BUG_ON(ss->module);
4377 }
4378
4379 /**
4380  * cgroup_load_subsys: load and register a modular subsystem at runtime
4381  * @ss: the subsystem to load
4382  *
4383  * This function should be called in a modular subsystem's initcall. If the
4384  * subsystem is built as a module, it will be assigned a new subsys_id and set
4385  * up for use. If the subsystem is built-in anyway, work is delegated to the
4386  * simpler cgroup_init_subsys.
4387  */
4388 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4389 {
4390         int i;
4391         struct cgroup_subsys_state *css;
4392
4393         /* check name and function validity */
4394         if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4395             ss->create == NULL || ss->destroy == NULL)
4396                 return -EINVAL;
4397
4398         /*
4399          * we don't support callbacks in modular subsystems. this check is
4400          * before the ss->module check for consistency; a subsystem that could
4401          * be a module should still have no callbacks even if the user isn't
4402          * compiling it as one.
4403          */
4404         if (ss->fork || ss->exit)
4405                 return -EINVAL;
4406
4407         /*
4408          * an optionally modular subsystem is built-in: we want to do nothing,
4409          * since cgroup_init_subsys will have already taken care of it.
4410          */
4411         if (ss->module == NULL) {
4412                 /* a sanity check */
4413                 BUG_ON(subsys[ss->subsys_id] != ss);
4414                 return 0;
4415         }
4416
4417         /* init base cftset */
4418         cgroup_init_cftsets(ss);
4419
4420         mutex_lock(&cgroup_mutex);
4421         subsys[ss->subsys_id] = ss;
4422
4423         /*
4424          * no ss->create seems to need anything important in the ss struct, so
4425          * this can happen first (i.e. before the rootnode attachment).
4426          */
4427         css = ss->create(dummytop);
4428         if (IS_ERR(css)) {
4429                 /* failure case - need to deassign the subsys[] slot. */
4430                 subsys[ss->subsys_id] = NULL;
4431                 mutex_unlock(&cgroup_mutex);
4432                 return PTR_ERR(css);
4433         }
4434
4435         list_add(&ss->sibling, &rootnode.subsys_list);
4436         ss->root = &rootnode;
4437
4438         /* our new subsystem will be attached to the dummy hierarchy. */
4439         init_cgroup_css(css, ss, dummytop);
4440         /* init_idr must be after init_cgroup_css because it sets css->id. */
4441         if (ss->use_id) {
4442                 int ret = cgroup_init_idr(ss, css);
4443                 if (ret) {
4444                         dummytop->subsys[ss->subsys_id] = NULL;
4445                         ss->destroy(dummytop);
4446                         subsys[ss->subsys_id] = NULL;
4447                         mutex_unlock(&cgroup_mutex);
4448                         return ret;
4449                 }
4450         }
4451
4452         /*
4453          * Now we need to entangle the css into the existing css_sets. unlike
4454          * in cgroup_init_subsys, there are now multiple css_sets, so each one
4455          * will need a new pointer to it; done by iterating the css_set_table.
4456          * furthermore, modifying the existing css_sets will corrupt the hash
4457          * table state, so each changed css_set will need its hash recomputed.
4458          * this is all done under the css_set_lock.
4459          */
4460         write_lock(&css_set_lock);
4461         for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
4462                 struct css_set *cg;
4463                 struct hlist_node *node, *tmp;
4464                 struct hlist_head *bucket = &css_set_table[i], *new_bucket;
4465
4466                 hlist_for_each_entry_safe(cg, node, tmp, bucket, hlist) {
4467                         /* skip entries that we already rehashed */
4468                         if (cg->subsys[ss->subsys_id])
4469                                 continue;
4470                         /* remove existing entry */
4471                         hlist_del(&cg->hlist);
4472                         /* set new value */
4473                         cg->subsys[ss->subsys_id] = css;
4474                         /* recompute hash and restore entry */
4475                         new_bucket = css_set_hash(cg->subsys);
4476                         hlist_add_head(&cg->hlist, new_bucket);
4477                 }
4478         }
4479         write_unlock(&css_set_lock);
4480
4481         ss->active = 1;
4482
4483         if (ss->post_create)
4484                 ss->post_create(&ss->root->top_cgroup);
4485
4486         /* success! */
4487         mutex_unlock(&cgroup_mutex);
4488         return 0;
4489 }
4490 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4491
4492 /**
4493  * cgroup_unload_subsys: unload a modular subsystem
4494  * @ss: the subsystem to unload
4495  *
4496  * This function should be called in a modular subsystem's exitcall. When this
4497  * function is invoked, the refcount on the subsystem's module will be 0, so
4498  * the subsystem will not be attached to any hierarchy.
4499  */
4500 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4501 {
4502         struct cg_cgroup_link *link;
4503         struct hlist_head *hhead;
4504
4505         BUG_ON(ss->module == NULL);
4506
4507         /*
4508          * we shouldn't be called if the subsystem is in use, and the use of
4509          * try_module_get in parse_cgroupfs_options should ensure that it
4510          * doesn't start being used while we're killing it off.
4511          */
4512         BUG_ON(ss->root != &rootnode);
4513
4514         mutex_lock(&cgroup_mutex);
4515         /* deassign the subsys_id */
4516         subsys[ss->subsys_id] = NULL;
4517
4518         /* remove subsystem from rootnode's list of subsystems */
4519         list_del_init(&ss->sibling);
4520
4521         /*
4522          * disentangle the css from all css_sets attached to the dummytop. as
4523          * in loading, we need to pay our respects to the hashtable gods.
4524          */
4525         write_lock(&css_set_lock);
4526         list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
4527                 struct css_set *cg = link->cg;
4528
4529                 hlist_del(&cg->hlist);
4530                 BUG_ON(!cg->subsys[ss->subsys_id]);
4531                 cg->subsys[ss->subsys_id] = NULL;
4532                 hhead = css_set_hash(cg->subsys);
4533                 hlist_add_head(&cg->hlist, hhead);
4534         }
4535         write_unlock(&css_set_lock);
4536
4537         /*
4538          * remove subsystem's css from the dummytop and free it - need to free
4539          * before marking as null because ss->destroy needs the cgrp->subsys
4540          * pointer to find their state. note that this also takes care of
4541          * freeing the css_id.
4542          */
4543         ss->destroy(dummytop);
4544         dummytop->subsys[ss->subsys_id] = NULL;
4545
4546         mutex_unlock(&cgroup_mutex);
4547 }
4548 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4549
4550 /**
4551  * cgroup_init_early - cgroup initialization at system boot
4552  *
4553  * Initialize cgroups at system boot, and initialize any
4554  * subsystems that request early init.
4555  */
4556 int __init cgroup_init_early(void)
4557 {
4558         int i;
4559         atomic_set(&init_css_set.refcount, 1);
4560         INIT_LIST_HEAD(&init_css_set.cg_links);
4561         INIT_LIST_HEAD(&init_css_set.tasks);
4562         INIT_HLIST_NODE(&init_css_set.hlist);
4563         css_set_count = 1;
4564         init_cgroup_root(&rootnode);
4565         root_count = 1;
4566         init_task.cgroups = &init_css_set;
4567
4568         init_css_set_link.cg = &init_css_set;
4569         init_css_set_link.cgrp = dummytop;
4570         list_add(&init_css_set_link.cgrp_link_list,
4571                  &rootnode.top_cgroup.css_sets);
4572         list_add(&init_css_set_link.cg_link_list,
4573                  &init_css_set.cg_links);
4574
4575         for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
4576                 INIT_HLIST_HEAD(&css_set_table[i]);
4577
4578         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4579                 struct cgroup_subsys *ss = subsys[i];
4580
4581                 /* at bootup time, we don't worry about modular subsystems */
4582                 if (!ss || ss->module)
4583                         continue;
4584
4585                 BUG_ON(!ss->name);
4586                 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4587                 BUG_ON(!ss->create);
4588                 BUG_ON(!ss->destroy);
4589                 if (ss->subsys_id != i) {
4590                         printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4591                                ss->name, ss->subsys_id);
4592                         BUG();
4593                 }
4594
4595                 if (ss->early_init)
4596                         cgroup_init_subsys(ss);
4597         }
4598         return 0;
4599 }
4600
4601 /**
4602  * cgroup_init - cgroup initialization
4603  *
4604  * Register cgroup filesystem and /proc file, and initialize
4605  * any subsystems that didn't request early init.
4606  */
4607 int __init cgroup_init(void)
4608 {
4609         int err;
4610         int i;
4611         struct hlist_head *hhead;
4612
4613         err = bdi_init(&cgroup_backing_dev_info);
4614         if (err)
4615                 return err;
4616
4617         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4618                 struct cgroup_subsys *ss = subsys[i];
4619
4620                 /* at bootup time, we don't worry about modular subsystems */
4621                 if (!ss || ss->module)
4622                         continue;
4623                 if (!ss->early_init)
4624                         cgroup_init_subsys(ss);
4625                 if (ss->use_id)
4626                         cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4627         }
4628
4629         /* Add init_css_set to the hash table */
4630         hhead = css_set_hash(init_css_set.subsys);
4631         hlist_add_head(&init_css_set.hlist, hhead);
4632         BUG_ON(!init_root_id(&rootnode));
4633
4634         cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4635         if (!cgroup_kobj) {
4636                 err = -ENOMEM;
4637                 goto out;
4638         }
4639
4640         err = register_filesystem(&cgroup_fs_type);
4641         if (err < 0) {
4642                 kobject_put(cgroup_kobj);
4643                 goto out;
4644         }
4645
4646         proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4647
4648 out:
4649         if (err)
4650                 bdi_destroy(&cgroup_backing_dev_info);
4651
4652         return err;
4653 }
4654
4655 /*
4656  * proc_cgroup_show()
4657  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
4658  *  - Used for /proc/<pid>/cgroup.
4659  *  - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4660  *    doesn't really matter if tsk->cgroup changes after we read it,
4661  *    and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4662  *    anyway.  No need to check that tsk->cgroup != NULL, thanks to
4663  *    the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4664  *    cgroup to top_cgroup.
4665  */
4666
4667 /* TODO: Use a proper seq_file iterator */
4668 static int proc_cgroup_show(struct seq_file *m, void *v)
4669 {
4670         struct pid *pid;
4671         struct task_struct *tsk;
4672         char *buf;
4673         int retval;
4674         struct cgroupfs_root *root;
4675
4676         retval = -ENOMEM;
4677         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4678         if (!buf)
4679                 goto out;
4680
4681         retval = -ESRCH;
4682         pid = m->private;
4683         tsk = get_pid_task(pid, PIDTYPE_PID);
4684         if (!tsk)
4685                 goto out_free;
4686
4687         retval = 0;
4688
4689         mutex_lock(&cgroup_mutex);
4690
4691         for_each_active_root(root) {
4692                 struct cgroup_subsys *ss;
4693                 struct cgroup *cgrp;
4694                 int count = 0;
4695
4696                 seq_printf(m, "%d:", root->hierarchy_id);
4697                 for_each_subsys(root, ss)
4698                         seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4699                 if (strlen(root->name))
4700                         seq_printf(m, "%sname=%s", count ? "," : "",
4701                                    root->name);
4702                 seq_putc(m, ':');
4703                 cgrp = task_cgroup_from_root(tsk, root);
4704                 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4705                 if (retval < 0)
4706                         goto out_unlock;
4707                 seq_puts(m, buf);
4708                 seq_putc(m, '\n');
4709         }
4710
4711 out_unlock:
4712         mutex_unlock(&cgroup_mutex);
4713         put_task_struct(tsk);
4714 out_free:
4715         kfree(buf);
4716 out:
4717         return retval;
4718 }
4719
4720 static int cgroup_open(struct inode *inode, struct file *file)
4721 {
4722         struct pid *pid = PROC_I(inode)->pid;
4723         return single_open(file, proc_cgroup_show, pid);
4724 }
4725
4726 const struct file_operations proc_cgroup_operations = {
4727         .open           = cgroup_open,
4728         .read           = seq_read,
4729         .llseek         = seq_lseek,
4730         .release        = single_release,
4731 };
4732
4733 /* Display information about each subsystem and each hierarchy */
4734 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4735 {
4736         int i;
4737
4738         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4739         /*
4740          * ideally we don't want subsystems moving around while we do this.
4741          * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4742          * subsys/hierarchy state.
4743          */
4744         mutex_lock(&cgroup_mutex);
4745         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4746                 struct cgroup_subsys *ss = subsys[i];
4747                 if (ss == NULL)
4748                         continue;
4749                 seq_printf(m, "%s\t%d\t%d\t%d\n",
4750                            ss->name, ss->root->hierarchy_id,
4751                            ss->root->number_of_cgroups, !ss->disabled);
4752         }
4753         mutex_unlock(&cgroup_mutex);
4754         return 0;
4755 }
4756
4757 static int cgroupstats_open(struct inode *inode, struct file *file)
4758 {
4759         return single_open(file, proc_cgroupstats_show, NULL);
4760 }
4761
4762 static const struct file_operations proc_cgroupstats_operations = {
4763         .open = cgroupstats_open,
4764         .read = seq_read,
4765         .llseek = seq_lseek,
4766         .release = single_release,
4767 };
4768
4769 /**
4770  * cgroup_fork - attach newly forked task to its parents cgroup.
4771  * @child: pointer to task_struct of forking parent process.
4772  *
4773  * Description: A task inherits its parent's cgroup at fork().
4774  *
4775  * A pointer to the shared css_set was automatically copied in
4776  * fork.c by dup_task_struct().  However, we ignore that copy, since
4777  * it was not made under the protection of RCU or cgroup_mutex, so
4778  * might no longer be a valid cgroup pointer.  cgroup_attach_task() might
4779  * have already changed current->cgroups, allowing the previously
4780  * referenced cgroup group to be removed and freed.
4781  *
4782  * At the point that cgroup_fork() is called, 'current' is the parent
4783  * task, and the passed argument 'child' points to the child task.
4784  */
4785 void cgroup_fork(struct task_struct *child)
4786 {
4787         task_lock(current);
4788         child->cgroups = current->cgroups;
4789         get_css_set(child->cgroups);
4790         task_unlock(current);
4791         INIT_LIST_HEAD(&child->cg_list);
4792 }
4793
4794 /**
4795  * cgroup_post_fork - called on a new task after adding it to the task list
4796  * @child: the task in question
4797  *
4798  * Adds the task to the list running through its css_set if necessary and
4799  * call the subsystem fork() callbacks.  Has to be after the task is
4800  * visible on the task list in case we race with the first call to
4801  * cgroup_iter_start() - to guarantee that the new task ends up on its
4802  * list.
4803  */
4804 void cgroup_post_fork(struct task_struct *child)
4805 {
4806         int i;
4807
4808         /*
4809          * use_task_css_set_links is set to 1 before we walk the tasklist
4810          * under the tasklist_lock and we read it here after we added the child
4811          * to the tasklist under the tasklist_lock as well. If the child wasn't
4812          * yet in the tasklist when we walked through it from
4813          * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4814          * should be visible now due to the paired locking and barriers implied
4815          * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4816          * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4817          * lock on fork.
4818          */
4819         if (use_task_css_set_links) {
4820                 write_lock(&css_set_lock);
4821                 task_lock(child);
4822                 if (list_empty(&child->cg_list))
4823                         list_add(&child->cg_list, &child->cgroups->tasks);
4824                 task_unlock(child);
4825                 write_unlock(&css_set_lock);
4826         }
4827
4828         /*
4829          * Call ss->fork().  This must happen after @child is linked on
4830          * css_set; otherwise, @child might change state between ->fork()
4831          * and addition to css_set.
4832          */
4833         if (need_forkexit_callback) {
4834                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4835                         struct cgroup_subsys *ss = subsys[i];
4836
4837                         /*
4838                          * fork/exit callbacks are supported only for
4839                          * builtin subsystems and we don't need further
4840                          * synchronization as they never go away.
4841                          */
4842                         if (!ss || ss->module)
4843                                 continue;
4844
4845                         if (ss->fork)
4846                                 ss->fork(child);
4847                 }
4848         }
4849 }
4850
4851 /**
4852  * cgroup_exit - detach cgroup from exiting task
4853  * @tsk: pointer to task_struct of exiting process
4854  * @run_callback: run exit callbacks?
4855  *
4856  * Description: Detach cgroup from @tsk and release it.
4857  *
4858  * Note that cgroups marked notify_on_release force every task in
4859  * them to take the global cgroup_mutex mutex when exiting.
4860  * This could impact scaling on very large systems.  Be reluctant to
4861  * use notify_on_release cgroups where very high task exit scaling
4862  * is required on large systems.
4863  *
4864  * the_top_cgroup_hack:
4865  *
4866  *    Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4867  *
4868  *    We call cgroup_exit() while the task is still competent to
4869  *    handle notify_on_release(), then leave the task attached to the
4870  *    root cgroup in each hierarchy for the remainder of its exit.
4871  *
4872  *    To do this properly, we would increment the reference count on
4873  *    top_cgroup, and near the very end of the kernel/exit.c do_exit()
4874  *    code we would add a second cgroup function call, to drop that
4875  *    reference.  This would just create an unnecessary hot spot on
4876  *    the top_cgroup reference count, to no avail.
4877  *
4878  *    Normally, holding a reference to a cgroup without bumping its
4879  *    count is unsafe.   The cgroup could go away, or someone could
4880  *    attach us to a different cgroup, decrementing the count on
4881  *    the first cgroup that we never incremented.  But in this case,
4882  *    top_cgroup isn't going away, and either task has PF_EXITING set,
4883  *    which wards off any cgroup_attach_task() attempts, or task is a failed
4884  *    fork, never visible to cgroup_attach_task.
4885  */
4886 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4887 {
4888         struct css_set *cg;
4889         int i;
4890
4891         /*
4892          * Unlink from the css_set task list if necessary.
4893          * Optimistically check cg_list before taking
4894          * css_set_lock
4895          */
4896         if (!list_empty(&tsk->cg_list)) {
4897                 write_lock(&css_set_lock);
4898                 if (!list_empty(&tsk->cg_list))
4899                         list_del_init(&tsk->cg_list);
4900                 write_unlock(&css_set_lock);
4901         }
4902
4903         /* Reassign the task to the init_css_set. */
4904         task_lock(tsk);
4905         cg = tsk->cgroups;
4906         tsk->cgroups = &init_css_set;
4907
4908         if (run_callbacks && need_forkexit_callback) {
4909                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4910                         struct cgroup_subsys *ss = subsys[i];
4911
4912                         /* modular subsystems can't use callbacks */
4913                         if (!ss || ss->module)
4914                                 continue;
4915
4916                         if (ss->exit) {
4917                                 struct cgroup *old_cgrp =
4918                                         rcu_dereference_raw(cg->subsys[i])->cgroup;
4919                                 struct cgroup *cgrp = task_cgroup(tsk, i);
4920                                 ss->exit(cgrp, old_cgrp, tsk);
4921                         }
4922                 }
4923         }
4924         task_unlock(tsk);
4925
4926         if (cg)
4927                 put_css_set_taskexit(cg);
4928 }
4929
4930 /**
4931  * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
4932  * @cgrp: the cgroup in question
4933  * @task: the task in question
4934  *
4935  * See if @cgrp is a descendant of @task's cgroup in the appropriate
4936  * hierarchy.
4937  *
4938  * If we are sending in dummytop, then presumably we are creating
4939  * the top cgroup in the subsystem.
4940  *
4941  * Called only by the ns (nsproxy) cgroup.
4942  */
4943 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
4944 {
4945         int ret;
4946         struct cgroup *target;
4947
4948         if (cgrp == dummytop)
4949                 return 1;
4950
4951         target = task_cgroup_from_root(task, cgrp->root);
4952         while (cgrp != target && cgrp!= cgrp->top_cgroup)
4953                 cgrp = cgrp->parent;
4954         ret = (cgrp == target);
4955         return ret;
4956 }
4957
4958 static void check_for_release(struct cgroup *cgrp)
4959 {
4960         /* All of these checks rely on RCU to keep the cgroup
4961          * structure alive */
4962         if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
4963             && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
4964                 /* Control Group is currently removeable. If it's not
4965                  * already queued for a userspace notification, queue
4966                  * it now */
4967                 int need_schedule_work = 0;
4968                 raw_spin_lock(&release_list_lock);
4969                 if (!cgroup_is_removed(cgrp) &&
4970                     list_empty(&cgrp->release_list)) {
4971                         list_add(&cgrp->release_list, &release_list);
4972                         need_schedule_work = 1;
4973                 }
4974                 raw_spin_unlock(&release_list_lock);
4975                 if (need_schedule_work)
4976                         schedule_work(&release_agent_work);
4977         }
4978 }
4979
4980 /* Caller must verify that the css is not for root cgroup */
4981 bool __css_tryget(struct cgroup_subsys_state *css)
4982 {
4983         while (true) {
4984                 int t, v;
4985
4986                 v = css_refcnt(css);
4987                 t = atomic_cmpxchg(&css->refcnt, v, v + 1);
4988                 if (likely(t == v))
4989                         return true;
4990                 else if (t < 0)
4991                         return false;
4992                 cpu_relax();
4993         }
4994 }
4995 EXPORT_SYMBOL_GPL(__css_tryget);
4996
4997 /* Caller must verify that the css is not for root cgroup */
4998 void __css_put(struct cgroup_subsys_state *css)
4999 {
5000         struct cgroup *cgrp = css->cgroup;
5001         int v;
5002
5003         rcu_read_lock();
5004         v = css_unbias_refcnt(atomic_dec_return(&css->refcnt));
5005
5006         switch (v) {
5007         case 1:
5008                 if (notify_on_release(cgrp)) {
5009                         set_bit(CGRP_RELEASABLE, &cgrp->flags);
5010                         check_for_release(cgrp);
5011                 }
5012                 break;
5013         case 0:
5014                 schedule_work(&css->dput_work);
5015                 break;
5016         }
5017         rcu_read_unlock();
5018 }
5019 EXPORT_SYMBOL_GPL(__css_put);
5020
5021 /*
5022  * Notify userspace when a cgroup is released, by running the
5023  * configured release agent with the name of the cgroup (path
5024  * relative to the root of cgroup file system) as the argument.
5025  *
5026  * Most likely, this user command will try to rmdir this cgroup.
5027  *
5028  * This races with the possibility that some other task will be
5029  * attached to this cgroup before it is removed, or that some other
5030  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
5031  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5032  * unused, and this cgroup will be reprieved from its death sentence,
5033  * to continue to serve a useful existence.  Next time it's released,
5034  * we will get notified again, if it still has 'notify_on_release' set.
5035  *
5036  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5037  * means only wait until the task is successfully execve()'d.  The
5038  * separate release agent task is forked by call_usermodehelper(),
5039  * then control in this thread returns here, without waiting for the
5040  * release agent task.  We don't bother to wait because the caller of
5041  * this routine has no use for the exit status of the release agent
5042  * task, so no sense holding our caller up for that.
5043  */
5044 static void cgroup_release_agent(struct work_struct *work)
5045 {
5046         BUG_ON(work != &release_agent_work);
5047         mutex_lock(&cgroup_mutex);
5048         raw_spin_lock(&release_list_lock);
5049         while (!list_empty(&release_list)) {
5050                 char *argv[3], *envp[3];
5051                 int i;
5052                 char *pathbuf = NULL, *agentbuf = NULL;
5053                 struct cgroup *cgrp = list_entry(release_list.next,
5054                                                     struct cgroup,
5055                                                     release_list);
5056                 list_del_init(&cgrp->release_list);
5057                 raw_spin_unlock(&release_list_lock);
5058                 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5059                 if (!pathbuf)
5060                         goto continue_free;
5061                 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5062                         goto continue_free;
5063                 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5064                 if (!agentbuf)
5065                         goto continue_free;
5066
5067                 i = 0;
5068                 argv[i++] = agentbuf;
5069                 argv[i++] = pathbuf;
5070                 argv[i] = NULL;
5071
5072                 i = 0;
5073                 /* minimal command environment */
5074                 envp[i++] = "HOME=/";
5075                 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5076                 envp[i] = NULL;
5077
5078                 /* Drop the lock while we invoke the usermode helper,
5079                  * since the exec could involve hitting disk and hence
5080                  * be a slow process */
5081                 mutex_unlock(&cgroup_mutex);
5082                 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5083                 mutex_lock(&cgroup_mutex);
5084  continue_free:
5085                 kfree(pathbuf);
5086                 kfree(agentbuf);
5087                 raw_spin_lock(&release_list_lock);
5088         }
5089         raw_spin_unlock(&release_list_lock);
5090         mutex_unlock(&cgroup_mutex);
5091 }
5092
5093 static int __init cgroup_disable(char *str)
5094 {
5095         int i;
5096         char *token;
5097
5098         while ((token = strsep(&str, ",")) != NULL) {
5099                 if (!*token)
5100                         continue;
5101                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
5102                         struct cgroup_subsys *ss = subsys[i];
5103
5104                         /*
5105                          * cgroup_disable, being at boot time, can't
5106                          * know about module subsystems, so we don't
5107                          * worry about them.
5108                          */
5109                         if (!ss || ss->module)
5110                                 continue;
5111
5112                         if (!strcmp(token, ss->name)) {
5113                                 ss->disabled = 1;
5114                                 printk(KERN_INFO "Disabling %s control group"
5115                                         " subsystem\n", ss->name);
5116                                 break;
5117                         }
5118                 }
5119         }
5120         return 1;
5121 }
5122 __setup("cgroup_disable=", cgroup_disable);
5123
5124 /*
5125  * Functons for CSS ID.
5126  */
5127
5128 /*
5129  *To get ID other than 0, this should be called when !cgroup_is_removed().
5130  */
5131 unsigned short css_id(struct cgroup_subsys_state *css)
5132 {
5133         struct css_id *cssid;
5134
5135         /*
5136          * This css_id() can return correct value when somone has refcnt
5137          * on this or this is under rcu_read_lock(). Once css->id is allocated,
5138          * it's unchanged until freed.
5139          */
5140         cssid = rcu_dereference_check(css->id, css_refcnt(css));
5141
5142         if (cssid)
5143                 return cssid->id;
5144         return 0;
5145 }
5146 EXPORT_SYMBOL_GPL(css_id);
5147
5148 unsigned short css_depth(struct cgroup_subsys_state *css)
5149 {
5150         struct css_id *cssid;
5151
5152         cssid = rcu_dereference_check(css->id, css_refcnt(css));
5153
5154         if (cssid)
5155                 return cssid->depth;
5156         return 0;
5157 }
5158 EXPORT_SYMBOL_GPL(css_depth);
5159
5160 /**
5161  *  css_is_ancestor - test "root" css is an ancestor of "child"
5162  * @child: the css to be tested.
5163  * @root: the css supporsed to be an ancestor of the child.
5164  *
5165  * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5166  * this function reads css->id, the caller must hold rcu_read_lock().
5167  * But, considering usual usage, the csses should be valid objects after test.
5168  * Assuming that the caller will do some action to the child if this returns
5169  * returns true, the caller must take "child";s reference count.
5170  * If "child" is valid object and this returns true, "root" is valid, too.
5171  */
5172
5173 bool css_is_ancestor(struct cgroup_subsys_state *child,
5174                     const struct cgroup_subsys_state *root)
5175 {
5176         struct css_id *child_id;
5177         struct css_id *root_id;
5178
5179         child_id  = rcu_dereference(child->id);
5180         if (!child_id)
5181                 return false;
5182         root_id = rcu_dereference(root->id);
5183         if (!root_id)
5184                 return false;
5185         if (child_id->depth < root_id->depth)
5186                 return false;
5187         if (child_id->stack[root_id->depth] != root_id->id)
5188                 return false;
5189         return true;
5190 }
5191
5192 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5193 {
5194         struct css_id *id = css->id;
5195         /* When this is called before css_id initialization, id can be NULL */
5196         if (!id)
5197                 return;
5198
5199         BUG_ON(!ss->use_id);
5200
5201         rcu_assign_pointer(id->css, NULL);
5202         rcu_assign_pointer(css->id, NULL);
5203         spin_lock(&ss->id_lock);
5204         idr_remove(&ss->idr, id->id);
5205         spin_unlock(&ss->id_lock);
5206         kfree_rcu(id, rcu_head);
5207 }
5208 EXPORT_SYMBOL_GPL(free_css_id);
5209
5210 /*
5211  * This is called by init or create(). Then, calls to this function are
5212  * always serialized (By cgroup_mutex() at create()).
5213  */
5214
5215 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5216 {
5217         struct css_id *newid;
5218         int myid, error, size;
5219
5220         BUG_ON(!ss->use_id);
5221
5222         size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5223         newid = kzalloc(size, GFP_KERNEL);
5224         if (!newid)
5225                 return ERR_PTR(-ENOMEM);
5226         /* get id */
5227         if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
5228                 error = -ENOMEM;
5229                 goto err_out;
5230         }
5231         spin_lock(&ss->id_lock);
5232         /* Don't use 0. allocates an ID of 1-65535 */
5233         error = idr_get_new_above(&ss->idr, newid, 1, &myid);
5234         spin_unlock(&ss->id_lock);
5235
5236         /* Returns error when there are no free spaces for new ID.*/
5237         if (error) {
5238                 error = -ENOSPC;
5239                 goto err_out;
5240         }
5241         if (myid > CSS_ID_MAX)
5242                 goto remove_idr;
5243
5244         newid->id = myid;
5245         newid->depth = depth;
5246         return newid;
5247 remove_idr:
5248         error = -ENOSPC;
5249         spin_lock(&ss->id_lock);
5250         idr_remove(&ss->idr, myid);
5251         spin_unlock(&ss->id_lock);
5252 err_out:
5253         kfree(newid);
5254         return ERR_PTR(error);
5255
5256 }
5257
5258 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5259                                             struct cgroup_subsys_state *rootcss)
5260 {
5261         struct css_id *newid;
5262
5263         spin_lock_init(&ss->id_lock);
5264         idr_init(&ss->idr);
5265
5266         newid = get_new_cssid(ss, 0);
5267         if (IS_ERR(newid))
5268                 return PTR_ERR(newid);
5269
5270         newid->stack[0] = newid->id;
5271         newid->css = rootcss;
5272         rootcss->id = newid;
5273         return 0;
5274 }
5275
5276 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5277                         struct cgroup *child)
5278 {
5279         int subsys_id, i, depth = 0;
5280         struct cgroup_subsys_state *parent_css, *child_css;
5281         struct css_id *child_id, *parent_id;
5282
5283         subsys_id = ss->subsys_id;
5284         parent_css = parent->subsys[subsys_id];
5285         child_css = child->subsys[subsys_id];
5286         parent_id = parent_css->id;
5287         depth = parent_id->depth + 1;
5288
5289         child_id = get_new_cssid(ss, depth);
5290         if (IS_ERR(child_id))
5291                 return PTR_ERR(child_id);
5292
5293         for (i = 0; i < depth; i++)
5294                 child_id->stack[i] = parent_id->stack[i];
5295         child_id->stack[depth] = child_id->id;
5296         /*
5297          * child_id->css pointer will be set after this cgroup is available
5298          * see cgroup_populate_dir()
5299          */
5300         rcu_assign_pointer(child_css->id, child_id);
5301
5302         return 0;
5303 }
5304
5305 /**
5306  * css_lookup - lookup css by id
5307  * @ss: cgroup subsys to be looked into.
5308  * @id: the id
5309  *
5310  * Returns pointer to cgroup_subsys_state if there is valid one with id.
5311  * NULL if not. Should be called under rcu_read_lock()
5312  */
5313 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5314 {
5315         struct css_id *cssid = NULL;
5316
5317         BUG_ON(!ss->use_id);
5318         cssid = idr_find(&ss->idr, id);
5319
5320         if (unlikely(!cssid))
5321                 return NULL;
5322
5323         return rcu_dereference(cssid->css);
5324 }
5325 EXPORT_SYMBOL_GPL(css_lookup);
5326
5327 /**
5328  * css_get_next - lookup next cgroup under specified hierarchy.
5329  * @ss: pointer to subsystem
5330  * @id: current position of iteration.
5331  * @root: pointer to css. search tree under this.
5332  * @foundid: position of found object.
5333  *
5334  * Search next css under the specified hierarchy of rootid. Calling under
5335  * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
5336  */
5337 struct cgroup_subsys_state *
5338 css_get_next(struct cgroup_subsys *ss, int id,
5339              struct cgroup_subsys_state *root, int *foundid)
5340 {
5341         struct cgroup_subsys_state *ret = NULL;
5342         struct css_id *tmp;
5343         int tmpid;
5344         int rootid = css_id(root);
5345         int depth = css_depth(root);
5346
5347         if (!rootid)
5348                 return NULL;
5349
5350         BUG_ON(!ss->use_id);
5351         WARN_ON_ONCE(!rcu_read_lock_held());
5352
5353         /* fill start point for scan */
5354         tmpid = id;
5355         while (1) {
5356                 /*
5357                  * scan next entry from bitmap(tree), tmpid is updated after
5358                  * idr_get_next().
5359                  */
5360                 tmp = idr_get_next(&ss->idr, &tmpid);
5361                 if (!tmp)
5362                         break;
5363                 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
5364                         ret = rcu_dereference(tmp->css);
5365                         if (ret) {
5366                                 *foundid = tmpid;
5367                                 break;
5368                         }
5369                 }
5370                 /* continue to scan from next id */
5371                 tmpid = tmpid + 1;
5372         }
5373         return ret;
5374 }
5375
5376 /*
5377  * get corresponding css from file open on cgroupfs directory
5378  */
5379 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5380 {
5381         struct cgroup *cgrp;
5382         struct inode *inode;
5383         struct cgroup_subsys_state *css;
5384
5385         inode = f->f_dentry->d_inode;
5386         /* check in cgroup filesystem dir */
5387         if (inode->i_op != &cgroup_dir_inode_operations)
5388                 return ERR_PTR(-EBADF);
5389
5390         if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5391                 return ERR_PTR(-EINVAL);
5392
5393         /* get cgroup */
5394         cgrp = __d_cgrp(f->f_dentry);
5395         css = cgrp->subsys[id];
5396         return css ? css : ERR_PTR(-ENOENT);
5397 }
5398
5399 #ifdef CONFIG_CGROUP_DEBUG
5400 static struct cgroup_subsys_state *debug_create(struct cgroup *cont)
5401 {
5402         struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5403
5404         if (!css)
5405                 return ERR_PTR(-ENOMEM);
5406
5407         return css;
5408 }
5409
5410 static void debug_destroy(struct cgroup *cont)
5411 {
5412         kfree(cont->subsys[debug_subsys_id]);
5413 }
5414
5415 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
5416 {
5417         return atomic_read(&cont->count);
5418 }
5419
5420 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5421 {
5422         return cgroup_task_count(cont);
5423 }
5424
5425 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5426 {
5427         return (u64)(unsigned long)current->cgroups;
5428 }
5429
5430 static u64 current_css_set_refcount_read(struct cgroup *cont,
5431                                            struct cftype *cft)
5432 {
5433         u64 count;
5434
5435         rcu_read_lock();
5436         count = atomic_read(&current->cgroups->refcount);
5437         rcu_read_unlock();
5438         return count;
5439 }
5440
5441 static int current_css_set_cg_links_read(struct cgroup *cont,
5442                                          struct cftype *cft,
5443                                          struct seq_file *seq)
5444 {
5445         struct cg_cgroup_link *link;
5446         struct css_set *cg;
5447
5448         read_lock(&css_set_lock);
5449         rcu_read_lock();
5450         cg = rcu_dereference(current->cgroups);
5451         list_for_each_entry(link, &cg->cg_links, cg_link_list) {
5452                 struct cgroup *c = link->cgrp;
5453                 const char *name;
5454
5455                 if (c->dentry)
5456                         name = c->dentry->d_name.name;
5457                 else
5458                         name = "?";
5459                 seq_printf(seq, "Root %d group %s\n",
5460                            c->root->hierarchy_id, name);
5461         }
5462         rcu_read_unlock();
5463         read_unlock(&css_set_lock);
5464         return 0;
5465 }
5466
5467 #define MAX_TASKS_SHOWN_PER_CSS 25
5468 static int cgroup_css_links_read(struct cgroup *cont,
5469                                  struct cftype *cft,
5470                                  struct seq_file *seq)
5471 {
5472         struct cg_cgroup_link *link;
5473
5474         read_lock(&css_set_lock);
5475         list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
5476                 struct css_set *cg = link->cg;
5477                 struct task_struct *task;
5478                 int count = 0;
5479                 seq_printf(seq, "css_set %p\n", cg);
5480                 list_for_each_entry(task, &cg->tasks, cg_list) {
5481                         if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5482                                 seq_puts(seq, "  ...\n");
5483                                 break;
5484                         } else {
5485                                 seq_printf(seq, "  task %d\n",
5486                                            task_pid_vnr(task));
5487                         }
5488                 }
5489         }
5490         read_unlock(&css_set_lock);
5491         return 0;
5492 }
5493
5494 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5495 {
5496         return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5497 }
5498
5499 static struct cftype debug_files[] =  {
5500         {
5501                 .name = "cgroup_refcount",
5502                 .read_u64 = cgroup_refcount_read,
5503         },
5504         {
5505                 .name = "taskcount",
5506                 .read_u64 = debug_taskcount_read,
5507         },
5508
5509         {
5510                 .name = "current_css_set",
5511                 .read_u64 = current_css_set_read,
5512         },
5513
5514         {
5515                 .name = "current_css_set_refcount",
5516                 .read_u64 = current_css_set_refcount_read,
5517         },
5518
5519         {
5520                 .name = "current_css_set_cg_links",
5521                 .read_seq_string = current_css_set_cg_links_read,
5522         },
5523
5524         {
5525                 .name = "cgroup_css_links",
5526                 .read_seq_string = cgroup_css_links_read,
5527         },
5528
5529         {
5530                 .name = "releasable",
5531                 .read_u64 = releasable_read,
5532         },
5533
5534         { }     /* terminate */
5535 };
5536
5537 struct cgroup_subsys debug_subsys = {
5538         .name = "debug",
5539         .create = debug_create,
5540         .destroy = debug_destroy,
5541         .subsys_id = debug_subsys_id,
5542         .base_cftypes = debug_files,
5543 };
5544 #endif /* CONFIG_CGROUP_DEBUG */