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/ctype.h>
27 #include <linux/errno.h>
29 #include <linux/kernel.h>
30 #include <linux/list.h>
32 #include <linux/mutex.h>
33 #include <linux/mount.h>
34 #include <linux/pagemap.h>
35 #include <linux/proc_fs.h>
36 #include <linux/rcupdate.h>
37 #include <linux/sched.h>
38 #include <linux/backing-dev.h>
39 #include <linux/seq_file.h>
40 #include <linux/slab.h>
41 #include <linux/magic.h>
42 #include <linux/spinlock.h>
43 #include <linux/string.h>
44 #include <linux/sort.h>
45 #include <linux/kmod.h>
46 #include <linux/delayacct.h>
47 #include <linux/cgroupstats.h>
48 #include <linux/hash.h>
49 #include <linux/namei.h>
50 #include <linux/smp_lock.h>
51 #include <linux/pid_namespace.h>
53 #include <asm/atomic.h>
55 static DEFINE_MUTEX(cgroup_mutex);
57 /* Generate an array of cgroup subsystem pointers */
58 #define SUBSYS(_x) &_x ## _subsys,
60 static struct cgroup_subsys *subsys[] = {
61 #include <linux/cgroup_subsys.h>
64 #define MAX_CGROUP_ROOT_NAMELEN 64
67 * A cgroupfs_root represents the root of a cgroup hierarchy,
68 * and may be associated with a superblock to form an active
71 struct cgroupfs_root {
72 struct super_block *sb;
75 * The bitmask of subsystems intended to be attached to this
78 unsigned long subsys_bits;
80 /* The bitmask of subsystems currently attached to this hierarchy */
81 unsigned long actual_subsys_bits;
83 /* A list running through the attached subsystems */
84 struct list_head subsys_list;
86 /* The root cgroup for this hierarchy */
87 struct cgroup top_cgroup;
89 /* Tracks how many cgroups are currently defined in hierarchy.*/
90 int number_of_cgroups;
92 /* A list running through the active hierarchies */
93 struct list_head root_list;
95 /* Hierarchy-specific flags */
98 /* The path to use for release notifications. */
99 char release_agent_path[PATH_MAX];
101 /* The name for this hierarchy - may be empty */
102 char name[MAX_CGROUP_ROOT_NAMELEN];
106 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
107 * subsystems that are otherwise unattached - it never has more than a
108 * single cgroup, and all tasks are part of that cgroup.
110 static struct cgroupfs_root rootnode;
113 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
114 * cgroup_subsys->use_id != 0.
116 #define CSS_ID_MAX (65535)
119 * The css to which this ID points. This pointer is set to valid value
120 * after cgroup is populated. If cgroup is removed, this will be NULL.
121 * This pointer is expected to be RCU-safe because destroy()
122 * is called after synchronize_rcu(). But for safe use, css_is_removed()
123 * css_tryget() should be used for avoiding race.
125 struct cgroup_subsys_state *css;
131 * Depth in hierarchy which this ID belongs to.
133 unsigned short depth;
135 * ID is freed by RCU. (and lookup routine is RCU safe.)
137 struct rcu_head rcu_head;
139 * Hierarchy of CSS ID belongs to.
141 unsigned short stack[0]; /* Array of Length (depth+1) */
145 /* The list of hierarchy roots */
147 static LIST_HEAD(roots);
148 static int root_count;
150 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
151 #define dummytop (&rootnode.top_cgroup)
153 /* This flag indicates whether tasks in the fork and exit paths should
154 * check for fork/exit handlers to call. This avoids us having to do
155 * extra work in the fork/exit path if none of the subsystems need to
158 static int need_forkexit_callback __read_mostly;
160 /* convenient tests for these bits */
161 inline int cgroup_is_removed(const struct cgroup *cgrp)
163 return test_bit(CGRP_REMOVED, &cgrp->flags);
166 /* bits in struct cgroupfs_root flags field */
168 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
171 static int cgroup_is_releasable(const struct cgroup *cgrp)
174 (1 << CGRP_RELEASABLE) |
175 (1 << CGRP_NOTIFY_ON_RELEASE);
176 return (cgrp->flags & bits) == bits;
179 static int notify_on_release(const struct cgroup *cgrp)
181 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
185 * for_each_subsys() allows you to iterate on each subsystem attached to
186 * an active hierarchy
188 #define for_each_subsys(_root, _ss) \
189 list_for_each_entry(_ss, &_root->subsys_list, sibling)
191 /* for_each_active_root() allows you to iterate across the active hierarchies */
192 #define for_each_active_root(_root) \
193 list_for_each_entry(_root, &roots, root_list)
195 /* the list of cgroups eligible for automatic release. Protected by
196 * release_list_lock */
197 static LIST_HEAD(release_list);
198 static DEFINE_SPINLOCK(release_list_lock);
199 static void cgroup_release_agent(struct work_struct *work);
200 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
201 static void check_for_release(struct cgroup *cgrp);
203 /* Link structure for associating css_set objects with cgroups */
204 struct cg_cgroup_link {
206 * List running through cg_cgroup_links associated with a
207 * cgroup, anchored on cgroup->css_sets
209 struct list_head cgrp_link_list;
212 * List running through cg_cgroup_links pointing at a
213 * single css_set object, anchored on css_set->cg_links
215 struct list_head cg_link_list;
219 /* The default css_set - used by init and its children prior to any
220 * hierarchies being mounted. It contains a pointer to the root state
221 * for each subsystem. Also used to anchor the list of css_sets. Not
222 * reference-counted, to improve performance when child cgroups
223 * haven't been created.
226 static struct css_set init_css_set;
227 static struct cg_cgroup_link init_css_set_link;
229 static int cgroup_subsys_init_idr(struct cgroup_subsys *ss);
231 /* css_set_lock protects the list of css_set objects, and the
232 * chain of tasks off each css_set. Nests outside task->alloc_lock
233 * due to cgroup_iter_start() */
234 static DEFINE_RWLOCK(css_set_lock);
235 static int css_set_count;
238 * hash table for cgroup groups. This improves the performance to find
239 * an existing css_set. This hash doesn't (currently) take into
240 * account cgroups in empty hierarchies.
242 #define CSS_SET_HASH_BITS 7
243 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
244 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
246 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
250 unsigned long tmp = 0UL;
252 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
253 tmp += (unsigned long)css[i];
254 tmp = (tmp >> 16) ^ tmp;
256 index = hash_long(tmp, CSS_SET_HASH_BITS);
258 return &css_set_table[index];
261 /* We don't maintain the lists running through each css_set to its
262 * task until after the first call to cgroup_iter_start(). This
263 * reduces the fork()/exit() overhead for people who have cgroups
264 * compiled into their kernel but not actually in use */
265 static int use_task_css_set_links __read_mostly;
267 /* When we create or destroy a css_set, the operation simply
268 * takes/releases a reference count on all the cgroups referenced
269 * by subsystems in this css_set. This can end up multiple-counting
270 * some cgroups, but that's OK - the ref-count is just a
271 * busy/not-busy indicator; ensuring that we only count each cgroup
272 * once would require taking a global lock to ensure that no
273 * subsystems moved between hierarchies while we were doing so.
275 * Possible TODO: decide at boot time based on the number of
276 * registered subsystems and the number of CPUs or NUMA nodes whether
277 * it's better for performance to ref-count every subsystem, or to
278 * take a global lock and only add one ref count to each hierarchy.
282 * unlink a css_set from the list and free it
284 static void unlink_css_set(struct css_set *cg)
286 struct cg_cgroup_link *link;
287 struct cg_cgroup_link *saved_link;
289 hlist_del(&cg->hlist);
292 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
294 list_del(&link->cg_link_list);
295 list_del(&link->cgrp_link_list);
300 static void __put_css_set(struct css_set *cg, int taskexit)
304 * Ensure that the refcount doesn't hit zero while any readers
305 * can see it. Similar to atomic_dec_and_lock(), but for an
308 if (atomic_add_unless(&cg->refcount, -1, 1))
310 write_lock(&css_set_lock);
311 if (!atomic_dec_and_test(&cg->refcount)) {
312 write_unlock(&css_set_lock);
316 write_unlock(&css_set_lock);
319 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
320 struct cgroup *cgrp = rcu_dereference(cg->subsys[i]->cgroup);
321 if (atomic_dec_and_test(&cgrp->count) &&
322 notify_on_release(cgrp)) {
324 set_bit(CGRP_RELEASABLE, &cgrp->flags);
325 check_for_release(cgrp);
333 * refcounted get/put for css_set objects
335 static inline void get_css_set(struct css_set *cg)
337 atomic_inc(&cg->refcount);
340 static inline void put_css_set(struct css_set *cg)
342 __put_css_set(cg, 0);
345 static inline void put_css_set_taskexit(struct css_set *cg)
347 __put_css_set(cg, 1);
351 * compare_css_sets - helper function for find_existing_css_set().
352 * @cg: candidate css_set being tested
353 * @old_cg: existing css_set for a task
354 * @new_cgrp: cgroup that's being entered by the task
355 * @template: desired set of css pointers in css_set (pre-calculated)
357 * Returns true if "cg" matches "old_cg" except for the hierarchy
358 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
360 static bool compare_css_sets(struct css_set *cg,
361 struct css_set *old_cg,
362 struct cgroup *new_cgrp,
363 struct cgroup_subsys_state *template[])
365 struct list_head *l1, *l2;
367 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
368 /* Not all subsystems matched */
373 * Compare cgroup pointers in order to distinguish between
374 * different cgroups in heirarchies with no subsystems. We
375 * could get by with just this check alone (and skip the
376 * memcmp above) but on most setups the memcmp check will
377 * avoid the need for this more expensive check on almost all
382 l2 = &old_cg->cg_links;
384 struct cg_cgroup_link *cgl1, *cgl2;
385 struct cgroup *cg1, *cg2;
389 /* See if we reached the end - both lists are equal length. */
390 if (l1 == &cg->cg_links) {
391 BUG_ON(l2 != &old_cg->cg_links);
394 BUG_ON(l2 == &old_cg->cg_links);
396 /* Locate the cgroups associated with these links. */
397 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
398 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
401 /* Hierarchies should be linked in the same order. */
402 BUG_ON(cg1->root != cg2->root);
405 * If this hierarchy is the hierarchy of the cgroup
406 * that's changing, then we need to check that this
407 * css_set points to the new cgroup; if it's any other
408 * hierarchy, then this css_set should point to the
409 * same cgroup as the old css_set.
411 if (cg1->root == new_cgrp->root) {
423 * find_existing_css_set() is a helper for
424 * find_css_set(), and checks to see whether an existing
425 * css_set is suitable.
427 * oldcg: the cgroup group that we're using before the cgroup
430 * cgrp: the cgroup that we're moving into
432 * template: location in which to build the desired set of subsystem
433 * state objects for the new cgroup group
435 static struct css_set *find_existing_css_set(
436 struct css_set *oldcg,
438 struct cgroup_subsys_state *template[])
441 struct cgroupfs_root *root = cgrp->root;
442 struct hlist_head *hhead;
443 struct hlist_node *node;
446 /* Built the set of subsystem state objects that we want to
447 * see in the new css_set */
448 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
449 if (root->subsys_bits & (1UL << i)) {
450 /* Subsystem is in this hierarchy. So we want
451 * the subsystem state from the new
453 template[i] = cgrp->subsys[i];
455 /* Subsystem is not in this hierarchy, so we
456 * don't want to change the subsystem state */
457 template[i] = oldcg->subsys[i];
461 hhead = css_set_hash(template);
462 hlist_for_each_entry(cg, node, hhead, hlist) {
463 if (!compare_css_sets(cg, oldcg, cgrp, template))
466 /* This css_set matches what we need */
470 /* No existing cgroup group matched */
474 static void free_cg_links(struct list_head *tmp)
476 struct cg_cgroup_link *link;
477 struct cg_cgroup_link *saved_link;
479 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
480 list_del(&link->cgrp_link_list);
486 * allocate_cg_links() allocates "count" cg_cgroup_link structures
487 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
488 * success or a negative error
490 static int allocate_cg_links(int count, struct list_head *tmp)
492 struct cg_cgroup_link *link;
495 for (i = 0; i < count; i++) {
496 link = kmalloc(sizeof(*link), GFP_KERNEL);
501 list_add(&link->cgrp_link_list, tmp);
507 * link_css_set - a helper function to link a css_set to a cgroup
508 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
509 * @cg: the css_set to be linked
510 * @cgrp: the destination cgroup
512 static void link_css_set(struct list_head *tmp_cg_links,
513 struct css_set *cg, struct cgroup *cgrp)
515 struct cg_cgroup_link *link;
517 BUG_ON(list_empty(tmp_cg_links));
518 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
522 list_move(&link->cgrp_link_list, &cgrp->css_sets);
524 * Always add links to the tail of the list so that the list
525 * is sorted by order of hierarchy creation
527 list_add_tail(&link->cg_link_list, &cg->cg_links);
531 * find_css_set() takes an existing cgroup group and a
532 * cgroup object, and returns a css_set object that's
533 * equivalent to the old group, but with the given cgroup
534 * substituted into the appropriate hierarchy. Must be called with
537 static struct css_set *find_css_set(
538 struct css_set *oldcg, struct cgroup *cgrp)
541 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
544 struct list_head tmp_cg_links;
546 struct hlist_head *hhead;
547 struct cg_cgroup_link *link;
549 /* First see if we already have a cgroup group that matches
551 read_lock(&css_set_lock);
552 res = find_existing_css_set(oldcg, cgrp, template);
555 read_unlock(&css_set_lock);
560 res = kmalloc(sizeof(*res), GFP_KERNEL);
564 /* Allocate all the cg_cgroup_link objects that we'll need */
565 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
570 atomic_set(&res->refcount, 1);
571 INIT_LIST_HEAD(&res->cg_links);
572 INIT_LIST_HEAD(&res->tasks);
573 INIT_HLIST_NODE(&res->hlist);
575 /* Copy the set of subsystem state objects generated in
576 * find_existing_css_set() */
577 memcpy(res->subsys, template, sizeof(res->subsys));
579 write_lock(&css_set_lock);
580 /* Add reference counts and links from the new css_set. */
581 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
582 struct cgroup *cgrp = res->subsys[i]->cgroup;
583 atomic_inc(&cgrp->count);
585 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
586 struct cgroup *c = link->cgrp;
587 if (c->root == cgrp->root)
589 link_css_set(&tmp_cg_links, res, c);
592 BUG_ON(!list_empty(&tmp_cg_links));
596 /* Add this cgroup group to the hash table */
597 hhead = css_set_hash(res->subsys);
598 hlist_add_head(&res->hlist, hhead);
600 write_unlock(&css_set_lock);
606 * Return the cgroup for "task" from the given hierarchy. Must be
607 * called with cgroup_mutex held.
609 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
610 struct cgroupfs_root *root)
613 struct cgroup *res = NULL;
615 BUG_ON(!mutex_is_locked(&cgroup_mutex));
616 read_lock(&css_set_lock);
618 * No need to lock the task - since we hold cgroup_mutex the
619 * task can't change groups, so the only thing that can happen
620 * is that it exits and its css is set back to init_css_set.
623 if (css == &init_css_set) {
624 res = &root->top_cgroup;
626 struct cg_cgroup_link *link;
627 list_for_each_entry(link, &css->cg_links, cg_link_list) {
628 struct cgroup *c = link->cgrp;
629 if (c->root == root) {
635 read_unlock(&css_set_lock);
641 * There is one global cgroup mutex. We also require taking
642 * task_lock() when dereferencing a task's cgroup subsys pointers.
643 * See "The task_lock() exception", at the end of this comment.
645 * A task must hold cgroup_mutex to modify cgroups.
647 * Any task can increment and decrement the count field without lock.
648 * So in general, code holding cgroup_mutex can't rely on the count
649 * field not changing. However, if the count goes to zero, then only
650 * cgroup_attach_task() can increment it again. Because a count of zero
651 * means that no tasks are currently attached, therefore there is no
652 * way a task attached to that cgroup can fork (the other way to
653 * increment the count). So code holding cgroup_mutex can safely
654 * assume that if the count is zero, it will stay zero. Similarly, if
655 * a task holds cgroup_mutex on a cgroup with zero count, it
656 * knows that the cgroup won't be removed, as cgroup_rmdir()
659 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
660 * (usually) take cgroup_mutex. These are the two most performance
661 * critical pieces of code here. The exception occurs on cgroup_exit(),
662 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
663 * is taken, and if the cgroup count is zero, a usermode call made
664 * to the release agent with the name of the cgroup (path relative to
665 * the root of cgroup file system) as the argument.
667 * A cgroup can only be deleted if both its 'count' of using tasks
668 * is zero, and its list of 'children' cgroups is empty. Since all
669 * tasks in the system use _some_ cgroup, and since there is always at
670 * least one task in the system (init, pid == 1), therefore, top_cgroup
671 * always has either children cgroups and/or using tasks. So we don't
672 * need a special hack to ensure that top_cgroup cannot be deleted.
674 * The task_lock() exception
676 * The need for this exception arises from the action of
677 * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
678 * another. It does so using cgroup_mutex, however there are
679 * several performance critical places that need to reference
680 * task->cgroup without the expense of grabbing a system global
681 * mutex. Therefore except as noted below, when dereferencing or, as
682 * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
683 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
684 * the task_struct routinely used for such matters.
686 * P.S. One more locking exception. RCU is used to guard the
687 * update of a tasks cgroup pointer by cgroup_attach_task()
691 * cgroup_lock - lock out any changes to cgroup structures
694 void cgroup_lock(void)
696 mutex_lock(&cgroup_mutex);
700 * cgroup_unlock - release lock on cgroup changes
702 * Undo the lock taken in a previous cgroup_lock() call.
704 void cgroup_unlock(void)
706 mutex_unlock(&cgroup_mutex);
710 * A couple of forward declarations required, due to cyclic reference loop:
711 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
712 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
716 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
717 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
718 static int cgroup_populate_dir(struct cgroup *cgrp);
719 static const struct inode_operations cgroup_dir_inode_operations;
720 static struct file_operations proc_cgroupstats_operations;
722 static struct backing_dev_info cgroup_backing_dev_info = {
724 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
727 static int alloc_css_id(struct cgroup_subsys *ss,
728 struct cgroup *parent, struct cgroup *child);
730 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
732 struct inode *inode = new_inode(sb);
735 inode->i_mode = mode;
736 inode->i_uid = current_fsuid();
737 inode->i_gid = current_fsgid();
738 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
739 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
745 * Call subsys's pre_destroy handler.
746 * This is called before css refcnt check.
748 static int cgroup_call_pre_destroy(struct cgroup *cgrp)
750 struct cgroup_subsys *ss;
753 for_each_subsys(cgrp->root, ss)
754 if (ss->pre_destroy) {
755 ret = ss->pre_destroy(ss, cgrp);
762 static void free_cgroup_rcu(struct rcu_head *obj)
764 struct cgroup *cgrp = container_of(obj, struct cgroup, rcu_head);
769 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
771 /* is dentry a directory ? if so, kfree() associated cgroup */
772 if (S_ISDIR(inode->i_mode)) {
773 struct cgroup *cgrp = dentry->d_fsdata;
774 struct cgroup_subsys *ss;
775 BUG_ON(!(cgroup_is_removed(cgrp)));
776 /* It's possible for external users to be holding css
777 * reference counts on a cgroup; css_put() needs to
778 * be able to access the cgroup after decrementing
779 * the reference count in order to know if it needs to
780 * queue the cgroup to be handled by the release
784 mutex_lock(&cgroup_mutex);
786 * Release the subsystem state objects.
788 for_each_subsys(cgrp->root, ss)
789 ss->destroy(ss, cgrp);
791 cgrp->root->number_of_cgroups--;
792 mutex_unlock(&cgroup_mutex);
795 * Drop the active superblock reference that we took when we
798 deactivate_super(cgrp->root->sb);
800 call_rcu(&cgrp->rcu_head, free_cgroup_rcu);
805 static void remove_dir(struct dentry *d)
807 struct dentry *parent = dget(d->d_parent);
810 simple_rmdir(parent->d_inode, d);
814 static void cgroup_clear_directory(struct dentry *dentry)
816 struct list_head *node;
818 BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
819 spin_lock(&dcache_lock);
820 node = dentry->d_subdirs.next;
821 while (node != &dentry->d_subdirs) {
822 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
825 /* This should never be called on a cgroup
826 * directory with child cgroups */
827 BUG_ON(d->d_inode->i_mode & S_IFDIR);
829 spin_unlock(&dcache_lock);
831 simple_unlink(dentry->d_inode, d);
833 spin_lock(&dcache_lock);
835 node = dentry->d_subdirs.next;
837 spin_unlock(&dcache_lock);
841 * NOTE : the dentry must have been dget()'ed
843 static void cgroup_d_remove_dir(struct dentry *dentry)
845 cgroup_clear_directory(dentry);
847 spin_lock(&dcache_lock);
848 list_del_init(&dentry->d_u.d_child);
849 spin_unlock(&dcache_lock);
854 * A queue for waiters to do rmdir() cgroup. A tasks will sleep when
855 * cgroup->count == 0 && list_empty(&cgroup->children) && subsys has some
856 * reference to css->refcnt. In general, this refcnt is expected to goes down
859 * CGRP_WAIT_ON_RMDIR flag is set under cgroup's inode->i_mutex;
861 DECLARE_WAIT_QUEUE_HEAD(cgroup_rmdir_waitq);
863 static void cgroup_wakeup_rmdir_waiter(struct cgroup *cgrp)
865 if (unlikely(test_and_clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags)))
866 wake_up_all(&cgroup_rmdir_waitq);
869 void cgroup_exclude_rmdir(struct cgroup_subsys_state *css)
874 void cgroup_release_and_wakeup_rmdir(struct cgroup_subsys_state *css)
876 cgroup_wakeup_rmdir_waiter(css->cgroup);
881 static int rebind_subsystems(struct cgroupfs_root *root,
882 unsigned long final_bits)
884 unsigned long added_bits, removed_bits;
885 struct cgroup *cgrp = &root->top_cgroup;
888 removed_bits = root->actual_subsys_bits & ~final_bits;
889 added_bits = final_bits & ~root->actual_subsys_bits;
890 /* Check that any added subsystems are currently free */
891 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
892 unsigned long bit = 1UL << i;
893 struct cgroup_subsys *ss = subsys[i];
894 if (!(bit & added_bits))
896 if (ss->root != &rootnode) {
897 /* Subsystem isn't free */
902 /* Currently we don't handle adding/removing subsystems when
903 * any child cgroups exist. This is theoretically supportable
904 * but involves complex error handling, so it's being left until
906 if (root->number_of_cgroups > 1)
909 /* Process each subsystem */
910 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
911 struct cgroup_subsys *ss = subsys[i];
912 unsigned long bit = 1UL << i;
913 if (bit & added_bits) {
914 /* We're binding this subsystem to this hierarchy */
915 BUG_ON(cgrp->subsys[i]);
916 BUG_ON(!dummytop->subsys[i]);
917 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
918 mutex_lock(&ss->hierarchy_mutex);
919 cgrp->subsys[i] = dummytop->subsys[i];
920 cgrp->subsys[i]->cgroup = cgrp;
921 list_move(&ss->sibling, &root->subsys_list);
925 mutex_unlock(&ss->hierarchy_mutex);
926 } else if (bit & removed_bits) {
927 /* We're removing this subsystem */
928 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
929 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
930 mutex_lock(&ss->hierarchy_mutex);
932 ss->bind(ss, dummytop);
933 dummytop->subsys[i]->cgroup = dummytop;
934 cgrp->subsys[i] = NULL;
935 subsys[i]->root = &rootnode;
936 list_move(&ss->sibling, &rootnode.subsys_list);
937 mutex_unlock(&ss->hierarchy_mutex);
938 } else if (bit & final_bits) {
939 /* Subsystem state should already exist */
940 BUG_ON(!cgrp->subsys[i]);
942 /* Subsystem state shouldn't exist */
943 BUG_ON(cgrp->subsys[i]);
946 root->subsys_bits = root->actual_subsys_bits = final_bits;
952 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
954 struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
955 struct cgroup_subsys *ss;
957 mutex_lock(&cgroup_mutex);
958 for_each_subsys(root, ss)
959 seq_printf(seq, ",%s", ss->name);
960 if (test_bit(ROOT_NOPREFIX, &root->flags))
961 seq_puts(seq, ",noprefix");
962 if (strlen(root->release_agent_path))
963 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
964 if (strlen(root->name))
965 seq_printf(seq, ",name=%s", root->name);
966 mutex_unlock(&cgroup_mutex);
970 struct cgroup_sb_opts {
971 unsigned long subsys_bits;
976 struct cgroupfs_root *new_root;
979 /* Convert a hierarchy specifier into a bitmask of subsystems and
981 static int parse_cgroupfs_options(char *data,
982 struct cgroup_sb_opts *opts)
984 char *token, *o = data ?: "all";
985 unsigned long mask = (unsigned long)-1;
987 #ifdef CONFIG_CPUSETS
988 mask = ~(1UL << cpuset_subsys_id);
991 memset(opts, 0, sizeof(*opts));
993 while ((token = strsep(&o, ",")) != NULL) {
996 if (!strcmp(token, "all")) {
997 /* Add all non-disabled subsystems */
999 opts->subsys_bits = 0;
1000 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1001 struct cgroup_subsys *ss = subsys[i];
1003 opts->subsys_bits |= 1ul << i;
1005 } else if (!strcmp(token, "noprefix")) {
1006 set_bit(ROOT_NOPREFIX, &opts->flags);
1007 } else if (!strncmp(token, "release_agent=", 14)) {
1008 /* Specifying two release agents is forbidden */
1009 if (opts->release_agent)
1011 opts->release_agent =
1012 kstrndup(token + 14, PATH_MAX, GFP_KERNEL);
1013 if (!opts->release_agent)
1015 } else if (!strncmp(token, "name=", 5)) {
1017 const char *name = token + 5;
1018 /* Can't specify an empty name */
1021 /* Must match [\w.-]+ */
1022 for (i = 0; i < strlen(name); i++) {
1026 if ((c == '.') || (c == '-') || (c == '_'))
1030 /* Specifying two names is forbidden */
1033 opts->name = kstrndup(name,
1034 MAX_CGROUP_ROOT_NAMELEN,
1039 struct cgroup_subsys *ss;
1041 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1043 if (!strcmp(token, ss->name)) {
1045 set_bit(i, &opts->subsys_bits);
1049 if (i == CGROUP_SUBSYS_COUNT)
1055 * Option noprefix was introduced just for backward compatibility
1056 * with the old cpuset, so we allow noprefix only if mounting just
1057 * the cpuset subsystem.
1059 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1060 (opts->subsys_bits & mask))
1063 /* We can't have an empty hierarchy */
1064 if (!opts->subsys_bits && !opts->name)
1070 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1073 struct cgroupfs_root *root = sb->s_fs_info;
1074 struct cgroup *cgrp = &root->top_cgroup;
1075 struct cgroup_sb_opts opts;
1078 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1079 mutex_lock(&cgroup_mutex);
1081 /* See what subsystems are wanted */
1082 ret = parse_cgroupfs_options(data, &opts);
1086 /* Don't allow flags to change at remount */
1087 if (opts.flags != root->flags) {
1092 /* Don't allow name to change at remount */
1093 if (opts.name && strcmp(opts.name, root->name)) {
1098 ret = rebind_subsystems(root, opts.subsys_bits);
1102 /* (re)populate subsystem files */
1103 cgroup_populate_dir(cgrp);
1105 if (opts.release_agent)
1106 strcpy(root->release_agent_path, opts.release_agent);
1108 kfree(opts.release_agent);
1110 mutex_unlock(&cgroup_mutex);
1111 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1116 static const struct super_operations cgroup_ops = {
1117 .statfs = simple_statfs,
1118 .drop_inode = generic_delete_inode,
1119 .show_options = cgroup_show_options,
1120 .remount_fs = cgroup_remount,
1123 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1125 INIT_LIST_HEAD(&cgrp->sibling);
1126 INIT_LIST_HEAD(&cgrp->children);
1127 INIT_LIST_HEAD(&cgrp->css_sets);
1128 INIT_LIST_HEAD(&cgrp->release_list);
1129 INIT_LIST_HEAD(&cgrp->pids_list);
1130 init_rwsem(&cgrp->pids_mutex);
1133 static void init_cgroup_root(struct cgroupfs_root *root)
1135 struct cgroup *cgrp = &root->top_cgroup;
1136 INIT_LIST_HEAD(&root->subsys_list);
1137 INIT_LIST_HEAD(&root->root_list);
1138 root->number_of_cgroups = 1;
1140 cgrp->top_cgroup = cgrp;
1141 init_cgroup_housekeeping(cgrp);
1144 static int cgroup_test_super(struct super_block *sb, void *data)
1146 struct cgroup_sb_opts *opts = data;
1147 struct cgroupfs_root *root = sb->s_fs_info;
1149 /* If we asked for a name then it must match */
1150 if (opts->name && strcmp(opts->name, root->name))
1153 /* If we asked for subsystems then they must match */
1154 if (opts->subsys_bits && (opts->subsys_bits != root->subsys_bits))
1160 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1162 struct cgroupfs_root *root;
1164 /* Empty hierarchies aren't supported */
1165 if (!opts->subsys_bits)
1168 root = kzalloc(sizeof(*root), GFP_KERNEL);
1170 return ERR_PTR(-ENOMEM);
1172 init_cgroup_root(root);
1173 root->subsys_bits = opts->subsys_bits;
1174 root->flags = opts->flags;
1175 if (opts->release_agent)
1176 strcpy(root->release_agent_path, opts->release_agent);
1178 strcpy(root->name, opts->name);
1182 static int cgroup_set_super(struct super_block *sb, void *data)
1185 struct cgroup_sb_opts *opts = data;
1187 /* If we don't have a new root, we can't set up a new sb */
1188 if (!opts->new_root)
1191 BUG_ON(!opts->subsys_bits);
1193 ret = set_anon_super(sb, NULL);
1197 sb->s_fs_info = opts->new_root;
1198 opts->new_root->sb = sb;
1200 sb->s_blocksize = PAGE_CACHE_SIZE;
1201 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1202 sb->s_magic = CGROUP_SUPER_MAGIC;
1203 sb->s_op = &cgroup_ops;
1208 static int cgroup_get_rootdir(struct super_block *sb)
1210 struct inode *inode =
1211 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1212 struct dentry *dentry;
1217 inode->i_fop = &simple_dir_operations;
1218 inode->i_op = &cgroup_dir_inode_operations;
1219 /* directories start off with i_nlink == 2 (for "." entry) */
1221 dentry = d_alloc_root(inode);
1226 sb->s_root = dentry;
1230 static int cgroup_get_sb(struct file_system_type *fs_type,
1231 int flags, const char *unused_dev_name,
1232 void *data, struct vfsmount *mnt)
1234 struct cgroup_sb_opts opts;
1235 struct cgroupfs_root *root;
1237 struct super_block *sb;
1238 struct cgroupfs_root *new_root;
1240 /* First find the desired set of subsystems */
1241 ret = parse_cgroupfs_options(data, &opts);
1246 * Allocate a new cgroup root. We may not need it if we're
1247 * reusing an existing hierarchy.
1249 new_root = cgroup_root_from_opts(&opts);
1250 if (IS_ERR(new_root)) {
1251 ret = PTR_ERR(new_root);
1254 opts.new_root = new_root;
1256 /* Locate an existing or new sb for this hierarchy */
1257 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, &opts);
1260 kfree(opts.new_root);
1264 root = sb->s_fs_info;
1266 if (root == opts.new_root) {
1267 /* We used the new root structure, so this is a new hierarchy */
1268 struct list_head tmp_cg_links;
1269 struct cgroup *root_cgrp = &root->top_cgroup;
1270 struct inode *inode;
1271 struct cgroupfs_root *existing_root;
1274 BUG_ON(sb->s_root != NULL);
1276 ret = cgroup_get_rootdir(sb);
1278 goto drop_new_super;
1279 inode = sb->s_root->d_inode;
1281 mutex_lock(&inode->i_mutex);
1282 mutex_lock(&cgroup_mutex);
1284 if (strlen(root->name)) {
1285 /* Check for name clashes with existing mounts */
1286 for_each_active_root(existing_root) {
1287 if (!strcmp(existing_root->name, root->name)) {
1289 mutex_unlock(&cgroup_mutex);
1290 mutex_unlock(&inode->i_mutex);
1291 goto drop_new_super;
1297 * We're accessing css_set_count without locking
1298 * css_set_lock here, but that's OK - it can only be
1299 * increased by someone holding cgroup_lock, and
1300 * that's us. The worst that can happen is that we
1301 * have some link structures left over
1303 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1305 mutex_unlock(&cgroup_mutex);
1306 mutex_unlock(&inode->i_mutex);
1307 goto drop_new_super;
1310 ret = rebind_subsystems(root, root->subsys_bits);
1311 if (ret == -EBUSY) {
1312 mutex_unlock(&cgroup_mutex);
1313 mutex_unlock(&inode->i_mutex);
1314 free_cg_links(&tmp_cg_links);
1315 goto drop_new_super;
1318 /* EBUSY should be the only error here */
1321 list_add(&root->root_list, &roots);
1324 sb->s_root->d_fsdata = root_cgrp;
1325 root->top_cgroup.dentry = sb->s_root;
1327 /* Link the top cgroup in this hierarchy into all
1328 * the css_set objects */
1329 write_lock(&css_set_lock);
1330 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1331 struct hlist_head *hhead = &css_set_table[i];
1332 struct hlist_node *node;
1335 hlist_for_each_entry(cg, node, hhead, hlist)
1336 link_css_set(&tmp_cg_links, cg, root_cgrp);
1338 write_unlock(&css_set_lock);
1340 free_cg_links(&tmp_cg_links);
1342 BUG_ON(!list_empty(&root_cgrp->sibling));
1343 BUG_ON(!list_empty(&root_cgrp->children));
1344 BUG_ON(root->number_of_cgroups != 1);
1346 cgroup_populate_dir(root_cgrp);
1347 mutex_unlock(&cgroup_mutex);
1348 mutex_unlock(&inode->i_mutex);
1351 * We re-used an existing hierarchy - the new root (if
1352 * any) is not needed
1354 kfree(opts.new_root);
1357 simple_set_mnt(mnt, sb);
1358 kfree(opts.release_agent);
1363 deactivate_locked_super(sb);
1365 kfree(opts.release_agent);
1371 static void cgroup_kill_sb(struct super_block *sb) {
1372 struct cgroupfs_root *root = sb->s_fs_info;
1373 struct cgroup *cgrp = &root->top_cgroup;
1375 struct cg_cgroup_link *link;
1376 struct cg_cgroup_link *saved_link;
1380 BUG_ON(root->number_of_cgroups != 1);
1381 BUG_ON(!list_empty(&cgrp->children));
1382 BUG_ON(!list_empty(&cgrp->sibling));
1384 mutex_lock(&cgroup_mutex);
1386 /* Rebind all subsystems back to the default hierarchy */
1387 ret = rebind_subsystems(root, 0);
1388 /* Shouldn't be able to fail ... */
1392 * Release all the links from css_sets to this hierarchy's
1395 write_lock(&css_set_lock);
1397 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1399 list_del(&link->cg_link_list);
1400 list_del(&link->cgrp_link_list);
1403 write_unlock(&css_set_lock);
1405 if (!list_empty(&root->root_list)) {
1406 list_del(&root->root_list);
1410 mutex_unlock(&cgroup_mutex);
1412 kill_litter_super(sb);
1416 static struct file_system_type cgroup_fs_type = {
1418 .get_sb = cgroup_get_sb,
1419 .kill_sb = cgroup_kill_sb,
1422 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1424 return dentry->d_fsdata;
1427 static inline struct cftype *__d_cft(struct dentry *dentry)
1429 return dentry->d_fsdata;
1433 * cgroup_path - generate the path of a cgroup
1434 * @cgrp: the cgroup in question
1435 * @buf: the buffer to write the path into
1436 * @buflen: the length of the buffer
1438 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1439 * reference. Writes path of cgroup into buf. Returns 0 on success,
1442 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1445 struct dentry *dentry = rcu_dereference(cgrp->dentry);
1447 if (!dentry || cgrp == dummytop) {
1449 * Inactive subsystems have no dentry for their root
1456 start = buf + buflen;
1460 int len = dentry->d_name.len;
1461 if ((start -= len) < buf)
1462 return -ENAMETOOLONG;
1463 memcpy(start, cgrp->dentry->d_name.name, len);
1464 cgrp = cgrp->parent;
1467 dentry = rcu_dereference(cgrp->dentry);
1471 return -ENAMETOOLONG;
1474 memmove(buf, start, buf + buflen - start);
1479 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1480 * @cgrp: the cgroup the task is attaching to
1481 * @tsk: the task to be attached
1483 * Call holding cgroup_mutex. May take task_lock of
1484 * the task 'tsk' during call.
1486 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1489 struct cgroup_subsys *ss;
1490 struct cgroup *oldcgrp;
1492 struct css_set *newcg;
1493 struct cgroupfs_root *root = cgrp->root;
1495 /* Nothing to do if the task is already in that cgroup */
1496 oldcgrp = task_cgroup_from_root(tsk, root);
1497 if (cgrp == oldcgrp)
1500 for_each_subsys(root, ss) {
1501 if (ss->can_attach) {
1502 retval = ss->can_attach(ss, cgrp, tsk);
1513 * Locate or allocate a new css_set for this task,
1514 * based on its final set of cgroups
1516 newcg = find_css_set(cg, cgrp);
1522 if (tsk->flags & PF_EXITING) {
1527 rcu_assign_pointer(tsk->cgroups, newcg);
1530 /* Update the css_set linked lists if we're using them */
1531 write_lock(&css_set_lock);
1532 if (!list_empty(&tsk->cg_list)) {
1533 list_del(&tsk->cg_list);
1534 list_add(&tsk->cg_list, &newcg->tasks);
1536 write_unlock(&css_set_lock);
1538 for_each_subsys(root, ss) {
1540 ss->attach(ss, cgrp, oldcgrp, tsk);
1542 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1547 * wake up rmdir() waiter. the rmdir should fail since the cgroup
1548 * is no longer empty.
1550 cgroup_wakeup_rmdir_waiter(cgrp);
1555 * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
1556 * held. May take task_lock of task
1558 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
1560 struct task_struct *tsk;
1561 const struct cred *cred = current_cred(), *tcred;
1566 tsk = find_task_by_vpid(pid);
1567 if (!tsk || tsk->flags & PF_EXITING) {
1572 tcred = __task_cred(tsk);
1574 cred->euid != tcred->uid &&
1575 cred->euid != tcred->suid) {
1579 get_task_struct(tsk);
1583 get_task_struct(tsk);
1586 ret = cgroup_attach_task(cgrp, tsk);
1587 put_task_struct(tsk);
1591 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
1594 if (!cgroup_lock_live_group(cgrp))
1596 ret = attach_task_by_pid(cgrp, pid);
1601 /* The various types of files and directories in a cgroup file system */
1602 enum cgroup_filetype {
1606 FILE_NOTIFY_ON_RELEASE,
1611 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1612 * @cgrp: the cgroup to be checked for liveness
1614 * On success, returns true; the lock should be later released with
1615 * cgroup_unlock(). On failure returns false with no lock held.
1617 bool cgroup_lock_live_group(struct cgroup *cgrp)
1619 mutex_lock(&cgroup_mutex);
1620 if (cgroup_is_removed(cgrp)) {
1621 mutex_unlock(&cgroup_mutex);
1627 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1630 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1631 if (!cgroup_lock_live_group(cgrp))
1633 strcpy(cgrp->root->release_agent_path, buffer);
1638 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1639 struct seq_file *seq)
1641 if (!cgroup_lock_live_group(cgrp))
1643 seq_puts(seq, cgrp->root->release_agent_path);
1644 seq_putc(seq, '\n');
1649 /* A buffer size big enough for numbers or short strings */
1650 #define CGROUP_LOCAL_BUFFER_SIZE 64
1652 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1654 const char __user *userbuf,
1655 size_t nbytes, loff_t *unused_ppos)
1657 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1663 if (nbytes >= sizeof(buffer))
1665 if (copy_from_user(buffer, userbuf, nbytes))
1668 buffer[nbytes] = 0; /* nul-terminate */
1670 if (cft->write_u64) {
1671 u64 val = simple_strtoull(buffer, &end, 0);
1674 retval = cft->write_u64(cgrp, cft, val);
1676 s64 val = simple_strtoll(buffer, &end, 0);
1679 retval = cft->write_s64(cgrp, cft, val);
1686 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1688 const char __user *userbuf,
1689 size_t nbytes, loff_t *unused_ppos)
1691 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1693 size_t max_bytes = cft->max_write_len;
1694 char *buffer = local_buffer;
1697 max_bytes = sizeof(local_buffer) - 1;
1698 if (nbytes >= max_bytes)
1700 /* Allocate a dynamic buffer if we need one */
1701 if (nbytes >= sizeof(local_buffer)) {
1702 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1706 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
1711 buffer[nbytes] = 0; /* nul-terminate */
1713 retval = cft->write_string(cgrp, cft, buffer);
1717 if (buffer != local_buffer)
1722 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1723 size_t nbytes, loff_t *ppos)
1725 struct cftype *cft = __d_cft(file->f_dentry);
1726 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1728 if (cgroup_is_removed(cgrp))
1731 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1732 if (cft->write_u64 || cft->write_s64)
1733 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1734 if (cft->write_string)
1735 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1737 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1738 return ret ? ret : nbytes;
1743 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1745 char __user *buf, size_t nbytes,
1748 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1749 u64 val = cft->read_u64(cgrp, cft);
1750 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1752 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1755 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1757 char __user *buf, size_t nbytes,
1760 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1761 s64 val = cft->read_s64(cgrp, cft);
1762 int len = sprintf(tmp, "%lld\n", (long long) val);
1764 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1767 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1768 size_t nbytes, loff_t *ppos)
1770 struct cftype *cft = __d_cft(file->f_dentry);
1771 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1773 if (cgroup_is_removed(cgrp))
1777 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1779 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1781 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1786 * seqfile ops/methods for returning structured data. Currently just
1787 * supports string->u64 maps, but can be extended in future.
1790 struct cgroup_seqfile_state {
1792 struct cgroup *cgroup;
1795 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1797 struct seq_file *sf = cb->state;
1798 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1801 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1803 struct cgroup_seqfile_state *state = m->private;
1804 struct cftype *cft = state->cft;
1805 if (cft->read_map) {
1806 struct cgroup_map_cb cb = {
1807 .fill = cgroup_map_add,
1810 return cft->read_map(state->cgroup, cft, &cb);
1812 return cft->read_seq_string(state->cgroup, cft, m);
1815 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
1817 struct seq_file *seq = file->private_data;
1818 kfree(seq->private);
1819 return single_release(inode, file);
1822 static struct file_operations cgroup_seqfile_operations = {
1824 .write = cgroup_file_write,
1825 .llseek = seq_lseek,
1826 .release = cgroup_seqfile_release,
1829 static int cgroup_file_open(struct inode *inode, struct file *file)
1834 err = generic_file_open(inode, file);
1837 cft = __d_cft(file->f_dentry);
1839 if (cft->read_map || cft->read_seq_string) {
1840 struct cgroup_seqfile_state *state =
1841 kzalloc(sizeof(*state), GFP_USER);
1845 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
1846 file->f_op = &cgroup_seqfile_operations;
1847 err = single_open(file, cgroup_seqfile_show, state);
1850 } else if (cft->open)
1851 err = cft->open(inode, file);
1858 static int cgroup_file_release(struct inode *inode, struct file *file)
1860 struct cftype *cft = __d_cft(file->f_dentry);
1862 return cft->release(inode, file);
1867 * cgroup_rename - Only allow simple rename of directories in place.
1869 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
1870 struct inode *new_dir, struct dentry *new_dentry)
1872 if (!S_ISDIR(old_dentry->d_inode->i_mode))
1874 if (new_dentry->d_inode)
1876 if (old_dir != new_dir)
1878 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1881 static struct file_operations cgroup_file_operations = {
1882 .read = cgroup_file_read,
1883 .write = cgroup_file_write,
1884 .llseek = generic_file_llseek,
1885 .open = cgroup_file_open,
1886 .release = cgroup_file_release,
1889 static const struct inode_operations cgroup_dir_inode_operations = {
1890 .lookup = simple_lookup,
1891 .mkdir = cgroup_mkdir,
1892 .rmdir = cgroup_rmdir,
1893 .rename = cgroup_rename,
1896 static int cgroup_create_file(struct dentry *dentry, mode_t mode,
1897 struct super_block *sb)
1899 static const struct dentry_operations cgroup_dops = {
1900 .d_iput = cgroup_diput,
1903 struct inode *inode;
1907 if (dentry->d_inode)
1910 inode = cgroup_new_inode(mode, sb);
1914 if (S_ISDIR(mode)) {
1915 inode->i_op = &cgroup_dir_inode_operations;
1916 inode->i_fop = &simple_dir_operations;
1918 /* start off with i_nlink == 2 (for "." entry) */
1921 /* start with the directory inode held, so that we can
1922 * populate it without racing with another mkdir */
1923 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
1924 } else if (S_ISREG(mode)) {
1926 inode->i_fop = &cgroup_file_operations;
1928 dentry->d_op = &cgroup_dops;
1929 d_instantiate(dentry, inode);
1930 dget(dentry); /* Extra count - pin the dentry in core */
1935 * cgroup_create_dir - create a directory for an object.
1936 * @cgrp: the cgroup we create the directory for. It must have a valid
1937 * ->parent field. And we are going to fill its ->dentry field.
1938 * @dentry: dentry of the new cgroup
1939 * @mode: mode to set on new directory.
1941 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
1944 struct dentry *parent;
1947 parent = cgrp->parent->dentry;
1948 error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
1950 dentry->d_fsdata = cgrp;
1951 inc_nlink(parent->d_inode);
1952 rcu_assign_pointer(cgrp->dentry, dentry);
1961 * cgroup_file_mode - deduce file mode of a control file
1962 * @cft: the control file in question
1964 * returns cft->mode if ->mode is not 0
1965 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1966 * returns S_IRUGO if it has only a read handler
1967 * returns S_IWUSR if it has only a write hander
1969 static mode_t cgroup_file_mode(const struct cftype *cft)
1976 if (cft->read || cft->read_u64 || cft->read_s64 ||
1977 cft->read_map || cft->read_seq_string)
1980 if (cft->write || cft->write_u64 || cft->write_s64 ||
1981 cft->write_string || cft->trigger)
1987 int cgroup_add_file(struct cgroup *cgrp,
1988 struct cgroup_subsys *subsys,
1989 const struct cftype *cft)
1991 struct dentry *dir = cgrp->dentry;
1992 struct dentry *dentry;
1996 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
1997 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
1998 strcpy(name, subsys->name);
2001 strcat(name, cft->name);
2002 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2003 dentry = lookup_one_len(name, dir, strlen(name));
2004 if (!IS_ERR(dentry)) {
2005 mode = cgroup_file_mode(cft);
2006 error = cgroup_create_file(dentry, mode | S_IFREG,
2009 dentry->d_fsdata = (void *)cft;
2012 error = PTR_ERR(dentry);
2016 int cgroup_add_files(struct cgroup *cgrp,
2017 struct cgroup_subsys *subsys,
2018 const struct cftype cft[],
2022 for (i = 0; i < count; i++) {
2023 err = cgroup_add_file(cgrp, subsys, &cft[i]);
2031 * cgroup_task_count - count the number of tasks in a cgroup.
2032 * @cgrp: the cgroup in question
2034 * Return the number of tasks in the cgroup.
2036 int cgroup_task_count(const struct cgroup *cgrp)
2039 struct cg_cgroup_link *link;
2041 read_lock(&css_set_lock);
2042 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2043 count += atomic_read(&link->cg->refcount);
2045 read_unlock(&css_set_lock);
2050 * Advance a list_head iterator. The iterator should be positioned at
2051 * the start of a css_set
2053 static void cgroup_advance_iter(struct cgroup *cgrp,
2054 struct cgroup_iter *it)
2056 struct list_head *l = it->cg_link;
2057 struct cg_cgroup_link *link;
2060 /* Advance to the next non-empty css_set */
2063 if (l == &cgrp->css_sets) {
2067 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2069 } while (list_empty(&cg->tasks));
2071 it->task = cg->tasks.next;
2075 * To reduce the fork() overhead for systems that are not actually
2076 * using their cgroups capability, we don't maintain the lists running
2077 * through each css_set to its tasks until we see the list actually
2078 * used - in other words after the first call to cgroup_iter_start().
2080 * The tasklist_lock is not held here, as do_each_thread() and
2081 * while_each_thread() are protected by RCU.
2083 static void cgroup_enable_task_cg_lists(void)
2085 struct task_struct *p, *g;
2086 write_lock(&css_set_lock);
2087 use_task_css_set_links = 1;
2088 do_each_thread(g, p) {
2091 * We should check if the process is exiting, otherwise
2092 * it will race with cgroup_exit() in that the list
2093 * entry won't be deleted though the process has exited.
2095 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2096 list_add(&p->cg_list, &p->cgroups->tasks);
2098 } while_each_thread(g, p);
2099 write_unlock(&css_set_lock);
2102 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
2105 * The first time anyone tries to iterate across a cgroup,
2106 * we need to enable the list linking each css_set to its
2107 * tasks, and fix up all existing tasks.
2109 if (!use_task_css_set_links)
2110 cgroup_enable_task_cg_lists();
2112 read_lock(&css_set_lock);
2113 it->cg_link = &cgrp->css_sets;
2114 cgroup_advance_iter(cgrp, it);
2117 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
2118 struct cgroup_iter *it)
2120 struct task_struct *res;
2121 struct list_head *l = it->task;
2122 struct cg_cgroup_link *link;
2124 /* If the iterator cg is NULL, we have no tasks */
2127 res = list_entry(l, struct task_struct, cg_list);
2128 /* Advance iterator to find next entry */
2130 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
2131 if (l == &link->cg->tasks) {
2132 /* We reached the end of this task list - move on to
2133 * the next cg_cgroup_link */
2134 cgroup_advance_iter(cgrp, it);
2141 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
2143 read_unlock(&css_set_lock);
2146 static inline int started_after_time(struct task_struct *t1,
2147 struct timespec *time,
2148 struct task_struct *t2)
2150 int start_diff = timespec_compare(&t1->start_time, time);
2151 if (start_diff > 0) {
2153 } else if (start_diff < 0) {
2157 * Arbitrarily, if two processes started at the same
2158 * time, we'll say that the lower pointer value
2159 * started first. Note that t2 may have exited by now
2160 * so this may not be a valid pointer any longer, but
2161 * that's fine - it still serves to distinguish
2162 * between two tasks started (effectively) simultaneously.
2169 * This function is a callback from heap_insert() and is used to order
2171 * In this case we order the heap in descending task start time.
2173 static inline int started_after(void *p1, void *p2)
2175 struct task_struct *t1 = p1;
2176 struct task_struct *t2 = p2;
2177 return started_after_time(t1, &t2->start_time, t2);
2181 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
2182 * @scan: struct cgroup_scanner containing arguments for the scan
2184 * Arguments include pointers to callback functions test_task() and
2186 * Iterate through all the tasks in a cgroup, calling test_task() for each,
2187 * and if it returns true, call process_task() for it also.
2188 * The test_task pointer may be NULL, meaning always true (select all tasks).
2189 * Effectively duplicates cgroup_iter_{start,next,end}()
2190 * but does not lock css_set_lock for the call to process_task().
2191 * The struct cgroup_scanner may be embedded in any structure of the caller's
2193 * It is guaranteed that process_task() will act on every task that
2194 * is a member of the cgroup for the duration of this call. This
2195 * function may or may not call process_task() for tasks that exit
2196 * or move to a different cgroup during the call, or are forked or
2197 * move into the cgroup during the call.
2199 * Note that test_task() may be called with locks held, and may in some
2200 * situations be called multiple times for the same task, so it should
2202 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
2203 * pre-allocated and will be used for heap operations (and its "gt" member will
2204 * be overwritten), else a temporary heap will be used (allocation of which
2205 * may cause this function to fail).
2207 int cgroup_scan_tasks(struct cgroup_scanner *scan)
2210 struct cgroup_iter it;
2211 struct task_struct *p, *dropped;
2212 /* Never dereference latest_task, since it's not refcounted */
2213 struct task_struct *latest_task = NULL;
2214 struct ptr_heap tmp_heap;
2215 struct ptr_heap *heap;
2216 struct timespec latest_time = { 0, 0 };
2219 /* The caller supplied our heap and pre-allocated its memory */
2221 heap->gt = &started_after;
2223 /* We need to allocate our own heap memory */
2225 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2227 /* cannot allocate the heap */
2233 * Scan tasks in the cgroup, using the scanner's "test_task" callback
2234 * to determine which are of interest, and using the scanner's
2235 * "process_task" callback to process any of them that need an update.
2236 * Since we don't want to hold any locks during the task updates,
2237 * gather tasks to be processed in a heap structure.
2238 * The heap is sorted by descending task start time.
2239 * If the statically-sized heap fills up, we overflow tasks that
2240 * started later, and in future iterations only consider tasks that
2241 * started after the latest task in the previous pass. This
2242 * guarantees forward progress and that we don't miss any tasks.
2245 cgroup_iter_start(scan->cg, &it);
2246 while ((p = cgroup_iter_next(scan->cg, &it))) {
2248 * Only affect tasks that qualify per the caller's callback,
2249 * if he provided one
2251 if (scan->test_task && !scan->test_task(p, scan))
2254 * Only process tasks that started after the last task
2257 if (!started_after_time(p, &latest_time, latest_task))
2259 dropped = heap_insert(heap, p);
2260 if (dropped == NULL) {
2262 * The new task was inserted; the heap wasn't
2266 } else if (dropped != p) {
2268 * The new task was inserted, and pushed out a
2272 put_task_struct(dropped);
2275 * Else the new task was newer than anything already in
2276 * the heap and wasn't inserted
2279 cgroup_iter_end(scan->cg, &it);
2282 for (i = 0; i < heap->size; i++) {
2283 struct task_struct *q = heap->ptrs[i];
2285 latest_time = q->start_time;
2288 /* Process the task per the caller's callback */
2289 scan->process_task(q, scan);
2293 * If we had to process any tasks at all, scan again
2294 * in case some of them were in the middle of forking
2295 * children that didn't get processed.
2296 * Not the most efficient way to do it, but it avoids
2297 * having to take callback_mutex in the fork path
2301 if (heap == &tmp_heap)
2302 heap_free(&tmp_heap);
2307 * Stuff for reading the 'tasks' file.
2309 * Reading this file can return large amounts of data if a cgroup has
2310 * *lots* of attached tasks. So it may need several calls to read(),
2311 * but we cannot guarantee that the information we produce is correct
2312 * unless we produce it entirely atomically.
2317 * Load into 'pidarray' up to 'npids' of the tasks using cgroup
2318 * 'cgrp'. Return actual number of pids loaded. No need to
2319 * task_lock(p) when reading out p->cgroup, since we're in an RCU
2320 * read section, so the css_set can't go away, and is
2321 * immutable after creation.
2323 static int pid_array_load(pid_t *pidarray, int npids, struct cgroup *cgrp)
2326 struct cgroup_iter it;
2327 struct task_struct *tsk;
2328 cgroup_iter_start(cgrp, &it);
2329 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2330 if (unlikely(n == npids))
2332 pid = task_pid_vnr(tsk);
2334 pidarray[n++] = pid;
2336 cgroup_iter_end(cgrp, &it);
2341 * cgroupstats_build - build and fill cgroupstats
2342 * @stats: cgroupstats to fill information into
2343 * @dentry: A dentry entry belonging to the cgroup for which stats have
2346 * Build and fill cgroupstats so that taskstats can export it to user
2349 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2352 struct cgroup *cgrp;
2353 struct cgroup_iter it;
2354 struct task_struct *tsk;
2357 * Validate dentry by checking the superblock operations,
2358 * and make sure it's a directory.
2360 if (dentry->d_sb->s_op != &cgroup_ops ||
2361 !S_ISDIR(dentry->d_inode->i_mode))
2365 cgrp = dentry->d_fsdata;
2367 cgroup_iter_start(cgrp, &it);
2368 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2369 switch (tsk->state) {
2371 stats->nr_running++;
2373 case TASK_INTERRUPTIBLE:
2374 stats->nr_sleeping++;
2376 case TASK_UNINTERRUPTIBLE:
2377 stats->nr_uninterruptible++;
2380 stats->nr_stopped++;
2383 if (delayacct_is_task_waiting_on_io(tsk))
2384 stats->nr_io_wait++;
2388 cgroup_iter_end(cgrp, &it);
2395 * Cache pids for all threads in the same pid namespace that are
2396 * opening the same "tasks" file.
2398 struct cgroup_pids {
2399 /* The node in cgrp->pids_list */
2400 struct list_head list;
2401 /* The cgroup those pids belong to */
2402 struct cgroup *cgrp;
2403 /* The namepsace those pids belong to */
2404 struct pid_namespace *ns;
2405 /* Array of process ids in the cgroup */
2407 /* How many files are using the this tasks_pids array */
2409 /* Length of the current tasks_pids array */
2413 static int cmppid(const void *a, const void *b)
2415 return *(pid_t *)a - *(pid_t *)b;
2419 * seq_file methods for the "tasks" file. The seq_file position is the
2420 * next pid to display; the seq_file iterator is a pointer to the pid
2421 * in the cgroup->tasks_pids array.
2424 static void *cgroup_tasks_start(struct seq_file *s, loff_t *pos)
2427 * Initially we receive a position value that corresponds to
2428 * one more than the last pid shown (or 0 on the first call or
2429 * after a seek to the start). Use a binary-search to find the
2430 * next pid to display, if any
2432 struct cgroup_pids *cp = s->private;
2433 struct cgroup *cgrp = cp->cgrp;
2434 int index = 0, pid = *pos;
2437 down_read(&cgrp->pids_mutex);
2439 int end = cp->length;
2441 while (index < end) {
2442 int mid = (index + end) / 2;
2443 if (cp->tasks_pids[mid] == pid) {
2446 } else if (cp->tasks_pids[mid] <= pid)
2452 /* If we're off the end of the array, we're done */
2453 if (index >= cp->length)
2455 /* Update the abstract position to be the actual pid that we found */
2456 iter = cp->tasks_pids + index;
2461 static void cgroup_tasks_stop(struct seq_file *s, void *v)
2463 struct cgroup_pids *cp = s->private;
2464 struct cgroup *cgrp = cp->cgrp;
2465 up_read(&cgrp->pids_mutex);
2468 static void *cgroup_tasks_next(struct seq_file *s, void *v, loff_t *pos)
2470 struct cgroup_pids *cp = s->private;
2472 int *end = cp->tasks_pids + cp->length;
2475 * Advance to the next pid in the array. If this goes off the
2487 static int cgroup_tasks_show(struct seq_file *s, void *v)
2489 return seq_printf(s, "%d\n", *(int *)v);
2492 static const struct seq_operations cgroup_tasks_seq_operations = {
2493 .start = cgroup_tasks_start,
2494 .stop = cgroup_tasks_stop,
2495 .next = cgroup_tasks_next,
2496 .show = cgroup_tasks_show,
2499 static void release_cgroup_pid_array(struct cgroup_pids *cp)
2501 struct cgroup *cgrp = cp->cgrp;
2503 down_write(&cgrp->pids_mutex);
2504 BUG_ON(!cp->use_count);
2505 if (!--cp->use_count) {
2506 list_del(&cp->list);
2508 kfree(cp->tasks_pids);
2511 up_write(&cgrp->pids_mutex);
2514 static int cgroup_tasks_release(struct inode *inode, struct file *file)
2516 struct seq_file *seq;
2517 struct cgroup_pids *cp;
2519 if (!(file->f_mode & FMODE_READ))
2522 seq = file->private_data;
2525 release_cgroup_pid_array(cp);
2526 return seq_release(inode, file);
2529 static struct file_operations cgroup_tasks_operations = {
2531 .llseek = seq_lseek,
2532 .write = cgroup_file_write,
2533 .release = cgroup_tasks_release,
2537 * Handle an open on 'tasks' file. Prepare an array containing the
2538 * process id's of tasks currently attached to the cgroup being opened.
2541 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2543 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2544 struct pid_namespace *ns = current->nsproxy->pid_ns;
2545 struct cgroup_pids *cp;
2550 /* Nothing to do for write-only files */
2551 if (!(file->f_mode & FMODE_READ))
2555 * If cgroup gets more users after we read count, we won't have
2556 * enough space - tough. This race is indistinguishable to the
2557 * caller from the case that the additional cgroup users didn't
2558 * show up until sometime later on.
2560 npids = cgroup_task_count(cgrp);
2561 pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
2564 npids = pid_array_load(pidarray, npids, cgrp);
2565 sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
2568 * Store the array in the cgroup, freeing the old
2569 * array if necessary
2571 down_write(&cgrp->pids_mutex);
2573 list_for_each_entry(cp, &cgrp->pids_list, list) {
2578 cp = kzalloc(sizeof(*cp), GFP_KERNEL);
2580 up_write(&cgrp->pids_mutex);
2587 list_add(&cp->list, &cgrp->pids_list);
2589 kfree(cp->tasks_pids);
2590 cp->tasks_pids = pidarray;
2593 up_write(&cgrp->pids_mutex);
2595 file->f_op = &cgroup_tasks_operations;
2597 retval = seq_open(file, &cgroup_tasks_seq_operations);
2599 release_cgroup_pid_array(cp);
2602 ((struct seq_file *)file->private_data)->private = cp;
2606 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2609 return notify_on_release(cgrp);
2612 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2616 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2618 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2620 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2625 * for the common functions, 'private' gives the type of file
2627 static struct cftype files[] = {
2630 .open = cgroup_tasks_open,
2631 .write_u64 = cgroup_tasks_write,
2632 .release = cgroup_tasks_release,
2633 .private = FILE_TASKLIST,
2634 .mode = S_IRUGO | S_IWUSR,
2638 .name = "notify_on_release",
2639 .read_u64 = cgroup_read_notify_on_release,
2640 .write_u64 = cgroup_write_notify_on_release,
2641 .private = FILE_NOTIFY_ON_RELEASE,
2645 static struct cftype cft_release_agent = {
2646 .name = "release_agent",
2647 .read_seq_string = cgroup_release_agent_show,
2648 .write_string = cgroup_release_agent_write,
2649 .max_write_len = PATH_MAX,
2650 .private = FILE_RELEASE_AGENT,
2653 static int cgroup_populate_dir(struct cgroup *cgrp)
2656 struct cgroup_subsys *ss;
2658 /* First clear out any existing files */
2659 cgroup_clear_directory(cgrp->dentry);
2661 err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2665 if (cgrp == cgrp->top_cgroup) {
2666 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2670 for_each_subsys(cgrp->root, ss) {
2671 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2674 /* This cgroup is ready now */
2675 for_each_subsys(cgrp->root, ss) {
2676 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2678 * Update id->css pointer and make this css visible from
2679 * CSS ID functions. This pointer will be dereferened
2680 * from RCU-read-side without locks.
2683 rcu_assign_pointer(css->id->css, css);
2689 static void init_cgroup_css(struct cgroup_subsys_state *css,
2690 struct cgroup_subsys *ss,
2691 struct cgroup *cgrp)
2694 atomic_set(&css->refcnt, 1);
2697 if (cgrp == dummytop)
2698 set_bit(CSS_ROOT, &css->flags);
2699 BUG_ON(cgrp->subsys[ss->subsys_id]);
2700 cgrp->subsys[ss->subsys_id] = css;
2703 static void cgroup_lock_hierarchy(struct cgroupfs_root *root)
2705 /* We need to take each hierarchy_mutex in a consistent order */
2708 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2709 struct cgroup_subsys *ss = subsys[i];
2710 if (ss->root == root)
2711 mutex_lock(&ss->hierarchy_mutex);
2715 static void cgroup_unlock_hierarchy(struct cgroupfs_root *root)
2719 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2720 struct cgroup_subsys *ss = subsys[i];
2721 if (ss->root == root)
2722 mutex_unlock(&ss->hierarchy_mutex);
2727 * cgroup_create - create a cgroup
2728 * @parent: cgroup that will be parent of the new cgroup
2729 * @dentry: dentry of the new cgroup
2730 * @mode: mode to set on new inode
2732 * Must be called with the mutex on the parent inode held
2734 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
2737 struct cgroup *cgrp;
2738 struct cgroupfs_root *root = parent->root;
2740 struct cgroup_subsys *ss;
2741 struct super_block *sb = root->sb;
2743 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
2747 /* Grab a reference on the superblock so the hierarchy doesn't
2748 * get deleted on unmount if there are child cgroups. This
2749 * can be done outside cgroup_mutex, since the sb can't
2750 * disappear while someone has an open control file on the
2752 atomic_inc(&sb->s_active);
2754 mutex_lock(&cgroup_mutex);
2756 init_cgroup_housekeeping(cgrp);
2758 cgrp->parent = parent;
2759 cgrp->root = parent->root;
2760 cgrp->top_cgroup = parent->top_cgroup;
2762 if (notify_on_release(parent))
2763 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2765 for_each_subsys(root, ss) {
2766 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
2771 init_cgroup_css(css, ss, cgrp);
2773 if (alloc_css_id(ss, parent, cgrp))
2775 /* At error, ->destroy() callback has to free assigned ID. */
2778 cgroup_lock_hierarchy(root);
2779 list_add(&cgrp->sibling, &cgrp->parent->children);
2780 cgroup_unlock_hierarchy(root);
2781 root->number_of_cgroups++;
2783 err = cgroup_create_dir(cgrp, dentry, mode);
2787 /* The cgroup directory was pre-locked for us */
2788 BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
2790 err = cgroup_populate_dir(cgrp);
2791 /* If err < 0, we have a half-filled directory - oh well ;) */
2793 mutex_unlock(&cgroup_mutex);
2794 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
2800 cgroup_lock_hierarchy(root);
2801 list_del(&cgrp->sibling);
2802 cgroup_unlock_hierarchy(root);
2803 root->number_of_cgroups--;
2807 for_each_subsys(root, ss) {
2808 if (cgrp->subsys[ss->subsys_id])
2809 ss->destroy(ss, cgrp);
2812 mutex_unlock(&cgroup_mutex);
2814 /* Release the reference count that we took on the superblock */
2815 deactivate_super(sb);
2821 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2823 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
2825 /* the vfs holds inode->i_mutex already */
2826 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
2829 static int cgroup_has_css_refs(struct cgroup *cgrp)
2831 /* Check the reference count on each subsystem. Since we
2832 * already established that there are no tasks in the
2833 * cgroup, if the css refcount is also 1, then there should
2834 * be no outstanding references, so the subsystem is safe to
2835 * destroy. We scan across all subsystems rather than using
2836 * the per-hierarchy linked list of mounted subsystems since
2837 * we can be called via check_for_release() with no
2838 * synchronization other than RCU, and the subsystem linked
2839 * list isn't RCU-safe */
2841 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2842 struct cgroup_subsys *ss = subsys[i];
2843 struct cgroup_subsys_state *css;
2844 /* Skip subsystems not in this hierarchy */
2845 if (ss->root != cgrp->root)
2847 css = cgrp->subsys[ss->subsys_id];
2848 /* When called from check_for_release() it's possible
2849 * that by this point the cgroup has been removed
2850 * and the css deleted. But a false-positive doesn't
2851 * matter, since it can only happen if the cgroup
2852 * has been deleted and hence no longer needs the
2853 * release agent to be called anyway. */
2854 if (css && (atomic_read(&css->refcnt) > 1))
2861 * Atomically mark all (or else none) of the cgroup's CSS objects as
2862 * CSS_REMOVED. Return true on success, or false if the cgroup has
2863 * busy subsystems. Call with cgroup_mutex held
2866 static int cgroup_clear_css_refs(struct cgroup *cgrp)
2868 struct cgroup_subsys *ss;
2869 unsigned long flags;
2870 bool failed = false;
2871 local_irq_save(flags);
2872 for_each_subsys(cgrp->root, ss) {
2873 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2876 /* We can only remove a CSS with a refcnt==1 */
2877 refcnt = atomic_read(&css->refcnt);
2884 * Drop the refcnt to 0 while we check other
2885 * subsystems. This will cause any racing
2886 * css_tryget() to spin until we set the
2887 * CSS_REMOVED bits or abort
2889 if (atomic_cmpxchg(&css->refcnt, refcnt, 0) == refcnt)
2895 for_each_subsys(cgrp->root, ss) {
2896 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2899 * Restore old refcnt if we previously managed
2900 * to clear it from 1 to 0
2902 if (!atomic_read(&css->refcnt))
2903 atomic_set(&css->refcnt, 1);
2905 /* Commit the fact that the CSS is removed */
2906 set_bit(CSS_REMOVED, &css->flags);
2909 local_irq_restore(flags);
2913 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
2915 struct cgroup *cgrp = dentry->d_fsdata;
2917 struct cgroup *parent;
2921 /* the vfs holds both inode->i_mutex already */
2923 mutex_lock(&cgroup_mutex);
2924 if (atomic_read(&cgrp->count) != 0) {
2925 mutex_unlock(&cgroup_mutex);
2928 if (!list_empty(&cgrp->children)) {
2929 mutex_unlock(&cgroup_mutex);
2932 mutex_unlock(&cgroup_mutex);
2935 * In general, subsystem has no css->refcnt after pre_destroy(). But
2936 * in racy cases, subsystem may have to get css->refcnt after
2937 * pre_destroy() and it makes rmdir return with -EBUSY. This sometimes
2938 * make rmdir return -EBUSY too often. To avoid that, we use waitqueue
2939 * for cgroup's rmdir. CGRP_WAIT_ON_RMDIR is for synchronizing rmdir
2940 * and subsystem's reference count handling. Please see css_get/put
2941 * and css_tryget() and cgroup_wakeup_rmdir_waiter() implementation.
2943 set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2946 * Call pre_destroy handlers of subsys. Notify subsystems
2947 * that rmdir() request comes.
2949 ret = cgroup_call_pre_destroy(cgrp);
2951 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2955 mutex_lock(&cgroup_mutex);
2956 parent = cgrp->parent;
2957 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
2958 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2959 mutex_unlock(&cgroup_mutex);
2962 prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
2963 if (!cgroup_clear_css_refs(cgrp)) {
2964 mutex_unlock(&cgroup_mutex);
2966 * Because someone may call cgroup_wakeup_rmdir_waiter() before
2967 * prepare_to_wait(), we need to check this flag.
2969 if (test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))
2971 finish_wait(&cgroup_rmdir_waitq, &wait);
2972 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2973 if (signal_pending(current))
2977 /* NO css_tryget() can success after here. */
2978 finish_wait(&cgroup_rmdir_waitq, &wait);
2979 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2981 spin_lock(&release_list_lock);
2982 set_bit(CGRP_REMOVED, &cgrp->flags);
2983 if (!list_empty(&cgrp->release_list))
2984 list_del(&cgrp->release_list);
2985 spin_unlock(&release_list_lock);
2987 cgroup_lock_hierarchy(cgrp->root);
2988 /* delete this cgroup from parent->children */
2989 list_del(&cgrp->sibling);
2990 cgroup_unlock_hierarchy(cgrp->root);
2992 spin_lock(&cgrp->dentry->d_lock);
2993 d = dget(cgrp->dentry);
2994 spin_unlock(&d->d_lock);
2996 cgroup_d_remove_dir(d);
2999 set_bit(CGRP_RELEASABLE, &parent->flags);
3000 check_for_release(parent);
3002 mutex_unlock(&cgroup_mutex);
3006 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
3008 struct cgroup_subsys_state *css;
3010 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
3012 /* Create the top cgroup state for this subsystem */
3013 list_add(&ss->sibling, &rootnode.subsys_list);
3014 ss->root = &rootnode;
3015 css = ss->create(ss, dummytop);
3016 /* We don't handle early failures gracefully */
3017 BUG_ON(IS_ERR(css));
3018 init_cgroup_css(css, ss, dummytop);
3020 /* Update the init_css_set to contain a subsys
3021 * pointer to this state - since the subsystem is
3022 * newly registered, all tasks and hence the
3023 * init_css_set is in the subsystem's top cgroup. */
3024 init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
3026 need_forkexit_callback |= ss->fork || ss->exit;
3028 /* At system boot, before all subsystems have been
3029 * registered, no tasks have been forked, so we don't
3030 * need to invoke fork callbacks here. */
3031 BUG_ON(!list_empty(&init_task.tasks));
3033 mutex_init(&ss->hierarchy_mutex);
3034 lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
3039 * cgroup_init_early - cgroup initialization at system boot
3041 * Initialize cgroups at system boot, and initialize any
3042 * subsystems that request early init.
3044 int __init cgroup_init_early(void)
3047 atomic_set(&init_css_set.refcount, 1);
3048 INIT_LIST_HEAD(&init_css_set.cg_links);
3049 INIT_LIST_HEAD(&init_css_set.tasks);
3050 INIT_HLIST_NODE(&init_css_set.hlist);
3052 init_cgroup_root(&rootnode);
3054 init_task.cgroups = &init_css_set;
3056 init_css_set_link.cg = &init_css_set;
3057 init_css_set_link.cgrp = dummytop;
3058 list_add(&init_css_set_link.cgrp_link_list,
3059 &rootnode.top_cgroup.css_sets);
3060 list_add(&init_css_set_link.cg_link_list,
3061 &init_css_set.cg_links);
3063 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
3064 INIT_HLIST_HEAD(&css_set_table[i]);
3066 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3067 struct cgroup_subsys *ss = subsys[i];
3070 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
3071 BUG_ON(!ss->create);
3072 BUG_ON(!ss->destroy);
3073 if (ss->subsys_id != i) {
3074 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
3075 ss->name, ss->subsys_id);
3080 cgroup_init_subsys(ss);
3086 * cgroup_init - cgroup initialization
3088 * Register cgroup filesystem and /proc file, and initialize
3089 * any subsystems that didn't request early init.
3091 int __init cgroup_init(void)
3095 struct hlist_head *hhead;
3097 err = bdi_init(&cgroup_backing_dev_info);
3101 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3102 struct cgroup_subsys *ss = subsys[i];
3103 if (!ss->early_init)
3104 cgroup_init_subsys(ss);
3106 cgroup_subsys_init_idr(ss);
3109 /* Add init_css_set to the hash table */
3110 hhead = css_set_hash(init_css_set.subsys);
3111 hlist_add_head(&init_css_set.hlist, hhead);
3113 err = register_filesystem(&cgroup_fs_type);
3117 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
3121 bdi_destroy(&cgroup_backing_dev_info);
3127 * proc_cgroup_show()
3128 * - Print task's cgroup paths into seq_file, one line for each hierarchy
3129 * - Used for /proc/<pid>/cgroup.
3130 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
3131 * doesn't really matter if tsk->cgroup changes after we read it,
3132 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
3133 * anyway. No need to check that tsk->cgroup != NULL, thanks to
3134 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
3135 * cgroup to top_cgroup.
3138 /* TODO: Use a proper seq_file iterator */
3139 static int proc_cgroup_show(struct seq_file *m, void *v)
3142 struct task_struct *tsk;
3145 struct cgroupfs_root *root;
3148 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3154 tsk = get_pid_task(pid, PIDTYPE_PID);
3160 mutex_lock(&cgroup_mutex);
3162 for_each_active_root(root) {
3163 struct cgroup_subsys *ss;
3164 struct cgroup *cgrp;
3167 seq_printf(m, "%lu:", root->subsys_bits);
3168 for_each_subsys(root, ss)
3169 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
3170 if (strlen(root->name))
3171 seq_printf(m, "%sname=%s", count ? "," : "",
3174 cgrp = task_cgroup_from_root(tsk, root);
3175 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
3183 mutex_unlock(&cgroup_mutex);
3184 put_task_struct(tsk);
3191 static int cgroup_open(struct inode *inode, struct file *file)
3193 struct pid *pid = PROC_I(inode)->pid;
3194 return single_open(file, proc_cgroup_show, pid);
3197 struct file_operations proc_cgroup_operations = {
3198 .open = cgroup_open,
3200 .llseek = seq_lseek,
3201 .release = single_release,
3204 /* Display information about each subsystem and each hierarchy */
3205 static int proc_cgroupstats_show(struct seq_file *m, void *v)
3209 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
3210 mutex_lock(&cgroup_mutex);
3211 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3212 struct cgroup_subsys *ss = subsys[i];
3213 seq_printf(m, "%s\t%lu\t%d\t%d\n",
3214 ss->name, ss->root->subsys_bits,
3215 ss->root->number_of_cgroups, !ss->disabled);
3217 mutex_unlock(&cgroup_mutex);
3221 static int cgroupstats_open(struct inode *inode, struct file *file)
3223 return single_open(file, proc_cgroupstats_show, NULL);
3226 static struct file_operations proc_cgroupstats_operations = {
3227 .open = cgroupstats_open,
3229 .llseek = seq_lseek,
3230 .release = single_release,
3234 * cgroup_fork - attach newly forked task to its parents cgroup.
3235 * @child: pointer to task_struct of forking parent process.
3237 * Description: A task inherits its parent's cgroup at fork().
3239 * A pointer to the shared css_set was automatically copied in
3240 * fork.c by dup_task_struct(). However, we ignore that copy, since
3241 * it was not made under the protection of RCU or cgroup_mutex, so
3242 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
3243 * have already changed current->cgroups, allowing the previously
3244 * referenced cgroup group to be removed and freed.
3246 * At the point that cgroup_fork() is called, 'current' is the parent
3247 * task, and the passed argument 'child' points to the child task.
3249 void cgroup_fork(struct task_struct *child)
3252 child->cgroups = current->cgroups;
3253 get_css_set(child->cgroups);
3254 task_unlock(current);
3255 INIT_LIST_HEAD(&child->cg_list);
3259 * cgroup_fork_callbacks - run fork callbacks
3260 * @child: the new task
3262 * Called on a new task very soon before adding it to the
3263 * tasklist. No need to take any locks since no-one can
3264 * be operating on this task.
3266 void cgroup_fork_callbacks(struct task_struct *child)
3268 if (need_forkexit_callback) {
3270 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3271 struct cgroup_subsys *ss = subsys[i];
3273 ss->fork(ss, child);
3279 * cgroup_post_fork - called on a new task after adding it to the task list
3280 * @child: the task in question
3282 * Adds the task to the list running through its css_set if necessary.
3283 * Has to be after the task is visible on the task list in case we race
3284 * with the first call to cgroup_iter_start() - to guarantee that the
3285 * new task ends up on its list.
3287 void cgroup_post_fork(struct task_struct *child)
3289 if (use_task_css_set_links) {
3290 write_lock(&css_set_lock);
3292 if (list_empty(&child->cg_list))
3293 list_add(&child->cg_list, &child->cgroups->tasks);
3295 write_unlock(&css_set_lock);
3299 * cgroup_exit - detach cgroup from exiting task
3300 * @tsk: pointer to task_struct of exiting process
3301 * @run_callback: run exit callbacks?
3303 * Description: Detach cgroup from @tsk and release it.
3305 * Note that cgroups marked notify_on_release force every task in
3306 * them to take the global cgroup_mutex mutex when exiting.
3307 * This could impact scaling on very large systems. Be reluctant to
3308 * use notify_on_release cgroups where very high task exit scaling
3309 * is required on large systems.
3311 * the_top_cgroup_hack:
3313 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
3315 * We call cgroup_exit() while the task is still competent to
3316 * handle notify_on_release(), then leave the task attached to the
3317 * root cgroup in each hierarchy for the remainder of its exit.
3319 * To do this properly, we would increment the reference count on
3320 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
3321 * code we would add a second cgroup function call, to drop that
3322 * reference. This would just create an unnecessary hot spot on
3323 * the top_cgroup reference count, to no avail.
3325 * Normally, holding a reference to a cgroup without bumping its
3326 * count is unsafe. The cgroup could go away, or someone could
3327 * attach us to a different cgroup, decrementing the count on
3328 * the first cgroup that we never incremented. But in this case,
3329 * top_cgroup isn't going away, and either task has PF_EXITING set,
3330 * which wards off any cgroup_attach_task() attempts, or task is a failed
3331 * fork, never visible to cgroup_attach_task.
3333 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
3338 if (run_callbacks && need_forkexit_callback) {
3339 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3340 struct cgroup_subsys *ss = subsys[i];
3347 * Unlink from the css_set task list if necessary.
3348 * Optimistically check cg_list before taking
3351 if (!list_empty(&tsk->cg_list)) {
3352 write_lock(&css_set_lock);
3353 if (!list_empty(&tsk->cg_list))
3354 list_del(&tsk->cg_list);
3355 write_unlock(&css_set_lock);
3358 /* Reassign the task to the init_css_set. */
3361 tsk->cgroups = &init_css_set;
3364 put_css_set_taskexit(cg);
3368 * cgroup_clone - clone the cgroup the given subsystem is attached to
3369 * @tsk: the task to be moved
3370 * @subsys: the given subsystem
3371 * @nodename: the name for the new cgroup
3373 * Duplicate the current cgroup in the hierarchy that the given
3374 * subsystem is attached to, and move this task into the new
3377 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
3380 struct dentry *dentry;
3382 struct cgroup *parent, *child;
3383 struct inode *inode;
3385 struct cgroupfs_root *root;
3386 struct cgroup_subsys *ss;
3388 /* We shouldn't be called by an unregistered subsystem */
3389 BUG_ON(!subsys->active);
3391 /* First figure out what hierarchy and cgroup we're dealing
3392 * with, and pin them so we can drop cgroup_mutex */
3393 mutex_lock(&cgroup_mutex);
3395 root = subsys->root;
3396 if (root == &rootnode) {
3397 mutex_unlock(&cgroup_mutex);
3401 /* Pin the hierarchy */
3402 if (!atomic_inc_not_zero(&root->sb->s_active)) {
3403 /* We race with the final deactivate_super() */
3404 mutex_unlock(&cgroup_mutex);
3408 /* Keep the cgroup alive */
3410 parent = task_cgroup(tsk, subsys->subsys_id);
3415 mutex_unlock(&cgroup_mutex);
3417 /* Now do the VFS work to create a cgroup */
3418 inode = parent->dentry->d_inode;
3420 /* Hold the parent directory mutex across this operation to
3421 * stop anyone else deleting the new cgroup */
3422 mutex_lock(&inode->i_mutex);
3423 dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
3424 if (IS_ERR(dentry)) {
3426 "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
3428 ret = PTR_ERR(dentry);
3432 /* Create the cgroup directory, which also creates the cgroup */
3433 ret = vfs_mkdir(inode, dentry, 0755);
3434 child = __d_cgrp(dentry);
3438 "Failed to create cgroup %s: %d\n", nodename,
3443 /* The cgroup now exists. Retake cgroup_mutex and check
3444 * that we're still in the same state that we thought we
3446 mutex_lock(&cgroup_mutex);
3447 if ((root != subsys->root) ||
3448 (parent != task_cgroup(tsk, subsys->subsys_id))) {
3449 /* Aargh, we raced ... */
3450 mutex_unlock(&inode->i_mutex);
3453 deactivate_super(root->sb);
3454 /* The cgroup is still accessible in the VFS, but
3455 * we're not going to try to rmdir() it at this
3458 "Race in cgroup_clone() - leaking cgroup %s\n",
3463 /* do any required auto-setup */
3464 for_each_subsys(root, ss) {
3466 ss->post_clone(ss, child);
3469 /* All seems fine. Finish by moving the task into the new cgroup */
3470 ret = cgroup_attach_task(child, tsk);
3471 mutex_unlock(&cgroup_mutex);
3474 mutex_unlock(&inode->i_mutex);
3476 mutex_lock(&cgroup_mutex);
3478 mutex_unlock(&cgroup_mutex);
3479 deactivate_super(root->sb);
3484 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
3485 * @cgrp: the cgroup in question
3486 * @task: the task in question
3488 * See if @cgrp is a descendant of @task's cgroup in the appropriate
3491 * If we are sending in dummytop, then presumably we are creating
3492 * the top cgroup in the subsystem.
3494 * Called only by the ns (nsproxy) cgroup.
3496 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
3499 struct cgroup *target;
3501 if (cgrp == dummytop)
3504 target = task_cgroup_from_root(task, cgrp->root);
3505 while (cgrp != target && cgrp!= cgrp->top_cgroup)
3506 cgrp = cgrp->parent;
3507 ret = (cgrp == target);
3511 static void check_for_release(struct cgroup *cgrp)
3513 /* All of these checks rely on RCU to keep the cgroup
3514 * structure alive */
3515 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
3516 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
3517 /* Control Group is currently removeable. If it's not
3518 * already queued for a userspace notification, queue
3520 int need_schedule_work = 0;
3521 spin_lock(&release_list_lock);
3522 if (!cgroup_is_removed(cgrp) &&
3523 list_empty(&cgrp->release_list)) {
3524 list_add(&cgrp->release_list, &release_list);
3525 need_schedule_work = 1;
3527 spin_unlock(&release_list_lock);
3528 if (need_schedule_work)
3529 schedule_work(&release_agent_work);
3533 void __css_put(struct cgroup_subsys_state *css)
3535 struct cgroup *cgrp = css->cgroup;
3537 if (atomic_dec_return(&css->refcnt) == 1) {
3538 if (notify_on_release(cgrp)) {
3539 set_bit(CGRP_RELEASABLE, &cgrp->flags);
3540 check_for_release(cgrp);
3542 cgroup_wakeup_rmdir_waiter(cgrp);
3548 * Notify userspace when a cgroup is released, by running the
3549 * configured release agent with the name of the cgroup (path
3550 * relative to the root of cgroup file system) as the argument.
3552 * Most likely, this user command will try to rmdir this cgroup.
3554 * This races with the possibility that some other task will be
3555 * attached to this cgroup before it is removed, or that some other
3556 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
3557 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
3558 * unused, and this cgroup will be reprieved from its death sentence,
3559 * to continue to serve a useful existence. Next time it's released,
3560 * we will get notified again, if it still has 'notify_on_release' set.
3562 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
3563 * means only wait until the task is successfully execve()'d. The
3564 * separate release agent task is forked by call_usermodehelper(),
3565 * then control in this thread returns here, without waiting for the
3566 * release agent task. We don't bother to wait because the caller of
3567 * this routine has no use for the exit status of the release agent
3568 * task, so no sense holding our caller up for that.
3570 static void cgroup_release_agent(struct work_struct *work)
3572 BUG_ON(work != &release_agent_work);
3573 mutex_lock(&cgroup_mutex);
3574 spin_lock(&release_list_lock);
3575 while (!list_empty(&release_list)) {
3576 char *argv[3], *envp[3];
3578 char *pathbuf = NULL, *agentbuf = NULL;
3579 struct cgroup *cgrp = list_entry(release_list.next,
3582 list_del_init(&cgrp->release_list);
3583 spin_unlock(&release_list_lock);
3584 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3587 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
3589 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
3594 argv[i++] = agentbuf;
3595 argv[i++] = pathbuf;
3599 /* minimal command environment */
3600 envp[i++] = "HOME=/";
3601 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3604 /* Drop the lock while we invoke the usermode helper,
3605 * since the exec could involve hitting disk and hence
3606 * be a slow process */
3607 mutex_unlock(&cgroup_mutex);
3608 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3609 mutex_lock(&cgroup_mutex);
3613 spin_lock(&release_list_lock);
3615 spin_unlock(&release_list_lock);
3616 mutex_unlock(&cgroup_mutex);
3619 static int __init cgroup_disable(char *str)
3624 while ((token = strsep(&str, ",")) != NULL) {
3628 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3629 struct cgroup_subsys *ss = subsys[i];
3631 if (!strcmp(token, ss->name)) {
3633 printk(KERN_INFO "Disabling %s control group"
3634 " subsystem\n", ss->name);
3641 __setup("cgroup_disable=", cgroup_disable);
3644 * Functons for CSS ID.
3648 *To get ID other than 0, this should be called when !cgroup_is_removed().
3650 unsigned short css_id(struct cgroup_subsys_state *css)
3652 struct css_id *cssid = rcu_dereference(css->id);
3659 unsigned short css_depth(struct cgroup_subsys_state *css)
3661 struct css_id *cssid = rcu_dereference(css->id);
3664 return cssid->depth;
3668 bool css_is_ancestor(struct cgroup_subsys_state *child,
3669 const struct cgroup_subsys_state *root)
3671 struct css_id *child_id = rcu_dereference(child->id);
3672 struct css_id *root_id = rcu_dereference(root->id);
3674 if (!child_id || !root_id || (child_id->depth < root_id->depth))
3676 return child_id->stack[root_id->depth] == root_id->id;
3679 static void __free_css_id_cb(struct rcu_head *head)
3683 id = container_of(head, struct css_id, rcu_head);
3687 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
3689 struct css_id *id = css->id;
3690 /* When this is called before css_id initialization, id can be NULL */
3694 BUG_ON(!ss->use_id);
3696 rcu_assign_pointer(id->css, NULL);
3697 rcu_assign_pointer(css->id, NULL);
3698 spin_lock(&ss->id_lock);
3699 idr_remove(&ss->idr, id->id);
3700 spin_unlock(&ss->id_lock);
3701 call_rcu(&id->rcu_head, __free_css_id_cb);
3705 * This is called by init or create(). Then, calls to this function are
3706 * always serialized (By cgroup_mutex() at create()).
3709 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
3711 struct css_id *newid;
3712 int myid, error, size;
3714 BUG_ON(!ss->use_id);
3716 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
3717 newid = kzalloc(size, GFP_KERNEL);
3719 return ERR_PTR(-ENOMEM);
3721 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
3725 spin_lock(&ss->id_lock);
3726 /* Don't use 0. allocates an ID of 1-65535 */
3727 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
3728 spin_unlock(&ss->id_lock);
3730 /* Returns error when there are no free spaces for new ID.*/
3735 if (myid > CSS_ID_MAX)
3739 newid->depth = depth;
3743 spin_lock(&ss->id_lock);
3744 idr_remove(&ss->idr, myid);
3745 spin_unlock(&ss->id_lock);
3748 return ERR_PTR(error);
3752 static int __init cgroup_subsys_init_idr(struct cgroup_subsys *ss)
3754 struct css_id *newid;
3755 struct cgroup_subsys_state *rootcss;
3757 spin_lock_init(&ss->id_lock);
3760 rootcss = init_css_set.subsys[ss->subsys_id];
3761 newid = get_new_cssid(ss, 0);
3763 return PTR_ERR(newid);
3765 newid->stack[0] = newid->id;
3766 newid->css = rootcss;
3767 rootcss->id = newid;
3771 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
3772 struct cgroup *child)
3774 int subsys_id, i, depth = 0;
3775 struct cgroup_subsys_state *parent_css, *child_css;
3776 struct css_id *child_id, *parent_id = NULL;
3778 subsys_id = ss->subsys_id;
3779 parent_css = parent->subsys[subsys_id];
3780 child_css = child->subsys[subsys_id];
3781 depth = css_depth(parent_css) + 1;
3782 parent_id = parent_css->id;
3784 child_id = get_new_cssid(ss, depth);
3785 if (IS_ERR(child_id))
3786 return PTR_ERR(child_id);
3788 for (i = 0; i < depth; i++)
3789 child_id->stack[i] = parent_id->stack[i];
3790 child_id->stack[depth] = child_id->id;
3792 * child_id->css pointer will be set after this cgroup is available
3793 * see cgroup_populate_dir()
3795 rcu_assign_pointer(child_css->id, child_id);
3801 * css_lookup - lookup css by id
3802 * @ss: cgroup subsys to be looked into.
3805 * Returns pointer to cgroup_subsys_state if there is valid one with id.
3806 * NULL if not. Should be called under rcu_read_lock()
3808 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
3810 struct css_id *cssid = NULL;
3812 BUG_ON(!ss->use_id);
3813 cssid = idr_find(&ss->idr, id);
3815 if (unlikely(!cssid))
3818 return rcu_dereference(cssid->css);
3822 * css_get_next - lookup next cgroup under specified hierarchy.
3823 * @ss: pointer to subsystem
3824 * @id: current position of iteration.
3825 * @root: pointer to css. search tree under this.
3826 * @foundid: position of found object.
3828 * Search next css under the specified hierarchy of rootid. Calling under
3829 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
3831 struct cgroup_subsys_state *
3832 css_get_next(struct cgroup_subsys *ss, int id,
3833 struct cgroup_subsys_state *root, int *foundid)
3835 struct cgroup_subsys_state *ret = NULL;
3838 int rootid = css_id(root);
3839 int depth = css_depth(root);
3844 BUG_ON(!ss->use_id);
3845 /* fill start point for scan */
3849 * scan next entry from bitmap(tree), tmpid is updated after
3852 spin_lock(&ss->id_lock);
3853 tmp = idr_get_next(&ss->idr, &tmpid);
3854 spin_unlock(&ss->id_lock);
3858 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
3859 ret = rcu_dereference(tmp->css);
3865 /* continue to scan from next id */
3871 #ifdef CONFIG_CGROUP_DEBUG
3872 static struct cgroup_subsys_state *debug_create(struct cgroup_subsys *ss,
3873 struct cgroup *cont)
3875 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
3878 return ERR_PTR(-ENOMEM);
3883 static void debug_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
3885 kfree(cont->subsys[debug_subsys_id]);
3888 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
3890 return atomic_read(&cont->count);
3893 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
3895 return cgroup_task_count(cont);
3898 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
3900 return (u64)(unsigned long)current->cgroups;
3903 static u64 current_css_set_refcount_read(struct cgroup *cont,
3909 count = atomic_read(¤t->cgroups->refcount);
3914 static int current_css_set_cg_links_read(struct cgroup *cont,
3916 struct seq_file *seq)
3918 struct cg_cgroup_link *link;
3921 read_lock(&css_set_lock);
3923 cg = rcu_dereference(current->cgroups);
3924 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
3925 struct cgroup *c = link->cgrp;
3929 name = c->dentry->d_name.name;
3932 seq_printf(seq, "Root %lu group %s\n",
3933 c->root->subsys_bits, name);
3936 read_unlock(&css_set_lock);
3940 #define MAX_TASKS_SHOWN_PER_CSS 25
3941 static int cgroup_css_links_read(struct cgroup *cont,
3943 struct seq_file *seq)
3945 struct cg_cgroup_link *link;
3947 read_lock(&css_set_lock);
3948 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
3949 struct css_set *cg = link->cg;
3950 struct task_struct *task;
3952 seq_printf(seq, "css_set %p\n", cg);
3953 list_for_each_entry(task, &cg->tasks, cg_list) {
3954 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
3955 seq_puts(seq, " ...\n");
3958 seq_printf(seq, " task %d\n",
3959 task_pid_vnr(task));
3963 read_unlock(&css_set_lock);
3967 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
3969 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
3972 static struct cftype debug_files[] = {
3974 .name = "cgroup_refcount",
3975 .read_u64 = cgroup_refcount_read,
3978 .name = "taskcount",
3979 .read_u64 = debug_taskcount_read,
3983 .name = "current_css_set",
3984 .read_u64 = current_css_set_read,
3988 .name = "current_css_set_refcount",
3989 .read_u64 = current_css_set_refcount_read,
3993 .name = "current_css_set_cg_links",
3994 .read_seq_string = current_css_set_cg_links_read,
3998 .name = "cgroup_css_links",
3999 .read_seq_string = cgroup_css_links_read,
4003 .name = "releasable",
4004 .read_u64 = releasable_read,
4008 static int debug_populate(struct cgroup_subsys *ss, struct cgroup *cont)
4010 return cgroup_add_files(cont, ss, debug_files,
4011 ARRAY_SIZE(debug_files));
4014 struct cgroup_subsys debug_subsys = {
4016 .create = debug_create,
4017 .destroy = debug_destroy,
4018 .populate = debug_populate,
4019 .subsys_id = debug_subsys_id,
4021 #endif /* CONFIG_CGROUP_DEBUG */