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