2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Copyright notices from the original cpuset code:
8 * --------------------------------------------------
9 * Copyright (C) 2003 BULL SA.
10 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
12 * Portions derived from Patrick Mochel's sysfs code.
13 * sysfs is Copyright (c) 2001-3 Patrick Mochel
15 * 2003-10-10 Written by Simon Derr.
16 * 2003-10-22 Updates by Stephen Hemminger.
17 * 2004 May-July Rework by Paul Jackson.
18 * ---------------------------------------------------
20 * This file is subject to the terms and conditions of the GNU General Public
21 * License. See the file COPYING in the main directory of the Linux
22 * distribution for more details.
25 #include <linux/cgroup.h>
26 #include <linux/module.h>
27 #include <linux/ctype.h>
28 #include <linux/errno.h>
30 #include <linux/kernel.h>
31 #include <linux/list.h>
33 #include <linux/mutex.h>
34 #include <linux/mount.h>
35 #include <linux/pagemap.h>
36 #include <linux/proc_fs.h>
37 #include <linux/rcupdate.h>
38 #include <linux/sched.h>
39 #include <linux/backing-dev.h>
40 #include <linux/seq_file.h>
41 #include <linux/slab.h>
42 #include <linux/magic.h>
43 #include <linux/spinlock.h>
44 #include <linux/string.h>
45 #include <linux/sort.h>
46 #include <linux/kmod.h>
47 #include <linux/delayacct.h>
48 #include <linux/cgroupstats.h>
49 #include <linux/hash.h>
50 #include <linux/namei.h>
51 #include <linux/smp_lock.h>
52 #include <linux/pid_namespace.h>
53 #include <linux/idr.h>
54 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
56 #include <asm/atomic.h>
58 static DEFINE_MUTEX(cgroup_mutex);
61 * Generate an array of cgroup subsystem pointers. At boot time, this is
62 * populated up to CGROUP_BUILTIN_SUBSYS_COUNT, and modular subsystems are
63 * registered after that. The mutable section of this array is protected by
66 #define SUBSYS(_x) &_x ## _subsys,
67 static struct cgroup_subsys *subsys[CGROUP_SUBSYS_COUNT] = {
68 #include <linux/cgroup_subsys.h>
71 #define MAX_CGROUP_ROOT_NAMELEN 64
74 * A cgroupfs_root represents the root of a cgroup hierarchy,
75 * and may be associated with a superblock to form an active
78 struct cgroupfs_root {
79 struct super_block *sb;
82 * The bitmask of subsystems intended to be attached to this
85 unsigned long subsys_bits;
87 /* Unique id for this hierarchy. */
90 /* The bitmask of subsystems currently attached to this hierarchy */
91 unsigned long actual_subsys_bits;
93 /* A list running through the attached subsystems */
94 struct list_head subsys_list;
96 /* The root cgroup for this hierarchy */
97 struct cgroup top_cgroup;
99 /* Tracks how many cgroups are currently defined in hierarchy.*/
100 int number_of_cgroups;
102 /* A list running through the active hierarchies */
103 struct list_head root_list;
105 /* Hierarchy-specific flags */
108 /* The path to use for release notifications. */
109 char release_agent_path[PATH_MAX];
111 /* The name for this hierarchy - may be empty */
112 char name[MAX_CGROUP_ROOT_NAMELEN];
116 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
117 * subsystems that are otherwise unattached - it never has more than a
118 * single cgroup, and all tasks are part of that cgroup.
120 static struct cgroupfs_root rootnode;
123 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
124 * cgroup_subsys->use_id != 0.
126 #define CSS_ID_MAX (65535)
129 * The css to which this ID points. This pointer is set to valid value
130 * after cgroup is populated. If cgroup is removed, this will be NULL.
131 * This pointer is expected to be RCU-safe because destroy()
132 * is called after synchronize_rcu(). But for safe use, css_is_removed()
133 * css_tryget() should be used for avoiding race.
135 struct cgroup_subsys_state *css;
141 * Depth in hierarchy which this ID belongs to.
143 unsigned short depth;
145 * ID is freed by RCU. (and lookup routine is RCU safe.)
147 struct rcu_head rcu_head;
149 * Hierarchy of CSS ID belongs to.
151 unsigned short stack[0]; /* Array of Length (depth+1) */
155 /* The list of hierarchy roots */
157 static LIST_HEAD(roots);
158 static int root_count;
160 static DEFINE_IDA(hierarchy_ida);
161 static int next_hierarchy_id;
162 static DEFINE_SPINLOCK(hierarchy_id_lock);
164 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
165 #define dummytop (&rootnode.top_cgroup)
167 /* This flag indicates whether tasks in the fork and exit paths should
168 * check for fork/exit handlers to call. This avoids us having to do
169 * extra work in the fork/exit path if none of the subsystems need to
172 static int need_forkexit_callback __read_mostly;
174 #ifdef CONFIG_PROVE_LOCKING
175 int cgroup_lock_is_held(void)
177 return lockdep_is_held(&cgroup_mutex);
179 #else /* #ifdef CONFIG_PROVE_LOCKING */
180 int cgroup_lock_is_held(void)
182 return mutex_is_locked(&cgroup_mutex);
184 #endif /* #else #ifdef CONFIG_PROVE_LOCKING */
186 EXPORT_SYMBOL_GPL(cgroup_lock_is_held);
188 /* convenient tests for these bits */
189 inline int cgroup_is_removed(const struct cgroup *cgrp)
191 return test_bit(CGRP_REMOVED, &cgrp->flags);
194 /* bits in struct cgroupfs_root flags field */
196 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
199 static int cgroup_is_releasable(const struct cgroup *cgrp)
202 (1 << CGRP_RELEASABLE) |
203 (1 << CGRP_NOTIFY_ON_RELEASE);
204 return (cgrp->flags & bits) == bits;
207 static int notify_on_release(const struct cgroup *cgrp)
209 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
213 * for_each_subsys() allows you to iterate on each subsystem attached to
214 * an active hierarchy
216 #define for_each_subsys(_root, _ss) \
217 list_for_each_entry(_ss, &_root->subsys_list, sibling)
219 /* for_each_active_root() allows you to iterate across the active hierarchies */
220 #define for_each_active_root(_root) \
221 list_for_each_entry(_root, &roots, root_list)
223 /* the list of cgroups eligible for automatic release. Protected by
224 * release_list_lock */
225 static LIST_HEAD(release_list);
226 static DEFINE_SPINLOCK(release_list_lock);
227 static void cgroup_release_agent(struct work_struct *work);
228 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
229 static void check_for_release(struct cgroup *cgrp);
231 /* Link structure for associating css_set objects with cgroups */
232 struct cg_cgroup_link {
234 * List running through cg_cgroup_links associated with a
235 * cgroup, anchored on cgroup->css_sets
237 struct list_head cgrp_link_list;
240 * List running through cg_cgroup_links pointing at a
241 * single css_set object, anchored on css_set->cg_links
243 struct list_head cg_link_list;
247 /* The default css_set - used by init and its children prior to any
248 * hierarchies being mounted. It contains a pointer to the root state
249 * for each subsystem. Also used to anchor the list of css_sets. Not
250 * reference-counted, to improve performance when child cgroups
251 * haven't been created.
254 static struct css_set init_css_set;
255 static struct cg_cgroup_link init_css_set_link;
257 static int cgroup_subsys_init_idr(struct cgroup_subsys *ss);
259 /* css_set_lock protects the list of css_set objects, and the
260 * chain of tasks off each css_set. Nests outside task->alloc_lock
261 * due to cgroup_iter_start() */
262 static DEFINE_RWLOCK(css_set_lock);
263 static int css_set_count;
266 * hash table for cgroup groups. This improves the performance to find
267 * an existing css_set. This hash doesn't (currently) take into
268 * account cgroups in empty hierarchies.
270 #define CSS_SET_HASH_BITS 7
271 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
272 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
274 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
278 unsigned long tmp = 0UL;
280 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
281 tmp += (unsigned long)css[i];
282 tmp = (tmp >> 16) ^ tmp;
284 index = hash_long(tmp, CSS_SET_HASH_BITS);
286 return &css_set_table[index];
289 static void free_css_set_rcu(struct rcu_head *obj)
291 struct css_set *cg = container_of(obj, struct css_set, rcu_head);
295 /* We don't maintain the lists running through each css_set to its
296 * task until after the first call to cgroup_iter_start(). This
297 * reduces the fork()/exit() overhead for people who have cgroups
298 * compiled into their kernel but not actually in use */
299 static int use_task_css_set_links __read_mostly;
301 static void __put_css_set(struct css_set *cg, int taskexit)
303 struct cg_cgroup_link *link;
304 struct cg_cgroup_link *saved_link;
306 * Ensure that the refcount doesn't hit zero while any readers
307 * can see it. Similar to atomic_dec_and_lock(), but for an
310 if (atomic_add_unless(&cg->refcount, -1, 1))
312 write_lock(&css_set_lock);
313 if (!atomic_dec_and_test(&cg->refcount)) {
314 write_unlock(&css_set_lock);
318 /* This css_set is dead. unlink it and release cgroup refcounts */
319 hlist_del(&cg->hlist);
322 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
324 struct cgroup *cgrp = link->cgrp;
325 list_del(&link->cg_link_list);
326 list_del(&link->cgrp_link_list);
327 if (atomic_dec_and_test(&cgrp->count) &&
328 notify_on_release(cgrp)) {
330 set_bit(CGRP_RELEASABLE, &cgrp->flags);
331 check_for_release(cgrp);
337 write_unlock(&css_set_lock);
338 call_rcu(&cg->rcu_head, free_css_set_rcu);
342 * refcounted get/put for css_set objects
344 static inline void get_css_set(struct css_set *cg)
346 atomic_inc(&cg->refcount);
349 static inline void put_css_set(struct css_set *cg)
351 __put_css_set(cg, 0);
354 static inline void put_css_set_taskexit(struct css_set *cg)
356 __put_css_set(cg, 1);
360 * compare_css_sets - helper function for find_existing_css_set().
361 * @cg: candidate css_set being tested
362 * @old_cg: existing css_set for a task
363 * @new_cgrp: cgroup that's being entered by the task
364 * @template: desired set of css pointers in css_set (pre-calculated)
366 * Returns true if "cg" matches "old_cg" except for the hierarchy
367 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
369 static bool compare_css_sets(struct css_set *cg,
370 struct css_set *old_cg,
371 struct cgroup *new_cgrp,
372 struct cgroup_subsys_state *template[])
374 struct list_head *l1, *l2;
376 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
377 /* Not all subsystems matched */
382 * Compare cgroup pointers in order to distinguish between
383 * different cgroups in heirarchies with no subsystems. We
384 * could get by with just this check alone (and skip the
385 * memcmp above) but on most setups the memcmp check will
386 * avoid the need for this more expensive check on almost all
391 l2 = &old_cg->cg_links;
393 struct cg_cgroup_link *cgl1, *cgl2;
394 struct cgroup *cg1, *cg2;
398 /* See if we reached the end - both lists are equal length. */
399 if (l1 == &cg->cg_links) {
400 BUG_ON(l2 != &old_cg->cg_links);
403 BUG_ON(l2 == &old_cg->cg_links);
405 /* Locate the cgroups associated with these links. */
406 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
407 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
410 /* Hierarchies should be linked in the same order. */
411 BUG_ON(cg1->root != cg2->root);
414 * If this hierarchy is the hierarchy of the cgroup
415 * that's changing, then we need to check that this
416 * css_set points to the new cgroup; if it's any other
417 * hierarchy, then this css_set should point to the
418 * same cgroup as the old css_set.
420 if (cg1->root == new_cgrp->root) {
432 * find_existing_css_set() is a helper for
433 * find_css_set(), and checks to see whether an existing
434 * css_set is suitable.
436 * oldcg: the cgroup group that we're using before the cgroup
439 * cgrp: the cgroup that we're moving into
441 * template: location in which to build the desired set of subsystem
442 * state objects for the new cgroup group
444 static struct css_set *find_existing_css_set(
445 struct css_set *oldcg,
447 struct cgroup_subsys_state *template[])
450 struct cgroupfs_root *root = cgrp->root;
451 struct hlist_head *hhead;
452 struct hlist_node *node;
456 * Build the set of subsystem state objects that we want to see in the
457 * new css_set. while subsystems can change globally, the entries here
458 * won't change, so no need for locking.
460 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
461 if (root->subsys_bits & (1UL << i)) {
462 /* Subsystem is in this hierarchy. So we want
463 * the subsystem state from the new
465 template[i] = cgrp->subsys[i];
467 /* Subsystem is not in this hierarchy, so we
468 * don't want to change the subsystem state */
469 template[i] = oldcg->subsys[i];
473 hhead = css_set_hash(template);
474 hlist_for_each_entry(cg, node, hhead, hlist) {
475 if (!compare_css_sets(cg, oldcg, cgrp, template))
478 /* This css_set matches what we need */
482 /* No existing cgroup group matched */
486 static void free_cg_links(struct list_head *tmp)
488 struct cg_cgroup_link *link;
489 struct cg_cgroup_link *saved_link;
491 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
492 list_del(&link->cgrp_link_list);
498 * allocate_cg_links() allocates "count" cg_cgroup_link structures
499 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
500 * success or a negative error
502 static int allocate_cg_links(int count, struct list_head *tmp)
504 struct cg_cgroup_link *link;
507 for (i = 0; i < count; i++) {
508 link = kmalloc(sizeof(*link), GFP_KERNEL);
513 list_add(&link->cgrp_link_list, tmp);
519 * link_css_set - a helper function to link a css_set to a cgroup
520 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
521 * @cg: the css_set to be linked
522 * @cgrp: the destination cgroup
524 static void link_css_set(struct list_head *tmp_cg_links,
525 struct css_set *cg, struct cgroup *cgrp)
527 struct cg_cgroup_link *link;
529 BUG_ON(list_empty(tmp_cg_links));
530 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
534 atomic_inc(&cgrp->count);
535 list_move(&link->cgrp_link_list, &cgrp->css_sets);
537 * Always add links to the tail of the list so that the list
538 * is sorted by order of hierarchy creation
540 list_add_tail(&link->cg_link_list, &cg->cg_links);
544 * find_css_set() takes an existing cgroup group and a
545 * cgroup object, and returns a css_set object that's
546 * equivalent to the old group, but with the given cgroup
547 * substituted into the appropriate hierarchy. Must be called with
550 static struct css_set *find_css_set(
551 struct css_set *oldcg, struct cgroup *cgrp)
554 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
556 struct list_head tmp_cg_links;
558 struct hlist_head *hhead;
559 struct cg_cgroup_link *link;
561 /* First see if we already have a cgroup group that matches
563 read_lock(&css_set_lock);
564 res = find_existing_css_set(oldcg, cgrp, template);
567 read_unlock(&css_set_lock);
572 res = kmalloc(sizeof(*res), GFP_KERNEL);
576 /* Allocate all the cg_cgroup_link objects that we'll need */
577 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
582 atomic_set(&res->refcount, 1);
583 INIT_LIST_HEAD(&res->cg_links);
584 INIT_LIST_HEAD(&res->tasks);
585 INIT_HLIST_NODE(&res->hlist);
587 /* Copy the set of subsystem state objects generated in
588 * find_existing_css_set() */
589 memcpy(res->subsys, template, sizeof(res->subsys));
591 write_lock(&css_set_lock);
592 /* Add reference counts and links from the new css_set. */
593 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
594 struct cgroup *c = link->cgrp;
595 if (c->root == cgrp->root)
597 link_css_set(&tmp_cg_links, res, c);
600 BUG_ON(!list_empty(&tmp_cg_links));
604 /* Add this cgroup group to the hash table */
605 hhead = css_set_hash(res->subsys);
606 hlist_add_head(&res->hlist, hhead);
608 write_unlock(&css_set_lock);
614 * Return the cgroup for "task" from the given hierarchy. Must be
615 * called with cgroup_mutex held.
617 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
618 struct cgroupfs_root *root)
621 struct cgroup *res = NULL;
623 BUG_ON(!mutex_is_locked(&cgroup_mutex));
624 read_lock(&css_set_lock);
626 * No need to lock the task - since we hold cgroup_mutex the
627 * task can't change groups, so the only thing that can happen
628 * is that it exits and its css is set back to init_css_set.
631 if (css == &init_css_set) {
632 res = &root->top_cgroup;
634 struct cg_cgroup_link *link;
635 list_for_each_entry(link, &css->cg_links, cg_link_list) {
636 struct cgroup *c = link->cgrp;
637 if (c->root == root) {
643 read_unlock(&css_set_lock);
649 * There is one global cgroup mutex. We also require taking
650 * task_lock() when dereferencing a task's cgroup subsys pointers.
651 * See "The task_lock() exception", at the end of this comment.
653 * A task must hold cgroup_mutex to modify cgroups.
655 * Any task can increment and decrement the count field without lock.
656 * So in general, code holding cgroup_mutex can't rely on the count
657 * field not changing. However, if the count goes to zero, then only
658 * cgroup_attach_task() can increment it again. Because a count of zero
659 * means that no tasks are currently attached, therefore there is no
660 * way a task attached to that cgroup can fork (the other way to
661 * increment the count). So code holding cgroup_mutex can safely
662 * assume that if the count is zero, it will stay zero. Similarly, if
663 * a task holds cgroup_mutex on a cgroup with zero count, it
664 * knows that the cgroup won't be removed, as cgroup_rmdir()
667 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
668 * (usually) take cgroup_mutex. These are the two most performance
669 * critical pieces of code here. The exception occurs on cgroup_exit(),
670 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
671 * is taken, and if the cgroup count is zero, a usermode call made
672 * to the release agent with the name of the cgroup (path relative to
673 * the root of cgroup file system) as the argument.
675 * A cgroup can only be deleted if both its 'count' of using tasks
676 * is zero, and its list of 'children' cgroups is empty. Since all
677 * tasks in the system use _some_ cgroup, and since there is always at
678 * least one task in the system (init, pid == 1), therefore, top_cgroup
679 * always has either children cgroups and/or using tasks. So we don't
680 * need a special hack to ensure that top_cgroup cannot be deleted.
682 * The task_lock() exception
684 * The need for this exception arises from the action of
685 * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
686 * another. It does so using cgroup_mutex, however there are
687 * several performance critical places that need to reference
688 * task->cgroup without the expense of grabbing a system global
689 * mutex. Therefore except as noted below, when dereferencing or, as
690 * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
691 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
692 * the task_struct routinely used for such matters.
694 * P.S. One more locking exception. RCU is used to guard the
695 * update of a tasks cgroup pointer by cgroup_attach_task()
699 * cgroup_lock - lock out any changes to cgroup structures
702 void cgroup_lock(void)
704 mutex_lock(&cgroup_mutex);
708 * cgroup_unlock - release lock on cgroup changes
710 * Undo the lock taken in a previous cgroup_lock() call.
712 void cgroup_unlock(void)
714 mutex_unlock(&cgroup_mutex);
718 * A couple of forward declarations required, due to cyclic reference loop:
719 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
720 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
724 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
725 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
726 static int cgroup_populate_dir(struct cgroup *cgrp);
727 static const struct inode_operations cgroup_dir_inode_operations;
728 static const struct file_operations proc_cgroupstats_operations;
730 static struct backing_dev_info cgroup_backing_dev_info = {
732 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
735 static int alloc_css_id(struct cgroup_subsys *ss,
736 struct cgroup *parent, struct cgroup *child);
738 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
740 struct inode *inode = new_inode(sb);
743 inode->i_mode = mode;
744 inode->i_uid = current_fsuid();
745 inode->i_gid = current_fsgid();
746 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
747 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
753 * Call subsys's pre_destroy handler.
754 * This is called before css refcnt check.
756 static int cgroup_call_pre_destroy(struct cgroup *cgrp)
758 struct cgroup_subsys *ss;
761 for_each_subsys(cgrp->root, ss)
762 if (ss->pre_destroy) {
763 ret = ss->pre_destroy(ss, cgrp);
770 static void free_cgroup_rcu(struct rcu_head *obj)
772 struct cgroup *cgrp = container_of(obj, struct cgroup, rcu_head);
777 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
779 /* is dentry a directory ? if so, kfree() associated cgroup */
780 if (S_ISDIR(inode->i_mode)) {
781 struct cgroup *cgrp = dentry->d_fsdata;
782 struct cgroup_subsys *ss;
783 BUG_ON(!(cgroup_is_removed(cgrp)));
784 /* It's possible for external users to be holding css
785 * reference counts on a cgroup; css_put() needs to
786 * be able to access the cgroup after decrementing
787 * the reference count in order to know if it needs to
788 * queue the cgroup to be handled by the release
792 mutex_lock(&cgroup_mutex);
794 * Release the subsystem state objects.
796 for_each_subsys(cgrp->root, ss)
797 ss->destroy(ss, cgrp);
799 cgrp->root->number_of_cgroups--;
800 mutex_unlock(&cgroup_mutex);
803 * Drop the active superblock reference that we took when we
806 deactivate_super(cgrp->root->sb);
809 * if we're getting rid of the cgroup, refcount should ensure
810 * that there are no pidlists left.
812 BUG_ON(!list_empty(&cgrp->pidlists));
814 call_rcu(&cgrp->rcu_head, free_cgroup_rcu);
819 static void remove_dir(struct dentry *d)
821 struct dentry *parent = dget(d->d_parent);
824 simple_rmdir(parent->d_inode, d);
828 static void cgroup_clear_directory(struct dentry *dentry)
830 struct list_head *node;
832 BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
833 spin_lock(&dcache_lock);
834 node = dentry->d_subdirs.next;
835 while (node != &dentry->d_subdirs) {
836 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
839 /* This should never be called on a cgroup
840 * directory with child cgroups */
841 BUG_ON(d->d_inode->i_mode & S_IFDIR);
843 spin_unlock(&dcache_lock);
845 simple_unlink(dentry->d_inode, d);
847 spin_lock(&dcache_lock);
849 node = dentry->d_subdirs.next;
851 spin_unlock(&dcache_lock);
855 * NOTE : the dentry must have been dget()'ed
857 static void cgroup_d_remove_dir(struct dentry *dentry)
859 cgroup_clear_directory(dentry);
861 spin_lock(&dcache_lock);
862 list_del_init(&dentry->d_u.d_child);
863 spin_unlock(&dcache_lock);
868 * A queue for waiters to do rmdir() cgroup. A tasks will sleep when
869 * cgroup->count == 0 && list_empty(&cgroup->children) && subsys has some
870 * reference to css->refcnt. In general, this refcnt is expected to goes down
873 * CGRP_WAIT_ON_RMDIR flag is set under cgroup's inode->i_mutex;
875 DECLARE_WAIT_QUEUE_HEAD(cgroup_rmdir_waitq);
877 static void cgroup_wakeup_rmdir_waiter(struct cgroup *cgrp)
879 if (unlikely(test_and_clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags)))
880 wake_up_all(&cgroup_rmdir_waitq);
883 void cgroup_exclude_rmdir(struct cgroup_subsys_state *css)
888 void cgroup_release_and_wakeup_rmdir(struct cgroup_subsys_state *css)
890 cgroup_wakeup_rmdir_waiter(css->cgroup);
895 * Call with cgroup_mutex held.
897 static int rebind_subsystems(struct cgroupfs_root *root,
898 unsigned long final_bits)
900 unsigned long added_bits, removed_bits;
901 struct cgroup *cgrp = &root->top_cgroup;
904 BUG_ON(!mutex_is_locked(&cgroup_mutex));
906 removed_bits = root->actual_subsys_bits & ~final_bits;
907 added_bits = final_bits & ~root->actual_subsys_bits;
908 /* Check that any added subsystems are currently free */
909 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
910 unsigned long bit = 1UL << i;
911 struct cgroup_subsys *ss = subsys[i];
912 if (!(bit & added_bits))
915 * Nobody should tell us to do a subsys that doesn't exist:
916 * parse_cgroupfs_options should catch that case and refcounts
917 * ensure that subsystems won't disappear once selected.
920 if (ss->root != &rootnode) {
921 /* Subsystem isn't free */
926 /* Currently we don't handle adding/removing subsystems when
927 * any child cgroups exist. This is theoretically supportable
928 * but involves complex error handling, so it's being left until
930 if (root->number_of_cgroups > 1)
933 /* Process each subsystem */
934 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
935 struct cgroup_subsys *ss = subsys[i];
936 unsigned long bit = 1UL << i;
937 if (bit & added_bits) {
938 /* We're binding this subsystem to this hierarchy */
940 BUG_ON(cgrp->subsys[i]);
941 BUG_ON(!dummytop->subsys[i]);
942 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
943 mutex_lock(&ss->hierarchy_mutex);
944 cgrp->subsys[i] = dummytop->subsys[i];
945 cgrp->subsys[i]->cgroup = cgrp;
946 list_move(&ss->sibling, &root->subsys_list);
950 mutex_unlock(&ss->hierarchy_mutex);
951 } else if (bit & removed_bits) {
952 /* We're removing this subsystem */
954 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
955 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
956 mutex_lock(&ss->hierarchy_mutex);
958 ss->bind(ss, dummytop);
959 dummytop->subsys[i]->cgroup = dummytop;
960 cgrp->subsys[i] = NULL;
961 subsys[i]->root = &rootnode;
962 list_move(&ss->sibling, &rootnode.subsys_list);
963 mutex_unlock(&ss->hierarchy_mutex);
964 } else if (bit & final_bits) {
965 /* Subsystem state should already exist */
967 BUG_ON(!cgrp->subsys[i]);
969 /* Subsystem state shouldn't exist */
970 BUG_ON(cgrp->subsys[i]);
973 root->subsys_bits = root->actual_subsys_bits = final_bits;
979 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
981 struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
982 struct cgroup_subsys *ss;
984 mutex_lock(&cgroup_mutex);
985 for_each_subsys(root, ss)
986 seq_printf(seq, ",%s", ss->name);
987 if (test_bit(ROOT_NOPREFIX, &root->flags))
988 seq_puts(seq, ",noprefix");
989 if (strlen(root->release_agent_path))
990 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
991 if (strlen(root->name))
992 seq_printf(seq, ",name=%s", root->name);
993 mutex_unlock(&cgroup_mutex);
997 struct cgroup_sb_opts {
998 unsigned long subsys_bits;
1000 char *release_agent;
1002 /* User explicitly requested empty subsystem */
1005 struct cgroupfs_root *new_root;
1010 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1011 * with cgroup_mutex held to protect the subsys[] array.
1013 static int parse_cgroupfs_options(char *data,
1014 struct cgroup_sb_opts *opts)
1016 char *token, *o = data ?: "all";
1017 unsigned long mask = (unsigned long)-1;
1019 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1021 #ifdef CONFIG_CPUSETS
1022 mask = ~(1UL << cpuset_subsys_id);
1025 memset(opts, 0, sizeof(*opts));
1027 while ((token = strsep(&o, ",")) != NULL) {
1030 if (!strcmp(token, "all")) {
1031 /* Add all non-disabled subsystems */
1033 opts->subsys_bits = 0;
1034 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1035 struct cgroup_subsys *ss = subsys[i];
1039 opts->subsys_bits |= 1ul << i;
1041 } else if (!strcmp(token, "none")) {
1042 /* Explicitly have no subsystems */
1044 } else if (!strcmp(token, "noprefix")) {
1045 set_bit(ROOT_NOPREFIX, &opts->flags);
1046 } else if (!strncmp(token, "release_agent=", 14)) {
1047 /* Specifying two release agents is forbidden */
1048 if (opts->release_agent)
1050 opts->release_agent =
1051 kstrndup(token + 14, PATH_MAX, GFP_KERNEL);
1052 if (!opts->release_agent)
1054 } else if (!strncmp(token, "name=", 5)) {
1056 const char *name = token + 5;
1057 /* Can't specify an empty name */
1060 /* Must match [\w.-]+ */
1061 for (i = 0; i < strlen(name); i++) {
1065 if ((c == '.') || (c == '-') || (c == '_'))
1069 /* Specifying two names is forbidden */
1072 opts->name = kstrndup(name,
1073 MAX_CGROUP_ROOT_NAMELEN,
1078 struct cgroup_subsys *ss;
1080 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1084 if (!strcmp(token, ss->name)) {
1086 set_bit(i, &opts->subsys_bits);
1090 if (i == CGROUP_SUBSYS_COUNT)
1095 /* Consistency checks */
1098 * Option noprefix was introduced just for backward compatibility
1099 * with the old cpuset, so we allow noprefix only if mounting just
1100 * the cpuset subsystem.
1102 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1103 (opts->subsys_bits & mask))
1107 /* Can't specify "none" and some subsystems */
1108 if (opts->subsys_bits && opts->none)
1112 * We either have to specify by name or by subsystems. (So all
1113 * empty hierarchies must have a name).
1115 if (!opts->subsys_bits && !opts->name)
1121 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1124 struct cgroupfs_root *root = sb->s_fs_info;
1125 struct cgroup *cgrp = &root->top_cgroup;
1126 struct cgroup_sb_opts opts;
1129 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1130 mutex_lock(&cgroup_mutex);
1132 /* See what subsystems are wanted */
1133 ret = parse_cgroupfs_options(data, &opts);
1137 /* Don't allow flags to change at remount */
1138 if (opts.flags != root->flags) {
1143 /* Don't allow name to change at remount */
1144 if (opts.name && strcmp(opts.name, root->name)) {
1149 ret = rebind_subsystems(root, opts.subsys_bits);
1153 /* (re)populate subsystem files */
1154 cgroup_populate_dir(cgrp);
1156 if (opts.release_agent)
1157 strcpy(root->release_agent_path, opts.release_agent);
1159 kfree(opts.release_agent);
1161 mutex_unlock(&cgroup_mutex);
1162 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1167 static const struct super_operations cgroup_ops = {
1168 .statfs = simple_statfs,
1169 .drop_inode = generic_delete_inode,
1170 .show_options = cgroup_show_options,
1171 .remount_fs = cgroup_remount,
1174 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1176 INIT_LIST_HEAD(&cgrp->sibling);
1177 INIT_LIST_HEAD(&cgrp->children);
1178 INIT_LIST_HEAD(&cgrp->css_sets);
1179 INIT_LIST_HEAD(&cgrp->release_list);
1180 INIT_LIST_HEAD(&cgrp->pidlists);
1181 mutex_init(&cgrp->pidlist_mutex);
1184 static void init_cgroup_root(struct cgroupfs_root *root)
1186 struct cgroup *cgrp = &root->top_cgroup;
1187 INIT_LIST_HEAD(&root->subsys_list);
1188 INIT_LIST_HEAD(&root->root_list);
1189 root->number_of_cgroups = 1;
1191 cgrp->top_cgroup = cgrp;
1192 init_cgroup_housekeeping(cgrp);
1195 static bool init_root_id(struct cgroupfs_root *root)
1200 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1202 spin_lock(&hierarchy_id_lock);
1203 /* Try to allocate the next unused ID */
1204 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1205 &root->hierarchy_id);
1207 /* Try again starting from 0 */
1208 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1210 next_hierarchy_id = root->hierarchy_id + 1;
1211 } else if (ret != -EAGAIN) {
1212 /* Can only get here if the 31-bit IDR is full ... */
1215 spin_unlock(&hierarchy_id_lock);
1220 static int cgroup_test_super(struct super_block *sb, void *data)
1222 struct cgroup_sb_opts *opts = data;
1223 struct cgroupfs_root *root = sb->s_fs_info;
1225 /* If we asked for a name then it must match */
1226 if (opts->name && strcmp(opts->name, root->name))
1230 * If we asked for subsystems (or explicitly for no
1231 * subsystems) then they must match
1233 if ((opts->subsys_bits || opts->none)
1234 && (opts->subsys_bits != root->subsys_bits))
1240 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1242 struct cgroupfs_root *root;
1244 if (!opts->subsys_bits && !opts->none)
1247 root = kzalloc(sizeof(*root), GFP_KERNEL);
1249 return ERR_PTR(-ENOMEM);
1251 if (!init_root_id(root)) {
1253 return ERR_PTR(-ENOMEM);
1255 init_cgroup_root(root);
1257 root->subsys_bits = opts->subsys_bits;
1258 root->flags = opts->flags;
1259 if (opts->release_agent)
1260 strcpy(root->release_agent_path, opts->release_agent);
1262 strcpy(root->name, opts->name);
1266 static void cgroup_drop_root(struct cgroupfs_root *root)
1271 BUG_ON(!root->hierarchy_id);
1272 spin_lock(&hierarchy_id_lock);
1273 ida_remove(&hierarchy_ida, root->hierarchy_id);
1274 spin_unlock(&hierarchy_id_lock);
1278 static int cgroup_set_super(struct super_block *sb, void *data)
1281 struct cgroup_sb_opts *opts = data;
1283 /* If we don't have a new root, we can't set up a new sb */
1284 if (!opts->new_root)
1287 BUG_ON(!opts->subsys_bits && !opts->none);
1289 ret = set_anon_super(sb, NULL);
1293 sb->s_fs_info = opts->new_root;
1294 opts->new_root->sb = sb;
1296 sb->s_blocksize = PAGE_CACHE_SIZE;
1297 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1298 sb->s_magic = CGROUP_SUPER_MAGIC;
1299 sb->s_op = &cgroup_ops;
1304 static int cgroup_get_rootdir(struct super_block *sb)
1306 struct inode *inode =
1307 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1308 struct dentry *dentry;
1313 inode->i_fop = &simple_dir_operations;
1314 inode->i_op = &cgroup_dir_inode_operations;
1315 /* directories start off with i_nlink == 2 (for "." entry) */
1317 dentry = d_alloc_root(inode);
1322 sb->s_root = dentry;
1326 static int cgroup_get_sb(struct file_system_type *fs_type,
1327 int flags, const char *unused_dev_name,
1328 void *data, struct vfsmount *mnt)
1330 struct cgroup_sb_opts opts;
1331 struct cgroupfs_root *root;
1333 struct super_block *sb;
1334 struct cgroupfs_root *new_root;
1336 /* First find the desired set of subsystems */
1337 mutex_lock(&cgroup_mutex);
1338 ret = parse_cgroupfs_options(data, &opts);
1339 mutex_unlock(&cgroup_mutex);
1344 * Allocate a new cgroup root. We may not need it if we're
1345 * reusing an existing hierarchy.
1347 new_root = cgroup_root_from_opts(&opts);
1348 if (IS_ERR(new_root)) {
1349 ret = PTR_ERR(new_root);
1352 opts.new_root = new_root;
1354 /* Locate an existing or new sb for this hierarchy */
1355 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, &opts);
1358 cgroup_drop_root(opts.new_root);
1362 root = sb->s_fs_info;
1364 if (root == opts.new_root) {
1365 /* We used the new root structure, so this is a new hierarchy */
1366 struct list_head tmp_cg_links;
1367 struct cgroup *root_cgrp = &root->top_cgroup;
1368 struct inode *inode;
1369 struct cgroupfs_root *existing_root;
1372 BUG_ON(sb->s_root != NULL);
1374 ret = cgroup_get_rootdir(sb);
1376 goto drop_new_super;
1377 inode = sb->s_root->d_inode;
1379 mutex_lock(&inode->i_mutex);
1380 mutex_lock(&cgroup_mutex);
1382 if (strlen(root->name)) {
1383 /* Check for name clashes with existing mounts */
1384 for_each_active_root(existing_root) {
1385 if (!strcmp(existing_root->name, root->name)) {
1387 mutex_unlock(&cgroup_mutex);
1388 mutex_unlock(&inode->i_mutex);
1389 goto drop_new_super;
1395 * We're accessing css_set_count without locking
1396 * css_set_lock here, but that's OK - it can only be
1397 * increased by someone holding cgroup_lock, and
1398 * that's us. The worst that can happen is that we
1399 * have some link structures left over
1401 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1403 mutex_unlock(&cgroup_mutex);
1404 mutex_unlock(&inode->i_mutex);
1405 goto drop_new_super;
1408 ret = rebind_subsystems(root, root->subsys_bits);
1409 if (ret == -EBUSY) {
1410 mutex_unlock(&cgroup_mutex);
1411 mutex_unlock(&inode->i_mutex);
1412 free_cg_links(&tmp_cg_links);
1413 goto drop_new_super;
1416 /* EBUSY should be the only error here */
1419 list_add(&root->root_list, &roots);
1422 sb->s_root->d_fsdata = root_cgrp;
1423 root->top_cgroup.dentry = sb->s_root;
1425 /* Link the top cgroup in this hierarchy into all
1426 * the css_set objects */
1427 write_lock(&css_set_lock);
1428 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1429 struct hlist_head *hhead = &css_set_table[i];
1430 struct hlist_node *node;
1433 hlist_for_each_entry(cg, node, hhead, hlist)
1434 link_css_set(&tmp_cg_links, cg, root_cgrp);
1436 write_unlock(&css_set_lock);
1438 free_cg_links(&tmp_cg_links);
1440 BUG_ON(!list_empty(&root_cgrp->sibling));
1441 BUG_ON(!list_empty(&root_cgrp->children));
1442 BUG_ON(root->number_of_cgroups != 1);
1444 cgroup_populate_dir(root_cgrp);
1445 mutex_unlock(&cgroup_mutex);
1446 mutex_unlock(&inode->i_mutex);
1449 * We re-used an existing hierarchy - the new root (if
1450 * any) is not needed
1452 cgroup_drop_root(opts.new_root);
1455 simple_set_mnt(mnt, sb);
1456 kfree(opts.release_agent);
1461 deactivate_locked_super(sb);
1463 kfree(opts.release_agent);
1469 static void cgroup_kill_sb(struct super_block *sb) {
1470 struct cgroupfs_root *root = sb->s_fs_info;
1471 struct cgroup *cgrp = &root->top_cgroup;
1473 struct cg_cgroup_link *link;
1474 struct cg_cgroup_link *saved_link;
1478 BUG_ON(root->number_of_cgroups != 1);
1479 BUG_ON(!list_empty(&cgrp->children));
1480 BUG_ON(!list_empty(&cgrp->sibling));
1482 mutex_lock(&cgroup_mutex);
1484 /* Rebind all subsystems back to the default hierarchy */
1485 ret = rebind_subsystems(root, 0);
1486 /* Shouldn't be able to fail ... */
1490 * Release all the links from css_sets to this hierarchy's
1493 write_lock(&css_set_lock);
1495 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1497 list_del(&link->cg_link_list);
1498 list_del(&link->cgrp_link_list);
1501 write_unlock(&css_set_lock);
1503 if (!list_empty(&root->root_list)) {
1504 list_del(&root->root_list);
1508 mutex_unlock(&cgroup_mutex);
1510 kill_litter_super(sb);
1511 cgroup_drop_root(root);
1514 static struct file_system_type cgroup_fs_type = {
1516 .get_sb = cgroup_get_sb,
1517 .kill_sb = cgroup_kill_sb,
1520 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1522 return dentry->d_fsdata;
1525 static inline struct cftype *__d_cft(struct dentry *dentry)
1527 return dentry->d_fsdata;
1531 * cgroup_path - generate the path of a cgroup
1532 * @cgrp: the cgroup in question
1533 * @buf: the buffer to write the path into
1534 * @buflen: the length of the buffer
1536 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1537 * reference. Writes path of cgroup into buf. Returns 0 on success,
1540 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1543 struct dentry *dentry = rcu_dereference(cgrp->dentry);
1545 if (!dentry || cgrp == dummytop) {
1547 * Inactive subsystems have no dentry for their root
1554 start = buf + buflen;
1558 int len = dentry->d_name.len;
1559 if ((start -= len) < buf)
1560 return -ENAMETOOLONG;
1561 memcpy(start, cgrp->dentry->d_name.name, len);
1562 cgrp = cgrp->parent;
1565 dentry = rcu_dereference(cgrp->dentry);
1569 return -ENAMETOOLONG;
1572 memmove(buf, start, buf + buflen - start);
1577 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1578 * @cgrp: the cgroup the task is attaching to
1579 * @tsk: the task to be attached
1581 * Call holding cgroup_mutex. May take task_lock of
1582 * the task 'tsk' during call.
1584 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1587 struct cgroup_subsys *ss, *failed_ss = NULL;
1588 struct cgroup *oldcgrp;
1590 struct css_set *newcg;
1591 struct cgroupfs_root *root = cgrp->root;
1593 /* Nothing to do if the task is already in that cgroup */
1594 oldcgrp = task_cgroup_from_root(tsk, root);
1595 if (cgrp == oldcgrp)
1598 for_each_subsys(root, ss) {
1599 if (ss->can_attach) {
1600 retval = ss->can_attach(ss, cgrp, tsk, false);
1603 * Remember on which subsystem the can_attach()
1604 * failed, so that we only call cancel_attach()
1605 * against the subsystems whose can_attach()
1606 * succeeded. (See below)
1619 * Locate or allocate a new css_set for this task,
1620 * based on its final set of cgroups
1622 newcg = find_css_set(cg, cgrp);
1630 if (tsk->flags & PF_EXITING) {
1636 rcu_assign_pointer(tsk->cgroups, newcg);
1639 /* Update the css_set linked lists if we're using them */
1640 write_lock(&css_set_lock);
1641 if (!list_empty(&tsk->cg_list)) {
1642 list_del(&tsk->cg_list);
1643 list_add(&tsk->cg_list, &newcg->tasks);
1645 write_unlock(&css_set_lock);
1647 for_each_subsys(root, ss) {
1649 ss->attach(ss, cgrp, oldcgrp, tsk, false);
1651 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1656 * wake up rmdir() waiter. the rmdir should fail since the cgroup
1657 * is no longer empty.
1659 cgroup_wakeup_rmdir_waiter(cgrp);
1662 for_each_subsys(root, ss) {
1663 if (ss == failed_ss)
1665 * This subsystem was the one that failed the
1666 * can_attach() check earlier, so we don't need
1667 * to call cancel_attach() against it or any
1668 * remaining subsystems.
1671 if (ss->cancel_attach)
1672 ss->cancel_attach(ss, cgrp, tsk, false);
1679 * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
1680 * held. May take task_lock of task
1682 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
1684 struct task_struct *tsk;
1685 const struct cred *cred = current_cred(), *tcred;
1690 tsk = find_task_by_vpid(pid);
1691 if (!tsk || tsk->flags & PF_EXITING) {
1696 tcred = __task_cred(tsk);
1698 cred->euid != tcred->uid &&
1699 cred->euid != tcred->suid) {
1703 get_task_struct(tsk);
1707 get_task_struct(tsk);
1710 ret = cgroup_attach_task(cgrp, tsk);
1711 put_task_struct(tsk);
1715 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
1718 if (!cgroup_lock_live_group(cgrp))
1720 ret = attach_task_by_pid(cgrp, pid);
1726 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1727 * @cgrp: the cgroup to be checked for liveness
1729 * On success, returns true; the lock should be later released with
1730 * cgroup_unlock(). On failure returns false with no lock held.
1732 bool cgroup_lock_live_group(struct cgroup *cgrp)
1734 mutex_lock(&cgroup_mutex);
1735 if (cgroup_is_removed(cgrp)) {
1736 mutex_unlock(&cgroup_mutex);
1742 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1745 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1746 if (!cgroup_lock_live_group(cgrp))
1748 strcpy(cgrp->root->release_agent_path, buffer);
1753 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1754 struct seq_file *seq)
1756 if (!cgroup_lock_live_group(cgrp))
1758 seq_puts(seq, cgrp->root->release_agent_path);
1759 seq_putc(seq, '\n');
1764 /* A buffer size big enough for numbers or short strings */
1765 #define CGROUP_LOCAL_BUFFER_SIZE 64
1767 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1769 const char __user *userbuf,
1770 size_t nbytes, loff_t *unused_ppos)
1772 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1778 if (nbytes >= sizeof(buffer))
1780 if (copy_from_user(buffer, userbuf, nbytes))
1783 buffer[nbytes] = 0; /* nul-terminate */
1784 if (cft->write_u64) {
1785 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
1788 retval = cft->write_u64(cgrp, cft, val);
1790 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
1793 retval = cft->write_s64(cgrp, cft, val);
1800 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1802 const char __user *userbuf,
1803 size_t nbytes, loff_t *unused_ppos)
1805 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1807 size_t max_bytes = cft->max_write_len;
1808 char *buffer = local_buffer;
1811 max_bytes = sizeof(local_buffer) - 1;
1812 if (nbytes >= max_bytes)
1814 /* Allocate a dynamic buffer if we need one */
1815 if (nbytes >= sizeof(local_buffer)) {
1816 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1820 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
1825 buffer[nbytes] = 0; /* nul-terminate */
1826 retval = cft->write_string(cgrp, cft, strstrip(buffer));
1830 if (buffer != local_buffer)
1835 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1836 size_t nbytes, loff_t *ppos)
1838 struct cftype *cft = __d_cft(file->f_dentry);
1839 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1841 if (cgroup_is_removed(cgrp))
1844 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1845 if (cft->write_u64 || cft->write_s64)
1846 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1847 if (cft->write_string)
1848 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1850 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1851 return ret ? ret : nbytes;
1856 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1858 char __user *buf, size_t nbytes,
1861 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1862 u64 val = cft->read_u64(cgrp, cft);
1863 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1865 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1868 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1870 char __user *buf, size_t nbytes,
1873 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1874 s64 val = cft->read_s64(cgrp, cft);
1875 int len = sprintf(tmp, "%lld\n", (long long) val);
1877 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1880 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1881 size_t nbytes, loff_t *ppos)
1883 struct cftype *cft = __d_cft(file->f_dentry);
1884 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1886 if (cgroup_is_removed(cgrp))
1890 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1892 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1894 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1899 * seqfile ops/methods for returning structured data. Currently just
1900 * supports string->u64 maps, but can be extended in future.
1903 struct cgroup_seqfile_state {
1905 struct cgroup *cgroup;
1908 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1910 struct seq_file *sf = cb->state;
1911 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1914 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1916 struct cgroup_seqfile_state *state = m->private;
1917 struct cftype *cft = state->cft;
1918 if (cft->read_map) {
1919 struct cgroup_map_cb cb = {
1920 .fill = cgroup_map_add,
1923 return cft->read_map(state->cgroup, cft, &cb);
1925 return cft->read_seq_string(state->cgroup, cft, m);
1928 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
1930 struct seq_file *seq = file->private_data;
1931 kfree(seq->private);
1932 return single_release(inode, file);
1935 static const struct file_operations cgroup_seqfile_operations = {
1937 .write = cgroup_file_write,
1938 .llseek = seq_lseek,
1939 .release = cgroup_seqfile_release,
1942 static int cgroup_file_open(struct inode *inode, struct file *file)
1947 err = generic_file_open(inode, file);
1950 cft = __d_cft(file->f_dentry);
1952 if (cft->read_map || cft->read_seq_string) {
1953 struct cgroup_seqfile_state *state =
1954 kzalloc(sizeof(*state), GFP_USER);
1958 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
1959 file->f_op = &cgroup_seqfile_operations;
1960 err = single_open(file, cgroup_seqfile_show, state);
1963 } else if (cft->open)
1964 err = cft->open(inode, file);
1971 static int cgroup_file_release(struct inode *inode, struct file *file)
1973 struct cftype *cft = __d_cft(file->f_dentry);
1975 return cft->release(inode, file);
1980 * cgroup_rename - Only allow simple rename of directories in place.
1982 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
1983 struct inode *new_dir, struct dentry *new_dentry)
1985 if (!S_ISDIR(old_dentry->d_inode->i_mode))
1987 if (new_dentry->d_inode)
1989 if (old_dir != new_dir)
1991 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1994 static const struct file_operations cgroup_file_operations = {
1995 .read = cgroup_file_read,
1996 .write = cgroup_file_write,
1997 .llseek = generic_file_llseek,
1998 .open = cgroup_file_open,
1999 .release = cgroup_file_release,
2002 static const struct inode_operations cgroup_dir_inode_operations = {
2003 .lookup = simple_lookup,
2004 .mkdir = cgroup_mkdir,
2005 .rmdir = cgroup_rmdir,
2006 .rename = cgroup_rename,
2009 static int cgroup_create_file(struct dentry *dentry, mode_t mode,
2010 struct super_block *sb)
2012 static const struct dentry_operations cgroup_dops = {
2013 .d_iput = cgroup_diput,
2016 struct inode *inode;
2020 if (dentry->d_inode)
2023 inode = cgroup_new_inode(mode, sb);
2027 if (S_ISDIR(mode)) {
2028 inode->i_op = &cgroup_dir_inode_operations;
2029 inode->i_fop = &simple_dir_operations;
2031 /* start off with i_nlink == 2 (for "." entry) */
2034 /* start with the directory inode held, so that we can
2035 * populate it without racing with another mkdir */
2036 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
2037 } else if (S_ISREG(mode)) {
2039 inode->i_fop = &cgroup_file_operations;
2041 dentry->d_op = &cgroup_dops;
2042 d_instantiate(dentry, inode);
2043 dget(dentry); /* Extra count - pin the dentry in core */
2048 * cgroup_create_dir - create a directory for an object.
2049 * @cgrp: the cgroup we create the directory for. It must have a valid
2050 * ->parent field. And we are going to fill its ->dentry field.
2051 * @dentry: dentry of the new cgroup
2052 * @mode: mode to set on new directory.
2054 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
2057 struct dentry *parent;
2060 parent = cgrp->parent->dentry;
2061 error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
2063 dentry->d_fsdata = cgrp;
2064 inc_nlink(parent->d_inode);
2065 rcu_assign_pointer(cgrp->dentry, dentry);
2074 * cgroup_file_mode - deduce file mode of a control file
2075 * @cft: the control file in question
2077 * returns cft->mode if ->mode is not 0
2078 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2079 * returns S_IRUGO if it has only a read handler
2080 * returns S_IWUSR if it has only a write hander
2082 static mode_t cgroup_file_mode(const struct cftype *cft)
2089 if (cft->read || cft->read_u64 || cft->read_s64 ||
2090 cft->read_map || cft->read_seq_string)
2093 if (cft->write || cft->write_u64 || cft->write_s64 ||
2094 cft->write_string || cft->trigger)
2100 int cgroup_add_file(struct cgroup *cgrp,
2101 struct cgroup_subsys *subsys,
2102 const struct cftype *cft)
2104 struct dentry *dir = cgrp->dentry;
2105 struct dentry *dentry;
2109 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2110 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2111 strcpy(name, subsys->name);
2114 strcat(name, cft->name);
2115 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2116 dentry = lookup_one_len(name, dir, strlen(name));
2117 if (!IS_ERR(dentry)) {
2118 mode = cgroup_file_mode(cft);
2119 error = cgroup_create_file(dentry, mode | S_IFREG,
2122 dentry->d_fsdata = (void *)cft;
2125 error = PTR_ERR(dentry);
2129 int cgroup_add_files(struct cgroup *cgrp,
2130 struct cgroup_subsys *subsys,
2131 const struct cftype cft[],
2135 for (i = 0; i < count; i++) {
2136 err = cgroup_add_file(cgrp, subsys, &cft[i]);
2144 * cgroup_task_count - count the number of tasks in a cgroup.
2145 * @cgrp: the cgroup in question
2147 * Return the number of tasks in the cgroup.
2149 int cgroup_task_count(const struct cgroup *cgrp)
2152 struct cg_cgroup_link *link;
2154 read_lock(&css_set_lock);
2155 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2156 count += atomic_read(&link->cg->refcount);
2158 read_unlock(&css_set_lock);
2163 * Advance a list_head iterator. The iterator should be positioned at
2164 * the start of a css_set
2166 static void cgroup_advance_iter(struct cgroup *cgrp,
2167 struct cgroup_iter *it)
2169 struct list_head *l = it->cg_link;
2170 struct cg_cgroup_link *link;
2173 /* Advance to the next non-empty css_set */
2176 if (l == &cgrp->css_sets) {
2180 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2182 } while (list_empty(&cg->tasks));
2184 it->task = cg->tasks.next;
2188 * To reduce the fork() overhead for systems that are not actually
2189 * using their cgroups capability, we don't maintain the lists running
2190 * through each css_set to its tasks until we see the list actually
2191 * used - in other words after the first call to cgroup_iter_start().
2193 * The tasklist_lock is not held here, as do_each_thread() and
2194 * while_each_thread() are protected by RCU.
2196 static void cgroup_enable_task_cg_lists(void)
2198 struct task_struct *p, *g;
2199 write_lock(&css_set_lock);
2200 use_task_css_set_links = 1;
2201 do_each_thread(g, p) {
2204 * We should check if the process is exiting, otherwise
2205 * it will race with cgroup_exit() in that the list
2206 * entry won't be deleted though the process has exited.
2208 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2209 list_add(&p->cg_list, &p->cgroups->tasks);
2211 } while_each_thread(g, p);
2212 write_unlock(&css_set_lock);
2215 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
2218 * The first time anyone tries to iterate across a cgroup,
2219 * we need to enable the list linking each css_set to its
2220 * tasks, and fix up all existing tasks.
2222 if (!use_task_css_set_links)
2223 cgroup_enable_task_cg_lists();
2225 read_lock(&css_set_lock);
2226 it->cg_link = &cgrp->css_sets;
2227 cgroup_advance_iter(cgrp, it);
2230 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
2231 struct cgroup_iter *it)
2233 struct task_struct *res;
2234 struct list_head *l = it->task;
2235 struct cg_cgroup_link *link;
2237 /* If the iterator cg is NULL, we have no tasks */
2240 res = list_entry(l, struct task_struct, cg_list);
2241 /* Advance iterator to find next entry */
2243 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
2244 if (l == &link->cg->tasks) {
2245 /* We reached the end of this task list - move on to
2246 * the next cg_cgroup_link */
2247 cgroup_advance_iter(cgrp, it);
2254 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
2256 read_unlock(&css_set_lock);
2259 static inline int started_after_time(struct task_struct *t1,
2260 struct timespec *time,
2261 struct task_struct *t2)
2263 int start_diff = timespec_compare(&t1->start_time, time);
2264 if (start_diff > 0) {
2266 } else if (start_diff < 0) {
2270 * Arbitrarily, if two processes started at the same
2271 * time, we'll say that the lower pointer value
2272 * started first. Note that t2 may have exited by now
2273 * so this may not be a valid pointer any longer, but
2274 * that's fine - it still serves to distinguish
2275 * between two tasks started (effectively) simultaneously.
2282 * This function is a callback from heap_insert() and is used to order
2284 * In this case we order the heap in descending task start time.
2286 static inline int started_after(void *p1, void *p2)
2288 struct task_struct *t1 = p1;
2289 struct task_struct *t2 = p2;
2290 return started_after_time(t1, &t2->start_time, t2);
2294 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
2295 * @scan: struct cgroup_scanner containing arguments for the scan
2297 * Arguments include pointers to callback functions test_task() and
2299 * Iterate through all the tasks in a cgroup, calling test_task() for each,
2300 * and if it returns true, call process_task() for it also.
2301 * The test_task pointer may be NULL, meaning always true (select all tasks).
2302 * Effectively duplicates cgroup_iter_{start,next,end}()
2303 * but does not lock css_set_lock for the call to process_task().
2304 * The struct cgroup_scanner may be embedded in any structure of the caller's
2306 * It is guaranteed that process_task() will act on every task that
2307 * is a member of the cgroup for the duration of this call. This
2308 * function may or may not call process_task() for tasks that exit
2309 * or move to a different cgroup during the call, or are forked or
2310 * move into the cgroup during the call.
2312 * Note that test_task() may be called with locks held, and may in some
2313 * situations be called multiple times for the same task, so it should
2315 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
2316 * pre-allocated and will be used for heap operations (and its "gt" member will
2317 * be overwritten), else a temporary heap will be used (allocation of which
2318 * may cause this function to fail).
2320 int cgroup_scan_tasks(struct cgroup_scanner *scan)
2323 struct cgroup_iter it;
2324 struct task_struct *p, *dropped;
2325 /* Never dereference latest_task, since it's not refcounted */
2326 struct task_struct *latest_task = NULL;
2327 struct ptr_heap tmp_heap;
2328 struct ptr_heap *heap;
2329 struct timespec latest_time = { 0, 0 };
2332 /* The caller supplied our heap and pre-allocated its memory */
2334 heap->gt = &started_after;
2336 /* We need to allocate our own heap memory */
2338 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2340 /* cannot allocate the heap */
2346 * Scan tasks in the cgroup, using the scanner's "test_task" callback
2347 * to determine which are of interest, and using the scanner's
2348 * "process_task" callback to process any of them that need an update.
2349 * Since we don't want to hold any locks during the task updates,
2350 * gather tasks to be processed in a heap structure.
2351 * The heap is sorted by descending task start time.
2352 * If the statically-sized heap fills up, we overflow tasks that
2353 * started later, and in future iterations only consider tasks that
2354 * started after the latest task in the previous pass. This
2355 * guarantees forward progress and that we don't miss any tasks.
2358 cgroup_iter_start(scan->cg, &it);
2359 while ((p = cgroup_iter_next(scan->cg, &it))) {
2361 * Only affect tasks that qualify per the caller's callback,
2362 * if he provided one
2364 if (scan->test_task && !scan->test_task(p, scan))
2367 * Only process tasks that started after the last task
2370 if (!started_after_time(p, &latest_time, latest_task))
2372 dropped = heap_insert(heap, p);
2373 if (dropped == NULL) {
2375 * The new task was inserted; the heap wasn't
2379 } else if (dropped != p) {
2381 * The new task was inserted, and pushed out a
2385 put_task_struct(dropped);
2388 * Else the new task was newer than anything already in
2389 * the heap and wasn't inserted
2392 cgroup_iter_end(scan->cg, &it);
2395 for (i = 0; i < heap->size; i++) {
2396 struct task_struct *q = heap->ptrs[i];
2398 latest_time = q->start_time;
2401 /* Process the task per the caller's callback */
2402 scan->process_task(q, scan);
2406 * If we had to process any tasks at all, scan again
2407 * in case some of them were in the middle of forking
2408 * children that didn't get processed.
2409 * Not the most efficient way to do it, but it avoids
2410 * having to take callback_mutex in the fork path
2414 if (heap == &tmp_heap)
2415 heap_free(&tmp_heap);
2420 * Stuff for reading the 'tasks'/'procs' files.
2422 * Reading this file can return large amounts of data if a cgroup has
2423 * *lots* of attached tasks. So it may need several calls to read(),
2424 * but we cannot guarantee that the information we produce is correct
2425 * unless we produce it entirely atomically.
2430 * The following two functions "fix" the issue where there are more pids
2431 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
2432 * TODO: replace with a kernel-wide solution to this problem
2434 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
2435 static void *pidlist_allocate(int count)
2437 if (PIDLIST_TOO_LARGE(count))
2438 return vmalloc(count * sizeof(pid_t));
2440 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
2442 static void pidlist_free(void *p)
2444 if (is_vmalloc_addr(p))
2449 static void *pidlist_resize(void *p, int newcount)
2452 /* note: if new alloc fails, old p will still be valid either way */
2453 if (is_vmalloc_addr(p)) {
2454 newlist = vmalloc(newcount * sizeof(pid_t));
2457 memcpy(newlist, p, newcount * sizeof(pid_t));
2460 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
2466 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
2467 * If the new stripped list is sufficiently smaller and there's enough memory
2468 * to allocate a new buffer, will let go of the unneeded memory. Returns the
2469 * number of unique elements.
2471 /* is the size difference enough that we should re-allocate the array? */
2472 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
2473 static int pidlist_uniq(pid_t **p, int length)
2480 * we presume the 0th element is unique, so i starts at 1. trivial
2481 * edge cases first; no work needs to be done for either
2483 if (length == 0 || length == 1)
2485 /* src and dest walk down the list; dest counts unique elements */
2486 for (src = 1; src < length; src++) {
2487 /* find next unique element */
2488 while (list[src] == list[src-1]) {
2493 /* dest always points to where the next unique element goes */
2494 list[dest] = list[src];
2499 * if the length difference is large enough, we want to allocate a
2500 * smaller buffer to save memory. if this fails due to out of memory,
2501 * we'll just stay with what we've got.
2503 if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
2504 newlist = pidlist_resize(list, dest);
2511 static int cmppid(const void *a, const void *b)
2513 return *(pid_t *)a - *(pid_t *)b;
2517 * find the appropriate pidlist for our purpose (given procs vs tasks)
2518 * returns with the lock on that pidlist already held, and takes care
2519 * of the use count, or returns NULL with no locks held if we're out of
2522 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
2523 enum cgroup_filetype type)
2525 struct cgroup_pidlist *l;
2526 /* don't need task_nsproxy() if we're looking at ourself */
2527 struct pid_namespace *ns = get_pid_ns(current->nsproxy->pid_ns);
2529 * We can't drop the pidlist_mutex before taking the l->mutex in case
2530 * the last ref-holder is trying to remove l from the list at the same
2531 * time. Holding the pidlist_mutex precludes somebody taking whichever
2532 * list we find out from under us - compare release_pid_array().
2534 mutex_lock(&cgrp->pidlist_mutex);
2535 list_for_each_entry(l, &cgrp->pidlists, links) {
2536 if (l->key.type == type && l->key.ns == ns) {
2537 /* found a matching list - drop the extra refcount */
2539 /* make sure l doesn't vanish out from under us */
2540 down_write(&l->mutex);
2541 mutex_unlock(&cgrp->pidlist_mutex);
2545 /* entry not found; create a new one */
2546 l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
2548 mutex_unlock(&cgrp->pidlist_mutex);
2552 init_rwsem(&l->mutex);
2553 down_write(&l->mutex);
2556 l->use_count = 0; /* don't increment here */
2559 list_add(&l->links, &cgrp->pidlists);
2560 mutex_unlock(&cgrp->pidlist_mutex);
2565 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
2567 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
2568 struct cgroup_pidlist **lp)
2572 int pid, n = 0; /* used for populating the array */
2573 struct cgroup_iter it;
2574 struct task_struct *tsk;
2575 struct cgroup_pidlist *l;
2578 * If cgroup gets more users after we read count, we won't have
2579 * enough space - tough. This race is indistinguishable to the
2580 * caller from the case that the additional cgroup users didn't
2581 * show up until sometime later on.
2583 length = cgroup_task_count(cgrp);
2584 array = pidlist_allocate(length);
2587 /* now, populate the array */
2588 cgroup_iter_start(cgrp, &it);
2589 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2590 if (unlikely(n == length))
2592 /* get tgid or pid for procs or tasks file respectively */
2593 if (type == CGROUP_FILE_PROCS)
2594 pid = task_tgid_vnr(tsk);
2596 pid = task_pid_vnr(tsk);
2597 if (pid > 0) /* make sure to only use valid results */
2600 cgroup_iter_end(cgrp, &it);
2602 /* now sort & (if procs) strip out duplicates */
2603 sort(array, length, sizeof(pid_t), cmppid, NULL);
2604 if (type == CGROUP_FILE_PROCS)
2605 length = pidlist_uniq(&array, length);
2606 l = cgroup_pidlist_find(cgrp, type);
2608 pidlist_free(array);
2611 /* store array, freeing old if necessary - lock already held */
2612 pidlist_free(l->list);
2616 up_write(&l->mutex);
2622 * cgroupstats_build - build and fill cgroupstats
2623 * @stats: cgroupstats to fill information into
2624 * @dentry: A dentry entry belonging to the cgroup for which stats have
2627 * Build and fill cgroupstats so that taskstats can export it to user
2630 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2633 struct cgroup *cgrp;
2634 struct cgroup_iter it;
2635 struct task_struct *tsk;
2638 * Validate dentry by checking the superblock operations,
2639 * and make sure it's a directory.
2641 if (dentry->d_sb->s_op != &cgroup_ops ||
2642 !S_ISDIR(dentry->d_inode->i_mode))
2646 cgrp = dentry->d_fsdata;
2648 cgroup_iter_start(cgrp, &it);
2649 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2650 switch (tsk->state) {
2652 stats->nr_running++;
2654 case TASK_INTERRUPTIBLE:
2655 stats->nr_sleeping++;
2657 case TASK_UNINTERRUPTIBLE:
2658 stats->nr_uninterruptible++;
2661 stats->nr_stopped++;
2664 if (delayacct_is_task_waiting_on_io(tsk))
2665 stats->nr_io_wait++;
2669 cgroup_iter_end(cgrp, &it);
2677 * seq_file methods for the tasks/procs files. The seq_file position is the
2678 * next pid to display; the seq_file iterator is a pointer to the pid
2679 * in the cgroup->l->list array.
2682 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
2685 * Initially we receive a position value that corresponds to
2686 * one more than the last pid shown (or 0 on the first call or
2687 * after a seek to the start). Use a binary-search to find the
2688 * next pid to display, if any
2690 struct cgroup_pidlist *l = s->private;
2691 int index = 0, pid = *pos;
2694 down_read(&l->mutex);
2696 int end = l->length;
2698 while (index < end) {
2699 int mid = (index + end) / 2;
2700 if (l->list[mid] == pid) {
2703 } else if (l->list[mid] <= pid)
2709 /* If we're off the end of the array, we're done */
2710 if (index >= l->length)
2712 /* Update the abstract position to be the actual pid that we found */
2713 iter = l->list + index;
2718 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
2720 struct cgroup_pidlist *l = s->private;
2724 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
2726 struct cgroup_pidlist *l = s->private;
2728 pid_t *end = l->list + l->length;
2730 * Advance to the next pid in the array. If this goes off the
2742 static int cgroup_pidlist_show(struct seq_file *s, void *v)
2744 return seq_printf(s, "%d\n", *(int *)v);
2748 * seq_operations functions for iterating on pidlists through seq_file -
2749 * independent of whether it's tasks or procs
2751 static const struct seq_operations cgroup_pidlist_seq_operations = {
2752 .start = cgroup_pidlist_start,
2753 .stop = cgroup_pidlist_stop,
2754 .next = cgroup_pidlist_next,
2755 .show = cgroup_pidlist_show,
2758 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
2761 * the case where we're the last user of this particular pidlist will
2762 * have us remove it from the cgroup's list, which entails taking the
2763 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
2764 * pidlist_mutex, we have to take pidlist_mutex first.
2766 mutex_lock(&l->owner->pidlist_mutex);
2767 down_write(&l->mutex);
2768 BUG_ON(!l->use_count);
2769 if (!--l->use_count) {
2770 /* we're the last user if refcount is 0; remove and free */
2771 list_del(&l->links);
2772 mutex_unlock(&l->owner->pidlist_mutex);
2773 pidlist_free(l->list);
2774 put_pid_ns(l->key.ns);
2775 up_write(&l->mutex);
2779 mutex_unlock(&l->owner->pidlist_mutex);
2780 up_write(&l->mutex);
2783 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
2785 struct cgroup_pidlist *l;
2786 if (!(file->f_mode & FMODE_READ))
2789 * the seq_file will only be initialized if the file was opened for
2790 * reading; hence we check if it's not null only in that case.
2792 l = ((struct seq_file *)file->private_data)->private;
2793 cgroup_release_pid_array(l);
2794 return seq_release(inode, file);
2797 static const struct file_operations cgroup_pidlist_operations = {
2799 .llseek = seq_lseek,
2800 .write = cgroup_file_write,
2801 .release = cgroup_pidlist_release,
2805 * The following functions handle opens on a file that displays a pidlist
2806 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
2809 /* helper function for the two below it */
2810 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
2812 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2813 struct cgroup_pidlist *l;
2816 /* Nothing to do for write-only files */
2817 if (!(file->f_mode & FMODE_READ))
2820 /* have the array populated */
2821 retval = pidlist_array_load(cgrp, type, &l);
2824 /* configure file information */
2825 file->f_op = &cgroup_pidlist_operations;
2827 retval = seq_open(file, &cgroup_pidlist_seq_operations);
2829 cgroup_release_pid_array(l);
2832 ((struct seq_file *)file->private_data)->private = l;
2835 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2837 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
2839 static int cgroup_procs_open(struct inode *unused, struct file *file)
2841 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
2844 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2847 return notify_on_release(cgrp);
2850 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2854 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2856 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2858 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2863 * for the common functions, 'private' gives the type of file
2865 /* for hysterical raisins, we can't put this on the older files */
2866 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
2867 static struct cftype files[] = {
2870 .open = cgroup_tasks_open,
2871 .write_u64 = cgroup_tasks_write,
2872 .release = cgroup_pidlist_release,
2873 .mode = S_IRUGO | S_IWUSR,
2876 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
2877 .open = cgroup_procs_open,
2878 /* .write_u64 = cgroup_procs_write, TODO */
2879 .release = cgroup_pidlist_release,
2883 .name = "notify_on_release",
2884 .read_u64 = cgroup_read_notify_on_release,
2885 .write_u64 = cgroup_write_notify_on_release,
2889 static struct cftype cft_release_agent = {
2890 .name = "release_agent",
2891 .read_seq_string = cgroup_release_agent_show,
2892 .write_string = cgroup_release_agent_write,
2893 .max_write_len = PATH_MAX,
2896 static int cgroup_populate_dir(struct cgroup *cgrp)
2899 struct cgroup_subsys *ss;
2901 /* First clear out any existing files */
2902 cgroup_clear_directory(cgrp->dentry);
2904 err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2908 if (cgrp == cgrp->top_cgroup) {
2909 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2913 for_each_subsys(cgrp->root, ss) {
2914 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2917 /* This cgroup is ready now */
2918 for_each_subsys(cgrp->root, ss) {
2919 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2921 * Update id->css pointer and make this css visible from
2922 * CSS ID functions. This pointer will be dereferened
2923 * from RCU-read-side without locks.
2926 rcu_assign_pointer(css->id->css, css);
2932 static void init_cgroup_css(struct cgroup_subsys_state *css,
2933 struct cgroup_subsys *ss,
2934 struct cgroup *cgrp)
2937 atomic_set(&css->refcnt, 1);
2940 if (cgrp == dummytop)
2941 set_bit(CSS_ROOT, &css->flags);
2942 BUG_ON(cgrp->subsys[ss->subsys_id]);
2943 cgrp->subsys[ss->subsys_id] = css;
2946 static void cgroup_lock_hierarchy(struct cgroupfs_root *root)
2948 /* We need to take each hierarchy_mutex in a consistent order */
2952 * No worry about a race with rebind_subsystems that might mess up the
2953 * locking order, since both parties are under cgroup_mutex.
2955 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2956 struct cgroup_subsys *ss = subsys[i];
2959 if (ss->root == root)
2960 mutex_lock(&ss->hierarchy_mutex);
2964 static void cgroup_unlock_hierarchy(struct cgroupfs_root *root)
2968 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2969 struct cgroup_subsys *ss = subsys[i];
2972 if (ss->root == root)
2973 mutex_unlock(&ss->hierarchy_mutex);
2978 * cgroup_create - create a cgroup
2979 * @parent: cgroup that will be parent of the new cgroup
2980 * @dentry: dentry of the new cgroup
2981 * @mode: mode to set on new inode
2983 * Must be called with the mutex on the parent inode held
2985 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
2988 struct cgroup *cgrp;
2989 struct cgroupfs_root *root = parent->root;
2991 struct cgroup_subsys *ss;
2992 struct super_block *sb = root->sb;
2994 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
2998 /* Grab a reference on the superblock so the hierarchy doesn't
2999 * get deleted on unmount if there are child cgroups. This
3000 * can be done outside cgroup_mutex, since the sb can't
3001 * disappear while someone has an open control file on the
3003 atomic_inc(&sb->s_active);
3005 mutex_lock(&cgroup_mutex);
3007 init_cgroup_housekeeping(cgrp);
3009 cgrp->parent = parent;
3010 cgrp->root = parent->root;
3011 cgrp->top_cgroup = parent->top_cgroup;
3013 if (notify_on_release(parent))
3014 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3016 for_each_subsys(root, ss) {
3017 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
3023 init_cgroup_css(css, ss, cgrp);
3025 err = alloc_css_id(ss, parent, cgrp);
3029 /* At error, ->destroy() callback has to free assigned ID. */
3032 cgroup_lock_hierarchy(root);
3033 list_add(&cgrp->sibling, &cgrp->parent->children);
3034 cgroup_unlock_hierarchy(root);
3035 root->number_of_cgroups++;
3037 err = cgroup_create_dir(cgrp, dentry, mode);
3041 /* The cgroup directory was pre-locked for us */
3042 BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
3044 err = cgroup_populate_dir(cgrp);
3045 /* If err < 0, we have a half-filled directory - oh well ;) */
3047 mutex_unlock(&cgroup_mutex);
3048 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
3054 cgroup_lock_hierarchy(root);
3055 list_del(&cgrp->sibling);
3056 cgroup_unlock_hierarchy(root);
3057 root->number_of_cgroups--;
3061 for_each_subsys(root, ss) {
3062 if (cgrp->subsys[ss->subsys_id])
3063 ss->destroy(ss, cgrp);
3066 mutex_unlock(&cgroup_mutex);
3068 /* Release the reference count that we took on the superblock */
3069 deactivate_super(sb);
3075 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
3077 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
3079 /* the vfs holds inode->i_mutex already */
3080 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
3083 static int cgroup_has_css_refs(struct cgroup *cgrp)
3085 /* Check the reference count on each subsystem. Since we
3086 * already established that there are no tasks in the
3087 * cgroup, if the css refcount is also 1, then there should
3088 * be no outstanding references, so the subsystem is safe to
3089 * destroy. We scan across all subsystems rather than using
3090 * the per-hierarchy linked list of mounted subsystems since
3091 * we can be called via check_for_release() with no
3092 * synchronization other than RCU, and the subsystem linked
3093 * list isn't RCU-safe */
3096 * We won't need to lock the subsys array, because the subsystems
3097 * we're concerned about aren't going anywhere since our cgroup root
3098 * has a reference on them.
3100 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3101 struct cgroup_subsys *ss = subsys[i];
3102 struct cgroup_subsys_state *css;
3103 /* Skip subsystems not present or not in this hierarchy */
3104 if (ss == NULL || ss->root != cgrp->root)
3106 css = cgrp->subsys[ss->subsys_id];
3107 /* When called from check_for_release() it's possible
3108 * that by this point the cgroup has been removed
3109 * and the css deleted. But a false-positive doesn't
3110 * matter, since it can only happen if the cgroup
3111 * has been deleted and hence no longer needs the
3112 * release agent to be called anyway. */
3113 if (css && (atomic_read(&css->refcnt) > 1))
3120 * Atomically mark all (or else none) of the cgroup's CSS objects as
3121 * CSS_REMOVED. Return true on success, or false if the cgroup has
3122 * busy subsystems. Call with cgroup_mutex held
3125 static int cgroup_clear_css_refs(struct cgroup *cgrp)
3127 struct cgroup_subsys *ss;
3128 unsigned long flags;
3129 bool failed = false;
3130 local_irq_save(flags);
3131 for_each_subsys(cgrp->root, ss) {
3132 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3135 /* We can only remove a CSS with a refcnt==1 */
3136 refcnt = atomic_read(&css->refcnt);
3143 * Drop the refcnt to 0 while we check other
3144 * subsystems. This will cause any racing
3145 * css_tryget() to spin until we set the
3146 * CSS_REMOVED bits or abort
3148 if (atomic_cmpxchg(&css->refcnt, refcnt, 0) == refcnt)
3154 for_each_subsys(cgrp->root, ss) {
3155 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3158 * Restore old refcnt if we previously managed
3159 * to clear it from 1 to 0
3161 if (!atomic_read(&css->refcnt))
3162 atomic_set(&css->refcnt, 1);
3164 /* Commit the fact that the CSS is removed */
3165 set_bit(CSS_REMOVED, &css->flags);
3168 local_irq_restore(flags);
3172 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
3174 struct cgroup *cgrp = dentry->d_fsdata;
3176 struct cgroup *parent;
3180 /* the vfs holds both inode->i_mutex already */
3182 mutex_lock(&cgroup_mutex);
3183 if (atomic_read(&cgrp->count) != 0) {
3184 mutex_unlock(&cgroup_mutex);
3187 if (!list_empty(&cgrp->children)) {
3188 mutex_unlock(&cgroup_mutex);
3191 mutex_unlock(&cgroup_mutex);
3194 * In general, subsystem has no css->refcnt after pre_destroy(). But
3195 * in racy cases, subsystem may have to get css->refcnt after
3196 * pre_destroy() and it makes rmdir return with -EBUSY. This sometimes
3197 * make rmdir return -EBUSY too often. To avoid that, we use waitqueue
3198 * for cgroup's rmdir. CGRP_WAIT_ON_RMDIR is for synchronizing rmdir
3199 * and subsystem's reference count handling. Please see css_get/put
3200 * and css_tryget() and cgroup_wakeup_rmdir_waiter() implementation.
3202 set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3205 * Call pre_destroy handlers of subsys. Notify subsystems
3206 * that rmdir() request comes.
3208 ret = cgroup_call_pre_destroy(cgrp);
3210 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3214 mutex_lock(&cgroup_mutex);
3215 parent = cgrp->parent;
3216 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
3217 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3218 mutex_unlock(&cgroup_mutex);
3221 prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
3222 if (!cgroup_clear_css_refs(cgrp)) {
3223 mutex_unlock(&cgroup_mutex);
3225 * Because someone may call cgroup_wakeup_rmdir_waiter() before
3226 * prepare_to_wait(), we need to check this flag.
3228 if (test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))
3230 finish_wait(&cgroup_rmdir_waitq, &wait);
3231 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3232 if (signal_pending(current))
3236 /* NO css_tryget() can success after here. */
3237 finish_wait(&cgroup_rmdir_waitq, &wait);
3238 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3240 spin_lock(&release_list_lock);
3241 set_bit(CGRP_REMOVED, &cgrp->flags);
3242 if (!list_empty(&cgrp->release_list))
3243 list_del(&cgrp->release_list);
3244 spin_unlock(&release_list_lock);
3246 cgroup_lock_hierarchy(cgrp->root);
3247 /* delete this cgroup from parent->children */
3248 list_del(&cgrp->sibling);
3249 cgroup_unlock_hierarchy(cgrp->root);
3251 spin_lock(&cgrp->dentry->d_lock);
3252 d = dget(cgrp->dentry);
3253 spin_unlock(&d->d_lock);
3255 cgroup_d_remove_dir(d);
3258 set_bit(CGRP_RELEASABLE, &parent->flags);
3259 check_for_release(parent);
3261 mutex_unlock(&cgroup_mutex);
3265 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
3267 struct cgroup_subsys_state *css;
3269 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
3271 /* Create the top cgroup state for this subsystem */
3272 list_add(&ss->sibling, &rootnode.subsys_list);
3273 ss->root = &rootnode;
3274 css = ss->create(ss, dummytop);
3275 /* We don't handle early failures gracefully */
3276 BUG_ON(IS_ERR(css));
3277 init_cgroup_css(css, ss, dummytop);
3279 /* Update the init_css_set to contain a subsys
3280 * pointer to this state - since the subsystem is
3281 * newly registered, all tasks and hence the
3282 * init_css_set is in the subsystem's top cgroup. */
3283 init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
3285 need_forkexit_callback |= ss->fork || ss->exit;
3287 /* At system boot, before all subsystems have been
3288 * registered, no tasks have been forked, so we don't
3289 * need to invoke fork callbacks here. */
3290 BUG_ON(!list_empty(&init_task.tasks));
3292 mutex_init(&ss->hierarchy_mutex);
3293 lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
3298 * cgroup_init_early - cgroup initialization at system boot
3300 * Initialize cgroups at system boot, and initialize any
3301 * subsystems that request early init.
3303 int __init cgroup_init_early(void)
3306 atomic_set(&init_css_set.refcount, 1);
3307 INIT_LIST_HEAD(&init_css_set.cg_links);
3308 INIT_LIST_HEAD(&init_css_set.tasks);
3309 INIT_HLIST_NODE(&init_css_set.hlist);
3311 init_cgroup_root(&rootnode);
3313 init_task.cgroups = &init_css_set;
3315 init_css_set_link.cg = &init_css_set;
3316 init_css_set_link.cgrp = dummytop;
3317 list_add(&init_css_set_link.cgrp_link_list,
3318 &rootnode.top_cgroup.css_sets);
3319 list_add(&init_css_set_link.cg_link_list,
3320 &init_css_set.cg_links);
3322 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
3323 INIT_HLIST_HEAD(&css_set_table[i]);
3325 /* at bootup time, we don't worry about modular subsystems */
3326 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3327 struct cgroup_subsys *ss = subsys[i];
3330 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
3331 BUG_ON(!ss->create);
3332 BUG_ON(!ss->destroy);
3333 if (ss->subsys_id != i) {
3334 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
3335 ss->name, ss->subsys_id);
3340 cgroup_init_subsys(ss);
3346 * cgroup_init - cgroup initialization
3348 * Register cgroup filesystem and /proc file, and initialize
3349 * any subsystems that didn't request early init.
3351 int __init cgroup_init(void)
3355 struct hlist_head *hhead;
3357 err = bdi_init(&cgroup_backing_dev_info);
3361 /* at bootup time, we don't worry about modular subsystems */
3362 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3363 struct cgroup_subsys *ss = subsys[i];
3364 if (!ss->early_init)
3365 cgroup_init_subsys(ss);
3367 cgroup_subsys_init_idr(ss);
3370 /* Add init_css_set to the hash table */
3371 hhead = css_set_hash(init_css_set.subsys);
3372 hlist_add_head(&init_css_set.hlist, hhead);
3373 BUG_ON(!init_root_id(&rootnode));
3374 err = register_filesystem(&cgroup_fs_type);
3378 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
3382 bdi_destroy(&cgroup_backing_dev_info);
3388 * proc_cgroup_show()
3389 * - Print task's cgroup paths into seq_file, one line for each hierarchy
3390 * - Used for /proc/<pid>/cgroup.
3391 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
3392 * doesn't really matter if tsk->cgroup changes after we read it,
3393 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
3394 * anyway. No need to check that tsk->cgroup != NULL, thanks to
3395 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
3396 * cgroup to top_cgroup.
3399 /* TODO: Use a proper seq_file iterator */
3400 static int proc_cgroup_show(struct seq_file *m, void *v)
3403 struct task_struct *tsk;
3406 struct cgroupfs_root *root;
3409 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3415 tsk = get_pid_task(pid, PIDTYPE_PID);
3421 mutex_lock(&cgroup_mutex);
3423 for_each_active_root(root) {
3424 struct cgroup_subsys *ss;
3425 struct cgroup *cgrp;
3428 seq_printf(m, "%d:", root->hierarchy_id);
3429 for_each_subsys(root, ss)
3430 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
3431 if (strlen(root->name))
3432 seq_printf(m, "%sname=%s", count ? "," : "",
3435 cgrp = task_cgroup_from_root(tsk, root);
3436 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
3444 mutex_unlock(&cgroup_mutex);
3445 put_task_struct(tsk);
3452 static int cgroup_open(struct inode *inode, struct file *file)
3454 struct pid *pid = PROC_I(inode)->pid;
3455 return single_open(file, proc_cgroup_show, pid);
3458 const struct file_operations proc_cgroup_operations = {
3459 .open = cgroup_open,
3461 .llseek = seq_lseek,
3462 .release = single_release,
3465 /* Display information about each subsystem and each hierarchy */
3466 static int proc_cgroupstats_show(struct seq_file *m, void *v)
3470 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
3472 * ideally we don't want subsystems moving around while we do this.
3473 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
3474 * subsys/hierarchy state.
3476 mutex_lock(&cgroup_mutex);
3477 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3478 struct cgroup_subsys *ss = subsys[i];
3481 seq_printf(m, "%s\t%d\t%d\t%d\n",
3482 ss->name, ss->root->hierarchy_id,
3483 ss->root->number_of_cgroups, !ss->disabled);
3485 mutex_unlock(&cgroup_mutex);
3489 static int cgroupstats_open(struct inode *inode, struct file *file)
3491 return single_open(file, proc_cgroupstats_show, NULL);
3494 static const struct file_operations proc_cgroupstats_operations = {
3495 .open = cgroupstats_open,
3497 .llseek = seq_lseek,
3498 .release = single_release,
3502 * cgroup_fork - attach newly forked task to its parents cgroup.
3503 * @child: pointer to task_struct of forking parent process.
3505 * Description: A task inherits its parent's cgroup at fork().
3507 * A pointer to the shared css_set was automatically copied in
3508 * fork.c by dup_task_struct(). However, we ignore that copy, since
3509 * it was not made under the protection of RCU or cgroup_mutex, so
3510 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
3511 * have already changed current->cgroups, allowing the previously
3512 * referenced cgroup group to be removed and freed.
3514 * At the point that cgroup_fork() is called, 'current' is the parent
3515 * task, and the passed argument 'child' points to the child task.
3517 void cgroup_fork(struct task_struct *child)
3520 child->cgroups = current->cgroups;
3521 get_css_set(child->cgroups);
3522 task_unlock(current);
3523 INIT_LIST_HEAD(&child->cg_list);
3527 * cgroup_fork_callbacks - run fork callbacks
3528 * @child: the new task
3530 * Called on a new task very soon before adding it to the
3531 * tasklist. No need to take any locks since no-one can
3532 * be operating on this task.
3534 void cgroup_fork_callbacks(struct task_struct *child)
3536 if (need_forkexit_callback) {
3539 * forkexit callbacks are only supported for builtin
3540 * subsystems, and the builtin section of the subsys array is
3541 * immutable, so we don't need to lock the subsys array here.
3543 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3544 struct cgroup_subsys *ss = subsys[i];
3546 ss->fork(ss, child);
3552 * cgroup_post_fork - called on a new task after adding it to the task list
3553 * @child: the task in question
3555 * Adds the task to the list running through its css_set if necessary.
3556 * Has to be after the task is visible on the task list in case we race
3557 * with the first call to cgroup_iter_start() - to guarantee that the
3558 * new task ends up on its list.
3560 void cgroup_post_fork(struct task_struct *child)
3562 if (use_task_css_set_links) {
3563 write_lock(&css_set_lock);
3565 if (list_empty(&child->cg_list))
3566 list_add(&child->cg_list, &child->cgroups->tasks);
3568 write_unlock(&css_set_lock);
3572 * cgroup_exit - detach cgroup from exiting task
3573 * @tsk: pointer to task_struct of exiting process
3574 * @run_callback: run exit callbacks?
3576 * Description: Detach cgroup from @tsk and release it.
3578 * Note that cgroups marked notify_on_release force every task in
3579 * them to take the global cgroup_mutex mutex when exiting.
3580 * This could impact scaling on very large systems. Be reluctant to
3581 * use notify_on_release cgroups where very high task exit scaling
3582 * is required on large systems.
3584 * the_top_cgroup_hack:
3586 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
3588 * We call cgroup_exit() while the task is still competent to
3589 * handle notify_on_release(), then leave the task attached to the
3590 * root cgroup in each hierarchy for the remainder of its exit.
3592 * To do this properly, we would increment the reference count on
3593 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
3594 * code we would add a second cgroup function call, to drop that
3595 * reference. This would just create an unnecessary hot spot on
3596 * the top_cgroup reference count, to no avail.
3598 * Normally, holding a reference to a cgroup without bumping its
3599 * count is unsafe. The cgroup could go away, or someone could
3600 * attach us to a different cgroup, decrementing the count on
3601 * the first cgroup that we never incremented. But in this case,
3602 * top_cgroup isn't going away, and either task has PF_EXITING set,
3603 * which wards off any cgroup_attach_task() attempts, or task is a failed
3604 * fork, never visible to cgroup_attach_task.
3606 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
3611 if (run_callbacks && need_forkexit_callback) {
3613 * modular subsystems can't use callbacks, so no need to lock
3616 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3617 struct cgroup_subsys *ss = subsys[i];
3624 * Unlink from the css_set task list if necessary.
3625 * Optimistically check cg_list before taking
3628 if (!list_empty(&tsk->cg_list)) {
3629 write_lock(&css_set_lock);
3630 if (!list_empty(&tsk->cg_list))
3631 list_del(&tsk->cg_list);
3632 write_unlock(&css_set_lock);
3635 /* Reassign the task to the init_css_set. */
3638 tsk->cgroups = &init_css_set;
3641 put_css_set_taskexit(cg);
3645 * cgroup_clone - clone the cgroup the given subsystem is attached to
3646 * @tsk: the task to be moved
3647 * @subsys: the given subsystem
3648 * @nodename: the name for the new cgroup
3650 * Duplicate the current cgroup in the hierarchy that the given
3651 * subsystem is attached to, and move this task into the new
3654 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
3657 struct dentry *dentry;
3659 struct cgroup *parent, *child;
3660 struct inode *inode;
3662 struct cgroupfs_root *root;
3663 struct cgroup_subsys *ss;
3665 /* We shouldn't be called by an unregistered subsystem */
3666 BUG_ON(!subsys->active);
3668 /* First figure out what hierarchy and cgroup we're dealing
3669 * with, and pin them so we can drop cgroup_mutex */
3670 mutex_lock(&cgroup_mutex);
3672 root = subsys->root;
3673 if (root == &rootnode) {
3674 mutex_unlock(&cgroup_mutex);
3678 /* Pin the hierarchy */
3679 if (!atomic_inc_not_zero(&root->sb->s_active)) {
3680 /* We race with the final deactivate_super() */
3681 mutex_unlock(&cgroup_mutex);
3685 /* Keep the cgroup alive */
3687 parent = task_cgroup(tsk, subsys->subsys_id);
3692 mutex_unlock(&cgroup_mutex);
3694 /* Now do the VFS work to create a cgroup */
3695 inode = parent->dentry->d_inode;
3697 /* Hold the parent directory mutex across this operation to
3698 * stop anyone else deleting the new cgroup */
3699 mutex_lock(&inode->i_mutex);
3700 dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
3701 if (IS_ERR(dentry)) {
3703 "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
3705 ret = PTR_ERR(dentry);
3709 /* Create the cgroup directory, which also creates the cgroup */
3710 ret = vfs_mkdir(inode, dentry, 0755);
3711 child = __d_cgrp(dentry);
3715 "Failed to create cgroup %s: %d\n", nodename,
3720 /* The cgroup now exists. Retake cgroup_mutex and check
3721 * that we're still in the same state that we thought we
3723 mutex_lock(&cgroup_mutex);
3724 if ((root != subsys->root) ||
3725 (parent != task_cgroup(tsk, subsys->subsys_id))) {
3726 /* Aargh, we raced ... */
3727 mutex_unlock(&inode->i_mutex);
3730 deactivate_super(root->sb);
3731 /* The cgroup is still accessible in the VFS, but
3732 * we're not going to try to rmdir() it at this
3735 "Race in cgroup_clone() - leaking cgroup %s\n",
3740 /* do any required auto-setup */
3741 for_each_subsys(root, ss) {
3743 ss->post_clone(ss, child);
3746 /* All seems fine. Finish by moving the task into the new cgroup */
3747 ret = cgroup_attach_task(child, tsk);
3748 mutex_unlock(&cgroup_mutex);
3751 mutex_unlock(&inode->i_mutex);
3753 mutex_lock(&cgroup_mutex);
3755 mutex_unlock(&cgroup_mutex);
3756 deactivate_super(root->sb);
3761 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
3762 * @cgrp: the cgroup in question
3763 * @task: the task in question
3765 * See if @cgrp is a descendant of @task's cgroup in the appropriate
3768 * If we are sending in dummytop, then presumably we are creating
3769 * the top cgroup in the subsystem.
3771 * Called only by the ns (nsproxy) cgroup.
3773 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
3776 struct cgroup *target;
3778 if (cgrp == dummytop)
3781 target = task_cgroup_from_root(task, cgrp->root);
3782 while (cgrp != target && cgrp!= cgrp->top_cgroup)
3783 cgrp = cgrp->parent;
3784 ret = (cgrp == target);
3788 static void check_for_release(struct cgroup *cgrp)
3790 /* All of these checks rely on RCU to keep the cgroup
3791 * structure alive */
3792 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
3793 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
3794 /* Control Group is currently removeable. If it's not
3795 * already queued for a userspace notification, queue
3797 int need_schedule_work = 0;
3798 spin_lock(&release_list_lock);
3799 if (!cgroup_is_removed(cgrp) &&
3800 list_empty(&cgrp->release_list)) {
3801 list_add(&cgrp->release_list, &release_list);
3802 need_schedule_work = 1;
3804 spin_unlock(&release_list_lock);
3805 if (need_schedule_work)
3806 schedule_work(&release_agent_work);
3810 /* Caller must verify that the css is not for root cgroup */
3811 void __css_put(struct cgroup_subsys_state *css, int count)
3813 struct cgroup *cgrp = css->cgroup;
3816 val = atomic_sub_return(count, &css->refcnt);
3818 if (notify_on_release(cgrp)) {
3819 set_bit(CGRP_RELEASABLE, &cgrp->flags);
3820 check_for_release(cgrp);
3822 cgroup_wakeup_rmdir_waiter(cgrp);
3825 WARN_ON_ONCE(val < 1);
3829 * Notify userspace when a cgroup is released, by running the
3830 * configured release agent with the name of the cgroup (path
3831 * relative to the root of cgroup file system) as the argument.
3833 * Most likely, this user command will try to rmdir this cgroup.
3835 * This races with the possibility that some other task will be
3836 * attached to this cgroup before it is removed, or that some other
3837 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
3838 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
3839 * unused, and this cgroup will be reprieved from its death sentence,
3840 * to continue to serve a useful existence. Next time it's released,
3841 * we will get notified again, if it still has 'notify_on_release' set.
3843 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
3844 * means only wait until the task is successfully execve()'d. The
3845 * separate release agent task is forked by call_usermodehelper(),
3846 * then control in this thread returns here, without waiting for the
3847 * release agent task. We don't bother to wait because the caller of
3848 * this routine has no use for the exit status of the release agent
3849 * task, so no sense holding our caller up for that.
3851 static void cgroup_release_agent(struct work_struct *work)
3853 BUG_ON(work != &release_agent_work);
3854 mutex_lock(&cgroup_mutex);
3855 spin_lock(&release_list_lock);
3856 while (!list_empty(&release_list)) {
3857 char *argv[3], *envp[3];
3859 char *pathbuf = NULL, *agentbuf = NULL;
3860 struct cgroup *cgrp = list_entry(release_list.next,
3863 list_del_init(&cgrp->release_list);
3864 spin_unlock(&release_list_lock);
3865 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3868 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
3870 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
3875 argv[i++] = agentbuf;
3876 argv[i++] = pathbuf;
3880 /* minimal command environment */
3881 envp[i++] = "HOME=/";
3882 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3885 /* Drop the lock while we invoke the usermode helper,
3886 * since the exec could involve hitting disk and hence
3887 * be a slow process */
3888 mutex_unlock(&cgroup_mutex);
3889 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3890 mutex_lock(&cgroup_mutex);
3894 spin_lock(&release_list_lock);
3896 spin_unlock(&release_list_lock);
3897 mutex_unlock(&cgroup_mutex);
3900 static int __init cgroup_disable(char *str)
3905 while ((token = strsep(&str, ",")) != NULL) {
3909 * cgroup_disable, being at boot time, can't know about module
3910 * subsystems, so we don't worry about them.
3912 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3913 struct cgroup_subsys *ss = subsys[i];
3915 if (!strcmp(token, ss->name)) {
3917 printk(KERN_INFO "Disabling %s control group"
3918 " subsystem\n", ss->name);
3925 __setup("cgroup_disable=", cgroup_disable);
3928 * Functons for CSS ID.
3932 *To get ID other than 0, this should be called when !cgroup_is_removed().
3934 unsigned short css_id(struct cgroup_subsys_state *css)
3936 struct css_id *cssid = rcu_dereference(css->id);
3943 unsigned short css_depth(struct cgroup_subsys_state *css)
3945 struct css_id *cssid = rcu_dereference(css->id);
3948 return cssid->depth;
3952 bool css_is_ancestor(struct cgroup_subsys_state *child,
3953 const struct cgroup_subsys_state *root)
3955 struct css_id *child_id = rcu_dereference(child->id);
3956 struct css_id *root_id = rcu_dereference(root->id);
3958 if (!child_id || !root_id || (child_id->depth < root_id->depth))
3960 return child_id->stack[root_id->depth] == root_id->id;
3963 static void __free_css_id_cb(struct rcu_head *head)
3967 id = container_of(head, struct css_id, rcu_head);
3971 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
3973 struct css_id *id = css->id;
3974 /* When this is called before css_id initialization, id can be NULL */
3978 BUG_ON(!ss->use_id);
3980 rcu_assign_pointer(id->css, NULL);
3981 rcu_assign_pointer(css->id, NULL);
3982 spin_lock(&ss->id_lock);
3983 idr_remove(&ss->idr, id->id);
3984 spin_unlock(&ss->id_lock);
3985 call_rcu(&id->rcu_head, __free_css_id_cb);
3989 * This is called by init or create(). Then, calls to this function are
3990 * always serialized (By cgroup_mutex() at create()).
3993 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
3995 struct css_id *newid;
3996 int myid, error, size;
3998 BUG_ON(!ss->use_id);
4000 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
4001 newid = kzalloc(size, GFP_KERNEL);
4003 return ERR_PTR(-ENOMEM);
4005 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
4009 spin_lock(&ss->id_lock);
4010 /* Don't use 0. allocates an ID of 1-65535 */
4011 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
4012 spin_unlock(&ss->id_lock);
4014 /* Returns error when there are no free spaces for new ID.*/
4019 if (myid > CSS_ID_MAX)
4023 newid->depth = depth;
4027 spin_lock(&ss->id_lock);
4028 idr_remove(&ss->idr, myid);
4029 spin_unlock(&ss->id_lock);
4032 return ERR_PTR(error);
4036 static int __init cgroup_subsys_init_idr(struct cgroup_subsys *ss)
4038 struct css_id *newid;
4039 struct cgroup_subsys_state *rootcss;
4041 spin_lock_init(&ss->id_lock);
4044 rootcss = init_css_set.subsys[ss->subsys_id];
4045 newid = get_new_cssid(ss, 0);
4047 return PTR_ERR(newid);
4049 newid->stack[0] = newid->id;
4050 newid->css = rootcss;
4051 rootcss->id = newid;
4055 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
4056 struct cgroup *child)
4058 int subsys_id, i, depth = 0;
4059 struct cgroup_subsys_state *parent_css, *child_css;
4060 struct css_id *child_id, *parent_id = NULL;
4062 subsys_id = ss->subsys_id;
4063 parent_css = parent->subsys[subsys_id];
4064 child_css = child->subsys[subsys_id];
4065 depth = css_depth(parent_css) + 1;
4066 parent_id = parent_css->id;
4068 child_id = get_new_cssid(ss, depth);
4069 if (IS_ERR(child_id))
4070 return PTR_ERR(child_id);
4072 for (i = 0; i < depth; i++)
4073 child_id->stack[i] = parent_id->stack[i];
4074 child_id->stack[depth] = child_id->id;
4076 * child_id->css pointer will be set after this cgroup is available
4077 * see cgroup_populate_dir()
4079 rcu_assign_pointer(child_css->id, child_id);
4085 * css_lookup - lookup css by id
4086 * @ss: cgroup subsys to be looked into.
4089 * Returns pointer to cgroup_subsys_state if there is valid one with id.
4090 * NULL if not. Should be called under rcu_read_lock()
4092 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
4094 struct css_id *cssid = NULL;
4096 BUG_ON(!ss->use_id);
4097 cssid = idr_find(&ss->idr, id);
4099 if (unlikely(!cssid))
4102 return rcu_dereference(cssid->css);
4106 * css_get_next - lookup next cgroup under specified hierarchy.
4107 * @ss: pointer to subsystem
4108 * @id: current position of iteration.
4109 * @root: pointer to css. search tree under this.
4110 * @foundid: position of found object.
4112 * Search next css under the specified hierarchy of rootid. Calling under
4113 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
4115 struct cgroup_subsys_state *
4116 css_get_next(struct cgroup_subsys *ss, int id,
4117 struct cgroup_subsys_state *root, int *foundid)
4119 struct cgroup_subsys_state *ret = NULL;
4122 int rootid = css_id(root);
4123 int depth = css_depth(root);
4128 BUG_ON(!ss->use_id);
4129 /* fill start point for scan */
4133 * scan next entry from bitmap(tree), tmpid is updated after
4136 spin_lock(&ss->id_lock);
4137 tmp = idr_get_next(&ss->idr, &tmpid);
4138 spin_unlock(&ss->id_lock);
4142 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
4143 ret = rcu_dereference(tmp->css);
4149 /* continue to scan from next id */
4155 #ifdef CONFIG_CGROUP_DEBUG
4156 static struct cgroup_subsys_state *debug_create(struct cgroup_subsys *ss,
4157 struct cgroup *cont)
4159 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4162 return ERR_PTR(-ENOMEM);
4167 static void debug_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
4169 kfree(cont->subsys[debug_subsys_id]);
4172 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
4174 return atomic_read(&cont->count);
4177 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
4179 return cgroup_task_count(cont);
4182 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
4184 return (u64)(unsigned long)current->cgroups;
4187 static u64 current_css_set_refcount_read(struct cgroup *cont,
4193 count = atomic_read(¤t->cgroups->refcount);
4198 static int current_css_set_cg_links_read(struct cgroup *cont,
4200 struct seq_file *seq)
4202 struct cg_cgroup_link *link;
4205 read_lock(&css_set_lock);
4207 cg = rcu_dereference(current->cgroups);
4208 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
4209 struct cgroup *c = link->cgrp;
4213 name = c->dentry->d_name.name;
4216 seq_printf(seq, "Root %d group %s\n",
4217 c->root->hierarchy_id, name);
4220 read_unlock(&css_set_lock);
4224 #define MAX_TASKS_SHOWN_PER_CSS 25
4225 static int cgroup_css_links_read(struct cgroup *cont,
4227 struct seq_file *seq)
4229 struct cg_cgroup_link *link;
4231 read_lock(&css_set_lock);
4232 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
4233 struct css_set *cg = link->cg;
4234 struct task_struct *task;
4236 seq_printf(seq, "css_set %p\n", cg);
4237 list_for_each_entry(task, &cg->tasks, cg_list) {
4238 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
4239 seq_puts(seq, " ...\n");
4242 seq_printf(seq, " task %d\n",
4243 task_pid_vnr(task));
4247 read_unlock(&css_set_lock);
4251 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
4253 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
4256 static struct cftype debug_files[] = {
4258 .name = "cgroup_refcount",
4259 .read_u64 = cgroup_refcount_read,
4262 .name = "taskcount",
4263 .read_u64 = debug_taskcount_read,
4267 .name = "current_css_set",
4268 .read_u64 = current_css_set_read,
4272 .name = "current_css_set_refcount",
4273 .read_u64 = current_css_set_refcount_read,
4277 .name = "current_css_set_cg_links",
4278 .read_seq_string = current_css_set_cg_links_read,
4282 .name = "cgroup_css_links",
4283 .read_seq_string = cgroup_css_links_read,
4287 .name = "releasable",
4288 .read_u64 = releasable_read,
4292 static int debug_populate(struct cgroup_subsys *ss, struct cgroup *cont)
4294 return cgroup_add_files(cont, ss, debug_files,
4295 ARRAY_SIZE(debug_files));
4298 struct cgroup_subsys debug_subsys = {
4300 .create = debug_create,
4301 .destroy = debug_destroy,
4302 .populate = debug_populate,
4303 .subsys_id = debug_subsys_id,
4305 #endif /* CONFIG_CGROUP_DEBUG */