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