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);
60 /* Generate an array of cgroup subsystem pointers */
61 #define SUBSYS(_x) &_x ## _subsys,
63 static struct cgroup_subsys *subsys[] = {
64 #include <linux/cgroup_subsys.h>
67 #define MAX_CGROUP_ROOT_NAMELEN 64
70 * A cgroupfs_root represents the root of a cgroup hierarchy,
71 * and may be associated with a superblock to form an active
74 struct cgroupfs_root {
75 struct super_block *sb;
78 * The bitmask of subsystems intended to be attached to this
81 unsigned long subsys_bits;
83 /* Unique id for this hierarchy. */
86 /* The bitmask of subsystems currently attached to this hierarchy */
87 unsigned long actual_subsys_bits;
89 /* A list running through the attached subsystems */
90 struct list_head subsys_list;
92 /* The root cgroup for this hierarchy */
93 struct cgroup top_cgroup;
95 /* Tracks how many cgroups are currently defined in hierarchy.*/
96 int number_of_cgroups;
98 /* A list running through the active hierarchies */
99 struct list_head root_list;
101 /* Hierarchy-specific flags */
104 /* The path to use for release notifications. */
105 char release_agent_path[PATH_MAX];
107 /* The name for this hierarchy - may be empty */
108 char name[MAX_CGROUP_ROOT_NAMELEN];
112 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
113 * subsystems that are otherwise unattached - it never has more than a
114 * single cgroup, and all tasks are part of that cgroup.
116 static struct cgroupfs_root rootnode;
119 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
120 * cgroup_subsys->use_id != 0.
122 #define CSS_ID_MAX (65535)
125 * The css to which this ID points. This pointer is set to valid value
126 * after cgroup is populated. If cgroup is removed, this will be NULL.
127 * This pointer is expected to be RCU-safe because destroy()
128 * is called after synchronize_rcu(). But for safe use, css_is_removed()
129 * css_tryget() should be used for avoiding race.
131 struct cgroup_subsys_state *css;
137 * Depth in hierarchy which this ID belongs to.
139 unsigned short depth;
141 * ID is freed by RCU. (and lookup routine is RCU safe.)
143 struct rcu_head rcu_head;
145 * Hierarchy of CSS ID belongs to.
147 unsigned short stack[0]; /* Array of Length (depth+1) */
151 /* The list of hierarchy roots */
153 static LIST_HEAD(roots);
154 static int root_count;
156 static DEFINE_IDA(hierarchy_ida);
157 static int next_hierarchy_id;
158 static DEFINE_SPINLOCK(hierarchy_id_lock);
160 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
161 #define dummytop (&rootnode.top_cgroup)
163 /* This flag indicates whether tasks in the fork and exit paths should
164 * check for fork/exit handlers to call. This avoids us having to do
165 * extra work in the fork/exit path if none of the subsystems need to
168 static int need_forkexit_callback __read_mostly;
170 #ifdef CONFIG_PROVE_LOCKING
171 int cgroup_lock_is_held(void)
173 return lockdep_is_held(&cgroup_mutex);
175 #else /* #ifdef CONFIG_PROVE_LOCKING */
176 int cgroup_lock_is_held(void)
178 return mutex_is_locked(&cgroup_mutex);
180 #endif /* #else #ifdef CONFIG_PROVE_LOCKING */
182 EXPORT_SYMBOL_GPL(cgroup_lock_is_held);
184 /* convenient tests for these bits */
185 inline int cgroup_is_removed(const struct cgroup *cgrp)
187 return test_bit(CGRP_REMOVED, &cgrp->flags);
190 /* bits in struct cgroupfs_root flags field */
192 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
195 static int cgroup_is_releasable(const struct cgroup *cgrp)
198 (1 << CGRP_RELEASABLE) |
199 (1 << CGRP_NOTIFY_ON_RELEASE);
200 return (cgrp->flags & bits) == bits;
203 static int notify_on_release(const struct cgroup *cgrp)
205 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
209 * for_each_subsys() allows you to iterate on each subsystem attached to
210 * an active hierarchy
212 #define for_each_subsys(_root, _ss) \
213 list_for_each_entry(_ss, &_root->subsys_list, sibling)
215 /* for_each_active_root() allows you to iterate across the active hierarchies */
216 #define for_each_active_root(_root) \
217 list_for_each_entry(_root, &roots, root_list)
219 /* the list of cgroups eligible for automatic release. Protected by
220 * release_list_lock */
221 static LIST_HEAD(release_list);
222 static DEFINE_SPINLOCK(release_list_lock);
223 static void cgroup_release_agent(struct work_struct *work);
224 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
225 static void check_for_release(struct cgroup *cgrp);
227 /* Link structure for associating css_set objects with cgroups */
228 struct cg_cgroup_link {
230 * List running through cg_cgroup_links associated with a
231 * cgroup, anchored on cgroup->css_sets
233 struct list_head cgrp_link_list;
236 * List running through cg_cgroup_links pointing at a
237 * single css_set object, anchored on css_set->cg_links
239 struct list_head cg_link_list;
243 /* The default css_set - used by init and its children prior to any
244 * hierarchies being mounted. It contains a pointer to the root state
245 * for each subsystem. Also used to anchor the list of css_sets. Not
246 * reference-counted, to improve performance when child cgroups
247 * haven't been created.
250 static struct css_set init_css_set;
251 static struct cg_cgroup_link init_css_set_link;
253 static int cgroup_subsys_init_idr(struct cgroup_subsys *ss);
255 /* css_set_lock protects the list of css_set objects, and the
256 * chain of tasks off each css_set. Nests outside task->alloc_lock
257 * due to cgroup_iter_start() */
258 static DEFINE_RWLOCK(css_set_lock);
259 static int css_set_count;
262 * hash table for cgroup groups. This improves the performance to find
263 * an existing css_set. This hash doesn't (currently) take into
264 * account cgroups in empty hierarchies.
266 #define CSS_SET_HASH_BITS 7
267 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
268 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
270 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
274 unsigned long tmp = 0UL;
276 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
277 tmp += (unsigned long)css[i];
278 tmp = (tmp >> 16) ^ tmp;
280 index = hash_long(tmp, CSS_SET_HASH_BITS);
282 return &css_set_table[index];
285 static void free_css_set_rcu(struct rcu_head *obj)
287 struct css_set *cg = container_of(obj, struct css_set, rcu_head);
291 /* We don't maintain the lists running through each css_set to its
292 * task until after the first call to cgroup_iter_start(). This
293 * reduces the fork()/exit() overhead for people who have cgroups
294 * compiled into their kernel but not actually in use */
295 static int use_task_css_set_links __read_mostly;
297 static void __put_css_set(struct css_set *cg, int taskexit)
299 struct cg_cgroup_link *link;
300 struct cg_cgroup_link *saved_link;
302 * Ensure that the refcount doesn't hit zero while any readers
303 * can see it. Similar to atomic_dec_and_lock(), but for an
306 if (atomic_add_unless(&cg->refcount, -1, 1))
308 write_lock(&css_set_lock);
309 if (!atomic_dec_and_test(&cg->refcount)) {
310 write_unlock(&css_set_lock);
314 /* This css_set is dead. unlink it and release cgroup refcounts */
315 hlist_del(&cg->hlist);
318 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
320 struct cgroup *cgrp = link->cgrp;
321 list_del(&link->cg_link_list);
322 list_del(&link->cgrp_link_list);
323 if (atomic_dec_and_test(&cgrp->count) &&
324 notify_on_release(cgrp)) {
326 set_bit(CGRP_RELEASABLE, &cgrp->flags);
327 check_for_release(cgrp);
333 write_unlock(&css_set_lock);
334 call_rcu(&cg->rcu_head, free_css_set_rcu);
338 * refcounted get/put for css_set objects
340 static inline void get_css_set(struct css_set *cg)
342 atomic_inc(&cg->refcount);
345 static inline void put_css_set(struct css_set *cg)
347 __put_css_set(cg, 0);
350 static inline void put_css_set_taskexit(struct css_set *cg)
352 __put_css_set(cg, 1);
356 * compare_css_sets - helper function for find_existing_css_set().
357 * @cg: candidate css_set being tested
358 * @old_cg: existing css_set for a task
359 * @new_cgrp: cgroup that's being entered by the task
360 * @template: desired set of css pointers in css_set (pre-calculated)
362 * Returns true if "cg" matches "old_cg" except for the hierarchy
363 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
365 static bool compare_css_sets(struct css_set *cg,
366 struct css_set *old_cg,
367 struct cgroup *new_cgrp,
368 struct cgroup_subsys_state *template[])
370 struct list_head *l1, *l2;
372 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
373 /* Not all subsystems matched */
378 * Compare cgroup pointers in order to distinguish between
379 * different cgroups in heirarchies with no subsystems. We
380 * could get by with just this check alone (and skip the
381 * memcmp above) but on most setups the memcmp check will
382 * avoid the need for this more expensive check on almost all
387 l2 = &old_cg->cg_links;
389 struct cg_cgroup_link *cgl1, *cgl2;
390 struct cgroup *cg1, *cg2;
394 /* See if we reached the end - both lists are equal length. */
395 if (l1 == &cg->cg_links) {
396 BUG_ON(l2 != &old_cg->cg_links);
399 BUG_ON(l2 == &old_cg->cg_links);
401 /* Locate the cgroups associated with these links. */
402 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
403 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
406 /* Hierarchies should be linked in the same order. */
407 BUG_ON(cg1->root != cg2->root);
410 * If this hierarchy is the hierarchy of the cgroup
411 * that's changing, then we need to check that this
412 * css_set points to the new cgroup; if it's any other
413 * hierarchy, then this css_set should point to the
414 * same cgroup as the old css_set.
416 if (cg1->root == new_cgrp->root) {
428 * find_existing_css_set() is a helper for
429 * find_css_set(), and checks to see whether an existing
430 * css_set is suitable.
432 * oldcg: the cgroup group that we're using before the cgroup
435 * cgrp: the cgroup that we're moving into
437 * template: location in which to build the desired set of subsystem
438 * state objects for the new cgroup group
440 static struct css_set *find_existing_css_set(
441 struct css_set *oldcg,
443 struct cgroup_subsys_state *template[])
446 struct cgroupfs_root *root = cgrp->root;
447 struct hlist_head *hhead;
448 struct hlist_node *node;
451 /* Built the set of subsystem state objects that we want to
452 * see in the new css_set */
453 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
454 if (root->subsys_bits & (1UL << i)) {
455 /* Subsystem is in this hierarchy. So we want
456 * the subsystem state from the new
458 template[i] = cgrp->subsys[i];
460 /* Subsystem is not in this hierarchy, so we
461 * don't want to change the subsystem state */
462 template[i] = oldcg->subsys[i];
466 hhead = css_set_hash(template);
467 hlist_for_each_entry(cg, node, hhead, hlist) {
468 if (!compare_css_sets(cg, oldcg, cgrp, template))
471 /* This css_set matches what we need */
475 /* No existing cgroup group matched */
479 static void free_cg_links(struct list_head *tmp)
481 struct cg_cgroup_link *link;
482 struct cg_cgroup_link *saved_link;
484 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
485 list_del(&link->cgrp_link_list);
491 * allocate_cg_links() allocates "count" cg_cgroup_link structures
492 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
493 * success or a negative error
495 static int allocate_cg_links(int count, struct list_head *tmp)
497 struct cg_cgroup_link *link;
500 for (i = 0; i < count; i++) {
501 link = kmalloc(sizeof(*link), GFP_KERNEL);
506 list_add(&link->cgrp_link_list, tmp);
512 * link_css_set - a helper function to link a css_set to a cgroup
513 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
514 * @cg: the css_set to be linked
515 * @cgrp: the destination cgroup
517 static void link_css_set(struct list_head *tmp_cg_links,
518 struct css_set *cg, struct cgroup *cgrp)
520 struct cg_cgroup_link *link;
522 BUG_ON(list_empty(tmp_cg_links));
523 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
527 atomic_inc(&cgrp->count);
528 list_move(&link->cgrp_link_list, &cgrp->css_sets);
530 * Always add links to the tail of the list so that the list
531 * is sorted by order of hierarchy creation
533 list_add_tail(&link->cg_link_list, &cg->cg_links);
537 * find_css_set() takes an existing cgroup group and a
538 * cgroup object, and returns a css_set object that's
539 * equivalent to the old group, but with the given cgroup
540 * substituted into the appropriate hierarchy. Must be called with
543 static struct css_set *find_css_set(
544 struct css_set *oldcg, struct cgroup *cgrp)
547 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
549 struct list_head tmp_cg_links;
551 struct hlist_head *hhead;
552 struct cg_cgroup_link *link;
554 /* First see if we already have a cgroup group that matches
556 read_lock(&css_set_lock);
557 res = find_existing_css_set(oldcg, cgrp, template);
560 read_unlock(&css_set_lock);
565 res = kmalloc(sizeof(*res), GFP_KERNEL);
569 /* Allocate all the cg_cgroup_link objects that we'll need */
570 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
575 atomic_set(&res->refcount, 1);
576 INIT_LIST_HEAD(&res->cg_links);
577 INIT_LIST_HEAD(&res->tasks);
578 INIT_HLIST_NODE(&res->hlist);
580 /* Copy the set of subsystem state objects generated in
581 * find_existing_css_set() */
582 memcpy(res->subsys, template, sizeof(res->subsys));
584 write_lock(&css_set_lock);
585 /* Add reference counts and links from the new css_set. */
586 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
587 struct cgroup *c = link->cgrp;
588 if (c->root == cgrp->root)
590 link_css_set(&tmp_cg_links, res, c);
593 BUG_ON(!list_empty(&tmp_cg_links));
597 /* Add this cgroup group to the hash table */
598 hhead = css_set_hash(res->subsys);
599 hlist_add_head(&res->hlist, hhead);
601 write_unlock(&css_set_lock);
607 * Return the cgroup for "task" from the given hierarchy. Must be
608 * called with cgroup_mutex held.
610 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
611 struct cgroupfs_root *root)
614 struct cgroup *res = NULL;
616 BUG_ON(!mutex_is_locked(&cgroup_mutex));
617 read_lock(&css_set_lock);
619 * No need to lock the task - since we hold cgroup_mutex the
620 * task can't change groups, so the only thing that can happen
621 * is that it exits and its css is set back to init_css_set.
624 if (css == &init_css_set) {
625 res = &root->top_cgroup;
627 struct cg_cgroup_link *link;
628 list_for_each_entry(link, &css->cg_links, cg_link_list) {
629 struct cgroup *c = link->cgrp;
630 if (c->root == root) {
636 read_unlock(&css_set_lock);
642 * There is one global cgroup mutex. We also require taking
643 * task_lock() when dereferencing a task's cgroup subsys pointers.
644 * See "The task_lock() exception", at the end of this comment.
646 * A task must hold cgroup_mutex to modify cgroups.
648 * Any task can increment and decrement the count field without lock.
649 * So in general, code holding cgroup_mutex can't rely on the count
650 * field not changing. However, if the count goes to zero, then only
651 * cgroup_attach_task() can increment it again. Because a count of zero
652 * means that no tasks are currently attached, therefore there is no
653 * way a task attached to that cgroup can fork (the other way to
654 * increment the count). So code holding cgroup_mutex can safely
655 * assume that if the count is zero, it will stay zero. Similarly, if
656 * a task holds cgroup_mutex on a cgroup with zero count, it
657 * knows that the cgroup won't be removed, as cgroup_rmdir()
660 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
661 * (usually) take cgroup_mutex. These are the two most performance
662 * critical pieces of code here. The exception occurs on cgroup_exit(),
663 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
664 * is taken, and if the cgroup count is zero, a usermode call made
665 * to the release agent with the name of the cgroup (path relative to
666 * the root of cgroup file system) as the argument.
668 * A cgroup can only be deleted if both its 'count' of using tasks
669 * is zero, and its list of 'children' cgroups is empty. Since all
670 * tasks in the system use _some_ cgroup, and since there is always at
671 * least one task in the system (init, pid == 1), therefore, top_cgroup
672 * always has either children cgroups and/or using tasks. So we don't
673 * need a special hack to ensure that top_cgroup cannot be deleted.
675 * The task_lock() exception
677 * The need for this exception arises from the action of
678 * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
679 * another. It does so using cgroup_mutex, however there are
680 * several performance critical places that need to reference
681 * task->cgroup without the expense of grabbing a system global
682 * mutex. Therefore except as noted below, when dereferencing or, as
683 * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
684 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
685 * the task_struct routinely used for such matters.
687 * P.S. One more locking exception. RCU is used to guard the
688 * update of a tasks cgroup pointer by cgroup_attach_task()
692 * cgroup_lock - lock out any changes to cgroup structures
695 void cgroup_lock(void)
697 mutex_lock(&cgroup_mutex);
701 * cgroup_unlock - release lock on cgroup changes
703 * Undo the lock taken in a previous cgroup_lock() call.
705 void cgroup_unlock(void)
707 mutex_unlock(&cgroup_mutex);
711 * A couple of forward declarations required, due to cyclic reference loop:
712 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
713 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
717 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
718 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
719 static int cgroup_populate_dir(struct cgroup *cgrp);
720 static const struct inode_operations cgroup_dir_inode_operations;
721 static const struct file_operations proc_cgroupstats_operations;
723 static struct backing_dev_info cgroup_backing_dev_info = {
725 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
728 static int alloc_css_id(struct cgroup_subsys *ss,
729 struct cgroup *parent, struct cgroup *child);
731 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
733 struct inode *inode = new_inode(sb);
736 inode->i_mode = mode;
737 inode->i_uid = current_fsuid();
738 inode->i_gid = current_fsgid();
739 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
740 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
746 * Call subsys's pre_destroy handler.
747 * This is called before css refcnt check.
749 static int cgroup_call_pre_destroy(struct cgroup *cgrp)
751 struct cgroup_subsys *ss;
754 for_each_subsys(cgrp->root, ss)
755 if (ss->pre_destroy) {
756 ret = ss->pre_destroy(ss, cgrp);
763 static void free_cgroup_rcu(struct rcu_head *obj)
765 struct cgroup *cgrp = container_of(obj, struct cgroup, rcu_head);
770 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
772 /* is dentry a directory ? if so, kfree() associated cgroup */
773 if (S_ISDIR(inode->i_mode)) {
774 struct cgroup *cgrp = dentry->d_fsdata;
775 struct cgroup_subsys *ss;
776 BUG_ON(!(cgroup_is_removed(cgrp)));
777 /* It's possible for external users to be holding css
778 * reference counts on a cgroup; css_put() needs to
779 * be able to access the cgroup after decrementing
780 * the reference count in order to know if it needs to
781 * queue the cgroup to be handled by the release
785 mutex_lock(&cgroup_mutex);
787 * Release the subsystem state objects.
789 for_each_subsys(cgrp->root, ss)
790 ss->destroy(ss, cgrp);
792 cgrp->root->number_of_cgroups--;
793 mutex_unlock(&cgroup_mutex);
796 * Drop the active superblock reference that we took when we
799 deactivate_super(cgrp->root->sb);
802 * if we're getting rid of the cgroup, refcount should ensure
803 * that there are no pidlists left.
805 BUG_ON(!list_empty(&cgrp->pidlists));
807 call_rcu(&cgrp->rcu_head, free_cgroup_rcu);
812 static void remove_dir(struct dentry *d)
814 struct dentry *parent = dget(d->d_parent);
817 simple_rmdir(parent->d_inode, d);
821 static void cgroup_clear_directory(struct dentry *dentry)
823 struct list_head *node;
825 BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
826 spin_lock(&dcache_lock);
827 node = dentry->d_subdirs.next;
828 while (node != &dentry->d_subdirs) {
829 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
832 /* This should never be called on a cgroup
833 * directory with child cgroups */
834 BUG_ON(d->d_inode->i_mode & S_IFDIR);
836 spin_unlock(&dcache_lock);
838 simple_unlink(dentry->d_inode, d);
840 spin_lock(&dcache_lock);
842 node = dentry->d_subdirs.next;
844 spin_unlock(&dcache_lock);
848 * NOTE : the dentry must have been dget()'ed
850 static void cgroup_d_remove_dir(struct dentry *dentry)
852 cgroup_clear_directory(dentry);
854 spin_lock(&dcache_lock);
855 list_del_init(&dentry->d_u.d_child);
856 spin_unlock(&dcache_lock);
861 * A queue for waiters to do rmdir() cgroup. A tasks will sleep when
862 * cgroup->count == 0 && list_empty(&cgroup->children) && subsys has some
863 * reference to css->refcnt. In general, this refcnt is expected to goes down
866 * CGRP_WAIT_ON_RMDIR flag is set under cgroup's inode->i_mutex;
868 DECLARE_WAIT_QUEUE_HEAD(cgroup_rmdir_waitq);
870 static void cgroup_wakeup_rmdir_waiter(struct cgroup *cgrp)
872 if (unlikely(test_and_clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags)))
873 wake_up_all(&cgroup_rmdir_waitq);
876 void cgroup_exclude_rmdir(struct cgroup_subsys_state *css)
881 void cgroup_release_and_wakeup_rmdir(struct cgroup_subsys_state *css)
883 cgroup_wakeup_rmdir_waiter(css->cgroup);
888 static int rebind_subsystems(struct cgroupfs_root *root,
889 unsigned long final_bits)
891 unsigned long added_bits, removed_bits;
892 struct cgroup *cgrp = &root->top_cgroup;
895 removed_bits = root->actual_subsys_bits & ~final_bits;
896 added_bits = final_bits & ~root->actual_subsys_bits;
897 /* Check that any added subsystems are currently free */
898 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
899 unsigned long bit = 1UL << i;
900 struct cgroup_subsys *ss = subsys[i];
901 if (!(bit & added_bits))
903 if (ss->root != &rootnode) {
904 /* Subsystem isn't free */
909 /* Currently we don't handle adding/removing subsystems when
910 * any child cgroups exist. This is theoretically supportable
911 * but involves complex error handling, so it's being left until
913 if (root->number_of_cgroups > 1)
916 /* Process each subsystem */
917 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
918 struct cgroup_subsys *ss = subsys[i];
919 unsigned long bit = 1UL << i;
920 if (bit & added_bits) {
921 /* We're binding this subsystem to this hierarchy */
922 BUG_ON(cgrp->subsys[i]);
923 BUG_ON(!dummytop->subsys[i]);
924 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
925 mutex_lock(&ss->hierarchy_mutex);
926 cgrp->subsys[i] = dummytop->subsys[i];
927 cgrp->subsys[i]->cgroup = cgrp;
928 list_move(&ss->sibling, &root->subsys_list);
932 mutex_unlock(&ss->hierarchy_mutex);
933 } else if (bit & removed_bits) {
934 /* We're removing this subsystem */
935 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
936 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
937 mutex_lock(&ss->hierarchy_mutex);
939 ss->bind(ss, dummytop);
940 dummytop->subsys[i]->cgroup = dummytop;
941 cgrp->subsys[i] = NULL;
942 subsys[i]->root = &rootnode;
943 list_move(&ss->sibling, &rootnode.subsys_list);
944 mutex_unlock(&ss->hierarchy_mutex);
945 } else if (bit & final_bits) {
946 /* Subsystem state should already exist */
947 BUG_ON(!cgrp->subsys[i]);
949 /* Subsystem state shouldn't exist */
950 BUG_ON(cgrp->subsys[i]);
953 root->subsys_bits = root->actual_subsys_bits = final_bits;
959 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
961 struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
962 struct cgroup_subsys *ss;
964 mutex_lock(&cgroup_mutex);
965 for_each_subsys(root, ss)
966 seq_printf(seq, ",%s", ss->name);
967 if (test_bit(ROOT_NOPREFIX, &root->flags))
968 seq_puts(seq, ",noprefix");
969 if (strlen(root->release_agent_path))
970 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
971 if (strlen(root->name))
972 seq_printf(seq, ",name=%s", root->name);
973 mutex_unlock(&cgroup_mutex);
977 struct cgroup_sb_opts {
978 unsigned long subsys_bits;
982 /* User explicitly requested empty subsystem */
985 struct cgroupfs_root *new_root;
989 /* Convert a hierarchy specifier into a bitmask of subsystems and
991 static int parse_cgroupfs_options(char *data,
992 struct cgroup_sb_opts *opts)
994 char *token, *o = data ?: "all";
995 unsigned long mask = (unsigned long)-1;
997 #ifdef CONFIG_CPUSETS
998 mask = ~(1UL << cpuset_subsys_id);
1001 memset(opts, 0, sizeof(*opts));
1003 while ((token = strsep(&o, ",")) != NULL) {
1006 if (!strcmp(token, "all")) {
1007 /* Add all non-disabled subsystems */
1009 opts->subsys_bits = 0;
1010 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1011 struct cgroup_subsys *ss = subsys[i];
1013 opts->subsys_bits |= 1ul << i;
1015 } else if (!strcmp(token, "none")) {
1016 /* Explicitly have no subsystems */
1018 } else if (!strcmp(token, "noprefix")) {
1019 set_bit(ROOT_NOPREFIX, &opts->flags);
1020 } else if (!strncmp(token, "release_agent=", 14)) {
1021 /* Specifying two release agents is forbidden */
1022 if (opts->release_agent)
1024 opts->release_agent =
1025 kstrndup(token + 14, PATH_MAX, GFP_KERNEL);
1026 if (!opts->release_agent)
1028 } else if (!strncmp(token, "name=", 5)) {
1030 const char *name = token + 5;
1031 /* Can't specify an empty name */
1034 /* Must match [\w.-]+ */
1035 for (i = 0; i < strlen(name); i++) {
1039 if ((c == '.') || (c == '-') || (c == '_'))
1043 /* Specifying two names is forbidden */
1046 opts->name = kstrndup(name,
1047 MAX_CGROUP_ROOT_NAMELEN,
1052 struct cgroup_subsys *ss;
1054 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1056 if (!strcmp(token, ss->name)) {
1058 set_bit(i, &opts->subsys_bits);
1062 if (i == CGROUP_SUBSYS_COUNT)
1067 /* Consistency checks */
1070 * Option noprefix was introduced just for backward compatibility
1071 * with the old cpuset, so we allow noprefix only if mounting just
1072 * the cpuset subsystem.
1074 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1075 (opts->subsys_bits & mask))
1079 /* Can't specify "none" and some subsystems */
1080 if (opts->subsys_bits && opts->none)
1084 * We either have to specify by name or by subsystems. (So all
1085 * empty hierarchies must have a name).
1087 if (!opts->subsys_bits && !opts->name)
1093 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1096 struct cgroupfs_root *root = sb->s_fs_info;
1097 struct cgroup *cgrp = &root->top_cgroup;
1098 struct cgroup_sb_opts opts;
1101 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1102 mutex_lock(&cgroup_mutex);
1104 /* See what subsystems are wanted */
1105 ret = parse_cgroupfs_options(data, &opts);
1109 /* Don't allow flags to change at remount */
1110 if (opts.flags != root->flags) {
1115 /* Don't allow name to change at remount */
1116 if (opts.name && strcmp(opts.name, root->name)) {
1121 ret = rebind_subsystems(root, opts.subsys_bits);
1125 /* (re)populate subsystem files */
1126 cgroup_populate_dir(cgrp);
1128 if (opts.release_agent)
1129 strcpy(root->release_agent_path, opts.release_agent);
1131 kfree(opts.release_agent);
1133 mutex_unlock(&cgroup_mutex);
1134 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1139 static const struct super_operations cgroup_ops = {
1140 .statfs = simple_statfs,
1141 .drop_inode = generic_delete_inode,
1142 .show_options = cgroup_show_options,
1143 .remount_fs = cgroup_remount,
1146 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1148 INIT_LIST_HEAD(&cgrp->sibling);
1149 INIT_LIST_HEAD(&cgrp->children);
1150 INIT_LIST_HEAD(&cgrp->css_sets);
1151 INIT_LIST_HEAD(&cgrp->release_list);
1152 INIT_LIST_HEAD(&cgrp->pidlists);
1153 mutex_init(&cgrp->pidlist_mutex);
1156 static void init_cgroup_root(struct cgroupfs_root *root)
1158 struct cgroup *cgrp = &root->top_cgroup;
1159 INIT_LIST_HEAD(&root->subsys_list);
1160 INIT_LIST_HEAD(&root->root_list);
1161 root->number_of_cgroups = 1;
1163 cgrp->top_cgroup = cgrp;
1164 init_cgroup_housekeeping(cgrp);
1167 static bool init_root_id(struct cgroupfs_root *root)
1172 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1174 spin_lock(&hierarchy_id_lock);
1175 /* Try to allocate the next unused ID */
1176 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1177 &root->hierarchy_id);
1179 /* Try again starting from 0 */
1180 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1182 next_hierarchy_id = root->hierarchy_id + 1;
1183 } else if (ret != -EAGAIN) {
1184 /* Can only get here if the 31-bit IDR is full ... */
1187 spin_unlock(&hierarchy_id_lock);
1192 static int cgroup_test_super(struct super_block *sb, void *data)
1194 struct cgroup_sb_opts *opts = data;
1195 struct cgroupfs_root *root = sb->s_fs_info;
1197 /* If we asked for a name then it must match */
1198 if (opts->name && strcmp(opts->name, root->name))
1202 * If we asked for subsystems (or explicitly for no
1203 * subsystems) then they must match
1205 if ((opts->subsys_bits || opts->none)
1206 && (opts->subsys_bits != root->subsys_bits))
1212 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1214 struct cgroupfs_root *root;
1216 if (!opts->subsys_bits && !opts->none)
1219 root = kzalloc(sizeof(*root), GFP_KERNEL);
1221 return ERR_PTR(-ENOMEM);
1223 if (!init_root_id(root)) {
1225 return ERR_PTR(-ENOMEM);
1227 init_cgroup_root(root);
1229 root->subsys_bits = opts->subsys_bits;
1230 root->flags = opts->flags;
1231 if (opts->release_agent)
1232 strcpy(root->release_agent_path, opts->release_agent);
1234 strcpy(root->name, opts->name);
1238 static void cgroup_drop_root(struct cgroupfs_root *root)
1243 BUG_ON(!root->hierarchy_id);
1244 spin_lock(&hierarchy_id_lock);
1245 ida_remove(&hierarchy_ida, root->hierarchy_id);
1246 spin_unlock(&hierarchy_id_lock);
1250 static int cgroup_set_super(struct super_block *sb, void *data)
1253 struct cgroup_sb_opts *opts = data;
1255 /* If we don't have a new root, we can't set up a new sb */
1256 if (!opts->new_root)
1259 BUG_ON(!opts->subsys_bits && !opts->none);
1261 ret = set_anon_super(sb, NULL);
1265 sb->s_fs_info = opts->new_root;
1266 opts->new_root->sb = sb;
1268 sb->s_blocksize = PAGE_CACHE_SIZE;
1269 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1270 sb->s_magic = CGROUP_SUPER_MAGIC;
1271 sb->s_op = &cgroup_ops;
1276 static int cgroup_get_rootdir(struct super_block *sb)
1278 struct inode *inode =
1279 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1280 struct dentry *dentry;
1285 inode->i_fop = &simple_dir_operations;
1286 inode->i_op = &cgroup_dir_inode_operations;
1287 /* directories start off with i_nlink == 2 (for "." entry) */
1289 dentry = d_alloc_root(inode);
1294 sb->s_root = dentry;
1298 static int cgroup_get_sb(struct file_system_type *fs_type,
1299 int flags, const char *unused_dev_name,
1300 void *data, struct vfsmount *mnt)
1302 struct cgroup_sb_opts opts;
1303 struct cgroupfs_root *root;
1305 struct super_block *sb;
1306 struct cgroupfs_root *new_root;
1308 /* First find the desired set of subsystems */
1309 ret = parse_cgroupfs_options(data, &opts);
1314 * Allocate a new cgroup root. We may not need it if we're
1315 * reusing an existing hierarchy.
1317 new_root = cgroup_root_from_opts(&opts);
1318 if (IS_ERR(new_root)) {
1319 ret = PTR_ERR(new_root);
1322 opts.new_root = new_root;
1324 /* Locate an existing or new sb for this hierarchy */
1325 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, &opts);
1328 cgroup_drop_root(opts.new_root);
1332 root = sb->s_fs_info;
1334 if (root == opts.new_root) {
1335 /* We used the new root structure, so this is a new hierarchy */
1336 struct list_head tmp_cg_links;
1337 struct cgroup *root_cgrp = &root->top_cgroup;
1338 struct inode *inode;
1339 struct cgroupfs_root *existing_root;
1342 BUG_ON(sb->s_root != NULL);
1344 ret = cgroup_get_rootdir(sb);
1346 goto drop_new_super;
1347 inode = sb->s_root->d_inode;
1349 mutex_lock(&inode->i_mutex);
1350 mutex_lock(&cgroup_mutex);
1352 if (strlen(root->name)) {
1353 /* Check for name clashes with existing mounts */
1354 for_each_active_root(existing_root) {
1355 if (!strcmp(existing_root->name, root->name)) {
1357 mutex_unlock(&cgroup_mutex);
1358 mutex_unlock(&inode->i_mutex);
1359 goto drop_new_super;
1365 * We're accessing css_set_count without locking
1366 * css_set_lock here, but that's OK - it can only be
1367 * increased by someone holding cgroup_lock, and
1368 * that's us. The worst that can happen is that we
1369 * have some link structures left over
1371 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1373 mutex_unlock(&cgroup_mutex);
1374 mutex_unlock(&inode->i_mutex);
1375 goto drop_new_super;
1378 ret = rebind_subsystems(root, root->subsys_bits);
1379 if (ret == -EBUSY) {
1380 mutex_unlock(&cgroup_mutex);
1381 mutex_unlock(&inode->i_mutex);
1382 free_cg_links(&tmp_cg_links);
1383 goto drop_new_super;
1386 /* EBUSY should be the only error here */
1389 list_add(&root->root_list, &roots);
1392 sb->s_root->d_fsdata = root_cgrp;
1393 root->top_cgroup.dentry = sb->s_root;
1395 /* Link the top cgroup in this hierarchy into all
1396 * the css_set objects */
1397 write_lock(&css_set_lock);
1398 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1399 struct hlist_head *hhead = &css_set_table[i];
1400 struct hlist_node *node;
1403 hlist_for_each_entry(cg, node, hhead, hlist)
1404 link_css_set(&tmp_cg_links, cg, root_cgrp);
1406 write_unlock(&css_set_lock);
1408 free_cg_links(&tmp_cg_links);
1410 BUG_ON(!list_empty(&root_cgrp->sibling));
1411 BUG_ON(!list_empty(&root_cgrp->children));
1412 BUG_ON(root->number_of_cgroups != 1);
1414 cgroup_populate_dir(root_cgrp);
1415 mutex_unlock(&cgroup_mutex);
1416 mutex_unlock(&inode->i_mutex);
1419 * We re-used an existing hierarchy - the new root (if
1420 * any) is not needed
1422 cgroup_drop_root(opts.new_root);
1425 simple_set_mnt(mnt, sb);
1426 kfree(opts.release_agent);
1431 deactivate_locked_super(sb);
1433 kfree(opts.release_agent);
1439 static void cgroup_kill_sb(struct super_block *sb) {
1440 struct cgroupfs_root *root = sb->s_fs_info;
1441 struct cgroup *cgrp = &root->top_cgroup;
1443 struct cg_cgroup_link *link;
1444 struct cg_cgroup_link *saved_link;
1448 BUG_ON(root->number_of_cgroups != 1);
1449 BUG_ON(!list_empty(&cgrp->children));
1450 BUG_ON(!list_empty(&cgrp->sibling));
1452 mutex_lock(&cgroup_mutex);
1454 /* Rebind all subsystems back to the default hierarchy */
1455 ret = rebind_subsystems(root, 0);
1456 /* Shouldn't be able to fail ... */
1460 * Release all the links from css_sets to this hierarchy's
1463 write_lock(&css_set_lock);
1465 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1467 list_del(&link->cg_link_list);
1468 list_del(&link->cgrp_link_list);
1471 write_unlock(&css_set_lock);
1473 if (!list_empty(&root->root_list)) {
1474 list_del(&root->root_list);
1478 mutex_unlock(&cgroup_mutex);
1480 kill_litter_super(sb);
1481 cgroup_drop_root(root);
1484 static struct file_system_type cgroup_fs_type = {
1486 .get_sb = cgroup_get_sb,
1487 .kill_sb = cgroup_kill_sb,
1490 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1492 return dentry->d_fsdata;
1495 static inline struct cftype *__d_cft(struct dentry *dentry)
1497 return dentry->d_fsdata;
1501 * cgroup_path - generate the path of a cgroup
1502 * @cgrp: the cgroup in question
1503 * @buf: the buffer to write the path into
1504 * @buflen: the length of the buffer
1506 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1507 * reference. Writes path of cgroup into buf. Returns 0 on success,
1510 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1513 struct dentry *dentry = rcu_dereference(cgrp->dentry);
1515 if (!dentry || cgrp == dummytop) {
1517 * Inactive subsystems have no dentry for their root
1524 start = buf + buflen;
1528 int len = dentry->d_name.len;
1529 if ((start -= len) < buf)
1530 return -ENAMETOOLONG;
1531 memcpy(start, cgrp->dentry->d_name.name, len);
1532 cgrp = cgrp->parent;
1535 dentry = rcu_dereference(cgrp->dentry);
1539 return -ENAMETOOLONG;
1542 memmove(buf, start, buf + buflen - start);
1547 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1548 * @cgrp: the cgroup the task is attaching to
1549 * @tsk: the task to be attached
1551 * Call holding cgroup_mutex. May take task_lock of
1552 * the task 'tsk' during call.
1554 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1557 struct cgroup_subsys *ss;
1558 struct cgroup *oldcgrp;
1560 struct css_set *newcg;
1561 struct cgroupfs_root *root = cgrp->root;
1563 /* Nothing to do if the task is already in that cgroup */
1564 oldcgrp = task_cgroup_from_root(tsk, root);
1565 if (cgrp == oldcgrp)
1568 for_each_subsys(root, ss) {
1569 if (ss->can_attach) {
1570 retval = ss->can_attach(ss, cgrp, tsk, false);
1581 * Locate or allocate a new css_set for this task,
1582 * based on its final set of cgroups
1584 newcg = find_css_set(cg, cgrp);
1590 if (tsk->flags & PF_EXITING) {
1595 rcu_assign_pointer(tsk->cgroups, newcg);
1598 /* Update the css_set linked lists if we're using them */
1599 write_lock(&css_set_lock);
1600 if (!list_empty(&tsk->cg_list)) {
1601 list_del(&tsk->cg_list);
1602 list_add(&tsk->cg_list, &newcg->tasks);
1604 write_unlock(&css_set_lock);
1606 for_each_subsys(root, ss) {
1608 ss->attach(ss, cgrp, oldcgrp, tsk, false);
1610 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1615 * wake up rmdir() waiter. the rmdir should fail since the cgroup
1616 * is no longer empty.
1618 cgroup_wakeup_rmdir_waiter(cgrp);
1623 * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
1624 * held. May take task_lock of task
1626 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
1628 struct task_struct *tsk;
1629 const struct cred *cred = current_cred(), *tcred;
1634 tsk = find_task_by_vpid(pid);
1635 if (!tsk || tsk->flags & PF_EXITING) {
1640 tcred = __task_cred(tsk);
1642 cred->euid != tcred->uid &&
1643 cred->euid != tcred->suid) {
1647 get_task_struct(tsk);
1651 get_task_struct(tsk);
1654 ret = cgroup_attach_task(cgrp, tsk);
1655 put_task_struct(tsk);
1659 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
1662 if (!cgroup_lock_live_group(cgrp))
1664 ret = attach_task_by_pid(cgrp, pid);
1670 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1671 * @cgrp: the cgroup to be checked for liveness
1673 * On success, returns true; the lock should be later released with
1674 * cgroup_unlock(). On failure returns false with no lock held.
1676 bool cgroup_lock_live_group(struct cgroup *cgrp)
1678 mutex_lock(&cgroup_mutex);
1679 if (cgroup_is_removed(cgrp)) {
1680 mutex_unlock(&cgroup_mutex);
1686 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1689 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1690 if (!cgroup_lock_live_group(cgrp))
1692 strcpy(cgrp->root->release_agent_path, buffer);
1697 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1698 struct seq_file *seq)
1700 if (!cgroup_lock_live_group(cgrp))
1702 seq_puts(seq, cgrp->root->release_agent_path);
1703 seq_putc(seq, '\n');
1708 /* A buffer size big enough for numbers or short strings */
1709 #define CGROUP_LOCAL_BUFFER_SIZE 64
1711 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1713 const char __user *userbuf,
1714 size_t nbytes, loff_t *unused_ppos)
1716 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1722 if (nbytes >= sizeof(buffer))
1724 if (copy_from_user(buffer, userbuf, nbytes))
1727 buffer[nbytes] = 0; /* nul-terminate */
1728 if (cft->write_u64) {
1729 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
1732 retval = cft->write_u64(cgrp, cft, val);
1734 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
1737 retval = cft->write_s64(cgrp, cft, val);
1744 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1746 const char __user *userbuf,
1747 size_t nbytes, loff_t *unused_ppos)
1749 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1751 size_t max_bytes = cft->max_write_len;
1752 char *buffer = local_buffer;
1755 max_bytes = sizeof(local_buffer) - 1;
1756 if (nbytes >= max_bytes)
1758 /* Allocate a dynamic buffer if we need one */
1759 if (nbytes >= sizeof(local_buffer)) {
1760 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1764 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
1769 buffer[nbytes] = 0; /* nul-terminate */
1770 retval = cft->write_string(cgrp, cft, strstrip(buffer));
1774 if (buffer != local_buffer)
1779 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1780 size_t nbytes, loff_t *ppos)
1782 struct cftype *cft = __d_cft(file->f_dentry);
1783 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1785 if (cgroup_is_removed(cgrp))
1788 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1789 if (cft->write_u64 || cft->write_s64)
1790 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1791 if (cft->write_string)
1792 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1794 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1795 return ret ? ret : nbytes;
1800 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1802 char __user *buf, size_t nbytes,
1805 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1806 u64 val = cft->read_u64(cgrp, cft);
1807 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1809 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1812 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1814 char __user *buf, size_t nbytes,
1817 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1818 s64 val = cft->read_s64(cgrp, cft);
1819 int len = sprintf(tmp, "%lld\n", (long long) val);
1821 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1824 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1825 size_t nbytes, loff_t *ppos)
1827 struct cftype *cft = __d_cft(file->f_dentry);
1828 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1830 if (cgroup_is_removed(cgrp))
1834 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1836 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1838 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1843 * seqfile ops/methods for returning structured data. Currently just
1844 * supports string->u64 maps, but can be extended in future.
1847 struct cgroup_seqfile_state {
1849 struct cgroup *cgroup;
1852 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1854 struct seq_file *sf = cb->state;
1855 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1858 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1860 struct cgroup_seqfile_state *state = m->private;
1861 struct cftype *cft = state->cft;
1862 if (cft->read_map) {
1863 struct cgroup_map_cb cb = {
1864 .fill = cgroup_map_add,
1867 return cft->read_map(state->cgroup, cft, &cb);
1869 return cft->read_seq_string(state->cgroup, cft, m);
1872 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
1874 struct seq_file *seq = file->private_data;
1875 kfree(seq->private);
1876 return single_release(inode, file);
1879 static const struct file_operations cgroup_seqfile_operations = {
1881 .write = cgroup_file_write,
1882 .llseek = seq_lseek,
1883 .release = cgroup_seqfile_release,
1886 static int cgroup_file_open(struct inode *inode, struct file *file)
1891 err = generic_file_open(inode, file);
1894 cft = __d_cft(file->f_dentry);
1896 if (cft->read_map || cft->read_seq_string) {
1897 struct cgroup_seqfile_state *state =
1898 kzalloc(sizeof(*state), GFP_USER);
1902 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
1903 file->f_op = &cgroup_seqfile_operations;
1904 err = single_open(file, cgroup_seqfile_show, state);
1907 } else if (cft->open)
1908 err = cft->open(inode, file);
1915 static int cgroup_file_release(struct inode *inode, struct file *file)
1917 struct cftype *cft = __d_cft(file->f_dentry);
1919 return cft->release(inode, file);
1924 * cgroup_rename - Only allow simple rename of directories in place.
1926 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
1927 struct inode *new_dir, struct dentry *new_dentry)
1929 if (!S_ISDIR(old_dentry->d_inode->i_mode))
1931 if (new_dentry->d_inode)
1933 if (old_dir != new_dir)
1935 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1938 static const struct file_operations cgroup_file_operations = {
1939 .read = cgroup_file_read,
1940 .write = cgroup_file_write,
1941 .llseek = generic_file_llseek,
1942 .open = cgroup_file_open,
1943 .release = cgroup_file_release,
1946 static const struct inode_operations cgroup_dir_inode_operations = {
1947 .lookup = simple_lookup,
1948 .mkdir = cgroup_mkdir,
1949 .rmdir = cgroup_rmdir,
1950 .rename = cgroup_rename,
1953 static int cgroup_create_file(struct dentry *dentry, mode_t mode,
1954 struct super_block *sb)
1956 static const struct dentry_operations cgroup_dops = {
1957 .d_iput = cgroup_diput,
1960 struct inode *inode;
1964 if (dentry->d_inode)
1967 inode = cgroup_new_inode(mode, sb);
1971 if (S_ISDIR(mode)) {
1972 inode->i_op = &cgroup_dir_inode_operations;
1973 inode->i_fop = &simple_dir_operations;
1975 /* start off with i_nlink == 2 (for "." entry) */
1978 /* start with the directory inode held, so that we can
1979 * populate it without racing with another mkdir */
1980 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
1981 } else if (S_ISREG(mode)) {
1983 inode->i_fop = &cgroup_file_operations;
1985 dentry->d_op = &cgroup_dops;
1986 d_instantiate(dentry, inode);
1987 dget(dentry); /* Extra count - pin the dentry in core */
1992 * cgroup_create_dir - create a directory for an object.
1993 * @cgrp: the cgroup we create the directory for. It must have a valid
1994 * ->parent field. And we are going to fill its ->dentry field.
1995 * @dentry: dentry of the new cgroup
1996 * @mode: mode to set on new directory.
1998 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
2001 struct dentry *parent;
2004 parent = cgrp->parent->dentry;
2005 error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
2007 dentry->d_fsdata = cgrp;
2008 inc_nlink(parent->d_inode);
2009 rcu_assign_pointer(cgrp->dentry, dentry);
2018 * cgroup_file_mode - deduce file mode of a control file
2019 * @cft: the control file in question
2021 * returns cft->mode if ->mode is not 0
2022 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2023 * returns S_IRUGO if it has only a read handler
2024 * returns S_IWUSR if it has only a write hander
2026 static mode_t cgroup_file_mode(const struct cftype *cft)
2033 if (cft->read || cft->read_u64 || cft->read_s64 ||
2034 cft->read_map || cft->read_seq_string)
2037 if (cft->write || cft->write_u64 || cft->write_s64 ||
2038 cft->write_string || cft->trigger)
2044 int cgroup_add_file(struct cgroup *cgrp,
2045 struct cgroup_subsys *subsys,
2046 const struct cftype *cft)
2048 struct dentry *dir = cgrp->dentry;
2049 struct dentry *dentry;
2053 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2054 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2055 strcpy(name, subsys->name);
2058 strcat(name, cft->name);
2059 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2060 dentry = lookup_one_len(name, dir, strlen(name));
2061 if (!IS_ERR(dentry)) {
2062 mode = cgroup_file_mode(cft);
2063 error = cgroup_create_file(dentry, mode | S_IFREG,
2066 dentry->d_fsdata = (void *)cft;
2069 error = PTR_ERR(dentry);
2073 int cgroup_add_files(struct cgroup *cgrp,
2074 struct cgroup_subsys *subsys,
2075 const struct cftype cft[],
2079 for (i = 0; i < count; i++) {
2080 err = cgroup_add_file(cgrp, subsys, &cft[i]);
2088 * cgroup_task_count - count the number of tasks in a cgroup.
2089 * @cgrp: the cgroup in question
2091 * Return the number of tasks in the cgroup.
2093 int cgroup_task_count(const struct cgroup *cgrp)
2096 struct cg_cgroup_link *link;
2098 read_lock(&css_set_lock);
2099 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2100 count += atomic_read(&link->cg->refcount);
2102 read_unlock(&css_set_lock);
2107 * Advance a list_head iterator. The iterator should be positioned at
2108 * the start of a css_set
2110 static void cgroup_advance_iter(struct cgroup *cgrp,
2111 struct cgroup_iter *it)
2113 struct list_head *l = it->cg_link;
2114 struct cg_cgroup_link *link;
2117 /* Advance to the next non-empty css_set */
2120 if (l == &cgrp->css_sets) {
2124 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2126 } while (list_empty(&cg->tasks));
2128 it->task = cg->tasks.next;
2132 * To reduce the fork() overhead for systems that are not actually
2133 * using their cgroups capability, we don't maintain the lists running
2134 * through each css_set to its tasks until we see the list actually
2135 * used - in other words after the first call to cgroup_iter_start().
2137 * The tasklist_lock is not held here, as do_each_thread() and
2138 * while_each_thread() are protected by RCU.
2140 static void cgroup_enable_task_cg_lists(void)
2142 struct task_struct *p, *g;
2143 write_lock(&css_set_lock);
2144 use_task_css_set_links = 1;
2145 do_each_thread(g, p) {
2148 * We should check if the process is exiting, otherwise
2149 * it will race with cgroup_exit() in that the list
2150 * entry won't be deleted though the process has exited.
2152 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2153 list_add(&p->cg_list, &p->cgroups->tasks);
2155 } while_each_thread(g, p);
2156 write_unlock(&css_set_lock);
2159 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
2162 * The first time anyone tries to iterate across a cgroup,
2163 * we need to enable the list linking each css_set to its
2164 * tasks, and fix up all existing tasks.
2166 if (!use_task_css_set_links)
2167 cgroup_enable_task_cg_lists();
2169 read_lock(&css_set_lock);
2170 it->cg_link = &cgrp->css_sets;
2171 cgroup_advance_iter(cgrp, it);
2174 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
2175 struct cgroup_iter *it)
2177 struct task_struct *res;
2178 struct list_head *l = it->task;
2179 struct cg_cgroup_link *link;
2181 /* If the iterator cg is NULL, we have no tasks */
2184 res = list_entry(l, struct task_struct, cg_list);
2185 /* Advance iterator to find next entry */
2187 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
2188 if (l == &link->cg->tasks) {
2189 /* We reached the end of this task list - move on to
2190 * the next cg_cgroup_link */
2191 cgroup_advance_iter(cgrp, it);
2198 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
2200 read_unlock(&css_set_lock);
2203 static inline int started_after_time(struct task_struct *t1,
2204 struct timespec *time,
2205 struct task_struct *t2)
2207 int start_diff = timespec_compare(&t1->start_time, time);
2208 if (start_diff > 0) {
2210 } else if (start_diff < 0) {
2214 * Arbitrarily, if two processes started at the same
2215 * time, we'll say that the lower pointer value
2216 * started first. Note that t2 may have exited by now
2217 * so this may not be a valid pointer any longer, but
2218 * that's fine - it still serves to distinguish
2219 * between two tasks started (effectively) simultaneously.
2226 * This function is a callback from heap_insert() and is used to order
2228 * In this case we order the heap in descending task start time.
2230 static inline int started_after(void *p1, void *p2)
2232 struct task_struct *t1 = p1;
2233 struct task_struct *t2 = p2;
2234 return started_after_time(t1, &t2->start_time, t2);
2238 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
2239 * @scan: struct cgroup_scanner containing arguments for the scan
2241 * Arguments include pointers to callback functions test_task() and
2243 * Iterate through all the tasks in a cgroup, calling test_task() for each,
2244 * and if it returns true, call process_task() for it also.
2245 * The test_task pointer may be NULL, meaning always true (select all tasks).
2246 * Effectively duplicates cgroup_iter_{start,next,end}()
2247 * but does not lock css_set_lock for the call to process_task().
2248 * The struct cgroup_scanner may be embedded in any structure of the caller's
2250 * It is guaranteed that process_task() will act on every task that
2251 * is a member of the cgroup for the duration of this call. This
2252 * function may or may not call process_task() for tasks that exit
2253 * or move to a different cgroup during the call, or are forked or
2254 * move into the cgroup during the call.
2256 * Note that test_task() may be called with locks held, and may in some
2257 * situations be called multiple times for the same task, so it should
2259 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
2260 * pre-allocated and will be used for heap operations (and its "gt" member will
2261 * be overwritten), else a temporary heap will be used (allocation of which
2262 * may cause this function to fail).
2264 int cgroup_scan_tasks(struct cgroup_scanner *scan)
2267 struct cgroup_iter it;
2268 struct task_struct *p, *dropped;
2269 /* Never dereference latest_task, since it's not refcounted */
2270 struct task_struct *latest_task = NULL;
2271 struct ptr_heap tmp_heap;
2272 struct ptr_heap *heap;
2273 struct timespec latest_time = { 0, 0 };
2276 /* The caller supplied our heap and pre-allocated its memory */
2278 heap->gt = &started_after;
2280 /* We need to allocate our own heap memory */
2282 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2284 /* cannot allocate the heap */
2290 * Scan tasks in the cgroup, using the scanner's "test_task" callback
2291 * to determine which are of interest, and using the scanner's
2292 * "process_task" callback to process any of them that need an update.
2293 * Since we don't want to hold any locks during the task updates,
2294 * gather tasks to be processed in a heap structure.
2295 * The heap is sorted by descending task start time.
2296 * If the statically-sized heap fills up, we overflow tasks that
2297 * started later, and in future iterations only consider tasks that
2298 * started after the latest task in the previous pass. This
2299 * guarantees forward progress and that we don't miss any tasks.
2302 cgroup_iter_start(scan->cg, &it);
2303 while ((p = cgroup_iter_next(scan->cg, &it))) {
2305 * Only affect tasks that qualify per the caller's callback,
2306 * if he provided one
2308 if (scan->test_task && !scan->test_task(p, scan))
2311 * Only process tasks that started after the last task
2314 if (!started_after_time(p, &latest_time, latest_task))
2316 dropped = heap_insert(heap, p);
2317 if (dropped == NULL) {
2319 * The new task was inserted; the heap wasn't
2323 } else if (dropped != p) {
2325 * The new task was inserted, and pushed out a
2329 put_task_struct(dropped);
2332 * Else the new task was newer than anything already in
2333 * the heap and wasn't inserted
2336 cgroup_iter_end(scan->cg, &it);
2339 for (i = 0; i < heap->size; i++) {
2340 struct task_struct *q = heap->ptrs[i];
2342 latest_time = q->start_time;
2345 /* Process the task per the caller's callback */
2346 scan->process_task(q, scan);
2350 * If we had to process any tasks at all, scan again
2351 * in case some of them were in the middle of forking
2352 * children that didn't get processed.
2353 * Not the most efficient way to do it, but it avoids
2354 * having to take callback_mutex in the fork path
2358 if (heap == &tmp_heap)
2359 heap_free(&tmp_heap);
2364 * Stuff for reading the 'tasks'/'procs' files.
2366 * Reading this file can return large amounts of data if a cgroup has
2367 * *lots* of attached tasks. So it may need several calls to read(),
2368 * but we cannot guarantee that the information we produce is correct
2369 * unless we produce it entirely atomically.
2374 * The following two functions "fix" the issue where there are more pids
2375 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
2376 * TODO: replace with a kernel-wide solution to this problem
2378 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
2379 static void *pidlist_allocate(int count)
2381 if (PIDLIST_TOO_LARGE(count))
2382 return vmalloc(count * sizeof(pid_t));
2384 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
2386 static void pidlist_free(void *p)
2388 if (is_vmalloc_addr(p))
2393 static void *pidlist_resize(void *p, int newcount)
2396 /* note: if new alloc fails, old p will still be valid either way */
2397 if (is_vmalloc_addr(p)) {
2398 newlist = vmalloc(newcount * sizeof(pid_t));
2401 memcpy(newlist, p, newcount * sizeof(pid_t));
2404 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
2410 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
2411 * If the new stripped list is sufficiently smaller and there's enough memory
2412 * to allocate a new buffer, will let go of the unneeded memory. Returns the
2413 * number of unique elements.
2415 /* is the size difference enough that we should re-allocate the array? */
2416 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
2417 static int pidlist_uniq(pid_t **p, int length)
2424 * we presume the 0th element is unique, so i starts at 1. trivial
2425 * edge cases first; no work needs to be done for either
2427 if (length == 0 || length == 1)
2429 /* src and dest walk down the list; dest counts unique elements */
2430 for (src = 1; src < length; src++) {
2431 /* find next unique element */
2432 while (list[src] == list[src-1]) {
2437 /* dest always points to where the next unique element goes */
2438 list[dest] = list[src];
2443 * if the length difference is large enough, we want to allocate a
2444 * smaller buffer to save memory. if this fails due to out of memory,
2445 * we'll just stay with what we've got.
2447 if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
2448 newlist = pidlist_resize(list, dest);
2455 static int cmppid(const void *a, const void *b)
2457 return *(pid_t *)a - *(pid_t *)b;
2461 * find the appropriate pidlist for our purpose (given procs vs tasks)
2462 * returns with the lock on that pidlist already held, and takes care
2463 * of the use count, or returns NULL with no locks held if we're out of
2466 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
2467 enum cgroup_filetype type)
2469 struct cgroup_pidlist *l;
2470 /* don't need task_nsproxy() if we're looking at ourself */
2471 struct pid_namespace *ns = get_pid_ns(current->nsproxy->pid_ns);
2473 * We can't drop the pidlist_mutex before taking the l->mutex in case
2474 * the last ref-holder is trying to remove l from the list at the same
2475 * time. Holding the pidlist_mutex precludes somebody taking whichever
2476 * list we find out from under us - compare release_pid_array().
2478 mutex_lock(&cgrp->pidlist_mutex);
2479 list_for_each_entry(l, &cgrp->pidlists, links) {
2480 if (l->key.type == type && l->key.ns == ns) {
2481 /* found a matching list - drop the extra refcount */
2483 /* make sure l doesn't vanish out from under us */
2484 down_write(&l->mutex);
2485 mutex_unlock(&cgrp->pidlist_mutex);
2489 /* entry not found; create a new one */
2490 l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
2492 mutex_unlock(&cgrp->pidlist_mutex);
2496 init_rwsem(&l->mutex);
2497 down_write(&l->mutex);
2500 l->use_count = 0; /* don't increment here */
2503 list_add(&l->links, &cgrp->pidlists);
2504 mutex_unlock(&cgrp->pidlist_mutex);
2509 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
2511 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
2512 struct cgroup_pidlist **lp)
2516 int pid, n = 0; /* used for populating the array */
2517 struct cgroup_iter it;
2518 struct task_struct *tsk;
2519 struct cgroup_pidlist *l;
2522 * If cgroup gets more users after we read count, we won't have
2523 * enough space - tough. This race is indistinguishable to the
2524 * caller from the case that the additional cgroup users didn't
2525 * show up until sometime later on.
2527 length = cgroup_task_count(cgrp);
2528 array = pidlist_allocate(length);
2531 /* now, populate the array */
2532 cgroup_iter_start(cgrp, &it);
2533 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2534 if (unlikely(n == length))
2536 /* get tgid or pid for procs or tasks file respectively */
2537 if (type == CGROUP_FILE_PROCS)
2538 pid = task_tgid_vnr(tsk);
2540 pid = task_pid_vnr(tsk);
2541 if (pid > 0) /* make sure to only use valid results */
2544 cgroup_iter_end(cgrp, &it);
2546 /* now sort & (if procs) strip out duplicates */
2547 sort(array, length, sizeof(pid_t), cmppid, NULL);
2548 if (type == CGROUP_FILE_PROCS)
2549 length = pidlist_uniq(&array, length);
2550 l = cgroup_pidlist_find(cgrp, type);
2552 pidlist_free(array);
2555 /* store array, freeing old if necessary - lock already held */
2556 pidlist_free(l->list);
2560 up_write(&l->mutex);
2566 * cgroupstats_build - build and fill cgroupstats
2567 * @stats: cgroupstats to fill information into
2568 * @dentry: A dentry entry belonging to the cgroup for which stats have
2571 * Build and fill cgroupstats so that taskstats can export it to user
2574 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2577 struct cgroup *cgrp;
2578 struct cgroup_iter it;
2579 struct task_struct *tsk;
2582 * Validate dentry by checking the superblock operations,
2583 * and make sure it's a directory.
2585 if (dentry->d_sb->s_op != &cgroup_ops ||
2586 !S_ISDIR(dentry->d_inode->i_mode))
2590 cgrp = dentry->d_fsdata;
2592 cgroup_iter_start(cgrp, &it);
2593 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2594 switch (tsk->state) {
2596 stats->nr_running++;
2598 case TASK_INTERRUPTIBLE:
2599 stats->nr_sleeping++;
2601 case TASK_UNINTERRUPTIBLE:
2602 stats->nr_uninterruptible++;
2605 stats->nr_stopped++;
2608 if (delayacct_is_task_waiting_on_io(tsk))
2609 stats->nr_io_wait++;
2613 cgroup_iter_end(cgrp, &it);
2621 * seq_file methods for the tasks/procs files. The seq_file position is the
2622 * next pid to display; the seq_file iterator is a pointer to the pid
2623 * in the cgroup->l->list array.
2626 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
2629 * Initially we receive a position value that corresponds to
2630 * one more than the last pid shown (or 0 on the first call or
2631 * after a seek to the start). Use a binary-search to find the
2632 * next pid to display, if any
2634 struct cgroup_pidlist *l = s->private;
2635 int index = 0, pid = *pos;
2638 down_read(&l->mutex);
2640 int end = l->length;
2642 while (index < end) {
2643 int mid = (index + end) / 2;
2644 if (l->list[mid] == pid) {
2647 } else if (l->list[mid] <= pid)
2653 /* If we're off the end of the array, we're done */
2654 if (index >= l->length)
2656 /* Update the abstract position to be the actual pid that we found */
2657 iter = l->list + index;
2662 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
2664 struct cgroup_pidlist *l = s->private;
2668 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
2670 struct cgroup_pidlist *l = s->private;
2672 pid_t *end = l->list + l->length;
2674 * Advance to the next pid in the array. If this goes off the
2686 static int cgroup_pidlist_show(struct seq_file *s, void *v)
2688 return seq_printf(s, "%d\n", *(int *)v);
2692 * seq_operations functions for iterating on pidlists through seq_file -
2693 * independent of whether it's tasks or procs
2695 static const struct seq_operations cgroup_pidlist_seq_operations = {
2696 .start = cgroup_pidlist_start,
2697 .stop = cgroup_pidlist_stop,
2698 .next = cgroup_pidlist_next,
2699 .show = cgroup_pidlist_show,
2702 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
2705 * the case where we're the last user of this particular pidlist will
2706 * have us remove it from the cgroup's list, which entails taking the
2707 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
2708 * pidlist_mutex, we have to take pidlist_mutex first.
2710 mutex_lock(&l->owner->pidlist_mutex);
2711 down_write(&l->mutex);
2712 BUG_ON(!l->use_count);
2713 if (!--l->use_count) {
2714 /* we're the last user if refcount is 0; remove and free */
2715 list_del(&l->links);
2716 mutex_unlock(&l->owner->pidlist_mutex);
2717 pidlist_free(l->list);
2718 put_pid_ns(l->key.ns);
2719 up_write(&l->mutex);
2723 mutex_unlock(&l->owner->pidlist_mutex);
2724 up_write(&l->mutex);
2727 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
2729 struct cgroup_pidlist *l;
2730 if (!(file->f_mode & FMODE_READ))
2733 * the seq_file will only be initialized if the file was opened for
2734 * reading; hence we check if it's not null only in that case.
2736 l = ((struct seq_file *)file->private_data)->private;
2737 cgroup_release_pid_array(l);
2738 return seq_release(inode, file);
2741 static const struct file_operations cgroup_pidlist_operations = {
2743 .llseek = seq_lseek,
2744 .write = cgroup_file_write,
2745 .release = cgroup_pidlist_release,
2749 * The following functions handle opens on a file that displays a pidlist
2750 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
2753 /* helper function for the two below it */
2754 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
2756 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2757 struct cgroup_pidlist *l;
2760 /* Nothing to do for write-only files */
2761 if (!(file->f_mode & FMODE_READ))
2764 /* have the array populated */
2765 retval = pidlist_array_load(cgrp, type, &l);
2768 /* configure file information */
2769 file->f_op = &cgroup_pidlist_operations;
2771 retval = seq_open(file, &cgroup_pidlist_seq_operations);
2773 cgroup_release_pid_array(l);
2776 ((struct seq_file *)file->private_data)->private = l;
2779 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2781 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
2783 static int cgroup_procs_open(struct inode *unused, struct file *file)
2785 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
2788 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2791 return notify_on_release(cgrp);
2794 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2798 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2800 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2802 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2807 * for the common functions, 'private' gives the type of file
2809 /* for hysterical raisins, we can't put this on the older files */
2810 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
2811 static struct cftype files[] = {
2814 .open = cgroup_tasks_open,
2815 .write_u64 = cgroup_tasks_write,
2816 .release = cgroup_pidlist_release,
2817 .mode = S_IRUGO | S_IWUSR,
2820 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
2821 .open = cgroup_procs_open,
2822 /* .write_u64 = cgroup_procs_write, TODO */
2823 .release = cgroup_pidlist_release,
2827 .name = "notify_on_release",
2828 .read_u64 = cgroup_read_notify_on_release,
2829 .write_u64 = cgroup_write_notify_on_release,
2833 static struct cftype cft_release_agent = {
2834 .name = "release_agent",
2835 .read_seq_string = cgroup_release_agent_show,
2836 .write_string = cgroup_release_agent_write,
2837 .max_write_len = PATH_MAX,
2840 static int cgroup_populate_dir(struct cgroup *cgrp)
2843 struct cgroup_subsys *ss;
2845 /* First clear out any existing files */
2846 cgroup_clear_directory(cgrp->dentry);
2848 err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2852 if (cgrp == cgrp->top_cgroup) {
2853 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2857 for_each_subsys(cgrp->root, ss) {
2858 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2861 /* This cgroup is ready now */
2862 for_each_subsys(cgrp->root, ss) {
2863 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2865 * Update id->css pointer and make this css visible from
2866 * CSS ID functions. This pointer will be dereferened
2867 * from RCU-read-side without locks.
2870 rcu_assign_pointer(css->id->css, css);
2876 static void init_cgroup_css(struct cgroup_subsys_state *css,
2877 struct cgroup_subsys *ss,
2878 struct cgroup *cgrp)
2881 atomic_set(&css->refcnt, 1);
2884 if (cgrp == dummytop)
2885 set_bit(CSS_ROOT, &css->flags);
2886 BUG_ON(cgrp->subsys[ss->subsys_id]);
2887 cgrp->subsys[ss->subsys_id] = css;
2890 static void cgroup_lock_hierarchy(struct cgroupfs_root *root)
2892 /* We need to take each hierarchy_mutex in a consistent order */
2895 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2896 struct cgroup_subsys *ss = subsys[i];
2897 if (ss->root == root)
2898 mutex_lock(&ss->hierarchy_mutex);
2902 static void cgroup_unlock_hierarchy(struct cgroupfs_root *root)
2906 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2907 struct cgroup_subsys *ss = subsys[i];
2908 if (ss->root == root)
2909 mutex_unlock(&ss->hierarchy_mutex);
2914 * cgroup_create - create a cgroup
2915 * @parent: cgroup that will be parent of the new cgroup
2916 * @dentry: dentry of the new cgroup
2917 * @mode: mode to set on new inode
2919 * Must be called with the mutex on the parent inode held
2921 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
2924 struct cgroup *cgrp;
2925 struct cgroupfs_root *root = parent->root;
2927 struct cgroup_subsys *ss;
2928 struct super_block *sb = root->sb;
2930 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
2934 /* Grab a reference on the superblock so the hierarchy doesn't
2935 * get deleted on unmount if there are child cgroups. This
2936 * can be done outside cgroup_mutex, since the sb can't
2937 * disappear while someone has an open control file on the
2939 atomic_inc(&sb->s_active);
2941 mutex_lock(&cgroup_mutex);
2943 init_cgroup_housekeeping(cgrp);
2945 cgrp->parent = parent;
2946 cgrp->root = parent->root;
2947 cgrp->top_cgroup = parent->top_cgroup;
2949 if (notify_on_release(parent))
2950 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2952 for_each_subsys(root, ss) {
2953 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
2959 init_cgroup_css(css, ss, cgrp);
2961 err = alloc_css_id(ss, parent, cgrp);
2965 /* At error, ->destroy() callback has to free assigned ID. */
2968 cgroup_lock_hierarchy(root);
2969 list_add(&cgrp->sibling, &cgrp->parent->children);
2970 cgroup_unlock_hierarchy(root);
2971 root->number_of_cgroups++;
2973 err = cgroup_create_dir(cgrp, dentry, mode);
2977 /* The cgroup directory was pre-locked for us */
2978 BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
2980 err = cgroup_populate_dir(cgrp);
2981 /* If err < 0, we have a half-filled directory - oh well ;) */
2983 mutex_unlock(&cgroup_mutex);
2984 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
2990 cgroup_lock_hierarchy(root);
2991 list_del(&cgrp->sibling);
2992 cgroup_unlock_hierarchy(root);
2993 root->number_of_cgroups--;
2997 for_each_subsys(root, ss) {
2998 if (cgrp->subsys[ss->subsys_id])
2999 ss->destroy(ss, cgrp);
3002 mutex_unlock(&cgroup_mutex);
3004 /* Release the reference count that we took on the superblock */
3005 deactivate_super(sb);
3011 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
3013 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
3015 /* the vfs holds inode->i_mutex already */
3016 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
3019 static int cgroup_has_css_refs(struct cgroup *cgrp)
3021 /* Check the reference count on each subsystem. Since we
3022 * already established that there are no tasks in the
3023 * cgroup, if the css refcount is also 1, then there should
3024 * be no outstanding references, so the subsystem is safe to
3025 * destroy. We scan across all subsystems rather than using
3026 * the per-hierarchy linked list of mounted subsystems since
3027 * we can be called via check_for_release() with no
3028 * synchronization other than RCU, and the subsystem linked
3029 * list isn't RCU-safe */
3031 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3032 struct cgroup_subsys *ss = subsys[i];
3033 struct cgroup_subsys_state *css;
3034 /* Skip subsystems not in this hierarchy */
3035 if (ss->root != cgrp->root)
3037 css = cgrp->subsys[ss->subsys_id];
3038 /* When called from check_for_release() it's possible
3039 * that by this point the cgroup has been removed
3040 * and the css deleted. But a false-positive doesn't
3041 * matter, since it can only happen if the cgroup
3042 * has been deleted and hence no longer needs the
3043 * release agent to be called anyway. */
3044 if (css && (atomic_read(&css->refcnt) > 1))
3051 * Atomically mark all (or else none) of the cgroup's CSS objects as
3052 * CSS_REMOVED. Return true on success, or false if the cgroup has
3053 * busy subsystems. Call with cgroup_mutex held
3056 static int cgroup_clear_css_refs(struct cgroup *cgrp)
3058 struct cgroup_subsys *ss;
3059 unsigned long flags;
3060 bool failed = false;
3061 local_irq_save(flags);
3062 for_each_subsys(cgrp->root, ss) {
3063 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3066 /* We can only remove a CSS with a refcnt==1 */
3067 refcnt = atomic_read(&css->refcnt);
3074 * Drop the refcnt to 0 while we check other
3075 * subsystems. This will cause any racing
3076 * css_tryget() to spin until we set the
3077 * CSS_REMOVED bits or abort
3079 if (atomic_cmpxchg(&css->refcnt, refcnt, 0) == refcnt)
3085 for_each_subsys(cgrp->root, ss) {
3086 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3089 * Restore old refcnt if we previously managed
3090 * to clear it from 1 to 0
3092 if (!atomic_read(&css->refcnt))
3093 atomic_set(&css->refcnt, 1);
3095 /* Commit the fact that the CSS is removed */
3096 set_bit(CSS_REMOVED, &css->flags);
3099 local_irq_restore(flags);
3103 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
3105 struct cgroup *cgrp = dentry->d_fsdata;
3107 struct cgroup *parent;
3111 /* the vfs holds both inode->i_mutex already */
3113 mutex_lock(&cgroup_mutex);
3114 if (atomic_read(&cgrp->count) != 0) {
3115 mutex_unlock(&cgroup_mutex);
3118 if (!list_empty(&cgrp->children)) {
3119 mutex_unlock(&cgroup_mutex);
3122 mutex_unlock(&cgroup_mutex);
3125 * In general, subsystem has no css->refcnt after pre_destroy(). But
3126 * in racy cases, subsystem may have to get css->refcnt after
3127 * pre_destroy() and it makes rmdir return with -EBUSY. This sometimes
3128 * make rmdir return -EBUSY too often. To avoid that, we use waitqueue
3129 * for cgroup's rmdir. CGRP_WAIT_ON_RMDIR is for synchronizing rmdir
3130 * and subsystem's reference count handling. Please see css_get/put
3131 * and css_tryget() and cgroup_wakeup_rmdir_waiter() implementation.
3133 set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3136 * Call pre_destroy handlers of subsys. Notify subsystems
3137 * that rmdir() request comes.
3139 ret = cgroup_call_pre_destroy(cgrp);
3141 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3145 mutex_lock(&cgroup_mutex);
3146 parent = cgrp->parent;
3147 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
3148 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3149 mutex_unlock(&cgroup_mutex);
3152 prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
3153 if (!cgroup_clear_css_refs(cgrp)) {
3154 mutex_unlock(&cgroup_mutex);
3156 * Because someone may call cgroup_wakeup_rmdir_waiter() before
3157 * prepare_to_wait(), we need to check this flag.
3159 if (test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))
3161 finish_wait(&cgroup_rmdir_waitq, &wait);
3162 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3163 if (signal_pending(current))
3167 /* NO css_tryget() can success after here. */
3168 finish_wait(&cgroup_rmdir_waitq, &wait);
3169 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3171 spin_lock(&release_list_lock);
3172 set_bit(CGRP_REMOVED, &cgrp->flags);
3173 if (!list_empty(&cgrp->release_list))
3174 list_del(&cgrp->release_list);
3175 spin_unlock(&release_list_lock);
3177 cgroup_lock_hierarchy(cgrp->root);
3178 /* delete this cgroup from parent->children */
3179 list_del(&cgrp->sibling);
3180 cgroup_unlock_hierarchy(cgrp->root);
3182 spin_lock(&cgrp->dentry->d_lock);
3183 d = dget(cgrp->dentry);
3184 spin_unlock(&d->d_lock);
3186 cgroup_d_remove_dir(d);
3189 set_bit(CGRP_RELEASABLE, &parent->flags);
3190 check_for_release(parent);
3192 mutex_unlock(&cgroup_mutex);
3196 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
3198 struct cgroup_subsys_state *css;
3200 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
3202 /* Create the top cgroup state for this subsystem */
3203 list_add(&ss->sibling, &rootnode.subsys_list);
3204 ss->root = &rootnode;
3205 css = ss->create(ss, dummytop);
3206 /* We don't handle early failures gracefully */
3207 BUG_ON(IS_ERR(css));
3208 init_cgroup_css(css, ss, dummytop);
3210 /* Update the init_css_set to contain a subsys
3211 * pointer to this state - since the subsystem is
3212 * newly registered, all tasks and hence the
3213 * init_css_set is in the subsystem's top cgroup. */
3214 init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
3216 need_forkexit_callback |= ss->fork || ss->exit;
3218 /* At system boot, before all subsystems have been
3219 * registered, no tasks have been forked, so we don't
3220 * need to invoke fork callbacks here. */
3221 BUG_ON(!list_empty(&init_task.tasks));
3223 mutex_init(&ss->hierarchy_mutex);
3224 lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
3229 * cgroup_init_early - cgroup initialization at system boot
3231 * Initialize cgroups at system boot, and initialize any
3232 * subsystems that request early init.
3234 int __init cgroup_init_early(void)
3237 atomic_set(&init_css_set.refcount, 1);
3238 INIT_LIST_HEAD(&init_css_set.cg_links);
3239 INIT_LIST_HEAD(&init_css_set.tasks);
3240 INIT_HLIST_NODE(&init_css_set.hlist);
3242 init_cgroup_root(&rootnode);
3244 init_task.cgroups = &init_css_set;
3246 init_css_set_link.cg = &init_css_set;
3247 init_css_set_link.cgrp = dummytop;
3248 list_add(&init_css_set_link.cgrp_link_list,
3249 &rootnode.top_cgroup.css_sets);
3250 list_add(&init_css_set_link.cg_link_list,
3251 &init_css_set.cg_links);
3253 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
3254 INIT_HLIST_HEAD(&css_set_table[i]);
3256 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3257 struct cgroup_subsys *ss = subsys[i];
3260 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
3261 BUG_ON(!ss->create);
3262 BUG_ON(!ss->destroy);
3263 if (ss->subsys_id != i) {
3264 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
3265 ss->name, ss->subsys_id);
3270 cgroup_init_subsys(ss);
3276 * cgroup_init - cgroup initialization
3278 * Register cgroup filesystem and /proc file, and initialize
3279 * any subsystems that didn't request early init.
3281 int __init cgroup_init(void)
3285 struct hlist_head *hhead;
3287 err = bdi_init(&cgroup_backing_dev_info);
3291 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3292 struct cgroup_subsys *ss = subsys[i];
3293 if (!ss->early_init)
3294 cgroup_init_subsys(ss);
3296 cgroup_subsys_init_idr(ss);
3299 /* Add init_css_set to the hash table */
3300 hhead = css_set_hash(init_css_set.subsys);
3301 hlist_add_head(&init_css_set.hlist, hhead);
3302 BUG_ON(!init_root_id(&rootnode));
3303 err = register_filesystem(&cgroup_fs_type);
3307 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
3311 bdi_destroy(&cgroup_backing_dev_info);
3317 * proc_cgroup_show()
3318 * - Print task's cgroup paths into seq_file, one line for each hierarchy
3319 * - Used for /proc/<pid>/cgroup.
3320 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
3321 * doesn't really matter if tsk->cgroup changes after we read it,
3322 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
3323 * anyway. No need to check that tsk->cgroup != NULL, thanks to
3324 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
3325 * cgroup to top_cgroup.
3328 /* TODO: Use a proper seq_file iterator */
3329 static int proc_cgroup_show(struct seq_file *m, void *v)
3332 struct task_struct *tsk;
3335 struct cgroupfs_root *root;
3338 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3344 tsk = get_pid_task(pid, PIDTYPE_PID);
3350 mutex_lock(&cgroup_mutex);
3352 for_each_active_root(root) {
3353 struct cgroup_subsys *ss;
3354 struct cgroup *cgrp;
3357 seq_printf(m, "%d:", root->hierarchy_id);
3358 for_each_subsys(root, ss)
3359 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
3360 if (strlen(root->name))
3361 seq_printf(m, "%sname=%s", count ? "," : "",
3364 cgrp = task_cgroup_from_root(tsk, root);
3365 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
3373 mutex_unlock(&cgroup_mutex);
3374 put_task_struct(tsk);
3381 static int cgroup_open(struct inode *inode, struct file *file)
3383 struct pid *pid = PROC_I(inode)->pid;
3384 return single_open(file, proc_cgroup_show, pid);
3387 const struct file_operations proc_cgroup_operations = {
3388 .open = cgroup_open,
3390 .llseek = seq_lseek,
3391 .release = single_release,
3394 /* Display information about each subsystem and each hierarchy */
3395 static int proc_cgroupstats_show(struct seq_file *m, void *v)
3399 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
3400 mutex_lock(&cgroup_mutex);
3401 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3402 struct cgroup_subsys *ss = subsys[i];
3403 seq_printf(m, "%s\t%d\t%d\t%d\n",
3404 ss->name, ss->root->hierarchy_id,
3405 ss->root->number_of_cgroups, !ss->disabled);
3407 mutex_unlock(&cgroup_mutex);
3411 static int cgroupstats_open(struct inode *inode, struct file *file)
3413 return single_open(file, proc_cgroupstats_show, NULL);
3416 static const struct file_operations proc_cgroupstats_operations = {
3417 .open = cgroupstats_open,
3419 .llseek = seq_lseek,
3420 .release = single_release,
3424 * cgroup_fork - attach newly forked task to its parents cgroup.
3425 * @child: pointer to task_struct of forking parent process.
3427 * Description: A task inherits its parent's cgroup at fork().
3429 * A pointer to the shared css_set was automatically copied in
3430 * fork.c by dup_task_struct(). However, we ignore that copy, since
3431 * it was not made under the protection of RCU or cgroup_mutex, so
3432 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
3433 * have already changed current->cgroups, allowing the previously
3434 * referenced cgroup group to be removed and freed.
3436 * At the point that cgroup_fork() is called, 'current' is the parent
3437 * task, and the passed argument 'child' points to the child task.
3439 void cgroup_fork(struct task_struct *child)
3442 child->cgroups = current->cgroups;
3443 get_css_set(child->cgroups);
3444 task_unlock(current);
3445 INIT_LIST_HEAD(&child->cg_list);
3449 * cgroup_fork_callbacks - run fork callbacks
3450 * @child: the new task
3452 * Called on a new task very soon before adding it to the
3453 * tasklist. No need to take any locks since no-one can
3454 * be operating on this task.
3456 void cgroup_fork_callbacks(struct task_struct *child)
3458 if (need_forkexit_callback) {
3460 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3461 struct cgroup_subsys *ss = subsys[i];
3463 ss->fork(ss, child);
3469 * cgroup_post_fork - called on a new task after adding it to the task list
3470 * @child: the task in question
3472 * Adds the task to the list running through its css_set if necessary.
3473 * Has to be after the task is visible on the task list in case we race
3474 * with the first call to cgroup_iter_start() - to guarantee that the
3475 * new task ends up on its list.
3477 void cgroup_post_fork(struct task_struct *child)
3479 if (use_task_css_set_links) {
3480 write_lock(&css_set_lock);
3482 if (list_empty(&child->cg_list))
3483 list_add(&child->cg_list, &child->cgroups->tasks);
3485 write_unlock(&css_set_lock);
3489 * cgroup_exit - detach cgroup from exiting task
3490 * @tsk: pointer to task_struct of exiting process
3491 * @run_callback: run exit callbacks?
3493 * Description: Detach cgroup from @tsk and release it.
3495 * Note that cgroups marked notify_on_release force every task in
3496 * them to take the global cgroup_mutex mutex when exiting.
3497 * This could impact scaling on very large systems. Be reluctant to
3498 * use notify_on_release cgroups where very high task exit scaling
3499 * is required on large systems.
3501 * the_top_cgroup_hack:
3503 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
3505 * We call cgroup_exit() while the task is still competent to
3506 * handle notify_on_release(), then leave the task attached to the
3507 * root cgroup in each hierarchy for the remainder of its exit.
3509 * To do this properly, we would increment the reference count on
3510 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
3511 * code we would add a second cgroup function call, to drop that
3512 * reference. This would just create an unnecessary hot spot on
3513 * the top_cgroup reference count, to no avail.
3515 * Normally, holding a reference to a cgroup without bumping its
3516 * count is unsafe. The cgroup could go away, or someone could
3517 * attach us to a different cgroup, decrementing the count on
3518 * the first cgroup that we never incremented. But in this case,
3519 * top_cgroup isn't going away, and either task has PF_EXITING set,
3520 * which wards off any cgroup_attach_task() attempts, or task is a failed
3521 * fork, never visible to cgroup_attach_task.
3523 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
3528 if (run_callbacks && need_forkexit_callback) {
3529 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3530 struct cgroup_subsys *ss = subsys[i];
3537 * Unlink from the css_set task list if necessary.
3538 * Optimistically check cg_list before taking
3541 if (!list_empty(&tsk->cg_list)) {
3542 write_lock(&css_set_lock);
3543 if (!list_empty(&tsk->cg_list))
3544 list_del(&tsk->cg_list);
3545 write_unlock(&css_set_lock);
3548 /* Reassign the task to the init_css_set. */
3551 tsk->cgroups = &init_css_set;
3554 put_css_set_taskexit(cg);
3558 * cgroup_clone - clone the cgroup the given subsystem is attached to
3559 * @tsk: the task to be moved
3560 * @subsys: the given subsystem
3561 * @nodename: the name for the new cgroup
3563 * Duplicate the current cgroup in the hierarchy that the given
3564 * subsystem is attached to, and move this task into the new
3567 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
3570 struct dentry *dentry;
3572 struct cgroup *parent, *child;
3573 struct inode *inode;
3575 struct cgroupfs_root *root;
3576 struct cgroup_subsys *ss;
3578 /* We shouldn't be called by an unregistered subsystem */
3579 BUG_ON(!subsys->active);
3581 /* First figure out what hierarchy and cgroup we're dealing
3582 * with, and pin them so we can drop cgroup_mutex */
3583 mutex_lock(&cgroup_mutex);
3585 root = subsys->root;
3586 if (root == &rootnode) {
3587 mutex_unlock(&cgroup_mutex);
3591 /* Pin the hierarchy */
3592 if (!atomic_inc_not_zero(&root->sb->s_active)) {
3593 /* We race with the final deactivate_super() */
3594 mutex_unlock(&cgroup_mutex);
3598 /* Keep the cgroup alive */
3600 parent = task_cgroup(tsk, subsys->subsys_id);
3605 mutex_unlock(&cgroup_mutex);
3607 /* Now do the VFS work to create a cgroup */
3608 inode = parent->dentry->d_inode;
3610 /* Hold the parent directory mutex across this operation to
3611 * stop anyone else deleting the new cgroup */
3612 mutex_lock(&inode->i_mutex);
3613 dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
3614 if (IS_ERR(dentry)) {
3616 "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
3618 ret = PTR_ERR(dentry);
3622 /* Create the cgroup directory, which also creates the cgroup */
3623 ret = vfs_mkdir(inode, dentry, 0755);
3624 child = __d_cgrp(dentry);
3628 "Failed to create cgroup %s: %d\n", nodename,
3633 /* The cgroup now exists. Retake cgroup_mutex and check
3634 * that we're still in the same state that we thought we
3636 mutex_lock(&cgroup_mutex);
3637 if ((root != subsys->root) ||
3638 (parent != task_cgroup(tsk, subsys->subsys_id))) {
3639 /* Aargh, we raced ... */
3640 mutex_unlock(&inode->i_mutex);
3643 deactivate_super(root->sb);
3644 /* The cgroup is still accessible in the VFS, but
3645 * we're not going to try to rmdir() it at this
3648 "Race in cgroup_clone() - leaking cgroup %s\n",
3653 /* do any required auto-setup */
3654 for_each_subsys(root, ss) {
3656 ss->post_clone(ss, child);
3659 /* All seems fine. Finish by moving the task into the new cgroup */
3660 ret = cgroup_attach_task(child, tsk);
3661 mutex_unlock(&cgroup_mutex);
3664 mutex_unlock(&inode->i_mutex);
3666 mutex_lock(&cgroup_mutex);
3668 mutex_unlock(&cgroup_mutex);
3669 deactivate_super(root->sb);
3674 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
3675 * @cgrp: the cgroup in question
3676 * @task: the task in question
3678 * See if @cgrp is a descendant of @task's cgroup in the appropriate
3681 * If we are sending in dummytop, then presumably we are creating
3682 * the top cgroup in the subsystem.
3684 * Called only by the ns (nsproxy) cgroup.
3686 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
3689 struct cgroup *target;
3691 if (cgrp == dummytop)
3694 target = task_cgroup_from_root(task, cgrp->root);
3695 while (cgrp != target && cgrp!= cgrp->top_cgroup)
3696 cgrp = cgrp->parent;
3697 ret = (cgrp == target);
3701 static void check_for_release(struct cgroup *cgrp)
3703 /* All of these checks rely on RCU to keep the cgroup
3704 * structure alive */
3705 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
3706 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
3707 /* Control Group is currently removeable. If it's not
3708 * already queued for a userspace notification, queue
3710 int need_schedule_work = 0;
3711 spin_lock(&release_list_lock);
3712 if (!cgroup_is_removed(cgrp) &&
3713 list_empty(&cgrp->release_list)) {
3714 list_add(&cgrp->release_list, &release_list);
3715 need_schedule_work = 1;
3717 spin_unlock(&release_list_lock);
3718 if (need_schedule_work)
3719 schedule_work(&release_agent_work);
3723 void __css_put(struct cgroup_subsys_state *css)
3725 struct cgroup *cgrp = css->cgroup;
3728 val = atomic_dec_return(&css->refcnt);
3730 if (notify_on_release(cgrp)) {
3731 set_bit(CGRP_RELEASABLE, &cgrp->flags);
3732 check_for_release(cgrp);
3734 cgroup_wakeup_rmdir_waiter(cgrp);
3737 WARN_ON_ONCE(val < 1);
3741 * Notify userspace when a cgroup is released, by running the
3742 * configured release agent with the name of the cgroup (path
3743 * relative to the root of cgroup file system) as the argument.
3745 * Most likely, this user command will try to rmdir this cgroup.
3747 * This races with the possibility that some other task will be
3748 * attached to this cgroup before it is removed, or that some other
3749 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
3750 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
3751 * unused, and this cgroup will be reprieved from its death sentence,
3752 * to continue to serve a useful existence. Next time it's released,
3753 * we will get notified again, if it still has 'notify_on_release' set.
3755 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
3756 * means only wait until the task is successfully execve()'d. The
3757 * separate release agent task is forked by call_usermodehelper(),
3758 * then control in this thread returns here, without waiting for the
3759 * release agent task. We don't bother to wait because the caller of
3760 * this routine has no use for the exit status of the release agent
3761 * task, so no sense holding our caller up for that.
3763 static void cgroup_release_agent(struct work_struct *work)
3765 BUG_ON(work != &release_agent_work);
3766 mutex_lock(&cgroup_mutex);
3767 spin_lock(&release_list_lock);
3768 while (!list_empty(&release_list)) {
3769 char *argv[3], *envp[3];
3771 char *pathbuf = NULL, *agentbuf = NULL;
3772 struct cgroup *cgrp = list_entry(release_list.next,
3775 list_del_init(&cgrp->release_list);
3776 spin_unlock(&release_list_lock);
3777 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3780 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
3782 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
3787 argv[i++] = agentbuf;
3788 argv[i++] = pathbuf;
3792 /* minimal command environment */
3793 envp[i++] = "HOME=/";
3794 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3797 /* Drop the lock while we invoke the usermode helper,
3798 * since the exec could involve hitting disk and hence
3799 * be a slow process */
3800 mutex_unlock(&cgroup_mutex);
3801 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3802 mutex_lock(&cgroup_mutex);
3806 spin_lock(&release_list_lock);
3808 spin_unlock(&release_list_lock);
3809 mutex_unlock(&cgroup_mutex);
3812 static int __init cgroup_disable(char *str)
3817 while ((token = strsep(&str, ",")) != NULL) {
3821 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3822 struct cgroup_subsys *ss = subsys[i];
3824 if (!strcmp(token, ss->name)) {
3826 printk(KERN_INFO "Disabling %s control group"
3827 " subsystem\n", ss->name);
3834 __setup("cgroup_disable=", cgroup_disable);
3837 * Functons for CSS ID.
3841 *To get ID other than 0, this should be called when !cgroup_is_removed().
3843 unsigned short css_id(struct cgroup_subsys_state *css)
3845 struct css_id *cssid = rcu_dereference(css->id);
3852 unsigned short css_depth(struct cgroup_subsys_state *css)
3854 struct css_id *cssid = rcu_dereference(css->id);
3857 return cssid->depth;
3861 bool css_is_ancestor(struct cgroup_subsys_state *child,
3862 const struct cgroup_subsys_state *root)
3864 struct css_id *child_id = rcu_dereference(child->id);
3865 struct css_id *root_id = rcu_dereference(root->id);
3867 if (!child_id || !root_id || (child_id->depth < root_id->depth))
3869 return child_id->stack[root_id->depth] == root_id->id;
3872 static void __free_css_id_cb(struct rcu_head *head)
3876 id = container_of(head, struct css_id, rcu_head);
3880 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
3882 struct css_id *id = css->id;
3883 /* When this is called before css_id initialization, id can be NULL */
3887 BUG_ON(!ss->use_id);
3889 rcu_assign_pointer(id->css, NULL);
3890 rcu_assign_pointer(css->id, NULL);
3891 spin_lock(&ss->id_lock);
3892 idr_remove(&ss->idr, id->id);
3893 spin_unlock(&ss->id_lock);
3894 call_rcu(&id->rcu_head, __free_css_id_cb);
3898 * This is called by init or create(). Then, calls to this function are
3899 * always serialized (By cgroup_mutex() at create()).
3902 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
3904 struct css_id *newid;
3905 int myid, error, size;
3907 BUG_ON(!ss->use_id);
3909 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
3910 newid = kzalloc(size, GFP_KERNEL);
3912 return ERR_PTR(-ENOMEM);
3914 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
3918 spin_lock(&ss->id_lock);
3919 /* Don't use 0. allocates an ID of 1-65535 */
3920 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
3921 spin_unlock(&ss->id_lock);
3923 /* Returns error when there are no free spaces for new ID.*/
3928 if (myid > CSS_ID_MAX)
3932 newid->depth = depth;
3936 spin_lock(&ss->id_lock);
3937 idr_remove(&ss->idr, myid);
3938 spin_unlock(&ss->id_lock);
3941 return ERR_PTR(error);
3945 static int __init cgroup_subsys_init_idr(struct cgroup_subsys *ss)
3947 struct css_id *newid;
3948 struct cgroup_subsys_state *rootcss;
3950 spin_lock_init(&ss->id_lock);
3953 rootcss = init_css_set.subsys[ss->subsys_id];
3954 newid = get_new_cssid(ss, 0);
3956 return PTR_ERR(newid);
3958 newid->stack[0] = newid->id;
3959 newid->css = rootcss;
3960 rootcss->id = newid;
3964 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
3965 struct cgroup *child)
3967 int subsys_id, i, depth = 0;
3968 struct cgroup_subsys_state *parent_css, *child_css;
3969 struct css_id *child_id, *parent_id = NULL;
3971 subsys_id = ss->subsys_id;
3972 parent_css = parent->subsys[subsys_id];
3973 child_css = child->subsys[subsys_id];
3974 depth = css_depth(parent_css) + 1;
3975 parent_id = parent_css->id;
3977 child_id = get_new_cssid(ss, depth);
3978 if (IS_ERR(child_id))
3979 return PTR_ERR(child_id);
3981 for (i = 0; i < depth; i++)
3982 child_id->stack[i] = parent_id->stack[i];
3983 child_id->stack[depth] = child_id->id;
3985 * child_id->css pointer will be set after this cgroup is available
3986 * see cgroup_populate_dir()
3988 rcu_assign_pointer(child_css->id, child_id);
3994 * css_lookup - lookup css by id
3995 * @ss: cgroup subsys to be looked into.
3998 * Returns pointer to cgroup_subsys_state if there is valid one with id.
3999 * NULL if not. Should be called under rcu_read_lock()
4001 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
4003 struct css_id *cssid = NULL;
4005 BUG_ON(!ss->use_id);
4006 cssid = idr_find(&ss->idr, id);
4008 if (unlikely(!cssid))
4011 return rcu_dereference(cssid->css);
4015 * css_get_next - lookup next cgroup under specified hierarchy.
4016 * @ss: pointer to subsystem
4017 * @id: current position of iteration.
4018 * @root: pointer to css. search tree under this.
4019 * @foundid: position of found object.
4021 * Search next css under the specified hierarchy of rootid. Calling under
4022 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
4024 struct cgroup_subsys_state *
4025 css_get_next(struct cgroup_subsys *ss, int id,
4026 struct cgroup_subsys_state *root, int *foundid)
4028 struct cgroup_subsys_state *ret = NULL;
4031 int rootid = css_id(root);
4032 int depth = css_depth(root);
4037 BUG_ON(!ss->use_id);
4038 /* fill start point for scan */
4042 * scan next entry from bitmap(tree), tmpid is updated after
4045 spin_lock(&ss->id_lock);
4046 tmp = idr_get_next(&ss->idr, &tmpid);
4047 spin_unlock(&ss->id_lock);
4051 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
4052 ret = rcu_dereference(tmp->css);
4058 /* continue to scan from next id */
4064 #ifdef CONFIG_CGROUP_DEBUG
4065 static struct cgroup_subsys_state *debug_create(struct cgroup_subsys *ss,
4066 struct cgroup *cont)
4068 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4071 return ERR_PTR(-ENOMEM);
4076 static void debug_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
4078 kfree(cont->subsys[debug_subsys_id]);
4081 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
4083 return atomic_read(&cont->count);
4086 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
4088 return cgroup_task_count(cont);
4091 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
4093 return (u64)(unsigned long)current->cgroups;
4096 static u64 current_css_set_refcount_read(struct cgroup *cont,
4102 count = atomic_read(¤t->cgroups->refcount);
4107 static int current_css_set_cg_links_read(struct cgroup *cont,
4109 struct seq_file *seq)
4111 struct cg_cgroup_link *link;
4114 read_lock(&css_set_lock);
4116 cg = rcu_dereference(current->cgroups);
4117 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
4118 struct cgroup *c = link->cgrp;
4122 name = c->dentry->d_name.name;
4125 seq_printf(seq, "Root %d group %s\n",
4126 c->root->hierarchy_id, name);
4129 read_unlock(&css_set_lock);
4133 #define MAX_TASKS_SHOWN_PER_CSS 25
4134 static int cgroup_css_links_read(struct cgroup *cont,
4136 struct seq_file *seq)
4138 struct cg_cgroup_link *link;
4140 read_lock(&css_set_lock);
4141 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
4142 struct css_set *cg = link->cg;
4143 struct task_struct *task;
4145 seq_printf(seq, "css_set %p\n", cg);
4146 list_for_each_entry(task, &cg->tasks, cg_list) {
4147 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
4148 seq_puts(seq, " ...\n");
4151 seq_printf(seq, " task %d\n",
4152 task_pid_vnr(task));
4156 read_unlock(&css_set_lock);
4160 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
4162 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
4165 static struct cftype debug_files[] = {
4167 .name = "cgroup_refcount",
4168 .read_u64 = cgroup_refcount_read,
4171 .name = "taskcount",
4172 .read_u64 = debug_taskcount_read,
4176 .name = "current_css_set",
4177 .read_u64 = current_css_set_read,
4181 .name = "current_css_set_refcount",
4182 .read_u64 = current_css_set_refcount_read,
4186 .name = "current_css_set_cg_links",
4187 .read_seq_string = current_css_set_cg_links_read,
4191 .name = "cgroup_css_links",
4192 .read_seq_string = cgroup_css_links_read,
4196 .name = "releasable",
4197 .read_u64 = releasable_read,
4201 static int debug_populate(struct cgroup_subsys *ss, struct cgroup *cont)
4203 return cgroup_add_files(cont, ss, debug_files,
4204 ARRAY_SIZE(debug_files));
4207 struct cgroup_subsys debug_subsys = {
4209 .create = debug_create,
4210 .destroy = debug_destroy,
4211 .populate = debug_populate,
4212 .subsys_id = debug_subsys_id,
4214 #endif /* CONFIG_CGROUP_DEBUG */