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>
49 #include <asm/atomic.h>
51 static DEFINE_MUTEX(cgroup_mutex);
53 /* Generate an array of cgroup subsystem pointers */
54 #define SUBSYS(_x) &_x ## _subsys,
56 static struct cgroup_subsys *subsys[] = {
57 #include <linux/cgroup_subsys.h>
61 * A cgroupfs_root represents the root of a cgroup hierarchy,
62 * and may be associated with a superblock to form an active
65 struct cgroupfs_root {
66 struct super_block *sb;
69 * The bitmask of subsystems intended to be attached to this
72 unsigned long subsys_bits;
74 /* The bitmask of subsystems currently attached to this hierarchy */
75 unsigned long actual_subsys_bits;
77 /* A list running through the attached subsystems */
78 struct list_head subsys_list;
80 /* The root cgroup for this hierarchy */
81 struct cgroup top_cgroup;
83 /* Tracks how many cgroups are currently defined in hierarchy.*/
84 int number_of_cgroups;
86 /* A list running through the mounted hierarchies */
87 struct list_head root_list;
89 /* Hierarchy-specific flags */
92 /* The path to use for release notifications. */
93 char release_agent_path[PATH_MAX];
98 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
99 * subsystems that are otherwise unattached - it never has more than a
100 * single cgroup, and all tasks are part of that cgroup.
102 static struct cgroupfs_root rootnode;
104 /* The list of hierarchy roots */
106 static LIST_HEAD(roots);
107 static int root_count;
109 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
110 #define dummytop (&rootnode.top_cgroup)
112 /* This flag indicates whether tasks in the fork and exit paths should
113 * check for fork/exit handlers to call. This avoids us having to do
114 * extra work in the fork/exit path if none of the subsystems need to
117 static int need_forkexit_callback __read_mostly;
118 static int need_mm_owner_callback __read_mostly;
120 /* convenient tests for these bits */
121 inline int cgroup_is_removed(const struct cgroup *cgrp)
123 return test_bit(CGRP_REMOVED, &cgrp->flags);
126 /* bits in struct cgroupfs_root flags field */
128 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
131 static int cgroup_is_releasable(const struct cgroup *cgrp)
134 (1 << CGRP_RELEASABLE) |
135 (1 << CGRP_NOTIFY_ON_RELEASE);
136 return (cgrp->flags & bits) == bits;
139 static int notify_on_release(const struct cgroup *cgrp)
141 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
145 * for_each_subsys() allows you to iterate on each subsystem attached to
146 * an active hierarchy
148 #define for_each_subsys(_root, _ss) \
149 list_for_each_entry(_ss, &_root->subsys_list, sibling)
151 /* for_each_root() allows you to iterate across the active hierarchies */
152 #define for_each_root(_root) \
153 list_for_each_entry(_root, &roots, root_list)
155 /* the list of cgroups eligible for automatic release. Protected by
156 * release_list_lock */
157 static LIST_HEAD(release_list);
158 static DEFINE_SPINLOCK(release_list_lock);
159 static void cgroup_release_agent(struct work_struct *work);
160 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
161 static void check_for_release(struct cgroup *cgrp);
163 /* Link structure for associating css_set objects with cgroups */
164 struct cg_cgroup_link {
166 * List running through cg_cgroup_links associated with a
167 * cgroup, anchored on cgroup->css_sets
169 struct list_head cgrp_link_list;
171 * List running through cg_cgroup_links pointing at a
172 * single css_set object, anchored on css_set->cg_links
174 struct list_head cg_link_list;
178 /* The default css_set - used by init and its children prior to any
179 * hierarchies being mounted. It contains a pointer to the root state
180 * for each subsystem. Also used to anchor the list of css_sets. Not
181 * reference-counted, to improve performance when child cgroups
182 * haven't been created.
185 static struct css_set init_css_set;
186 static struct cg_cgroup_link init_css_set_link;
188 /* css_set_lock protects the list of css_set objects, and the
189 * chain of tasks off each css_set. Nests outside task->alloc_lock
190 * due to cgroup_iter_start() */
191 static DEFINE_RWLOCK(css_set_lock);
192 static int css_set_count;
194 /* hash table for cgroup groups. This improves the performance to
195 * find an existing css_set */
196 #define CSS_SET_HASH_BITS 7
197 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
198 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
200 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
204 unsigned long tmp = 0UL;
206 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
207 tmp += (unsigned long)css[i];
208 tmp = (tmp >> 16) ^ tmp;
210 index = hash_long(tmp, CSS_SET_HASH_BITS);
212 return &css_set_table[index];
215 /* We don't maintain the lists running through each css_set to its
216 * task until after the first call to cgroup_iter_start(). This
217 * reduces the fork()/exit() overhead for people who have cgroups
218 * compiled into their kernel but not actually in use */
219 static int use_task_css_set_links __read_mostly;
221 /* When we create or destroy a css_set, the operation simply
222 * takes/releases a reference count on all the cgroups referenced
223 * by subsystems in this css_set. This can end up multiple-counting
224 * some cgroups, but that's OK - the ref-count is just a
225 * busy/not-busy indicator; ensuring that we only count each cgroup
226 * once would require taking a global lock to ensure that no
227 * subsystems moved between hierarchies while we were doing so.
229 * Possible TODO: decide at boot time based on the number of
230 * registered subsystems and the number of CPUs or NUMA nodes whether
231 * it's better for performance to ref-count every subsystem, or to
232 * take a global lock and only add one ref count to each hierarchy.
236 * unlink a css_set from the list and free it
238 static void unlink_css_set(struct css_set *cg)
240 struct cg_cgroup_link *link;
241 struct cg_cgroup_link *saved_link;
243 write_lock(&css_set_lock);
244 hlist_del(&cg->hlist);
247 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
249 list_del(&link->cg_link_list);
250 list_del(&link->cgrp_link_list);
254 write_unlock(&css_set_lock);
257 static void __release_css_set(struct kref *k, int taskexit)
260 struct css_set *cg = container_of(k, struct css_set, ref);
265 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
266 struct cgroup *cgrp = cg->subsys[i]->cgroup;
267 if (atomic_dec_and_test(&cgrp->count) &&
268 notify_on_release(cgrp)) {
270 set_bit(CGRP_RELEASABLE, &cgrp->flags);
271 check_for_release(cgrp);
278 static void release_css_set(struct kref *k)
280 __release_css_set(k, 0);
283 static void release_css_set_taskexit(struct kref *k)
285 __release_css_set(k, 1);
289 * refcounted get/put for css_set objects
291 static inline void get_css_set(struct css_set *cg)
296 static inline void put_css_set(struct css_set *cg)
298 kref_put(&cg->ref, release_css_set);
301 static inline void put_css_set_taskexit(struct css_set *cg)
303 kref_put(&cg->ref, release_css_set_taskexit);
307 * find_existing_css_set() is a helper for
308 * find_css_set(), and checks to see whether an existing
309 * css_set is suitable.
311 * oldcg: the cgroup group that we're using before the cgroup
314 * cgrp: the cgroup that we're moving into
316 * template: location in which to build the desired set of subsystem
317 * state objects for the new cgroup group
319 static struct css_set *find_existing_css_set(
320 struct css_set *oldcg,
322 struct cgroup_subsys_state *template[])
325 struct cgroupfs_root *root = cgrp->root;
326 struct hlist_head *hhead;
327 struct hlist_node *node;
330 /* Built the set of subsystem state objects that we want to
331 * see in the new css_set */
332 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
333 if (root->subsys_bits & (1UL << i)) {
334 /* Subsystem is in this hierarchy. So we want
335 * the subsystem state from the new
337 template[i] = cgrp->subsys[i];
339 /* Subsystem is not in this hierarchy, so we
340 * don't want to change the subsystem state */
341 template[i] = oldcg->subsys[i];
345 hhead = css_set_hash(template);
346 hlist_for_each_entry(cg, node, hhead, hlist) {
347 if (!memcmp(template, cg->subsys, sizeof(cg->subsys))) {
348 /* All subsystems matched */
353 /* No existing cgroup group matched */
358 * allocate_cg_links() allocates "count" cg_cgroup_link structures
359 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
360 * success or a negative error
362 static int allocate_cg_links(int count, struct list_head *tmp)
364 struct cg_cgroup_link *link;
365 struct cg_cgroup_link *saved_link;
368 for (i = 0; i < count; i++) {
369 link = kmalloc(sizeof(*link), GFP_KERNEL);
371 list_for_each_entry_safe(link, saved_link, tmp,
373 list_del(&link->cgrp_link_list);
378 list_add(&link->cgrp_link_list, tmp);
383 static void free_cg_links(struct list_head *tmp)
385 struct cg_cgroup_link *link;
386 struct cg_cgroup_link *saved_link;
388 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
389 list_del(&link->cgrp_link_list);
395 * find_css_set() takes an existing cgroup group and a
396 * cgroup object, and returns a css_set object that's
397 * equivalent to the old group, but with the given cgroup
398 * substituted into the appropriate hierarchy. Must be called with
401 static struct css_set *find_css_set(
402 struct css_set *oldcg, struct cgroup *cgrp)
405 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
408 struct list_head tmp_cg_links;
409 struct cg_cgroup_link *link;
411 struct hlist_head *hhead;
413 /* First see if we already have a cgroup group that matches
415 read_lock(&css_set_lock);
416 res = find_existing_css_set(oldcg, cgrp, template);
419 read_unlock(&css_set_lock);
424 res = kmalloc(sizeof(*res), GFP_KERNEL);
428 /* Allocate all the cg_cgroup_link objects that we'll need */
429 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
434 kref_init(&res->ref);
435 INIT_LIST_HEAD(&res->cg_links);
436 INIT_LIST_HEAD(&res->tasks);
437 INIT_HLIST_NODE(&res->hlist);
439 /* Copy the set of subsystem state objects generated in
440 * find_existing_css_set() */
441 memcpy(res->subsys, template, sizeof(res->subsys));
443 write_lock(&css_set_lock);
444 /* Add reference counts and links from the new css_set. */
445 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
446 struct cgroup *cgrp = res->subsys[i]->cgroup;
447 struct cgroup_subsys *ss = subsys[i];
448 atomic_inc(&cgrp->count);
450 * We want to add a link once per cgroup, so we
451 * only do it for the first subsystem in each
454 if (ss->root->subsys_list.next == &ss->sibling) {
455 BUG_ON(list_empty(&tmp_cg_links));
456 link = list_entry(tmp_cg_links.next,
457 struct cg_cgroup_link,
459 list_del(&link->cgrp_link_list);
460 list_add(&link->cgrp_link_list, &cgrp->css_sets);
462 list_add(&link->cg_link_list, &res->cg_links);
465 if (list_empty(&rootnode.subsys_list)) {
466 link = list_entry(tmp_cg_links.next,
467 struct cg_cgroup_link,
469 list_del(&link->cgrp_link_list);
470 list_add(&link->cgrp_link_list, &dummytop->css_sets);
472 list_add(&link->cg_link_list, &res->cg_links);
475 BUG_ON(!list_empty(&tmp_cg_links));
479 /* Add this cgroup group to the hash table */
480 hhead = css_set_hash(res->subsys);
481 hlist_add_head(&res->hlist, hhead);
483 write_unlock(&css_set_lock);
489 * There is one global cgroup mutex. We also require taking
490 * task_lock() when dereferencing a task's cgroup subsys pointers.
491 * See "The task_lock() exception", at the end of this comment.
493 * A task must hold cgroup_mutex to modify cgroups.
495 * Any task can increment and decrement the count field without lock.
496 * So in general, code holding cgroup_mutex can't rely on the count
497 * field not changing. However, if the count goes to zero, then only
498 * cgroup_attach_task() can increment it again. Because a count of zero
499 * means that no tasks are currently attached, therefore there is no
500 * way a task attached to that cgroup can fork (the other way to
501 * increment the count). So code holding cgroup_mutex can safely
502 * assume that if the count is zero, it will stay zero. Similarly, if
503 * a task holds cgroup_mutex on a cgroup with zero count, it
504 * knows that the cgroup won't be removed, as cgroup_rmdir()
507 * The cgroup_common_file_write handler for operations that modify
508 * the cgroup hierarchy holds cgroup_mutex across the entire operation,
509 * single threading all such cgroup modifications across the system.
511 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
512 * (usually) take cgroup_mutex. These are the two most performance
513 * critical pieces of code here. The exception occurs on cgroup_exit(),
514 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
515 * is taken, and if the cgroup count is zero, a usermode call made
516 * to the release agent with the name of the cgroup (path relative to
517 * the root of cgroup file system) as the argument.
519 * A cgroup can only be deleted if both its 'count' of using tasks
520 * is zero, and its list of 'children' cgroups is empty. Since all
521 * tasks in the system use _some_ cgroup, and since there is always at
522 * least one task in the system (init, pid == 1), therefore, top_cgroup
523 * always has either children cgroups and/or using tasks. So we don't
524 * need a special hack to ensure that top_cgroup cannot be deleted.
526 * The task_lock() exception
528 * The need for this exception arises from the action of
529 * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
530 * another. It does so using cgroup_mutex, however there are
531 * several performance critical places that need to reference
532 * task->cgroup without the expense of grabbing a system global
533 * mutex. Therefore except as noted below, when dereferencing or, as
534 * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
535 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
536 * the task_struct routinely used for such matters.
538 * P.S. One more locking exception. RCU is used to guard the
539 * update of a tasks cgroup pointer by cgroup_attach_task()
543 * cgroup_lock - lock out any changes to cgroup structures
546 void cgroup_lock(void)
548 mutex_lock(&cgroup_mutex);
552 * cgroup_unlock - release lock on cgroup changes
554 * Undo the lock taken in a previous cgroup_lock() call.
556 void cgroup_unlock(void)
558 mutex_unlock(&cgroup_mutex);
562 * A couple of forward declarations required, due to cyclic reference loop:
563 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
564 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
568 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
569 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
570 static int cgroup_populate_dir(struct cgroup *cgrp);
571 static struct inode_operations cgroup_dir_inode_operations;
572 static struct file_operations proc_cgroupstats_operations;
574 static struct backing_dev_info cgroup_backing_dev_info = {
575 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
578 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
580 struct inode *inode = new_inode(sb);
583 inode->i_mode = mode;
584 inode->i_uid = current->fsuid;
585 inode->i_gid = current->fsgid;
587 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
588 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
594 * Call subsys's pre_destroy handler.
595 * This is called before css refcnt check.
597 static void cgroup_call_pre_destroy(struct cgroup *cgrp)
599 struct cgroup_subsys *ss;
600 for_each_subsys(cgrp->root, ss)
601 if (ss->pre_destroy && cgrp->subsys[ss->subsys_id])
602 ss->pre_destroy(ss, cgrp);
606 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
608 /* is dentry a directory ? if so, kfree() associated cgroup */
609 if (S_ISDIR(inode->i_mode)) {
610 struct cgroup *cgrp = dentry->d_fsdata;
611 struct cgroup_subsys *ss;
612 BUG_ON(!(cgroup_is_removed(cgrp)));
613 /* It's possible for external users to be holding css
614 * reference counts on a cgroup; css_put() needs to
615 * be able to access the cgroup after decrementing
616 * the reference count in order to know if it needs to
617 * queue the cgroup to be handled by the release
621 mutex_lock(&cgroup_mutex);
623 * Release the subsystem state objects.
625 for_each_subsys(cgrp->root, ss) {
626 if (cgrp->subsys[ss->subsys_id])
627 ss->destroy(ss, cgrp);
630 cgrp->root->number_of_cgroups--;
631 mutex_unlock(&cgroup_mutex);
633 /* Drop the active superblock reference that we took when we
634 * created the cgroup */
635 deactivate_super(cgrp->root->sb);
642 static void remove_dir(struct dentry *d)
644 struct dentry *parent = dget(d->d_parent);
647 simple_rmdir(parent->d_inode, d);
651 static void cgroup_clear_directory(struct dentry *dentry)
653 struct list_head *node;
655 BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
656 spin_lock(&dcache_lock);
657 node = dentry->d_subdirs.next;
658 while (node != &dentry->d_subdirs) {
659 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
662 /* This should never be called on a cgroup
663 * directory with child cgroups */
664 BUG_ON(d->d_inode->i_mode & S_IFDIR);
666 spin_unlock(&dcache_lock);
668 simple_unlink(dentry->d_inode, d);
670 spin_lock(&dcache_lock);
672 node = dentry->d_subdirs.next;
674 spin_unlock(&dcache_lock);
678 * NOTE : the dentry must have been dget()'ed
680 static void cgroup_d_remove_dir(struct dentry *dentry)
682 cgroup_clear_directory(dentry);
684 spin_lock(&dcache_lock);
685 list_del_init(&dentry->d_u.d_child);
686 spin_unlock(&dcache_lock);
690 static int rebind_subsystems(struct cgroupfs_root *root,
691 unsigned long final_bits)
693 unsigned long added_bits, removed_bits;
694 struct cgroup *cgrp = &root->top_cgroup;
697 removed_bits = root->actual_subsys_bits & ~final_bits;
698 added_bits = final_bits & ~root->actual_subsys_bits;
699 /* Check that any added subsystems are currently free */
700 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
701 unsigned long bit = 1UL << i;
702 struct cgroup_subsys *ss = subsys[i];
703 if (!(bit & added_bits))
705 if (ss->root != &rootnode) {
706 /* Subsystem isn't free */
711 /* Currently we don't handle adding/removing subsystems when
712 * any child cgroups exist. This is theoretically supportable
713 * but involves complex error handling, so it's being left until
715 if (!list_empty(&cgrp->children))
718 /* Process each subsystem */
719 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
720 struct cgroup_subsys *ss = subsys[i];
721 unsigned long bit = 1UL << i;
722 if (bit & added_bits) {
723 /* We're binding this subsystem to this hierarchy */
724 BUG_ON(cgrp->subsys[i]);
725 BUG_ON(!dummytop->subsys[i]);
726 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
727 cgrp->subsys[i] = dummytop->subsys[i];
728 cgrp->subsys[i]->cgroup = cgrp;
729 list_add(&ss->sibling, &root->subsys_list);
730 rcu_assign_pointer(ss->root, root);
734 } else if (bit & removed_bits) {
735 /* We're removing this subsystem */
736 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
737 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
739 ss->bind(ss, dummytop);
740 dummytop->subsys[i]->cgroup = dummytop;
741 cgrp->subsys[i] = NULL;
742 rcu_assign_pointer(subsys[i]->root, &rootnode);
743 list_del(&ss->sibling);
744 } else if (bit & final_bits) {
745 /* Subsystem state should already exist */
746 BUG_ON(!cgrp->subsys[i]);
748 /* Subsystem state shouldn't exist */
749 BUG_ON(cgrp->subsys[i]);
752 root->subsys_bits = root->actual_subsys_bits = final_bits;
758 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
760 struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
761 struct cgroup_subsys *ss;
763 mutex_lock(&cgroup_mutex);
764 for_each_subsys(root, ss)
765 seq_printf(seq, ",%s", ss->name);
766 if (test_bit(ROOT_NOPREFIX, &root->flags))
767 seq_puts(seq, ",noprefix");
768 if (strlen(root->release_agent_path))
769 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
770 mutex_unlock(&cgroup_mutex);
774 struct cgroup_sb_opts {
775 unsigned long subsys_bits;
780 /* Convert a hierarchy specifier into a bitmask of subsystems and
782 static int parse_cgroupfs_options(char *data,
783 struct cgroup_sb_opts *opts)
785 char *token, *o = data ?: "all";
787 opts->subsys_bits = 0;
789 opts->release_agent = NULL;
791 while ((token = strsep(&o, ",")) != NULL) {
794 if (!strcmp(token, "all")) {
795 /* Add all non-disabled subsystems */
797 opts->subsys_bits = 0;
798 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
799 struct cgroup_subsys *ss = subsys[i];
801 opts->subsys_bits |= 1ul << i;
803 } else if (!strcmp(token, "noprefix")) {
804 set_bit(ROOT_NOPREFIX, &opts->flags);
805 } else if (!strncmp(token, "release_agent=", 14)) {
806 /* Specifying two release agents is forbidden */
807 if (opts->release_agent)
809 opts->release_agent = kzalloc(PATH_MAX, GFP_KERNEL);
810 if (!opts->release_agent)
812 strncpy(opts->release_agent, token + 14, PATH_MAX - 1);
813 opts->release_agent[PATH_MAX - 1] = 0;
815 struct cgroup_subsys *ss;
817 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
819 if (!strcmp(token, ss->name)) {
821 set_bit(i, &opts->subsys_bits);
825 if (i == CGROUP_SUBSYS_COUNT)
830 /* We can't have an empty hierarchy */
831 if (!opts->subsys_bits)
837 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
840 struct cgroupfs_root *root = sb->s_fs_info;
841 struct cgroup *cgrp = &root->top_cgroup;
842 struct cgroup_sb_opts opts;
844 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
845 mutex_lock(&cgroup_mutex);
847 /* See what subsystems are wanted */
848 ret = parse_cgroupfs_options(data, &opts);
852 /* Don't allow flags to change at remount */
853 if (opts.flags != root->flags) {
858 ret = rebind_subsystems(root, opts.subsys_bits);
860 /* (re)populate subsystem files */
862 cgroup_populate_dir(cgrp);
864 if (opts.release_agent)
865 strcpy(root->release_agent_path, opts.release_agent);
867 if (opts.release_agent)
868 kfree(opts.release_agent);
869 mutex_unlock(&cgroup_mutex);
870 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
874 static struct super_operations cgroup_ops = {
875 .statfs = simple_statfs,
876 .drop_inode = generic_delete_inode,
877 .show_options = cgroup_show_options,
878 .remount_fs = cgroup_remount,
881 static void init_cgroup_root(struct cgroupfs_root *root)
883 struct cgroup *cgrp = &root->top_cgroup;
884 INIT_LIST_HEAD(&root->subsys_list);
885 INIT_LIST_HEAD(&root->root_list);
886 root->number_of_cgroups = 1;
888 cgrp->top_cgroup = cgrp;
889 INIT_LIST_HEAD(&cgrp->sibling);
890 INIT_LIST_HEAD(&cgrp->children);
891 INIT_LIST_HEAD(&cgrp->css_sets);
892 INIT_LIST_HEAD(&cgrp->release_list);
895 static int cgroup_test_super(struct super_block *sb, void *data)
897 struct cgroupfs_root *new = data;
898 struct cgroupfs_root *root = sb->s_fs_info;
900 /* First check subsystems */
901 if (new->subsys_bits != root->subsys_bits)
904 /* Next check flags */
905 if (new->flags != root->flags)
911 static int cgroup_set_super(struct super_block *sb, void *data)
914 struct cgroupfs_root *root = data;
916 ret = set_anon_super(sb, NULL);
920 sb->s_fs_info = root;
923 sb->s_blocksize = PAGE_CACHE_SIZE;
924 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
925 sb->s_magic = CGROUP_SUPER_MAGIC;
926 sb->s_op = &cgroup_ops;
931 static int cgroup_get_rootdir(struct super_block *sb)
933 struct inode *inode =
934 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
935 struct dentry *dentry;
940 inode->i_fop = &simple_dir_operations;
941 inode->i_op = &cgroup_dir_inode_operations;
942 /* directories start off with i_nlink == 2 (for "." entry) */
944 dentry = d_alloc_root(inode);
953 static int cgroup_get_sb(struct file_system_type *fs_type,
954 int flags, const char *unused_dev_name,
955 void *data, struct vfsmount *mnt)
957 struct cgroup_sb_opts opts;
959 struct super_block *sb;
960 struct cgroupfs_root *root;
961 struct list_head tmp_cg_links;
962 INIT_LIST_HEAD(&tmp_cg_links);
964 /* First find the desired set of subsystems */
965 ret = parse_cgroupfs_options(data, &opts);
967 if (opts.release_agent)
968 kfree(opts.release_agent);
972 root = kzalloc(sizeof(*root), GFP_KERNEL);
974 if (opts.release_agent)
975 kfree(opts.release_agent);
979 init_cgroup_root(root);
980 root->subsys_bits = opts.subsys_bits;
981 root->flags = opts.flags;
982 if (opts.release_agent) {
983 strcpy(root->release_agent_path, opts.release_agent);
984 kfree(opts.release_agent);
987 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, root);
994 if (sb->s_fs_info != root) {
995 /* Reusing an existing superblock */
996 BUG_ON(sb->s_root == NULL);
1000 /* New superblock */
1001 struct cgroup *cgrp = &root->top_cgroup;
1002 struct inode *inode;
1005 BUG_ON(sb->s_root != NULL);
1007 ret = cgroup_get_rootdir(sb);
1009 goto drop_new_super;
1010 inode = sb->s_root->d_inode;
1012 mutex_lock(&inode->i_mutex);
1013 mutex_lock(&cgroup_mutex);
1016 * We're accessing css_set_count without locking
1017 * css_set_lock here, but that's OK - it can only be
1018 * increased by someone holding cgroup_lock, and
1019 * that's us. The worst that can happen is that we
1020 * have some link structures left over
1022 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1024 mutex_unlock(&cgroup_mutex);
1025 mutex_unlock(&inode->i_mutex);
1026 goto drop_new_super;
1029 ret = rebind_subsystems(root, root->subsys_bits);
1030 if (ret == -EBUSY) {
1031 mutex_unlock(&cgroup_mutex);
1032 mutex_unlock(&inode->i_mutex);
1033 goto drop_new_super;
1036 /* EBUSY should be the only error here */
1039 list_add(&root->root_list, &roots);
1042 sb->s_root->d_fsdata = &root->top_cgroup;
1043 root->top_cgroup.dentry = sb->s_root;
1045 /* Link the top cgroup in this hierarchy into all
1046 * the css_set objects */
1047 write_lock(&css_set_lock);
1048 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1049 struct hlist_head *hhead = &css_set_table[i];
1050 struct hlist_node *node;
1053 hlist_for_each_entry(cg, node, hhead, hlist) {
1054 struct cg_cgroup_link *link;
1056 BUG_ON(list_empty(&tmp_cg_links));
1057 link = list_entry(tmp_cg_links.next,
1058 struct cg_cgroup_link,
1060 list_del(&link->cgrp_link_list);
1062 list_add(&link->cgrp_link_list,
1063 &root->top_cgroup.css_sets);
1064 list_add(&link->cg_link_list, &cg->cg_links);
1067 write_unlock(&css_set_lock);
1069 free_cg_links(&tmp_cg_links);
1071 BUG_ON(!list_empty(&cgrp->sibling));
1072 BUG_ON(!list_empty(&cgrp->children));
1073 BUG_ON(root->number_of_cgroups != 1);
1075 cgroup_populate_dir(cgrp);
1076 mutex_unlock(&inode->i_mutex);
1077 mutex_unlock(&cgroup_mutex);
1080 return simple_set_mnt(mnt, sb);
1083 up_write(&sb->s_umount);
1084 deactivate_super(sb);
1085 free_cg_links(&tmp_cg_links);
1089 static void cgroup_kill_sb(struct super_block *sb) {
1090 struct cgroupfs_root *root = sb->s_fs_info;
1091 struct cgroup *cgrp = &root->top_cgroup;
1093 struct cg_cgroup_link *link;
1094 struct cg_cgroup_link *saved_link;
1098 BUG_ON(root->number_of_cgroups != 1);
1099 BUG_ON(!list_empty(&cgrp->children));
1100 BUG_ON(!list_empty(&cgrp->sibling));
1102 mutex_lock(&cgroup_mutex);
1104 /* Rebind all subsystems back to the default hierarchy */
1105 ret = rebind_subsystems(root, 0);
1106 /* Shouldn't be able to fail ... */
1110 * Release all the links from css_sets to this hierarchy's
1113 write_lock(&css_set_lock);
1115 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1117 list_del(&link->cg_link_list);
1118 list_del(&link->cgrp_link_list);
1121 write_unlock(&css_set_lock);
1123 if (!list_empty(&root->root_list)) {
1124 list_del(&root->root_list);
1127 mutex_unlock(&cgroup_mutex);
1130 kill_litter_super(sb);
1133 static struct file_system_type cgroup_fs_type = {
1135 .get_sb = cgroup_get_sb,
1136 .kill_sb = cgroup_kill_sb,
1139 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1141 return dentry->d_fsdata;
1144 static inline struct cftype *__d_cft(struct dentry *dentry)
1146 return dentry->d_fsdata;
1150 * cgroup_path - generate the path of a cgroup
1151 * @cgrp: the cgroup in question
1152 * @buf: the buffer to write the path into
1153 * @buflen: the length of the buffer
1155 * Called with cgroup_mutex held. Writes path of cgroup into buf.
1156 * Returns 0 on success, -errno on error.
1158 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1162 if (cgrp == dummytop) {
1164 * Inactive subsystems have no dentry for their root
1171 start = buf + buflen;
1175 int len = cgrp->dentry->d_name.len;
1176 if ((start -= len) < buf)
1177 return -ENAMETOOLONG;
1178 memcpy(start, cgrp->dentry->d_name.name, len);
1179 cgrp = cgrp->parent;
1185 return -ENAMETOOLONG;
1188 memmove(buf, start, buf + buflen - start);
1193 * Return the first subsystem attached to a cgroup's hierarchy, and
1197 static void get_first_subsys(const struct cgroup *cgrp,
1198 struct cgroup_subsys_state **css, int *subsys_id)
1200 const struct cgroupfs_root *root = cgrp->root;
1201 const struct cgroup_subsys *test_ss;
1202 BUG_ON(list_empty(&root->subsys_list));
1203 test_ss = list_entry(root->subsys_list.next,
1204 struct cgroup_subsys, sibling);
1206 *css = cgrp->subsys[test_ss->subsys_id];
1210 *subsys_id = test_ss->subsys_id;
1214 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1215 * @cgrp: the cgroup the task is attaching to
1216 * @tsk: the task to be attached
1218 * Call holding cgroup_mutex. May take task_lock of
1219 * the task 'tsk' during call.
1221 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1224 struct cgroup_subsys *ss;
1225 struct cgroup *oldcgrp;
1226 struct css_set *cg = tsk->cgroups;
1227 struct css_set *newcg;
1228 struct cgroupfs_root *root = cgrp->root;
1231 get_first_subsys(cgrp, NULL, &subsys_id);
1233 /* Nothing to do if the task is already in that cgroup */
1234 oldcgrp = task_cgroup(tsk, subsys_id);
1235 if (cgrp == oldcgrp)
1238 for_each_subsys(root, ss) {
1239 if (ss->can_attach) {
1240 retval = ss->can_attach(ss, cgrp, tsk);
1247 * Locate or allocate a new css_set for this task,
1248 * based on its final set of cgroups
1250 newcg = find_css_set(cg, cgrp);
1255 if (tsk->flags & PF_EXITING) {
1260 rcu_assign_pointer(tsk->cgroups, newcg);
1263 /* Update the css_set linked lists if we're using them */
1264 write_lock(&css_set_lock);
1265 if (!list_empty(&tsk->cg_list)) {
1266 list_del(&tsk->cg_list);
1267 list_add(&tsk->cg_list, &newcg->tasks);
1269 write_unlock(&css_set_lock);
1271 for_each_subsys(root, ss) {
1273 ss->attach(ss, cgrp, oldcgrp, tsk);
1275 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1282 * Attach task with pid 'pid' to cgroup 'cgrp'. Call with
1283 * cgroup_mutex, may take task_lock of task
1285 static int attach_task_by_pid(struct cgroup *cgrp, char *pidbuf)
1288 struct task_struct *tsk;
1291 if (sscanf(pidbuf, "%d", &pid) != 1)
1296 tsk = find_task_by_vpid(pid);
1297 if (!tsk || tsk->flags & PF_EXITING) {
1301 get_task_struct(tsk);
1304 if ((current->euid) && (current->euid != tsk->uid)
1305 && (current->euid != tsk->suid)) {
1306 put_task_struct(tsk);
1311 get_task_struct(tsk);
1314 ret = cgroup_attach_task(cgrp, tsk);
1315 put_task_struct(tsk);
1319 /* The various types of files and directories in a cgroup file system */
1320 enum cgroup_filetype {
1324 FILE_NOTIFY_ON_RELEASE,
1329 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1330 * @cgrp: the cgroup to be checked for liveness
1332 * Returns true (with lock held) on success, or false (with no lock
1335 int cgroup_lock_live_group(struct cgroup *cgrp)
1337 mutex_lock(&cgroup_mutex);
1338 if (cgroup_is_removed(cgrp)) {
1339 mutex_unlock(&cgroup_mutex);
1345 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1348 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1349 if (!cgroup_lock_live_group(cgrp))
1351 strcpy(cgrp->root->release_agent_path, buffer);
1352 mutex_unlock(&cgroup_mutex);
1356 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1357 struct seq_file *seq)
1359 if (!cgroup_lock_live_group(cgrp))
1361 seq_puts(seq, cgrp->root->release_agent_path);
1362 seq_putc(seq, '\n');
1363 mutex_unlock(&cgroup_mutex);
1367 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1369 const char __user *userbuf,
1370 size_t nbytes, loff_t *unused_ppos)
1378 if (nbytes >= sizeof(buffer))
1380 if (copy_from_user(buffer, userbuf, nbytes))
1383 buffer[nbytes] = 0; /* nul-terminate */
1385 if (cft->write_u64) {
1386 u64 val = simple_strtoull(buffer, &end, 0);
1389 retval = cft->write_u64(cgrp, cft, val);
1391 s64 val = simple_strtoll(buffer, &end, 0);
1394 retval = cft->write_s64(cgrp, cft, val);
1401 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1403 const char __user *userbuf,
1404 size_t nbytes, loff_t *unused_ppos)
1406 char local_buffer[64];
1408 size_t max_bytes = cft->max_write_len;
1409 char *buffer = local_buffer;
1412 max_bytes = sizeof(local_buffer) - 1;
1413 if (nbytes >= max_bytes)
1415 /* Allocate a dynamic buffer if we need one */
1416 if (nbytes >= sizeof(local_buffer)) {
1417 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1421 if (nbytes && copy_from_user(buffer, userbuf, nbytes))
1424 buffer[nbytes] = 0; /* nul-terminate */
1426 retval = cft->write_string(cgrp, cft, buffer);
1429 if (buffer != local_buffer)
1434 static ssize_t cgroup_common_file_write(struct cgroup *cgrp,
1437 const char __user *userbuf,
1438 size_t nbytes, loff_t *unused_ppos)
1440 enum cgroup_filetype type = cft->private;
1444 if (nbytes >= PATH_MAX)
1447 /* +1 for nul-terminator */
1448 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1452 if (copy_from_user(buffer, userbuf, nbytes)) {
1456 buffer[nbytes] = 0; /* nul-terminate */
1457 strstrip(buffer); /* strip -just- trailing whitespace */
1459 mutex_lock(&cgroup_mutex);
1462 * This was already checked for in cgroup_file_write(), but
1463 * check again now we're holding cgroup_mutex.
1465 if (cgroup_is_removed(cgrp)) {
1472 retval = attach_task_by_pid(cgrp, buffer);
1474 case FILE_NOTIFY_ON_RELEASE:
1475 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
1476 if (simple_strtoul(buffer, NULL, 10) != 0)
1477 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
1479 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
1489 mutex_unlock(&cgroup_mutex);
1495 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1496 size_t nbytes, loff_t *ppos)
1498 struct cftype *cft = __d_cft(file->f_dentry);
1499 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1501 if (!cft || cgroup_is_removed(cgrp))
1504 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1505 if (cft->write_u64 || cft->write_s64)
1506 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1507 if (cft->write_string)
1508 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1510 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1511 return ret ? ret : nbytes;
1516 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1518 char __user *buf, size_t nbytes,
1522 u64 val = cft->read_u64(cgrp, cft);
1523 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1525 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1528 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1530 char __user *buf, size_t nbytes,
1534 s64 val = cft->read_s64(cgrp, cft);
1535 int len = sprintf(tmp, "%lld\n", (long long) val);
1537 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1540 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1541 size_t nbytes, loff_t *ppos)
1543 struct cftype *cft = __d_cft(file->f_dentry);
1544 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1546 if (!cft || cgroup_is_removed(cgrp))
1550 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1552 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1554 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1559 * seqfile ops/methods for returning structured data. Currently just
1560 * supports string->u64 maps, but can be extended in future.
1563 struct cgroup_seqfile_state {
1565 struct cgroup *cgroup;
1568 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1570 struct seq_file *sf = cb->state;
1571 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1574 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1576 struct cgroup_seqfile_state *state = m->private;
1577 struct cftype *cft = state->cft;
1578 if (cft->read_map) {
1579 struct cgroup_map_cb cb = {
1580 .fill = cgroup_map_add,
1583 return cft->read_map(state->cgroup, cft, &cb);
1585 return cft->read_seq_string(state->cgroup, cft, m);
1588 int cgroup_seqfile_release(struct inode *inode, struct file *file)
1590 struct seq_file *seq = file->private_data;
1591 kfree(seq->private);
1592 return single_release(inode, file);
1595 static struct file_operations cgroup_seqfile_operations = {
1597 .write = cgroup_file_write,
1598 .llseek = seq_lseek,
1599 .release = cgroup_seqfile_release,
1602 static int cgroup_file_open(struct inode *inode, struct file *file)
1607 err = generic_file_open(inode, file);
1611 cft = __d_cft(file->f_dentry);
1614 if (cft->read_map || cft->read_seq_string) {
1615 struct cgroup_seqfile_state *state =
1616 kzalloc(sizeof(*state), GFP_USER);
1620 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
1621 file->f_op = &cgroup_seqfile_operations;
1622 err = single_open(file, cgroup_seqfile_show, state);
1625 } else if (cft->open)
1626 err = cft->open(inode, file);
1633 static int cgroup_file_release(struct inode *inode, struct file *file)
1635 struct cftype *cft = __d_cft(file->f_dentry);
1637 return cft->release(inode, file);
1642 * cgroup_rename - Only allow simple rename of directories in place.
1644 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
1645 struct inode *new_dir, struct dentry *new_dentry)
1647 if (!S_ISDIR(old_dentry->d_inode->i_mode))
1649 if (new_dentry->d_inode)
1651 if (old_dir != new_dir)
1653 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1656 static struct file_operations cgroup_file_operations = {
1657 .read = cgroup_file_read,
1658 .write = cgroup_file_write,
1659 .llseek = generic_file_llseek,
1660 .open = cgroup_file_open,
1661 .release = cgroup_file_release,
1664 static struct inode_operations cgroup_dir_inode_operations = {
1665 .lookup = simple_lookup,
1666 .mkdir = cgroup_mkdir,
1667 .rmdir = cgroup_rmdir,
1668 .rename = cgroup_rename,
1671 static int cgroup_create_file(struct dentry *dentry, int mode,
1672 struct super_block *sb)
1674 static struct dentry_operations cgroup_dops = {
1675 .d_iput = cgroup_diput,
1678 struct inode *inode;
1682 if (dentry->d_inode)
1685 inode = cgroup_new_inode(mode, sb);
1689 if (S_ISDIR(mode)) {
1690 inode->i_op = &cgroup_dir_inode_operations;
1691 inode->i_fop = &simple_dir_operations;
1693 /* start off with i_nlink == 2 (for "." entry) */
1696 /* start with the directory inode held, so that we can
1697 * populate it without racing with another mkdir */
1698 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
1699 } else if (S_ISREG(mode)) {
1701 inode->i_fop = &cgroup_file_operations;
1703 dentry->d_op = &cgroup_dops;
1704 d_instantiate(dentry, inode);
1705 dget(dentry); /* Extra count - pin the dentry in core */
1710 * cgroup_create_dir - create a directory for an object.
1711 * @cgrp: the cgroup we create the directory for. It must have a valid
1712 * ->parent field. And we are going to fill its ->dentry field.
1713 * @dentry: dentry of the new cgroup
1714 * @mode: mode to set on new directory.
1716 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
1719 struct dentry *parent;
1722 parent = cgrp->parent->dentry;
1723 error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
1725 dentry->d_fsdata = cgrp;
1726 inc_nlink(parent->d_inode);
1727 cgrp->dentry = dentry;
1735 int cgroup_add_file(struct cgroup *cgrp,
1736 struct cgroup_subsys *subsys,
1737 const struct cftype *cft)
1739 struct dentry *dir = cgrp->dentry;
1740 struct dentry *dentry;
1743 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
1744 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
1745 strcpy(name, subsys->name);
1748 strcat(name, cft->name);
1749 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
1750 dentry = lookup_one_len(name, dir, strlen(name));
1751 if (!IS_ERR(dentry)) {
1752 error = cgroup_create_file(dentry, 0644 | S_IFREG,
1755 dentry->d_fsdata = (void *)cft;
1758 error = PTR_ERR(dentry);
1762 int cgroup_add_files(struct cgroup *cgrp,
1763 struct cgroup_subsys *subsys,
1764 const struct cftype cft[],
1768 for (i = 0; i < count; i++) {
1769 err = cgroup_add_file(cgrp, subsys, &cft[i]);
1777 * cgroup_task_count - count the number of tasks in a cgroup.
1778 * @cgrp: the cgroup in question
1780 * Return the number of tasks in the cgroup.
1782 int cgroup_task_count(const struct cgroup *cgrp)
1785 struct cg_cgroup_link *link;
1787 read_lock(&css_set_lock);
1788 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
1789 count += atomic_read(&link->cg->ref.refcount);
1791 read_unlock(&css_set_lock);
1796 * Advance a list_head iterator. The iterator should be positioned at
1797 * the start of a css_set
1799 static void cgroup_advance_iter(struct cgroup *cgrp,
1800 struct cgroup_iter *it)
1802 struct list_head *l = it->cg_link;
1803 struct cg_cgroup_link *link;
1806 /* Advance to the next non-empty css_set */
1809 if (l == &cgrp->css_sets) {
1813 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
1815 } while (list_empty(&cg->tasks));
1817 it->task = cg->tasks.next;
1821 * To reduce the fork() overhead for systems that are not actually
1822 * using their cgroups capability, we don't maintain the lists running
1823 * through each css_set to its tasks until we see the list actually
1824 * used - in other words after the first call to cgroup_iter_start().
1826 * The tasklist_lock is not held here, as do_each_thread() and
1827 * while_each_thread() are protected by RCU.
1829 static void cgroup_enable_task_cg_lists(void)
1831 struct task_struct *p, *g;
1832 write_lock(&css_set_lock);
1833 use_task_css_set_links = 1;
1834 do_each_thread(g, p) {
1837 * We should check if the process is exiting, otherwise
1838 * it will race with cgroup_exit() in that the list
1839 * entry won't be deleted though the process has exited.
1841 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
1842 list_add(&p->cg_list, &p->cgroups->tasks);
1844 } while_each_thread(g, p);
1845 write_unlock(&css_set_lock);
1848 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
1851 * The first time anyone tries to iterate across a cgroup,
1852 * we need to enable the list linking each css_set to its
1853 * tasks, and fix up all existing tasks.
1855 if (!use_task_css_set_links)
1856 cgroup_enable_task_cg_lists();
1858 read_lock(&css_set_lock);
1859 it->cg_link = &cgrp->css_sets;
1860 cgroup_advance_iter(cgrp, it);
1863 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
1864 struct cgroup_iter *it)
1866 struct task_struct *res;
1867 struct list_head *l = it->task;
1869 /* If the iterator cg is NULL, we have no tasks */
1872 res = list_entry(l, struct task_struct, cg_list);
1873 /* Advance iterator to find next entry */
1875 if (l == &res->cgroups->tasks) {
1876 /* We reached the end of this task list - move on to
1877 * the next cg_cgroup_link */
1878 cgroup_advance_iter(cgrp, it);
1885 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
1887 read_unlock(&css_set_lock);
1890 static inline int started_after_time(struct task_struct *t1,
1891 struct timespec *time,
1892 struct task_struct *t2)
1894 int start_diff = timespec_compare(&t1->start_time, time);
1895 if (start_diff > 0) {
1897 } else if (start_diff < 0) {
1901 * Arbitrarily, if two processes started at the same
1902 * time, we'll say that the lower pointer value
1903 * started first. Note that t2 may have exited by now
1904 * so this may not be a valid pointer any longer, but
1905 * that's fine - it still serves to distinguish
1906 * between two tasks started (effectively) simultaneously.
1913 * This function is a callback from heap_insert() and is used to order
1915 * In this case we order the heap in descending task start time.
1917 static inline int started_after(void *p1, void *p2)
1919 struct task_struct *t1 = p1;
1920 struct task_struct *t2 = p2;
1921 return started_after_time(t1, &t2->start_time, t2);
1925 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
1926 * @scan: struct cgroup_scanner containing arguments for the scan
1928 * Arguments include pointers to callback functions test_task() and
1930 * Iterate through all the tasks in a cgroup, calling test_task() for each,
1931 * and if it returns true, call process_task() for it also.
1932 * The test_task pointer may be NULL, meaning always true (select all tasks).
1933 * Effectively duplicates cgroup_iter_{start,next,end}()
1934 * but does not lock css_set_lock for the call to process_task().
1935 * The struct cgroup_scanner may be embedded in any structure of the caller's
1937 * It is guaranteed that process_task() will act on every task that
1938 * is a member of the cgroup for the duration of this call. This
1939 * function may or may not call process_task() for tasks that exit
1940 * or move to a different cgroup during the call, or are forked or
1941 * move into the cgroup during the call.
1943 * Note that test_task() may be called with locks held, and may in some
1944 * situations be called multiple times for the same task, so it should
1946 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
1947 * pre-allocated and will be used for heap operations (and its "gt" member will
1948 * be overwritten), else a temporary heap will be used (allocation of which
1949 * may cause this function to fail).
1951 int cgroup_scan_tasks(struct cgroup_scanner *scan)
1954 struct cgroup_iter it;
1955 struct task_struct *p, *dropped;
1956 /* Never dereference latest_task, since it's not refcounted */
1957 struct task_struct *latest_task = NULL;
1958 struct ptr_heap tmp_heap;
1959 struct ptr_heap *heap;
1960 struct timespec latest_time = { 0, 0 };
1963 /* The caller supplied our heap and pre-allocated its memory */
1965 heap->gt = &started_after;
1967 /* We need to allocate our own heap memory */
1969 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
1971 /* cannot allocate the heap */
1977 * Scan tasks in the cgroup, using the scanner's "test_task" callback
1978 * to determine which are of interest, and using the scanner's
1979 * "process_task" callback to process any of them that need an update.
1980 * Since we don't want to hold any locks during the task updates,
1981 * gather tasks to be processed in a heap structure.
1982 * The heap is sorted by descending task start time.
1983 * If the statically-sized heap fills up, we overflow tasks that
1984 * started later, and in future iterations only consider tasks that
1985 * started after the latest task in the previous pass. This
1986 * guarantees forward progress and that we don't miss any tasks.
1989 cgroup_iter_start(scan->cg, &it);
1990 while ((p = cgroup_iter_next(scan->cg, &it))) {
1992 * Only affect tasks that qualify per the caller's callback,
1993 * if he provided one
1995 if (scan->test_task && !scan->test_task(p, scan))
1998 * Only process tasks that started after the last task
2001 if (!started_after_time(p, &latest_time, latest_task))
2003 dropped = heap_insert(heap, p);
2004 if (dropped == NULL) {
2006 * The new task was inserted; the heap wasn't
2010 } else if (dropped != p) {
2012 * The new task was inserted, and pushed out a
2016 put_task_struct(dropped);
2019 * Else the new task was newer than anything already in
2020 * the heap and wasn't inserted
2023 cgroup_iter_end(scan->cg, &it);
2026 for (i = 0; i < heap->size; i++) {
2027 struct task_struct *q = heap->ptrs[i];
2029 latest_time = q->start_time;
2032 /* Process the task per the caller's callback */
2033 scan->process_task(q, scan);
2037 * If we had to process any tasks at all, scan again
2038 * in case some of them were in the middle of forking
2039 * children that didn't get processed.
2040 * Not the most efficient way to do it, but it avoids
2041 * having to take callback_mutex in the fork path
2045 if (heap == &tmp_heap)
2046 heap_free(&tmp_heap);
2051 * Stuff for reading the 'tasks' file.
2053 * Reading this file can return large amounts of data if a cgroup has
2054 * *lots* of attached tasks. So it may need several calls to read(),
2055 * but we cannot guarantee that the information we produce is correct
2056 * unless we produce it entirely atomically.
2058 * Upon tasks file open(), a struct ctr_struct is allocated, that
2059 * will have a pointer to an array (also allocated here). The struct
2060 * ctr_struct * is stored in file->private_data. Its resources will
2061 * be freed by release() when the file is closed. The array is used
2062 * to sprintf the PIDs and then used by read().
2070 * Load into 'pidarray' up to 'npids' of the tasks using cgroup
2071 * 'cgrp'. Return actual number of pids loaded. No need to
2072 * task_lock(p) when reading out p->cgroup, since we're in an RCU
2073 * read section, so the css_set can't go away, and is
2074 * immutable after creation.
2076 static int pid_array_load(pid_t *pidarray, int npids, struct cgroup *cgrp)
2079 struct cgroup_iter it;
2080 struct task_struct *tsk;
2081 cgroup_iter_start(cgrp, &it);
2082 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2083 if (unlikely(n == npids))
2085 pidarray[n++] = task_pid_vnr(tsk);
2087 cgroup_iter_end(cgrp, &it);
2092 * cgroupstats_build - build and fill cgroupstats
2093 * @stats: cgroupstats to fill information into
2094 * @dentry: A dentry entry belonging to the cgroup for which stats have
2097 * Build and fill cgroupstats so that taskstats can export it to user
2100 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2103 struct cgroup *cgrp;
2104 struct cgroup_iter it;
2105 struct task_struct *tsk;
2107 * Validate dentry by checking the superblock operations
2109 if (dentry->d_sb->s_op != &cgroup_ops)
2113 cgrp = dentry->d_fsdata;
2116 cgroup_iter_start(cgrp, &it);
2117 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2118 switch (tsk->state) {
2120 stats->nr_running++;
2122 case TASK_INTERRUPTIBLE:
2123 stats->nr_sleeping++;
2125 case TASK_UNINTERRUPTIBLE:
2126 stats->nr_uninterruptible++;
2129 stats->nr_stopped++;
2132 if (delayacct_is_task_waiting_on_io(tsk))
2133 stats->nr_io_wait++;
2137 cgroup_iter_end(cgrp, &it);
2144 static int cmppid(const void *a, const void *b)
2146 return *(pid_t *)a - *(pid_t *)b;
2150 * Convert array 'a' of 'npids' pid_t's to a string of newline separated
2151 * decimal pids in 'buf'. Don't write more than 'sz' chars, but return
2152 * count 'cnt' of how many chars would be written if buf were large enough.
2154 static int pid_array_to_buf(char *buf, int sz, pid_t *a, int npids)
2159 for (i = 0; i < npids; i++)
2160 cnt += snprintf(buf + cnt, max(sz - cnt, 0), "%d\n", a[i]);
2165 * Handle an open on 'tasks' file. Prepare a buffer listing the
2166 * process id's of tasks currently attached to the cgroup being opened.
2168 * Does not require any specific cgroup mutexes, and does not take any.
2170 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2172 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2173 struct ctr_struct *ctr;
2178 if (!(file->f_mode & FMODE_READ))
2181 ctr = kmalloc(sizeof(*ctr), GFP_KERNEL);
2186 * If cgroup gets more users after we read count, we won't have
2187 * enough space - tough. This race is indistinguishable to the
2188 * caller from the case that the additional cgroup users didn't
2189 * show up until sometime later on.
2191 npids = cgroup_task_count(cgrp);
2193 pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
2197 npids = pid_array_load(pidarray, npids, cgrp);
2198 sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
2200 /* Call pid_array_to_buf() twice, first just to get bufsz */
2201 ctr->bufsz = pid_array_to_buf(&c, sizeof(c), pidarray, npids) + 1;
2202 ctr->buf = kmalloc(ctr->bufsz, GFP_KERNEL);
2205 ctr->bufsz = pid_array_to_buf(ctr->buf, ctr->bufsz, pidarray, npids);
2212 file->private_data = ctr;
2223 static ssize_t cgroup_tasks_read(struct cgroup *cgrp,
2225 struct file *file, char __user *buf,
2226 size_t nbytes, loff_t *ppos)
2228 struct ctr_struct *ctr = file->private_data;
2230 return simple_read_from_buffer(buf, nbytes, ppos, ctr->buf, ctr->bufsz);
2233 static int cgroup_tasks_release(struct inode *unused_inode,
2236 struct ctr_struct *ctr;
2238 if (file->f_mode & FMODE_READ) {
2239 ctr = file->private_data;
2246 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2249 return notify_on_release(cgrp);
2253 * for the common functions, 'private' gives the type of file
2255 static struct cftype files[] = {
2258 .open = cgroup_tasks_open,
2259 .read = cgroup_tasks_read,
2260 .write = cgroup_common_file_write,
2261 .release = cgroup_tasks_release,
2262 .private = FILE_TASKLIST,
2266 .name = "notify_on_release",
2267 .read_u64 = cgroup_read_notify_on_release,
2268 .write = cgroup_common_file_write,
2269 .private = FILE_NOTIFY_ON_RELEASE,
2273 static struct cftype cft_release_agent = {
2274 .name = "release_agent",
2275 .read_seq_string = cgroup_release_agent_show,
2276 .write_string = cgroup_release_agent_write,
2277 .max_write_len = PATH_MAX,
2278 .private = FILE_RELEASE_AGENT,
2281 static int cgroup_populate_dir(struct cgroup *cgrp)
2284 struct cgroup_subsys *ss;
2286 /* First clear out any existing files */
2287 cgroup_clear_directory(cgrp->dentry);
2289 err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2293 if (cgrp == cgrp->top_cgroup) {
2294 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2298 for_each_subsys(cgrp->root, ss) {
2299 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2306 static void init_cgroup_css(struct cgroup_subsys_state *css,
2307 struct cgroup_subsys *ss,
2308 struct cgroup *cgrp)
2311 atomic_set(&css->refcnt, 0);
2313 if (cgrp == dummytop)
2314 set_bit(CSS_ROOT, &css->flags);
2315 BUG_ON(cgrp->subsys[ss->subsys_id]);
2316 cgrp->subsys[ss->subsys_id] = css;
2320 * cgroup_create - create a cgroup
2321 * @parent: cgroup that will be parent of the new cgroup
2322 * @dentry: dentry of the new cgroup
2323 * @mode: mode to set on new inode
2325 * Must be called with the mutex on the parent inode held
2327 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
2330 struct cgroup *cgrp;
2331 struct cgroupfs_root *root = parent->root;
2333 struct cgroup_subsys *ss;
2334 struct super_block *sb = root->sb;
2336 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
2340 /* Grab a reference on the superblock so the hierarchy doesn't
2341 * get deleted on unmount if there are child cgroups. This
2342 * can be done outside cgroup_mutex, since the sb can't
2343 * disappear while someone has an open control file on the
2345 atomic_inc(&sb->s_active);
2347 mutex_lock(&cgroup_mutex);
2349 INIT_LIST_HEAD(&cgrp->sibling);
2350 INIT_LIST_HEAD(&cgrp->children);
2351 INIT_LIST_HEAD(&cgrp->css_sets);
2352 INIT_LIST_HEAD(&cgrp->release_list);
2354 cgrp->parent = parent;
2355 cgrp->root = parent->root;
2356 cgrp->top_cgroup = parent->top_cgroup;
2358 if (notify_on_release(parent))
2359 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2361 for_each_subsys(root, ss) {
2362 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
2367 init_cgroup_css(css, ss, cgrp);
2370 list_add(&cgrp->sibling, &cgrp->parent->children);
2371 root->number_of_cgroups++;
2373 err = cgroup_create_dir(cgrp, dentry, mode);
2377 /* The cgroup directory was pre-locked for us */
2378 BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
2380 err = cgroup_populate_dir(cgrp);
2381 /* If err < 0, we have a half-filled directory - oh well ;) */
2383 mutex_unlock(&cgroup_mutex);
2384 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
2390 list_del(&cgrp->sibling);
2391 root->number_of_cgroups--;
2395 for_each_subsys(root, ss) {
2396 if (cgrp->subsys[ss->subsys_id])
2397 ss->destroy(ss, cgrp);
2400 mutex_unlock(&cgroup_mutex);
2402 /* Release the reference count that we took on the superblock */
2403 deactivate_super(sb);
2409 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2411 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
2413 /* the vfs holds inode->i_mutex already */
2414 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
2417 static inline int cgroup_has_css_refs(struct cgroup *cgrp)
2419 /* Check the reference count on each subsystem. Since we
2420 * already established that there are no tasks in the
2421 * cgroup, if the css refcount is also 0, then there should
2422 * be no outstanding references, so the subsystem is safe to
2423 * destroy. We scan across all subsystems rather than using
2424 * the per-hierarchy linked list of mounted subsystems since
2425 * we can be called via check_for_release() with no
2426 * synchronization other than RCU, and the subsystem linked
2427 * list isn't RCU-safe */
2429 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2430 struct cgroup_subsys *ss = subsys[i];
2431 struct cgroup_subsys_state *css;
2432 /* Skip subsystems not in this hierarchy */
2433 if (ss->root != cgrp->root)
2435 css = cgrp->subsys[ss->subsys_id];
2436 /* When called from check_for_release() it's possible
2437 * that by this point the cgroup has been removed
2438 * and the css deleted. But a false-positive doesn't
2439 * matter, since it can only happen if the cgroup
2440 * has been deleted and hence no longer needs the
2441 * release agent to be called anyway. */
2442 if (css && atomic_read(&css->refcnt))
2448 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
2450 struct cgroup *cgrp = dentry->d_fsdata;
2452 struct cgroup *parent;
2453 struct super_block *sb;
2454 struct cgroupfs_root *root;
2456 /* the vfs holds both inode->i_mutex already */
2458 mutex_lock(&cgroup_mutex);
2459 if (atomic_read(&cgrp->count) != 0) {
2460 mutex_unlock(&cgroup_mutex);
2463 if (!list_empty(&cgrp->children)) {
2464 mutex_unlock(&cgroup_mutex);
2468 parent = cgrp->parent;
2473 * Call pre_destroy handlers of subsys. Notify subsystems
2474 * that rmdir() request comes.
2476 cgroup_call_pre_destroy(cgrp);
2478 if (cgroup_has_css_refs(cgrp)) {
2479 mutex_unlock(&cgroup_mutex);
2483 spin_lock(&release_list_lock);
2484 set_bit(CGRP_REMOVED, &cgrp->flags);
2485 if (!list_empty(&cgrp->release_list))
2486 list_del(&cgrp->release_list);
2487 spin_unlock(&release_list_lock);
2488 /* delete my sibling from parent->children */
2489 list_del(&cgrp->sibling);
2490 spin_lock(&cgrp->dentry->d_lock);
2491 d = dget(cgrp->dentry);
2492 cgrp->dentry = NULL;
2493 spin_unlock(&d->d_lock);
2495 cgroup_d_remove_dir(d);
2498 set_bit(CGRP_RELEASABLE, &parent->flags);
2499 check_for_release(parent);
2501 mutex_unlock(&cgroup_mutex);
2505 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
2507 struct cgroup_subsys_state *css;
2509 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
2511 /* Create the top cgroup state for this subsystem */
2512 ss->root = &rootnode;
2513 css = ss->create(ss, dummytop);
2514 /* We don't handle early failures gracefully */
2515 BUG_ON(IS_ERR(css));
2516 init_cgroup_css(css, ss, dummytop);
2518 /* Update the init_css_set to contain a subsys
2519 * pointer to this state - since the subsystem is
2520 * newly registered, all tasks and hence the
2521 * init_css_set is in the subsystem's top cgroup. */
2522 init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
2524 need_forkexit_callback |= ss->fork || ss->exit;
2525 need_mm_owner_callback |= !!ss->mm_owner_changed;
2527 /* At system boot, before all subsystems have been
2528 * registered, no tasks have been forked, so we don't
2529 * need to invoke fork callbacks here. */
2530 BUG_ON(!list_empty(&init_task.tasks));
2536 * cgroup_init_early - cgroup initialization at system boot
2538 * Initialize cgroups at system boot, and initialize any
2539 * subsystems that request early init.
2541 int __init cgroup_init_early(void)
2544 kref_init(&init_css_set.ref);
2545 kref_get(&init_css_set.ref);
2546 INIT_LIST_HEAD(&init_css_set.cg_links);
2547 INIT_LIST_HEAD(&init_css_set.tasks);
2548 INIT_HLIST_NODE(&init_css_set.hlist);
2550 init_cgroup_root(&rootnode);
2551 list_add(&rootnode.root_list, &roots);
2553 init_task.cgroups = &init_css_set;
2555 init_css_set_link.cg = &init_css_set;
2556 list_add(&init_css_set_link.cgrp_link_list,
2557 &rootnode.top_cgroup.css_sets);
2558 list_add(&init_css_set_link.cg_link_list,
2559 &init_css_set.cg_links);
2561 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
2562 INIT_HLIST_HEAD(&css_set_table[i]);
2564 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2565 struct cgroup_subsys *ss = subsys[i];
2568 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
2569 BUG_ON(!ss->create);
2570 BUG_ON(!ss->destroy);
2571 if (ss->subsys_id != i) {
2572 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
2573 ss->name, ss->subsys_id);
2578 cgroup_init_subsys(ss);
2584 * cgroup_init - cgroup initialization
2586 * Register cgroup filesystem and /proc file, and initialize
2587 * any subsystems that didn't request early init.
2589 int __init cgroup_init(void)
2593 struct hlist_head *hhead;
2595 err = bdi_init(&cgroup_backing_dev_info);
2599 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2600 struct cgroup_subsys *ss = subsys[i];
2601 if (!ss->early_init)
2602 cgroup_init_subsys(ss);
2605 /* Add init_css_set to the hash table */
2606 hhead = css_set_hash(init_css_set.subsys);
2607 hlist_add_head(&init_css_set.hlist, hhead);
2609 err = register_filesystem(&cgroup_fs_type);
2613 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
2617 bdi_destroy(&cgroup_backing_dev_info);
2623 * proc_cgroup_show()
2624 * - Print task's cgroup paths into seq_file, one line for each hierarchy
2625 * - Used for /proc/<pid>/cgroup.
2626 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
2627 * doesn't really matter if tsk->cgroup changes after we read it,
2628 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
2629 * anyway. No need to check that tsk->cgroup != NULL, thanks to
2630 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
2631 * cgroup to top_cgroup.
2634 /* TODO: Use a proper seq_file iterator */
2635 static int proc_cgroup_show(struct seq_file *m, void *v)
2638 struct task_struct *tsk;
2641 struct cgroupfs_root *root;
2644 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
2650 tsk = get_pid_task(pid, PIDTYPE_PID);
2656 mutex_lock(&cgroup_mutex);
2658 for_each_root(root) {
2659 struct cgroup_subsys *ss;
2660 struct cgroup *cgrp;
2664 /* Skip this hierarchy if it has no active subsystems */
2665 if (!root->actual_subsys_bits)
2667 seq_printf(m, "%lu:", root->subsys_bits);
2668 for_each_subsys(root, ss)
2669 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
2671 get_first_subsys(&root->top_cgroup, NULL, &subsys_id);
2672 cgrp = task_cgroup(tsk, subsys_id);
2673 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
2681 mutex_unlock(&cgroup_mutex);
2682 put_task_struct(tsk);
2689 static int cgroup_open(struct inode *inode, struct file *file)
2691 struct pid *pid = PROC_I(inode)->pid;
2692 return single_open(file, proc_cgroup_show, pid);
2695 struct file_operations proc_cgroup_operations = {
2696 .open = cgroup_open,
2698 .llseek = seq_lseek,
2699 .release = single_release,
2702 /* Display information about each subsystem and each hierarchy */
2703 static int proc_cgroupstats_show(struct seq_file *m, void *v)
2707 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
2708 mutex_lock(&cgroup_mutex);
2709 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2710 struct cgroup_subsys *ss = subsys[i];
2711 seq_printf(m, "%s\t%lu\t%d\t%d\n",
2712 ss->name, ss->root->subsys_bits,
2713 ss->root->number_of_cgroups, !ss->disabled);
2715 mutex_unlock(&cgroup_mutex);
2719 static int cgroupstats_open(struct inode *inode, struct file *file)
2721 return single_open(file, proc_cgroupstats_show, NULL);
2724 static struct file_operations proc_cgroupstats_operations = {
2725 .open = cgroupstats_open,
2727 .llseek = seq_lseek,
2728 .release = single_release,
2732 * cgroup_fork - attach newly forked task to its parents cgroup.
2733 * @child: pointer to task_struct of forking parent process.
2735 * Description: A task inherits its parent's cgroup at fork().
2737 * A pointer to the shared css_set was automatically copied in
2738 * fork.c by dup_task_struct(). However, we ignore that copy, since
2739 * it was not made under the protection of RCU or cgroup_mutex, so
2740 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
2741 * have already changed current->cgroups, allowing the previously
2742 * referenced cgroup group to be removed and freed.
2744 * At the point that cgroup_fork() is called, 'current' is the parent
2745 * task, and the passed argument 'child' points to the child task.
2747 void cgroup_fork(struct task_struct *child)
2750 child->cgroups = current->cgroups;
2751 get_css_set(child->cgroups);
2752 task_unlock(current);
2753 INIT_LIST_HEAD(&child->cg_list);
2757 * cgroup_fork_callbacks - run fork callbacks
2758 * @child: the new task
2760 * Called on a new task very soon before adding it to the
2761 * tasklist. No need to take any locks since no-one can
2762 * be operating on this task.
2764 void cgroup_fork_callbacks(struct task_struct *child)
2766 if (need_forkexit_callback) {
2768 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2769 struct cgroup_subsys *ss = subsys[i];
2771 ss->fork(ss, child);
2776 #ifdef CONFIG_MM_OWNER
2778 * cgroup_mm_owner_callbacks - run callbacks when the mm->owner changes
2781 * Called on every change to mm->owner. mm_init_owner() does not
2782 * invoke this routine, since it assigns the mm->owner the first time
2783 * and does not change it.
2785 void cgroup_mm_owner_callbacks(struct task_struct *old, struct task_struct *new)
2787 struct cgroup *oldcgrp, *newcgrp;
2789 if (need_mm_owner_callback) {
2791 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2792 struct cgroup_subsys *ss = subsys[i];
2793 oldcgrp = task_cgroup(old, ss->subsys_id);
2794 newcgrp = task_cgroup(new, ss->subsys_id);
2795 if (oldcgrp == newcgrp)
2797 if (ss->mm_owner_changed)
2798 ss->mm_owner_changed(ss, oldcgrp, newcgrp);
2802 #endif /* CONFIG_MM_OWNER */
2805 * cgroup_post_fork - called on a new task after adding it to the task list
2806 * @child: the task in question
2808 * Adds the task to the list running through its css_set if necessary.
2809 * Has to be after the task is visible on the task list in case we race
2810 * with the first call to cgroup_iter_start() - to guarantee that the
2811 * new task ends up on its list.
2813 void cgroup_post_fork(struct task_struct *child)
2815 if (use_task_css_set_links) {
2816 write_lock(&css_set_lock);
2817 if (list_empty(&child->cg_list))
2818 list_add(&child->cg_list, &child->cgroups->tasks);
2819 write_unlock(&css_set_lock);
2823 * cgroup_exit - detach cgroup from exiting task
2824 * @tsk: pointer to task_struct of exiting process
2825 * @run_callback: run exit callbacks?
2827 * Description: Detach cgroup from @tsk and release it.
2829 * Note that cgroups marked notify_on_release force every task in
2830 * them to take the global cgroup_mutex mutex when exiting.
2831 * This could impact scaling on very large systems. Be reluctant to
2832 * use notify_on_release cgroups where very high task exit scaling
2833 * is required on large systems.
2835 * the_top_cgroup_hack:
2837 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
2839 * We call cgroup_exit() while the task is still competent to
2840 * handle notify_on_release(), then leave the task attached to the
2841 * root cgroup in each hierarchy for the remainder of its exit.
2843 * To do this properly, we would increment the reference count on
2844 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
2845 * code we would add a second cgroup function call, to drop that
2846 * reference. This would just create an unnecessary hot spot on
2847 * the top_cgroup reference count, to no avail.
2849 * Normally, holding a reference to a cgroup without bumping its
2850 * count is unsafe. The cgroup could go away, or someone could
2851 * attach us to a different cgroup, decrementing the count on
2852 * the first cgroup that we never incremented. But in this case,
2853 * top_cgroup isn't going away, and either task has PF_EXITING set,
2854 * which wards off any cgroup_attach_task() attempts, or task is a failed
2855 * fork, never visible to cgroup_attach_task.
2857 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
2862 if (run_callbacks && need_forkexit_callback) {
2863 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2864 struct cgroup_subsys *ss = subsys[i];
2871 * Unlink from the css_set task list if necessary.
2872 * Optimistically check cg_list before taking
2875 if (!list_empty(&tsk->cg_list)) {
2876 write_lock(&css_set_lock);
2877 if (!list_empty(&tsk->cg_list))
2878 list_del(&tsk->cg_list);
2879 write_unlock(&css_set_lock);
2882 /* Reassign the task to the init_css_set. */
2885 tsk->cgroups = &init_css_set;
2888 put_css_set_taskexit(cg);
2892 * cgroup_clone - clone the cgroup the given subsystem is attached to
2893 * @tsk: the task to be moved
2894 * @subsys: the given subsystem
2896 * Duplicate the current cgroup in the hierarchy that the given
2897 * subsystem is attached to, and move this task into the new
2900 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys)
2902 struct dentry *dentry;
2904 char nodename[MAX_CGROUP_TYPE_NAMELEN];
2905 struct cgroup *parent, *child;
2906 struct inode *inode;
2908 struct cgroupfs_root *root;
2909 struct cgroup_subsys *ss;
2911 /* We shouldn't be called by an unregistered subsystem */
2912 BUG_ON(!subsys->active);
2914 /* First figure out what hierarchy and cgroup we're dealing
2915 * with, and pin them so we can drop cgroup_mutex */
2916 mutex_lock(&cgroup_mutex);
2918 root = subsys->root;
2919 if (root == &rootnode) {
2921 "Not cloning cgroup for unused subsystem %s\n",
2923 mutex_unlock(&cgroup_mutex);
2927 parent = task_cgroup(tsk, subsys->subsys_id);
2929 snprintf(nodename, MAX_CGROUP_TYPE_NAMELEN, "%d", tsk->pid);
2931 /* Pin the hierarchy */
2932 atomic_inc(&parent->root->sb->s_active);
2934 /* Keep the cgroup alive */
2936 mutex_unlock(&cgroup_mutex);
2938 /* Now do the VFS work to create a cgroup */
2939 inode = parent->dentry->d_inode;
2941 /* Hold the parent directory mutex across this operation to
2942 * stop anyone else deleting the new cgroup */
2943 mutex_lock(&inode->i_mutex);
2944 dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
2945 if (IS_ERR(dentry)) {
2947 "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
2949 ret = PTR_ERR(dentry);
2953 /* Create the cgroup directory, which also creates the cgroup */
2954 ret = vfs_mkdir(inode, dentry, S_IFDIR | 0755);
2955 child = __d_cgrp(dentry);
2959 "Failed to create cgroup %s: %d\n", nodename,
2966 "Couldn't find new cgroup %s\n", nodename);
2971 /* The cgroup now exists. Retake cgroup_mutex and check
2972 * that we're still in the same state that we thought we
2974 mutex_lock(&cgroup_mutex);
2975 if ((root != subsys->root) ||
2976 (parent != task_cgroup(tsk, subsys->subsys_id))) {
2977 /* Aargh, we raced ... */
2978 mutex_unlock(&inode->i_mutex);
2981 deactivate_super(parent->root->sb);
2982 /* The cgroup is still accessible in the VFS, but
2983 * we're not going to try to rmdir() it at this
2986 "Race in cgroup_clone() - leaking cgroup %s\n",
2991 /* do any required auto-setup */
2992 for_each_subsys(root, ss) {
2994 ss->post_clone(ss, child);
2997 /* All seems fine. Finish by moving the task into the new cgroup */
2998 ret = cgroup_attach_task(child, tsk);
2999 mutex_unlock(&cgroup_mutex);
3002 mutex_unlock(&inode->i_mutex);
3004 mutex_lock(&cgroup_mutex);
3006 mutex_unlock(&cgroup_mutex);
3007 deactivate_super(parent->root->sb);
3012 * cgroup_is_descendant - see if @cgrp is a descendant of current task's cgrp
3013 * @cgrp: the cgroup in question
3015 * See if @cgrp is a descendant of the current task's cgroup in
3016 * the appropriate hierarchy.
3018 * If we are sending in dummytop, then presumably we are creating
3019 * the top cgroup in the subsystem.
3021 * Called only by the ns (nsproxy) cgroup.
3023 int cgroup_is_descendant(const struct cgroup *cgrp)
3026 struct cgroup *target;
3029 if (cgrp == dummytop)
3032 get_first_subsys(cgrp, NULL, &subsys_id);
3033 target = task_cgroup(current, subsys_id);
3034 while (cgrp != target && cgrp!= cgrp->top_cgroup)
3035 cgrp = cgrp->parent;
3036 ret = (cgrp == target);
3040 static void check_for_release(struct cgroup *cgrp)
3042 /* All of these checks rely on RCU to keep the cgroup
3043 * structure alive */
3044 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
3045 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
3046 /* Control Group is currently removeable. If it's not
3047 * already queued for a userspace notification, queue
3049 int need_schedule_work = 0;
3050 spin_lock(&release_list_lock);
3051 if (!cgroup_is_removed(cgrp) &&
3052 list_empty(&cgrp->release_list)) {
3053 list_add(&cgrp->release_list, &release_list);
3054 need_schedule_work = 1;
3056 spin_unlock(&release_list_lock);
3057 if (need_schedule_work)
3058 schedule_work(&release_agent_work);
3062 void __css_put(struct cgroup_subsys_state *css)
3064 struct cgroup *cgrp = css->cgroup;
3066 if (atomic_dec_and_test(&css->refcnt) && notify_on_release(cgrp)) {
3067 set_bit(CGRP_RELEASABLE, &cgrp->flags);
3068 check_for_release(cgrp);
3074 * Notify userspace when a cgroup is released, by running the
3075 * configured release agent with the name of the cgroup (path
3076 * relative to the root of cgroup file system) as the argument.
3078 * Most likely, this user command will try to rmdir this cgroup.
3080 * This races with the possibility that some other task will be
3081 * attached to this cgroup before it is removed, or that some other
3082 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
3083 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
3084 * unused, and this cgroup will be reprieved from its death sentence,
3085 * to continue to serve a useful existence. Next time it's released,
3086 * we will get notified again, if it still has 'notify_on_release' set.
3088 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
3089 * means only wait until the task is successfully execve()'d. The
3090 * separate release agent task is forked by call_usermodehelper(),
3091 * then control in this thread returns here, without waiting for the
3092 * release agent task. We don't bother to wait because the caller of
3093 * this routine has no use for the exit status of the release agent
3094 * task, so no sense holding our caller up for that.
3096 static void cgroup_release_agent(struct work_struct *work)
3098 BUG_ON(work != &release_agent_work);
3099 mutex_lock(&cgroup_mutex);
3100 spin_lock(&release_list_lock);
3101 while (!list_empty(&release_list)) {
3102 char *argv[3], *envp[3];
3104 char *pathbuf = NULL, *agentbuf = NULL;
3105 struct cgroup *cgrp = list_entry(release_list.next,
3108 list_del_init(&cgrp->release_list);
3109 spin_unlock(&release_list_lock);
3110 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3113 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
3115 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
3120 argv[i++] = agentbuf;
3121 argv[i++] = pathbuf;
3125 /* minimal command environment */
3126 envp[i++] = "HOME=/";
3127 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3130 /* Drop the lock while we invoke the usermode helper,
3131 * since the exec could involve hitting disk and hence
3132 * be a slow process */
3133 mutex_unlock(&cgroup_mutex);
3134 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3135 mutex_lock(&cgroup_mutex);
3139 spin_lock(&release_list_lock);
3141 spin_unlock(&release_list_lock);
3142 mutex_unlock(&cgroup_mutex);
3145 static int __init cgroup_disable(char *str)
3150 while ((token = strsep(&str, ",")) != NULL) {
3154 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3155 struct cgroup_subsys *ss = subsys[i];
3157 if (!strcmp(token, ss->name)) {
3159 printk(KERN_INFO "Disabling %s control group"
3160 " subsystem\n", ss->name);
3167 __setup("cgroup_disable=", cgroup_disable);