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