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/errno.h>
28 #include <linux/kernel.h>
29 #include <linux/list.h>
31 #include <linux/mutex.h>
32 #include <linux/mount.h>
33 #include <linux/pagemap.h>
34 #include <linux/proc_fs.h>
35 #include <linux/rcupdate.h>
36 #include <linux/sched.h>
37 #include <linux/backing-dev.h>
38 #include <linux/seq_file.h>
39 #include <linux/slab.h>
40 #include <linux/magic.h>
41 #include <linux/spinlock.h>
42 #include <linux/string.h>
43 #include <linux/sort.h>
44 #include <linux/kmod.h>
45 #include <linux/delayacct.h>
46 #include <linux/cgroupstats.h>
47 #include <linux/hash.h>
48 #include <linux/namei.h>
49 #include <linux/smp_lock.h>
50 #include <linux/pid_namespace.h>
52 #include <asm/atomic.h>
54 static DEFINE_MUTEX(cgroup_mutex);
56 /* Generate an array of cgroup subsystem pointers */
57 #define SUBSYS(_x) &_x ## _subsys,
59 static struct cgroup_subsys *subsys[] = {
60 #include <linux/cgroup_subsys.h>
64 * A cgroupfs_root represents the root of a cgroup hierarchy,
65 * and may be associated with a superblock to form an active
68 struct cgroupfs_root {
69 struct super_block *sb;
72 * The bitmask of subsystems intended to be attached to this
75 unsigned long subsys_bits;
77 /* The bitmask of subsystems currently attached to this hierarchy */
78 unsigned long actual_subsys_bits;
80 /* A list running through the attached subsystems */
81 struct list_head subsys_list;
83 /* The root cgroup for this hierarchy */
84 struct cgroup top_cgroup;
86 /* Tracks how many cgroups are currently defined in hierarchy.*/
87 int number_of_cgroups;
89 /* A list running through the active hierarchies */
90 struct list_head root_list;
92 /* Hierarchy-specific flags */
95 /* The path to use for release notifications. */
96 char release_agent_path[PATH_MAX];
100 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
101 * subsystems that are otherwise unattached - it never has more than a
102 * single cgroup, and all tasks are part of that cgroup.
104 static struct cgroupfs_root rootnode;
107 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
108 * cgroup_subsys->use_id != 0.
110 #define CSS_ID_MAX (65535)
113 * The css to which this ID points. This pointer is set to valid value
114 * after cgroup is populated. If cgroup is removed, this will be NULL.
115 * This pointer is expected to be RCU-safe because destroy()
116 * is called after synchronize_rcu(). But for safe use, css_is_removed()
117 * css_tryget() should be used for avoiding race.
119 struct cgroup_subsys_state *css;
125 * Depth in hierarchy which this ID belongs to.
127 unsigned short depth;
129 * ID is freed by RCU. (and lookup routine is RCU safe.)
131 struct rcu_head rcu_head;
133 * Hierarchy of CSS ID belongs to.
135 unsigned short stack[0]; /* Array of Length (depth+1) */
139 /* The list of hierarchy roots */
141 static LIST_HEAD(roots);
142 static int root_count;
144 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
145 #define dummytop (&rootnode.top_cgroup)
147 /* This flag indicates whether tasks in the fork and exit paths should
148 * check for fork/exit handlers to call. This avoids us having to do
149 * extra work in the fork/exit path if none of the subsystems need to
152 static int need_forkexit_callback __read_mostly;
154 /* convenient tests for these bits */
155 inline int cgroup_is_removed(const struct cgroup *cgrp)
157 return test_bit(CGRP_REMOVED, &cgrp->flags);
160 /* bits in struct cgroupfs_root flags field */
162 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
165 static int cgroup_is_releasable(const struct cgroup *cgrp)
168 (1 << CGRP_RELEASABLE) |
169 (1 << CGRP_NOTIFY_ON_RELEASE);
170 return (cgrp->flags & bits) == bits;
173 static int notify_on_release(const struct cgroup *cgrp)
175 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
179 * for_each_subsys() allows you to iterate on each subsystem attached to
180 * an active hierarchy
182 #define for_each_subsys(_root, _ss) \
183 list_for_each_entry(_ss, &_root->subsys_list, sibling)
185 /* for_each_active_root() allows you to iterate across the active hierarchies */
186 #define for_each_active_root(_root) \
187 list_for_each_entry(_root, &roots, root_list)
189 /* the list of cgroups eligible for automatic release. Protected by
190 * release_list_lock */
191 static LIST_HEAD(release_list);
192 static DEFINE_SPINLOCK(release_list_lock);
193 static void cgroup_release_agent(struct work_struct *work);
194 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
195 static void check_for_release(struct cgroup *cgrp);
197 /* Link structure for associating css_set objects with cgroups */
198 struct cg_cgroup_link {
200 * List running through cg_cgroup_links associated with a
201 * cgroup, anchored on cgroup->css_sets
203 struct list_head cgrp_link_list;
205 * List running through cg_cgroup_links pointing at a
206 * single css_set object, anchored on css_set->cg_links
208 struct list_head cg_link_list;
212 /* The default css_set - used by init and its children prior to any
213 * hierarchies being mounted. It contains a pointer to the root state
214 * for each subsystem. Also used to anchor the list of css_sets. Not
215 * reference-counted, to improve performance when child cgroups
216 * haven't been created.
219 static struct css_set init_css_set;
220 static struct cg_cgroup_link init_css_set_link;
222 static int cgroup_subsys_init_idr(struct cgroup_subsys *ss);
224 /* css_set_lock protects the list of css_set objects, and the
225 * chain of tasks off each css_set. Nests outside task->alloc_lock
226 * due to cgroup_iter_start() */
227 static DEFINE_RWLOCK(css_set_lock);
228 static int css_set_count;
230 /* hash table for cgroup groups. This improves the performance to
231 * find an existing css_set */
232 #define CSS_SET_HASH_BITS 7
233 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
234 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
236 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
240 unsigned long tmp = 0UL;
242 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
243 tmp += (unsigned long)css[i];
244 tmp = (tmp >> 16) ^ tmp;
246 index = hash_long(tmp, CSS_SET_HASH_BITS);
248 return &css_set_table[index];
251 /* We don't maintain the lists running through each css_set to its
252 * task until after the first call to cgroup_iter_start(). This
253 * reduces the fork()/exit() overhead for people who have cgroups
254 * compiled into their kernel but not actually in use */
255 static int use_task_css_set_links __read_mostly;
257 /* When we create or destroy a css_set, the operation simply
258 * takes/releases a reference count on all the cgroups referenced
259 * by subsystems in this css_set. This can end up multiple-counting
260 * some cgroups, but that's OK - the ref-count is just a
261 * busy/not-busy indicator; ensuring that we only count each cgroup
262 * once would require taking a global lock to ensure that no
263 * subsystems moved between hierarchies while we were doing so.
265 * Possible TODO: decide at boot time based on the number of
266 * registered subsystems and the number of CPUs or NUMA nodes whether
267 * it's better for performance to ref-count every subsystem, or to
268 * take a global lock and only add one ref count to each hierarchy.
272 * unlink a css_set from the list and free it
274 static void unlink_css_set(struct css_set *cg)
276 struct cg_cgroup_link *link;
277 struct cg_cgroup_link *saved_link;
279 hlist_del(&cg->hlist);
282 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
284 list_del(&link->cg_link_list);
285 list_del(&link->cgrp_link_list);
290 static void __put_css_set(struct css_set *cg, int taskexit)
294 * Ensure that the refcount doesn't hit zero while any readers
295 * can see it. Similar to atomic_dec_and_lock(), but for an
298 if (atomic_add_unless(&cg->refcount, -1, 1))
300 write_lock(&css_set_lock);
301 if (!atomic_dec_and_test(&cg->refcount)) {
302 write_unlock(&css_set_lock);
306 write_unlock(&css_set_lock);
309 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
310 struct cgroup *cgrp = rcu_dereference(cg->subsys[i]->cgroup);
311 if (atomic_dec_and_test(&cgrp->count) &&
312 notify_on_release(cgrp)) {
314 set_bit(CGRP_RELEASABLE, &cgrp->flags);
315 check_for_release(cgrp);
323 * refcounted get/put for css_set objects
325 static inline void get_css_set(struct css_set *cg)
327 atomic_inc(&cg->refcount);
330 static inline void put_css_set(struct css_set *cg)
332 __put_css_set(cg, 0);
335 static inline void put_css_set_taskexit(struct css_set *cg)
337 __put_css_set(cg, 1);
341 * find_existing_css_set() is a helper for
342 * find_css_set(), and checks to see whether an existing
343 * css_set is suitable.
345 * oldcg: the cgroup group that we're using before the cgroup
348 * cgrp: the cgroup that we're moving into
350 * template: location in which to build the desired set of subsystem
351 * state objects for the new cgroup group
353 static struct css_set *find_existing_css_set(
354 struct css_set *oldcg,
356 struct cgroup_subsys_state *template[])
359 struct cgroupfs_root *root = cgrp->root;
360 struct hlist_head *hhead;
361 struct hlist_node *node;
364 /* Built the set of subsystem state objects that we want to
365 * see in the new css_set */
366 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
367 if (root->subsys_bits & (1UL << i)) {
368 /* Subsystem is in this hierarchy. So we want
369 * the subsystem state from the new
371 template[i] = cgrp->subsys[i];
373 /* Subsystem is not in this hierarchy, so we
374 * don't want to change the subsystem state */
375 template[i] = oldcg->subsys[i];
379 hhead = css_set_hash(template);
380 hlist_for_each_entry(cg, node, hhead, hlist) {
381 if (!memcmp(template, cg->subsys, sizeof(cg->subsys))) {
382 /* All subsystems matched */
387 /* No existing cgroup group matched */
391 static void free_cg_links(struct list_head *tmp)
393 struct cg_cgroup_link *link;
394 struct cg_cgroup_link *saved_link;
396 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
397 list_del(&link->cgrp_link_list);
403 * allocate_cg_links() allocates "count" cg_cgroup_link structures
404 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
405 * success or a negative error
407 static int allocate_cg_links(int count, struct list_head *tmp)
409 struct cg_cgroup_link *link;
412 for (i = 0; i < count; i++) {
413 link = kmalloc(sizeof(*link), GFP_KERNEL);
418 list_add(&link->cgrp_link_list, tmp);
424 * link_css_set - a helper function to link a css_set to a cgroup
425 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
426 * @cg: the css_set to be linked
427 * @cgrp: the destination cgroup
429 static void link_css_set(struct list_head *tmp_cg_links,
430 struct css_set *cg, struct cgroup *cgrp)
432 struct cg_cgroup_link *link;
434 BUG_ON(list_empty(tmp_cg_links));
435 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
438 list_move(&link->cgrp_link_list, &cgrp->css_sets);
439 list_add(&link->cg_link_list, &cg->cg_links);
443 * find_css_set() takes an existing cgroup group and a
444 * cgroup object, and returns a css_set object that's
445 * equivalent to the old group, but with the given cgroup
446 * substituted into the appropriate hierarchy. Must be called with
449 static struct css_set *find_css_set(
450 struct css_set *oldcg, struct cgroup *cgrp)
453 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
456 struct list_head tmp_cg_links;
458 struct hlist_head *hhead;
460 /* First see if we already have a cgroup group that matches
462 read_lock(&css_set_lock);
463 res = find_existing_css_set(oldcg, cgrp, template);
466 read_unlock(&css_set_lock);
471 res = kmalloc(sizeof(*res), GFP_KERNEL);
475 /* Allocate all the cg_cgroup_link objects that we'll need */
476 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
481 atomic_set(&res->refcount, 1);
482 INIT_LIST_HEAD(&res->cg_links);
483 INIT_LIST_HEAD(&res->tasks);
484 INIT_HLIST_NODE(&res->hlist);
486 /* Copy the set of subsystem state objects generated in
487 * find_existing_css_set() */
488 memcpy(res->subsys, template, sizeof(res->subsys));
490 write_lock(&css_set_lock);
491 /* Add reference counts and links from the new css_set. */
492 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
493 struct cgroup *cgrp = res->subsys[i]->cgroup;
494 struct cgroup_subsys *ss = subsys[i];
495 atomic_inc(&cgrp->count);
497 * We want to add a link once per cgroup, so we
498 * only do it for the first subsystem in each
501 if (ss->root->subsys_list.next == &ss->sibling)
502 link_css_set(&tmp_cg_links, res, cgrp);
504 if (list_empty(&rootnode.subsys_list))
505 link_css_set(&tmp_cg_links, res, dummytop);
507 BUG_ON(!list_empty(&tmp_cg_links));
511 /* Add this cgroup group to the hash table */
512 hhead = css_set_hash(res->subsys);
513 hlist_add_head(&res->hlist, hhead);
515 write_unlock(&css_set_lock);
521 * There is one global cgroup mutex. We also require taking
522 * task_lock() when dereferencing a task's cgroup subsys pointers.
523 * See "The task_lock() exception", at the end of this comment.
525 * A task must hold cgroup_mutex to modify cgroups.
527 * Any task can increment and decrement the count field without lock.
528 * So in general, code holding cgroup_mutex can't rely on the count
529 * field not changing. However, if the count goes to zero, then only
530 * cgroup_attach_task() can increment it again. Because a count of zero
531 * means that no tasks are currently attached, therefore there is no
532 * way a task attached to that cgroup can fork (the other way to
533 * increment the count). So code holding cgroup_mutex can safely
534 * assume that if the count is zero, it will stay zero. Similarly, if
535 * a task holds cgroup_mutex on a cgroup with zero count, it
536 * knows that the cgroup won't be removed, as cgroup_rmdir()
539 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
540 * (usually) take cgroup_mutex. These are the two most performance
541 * critical pieces of code here. The exception occurs on cgroup_exit(),
542 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
543 * is taken, and if the cgroup count is zero, a usermode call made
544 * to the release agent with the name of the cgroup (path relative to
545 * the root of cgroup file system) as the argument.
547 * A cgroup can only be deleted if both its 'count' of using tasks
548 * is zero, and its list of 'children' cgroups is empty. Since all
549 * tasks in the system use _some_ cgroup, and since there is always at
550 * least one task in the system (init, pid == 1), therefore, top_cgroup
551 * always has either children cgroups and/or using tasks. So we don't
552 * need a special hack to ensure that top_cgroup cannot be deleted.
554 * The task_lock() exception
556 * The need for this exception arises from the action of
557 * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
558 * another. It does so using cgroup_mutex, however there are
559 * several performance critical places that need to reference
560 * task->cgroup without the expense of grabbing a system global
561 * mutex. Therefore except as noted below, when dereferencing or, as
562 * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
563 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
564 * the task_struct routinely used for such matters.
566 * P.S. One more locking exception. RCU is used to guard the
567 * update of a tasks cgroup pointer by cgroup_attach_task()
571 * cgroup_lock - lock out any changes to cgroup structures
574 void cgroup_lock(void)
576 mutex_lock(&cgroup_mutex);
580 * cgroup_unlock - release lock on cgroup changes
582 * Undo the lock taken in a previous cgroup_lock() call.
584 void cgroup_unlock(void)
586 mutex_unlock(&cgroup_mutex);
590 * A couple of forward declarations required, due to cyclic reference loop:
591 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
592 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
596 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
597 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
598 static int cgroup_populate_dir(struct cgroup *cgrp);
599 static struct inode_operations cgroup_dir_inode_operations;
600 static struct file_operations proc_cgroupstats_operations;
602 static struct backing_dev_info cgroup_backing_dev_info = {
603 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
606 static int alloc_css_id(struct cgroup_subsys *ss,
607 struct cgroup *parent, struct cgroup *child);
609 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
611 struct inode *inode = new_inode(sb);
614 inode->i_mode = mode;
615 inode->i_uid = current_fsuid();
616 inode->i_gid = current_fsgid();
617 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
618 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
624 * Call subsys's pre_destroy handler.
625 * This is called before css refcnt check.
627 static int cgroup_call_pre_destroy(struct cgroup *cgrp)
629 struct cgroup_subsys *ss;
632 for_each_subsys(cgrp->root, ss)
633 if (ss->pre_destroy) {
634 ret = ss->pre_destroy(ss, cgrp);
641 static void free_cgroup_rcu(struct rcu_head *obj)
643 struct cgroup *cgrp = container_of(obj, struct cgroup, rcu_head);
648 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
650 /* is dentry a directory ? if so, kfree() associated cgroup */
651 if (S_ISDIR(inode->i_mode)) {
652 struct cgroup *cgrp = dentry->d_fsdata;
653 struct cgroup_subsys *ss;
654 BUG_ON(!(cgroup_is_removed(cgrp)));
655 /* It's possible for external users to be holding css
656 * reference counts on a cgroup; css_put() needs to
657 * be able to access the cgroup after decrementing
658 * the reference count in order to know if it needs to
659 * queue the cgroup to be handled by the release
663 mutex_lock(&cgroup_mutex);
665 * Release the subsystem state objects.
667 for_each_subsys(cgrp->root, ss)
668 ss->destroy(ss, cgrp);
670 cgrp->root->number_of_cgroups--;
671 mutex_unlock(&cgroup_mutex);
674 * Drop the active superblock reference that we took when we
677 deactivate_super(cgrp->root->sb);
679 call_rcu(&cgrp->rcu_head, free_cgroup_rcu);
684 static void remove_dir(struct dentry *d)
686 struct dentry *parent = dget(d->d_parent);
689 simple_rmdir(parent->d_inode, d);
693 static void cgroup_clear_directory(struct dentry *dentry)
695 struct list_head *node;
697 BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
698 spin_lock(&dcache_lock);
699 node = dentry->d_subdirs.next;
700 while (node != &dentry->d_subdirs) {
701 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
704 /* This should never be called on a cgroup
705 * directory with child cgroups */
706 BUG_ON(d->d_inode->i_mode & S_IFDIR);
708 spin_unlock(&dcache_lock);
710 simple_unlink(dentry->d_inode, d);
712 spin_lock(&dcache_lock);
714 node = dentry->d_subdirs.next;
716 spin_unlock(&dcache_lock);
720 * NOTE : the dentry must have been dget()'ed
722 static void cgroup_d_remove_dir(struct dentry *dentry)
724 cgroup_clear_directory(dentry);
726 spin_lock(&dcache_lock);
727 list_del_init(&dentry->d_u.d_child);
728 spin_unlock(&dcache_lock);
733 * A queue for waiters to do rmdir() cgroup. A tasks will sleep when
734 * cgroup->count == 0 && list_empty(&cgroup->children) && subsys has some
735 * reference to css->refcnt. In general, this refcnt is expected to goes down
738 * CGRP_WAIT_ON_RMDIR flag is modified under cgroup's inode->i_mutex;
740 DECLARE_WAIT_QUEUE_HEAD(cgroup_rmdir_waitq);
742 static void cgroup_wakeup_rmdir_waiters(const struct cgroup *cgrp)
744 if (unlikely(test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags)))
745 wake_up_all(&cgroup_rmdir_waitq);
748 static int rebind_subsystems(struct cgroupfs_root *root,
749 unsigned long final_bits)
751 unsigned long added_bits, removed_bits;
752 struct cgroup *cgrp = &root->top_cgroup;
755 removed_bits = root->actual_subsys_bits & ~final_bits;
756 added_bits = final_bits & ~root->actual_subsys_bits;
757 /* Check that any added subsystems are currently free */
758 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
759 unsigned long bit = 1UL << i;
760 struct cgroup_subsys *ss = subsys[i];
761 if (!(bit & added_bits))
763 if (ss->root != &rootnode) {
764 /* Subsystem isn't free */
769 /* Currently we don't handle adding/removing subsystems when
770 * any child cgroups exist. This is theoretically supportable
771 * but involves complex error handling, so it's being left until
773 if (root->number_of_cgroups > 1)
776 /* Process each subsystem */
777 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
778 struct cgroup_subsys *ss = subsys[i];
779 unsigned long bit = 1UL << i;
780 if (bit & added_bits) {
781 /* We're binding this subsystem to this hierarchy */
782 BUG_ON(cgrp->subsys[i]);
783 BUG_ON(!dummytop->subsys[i]);
784 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
785 mutex_lock(&ss->hierarchy_mutex);
786 cgrp->subsys[i] = dummytop->subsys[i];
787 cgrp->subsys[i]->cgroup = cgrp;
788 list_move(&ss->sibling, &root->subsys_list);
792 mutex_unlock(&ss->hierarchy_mutex);
793 } else if (bit & removed_bits) {
794 /* We're removing this subsystem */
795 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
796 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
797 mutex_lock(&ss->hierarchy_mutex);
799 ss->bind(ss, dummytop);
800 dummytop->subsys[i]->cgroup = dummytop;
801 cgrp->subsys[i] = NULL;
802 subsys[i]->root = &rootnode;
803 list_move(&ss->sibling, &rootnode.subsys_list);
804 mutex_unlock(&ss->hierarchy_mutex);
805 } else if (bit & final_bits) {
806 /* Subsystem state should already exist */
807 BUG_ON(!cgrp->subsys[i]);
809 /* Subsystem state shouldn't exist */
810 BUG_ON(cgrp->subsys[i]);
813 root->subsys_bits = root->actual_subsys_bits = final_bits;
819 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
821 struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
822 struct cgroup_subsys *ss;
824 mutex_lock(&cgroup_mutex);
825 for_each_subsys(root, ss)
826 seq_printf(seq, ",%s", ss->name);
827 if (test_bit(ROOT_NOPREFIX, &root->flags))
828 seq_puts(seq, ",noprefix");
829 if (strlen(root->release_agent_path))
830 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
831 mutex_unlock(&cgroup_mutex);
835 struct cgroup_sb_opts {
836 unsigned long subsys_bits;
841 /* Convert a hierarchy specifier into a bitmask of subsystems and
843 static int parse_cgroupfs_options(char *data,
844 struct cgroup_sb_opts *opts)
846 char *token, *o = data ?: "all";
847 unsigned long mask = (unsigned long)-1;
849 #ifdef CONFIG_CPUSETS
850 mask = ~(1UL << cpuset_subsys_id);
853 opts->subsys_bits = 0;
855 opts->release_agent = NULL;
857 while ((token = strsep(&o, ",")) != NULL) {
860 if (!strcmp(token, "all")) {
861 /* Add all non-disabled subsystems */
863 opts->subsys_bits = 0;
864 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
865 struct cgroup_subsys *ss = subsys[i];
867 opts->subsys_bits |= 1ul << i;
869 } else if (!strcmp(token, "noprefix")) {
870 set_bit(ROOT_NOPREFIX, &opts->flags);
871 } else if (!strncmp(token, "release_agent=", 14)) {
872 /* Specifying two release agents is forbidden */
873 if (opts->release_agent)
875 opts->release_agent = kzalloc(PATH_MAX, GFP_KERNEL);
876 if (!opts->release_agent)
878 strncpy(opts->release_agent, token + 14, PATH_MAX - 1);
879 opts->release_agent[PATH_MAX - 1] = 0;
881 struct cgroup_subsys *ss;
883 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
885 if (!strcmp(token, ss->name)) {
887 set_bit(i, &opts->subsys_bits);
891 if (i == CGROUP_SUBSYS_COUNT)
897 * Option noprefix was introduced just for backward compatibility
898 * with the old cpuset, so we allow noprefix only if mounting just
899 * the cpuset subsystem.
901 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
902 (opts->subsys_bits & mask))
905 /* We can't have an empty hierarchy */
906 if (!opts->subsys_bits)
912 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
915 struct cgroupfs_root *root = sb->s_fs_info;
916 struct cgroup *cgrp = &root->top_cgroup;
917 struct cgroup_sb_opts opts;
920 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
921 mutex_lock(&cgroup_mutex);
923 /* See what subsystems are wanted */
924 ret = parse_cgroupfs_options(data, &opts);
928 /* Don't allow flags to change at remount */
929 if (opts.flags != root->flags) {
934 ret = rebind_subsystems(root, opts.subsys_bits);
938 /* (re)populate subsystem files */
939 cgroup_populate_dir(cgrp);
941 if (opts.release_agent)
942 strcpy(root->release_agent_path, opts.release_agent);
944 kfree(opts.release_agent);
945 mutex_unlock(&cgroup_mutex);
946 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
951 static struct super_operations cgroup_ops = {
952 .statfs = simple_statfs,
953 .drop_inode = generic_delete_inode,
954 .show_options = cgroup_show_options,
955 .remount_fs = cgroup_remount,
958 static void init_cgroup_housekeeping(struct cgroup *cgrp)
960 INIT_LIST_HEAD(&cgrp->sibling);
961 INIT_LIST_HEAD(&cgrp->children);
962 INIT_LIST_HEAD(&cgrp->css_sets);
963 INIT_LIST_HEAD(&cgrp->release_list);
964 INIT_LIST_HEAD(&cgrp->pids_list);
965 init_rwsem(&cgrp->pids_mutex);
967 static void init_cgroup_root(struct cgroupfs_root *root)
969 struct cgroup *cgrp = &root->top_cgroup;
970 INIT_LIST_HEAD(&root->subsys_list);
971 INIT_LIST_HEAD(&root->root_list);
972 root->number_of_cgroups = 1;
974 cgrp->top_cgroup = cgrp;
975 init_cgroup_housekeeping(cgrp);
978 static int cgroup_test_super(struct super_block *sb, void *data)
980 struct cgroupfs_root *new = data;
981 struct cgroupfs_root *root = sb->s_fs_info;
983 /* First check subsystems */
984 if (new->subsys_bits != root->subsys_bits)
987 /* Next check flags */
988 if (new->flags != root->flags)
994 static int cgroup_set_super(struct super_block *sb, void *data)
997 struct cgroupfs_root *root = data;
999 ret = set_anon_super(sb, NULL);
1003 sb->s_fs_info = root;
1006 sb->s_blocksize = PAGE_CACHE_SIZE;
1007 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1008 sb->s_magic = CGROUP_SUPER_MAGIC;
1009 sb->s_op = &cgroup_ops;
1014 static int cgroup_get_rootdir(struct super_block *sb)
1016 struct inode *inode =
1017 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1018 struct dentry *dentry;
1023 inode->i_fop = &simple_dir_operations;
1024 inode->i_op = &cgroup_dir_inode_operations;
1025 /* directories start off with i_nlink == 2 (for "." entry) */
1027 dentry = d_alloc_root(inode);
1032 sb->s_root = dentry;
1036 static int cgroup_get_sb(struct file_system_type *fs_type,
1037 int flags, const char *unused_dev_name,
1038 void *data, struct vfsmount *mnt)
1040 struct cgroup_sb_opts opts;
1042 struct super_block *sb;
1043 struct cgroupfs_root *root;
1044 struct list_head tmp_cg_links;
1046 /* First find the desired set of subsystems */
1047 ret = parse_cgroupfs_options(data, &opts);
1049 kfree(opts.release_agent);
1053 root = kzalloc(sizeof(*root), GFP_KERNEL);
1055 kfree(opts.release_agent);
1059 init_cgroup_root(root);
1060 root->subsys_bits = opts.subsys_bits;
1061 root->flags = opts.flags;
1062 if (opts.release_agent) {
1063 strcpy(root->release_agent_path, opts.release_agent);
1064 kfree(opts.release_agent);
1067 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, root);
1074 if (sb->s_fs_info != root) {
1075 /* Reusing an existing superblock */
1076 BUG_ON(sb->s_root == NULL);
1080 /* New superblock */
1081 struct cgroup *root_cgrp = &root->top_cgroup;
1082 struct inode *inode;
1085 BUG_ON(sb->s_root != NULL);
1087 ret = cgroup_get_rootdir(sb);
1089 goto drop_new_super;
1090 inode = sb->s_root->d_inode;
1092 mutex_lock(&inode->i_mutex);
1093 mutex_lock(&cgroup_mutex);
1096 * We're accessing css_set_count without locking
1097 * css_set_lock here, but that's OK - it can only be
1098 * increased by someone holding cgroup_lock, and
1099 * that's us. The worst that can happen is that we
1100 * have some link structures left over
1102 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1104 mutex_unlock(&cgroup_mutex);
1105 mutex_unlock(&inode->i_mutex);
1106 goto drop_new_super;
1109 ret = rebind_subsystems(root, root->subsys_bits);
1110 if (ret == -EBUSY) {
1111 mutex_unlock(&cgroup_mutex);
1112 mutex_unlock(&inode->i_mutex);
1116 /* EBUSY should be the only error here */
1119 list_add(&root->root_list, &roots);
1122 sb->s_root->d_fsdata = root_cgrp;
1123 root->top_cgroup.dentry = sb->s_root;
1125 /* Link the top cgroup in this hierarchy into all
1126 * the css_set objects */
1127 write_lock(&css_set_lock);
1128 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1129 struct hlist_head *hhead = &css_set_table[i];
1130 struct hlist_node *node;
1133 hlist_for_each_entry(cg, node, hhead, hlist)
1134 link_css_set(&tmp_cg_links, cg, root_cgrp);
1136 write_unlock(&css_set_lock);
1138 free_cg_links(&tmp_cg_links);
1140 BUG_ON(!list_empty(&root_cgrp->sibling));
1141 BUG_ON(!list_empty(&root_cgrp->children));
1142 BUG_ON(root->number_of_cgroups != 1);
1144 cgroup_populate_dir(root_cgrp);
1145 mutex_unlock(&inode->i_mutex);
1146 mutex_unlock(&cgroup_mutex);
1149 simple_set_mnt(mnt, sb);
1153 free_cg_links(&tmp_cg_links);
1155 deactivate_locked_super(sb);
1159 static void cgroup_kill_sb(struct super_block *sb) {
1160 struct cgroupfs_root *root = sb->s_fs_info;
1161 struct cgroup *cgrp = &root->top_cgroup;
1163 struct cg_cgroup_link *link;
1164 struct cg_cgroup_link *saved_link;
1168 BUG_ON(root->number_of_cgroups != 1);
1169 BUG_ON(!list_empty(&cgrp->children));
1170 BUG_ON(!list_empty(&cgrp->sibling));
1172 mutex_lock(&cgroup_mutex);
1174 /* Rebind all subsystems back to the default hierarchy */
1175 ret = rebind_subsystems(root, 0);
1176 /* Shouldn't be able to fail ... */
1180 * Release all the links from css_sets to this hierarchy's
1183 write_lock(&css_set_lock);
1185 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1187 list_del(&link->cg_link_list);
1188 list_del(&link->cgrp_link_list);
1191 write_unlock(&css_set_lock);
1193 if (!list_empty(&root->root_list)) {
1194 list_del(&root->root_list);
1198 mutex_unlock(&cgroup_mutex);
1200 kill_litter_super(sb);
1204 static struct file_system_type cgroup_fs_type = {
1206 .get_sb = cgroup_get_sb,
1207 .kill_sb = cgroup_kill_sb,
1210 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1212 return dentry->d_fsdata;
1215 static inline struct cftype *__d_cft(struct dentry *dentry)
1217 return dentry->d_fsdata;
1221 * cgroup_path - generate the path of a cgroup
1222 * @cgrp: the cgroup in question
1223 * @buf: the buffer to write the path into
1224 * @buflen: the length of the buffer
1226 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1227 * reference. Writes path of cgroup into buf. Returns 0 on success,
1230 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1233 struct dentry *dentry = rcu_dereference(cgrp->dentry);
1235 if (!dentry || cgrp == dummytop) {
1237 * Inactive subsystems have no dentry for their root
1244 start = buf + buflen;
1248 int len = dentry->d_name.len;
1249 if ((start -= len) < buf)
1250 return -ENAMETOOLONG;
1251 memcpy(start, cgrp->dentry->d_name.name, len);
1252 cgrp = cgrp->parent;
1255 dentry = rcu_dereference(cgrp->dentry);
1259 return -ENAMETOOLONG;
1262 memmove(buf, start, buf + buflen - start);
1267 * Return the first subsystem attached to a cgroup's hierarchy, and
1271 static void get_first_subsys(const struct cgroup *cgrp,
1272 struct cgroup_subsys_state **css, int *subsys_id)
1274 const struct cgroupfs_root *root = cgrp->root;
1275 const struct cgroup_subsys *test_ss;
1276 BUG_ON(list_empty(&root->subsys_list));
1277 test_ss = list_entry(root->subsys_list.next,
1278 struct cgroup_subsys, sibling);
1280 *css = cgrp->subsys[test_ss->subsys_id];
1284 *subsys_id = test_ss->subsys_id;
1288 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1289 * @cgrp: the cgroup the task is attaching to
1290 * @tsk: the task to be attached
1292 * Call holding cgroup_mutex. May take task_lock of
1293 * the task 'tsk' during call.
1295 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1298 struct cgroup_subsys *ss;
1299 struct cgroup *oldcgrp;
1301 struct css_set *newcg;
1302 struct cgroupfs_root *root = cgrp->root;
1305 get_first_subsys(cgrp, NULL, &subsys_id);
1307 /* Nothing to do if the task is already in that cgroup */
1308 oldcgrp = task_cgroup(tsk, subsys_id);
1309 if (cgrp == oldcgrp)
1312 for_each_subsys(root, ss) {
1313 if (ss->can_attach) {
1314 retval = ss->can_attach(ss, cgrp, tsk);
1325 * Locate or allocate a new css_set for this task,
1326 * based on its final set of cgroups
1328 newcg = find_css_set(cg, cgrp);
1334 if (tsk->flags & PF_EXITING) {
1339 rcu_assign_pointer(tsk->cgroups, newcg);
1342 /* Update the css_set linked lists if we're using them */
1343 write_lock(&css_set_lock);
1344 if (!list_empty(&tsk->cg_list)) {
1345 list_del(&tsk->cg_list);
1346 list_add(&tsk->cg_list, &newcg->tasks);
1348 write_unlock(&css_set_lock);
1350 for_each_subsys(root, ss) {
1352 ss->attach(ss, cgrp, oldcgrp, tsk);
1354 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1359 * wake up rmdir() waiter. the rmdir should fail since the cgroup
1360 * is no longer empty.
1362 cgroup_wakeup_rmdir_waiters(cgrp);
1367 * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
1368 * held. May take task_lock of task
1370 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
1372 struct task_struct *tsk;
1373 const struct cred *cred = current_cred(), *tcred;
1378 tsk = find_task_by_vpid(pid);
1379 if (!tsk || tsk->flags & PF_EXITING) {
1384 tcred = __task_cred(tsk);
1386 cred->euid != tcred->uid &&
1387 cred->euid != tcred->suid) {
1391 get_task_struct(tsk);
1395 get_task_struct(tsk);
1398 ret = cgroup_attach_task(cgrp, tsk);
1399 put_task_struct(tsk);
1403 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
1406 if (!cgroup_lock_live_group(cgrp))
1408 ret = attach_task_by_pid(cgrp, pid);
1413 /* The various types of files and directories in a cgroup file system */
1414 enum cgroup_filetype {
1418 FILE_NOTIFY_ON_RELEASE,
1423 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1424 * @cgrp: the cgroup to be checked for liveness
1426 * On success, returns true; the lock should be later released with
1427 * cgroup_unlock(). On failure returns false with no lock held.
1429 bool cgroup_lock_live_group(struct cgroup *cgrp)
1431 mutex_lock(&cgroup_mutex);
1432 if (cgroup_is_removed(cgrp)) {
1433 mutex_unlock(&cgroup_mutex);
1439 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1442 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1443 if (!cgroup_lock_live_group(cgrp))
1445 strcpy(cgrp->root->release_agent_path, buffer);
1450 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1451 struct seq_file *seq)
1453 if (!cgroup_lock_live_group(cgrp))
1455 seq_puts(seq, cgrp->root->release_agent_path);
1456 seq_putc(seq, '\n');
1461 /* A buffer size big enough for numbers or short strings */
1462 #define CGROUP_LOCAL_BUFFER_SIZE 64
1464 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1466 const char __user *userbuf,
1467 size_t nbytes, loff_t *unused_ppos)
1469 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1475 if (nbytes >= sizeof(buffer))
1477 if (copy_from_user(buffer, userbuf, nbytes))
1480 buffer[nbytes] = 0; /* nul-terminate */
1482 if (cft->write_u64) {
1483 u64 val = simple_strtoull(buffer, &end, 0);
1486 retval = cft->write_u64(cgrp, cft, val);
1488 s64 val = simple_strtoll(buffer, &end, 0);
1491 retval = cft->write_s64(cgrp, cft, val);
1498 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1500 const char __user *userbuf,
1501 size_t nbytes, loff_t *unused_ppos)
1503 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1505 size_t max_bytes = cft->max_write_len;
1506 char *buffer = local_buffer;
1509 max_bytes = sizeof(local_buffer) - 1;
1510 if (nbytes >= max_bytes)
1512 /* Allocate a dynamic buffer if we need one */
1513 if (nbytes >= sizeof(local_buffer)) {
1514 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1518 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
1523 buffer[nbytes] = 0; /* nul-terminate */
1525 retval = cft->write_string(cgrp, cft, buffer);
1529 if (buffer != local_buffer)
1534 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1535 size_t nbytes, loff_t *ppos)
1537 struct cftype *cft = __d_cft(file->f_dentry);
1538 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1540 if (cgroup_is_removed(cgrp))
1543 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1544 if (cft->write_u64 || cft->write_s64)
1545 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1546 if (cft->write_string)
1547 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1549 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1550 return ret ? ret : nbytes;
1555 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1557 char __user *buf, size_t nbytes,
1560 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1561 u64 val = cft->read_u64(cgrp, cft);
1562 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1564 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1567 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1569 char __user *buf, size_t nbytes,
1572 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1573 s64 val = cft->read_s64(cgrp, cft);
1574 int len = sprintf(tmp, "%lld\n", (long long) val);
1576 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1579 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1580 size_t nbytes, loff_t *ppos)
1582 struct cftype *cft = __d_cft(file->f_dentry);
1583 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1585 if (cgroup_is_removed(cgrp))
1589 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1591 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1593 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1598 * seqfile ops/methods for returning structured data. Currently just
1599 * supports string->u64 maps, but can be extended in future.
1602 struct cgroup_seqfile_state {
1604 struct cgroup *cgroup;
1607 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1609 struct seq_file *sf = cb->state;
1610 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1613 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1615 struct cgroup_seqfile_state *state = m->private;
1616 struct cftype *cft = state->cft;
1617 if (cft->read_map) {
1618 struct cgroup_map_cb cb = {
1619 .fill = cgroup_map_add,
1622 return cft->read_map(state->cgroup, cft, &cb);
1624 return cft->read_seq_string(state->cgroup, cft, m);
1627 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
1629 struct seq_file *seq = file->private_data;
1630 kfree(seq->private);
1631 return single_release(inode, file);
1634 static struct file_operations cgroup_seqfile_operations = {
1636 .write = cgroup_file_write,
1637 .llseek = seq_lseek,
1638 .release = cgroup_seqfile_release,
1641 static int cgroup_file_open(struct inode *inode, struct file *file)
1646 err = generic_file_open(inode, file);
1649 cft = __d_cft(file->f_dentry);
1651 if (cft->read_map || cft->read_seq_string) {
1652 struct cgroup_seqfile_state *state =
1653 kzalloc(sizeof(*state), GFP_USER);
1657 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
1658 file->f_op = &cgroup_seqfile_operations;
1659 err = single_open(file, cgroup_seqfile_show, state);
1662 } else if (cft->open)
1663 err = cft->open(inode, file);
1670 static int cgroup_file_release(struct inode *inode, struct file *file)
1672 struct cftype *cft = __d_cft(file->f_dentry);
1674 return cft->release(inode, file);
1679 * cgroup_rename - Only allow simple rename of directories in place.
1681 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
1682 struct inode *new_dir, struct dentry *new_dentry)
1684 if (!S_ISDIR(old_dentry->d_inode->i_mode))
1686 if (new_dentry->d_inode)
1688 if (old_dir != new_dir)
1690 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1693 static struct file_operations cgroup_file_operations = {
1694 .read = cgroup_file_read,
1695 .write = cgroup_file_write,
1696 .llseek = generic_file_llseek,
1697 .open = cgroup_file_open,
1698 .release = cgroup_file_release,
1701 static struct inode_operations cgroup_dir_inode_operations = {
1702 .lookup = simple_lookup,
1703 .mkdir = cgroup_mkdir,
1704 .rmdir = cgroup_rmdir,
1705 .rename = cgroup_rename,
1708 static int cgroup_create_file(struct dentry *dentry, mode_t mode,
1709 struct super_block *sb)
1711 static const struct dentry_operations cgroup_dops = {
1712 .d_iput = cgroup_diput,
1715 struct inode *inode;
1719 if (dentry->d_inode)
1722 inode = cgroup_new_inode(mode, sb);
1726 if (S_ISDIR(mode)) {
1727 inode->i_op = &cgroup_dir_inode_operations;
1728 inode->i_fop = &simple_dir_operations;
1730 /* start off with i_nlink == 2 (for "." entry) */
1733 /* start with the directory inode held, so that we can
1734 * populate it without racing with another mkdir */
1735 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
1736 } else if (S_ISREG(mode)) {
1738 inode->i_fop = &cgroup_file_operations;
1740 dentry->d_op = &cgroup_dops;
1741 d_instantiate(dentry, inode);
1742 dget(dentry); /* Extra count - pin the dentry in core */
1747 * cgroup_create_dir - create a directory for an object.
1748 * @cgrp: the cgroup we create the directory for. It must have a valid
1749 * ->parent field. And we are going to fill its ->dentry field.
1750 * @dentry: dentry of the new cgroup
1751 * @mode: mode to set on new directory.
1753 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
1756 struct dentry *parent;
1759 parent = cgrp->parent->dentry;
1760 error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
1762 dentry->d_fsdata = cgrp;
1763 inc_nlink(parent->d_inode);
1764 rcu_assign_pointer(cgrp->dentry, dentry);
1773 * cgroup_file_mode - deduce file mode of a control file
1774 * @cft: the control file in question
1776 * returns cft->mode if ->mode is not 0
1777 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1778 * returns S_IRUGO if it has only a read handler
1779 * returns S_IWUSR if it has only a write hander
1781 static mode_t cgroup_file_mode(const struct cftype *cft)
1788 if (cft->read || cft->read_u64 || cft->read_s64 ||
1789 cft->read_map || cft->read_seq_string)
1792 if (cft->write || cft->write_u64 || cft->write_s64 ||
1793 cft->write_string || cft->trigger)
1799 int cgroup_add_file(struct cgroup *cgrp,
1800 struct cgroup_subsys *subsys,
1801 const struct cftype *cft)
1803 struct dentry *dir = cgrp->dentry;
1804 struct dentry *dentry;
1808 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
1809 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
1810 strcpy(name, subsys->name);
1813 strcat(name, cft->name);
1814 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
1815 dentry = lookup_one_len(name, dir, strlen(name));
1816 if (!IS_ERR(dentry)) {
1817 mode = cgroup_file_mode(cft);
1818 error = cgroup_create_file(dentry, mode | S_IFREG,
1821 dentry->d_fsdata = (void *)cft;
1824 error = PTR_ERR(dentry);
1828 int cgroup_add_files(struct cgroup *cgrp,
1829 struct cgroup_subsys *subsys,
1830 const struct cftype cft[],
1834 for (i = 0; i < count; i++) {
1835 err = cgroup_add_file(cgrp, subsys, &cft[i]);
1843 * cgroup_task_count - count the number of tasks in a cgroup.
1844 * @cgrp: the cgroup in question
1846 * Return the number of tasks in the cgroup.
1848 int cgroup_task_count(const struct cgroup *cgrp)
1851 struct cg_cgroup_link *link;
1853 read_lock(&css_set_lock);
1854 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
1855 count += atomic_read(&link->cg->refcount);
1857 read_unlock(&css_set_lock);
1862 * Advance a list_head iterator. The iterator should be positioned at
1863 * the start of a css_set
1865 static void cgroup_advance_iter(struct cgroup *cgrp,
1866 struct cgroup_iter *it)
1868 struct list_head *l = it->cg_link;
1869 struct cg_cgroup_link *link;
1872 /* Advance to the next non-empty css_set */
1875 if (l == &cgrp->css_sets) {
1879 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
1881 } while (list_empty(&cg->tasks));
1883 it->task = cg->tasks.next;
1887 * To reduce the fork() overhead for systems that are not actually
1888 * using their cgroups capability, we don't maintain the lists running
1889 * through each css_set to its tasks until we see the list actually
1890 * used - in other words after the first call to cgroup_iter_start().
1892 * The tasklist_lock is not held here, as do_each_thread() and
1893 * while_each_thread() are protected by RCU.
1895 static void cgroup_enable_task_cg_lists(void)
1897 struct task_struct *p, *g;
1898 write_lock(&css_set_lock);
1899 use_task_css_set_links = 1;
1900 do_each_thread(g, p) {
1903 * We should check if the process is exiting, otherwise
1904 * it will race with cgroup_exit() in that the list
1905 * entry won't be deleted though the process has exited.
1907 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
1908 list_add(&p->cg_list, &p->cgroups->tasks);
1910 } while_each_thread(g, p);
1911 write_unlock(&css_set_lock);
1914 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
1917 * The first time anyone tries to iterate across a cgroup,
1918 * we need to enable the list linking each css_set to its
1919 * tasks, and fix up all existing tasks.
1921 if (!use_task_css_set_links)
1922 cgroup_enable_task_cg_lists();
1924 read_lock(&css_set_lock);
1925 it->cg_link = &cgrp->css_sets;
1926 cgroup_advance_iter(cgrp, it);
1929 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
1930 struct cgroup_iter *it)
1932 struct task_struct *res;
1933 struct list_head *l = it->task;
1934 struct cg_cgroup_link *link;
1936 /* If the iterator cg is NULL, we have no tasks */
1939 res = list_entry(l, struct task_struct, cg_list);
1940 /* Advance iterator to find next entry */
1942 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
1943 if (l == &link->cg->tasks) {
1944 /* We reached the end of this task list - move on to
1945 * the next cg_cgroup_link */
1946 cgroup_advance_iter(cgrp, it);
1953 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
1955 read_unlock(&css_set_lock);
1958 static inline int started_after_time(struct task_struct *t1,
1959 struct timespec *time,
1960 struct task_struct *t2)
1962 int start_diff = timespec_compare(&t1->start_time, time);
1963 if (start_diff > 0) {
1965 } else if (start_diff < 0) {
1969 * Arbitrarily, if two processes started at the same
1970 * time, we'll say that the lower pointer value
1971 * started first. Note that t2 may have exited by now
1972 * so this may not be a valid pointer any longer, but
1973 * that's fine - it still serves to distinguish
1974 * between two tasks started (effectively) simultaneously.
1981 * This function is a callback from heap_insert() and is used to order
1983 * In this case we order the heap in descending task start time.
1985 static inline int started_after(void *p1, void *p2)
1987 struct task_struct *t1 = p1;
1988 struct task_struct *t2 = p2;
1989 return started_after_time(t1, &t2->start_time, t2);
1993 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
1994 * @scan: struct cgroup_scanner containing arguments for the scan
1996 * Arguments include pointers to callback functions test_task() and
1998 * Iterate through all the tasks in a cgroup, calling test_task() for each,
1999 * and if it returns true, call process_task() for it also.
2000 * The test_task pointer may be NULL, meaning always true (select all tasks).
2001 * Effectively duplicates cgroup_iter_{start,next,end}()
2002 * but does not lock css_set_lock for the call to process_task().
2003 * The struct cgroup_scanner may be embedded in any structure of the caller's
2005 * It is guaranteed that process_task() will act on every task that
2006 * is a member of the cgroup for the duration of this call. This
2007 * function may or may not call process_task() for tasks that exit
2008 * or move to a different cgroup during the call, or are forked or
2009 * move into the cgroup during the call.
2011 * Note that test_task() may be called with locks held, and may in some
2012 * situations be called multiple times for the same task, so it should
2014 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
2015 * pre-allocated and will be used for heap operations (and its "gt" member will
2016 * be overwritten), else a temporary heap will be used (allocation of which
2017 * may cause this function to fail).
2019 int cgroup_scan_tasks(struct cgroup_scanner *scan)
2022 struct cgroup_iter it;
2023 struct task_struct *p, *dropped;
2024 /* Never dereference latest_task, since it's not refcounted */
2025 struct task_struct *latest_task = NULL;
2026 struct ptr_heap tmp_heap;
2027 struct ptr_heap *heap;
2028 struct timespec latest_time = { 0, 0 };
2031 /* The caller supplied our heap and pre-allocated its memory */
2033 heap->gt = &started_after;
2035 /* We need to allocate our own heap memory */
2037 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2039 /* cannot allocate the heap */
2045 * Scan tasks in the cgroup, using the scanner's "test_task" callback
2046 * to determine which are of interest, and using the scanner's
2047 * "process_task" callback to process any of them that need an update.
2048 * Since we don't want to hold any locks during the task updates,
2049 * gather tasks to be processed in a heap structure.
2050 * The heap is sorted by descending task start time.
2051 * If the statically-sized heap fills up, we overflow tasks that
2052 * started later, and in future iterations only consider tasks that
2053 * started after the latest task in the previous pass. This
2054 * guarantees forward progress and that we don't miss any tasks.
2057 cgroup_iter_start(scan->cg, &it);
2058 while ((p = cgroup_iter_next(scan->cg, &it))) {
2060 * Only affect tasks that qualify per the caller's callback,
2061 * if he provided one
2063 if (scan->test_task && !scan->test_task(p, scan))
2066 * Only process tasks that started after the last task
2069 if (!started_after_time(p, &latest_time, latest_task))
2071 dropped = heap_insert(heap, p);
2072 if (dropped == NULL) {
2074 * The new task was inserted; the heap wasn't
2078 } else if (dropped != p) {
2080 * The new task was inserted, and pushed out a
2084 put_task_struct(dropped);
2087 * Else the new task was newer than anything already in
2088 * the heap and wasn't inserted
2091 cgroup_iter_end(scan->cg, &it);
2094 for (i = 0; i < heap->size; i++) {
2095 struct task_struct *q = heap->ptrs[i];
2097 latest_time = q->start_time;
2100 /* Process the task per the caller's callback */
2101 scan->process_task(q, scan);
2105 * If we had to process any tasks at all, scan again
2106 * in case some of them were in the middle of forking
2107 * children that didn't get processed.
2108 * Not the most efficient way to do it, but it avoids
2109 * having to take callback_mutex in the fork path
2113 if (heap == &tmp_heap)
2114 heap_free(&tmp_heap);
2119 * Stuff for reading the 'tasks' file.
2121 * Reading this file can return large amounts of data if a cgroup has
2122 * *lots* of attached tasks. So it may need several calls to read(),
2123 * but we cannot guarantee that the information we produce is correct
2124 * unless we produce it entirely atomically.
2129 * Load into 'pidarray' up to 'npids' of the tasks using cgroup
2130 * 'cgrp'. Return actual number of pids loaded. No need to
2131 * task_lock(p) when reading out p->cgroup, since we're in an RCU
2132 * read section, so the css_set can't go away, and is
2133 * immutable after creation.
2135 static int pid_array_load(pid_t *pidarray, int npids, struct cgroup *cgrp)
2138 struct cgroup_iter it;
2139 struct task_struct *tsk;
2140 cgroup_iter_start(cgrp, &it);
2141 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2142 if (unlikely(n == npids))
2144 pid = task_pid_vnr(tsk);
2146 pidarray[n++] = pid;
2148 cgroup_iter_end(cgrp, &it);
2153 * cgroupstats_build - build and fill cgroupstats
2154 * @stats: cgroupstats to fill information into
2155 * @dentry: A dentry entry belonging to the cgroup for which stats have
2158 * Build and fill cgroupstats so that taskstats can export it to user
2161 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2164 struct cgroup *cgrp;
2165 struct cgroup_iter it;
2166 struct task_struct *tsk;
2169 * Validate dentry by checking the superblock operations,
2170 * and make sure it's a directory.
2172 if (dentry->d_sb->s_op != &cgroup_ops ||
2173 !S_ISDIR(dentry->d_inode->i_mode))
2177 cgrp = dentry->d_fsdata;
2179 cgroup_iter_start(cgrp, &it);
2180 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2181 switch (tsk->state) {
2183 stats->nr_running++;
2185 case TASK_INTERRUPTIBLE:
2186 stats->nr_sleeping++;
2188 case TASK_UNINTERRUPTIBLE:
2189 stats->nr_uninterruptible++;
2192 stats->nr_stopped++;
2195 if (delayacct_is_task_waiting_on_io(tsk))
2196 stats->nr_io_wait++;
2200 cgroup_iter_end(cgrp, &it);
2207 * Cache pids for all threads in the same pid namespace that are
2208 * opening the same "tasks" file.
2210 struct cgroup_pids {
2211 /* The node in cgrp->pids_list */
2212 struct list_head list;
2213 /* The cgroup those pids belong to */
2214 struct cgroup *cgrp;
2215 /* The namepsace those pids belong to */
2216 struct pid_namespace *ns;
2217 /* Array of process ids in the cgroup */
2219 /* How many files are using the this tasks_pids array */
2221 /* Length of the current tasks_pids array */
2225 static int cmppid(const void *a, const void *b)
2227 return *(pid_t *)a - *(pid_t *)b;
2231 * seq_file methods for the "tasks" file. The seq_file position is the
2232 * next pid to display; the seq_file iterator is a pointer to the pid
2233 * in the cgroup->tasks_pids array.
2236 static void *cgroup_tasks_start(struct seq_file *s, loff_t *pos)
2239 * Initially we receive a position value that corresponds to
2240 * one more than the last pid shown (or 0 on the first call or
2241 * after a seek to the start). Use a binary-search to find the
2242 * next pid to display, if any
2244 struct cgroup_pids *cp = s->private;
2245 struct cgroup *cgrp = cp->cgrp;
2246 int index = 0, pid = *pos;
2249 down_read(&cgrp->pids_mutex);
2251 int end = cp->length;
2253 while (index < end) {
2254 int mid = (index + end) / 2;
2255 if (cp->tasks_pids[mid] == pid) {
2258 } else if (cp->tasks_pids[mid] <= pid)
2264 /* If we're off the end of the array, we're done */
2265 if (index >= cp->length)
2267 /* Update the abstract position to be the actual pid that we found */
2268 iter = cp->tasks_pids + index;
2273 static void cgroup_tasks_stop(struct seq_file *s, void *v)
2275 struct cgroup_pids *cp = s->private;
2276 struct cgroup *cgrp = cp->cgrp;
2277 up_read(&cgrp->pids_mutex);
2280 static void *cgroup_tasks_next(struct seq_file *s, void *v, loff_t *pos)
2282 struct cgroup_pids *cp = s->private;
2284 int *end = cp->tasks_pids + cp->length;
2287 * Advance to the next pid in the array. If this goes off the
2299 static int cgroup_tasks_show(struct seq_file *s, void *v)
2301 return seq_printf(s, "%d\n", *(int *)v);
2304 static struct seq_operations cgroup_tasks_seq_operations = {
2305 .start = cgroup_tasks_start,
2306 .stop = cgroup_tasks_stop,
2307 .next = cgroup_tasks_next,
2308 .show = cgroup_tasks_show,
2311 static void release_cgroup_pid_array(struct cgroup_pids *cp)
2313 struct cgroup *cgrp = cp->cgrp;
2315 down_write(&cgrp->pids_mutex);
2316 BUG_ON(!cp->use_count);
2317 if (!--cp->use_count) {
2318 list_del(&cp->list);
2320 kfree(cp->tasks_pids);
2323 up_write(&cgrp->pids_mutex);
2326 static int cgroup_tasks_release(struct inode *inode, struct file *file)
2328 struct seq_file *seq;
2329 struct cgroup_pids *cp;
2331 if (!(file->f_mode & FMODE_READ))
2334 seq = file->private_data;
2337 release_cgroup_pid_array(cp);
2338 return seq_release(inode, file);
2341 static struct file_operations cgroup_tasks_operations = {
2343 .llseek = seq_lseek,
2344 .write = cgroup_file_write,
2345 .release = cgroup_tasks_release,
2349 * Handle an open on 'tasks' file. Prepare an array containing the
2350 * process id's of tasks currently attached to the cgroup being opened.
2353 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2355 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2356 struct pid_namespace *ns = current->nsproxy->pid_ns;
2357 struct cgroup_pids *cp;
2362 /* Nothing to do for write-only files */
2363 if (!(file->f_mode & FMODE_READ))
2367 * If cgroup gets more users after we read count, we won't have
2368 * enough space - tough. This race is indistinguishable to the
2369 * caller from the case that the additional cgroup users didn't
2370 * show up until sometime later on.
2372 npids = cgroup_task_count(cgrp);
2373 pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
2376 npids = pid_array_load(pidarray, npids, cgrp);
2377 sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
2380 * Store the array in the cgroup, freeing the old
2381 * array if necessary
2383 down_write(&cgrp->pids_mutex);
2385 list_for_each_entry(cp, &cgrp->pids_list, list) {
2390 cp = kzalloc(sizeof(*cp), GFP_KERNEL);
2392 up_write(&cgrp->pids_mutex);
2399 list_add(&cp->list, &cgrp->pids_list);
2401 kfree(cp->tasks_pids);
2402 cp->tasks_pids = pidarray;
2405 up_write(&cgrp->pids_mutex);
2407 file->f_op = &cgroup_tasks_operations;
2409 retval = seq_open(file, &cgroup_tasks_seq_operations);
2411 release_cgroup_pid_array(cp);
2414 ((struct seq_file *)file->private_data)->private = cp;
2418 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2421 return notify_on_release(cgrp);
2424 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2428 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2430 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2432 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2437 * for the common functions, 'private' gives the type of file
2439 static struct cftype files[] = {
2442 .open = cgroup_tasks_open,
2443 .write_u64 = cgroup_tasks_write,
2444 .release = cgroup_tasks_release,
2445 .private = FILE_TASKLIST,
2446 .mode = S_IRUGO | S_IWUSR,
2450 .name = "notify_on_release",
2451 .read_u64 = cgroup_read_notify_on_release,
2452 .write_u64 = cgroup_write_notify_on_release,
2453 .private = FILE_NOTIFY_ON_RELEASE,
2457 static struct cftype cft_release_agent = {
2458 .name = "release_agent",
2459 .read_seq_string = cgroup_release_agent_show,
2460 .write_string = cgroup_release_agent_write,
2461 .max_write_len = PATH_MAX,
2462 .private = FILE_RELEASE_AGENT,
2465 static int cgroup_populate_dir(struct cgroup *cgrp)
2468 struct cgroup_subsys *ss;
2470 /* First clear out any existing files */
2471 cgroup_clear_directory(cgrp->dentry);
2473 err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2477 if (cgrp == cgrp->top_cgroup) {
2478 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2482 for_each_subsys(cgrp->root, ss) {
2483 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2486 /* This cgroup is ready now */
2487 for_each_subsys(cgrp->root, ss) {
2488 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2490 * Update id->css pointer and make this css visible from
2491 * CSS ID functions. This pointer will be dereferened
2492 * from RCU-read-side without locks.
2495 rcu_assign_pointer(css->id->css, css);
2501 static void init_cgroup_css(struct cgroup_subsys_state *css,
2502 struct cgroup_subsys *ss,
2503 struct cgroup *cgrp)
2506 atomic_set(&css->refcnt, 1);
2509 if (cgrp == dummytop)
2510 set_bit(CSS_ROOT, &css->flags);
2511 BUG_ON(cgrp->subsys[ss->subsys_id]);
2512 cgrp->subsys[ss->subsys_id] = css;
2515 static void cgroup_lock_hierarchy(struct cgroupfs_root *root)
2517 /* We need to take each hierarchy_mutex in a consistent order */
2520 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2521 struct cgroup_subsys *ss = subsys[i];
2522 if (ss->root == root)
2523 mutex_lock(&ss->hierarchy_mutex);
2527 static void cgroup_unlock_hierarchy(struct cgroupfs_root *root)
2531 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2532 struct cgroup_subsys *ss = subsys[i];
2533 if (ss->root == root)
2534 mutex_unlock(&ss->hierarchy_mutex);
2539 * cgroup_create - create a cgroup
2540 * @parent: cgroup that will be parent of the new cgroup
2541 * @dentry: dentry of the new cgroup
2542 * @mode: mode to set on new inode
2544 * Must be called with the mutex on the parent inode held
2546 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
2549 struct cgroup *cgrp;
2550 struct cgroupfs_root *root = parent->root;
2552 struct cgroup_subsys *ss;
2553 struct super_block *sb = root->sb;
2555 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
2559 /* Grab a reference on the superblock so the hierarchy doesn't
2560 * get deleted on unmount if there are child cgroups. This
2561 * can be done outside cgroup_mutex, since the sb can't
2562 * disappear while someone has an open control file on the
2564 atomic_inc(&sb->s_active);
2566 mutex_lock(&cgroup_mutex);
2568 init_cgroup_housekeeping(cgrp);
2570 cgrp->parent = parent;
2571 cgrp->root = parent->root;
2572 cgrp->top_cgroup = parent->top_cgroup;
2574 if (notify_on_release(parent))
2575 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2577 for_each_subsys(root, ss) {
2578 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
2583 init_cgroup_css(css, ss, cgrp);
2585 if (alloc_css_id(ss, parent, cgrp))
2587 /* At error, ->destroy() callback has to free assigned ID. */
2590 cgroup_lock_hierarchy(root);
2591 list_add(&cgrp->sibling, &cgrp->parent->children);
2592 cgroup_unlock_hierarchy(root);
2593 root->number_of_cgroups++;
2595 err = cgroup_create_dir(cgrp, dentry, mode);
2599 /* The cgroup directory was pre-locked for us */
2600 BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
2602 err = cgroup_populate_dir(cgrp);
2603 /* If err < 0, we have a half-filled directory - oh well ;) */
2605 mutex_unlock(&cgroup_mutex);
2606 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
2612 cgroup_lock_hierarchy(root);
2613 list_del(&cgrp->sibling);
2614 cgroup_unlock_hierarchy(root);
2615 root->number_of_cgroups--;
2619 for_each_subsys(root, ss) {
2620 if (cgrp->subsys[ss->subsys_id])
2621 ss->destroy(ss, cgrp);
2624 mutex_unlock(&cgroup_mutex);
2626 /* Release the reference count that we took on the superblock */
2627 deactivate_super(sb);
2633 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2635 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
2637 /* the vfs holds inode->i_mutex already */
2638 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
2641 static int cgroup_has_css_refs(struct cgroup *cgrp)
2643 /* Check the reference count on each subsystem. Since we
2644 * already established that there are no tasks in the
2645 * cgroup, if the css refcount is also 1, then there should
2646 * be no outstanding references, so the subsystem is safe to
2647 * destroy. We scan across all subsystems rather than using
2648 * the per-hierarchy linked list of mounted subsystems since
2649 * we can be called via check_for_release() with no
2650 * synchronization other than RCU, and the subsystem linked
2651 * list isn't RCU-safe */
2653 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2654 struct cgroup_subsys *ss = subsys[i];
2655 struct cgroup_subsys_state *css;
2656 /* Skip subsystems not in this hierarchy */
2657 if (ss->root != cgrp->root)
2659 css = cgrp->subsys[ss->subsys_id];
2660 /* When called from check_for_release() it's possible
2661 * that by this point the cgroup has been removed
2662 * and the css deleted. But a false-positive doesn't
2663 * matter, since it can only happen if the cgroup
2664 * has been deleted and hence no longer needs the
2665 * release agent to be called anyway. */
2666 if (css && (atomic_read(&css->refcnt) > 1))
2673 * Atomically mark all (or else none) of the cgroup's CSS objects as
2674 * CSS_REMOVED. Return true on success, or false if the cgroup has
2675 * busy subsystems. Call with cgroup_mutex held
2678 static int cgroup_clear_css_refs(struct cgroup *cgrp)
2680 struct cgroup_subsys *ss;
2681 unsigned long flags;
2682 bool failed = false;
2683 local_irq_save(flags);
2684 for_each_subsys(cgrp->root, ss) {
2685 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2688 /* We can only remove a CSS with a refcnt==1 */
2689 refcnt = atomic_read(&css->refcnt);
2696 * Drop the refcnt to 0 while we check other
2697 * subsystems. This will cause any racing
2698 * css_tryget() to spin until we set the
2699 * CSS_REMOVED bits or abort
2701 if (atomic_cmpxchg(&css->refcnt, refcnt, 0) == refcnt)
2707 for_each_subsys(cgrp->root, ss) {
2708 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2711 * Restore old refcnt if we previously managed
2712 * to clear it from 1 to 0
2714 if (!atomic_read(&css->refcnt))
2715 atomic_set(&css->refcnt, 1);
2717 /* Commit the fact that the CSS is removed */
2718 set_bit(CSS_REMOVED, &css->flags);
2721 local_irq_restore(flags);
2725 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
2727 struct cgroup *cgrp = dentry->d_fsdata;
2729 struct cgroup *parent;
2733 /* the vfs holds both inode->i_mutex already */
2735 mutex_lock(&cgroup_mutex);
2736 if (atomic_read(&cgrp->count) != 0) {
2737 mutex_unlock(&cgroup_mutex);
2740 if (!list_empty(&cgrp->children)) {
2741 mutex_unlock(&cgroup_mutex);
2744 mutex_unlock(&cgroup_mutex);
2747 * Call pre_destroy handlers of subsys. Notify subsystems
2748 * that rmdir() request comes.
2750 ret = cgroup_call_pre_destroy(cgrp);
2754 mutex_lock(&cgroup_mutex);
2755 parent = cgrp->parent;
2756 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
2757 mutex_unlock(&cgroup_mutex);
2761 * css_put/get is provided for subsys to grab refcnt to css. In typical
2762 * case, subsystem has no reference after pre_destroy(). But, under
2763 * hierarchy management, some *temporal* refcnt can be hold.
2764 * To avoid returning -EBUSY to a user, waitqueue is used. If subsys
2765 * is really busy, it should return -EBUSY at pre_destroy(). wake_up
2766 * is called when css_put() is called and refcnt goes down to 0.
2768 set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2769 prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
2771 if (!cgroup_clear_css_refs(cgrp)) {
2772 mutex_unlock(&cgroup_mutex);
2774 finish_wait(&cgroup_rmdir_waitq, &wait);
2775 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2776 if (signal_pending(current))
2780 /* NO css_tryget() can success after here. */
2781 finish_wait(&cgroup_rmdir_waitq, &wait);
2782 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2784 spin_lock(&release_list_lock);
2785 set_bit(CGRP_REMOVED, &cgrp->flags);
2786 if (!list_empty(&cgrp->release_list))
2787 list_del(&cgrp->release_list);
2788 spin_unlock(&release_list_lock);
2790 cgroup_lock_hierarchy(cgrp->root);
2791 /* delete this cgroup from parent->children */
2792 list_del(&cgrp->sibling);
2793 cgroup_unlock_hierarchy(cgrp->root);
2795 spin_lock(&cgrp->dentry->d_lock);
2796 d = dget(cgrp->dentry);
2797 spin_unlock(&d->d_lock);
2799 cgroup_d_remove_dir(d);
2802 set_bit(CGRP_RELEASABLE, &parent->flags);
2803 check_for_release(parent);
2805 mutex_unlock(&cgroup_mutex);
2809 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
2811 struct cgroup_subsys_state *css;
2813 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
2815 /* Create the top cgroup state for this subsystem */
2816 list_add(&ss->sibling, &rootnode.subsys_list);
2817 ss->root = &rootnode;
2818 css = ss->create(ss, dummytop);
2819 /* We don't handle early failures gracefully */
2820 BUG_ON(IS_ERR(css));
2821 init_cgroup_css(css, ss, dummytop);
2823 /* Update the init_css_set to contain a subsys
2824 * pointer to this state - since the subsystem is
2825 * newly registered, all tasks and hence the
2826 * init_css_set is in the subsystem's top cgroup. */
2827 init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
2829 need_forkexit_callback |= ss->fork || ss->exit;
2831 /* At system boot, before all subsystems have been
2832 * registered, no tasks have been forked, so we don't
2833 * need to invoke fork callbacks here. */
2834 BUG_ON(!list_empty(&init_task.tasks));
2836 mutex_init(&ss->hierarchy_mutex);
2837 lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
2842 * cgroup_init_early - cgroup initialization at system boot
2844 * Initialize cgroups at system boot, and initialize any
2845 * subsystems that request early init.
2847 int __init cgroup_init_early(void)
2850 atomic_set(&init_css_set.refcount, 1);
2851 INIT_LIST_HEAD(&init_css_set.cg_links);
2852 INIT_LIST_HEAD(&init_css_set.tasks);
2853 INIT_HLIST_NODE(&init_css_set.hlist);
2855 init_cgroup_root(&rootnode);
2857 init_task.cgroups = &init_css_set;
2859 init_css_set_link.cg = &init_css_set;
2860 list_add(&init_css_set_link.cgrp_link_list,
2861 &rootnode.top_cgroup.css_sets);
2862 list_add(&init_css_set_link.cg_link_list,
2863 &init_css_set.cg_links);
2865 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
2866 INIT_HLIST_HEAD(&css_set_table[i]);
2868 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2869 struct cgroup_subsys *ss = subsys[i];
2872 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
2873 BUG_ON(!ss->create);
2874 BUG_ON(!ss->destroy);
2875 if (ss->subsys_id != i) {
2876 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
2877 ss->name, ss->subsys_id);
2882 cgroup_init_subsys(ss);
2888 * cgroup_init - cgroup initialization
2890 * Register cgroup filesystem and /proc file, and initialize
2891 * any subsystems that didn't request early init.
2893 int __init cgroup_init(void)
2897 struct hlist_head *hhead;
2899 err = bdi_init(&cgroup_backing_dev_info);
2903 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2904 struct cgroup_subsys *ss = subsys[i];
2905 if (!ss->early_init)
2906 cgroup_init_subsys(ss);
2908 cgroup_subsys_init_idr(ss);
2911 /* Add init_css_set to the hash table */
2912 hhead = css_set_hash(init_css_set.subsys);
2913 hlist_add_head(&init_css_set.hlist, hhead);
2915 err = register_filesystem(&cgroup_fs_type);
2919 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
2923 bdi_destroy(&cgroup_backing_dev_info);
2929 * proc_cgroup_show()
2930 * - Print task's cgroup paths into seq_file, one line for each hierarchy
2931 * - Used for /proc/<pid>/cgroup.
2932 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
2933 * doesn't really matter if tsk->cgroup changes after we read it,
2934 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
2935 * anyway. No need to check that tsk->cgroup != NULL, thanks to
2936 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
2937 * cgroup to top_cgroup.
2940 /* TODO: Use a proper seq_file iterator */
2941 static int proc_cgroup_show(struct seq_file *m, void *v)
2944 struct task_struct *tsk;
2947 struct cgroupfs_root *root;
2950 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
2956 tsk = get_pid_task(pid, PIDTYPE_PID);
2962 mutex_lock(&cgroup_mutex);
2964 for_each_active_root(root) {
2965 struct cgroup_subsys *ss;
2966 struct cgroup *cgrp;
2970 seq_printf(m, "%lu:", root->subsys_bits);
2971 for_each_subsys(root, ss)
2972 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
2974 get_first_subsys(&root->top_cgroup, NULL, &subsys_id);
2975 cgrp = task_cgroup(tsk, subsys_id);
2976 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
2984 mutex_unlock(&cgroup_mutex);
2985 put_task_struct(tsk);
2992 static int cgroup_open(struct inode *inode, struct file *file)
2994 struct pid *pid = PROC_I(inode)->pid;
2995 return single_open(file, proc_cgroup_show, pid);
2998 struct file_operations proc_cgroup_operations = {
2999 .open = cgroup_open,
3001 .llseek = seq_lseek,
3002 .release = single_release,
3005 /* Display information about each subsystem and each hierarchy */
3006 static int proc_cgroupstats_show(struct seq_file *m, void *v)
3010 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
3011 mutex_lock(&cgroup_mutex);
3012 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3013 struct cgroup_subsys *ss = subsys[i];
3014 seq_printf(m, "%s\t%lu\t%d\t%d\n",
3015 ss->name, ss->root->subsys_bits,
3016 ss->root->number_of_cgroups, !ss->disabled);
3018 mutex_unlock(&cgroup_mutex);
3022 static int cgroupstats_open(struct inode *inode, struct file *file)
3024 return single_open(file, proc_cgroupstats_show, NULL);
3027 static struct file_operations proc_cgroupstats_operations = {
3028 .open = cgroupstats_open,
3030 .llseek = seq_lseek,
3031 .release = single_release,
3035 * cgroup_fork - attach newly forked task to its parents cgroup.
3036 * @child: pointer to task_struct of forking parent process.
3038 * Description: A task inherits its parent's cgroup at fork().
3040 * A pointer to the shared css_set was automatically copied in
3041 * fork.c by dup_task_struct(). However, we ignore that copy, since
3042 * it was not made under the protection of RCU or cgroup_mutex, so
3043 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
3044 * have already changed current->cgroups, allowing the previously
3045 * referenced cgroup group to be removed and freed.
3047 * At the point that cgroup_fork() is called, 'current' is the parent
3048 * task, and the passed argument 'child' points to the child task.
3050 void cgroup_fork(struct task_struct *child)
3053 child->cgroups = current->cgroups;
3054 get_css_set(child->cgroups);
3055 task_unlock(current);
3056 INIT_LIST_HEAD(&child->cg_list);
3060 * cgroup_fork_callbacks - run fork callbacks
3061 * @child: the new task
3063 * Called on a new task very soon before adding it to the
3064 * tasklist. No need to take any locks since no-one can
3065 * be operating on this task.
3067 void cgroup_fork_callbacks(struct task_struct *child)
3069 if (need_forkexit_callback) {
3071 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3072 struct cgroup_subsys *ss = subsys[i];
3074 ss->fork(ss, child);
3080 * cgroup_post_fork - called on a new task after adding it to the task list
3081 * @child: the task in question
3083 * Adds the task to the list running through its css_set if necessary.
3084 * Has to be after the task is visible on the task list in case we race
3085 * with the first call to cgroup_iter_start() - to guarantee that the
3086 * new task ends up on its list.
3088 void cgroup_post_fork(struct task_struct *child)
3090 if (use_task_css_set_links) {
3091 write_lock(&css_set_lock);
3093 if (list_empty(&child->cg_list))
3094 list_add(&child->cg_list, &child->cgroups->tasks);
3096 write_unlock(&css_set_lock);
3100 * cgroup_exit - detach cgroup from exiting task
3101 * @tsk: pointer to task_struct of exiting process
3102 * @run_callback: run exit callbacks?
3104 * Description: Detach cgroup from @tsk and release it.
3106 * Note that cgroups marked notify_on_release force every task in
3107 * them to take the global cgroup_mutex mutex when exiting.
3108 * This could impact scaling on very large systems. Be reluctant to
3109 * use notify_on_release cgroups where very high task exit scaling
3110 * is required on large systems.
3112 * the_top_cgroup_hack:
3114 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
3116 * We call cgroup_exit() while the task is still competent to
3117 * handle notify_on_release(), then leave the task attached to the
3118 * root cgroup in each hierarchy for the remainder of its exit.
3120 * To do this properly, we would increment the reference count on
3121 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
3122 * code we would add a second cgroup function call, to drop that
3123 * reference. This would just create an unnecessary hot spot on
3124 * the top_cgroup reference count, to no avail.
3126 * Normally, holding a reference to a cgroup without bumping its
3127 * count is unsafe. The cgroup could go away, or someone could
3128 * attach us to a different cgroup, decrementing the count on
3129 * the first cgroup that we never incremented. But in this case,
3130 * top_cgroup isn't going away, and either task has PF_EXITING set,
3131 * which wards off any cgroup_attach_task() attempts, or task is a failed
3132 * fork, never visible to cgroup_attach_task.
3134 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
3139 if (run_callbacks && need_forkexit_callback) {
3140 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3141 struct cgroup_subsys *ss = subsys[i];
3148 * Unlink from the css_set task list if necessary.
3149 * Optimistically check cg_list before taking
3152 if (!list_empty(&tsk->cg_list)) {
3153 write_lock(&css_set_lock);
3154 if (!list_empty(&tsk->cg_list))
3155 list_del(&tsk->cg_list);
3156 write_unlock(&css_set_lock);
3159 /* Reassign the task to the init_css_set. */
3162 tsk->cgroups = &init_css_set;
3165 put_css_set_taskexit(cg);
3169 * cgroup_clone - clone the cgroup the given subsystem is attached to
3170 * @tsk: the task to be moved
3171 * @subsys: the given subsystem
3172 * @nodename: the name for the new cgroup
3174 * Duplicate the current cgroup in the hierarchy that the given
3175 * subsystem is attached to, and move this task into the new
3178 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
3181 struct dentry *dentry;
3183 struct cgroup *parent, *child;
3184 struct inode *inode;
3186 struct cgroupfs_root *root;
3187 struct cgroup_subsys *ss;
3189 /* We shouldn't be called by an unregistered subsystem */
3190 BUG_ON(!subsys->active);
3192 /* First figure out what hierarchy and cgroup we're dealing
3193 * with, and pin them so we can drop cgroup_mutex */
3194 mutex_lock(&cgroup_mutex);
3196 root = subsys->root;
3197 if (root == &rootnode) {
3198 mutex_unlock(&cgroup_mutex);
3202 /* Pin the hierarchy */
3203 if (!atomic_inc_not_zero(&root->sb->s_active)) {
3204 /* We race with the final deactivate_super() */
3205 mutex_unlock(&cgroup_mutex);
3209 /* Keep the cgroup alive */
3211 parent = task_cgroup(tsk, subsys->subsys_id);
3216 mutex_unlock(&cgroup_mutex);
3218 /* Now do the VFS work to create a cgroup */
3219 inode = parent->dentry->d_inode;
3221 /* Hold the parent directory mutex across this operation to
3222 * stop anyone else deleting the new cgroup */
3223 mutex_lock(&inode->i_mutex);
3224 dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
3225 if (IS_ERR(dentry)) {
3227 "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
3229 ret = PTR_ERR(dentry);
3233 /* Create the cgroup directory, which also creates the cgroup */
3234 ret = vfs_mkdir(inode, dentry, 0755);
3235 child = __d_cgrp(dentry);
3239 "Failed to create cgroup %s: %d\n", nodename,
3244 /* The cgroup now exists. Retake cgroup_mutex and check
3245 * that we're still in the same state that we thought we
3247 mutex_lock(&cgroup_mutex);
3248 if ((root != subsys->root) ||
3249 (parent != task_cgroup(tsk, subsys->subsys_id))) {
3250 /* Aargh, we raced ... */
3251 mutex_unlock(&inode->i_mutex);
3254 deactivate_super(root->sb);
3255 /* The cgroup is still accessible in the VFS, but
3256 * we're not going to try to rmdir() it at this
3259 "Race in cgroup_clone() - leaking cgroup %s\n",
3264 /* do any required auto-setup */
3265 for_each_subsys(root, ss) {
3267 ss->post_clone(ss, child);
3270 /* All seems fine. Finish by moving the task into the new cgroup */
3271 ret = cgroup_attach_task(child, tsk);
3272 mutex_unlock(&cgroup_mutex);
3275 mutex_unlock(&inode->i_mutex);
3277 mutex_lock(&cgroup_mutex);
3279 mutex_unlock(&cgroup_mutex);
3280 deactivate_super(root->sb);
3285 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
3286 * @cgrp: the cgroup in question
3287 * @task: the task in question
3289 * See if @cgrp is a descendant of @task's cgroup in the appropriate
3292 * If we are sending in dummytop, then presumably we are creating
3293 * the top cgroup in the subsystem.
3295 * Called only by the ns (nsproxy) cgroup.
3297 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
3300 struct cgroup *target;
3303 if (cgrp == dummytop)
3306 get_first_subsys(cgrp, NULL, &subsys_id);
3307 target = task_cgroup(task, subsys_id);
3308 while (cgrp != target && cgrp!= cgrp->top_cgroup)
3309 cgrp = cgrp->parent;
3310 ret = (cgrp == target);
3314 static void check_for_release(struct cgroup *cgrp)
3316 /* All of these checks rely on RCU to keep the cgroup
3317 * structure alive */
3318 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
3319 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
3320 /* Control Group is currently removeable. If it's not
3321 * already queued for a userspace notification, queue
3323 int need_schedule_work = 0;
3324 spin_lock(&release_list_lock);
3325 if (!cgroup_is_removed(cgrp) &&
3326 list_empty(&cgrp->release_list)) {
3327 list_add(&cgrp->release_list, &release_list);
3328 need_schedule_work = 1;
3330 spin_unlock(&release_list_lock);
3331 if (need_schedule_work)
3332 schedule_work(&release_agent_work);
3336 void __css_put(struct cgroup_subsys_state *css)
3338 struct cgroup *cgrp = css->cgroup;
3340 if (atomic_dec_return(&css->refcnt) == 1) {
3341 if (notify_on_release(cgrp)) {
3342 set_bit(CGRP_RELEASABLE, &cgrp->flags);
3343 check_for_release(cgrp);
3345 cgroup_wakeup_rmdir_waiters(cgrp);
3351 * Notify userspace when a cgroup is released, by running the
3352 * configured release agent with the name of the cgroup (path
3353 * relative to the root of cgroup file system) as the argument.
3355 * Most likely, this user command will try to rmdir this cgroup.
3357 * This races with the possibility that some other task will be
3358 * attached to this cgroup before it is removed, or that some other
3359 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
3360 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
3361 * unused, and this cgroup will be reprieved from its death sentence,
3362 * to continue to serve a useful existence. Next time it's released,
3363 * we will get notified again, if it still has 'notify_on_release' set.
3365 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
3366 * means only wait until the task is successfully execve()'d. The
3367 * separate release agent task is forked by call_usermodehelper(),
3368 * then control in this thread returns here, without waiting for the
3369 * release agent task. We don't bother to wait because the caller of
3370 * this routine has no use for the exit status of the release agent
3371 * task, so no sense holding our caller up for that.
3373 static void cgroup_release_agent(struct work_struct *work)
3375 BUG_ON(work != &release_agent_work);
3376 mutex_lock(&cgroup_mutex);
3377 spin_lock(&release_list_lock);
3378 while (!list_empty(&release_list)) {
3379 char *argv[3], *envp[3];
3381 char *pathbuf = NULL, *agentbuf = NULL;
3382 struct cgroup *cgrp = list_entry(release_list.next,
3385 list_del_init(&cgrp->release_list);
3386 spin_unlock(&release_list_lock);
3387 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3390 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
3392 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
3397 argv[i++] = agentbuf;
3398 argv[i++] = pathbuf;
3402 /* minimal command environment */
3403 envp[i++] = "HOME=/";
3404 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3407 /* Drop the lock while we invoke the usermode helper,
3408 * since the exec could involve hitting disk and hence
3409 * be a slow process */
3410 mutex_unlock(&cgroup_mutex);
3411 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3412 mutex_lock(&cgroup_mutex);
3416 spin_lock(&release_list_lock);
3418 spin_unlock(&release_list_lock);
3419 mutex_unlock(&cgroup_mutex);
3422 static int __init cgroup_disable(char *str)
3427 while ((token = strsep(&str, ",")) != NULL) {
3431 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3432 struct cgroup_subsys *ss = subsys[i];
3434 if (!strcmp(token, ss->name)) {
3436 printk(KERN_INFO "Disabling %s control group"
3437 " subsystem\n", ss->name);
3444 __setup("cgroup_disable=", cgroup_disable);
3447 * Functons for CSS ID.
3451 *To get ID other than 0, this should be called when !cgroup_is_removed().
3453 unsigned short css_id(struct cgroup_subsys_state *css)
3455 struct css_id *cssid = rcu_dereference(css->id);
3462 unsigned short css_depth(struct cgroup_subsys_state *css)
3464 struct css_id *cssid = rcu_dereference(css->id);
3467 return cssid->depth;
3471 bool css_is_ancestor(struct cgroup_subsys_state *child,
3472 const struct cgroup_subsys_state *root)
3474 struct css_id *child_id = rcu_dereference(child->id);
3475 struct css_id *root_id = rcu_dereference(root->id);
3477 if (!child_id || !root_id || (child_id->depth < root_id->depth))
3479 return child_id->stack[root_id->depth] == root_id->id;
3482 static void __free_css_id_cb(struct rcu_head *head)
3486 id = container_of(head, struct css_id, rcu_head);
3490 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
3492 struct css_id *id = css->id;
3493 /* When this is called before css_id initialization, id can be NULL */
3497 BUG_ON(!ss->use_id);
3499 rcu_assign_pointer(id->css, NULL);
3500 rcu_assign_pointer(css->id, NULL);
3501 spin_lock(&ss->id_lock);
3502 idr_remove(&ss->idr, id->id);
3503 spin_unlock(&ss->id_lock);
3504 call_rcu(&id->rcu_head, __free_css_id_cb);
3508 * This is called by init or create(). Then, calls to this function are
3509 * always serialized (By cgroup_mutex() at create()).
3512 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
3514 struct css_id *newid;
3515 int myid, error, size;
3517 BUG_ON(!ss->use_id);
3519 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
3520 newid = kzalloc(size, GFP_KERNEL);
3522 return ERR_PTR(-ENOMEM);
3524 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
3528 spin_lock(&ss->id_lock);
3529 /* Don't use 0. allocates an ID of 1-65535 */
3530 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
3531 spin_unlock(&ss->id_lock);
3533 /* Returns error when there are no free spaces for new ID.*/
3538 if (myid > CSS_ID_MAX)
3542 newid->depth = depth;
3546 spin_lock(&ss->id_lock);
3547 idr_remove(&ss->idr, myid);
3548 spin_unlock(&ss->id_lock);
3551 return ERR_PTR(error);
3555 static int __init cgroup_subsys_init_idr(struct cgroup_subsys *ss)
3557 struct css_id *newid;
3558 struct cgroup_subsys_state *rootcss;
3560 spin_lock_init(&ss->id_lock);
3563 rootcss = init_css_set.subsys[ss->subsys_id];
3564 newid = get_new_cssid(ss, 0);
3566 return PTR_ERR(newid);
3568 newid->stack[0] = newid->id;
3569 newid->css = rootcss;
3570 rootcss->id = newid;
3574 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
3575 struct cgroup *child)
3577 int subsys_id, i, depth = 0;
3578 struct cgroup_subsys_state *parent_css, *child_css;
3579 struct css_id *child_id, *parent_id = NULL;
3581 subsys_id = ss->subsys_id;
3582 parent_css = parent->subsys[subsys_id];
3583 child_css = child->subsys[subsys_id];
3584 depth = css_depth(parent_css) + 1;
3585 parent_id = parent_css->id;
3587 child_id = get_new_cssid(ss, depth);
3588 if (IS_ERR(child_id))
3589 return PTR_ERR(child_id);
3591 for (i = 0; i < depth; i++)
3592 child_id->stack[i] = parent_id->stack[i];
3593 child_id->stack[depth] = child_id->id;
3595 * child_id->css pointer will be set after this cgroup is available
3596 * see cgroup_populate_dir()
3598 rcu_assign_pointer(child_css->id, child_id);
3604 * css_lookup - lookup css by id
3605 * @ss: cgroup subsys to be looked into.
3608 * Returns pointer to cgroup_subsys_state if there is valid one with id.
3609 * NULL if not. Should be called under rcu_read_lock()
3611 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
3613 struct css_id *cssid = NULL;
3615 BUG_ON(!ss->use_id);
3616 cssid = idr_find(&ss->idr, id);
3618 if (unlikely(!cssid))
3621 return rcu_dereference(cssid->css);
3625 * css_get_next - lookup next cgroup under specified hierarchy.
3626 * @ss: pointer to subsystem
3627 * @id: current position of iteration.
3628 * @root: pointer to css. search tree under this.
3629 * @foundid: position of found object.
3631 * Search next css under the specified hierarchy of rootid. Calling under
3632 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
3634 struct cgroup_subsys_state *
3635 css_get_next(struct cgroup_subsys *ss, int id,
3636 struct cgroup_subsys_state *root, int *foundid)
3638 struct cgroup_subsys_state *ret = NULL;
3641 int rootid = css_id(root);
3642 int depth = css_depth(root);
3647 BUG_ON(!ss->use_id);
3648 /* fill start point for scan */
3652 * scan next entry from bitmap(tree), tmpid is updated after
3655 spin_lock(&ss->id_lock);
3656 tmp = idr_get_next(&ss->idr, &tmpid);
3657 spin_unlock(&ss->id_lock);
3661 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
3662 ret = rcu_dereference(tmp->css);
3668 /* continue to scan from next id */