2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/backing-dev.h>
44 #include <linux/seq_file.h>
45 #include <linux/slab.h>
46 #include <linux/magic.h>
47 #include <linux/spinlock.h>
48 #include <linux/string.h>
49 #include <linux/sort.h>
50 #include <linux/kmod.h>
51 #include <linux/module.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hashtable.h>
55 #include <linux/namei.h>
56 #include <linux/pid_namespace.h>
57 #include <linux/idr.h>
58 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
59 #include <linux/eventfd.h>
60 #include <linux/poll.h>
61 #include <linux/flex_array.h> /* used in cgroup_attach_task */
62 #include <linux/kthread.h>
64 #include <linux/atomic.h>
67 * cgroup_mutex is the master lock. Any modification to cgroup or its
68 * hierarchy must be performed while holding it.
70 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
71 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
72 * release_agent_path and so on. Modifying requires both cgroup_mutex and
73 * cgroup_root_mutex. Readers can acquire either of the two. This is to
74 * break the following locking order cycle.
76 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
77 * B. namespace_sem -> cgroup_mutex
79 * B happens only through cgroup_show_options() and using cgroup_root_mutex
82 #ifdef CONFIG_PROVE_RCU
83 DEFINE_MUTEX(cgroup_mutex);
84 EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for task_subsys_state_check() */
86 static DEFINE_MUTEX(cgroup_mutex);
89 static DEFINE_MUTEX(cgroup_root_mutex);
92 * Generate an array of cgroup subsystem pointers. At boot time, this is
93 * populated with the built in subsystems, and modular subsystems are
94 * registered after that. The mutable section of this array is protected by
97 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
98 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
99 static struct cgroup_subsys *subsys[CGROUP_SUBSYS_COUNT] = {
100 #include <linux/cgroup_subsys.h>
104 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
105 * subsystems that are otherwise unattached - it never has more than a
106 * single cgroup, and all tasks are part of that cgroup.
108 static struct cgroupfs_root rootnode;
111 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
114 struct list_head node;
115 struct dentry *dentry;
119 struct simple_xattrs xattrs;
123 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
124 * cgroup_subsys->use_id != 0.
126 #define CSS_ID_MAX (65535)
129 * The css to which this ID points. This pointer is set to valid value
130 * after cgroup is populated. If cgroup is removed, this will be NULL.
131 * This pointer is expected to be RCU-safe because destroy()
132 * is called after synchronize_rcu(). But for safe use, css_tryget()
133 * should be used for avoiding race.
135 struct cgroup_subsys_state __rcu *css;
141 * Depth in hierarchy which this ID belongs to.
143 unsigned short depth;
145 * ID is freed by RCU. (and lookup routine is RCU safe.)
147 struct rcu_head rcu_head;
149 * Hierarchy of CSS ID belongs to.
151 unsigned short stack[0]; /* Array of Length (depth+1) */
155 * cgroup_event represents events which userspace want to receive.
157 struct cgroup_event {
159 * Cgroup which the event belongs to.
163 * Control file which the event associated.
167 * eventfd to signal userspace about the event.
169 struct eventfd_ctx *eventfd;
171 * Each of these stored in a list by the cgroup.
173 struct list_head list;
175 * All fields below needed to unregister event when
176 * userspace closes eventfd.
179 wait_queue_head_t *wqh;
181 struct work_struct remove;
184 /* The list of hierarchy roots */
186 static LIST_HEAD(roots);
187 static int root_count;
190 * Hierarchy ID allocation and mapping. It follows the same exclusion
191 * rules as other root ops - both cgroup_mutex and cgroup_root_mutex for
192 * writes, either for reads.
194 static DEFINE_IDR(cgroup_hierarchy_idr);
196 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
197 #define dummytop (&rootnode.top_cgroup)
199 static struct cgroup_name root_cgroup_name = { .name = "/" };
201 /* This flag indicates whether tasks in the fork and exit paths should
202 * check for fork/exit handlers to call. This avoids us having to do
203 * extra work in the fork/exit path if none of the subsystems need to
206 static int need_forkexit_callback __read_mostly;
208 static void cgroup_offline_fn(struct work_struct *work);
209 static int cgroup_destroy_locked(struct cgroup *cgrp);
210 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
211 struct cftype cfts[], bool is_add);
213 /* convenient tests for these bits */
214 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
216 return test_bit(CGRP_DEAD, &cgrp->flags);
220 * cgroup_is_descendant - test ancestry
221 * @cgrp: the cgroup to be tested
222 * @ancestor: possible ancestor of @cgrp
224 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
225 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
226 * and @ancestor are accessible.
228 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
231 if (cgrp == ancestor)
237 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
239 static int cgroup_is_releasable(const struct cgroup *cgrp)
242 (1 << CGRP_RELEASABLE) |
243 (1 << CGRP_NOTIFY_ON_RELEASE);
244 return (cgrp->flags & bits) == bits;
247 static int notify_on_release(const struct cgroup *cgrp)
249 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
253 * for_each_subsys() allows you to iterate on each subsystem attached to
254 * an active hierarchy
256 #define for_each_subsys(_root, _ss) \
257 list_for_each_entry(_ss, &_root->subsys_list, sibling)
259 /* for_each_active_root() allows you to iterate across the active hierarchies */
260 #define for_each_active_root(_root) \
261 list_for_each_entry(_root, &roots, root_list)
263 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
265 return dentry->d_fsdata;
268 static inline struct cfent *__d_cfe(struct dentry *dentry)
270 return dentry->d_fsdata;
273 static inline struct cftype *__d_cft(struct dentry *dentry)
275 return __d_cfe(dentry)->type;
279 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
280 * @cgrp: the cgroup to be checked for liveness
282 * On success, returns true; the mutex should be later unlocked. On
283 * failure returns false with no lock held.
285 static bool cgroup_lock_live_group(struct cgroup *cgrp)
287 mutex_lock(&cgroup_mutex);
288 if (cgroup_is_dead(cgrp)) {
289 mutex_unlock(&cgroup_mutex);
295 /* the list of cgroups eligible for automatic release. Protected by
296 * release_list_lock */
297 static LIST_HEAD(release_list);
298 static DEFINE_RAW_SPINLOCK(release_list_lock);
299 static void cgroup_release_agent(struct work_struct *work);
300 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
301 static void check_for_release(struct cgroup *cgrp);
304 * A cgroup can be associated with multiple css_sets as different tasks may
305 * belong to different cgroups on different hierarchies. In the other
306 * direction, a css_set is naturally associated with multiple cgroups.
307 * This M:N relationship is represented by the following link structure
308 * which exists for each association and allows traversing the associations
311 struct cgrp_cset_link {
312 /* the cgroup and css_set this link associates */
314 struct css_set *cset;
316 /* list of cgrp_cset_links anchored at cgrp->cset_links */
317 struct list_head cset_link;
319 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
320 struct list_head cgrp_link;
323 /* The default css_set - used by init and its children prior to any
324 * hierarchies being mounted. It contains a pointer to the root state
325 * for each subsystem. Also used to anchor the list of css_sets. Not
326 * reference-counted, to improve performance when child cgroups
327 * haven't been created.
330 static struct css_set init_css_set;
331 static struct cgrp_cset_link init_cgrp_cset_link;
333 static int cgroup_init_idr(struct cgroup_subsys *ss,
334 struct cgroup_subsys_state *css);
336 /* css_set_lock protects the list of css_set objects, and the
337 * chain of tasks off each css_set. Nests outside task->alloc_lock
338 * due to cgroup_iter_start() */
339 static DEFINE_RWLOCK(css_set_lock);
340 static int css_set_count;
343 * hash table for cgroup groups. This improves the performance to find
344 * an existing css_set. This hash doesn't (currently) take into
345 * account cgroups in empty hierarchies.
347 #define CSS_SET_HASH_BITS 7
348 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
350 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
353 unsigned long key = 0UL;
355 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
356 key += (unsigned long)css[i];
357 key = (key >> 16) ^ key;
362 /* We don't maintain the lists running through each css_set to its
363 * task until after the first call to cgroup_iter_start(). This
364 * reduces the fork()/exit() overhead for people who have cgroups
365 * compiled into their kernel but not actually in use */
366 static int use_task_css_set_links __read_mostly;
368 static void __put_css_set(struct css_set *cset, int taskexit)
370 struct cgrp_cset_link *link, *tmp_link;
373 * Ensure that the refcount doesn't hit zero while any readers
374 * can see it. Similar to atomic_dec_and_lock(), but for an
377 if (atomic_add_unless(&cset->refcount, -1, 1))
379 write_lock(&css_set_lock);
380 if (!atomic_dec_and_test(&cset->refcount)) {
381 write_unlock(&css_set_lock);
385 /* This css_set is dead. unlink it and release cgroup refcounts */
386 hash_del(&cset->hlist);
389 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
390 struct cgroup *cgrp = link->cgrp;
392 list_del(&link->cset_link);
393 list_del(&link->cgrp_link);
395 /* @cgrp can't go away while we're holding css_set_lock */
396 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
398 set_bit(CGRP_RELEASABLE, &cgrp->flags);
399 check_for_release(cgrp);
405 write_unlock(&css_set_lock);
406 kfree_rcu(cset, rcu_head);
410 * refcounted get/put for css_set objects
412 static inline void get_css_set(struct css_set *cset)
414 atomic_inc(&cset->refcount);
417 static inline void put_css_set(struct css_set *cset)
419 __put_css_set(cset, 0);
422 static inline void put_css_set_taskexit(struct css_set *cset)
424 __put_css_set(cset, 1);
428 * compare_css_sets - helper function for find_existing_css_set().
429 * @cset: candidate css_set being tested
430 * @old_cset: existing css_set for a task
431 * @new_cgrp: cgroup that's being entered by the task
432 * @template: desired set of css pointers in css_set (pre-calculated)
434 * Returns true if "cg" matches "old_cg" except for the hierarchy
435 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
437 static bool compare_css_sets(struct css_set *cset,
438 struct css_set *old_cset,
439 struct cgroup *new_cgrp,
440 struct cgroup_subsys_state *template[])
442 struct list_head *l1, *l2;
444 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
445 /* Not all subsystems matched */
450 * Compare cgroup pointers in order to distinguish between
451 * different cgroups in heirarchies with no subsystems. We
452 * could get by with just this check alone (and skip the
453 * memcmp above) but on most setups the memcmp check will
454 * avoid the need for this more expensive check on almost all
458 l1 = &cset->cgrp_links;
459 l2 = &old_cset->cgrp_links;
461 struct cgrp_cset_link *link1, *link2;
462 struct cgroup *cgrp1, *cgrp2;
466 /* See if we reached the end - both lists are equal length. */
467 if (l1 == &cset->cgrp_links) {
468 BUG_ON(l2 != &old_cset->cgrp_links);
471 BUG_ON(l2 == &old_cset->cgrp_links);
473 /* Locate the cgroups associated with these links. */
474 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
475 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
478 /* Hierarchies should be linked in the same order. */
479 BUG_ON(cgrp1->root != cgrp2->root);
482 * If this hierarchy is the hierarchy of the cgroup
483 * that's changing, then we need to check that this
484 * css_set points to the new cgroup; if it's any other
485 * hierarchy, then this css_set should point to the
486 * same cgroup as the old css_set.
488 if (cgrp1->root == new_cgrp->root) {
489 if (cgrp1 != new_cgrp)
500 * find_existing_css_set() is a helper for
501 * find_css_set(), and checks to see whether an existing
502 * css_set is suitable.
504 * oldcg: the cgroup group that we're using before the cgroup
507 * cgrp: the cgroup that we're moving into
509 * template: location in which to build the desired set of subsystem
510 * state objects for the new cgroup group
512 static struct css_set *find_existing_css_set(struct css_set *old_cset,
514 struct cgroup_subsys_state *template[])
517 struct cgroupfs_root *root = cgrp->root;
518 struct css_set *cset;
522 * Build the set of subsystem state objects that we want to see in the
523 * new css_set. while subsystems can change globally, the entries here
524 * won't change, so no need for locking.
526 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
527 if (root->subsys_mask & (1UL << i)) {
528 /* Subsystem is in this hierarchy. So we want
529 * the subsystem state from the new
531 template[i] = cgrp->subsys[i];
533 /* Subsystem is not in this hierarchy, so we
534 * don't want to change the subsystem state */
535 template[i] = old_cset->subsys[i];
539 key = css_set_hash(template);
540 hash_for_each_possible(css_set_table, cset, hlist, key) {
541 if (!compare_css_sets(cset, old_cset, cgrp, template))
544 /* This css_set matches what we need */
548 /* No existing cgroup group matched */
552 static void free_cgrp_cset_links(struct list_head *links_to_free)
554 struct cgrp_cset_link *link, *tmp_link;
556 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
557 list_del(&link->cset_link);
563 * allocate_cgrp_cset_links - allocate cgrp_cset_links
564 * @count: the number of links to allocate
565 * @tmp_links: list_head the allocated links are put on
567 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
568 * through ->cset_link. Returns 0 on success or -errno.
570 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
572 struct cgrp_cset_link *link;
575 INIT_LIST_HEAD(tmp_links);
577 for (i = 0; i < count; i++) {
578 link = kzalloc(sizeof(*link), GFP_KERNEL);
580 free_cgrp_cset_links(tmp_links);
583 list_add(&link->cset_link, tmp_links);
589 * link_css_set - a helper function to link a css_set to a cgroup
590 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
591 * @cset: the css_set to be linked
592 * @cgrp: the destination cgroup
594 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
597 struct cgrp_cset_link *link;
599 BUG_ON(list_empty(tmp_links));
600 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
603 list_move(&link->cset_link, &cgrp->cset_links);
605 * Always add links to the tail of the list so that the list
606 * is sorted by order of hierarchy creation
608 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
612 * find_css_set() takes an existing cgroup group and a
613 * cgroup object, and returns a css_set object that's
614 * equivalent to the old group, but with the given cgroup
615 * substituted into the appropriate hierarchy. Must be called with
618 static struct css_set *find_css_set(struct css_set *old_cset,
621 struct css_set *cset;
622 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
623 struct list_head tmp_links;
624 struct cgrp_cset_link *link;
627 /* First see if we already have a cgroup group that matches
629 read_lock(&css_set_lock);
630 cset = find_existing_css_set(old_cset, cgrp, template);
633 read_unlock(&css_set_lock);
638 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
642 /* Allocate all the cgrp_cset_link objects that we'll need */
643 if (allocate_cgrp_cset_links(root_count, &tmp_links) < 0) {
648 atomic_set(&cset->refcount, 1);
649 INIT_LIST_HEAD(&cset->cgrp_links);
650 INIT_LIST_HEAD(&cset->tasks);
651 INIT_HLIST_NODE(&cset->hlist);
653 /* Copy the set of subsystem state objects generated in
654 * find_existing_css_set() */
655 memcpy(cset->subsys, template, sizeof(cset->subsys));
657 write_lock(&css_set_lock);
658 /* Add reference counts and links from the new css_set. */
659 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
660 struct cgroup *c = link->cgrp;
662 if (c->root == cgrp->root)
664 link_css_set(&tmp_links, cset, c);
667 BUG_ON(!list_empty(&tmp_links));
671 /* Add this cgroup group to the hash table */
672 key = css_set_hash(cset->subsys);
673 hash_add(css_set_table, &cset->hlist, key);
675 write_unlock(&css_set_lock);
681 * Return the cgroup for "task" from the given hierarchy. Must be
682 * called with cgroup_mutex held.
684 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
685 struct cgroupfs_root *root)
687 struct css_set *cset;
688 struct cgroup *res = NULL;
690 BUG_ON(!mutex_is_locked(&cgroup_mutex));
691 read_lock(&css_set_lock);
693 * No need to lock the task - since we hold cgroup_mutex the
694 * task can't change groups, so the only thing that can happen
695 * is that it exits and its css is set back to init_css_set.
697 cset = task->cgroups;
698 if (cset == &init_css_set) {
699 res = &root->top_cgroup;
701 struct cgrp_cset_link *link;
703 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
704 struct cgroup *c = link->cgrp;
706 if (c->root == root) {
712 read_unlock(&css_set_lock);
718 * There is one global cgroup mutex. We also require taking
719 * task_lock() when dereferencing a task's cgroup subsys pointers.
720 * See "The task_lock() exception", at the end of this comment.
722 * A task must hold cgroup_mutex to modify cgroups.
724 * Any task can increment and decrement the count field without lock.
725 * So in general, code holding cgroup_mutex can't rely on the count
726 * field not changing. However, if the count goes to zero, then only
727 * cgroup_attach_task() can increment it again. Because a count of zero
728 * means that no tasks are currently attached, therefore there is no
729 * way a task attached to that cgroup can fork (the other way to
730 * increment the count). So code holding cgroup_mutex can safely
731 * assume that if the count is zero, it will stay zero. Similarly, if
732 * a task holds cgroup_mutex on a cgroup with zero count, it
733 * knows that the cgroup won't be removed, as cgroup_rmdir()
736 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
737 * (usually) take cgroup_mutex. These are the two most performance
738 * critical pieces of code here. The exception occurs on cgroup_exit(),
739 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
740 * is taken, and if the cgroup count is zero, a usermode call made
741 * to the release agent with the name of the cgroup (path relative to
742 * the root of cgroup file system) as the argument.
744 * A cgroup can only be deleted if both its 'count' of using tasks
745 * is zero, and its list of 'children' cgroups is empty. Since all
746 * tasks in the system use _some_ cgroup, and since there is always at
747 * least one task in the system (init, pid == 1), therefore, top_cgroup
748 * always has either children cgroups and/or using tasks. So we don't
749 * need a special hack to ensure that top_cgroup cannot be deleted.
751 * The task_lock() exception
753 * The need for this exception arises from the action of
754 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
755 * another. It does so using cgroup_mutex, however there are
756 * several performance critical places that need to reference
757 * task->cgroup without the expense of grabbing a system global
758 * mutex. Therefore except as noted below, when dereferencing or, as
759 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
760 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
761 * the task_struct routinely used for such matters.
763 * P.S. One more locking exception. RCU is used to guard the
764 * update of a tasks cgroup pointer by cgroup_attach_task()
768 * A couple of forward declarations required, due to cyclic reference loop:
769 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
770 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
774 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
775 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
776 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
777 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
778 unsigned long subsys_mask);
779 static const struct inode_operations cgroup_dir_inode_operations;
780 static const struct file_operations proc_cgroupstats_operations;
782 static struct backing_dev_info cgroup_backing_dev_info = {
784 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
787 static int alloc_css_id(struct cgroup_subsys *ss,
788 struct cgroup *parent, struct cgroup *child);
790 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
792 struct inode *inode = new_inode(sb);
795 inode->i_ino = get_next_ino();
796 inode->i_mode = mode;
797 inode->i_uid = current_fsuid();
798 inode->i_gid = current_fsgid();
799 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
800 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
805 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
807 struct cgroup_name *name;
809 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
812 strcpy(name->name, dentry->d_name.name);
816 static void cgroup_free_fn(struct work_struct *work)
818 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
819 struct cgroup_subsys *ss;
821 mutex_lock(&cgroup_mutex);
823 * Release the subsystem state objects.
825 for_each_subsys(cgrp->root, ss)
828 cgrp->root->number_of_cgroups--;
829 mutex_unlock(&cgroup_mutex);
832 * We get a ref to the parent's dentry, and put the ref when
833 * this cgroup is being freed, so it's guaranteed that the
834 * parent won't be destroyed before its children.
836 dput(cgrp->parent->dentry);
838 ida_simple_remove(&cgrp->root->cgroup_ida, cgrp->id);
841 * Drop the active superblock reference that we took when we
842 * created the cgroup. This will free cgrp->root, if we are
843 * holding the last reference to @sb.
845 deactivate_super(cgrp->root->sb);
848 * if we're getting rid of the cgroup, refcount should ensure
849 * that there are no pidlists left.
851 BUG_ON(!list_empty(&cgrp->pidlists));
853 simple_xattrs_free(&cgrp->xattrs);
855 kfree(rcu_dereference_raw(cgrp->name));
859 static void cgroup_free_rcu(struct rcu_head *head)
861 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
863 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
864 schedule_work(&cgrp->destroy_work);
867 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
869 /* is dentry a directory ? if so, kfree() associated cgroup */
870 if (S_ISDIR(inode->i_mode)) {
871 struct cgroup *cgrp = dentry->d_fsdata;
873 BUG_ON(!(cgroup_is_dead(cgrp)));
874 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
876 struct cfent *cfe = __d_cfe(dentry);
877 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
879 WARN_ONCE(!list_empty(&cfe->node) &&
880 cgrp != &cgrp->root->top_cgroup,
881 "cfe still linked for %s\n", cfe->type->name);
882 simple_xattrs_free(&cfe->xattrs);
888 static int cgroup_delete(const struct dentry *d)
893 static void remove_dir(struct dentry *d)
895 struct dentry *parent = dget(d->d_parent);
898 simple_rmdir(parent->d_inode, d);
902 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
906 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
907 lockdep_assert_held(&cgroup_mutex);
910 * If we're doing cleanup due to failure of cgroup_create(),
911 * the corresponding @cfe may not exist.
913 list_for_each_entry(cfe, &cgrp->files, node) {
914 struct dentry *d = cfe->dentry;
916 if (cft && cfe->type != cft)
921 simple_unlink(cgrp->dentry->d_inode, d);
922 list_del_init(&cfe->node);
930 * cgroup_clear_directory - selective removal of base and subsystem files
931 * @dir: directory containing the files
932 * @base_files: true if the base files should be removed
933 * @subsys_mask: mask of the subsystem ids whose files should be removed
935 static void cgroup_clear_directory(struct dentry *dir, bool base_files,
936 unsigned long subsys_mask)
938 struct cgroup *cgrp = __d_cgrp(dir);
939 struct cgroup_subsys *ss;
941 for_each_subsys(cgrp->root, ss) {
942 struct cftype_set *set;
943 if (!test_bit(ss->subsys_id, &subsys_mask))
945 list_for_each_entry(set, &ss->cftsets, node)
946 cgroup_addrm_files(cgrp, NULL, set->cfts, false);
949 while (!list_empty(&cgrp->files))
950 cgroup_rm_file(cgrp, NULL);
955 * NOTE : the dentry must have been dget()'ed
957 static void cgroup_d_remove_dir(struct dentry *dentry)
959 struct dentry *parent;
960 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
962 cgroup_clear_directory(dentry, true, root->subsys_mask);
964 parent = dentry->d_parent;
965 spin_lock(&parent->d_lock);
966 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
967 list_del_init(&dentry->d_u.d_child);
968 spin_unlock(&dentry->d_lock);
969 spin_unlock(&parent->d_lock);
974 * Call with cgroup_mutex held. Drops reference counts on modules, including
975 * any duplicate ones that parse_cgroupfs_options took. If this function
976 * returns an error, no reference counts are touched.
978 static int rebind_subsystems(struct cgroupfs_root *root,
979 unsigned long final_subsys_mask)
981 unsigned long added_mask, removed_mask;
982 struct cgroup *cgrp = &root->top_cgroup;
985 BUG_ON(!mutex_is_locked(&cgroup_mutex));
986 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
988 removed_mask = root->actual_subsys_mask & ~final_subsys_mask;
989 added_mask = final_subsys_mask & ~root->actual_subsys_mask;
990 /* Check that any added subsystems are currently free */
991 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
992 unsigned long bit = 1UL << i;
993 struct cgroup_subsys *ss = subsys[i];
994 if (!(bit & added_mask))
997 * Nobody should tell us to do a subsys that doesn't exist:
998 * parse_cgroupfs_options should catch that case and refcounts
999 * ensure that subsystems won't disappear once selected.
1002 if (ss->root != &rootnode) {
1003 /* Subsystem isn't free */
1008 /* Currently we don't handle adding/removing subsystems when
1009 * any child cgroups exist. This is theoretically supportable
1010 * but involves complex error handling, so it's being left until
1012 if (root->number_of_cgroups > 1)
1015 /* Process each subsystem */
1016 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1017 struct cgroup_subsys *ss = subsys[i];
1018 unsigned long bit = 1UL << i;
1019 if (bit & added_mask) {
1020 /* We're binding this subsystem to this hierarchy */
1022 BUG_ON(cgrp->subsys[i]);
1023 BUG_ON(!dummytop->subsys[i]);
1024 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
1025 cgrp->subsys[i] = dummytop->subsys[i];
1026 cgrp->subsys[i]->cgroup = cgrp;
1027 list_move(&ss->sibling, &root->subsys_list);
1031 /* refcount was already taken, and we're keeping it */
1032 } else if (bit & removed_mask) {
1033 /* We're removing this subsystem */
1035 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1036 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1039 dummytop->subsys[i]->cgroup = dummytop;
1040 cgrp->subsys[i] = NULL;
1041 subsys[i]->root = &rootnode;
1042 list_move(&ss->sibling, &rootnode.subsys_list);
1043 /* subsystem is now free - drop reference on module */
1044 module_put(ss->module);
1045 } else if (bit & final_subsys_mask) {
1046 /* Subsystem state should already exist */
1048 BUG_ON(!cgrp->subsys[i]);
1050 * a refcount was taken, but we already had one, so
1051 * drop the extra reference.
1053 module_put(ss->module);
1054 #ifdef CONFIG_MODULE_UNLOAD
1055 BUG_ON(ss->module && !module_refcount(ss->module));
1058 /* Subsystem state shouldn't exist */
1059 BUG_ON(cgrp->subsys[i]);
1062 root->subsys_mask = root->actual_subsys_mask = final_subsys_mask;
1067 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1069 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1070 struct cgroup_subsys *ss;
1072 mutex_lock(&cgroup_root_mutex);
1073 for_each_subsys(root, ss)
1074 seq_printf(seq, ",%s", ss->name);
1075 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1076 seq_puts(seq, ",sane_behavior");
1077 if (root->flags & CGRP_ROOT_NOPREFIX)
1078 seq_puts(seq, ",noprefix");
1079 if (root->flags & CGRP_ROOT_XATTR)
1080 seq_puts(seq, ",xattr");
1081 if (strlen(root->release_agent_path))
1082 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1083 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1084 seq_puts(seq, ",clone_children");
1085 if (strlen(root->name))
1086 seq_printf(seq, ",name=%s", root->name);
1087 mutex_unlock(&cgroup_root_mutex);
1091 struct cgroup_sb_opts {
1092 unsigned long subsys_mask;
1093 unsigned long flags;
1094 char *release_agent;
1095 bool cpuset_clone_children;
1097 /* User explicitly requested empty subsystem */
1100 struct cgroupfs_root *new_root;
1105 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1106 * with cgroup_mutex held to protect the subsys[] array. This function takes
1107 * refcounts on subsystems to be used, unless it returns error, in which case
1108 * no refcounts are taken.
1110 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1112 char *token, *o = data;
1113 bool all_ss = false, one_ss = false;
1114 unsigned long mask = (unsigned long)-1;
1116 bool module_pin_failed = false;
1118 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1120 #ifdef CONFIG_CPUSETS
1121 mask = ~(1UL << cpuset_subsys_id);
1124 memset(opts, 0, sizeof(*opts));
1126 while ((token = strsep(&o, ",")) != NULL) {
1129 if (!strcmp(token, "none")) {
1130 /* Explicitly have no subsystems */
1134 if (!strcmp(token, "all")) {
1135 /* Mutually exclusive option 'all' + subsystem name */
1141 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1142 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1145 if (!strcmp(token, "noprefix")) {
1146 opts->flags |= CGRP_ROOT_NOPREFIX;
1149 if (!strcmp(token, "clone_children")) {
1150 opts->cpuset_clone_children = true;
1153 if (!strcmp(token, "xattr")) {
1154 opts->flags |= CGRP_ROOT_XATTR;
1157 if (!strncmp(token, "release_agent=", 14)) {
1158 /* Specifying two release agents is forbidden */
1159 if (opts->release_agent)
1161 opts->release_agent =
1162 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1163 if (!opts->release_agent)
1167 if (!strncmp(token, "name=", 5)) {
1168 const char *name = token + 5;
1169 /* Can't specify an empty name */
1172 /* Must match [\w.-]+ */
1173 for (i = 0; i < strlen(name); i++) {
1177 if ((c == '.') || (c == '-') || (c == '_'))
1181 /* Specifying two names is forbidden */
1184 opts->name = kstrndup(name,
1185 MAX_CGROUP_ROOT_NAMELEN - 1,
1193 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1194 struct cgroup_subsys *ss = subsys[i];
1197 if (strcmp(token, ss->name))
1202 /* Mutually exclusive option 'all' + subsystem name */
1205 set_bit(i, &opts->subsys_mask);
1210 if (i == CGROUP_SUBSYS_COUNT)
1215 * If the 'all' option was specified select all the subsystems,
1216 * otherwise if 'none', 'name=' and a subsystem name options
1217 * were not specified, let's default to 'all'
1219 if (all_ss || (!one_ss && !opts->none && !opts->name)) {
1220 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1221 struct cgroup_subsys *ss = subsys[i];
1226 set_bit(i, &opts->subsys_mask);
1230 /* Consistency checks */
1232 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1233 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1235 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1236 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1240 if (opts->cpuset_clone_children) {
1241 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1247 * Option noprefix was introduced just for backward compatibility
1248 * with the old cpuset, so we allow noprefix only if mounting just
1249 * the cpuset subsystem.
1251 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1255 /* Can't specify "none" and some subsystems */
1256 if (opts->subsys_mask && opts->none)
1260 * We either have to specify by name or by subsystems. (So all
1261 * empty hierarchies must have a name).
1263 if (!opts->subsys_mask && !opts->name)
1267 * Grab references on all the modules we'll need, so the subsystems
1268 * don't dance around before rebind_subsystems attaches them. This may
1269 * take duplicate reference counts on a subsystem that's already used,
1270 * but rebind_subsystems handles this case.
1272 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1273 unsigned long bit = 1UL << i;
1275 if (!(bit & opts->subsys_mask))
1277 if (!try_module_get(subsys[i]->module)) {
1278 module_pin_failed = true;
1282 if (module_pin_failed) {
1284 * oops, one of the modules was going away. this means that we
1285 * raced with a module_delete call, and to the user this is
1286 * essentially a "subsystem doesn't exist" case.
1288 for (i--; i >= 0; i--) {
1289 /* drop refcounts only on the ones we took */
1290 unsigned long bit = 1UL << i;
1292 if (!(bit & opts->subsys_mask))
1294 module_put(subsys[i]->module);
1302 static void drop_parsed_module_refcounts(unsigned long subsys_mask)
1305 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1306 unsigned long bit = 1UL << i;
1308 if (!(bit & subsys_mask))
1310 module_put(subsys[i]->module);
1314 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1317 struct cgroupfs_root *root = sb->s_fs_info;
1318 struct cgroup *cgrp = &root->top_cgroup;
1319 struct cgroup_sb_opts opts;
1320 unsigned long added_mask, removed_mask;
1322 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1323 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1327 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1328 mutex_lock(&cgroup_mutex);
1329 mutex_lock(&cgroup_root_mutex);
1331 /* See what subsystems are wanted */
1332 ret = parse_cgroupfs_options(data, &opts);
1336 if (opts.subsys_mask != root->actual_subsys_mask || opts.release_agent)
1337 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1338 task_tgid_nr(current), current->comm);
1340 added_mask = opts.subsys_mask & ~root->subsys_mask;
1341 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1343 /* Don't allow flags or name to change at remount */
1344 if (opts.flags != root->flags ||
1345 (opts.name && strcmp(opts.name, root->name))) {
1347 drop_parsed_module_refcounts(opts.subsys_mask);
1352 * Clear out the files of subsystems that should be removed, do
1353 * this before rebind_subsystems, since rebind_subsystems may
1354 * change this hierarchy's subsys_list.
1356 cgroup_clear_directory(cgrp->dentry, false, removed_mask);
1358 ret = rebind_subsystems(root, opts.subsys_mask);
1360 /* rebind_subsystems failed, re-populate the removed files */
1361 cgroup_populate_dir(cgrp, false, removed_mask);
1362 drop_parsed_module_refcounts(opts.subsys_mask);
1366 /* re-populate subsystem files */
1367 cgroup_populate_dir(cgrp, false, added_mask);
1369 if (opts.release_agent)
1370 strcpy(root->release_agent_path, opts.release_agent);
1372 kfree(opts.release_agent);
1374 mutex_unlock(&cgroup_root_mutex);
1375 mutex_unlock(&cgroup_mutex);
1376 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1380 static const struct super_operations cgroup_ops = {
1381 .statfs = simple_statfs,
1382 .drop_inode = generic_delete_inode,
1383 .show_options = cgroup_show_options,
1384 .remount_fs = cgroup_remount,
1387 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1389 INIT_LIST_HEAD(&cgrp->sibling);
1390 INIT_LIST_HEAD(&cgrp->children);
1391 INIT_LIST_HEAD(&cgrp->files);
1392 INIT_LIST_HEAD(&cgrp->cset_links);
1393 INIT_LIST_HEAD(&cgrp->allcg_node);
1394 INIT_LIST_HEAD(&cgrp->release_list);
1395 INIT_LIST_HEAD(&cgrp->pidlists);
1396 mutex_init(&cgrp->pidlist_mutex);
1397 INIT_LIST_HEAD(&cgrp->event_list);
1398 spin_lock_init(&cgrp->event_list_lock);
1399 simple_xattrs_init(&cgrp->xattrs);
1402 static void init_cgroup_root(struct cgroupfs_root *root)
1404 struct cgroup *cgrp = &root->top_cgroup;
1406 INIT_LIST_HEAD(&root->subsys_list);
1407 INIT_LIST_HEAD(&root->root_list);
1408 INIT_LIST_HEAD(&root->allcg_list);
1409 root->number_of_cgroups = 1;
1411 cgrp->name = &root_cgroup_name;
1412 init_cgroup_housekeeping(cgrp);
1413 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
1416 static int cgroup_init_root_id(struct cgroupfs_root *root)
1420 lockdep_assert_held(&cgroup_mutex);
1421 lockdep_assert_held(&cgroup_root_mutex);
1423 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 2, 0, GFP_KERNEL);
1427 root->hierarchy_id = id;
1431 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1433 lockdep_assert_held(&cgroup_mutex);
1434 lockdep_assert_held(&cgroup_root_mutex);
1436 if (root->hierarchy_id) {
1437 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1438 root->hierarchy_id = 0;
1442 static int cgroup_test_super(struct super_block *sb, void *data)
1444 struct cgroup_sb_opts *opts = data;
1445 struct cgroupfs_root *root = sb->s_fs_info;
1447 /* If we asked for a name then it must match */
1448 if (opts->name && strcmp(opts->name, root->name))
1452 * If we asked for subsystems (or explicitly for no
1453 * subsystems) then they must match
1455 if ((opts->subsys_mask || opts->none)
1456 && (opts->subsys_mask != root->subsys_mask))
1462 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1464 struct cgroupfs_root *root;
1466 if (!opts->subsys_mask && !opts->none)
1469 root = kzalloc(sizeof(*root), GFP_KERNEL);
1471 return ERR_PTR(-ENOMEM);
1473 init_cgroup_root(root);
1475 root->subsys_mask = opts->subsys_mask;
1476 root->flags = opts->flags;
1477 ida_init(&root->cgroup_ida);
1478 if (opts->release_agent)
1479 strcpy(root->release_agent_path, opts->release_agent);
1481 strcpy(root->name, opts->name);
1482 if (opts->cpuset_clone_children)
1483 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1487 static void cgroup_free_root(struct cgroupfs_root *root)
1490 /* hierarhcy ID shoulid already have been released */
1491 WARN_ON_ONCE(root->hierarchy_id);
1493 ida_destroy(&root->cgroup_ida);
1498 static int cgroup_set_super(struct super_block *sb, void *data)
1501 struct cgroup_sb_opts *opts = data;
1503 /* If we don't have a new root, we can't set up a new sb */
1504 if (!opts->new_root)
1507 BUG_ON(!opts->subsys_mask && !opts->none);
1509 ret = set_anon_super(sb, NULL);
1513 sb->s_fs_info = opts->new_root;
1514 opts->new_root->sb = sb;
1516 sb->s_blocksize = PAGE_CACHE_SIZE;
1517 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1518 sb->s_magic = CGROUP_SUPER_MAGIC;
1519 sb->s_op = &cgroup_ops;
1524 static int cgroup_get_rootdir(struct super_block *sb)
1526 static const struct dentry_operations cgroup_dops = {
1527 .d_iput = cgroup_diput,
1528 .d_delete = cgroup_delete,
1531 struct inode *inode =
1532 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1537 inode->i_fop = &simple_dir_operations;
1538 inode->i_op = &cgroup_dir_inode_operations;
1539 /* directories start off with i_nlink == 2 (for "." entry) */
1541 sb->s_root = d_make_root(inode);
1544 /* for everything else we want ->d_op set */
1545 sb->s_d_op = &cgroup_dops;
1549 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1550 int flags, const char *unused_dev_name,
1553 struct cgroup_sb_opts opts;
1554 struct cgroupfs_root *root;
1556 struct super_block *sb;
1557 struct cgroupfs_root *new_root;
1558 struct inode *inode;
1560 /* First find the desired set of subsystems */
1561 mutex_lock(&cgroup_mutex);
1562 ret = parse_cgroupfs_options(data, &opts);
1563 mutex_unlock(&cgroup_mutex);
1568 * Allocate a new cgroup root. We may not need it if we're
1569 * reusing an existing hierarchy.
1571 new_root = cgroup_root_from_opts(&opts);
1572 if (IS_ERR(new_root)) {
1573 ret = PTR_ERR(new_root);
1576 opts.new_root = new_root;
1578 /* Locate an existing or new sb for this hierarchy */
1579 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1582 cgroup_free_root(opts.new_root);
1586 root = sb->s_fs_info;
1588 if (root == opts.new_root) {
1589 /* We used the new root structure, so this is a new hierarchy */
1590 struct list_head tmp_links;
1591 struct cgroup *root_cgrp = &root->top_cgroup;
1592 struct cgroupfs_root *existing_root;
1593 const struct cred *cred;
1595 struct css_set *cset;
1597 BUG_ON(sb->s_root != NULL);
1599 ret = cgroup_get_rootdir(sb);
1601 goto drop_new_super;
1602 inode = sb->s_root->d_inode;
1604 mutex_lock(&inode->i_mutex);
1605 mutex_lock(&cgroup_mutex);
1606 mutex_lock(&cgroup_root_mutex);
1608 /* Check for name clashes with existing mounts */
1610 if (strlen(root->name))
1611 for_each_active_root(existing_root)
1612 if (!strcmp(existing_root->name, root->name))
1616 * We're accessing css_set_count without locking
1617 * css_set_lock here, but that's OK - it can only be
1618 * increased by someone holding cgroup_lock, and
1619 * that's us. The worst that can happen is that we
1620 * have some link structures left over
1622 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1626 ret = cgroup_init_root_id(root);
1630 ret = rebind_subsystems(root, root->subsys_mask);
1631 if (ret == -EBUSY) {
1632 free_cgrp_cset_links(&tmp_links);
1636 * There must be no failure case after here, since rebinding
1637 * takes care of subsystems' refcounts, which are explicitly
1638 * dropped in the failure exit path.
1641 /* EBUSY should be the only error here */
1644 list_add(&root->root_list, &roots);
1647 sb->s_root->d_fsdata = root_cgrp;
1648 root->top_cgroup.dentry = sb->s_root;
1650 /* Link the top cgroup in this hierarchy into all
1651 * the css_set objects */
1652 write_lock(&css_set_lock);
1653 hash_for_each(css_set_table, i, cset, hlist)
1654 link_css_set(&tmp_links, cset, root_cgrp);
1655 write_unlock(&css_set_lock);
1657 free_cgrp_cset_links(&tmp_links);
1659 BUG_ON(!list_empty(&root_cgrp->children));
1660 BUG_ON(root->number_of_cgroups != 1);
1662 cred = override_creds(&init_cred);
1663 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1665 mutex_unlock(&cgroup_root_mutex);
1666 mutex_unlock(&cgroup_mutex);
1667 mutex_unlock(&inode->i_mutex);
1670 * We re-used an existing hierarchy - the new root (if
1671 * any) is not needed
1673 cgroup_free_root(opts.new_root);
1675 if (root->flags != opts.flags) {
1676 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1677 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1679 goto drop_new_super;
1681 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1685 /* no subsys rebinding, so refcounts don't change */
1686 drop_parsed_module_refcounts(opts.subsys_mask);
1689 kfree(opts.release_agent);
1691 return dget(sb->s_root);
1694 cgroup_exit_root_id(root);
1695 mutex_unlock(&cgroup_root_mutex);
1696 mutex_unlock(&cgroup_mutex);
1697 mutex_unlock(&inode->i_mutex);
1699 deactivate_locked_super(sb);
1701 drop_parsed_module_refcounts(opts.subsys_mask);
1703 kfree(opts.release_agent);
1705 return ERR_PTR(ret);
1708 static void cgroup_kill_sb(struct super_block *sb) {
1709 struct cgroupfs_root *root = sb->s_fs_info;
1710 struct cgroup *cgrp = &root->top_cgroup;
1711 struct cgrp_cset_link *link, *tmp_link;
1716 BUG_ON(root->number_of_cgroups != 1);
1717 BUG_ON(!list_empty(&cgrp->children));
1719 mutex_lock(&cgroup_mutex);
1720 mutex_lock(&cgroup_root_mutex);
1722 /* Rebind all subsystems back to the default hierarchy */
1723 ret = rebind_subsystems(root, 0);
1724 /* Shouldn't be able to fail ... */
1728 * Release all the links from cset_links to this hierarchy's
1731 write_lock(&css_set_lock);
1733 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1734 list_del(&link->cset_link);
1735 list_del(&link->cgrp_link);
1738 write_unlock(&css_set_lock);
1740 if (!list_empty(&root->root_list)) {
1741 list_del(&root->root_list);
1745 cgroup_exit_root_id(root);
1747 mutex_unlock(&cgroup_root_mutex);
1748 mutex_unlock(&cgroup_mutex);
1750 simple_xattrs_free(&cgrp->xattrs);
1752 kill_litter_super(sb);
1753 cgroup_free_root(root);
1756 static struct file_system_type cgroup_fs_type = {
1758 .mount = cgroup_mount,
1759 .kill_sb = cgroup_kill_sb,
1762 static struct kobject *cgroup_kobj;
1765 * cgroup_path - generate the path of a cgroup
1766 * @cgrp: the cgroup in question
1767 * @buf: the buffer to write the path into
1768 * @buflen: the length of the buffer
1770 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1772 * We can't generate cgroup path using dentry->d_name, as accessing
1773 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1774 * inode's i_mutex, while on the other hand cgroup_path() can be called
1775 * with some irq-safe spinlocks held.
1777 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1779 int ret = -ENAMETOOLONG;
1782 if (!cgrp->parent) {
1783 if (strlcpy(buf, "/", buflen) >= buflen)
1784 return -ENAMETOOLONG;
1788 start = buf + buflen - 1;
1793 const char *name = cgroup_name(cgrp);
1797 if ((start -= len) < buf)
1799 memcpy(start, name, len);
1805 cgrp = cgrp->parent;
1806 } while (cgrp->parent);
1808 memmove(buf, start, buf + buflen - start);
1813 EXPORT_SYMBOL_GPL(cgroup_path);
1816 * task_cgroup_path_from_hierarchy - cgroup path of a task on a hierarchy
1817 * @task: target task
1818 * @hierarchy_id: the hierarchy to look up @task's cgroup from
1819 * @buf: the buffer to write the path into
1820 * @buflen: the length of the buffer
1822 * Determine @task's cgroup on the hierarchy specified by @hierarchy_id and
1823 * copy its path into @buf. This function grabs cgroup_mutex and shouldn't
1824 * be used inside locks used by cgroup controller callbacks.
1826 int task_cgroup_path_from_hierarchy(struct task_struct *task, int hierarchy_id,
1827 char *buf, size_t buflen)
1829 struct cgroupfs_root *root;
1830 struct cgroup *cgrp = NULL;
1833 mutex_lock(&cgroup_mutex);
1835 root = idr_find(&cgroup_hierarchy_idr, hierarchy_id);
1837 cgrp = task_cgroup_from_root(task, root);
1838 ret = cgroup_path(cgrp, buf, buflen);
1841 mutex_unlock(&cgroup_mutex);
1845 EXPORT_SYMBOL_GPL(task_cgroup_path_from_hierarchy);
1848 * Control Group taskset
1850 struct task_and_cgroup {
1851 struct task_struct *task;
1852 struct cgroup *cgrp;
1856 struct cgroup_taskset {
1857 struct task_and_cgroup single;
1858 struct flex_array *tc_array;
1861 struct cgroup *cur_cgrp;
1865 * cgroup_taskset_first - reset taskset and return the first task
1866 * @tset: taskset of interest
1868 * @tset iteration is initialized and the first task is returned.
1870 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1872 if (tset->tc_array) {
1874 return cgroup_taskset_next(tset);
1876 tset->cur_cgrp = tset->single.cgrp;
1877 return tset->single.task;
1880 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1883 * cgroup_taskset_next - iterate to the next task in taskset
1884 * @tset: taskset of interest
1886 * Return the next task in @tset. Iteration must have been initialized
1887 * with cgroup_taskset_first().
1889 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1891 struct task_and_cgroup *tc;
1893 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1896 tc = flex_array_get(tset->tc_array, tset->idx++);
1897 tset->cur_cgrp = tc->cgrp;
1900 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1903 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1904 * @tset: taskset of interest
1906 * Return the cgroup for the current (last returned) task of @tset. This
1907 * function must be preceded by either cgroup_taskset_first() or
1908 * cgroup_taskset_next().
1910 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1912 return tset->cur_cgrp;
1914 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1917 * cgroup_taskset_size - return the number of tasks in taskset
1918 * @tset: taskset of interest
1920 int cgroup_taskset_size(struct cgroup_taskset *tset)
1922 return tset->tc_array ? tset->tc_array_len : 1;
1924 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1928 * cgroup_task_migrate - move a task from one cgroup to another.
1930 * Must be called with cgroup_mutex and threadgroup locked.
1932 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1933 struct task_struct *tsk,
1934 struct css_set *new_cset)
1936 struct css_set *old_cset;
1939 * We are synchronized through threadgroup_lock() against PF_EXITING
1940 * setting such that we can't race against cgroup_exit() changing the
1941 * css_set to init_css_set and dropping the old one.
1943 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1944 old_cset = tsk->cgroups;
1947 rcu_assign_pointer(tsk->cgroups, new_cset);
1950 /* Update the css_set linked lists if we're using them */
1951 write_lock(&css_set_lock);
1952 if (!list_empty(&tsk->cg_list))
1953 list_move(&tsk->cg_list, &new_cset->tasks);
1954 write_unlock(&css_set_lock);
1957 * We just gained a reference on old_cset by taking it from the
1958 * task. As trading it for new_cset is protected by cgroup_mutex,
1959 * we're safe to drop it here; it will be freed under RCU.
1961 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1962 put_css_set(old_cset);
1966 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1967 * @cgrp: the cgroup to attach to
1968 * @tsk: the task or the leader of the threadgroup to be attached
1969 * @threadgroup: attach the whole threadgroup?
1971 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1972 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1974 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1977 int retval, i, group_size;
1978 struct cgroup_subsys *ss, *failed_ss = NULL;
1979 struct cgroupfs_root *root = cgrp->root;
1980 /* threadgroup list cursor and array */
1981 struct task_struct *leader = tsk;
1982 struct task_and_cgroup *tc;
1983 struct flex_array *group;
1984 struct cgroup_taskset tset = { };
1987 * step 0: in order to do expensive, possibly blocking operations for
1988 * every thread, we cannot iterate the thread group list, since it needs
1989 * rcu or tasklist locked. instead, build an array of all threads in the
1990 * group - group_rwsem prevents new threads from appearing, and if
1991 * threads exit, this will just be an over-estimate.
1994 group_size = get_nr_threads(tsk);
1997 /* flex_array supports very large thread-groups better than kmalloc. */
1998 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2001 /* pre-allocate to guarantee space while iterating in rcu read-side. */
2002 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
2004 goto out_free_group_list;
2008 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2009 * already PF_EXITING could be freed from underneath us unless we
2010 * take an rcu_read_lock.
2014 struct task_and_cgroup ent;
2016 /* @tsk either already exited or can't exit until the end */
2017 if (tsk->flags & PF_EXITING)
2020 /* as per above, nr_threads may decrease, but not increase. */
2021 BUG_ON(i >= group_size);
2023 ent.cgrp = task_cgroup_from_root(tsk, root);
2024 /* nothing to do if this task is already in the cgroup */
2025 if (ent.cgrp == cgrp)
2028 * saying GFP_ATOMIC has no effect here because we did prealloc
2029 * earlier, but it's good form to communicate our expectations.
2031 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2032 BUG_ON(retval != 0);
2037 } while_each_thread(leader, tsk);
2039 /* remember the number of threads in the array for later. */
2041 tset.tc_array = group;
2042 tset.tc_array_len = group_size;
2044 /* methods shouldn't be called if no task is actually migrating */
2047 goto out_free_group_list;
2050 * step 1: check that we can legitimately attach to the cgroup.
2052 for_each_subsys(root, ss) {
2053 if (ss->can_attach) {
2054 retval = ss->can_attach(cgrp, &tset);
2057 goto out_cancel_attach;
2063 * step 2: make sure css_sets exist for all threads to be migrated.
2064 * we use find_css_set, which allocates a new one if necessary.
2066 for (i = 0; i < group_size; i++) {
2067 tc = flex_array_get(group, i);
2068 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2071 goto out_put_css_set_refs;
2076 * step 3: now that we're guaranteed success wrt the css_sets,
2077 * proceed to move all tasks to the new cgroup. There are no
2078 * failure cases after here, so this is the commit point.
2080 for (i = 0; i < group_size; i++) {
2081 tc = flex_array_get(group, i);
2082 cgroup_task_migrate(tc->cgrp, tc->task, tc->cg);
2084 /* nothing is sensitive to fork() after this point. */
2087 * step 4: do subsystem attach callbacks.
2089 for_each_subsys(root, ss) {
2091 ss->attach(cgrp, &tset);
2095 * step 5: success! and cleanup
2098 out_put_css_set_refs:
2100 for (i = 0; i < group_size; i++) {
2101 tc = flex_array_get(group, i);
2104 put_css_set(tc->cg);
2109 for_each_subsys(root, ss) {
2110 if (ss == failed_ss)
2112 if (ss->cancel_attach)
2113 ss->cancel_attach(cgrp, &tset);
2116 out_free_group_list:
2117 flex_array_free(group);
2122 * Find the task_struct of the task to attach by vpid and pass it along to the
2123 * function to attach either it or all tasks in its threadgroup. Will lock
2124 * cgroup_mutex and threadgroup; may take task_lock of task.
2126 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2128 struct task_struct *tsk;
2129 const struct cred *cred = current_cred(), *tcred;
2132 if (!cgroup_lock_live_group(cgrp))
2138 tsk = find_task_by_vpid(pid);
2142 goto out_unlock_cgroup;
2145 * even if we're attaching all tasks in the thread group, we
2146 * only need to check permissions on one of them.
2148 tcred = __task_cred(tsk);
2149 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2150 !uid_eq(cred->euid, tcred->uid) &&
2151 !uid_eq(cred->euid, tcred->suid)) {
2154 goto out_unlock_cgroup;
2160 tsk = tsk->group_leader;
2163 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2164 * trapped in a cpuset, or RT worker may be born in a cgroup
2165 * with no rt_runtime allocated. Just say no.
2167 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2170 goto out_unlock_cgroup;
2173 get_task_struct(tsk);
2176 threadgroup_lock(tsk);
2178 if (!thread_group_leader(tsk)) {
2180 * a race with de_thread from another thread's exec()
2181 * may strip us of our leadership, if this happens,
2182 * there is no choice but to throw this task away and
2183 * try again; this is
2184 * "double-double-toil-and-trouble-check locking".
2186 threadgroup_unlock(tsk);
2187 put_task_struct(tsk);
2188 goto retry_find_task;
2192 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2194 threadgroup_unlock(tsk);
2196 put_task_struct(tsk);
2198 mutex_unlock(&cgroup_mutex);
2203 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2204 * @from: attach to all cgroups of a given task
2205 * @tsk: the task to be attached
2207 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2209 struct cgroupfs_root *root;
2212 mutex_lock(&cgroup_mutex);
2213 for_each_active_root(root) {
2214 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2216 retval = cgroup_attach_task(from_cg, tsk, false);
2220 mutex_unlock(&cgroup_mutex);
2224 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2226 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2228 return attach_task_by_pid(cgrp, pid, false);
2231 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2233 return attach_task_by_pid(cgrp, tgid, true);
2236 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2239 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2240 if (strlen(buffer) >= PATH_MAX)
2242 if (!cgroup_lock_live_group(cgrp))
2244 mutex_lock(&cgroup_root_mutex);
2245 strcpy(cgrp->root->release_agent_path, buffer);
2246 mutex_unlock(&cgroup_root_mutex);
2247 mutex_unlock(&cgroup_mutex);
2251 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2252 struct seq_file *seq)
2254 if (!cgroup_lock_live_group(cgrp))
2256 seq_puts(seq, cgrp->root->release_agent_path);
2257 seq_putc(seq, '\n');
2258 mutex_unlock(&cgroup_mutex);
2262 static int cgroup_sane_behavior_show(struct cgroup *cgrp, struct cftype *cft,
2263 struct seq_file *seq)
2265 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2269 /* A buffer size big enough for numbers or short strings */
2270 #define CGROUP_LOCAL_BUFFER_SIZE 64
2272 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2274 const char __user *userbuf,
2275 size_t nbytes, loff_t *unused_ppos)
2277 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2283 if (nbytes >= sizeof(buffer))
2285 if (copy_from_user(buffer, userbuf, nbytes))
2288 buffer[nbytes] = 0; /* nul-terminate */
2289 if (cft->write_u64) {
2290 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2293 retval = cft->write_u64(cgrp, cft, val);
2295 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2298 retval = cft->write_s64(cgrp, cft, val);
2305 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2307 const char __user *userbuf,
2308 size_t nbytes, loff_t *unused_ppos)
2310 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2312 size_t max_bytes = cft->max_write_len;
2313 char *buffer = local_buffer;
2316 max_bytes = sizeof(local_buffer) - 1;
2317 if (nbytes >= max_bytes)
2319 /* Allocate a dynamic buffer if we need one */
2320 if (nbytes >= sizeof(local_buffer)) {
2321 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2325 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2330 buffer[nbytes] = 0; /* nul-terminate */
2331 retval = cft->write_string(cgrp, cft, strstrip(buffer));
2335 if (buffer != local_buffer)
2340 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2341 size_t nbytes, loff_t *ppos)
2343 struct cftype *cft = __d_cft(file->f_dentry);
2344 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2346 if (cgroup_is_dead(cgrp))
2349 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2350 if (cft->write_u64 || cft->write_s64)
2351 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2352 if (cft->write_string)
2353 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2355 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2356 return ret ? ret : nbytes;
2361 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2363 char __user *buf, size_t nbytes,
2366 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2367 u64 val = cft->read_u64(cgrp, cft);
2368 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2370 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2373 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2375 char __user *buf, size_t nbytes,
2378 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2379 s64 val = cft->read_s64(cgrp, cft);
2380 int len = sprintf(tmp, "%lld\n", (long long) val);
2382 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2385 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2386 size_t nbytes, loff_t *ppos)
2388 struct cftype *cft = __d_cft(file->f_dentry);
2389 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2391 if (cgroup_is_dead(cgrp))
2395 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2397 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2399 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2404 * seqfile ops/methods for returning structured data. Currently just
2405 * supports string->u64 maps, but can be extended in future.
2408 struct cgroup_seqfile_state {
2410 struct cgroup *cgroup;
2413 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2415 struct seq_file *sf = cb->state;
2416 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2419 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2421 struct cgroup_seqfile_state *state = m->private;
2422 struct cftype *cft = state->cft;
2423 if (cft->read_map) {
2424 struct cgroup_map_cb cb = {
2425 .fill = cgroup_map_add,
2428 return cft->read_map(state->cgroup, cft, &cb);
2430 return cft->read_seq_string(state->cgroup, cft, m);
2433 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2435 struct seq_file *seq = file->private_data;
2436 kfree(seq->private);
2437 return single_release(inode, file);
2440 static const struct file_operations cgroup_seqfile_operations = {
2442 .write = cgroup_file_write,
2443 .llseek = seq_lseek,
2444 .release = cgroup_seqfile_release,
2447 static int cgroup_file_open(struct inode *inode, struct file *file)
2452 err = generic_file_open(inode, file);
2455 cft = __d_cft(file->f_dentry);
2457 if (cft->read_map || cft->read_seq_string) {
2458 struct cgroup_seqfile_state *state;
2460 state = kzalloc(sizeof(*state), GFP_USER);
2465 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2466 file->f_op = &cgroup_seqfile_operations;
2467 err = single_open(file, cgroup_seqfile_show, state);
2470 } else if (cft->open)
2471 err = cft->open(inode, file);
2478 static int cgroup_file_release(struct inode *inode, struct file *file)
2480 struct cftype *cft = __d_cft(file->f_dentry);
2482 return cft->release(inode, file);
2487 * cgroup_rename - Only allow simple rename of directories in place.
2489 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2490 struct inode *new_dir, struct dentry *new_dentry)
2493 struct cgroup_name *name, *old_name;
2494 struct cgroup *cgrp;
2497 * It's convinient to use parent dir's i_mutex to protected
2500 lockdep_assert_held(&old_dir->i_mutex);
2502 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2504 if (new_dentry->d_inode)
2506 if (old_dir != new_dir)
2509 cgrp = __d_cgrp(old_dentry);
2512 * This isn't a proper migration and its usefulness is very
2513 * limited. Disallow if sane_behavior.
2515 if (cgroup_sane_behavior(cgrp))
2518 name = cgroup_alloc_name(new_dentry);
2522 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2528 old_name = cgrp->name;
2529 rcu_assign_pointer(cgrp->name, name);
2531 kfree_rcu(old_name, rcu_head);
2535 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2537 if (S_ISDIR(dentry->d_inode->i_mode))
2538 return &__d_cgrp(dentry)->xattrs;
2540 return &__d_cfe(dentry)->xattrs;
2543 static inline int xattr_enabled(struct dentry *dentry)
2545 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2546 return root->flags & CGRP_ROOT_XATTR;
2549 static bool is_valid_xattr(const char *name)
2551 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2552 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2557 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2558 const void *val, size_t size, int flags)
2560 if (!xattr_enabled(dentry))
2562 if (!is_valid_xattr(name))
2564 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2567 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2569 if (!xattr_enabled(dentry))
2571 if (!is_valid_xattr(name))
2573 return simple_xattr_remove(__d_xattrs(dentry), name);
2576 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2577 void *buf, size_t size)
2579 if (!xattr_enabled(dentry))
2581 if (!is_valid_xattr(name))
2583 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2586 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2588 if (!xattr_enabled(dentry))
2590 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2593 static const struct file_operations cgroup_file_operations = {
2594 .read = cgroup_file_read,
2595 .write = cgroup_file_write,
2596 .llseek = generic_file_llseek,
2597 .open = cgroup_file_open,
2598 .release = cgroup_file_release,
2601 static const struct inode_operations cgroup_file_inode_operations = {
2602 .setxattr = cgroup_setxattr,
2603 .getxattr = cgroup_getxattr,
2604 .listxattr = cgroup_listxattr,
2605 .removexattr = cgroup_removexattr,
2608 static const struct inode_operations cgroup_dir_inode_operations = {
2609 .lookup = cgroup_lookup,
2610 .mkdir = cgroup_mkdir,
2611 .rmdir = cgroup_rmdir,
2612 .rename = cgroup_rename,
2613 .setxattr = cgroup_setxattr,
2614 .getxattr = cgroup_getxattr,
2615 .listxattr = cgroup_listxattr,
2616 .removexattr = cgroup_removexattr,
2619 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2621 if (dentry->d_name.len > NAME_MAX)
2622 return ERR_PTR(-ENAMETOOLONG);
2623 d_add(dentry, NULL);
2628 * Check if a file is a control file
2630 static inline struct cftype *__file_cft(struct file *file)
2632 if (file_inode(file)->i_fop != &cgroup_file_operations)
2633 return ERR_PTR(-EINVAL);
2634 return __d_cft(file->f_dentry);
2637 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2638 struct super_block *sb)
2640 struct inode *inode;
2644 if (dentry->d_inode)
2647 inode = cgroup_new_inode(mode, sb);
2651 if (S_ISDIR(mode)) {
2652 inode->i_op = &cgroup_dir_inode_operations;
2653 inode->i_fop = &simple_dir_operations;
2655 /* start off with i_nlink == 2 (for "." entry) */
2657 inc_nlink(dentry->d_parent->d_inode);
2660 * Control reaches here with cgroup_mutex held.
2661 * @inode->i_mutex should nest outside cgroup_mutex but we
2662 * want to populate it immediately without releasing
2663 * cgroup_mutex. As @inode isn't visible to anyone else
2664 * yet, trylock will always succeed without affecting
2667 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2668 } else if (S_ISREG(mode)) {
2670 inode->i_fop = &cgroup_file_operations;
2671 inode->i_op = &cgroup_file_inode_operations;
2673 d_instantiate(dentry, inode);
2674 dget(dentry); /* Extra count - pin the dentry in core */
2679 * cgroup_file_mode - deduce file mode of a control file
2680 * @cft: the control file in question
2682 * returns cft->mode if ->mode is not 0
2683 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2684 * returns S_IRUGO if it has only a read handler
2685 * returns S_IWUSR if it has only a write hander
2687 static umode_t cgroup_file_mode(const struct cftype *cft)
2694 if (cft->read || cft->read_u64 || cft->read_s64 ||
2695 cft->read_map || cft->read_seq_string)
2698 if (cft->write || cft->write_u64 || cft->write_s64 ||
2699 cft->write_string || cft->trigger)
2705 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2708 struct dentry *dir = cgrp->dentry;
2709 struct cgroup *parent = __d_cgrp(dir);
2710 struct dentry *dentry;
2714 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2716 if (subsys && !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2717 strcpy(name, subsys->name);
2720 strcat(name, cft->name);
2722 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2724 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2728 dentry = lookup_one_len(name, dir, strlen(name));
2729 if (IS_ERR(dentry)) {
2730 error = PTR_ERR(dentry);
2734 cfe->type = (void *)cft;
2735 cfe->dentry = dentry;
2736 dentry->d_fsdata = cfe;
2737 simple_xattrs_init(&cfe->xattrs);
2739 mode = cgroup_file_mode(cft);
2740 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2742 list_add_tail(&cfe->node, &parent->files);
2751 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2752 struct cftype cfts[], bool is_add)
2757 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2758 /* does cft->flags tell us to skip this file on @cgrp? */
2759 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2761 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2763 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2767 err = cgroup_add_file(cgrp, subsys, cft);
2769 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2773 cgroup_rm_file(cgrp, cft);
2779 static DEFINE_MUTEX(cgroup_cft_mutex);
2781 static void cgroup_cfts_prepare(void)
2782 __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2785 * Thanks to the entanglement with vfs inode locking, we can't walk
2786 * the existing cgroups under cgroup_mutex and create files.
2787 * Instead, we increment reference on all cgroups and build list of
2788 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2789 * exclusive access to the field.
2791 mutex_lock(&cgroup_cft_mutex);
2792 mutex_lock(&cgroup_mutex);
2795 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2796 struct cftype *cfts, bool is_add)
2797 __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2800 struct cgroup *cgrp, *n;
2801 struct super_block *sb = ss->root->sb;
2803 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2804 if (cfts && ss->root != &rootnode &&
2805 atomic_inc_not_zero(sb->s_active)) {
2806 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2808 list_add_tail(&cgrp->cft_q_node, &pending);
2814 mutex_unlock(&cgroup_mutex);
2817 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2818 * files for all cgroups which were created before.
2820 list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2821 struct inode *inode = cgrp->dentry->d_inode;
2823 mutex_lock(&inode->i_mutex);
2824 mutex_lock(&cgroup_mutex);
2825 if (!cgroup_is_dead(cgrp))
2826 cgroup_addrm_files(cgrp, ss, cfts, is_add);
2827 mutex_unlock(&cgroup_mutex);
2828 mutex_unlock(&inode->i_mutex);
2830 list_del_init(&cgrp->cft_q_node);
2835 deactivate_super(sb);
2837 mutex_unlock(&cgroup_cft_mutex);
2841 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2842 * @ss: target cgroup subsystem
2843 * @cfts: zero-length name terminated array of cftypes
2845 * Register @cfts to @ss. Files described by @cfts are created for all
2846 * existing cgroups to which @ss is attached and all future cgroups will
2847 * have them too. This function can be called anytime whether @ss is
2850 * Returns 0 on successful registration, -errno on failure. Note that this
2851 * function currently returns 0 as long as @cfts registration is successful
2852 * even if some file creation attempts on existing cgroups fail.
2854 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2856 struct cftype_set *set;
2858 set = kzalloc(sizeof(*set), GFP_KERNEL);
2862 cgroup_cfts_prepare();
2864 list_add_tail(&set->node, &ss->cftsets);
2865 cgroup_cfts_commit(ss, cfts, true);
2869 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2872 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2873 * @ss: target cgroup subsystem
2874 * @cfts: zero-length name terminated array of cftypes
2876 * Unregister @cfts from @ss. Files described by @cfts are removed from
2877 * all existing cgroups to which @ss is attached and all future cgroups
2878 * won't have them either. This function can be called anytime whether @ss
2879 * is attached or not.
2881 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2882 * registered with @ss.
2884 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2886 struct cftype_set *set;
2888 cgroup_cfts_prepare();
2890 list_for_each_entry(set, &ss->cftsets, node) {
2891 if (set->cfts == cfts) {
2892 list_del(&set->node);
2894 cgroup_cfts_commit(ss, cfts, false);
2899 cgroup_cfts_commit(ss, NULL, false);
2904 * cgroup_task_count - count the number of tasks in a cgroup.
2905 * @cgrp: the cgroup in question
2907 * Return the number of tasks in the cgroup.
2909 int cgroup_task_count(const struct cgroup *cgrp)
2912 struct cgrp_cset_link *link;
2914 read_lock(&css_set_lock);
2915 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2916 count += atomic_read(&link->cset->refcount);
2917 read_unlock(&css_set_lock);
2922 * Advance a list_head iterator. The iterator should be positioned at
2923 * the start of a css_set
2925 static void cgroup_advance_iter(struct cgroup *cgrp, struct cgroup_iter *it)
2927 struct list_head *l = it->cset_link;
2928 struct cgrp_cset_link *link;
2929 struct css_set *cset;
2931 /* Advance to the next non-empty css_set */
2934 if (l == &cgrp->cset_links) {
2935 it->cset_link = NULL;
2938 link = list_entry(l, struct cgrp_cset_link, cset_link);
2940 } while (list_empty(&cset->tasks));
2942 it->task = cset->tasks.next;
2946 * To reduce the fork() overhead for systems that are not actually
2947 * using their cgroups capability, we don't maintain the lists running
2948 * through each css_set to its tasks until we see the list actually
2949 * used - in other words after the first call to cgroup_iter_start().
2951 static void cgroup_enable_task_cg_lists(void)
2953 struct task_struct *p, *g;
2954 write_lock(&css_set_lock);
2955 use_task_css_set_links = 1;
2957 * We need tasklist_lock because RCU is not safe against
2958 * while_each_thread(). Besides, a forking task that has passed
2959 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2960 * is not guaranteed to have its child immediately visible in the
2961 * tasklist if we walk through it with RCU.
2963 read_lock(&tasklist_lock);
2964 do_each_thread(g, p) {
2967 * We should check if the process is exiting, otherwise
2968 * it will race with cgroup_exit() in that the list
2969 * entry won't be deleted though the process has exited.
2971 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2972 list_add(&p->cg_list, &p->cgroups->tasks);
2974 } while_each_thread(g, p);
2975 read_unlock(&tasklist_lock);
2976 write_unlock(&css_set_lock);
2980 * cgroup_next_sibling - find the next sibling of a given cgroup
2981 * @pos: the current cgroup
2983 * This function returns the next sibling of @pos and should be called
2984 * under RCU read lock. The only requirement is that @pos is accessible.
2985 * The next sibling is guaranteed to be returned regardless of @pos's
2988 struct cgroup *cgroup_next_sibling(struct cgroup *pos)
2990 struct cgroup *next;
2992 WARN_ON_ONCE(!rcu_read_lock_held());
2995 * @pos could already have been removed. Once a cgroup is removed,
2996 * its ->sibling.next is no longer updated when its next sibling
2997 * changes. As CGRP_DEAD assertion is serialized and happens
2998 * before the cgroup is taken off the ->sibling list, if we see it
2999 * unasserted, it's guaranteed that the next sibling hasn't
3000 * finished its grace period even if it's already removed, and thus
3001 * safe to dereference from this RCU critical section. If
3002 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3003 * to be visible as %true here.
3005 if (likely(!cgroup_is_dead(pos))) {
3006 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3007 if (&next->sibling != &pos->parent->children)
3013 * Can't dereference the next pointer. Each cgroup is given a
3014 * monotonically increasing unique serial number and always
3015 * appended to the sibling list, so the next one can be found by
3016 * walking the parent's children until we see a cgroup with higher
3017 * serial number than @pos's.
3019 * While this path can be slow, it's taken only when either the
3020 * current cgroup is removed or iteration and removal race.
3022 list_for_each_entry_rcu(next, &pos->parent->children, sibling)
3023 if (next->serial_nr > pos->serial_nr)
3027 EXPORT_SYMBOL_GPL(cgroup_next_sibling);
3030 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
3031 * @pos: the current position (%NULL to initiate traversal)
3032 * @cgroup: cgroup whose descendants to walk
3034 * To be used by cgroup_for_each_descendant_pre(). Find the next
3035 * descendant to visit for pre-order traversal of @cgroup's descendants.
3037 * While this function requires RCU read locking, it doesn't require the
3038 * whole traversal to be contained in a single RCU critical section. This
3039 * function will return the correct next descendant as long as both @pos
3040 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3042 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
3043 struct cgroup *cgroup)
3045 struct cgroup *next;
3047 WARN_ON_ONCE(!rcu_read_lock_held());
3049 /* if first iteration, pretend we just visited @cgroup */
3053 /* visit the first child if exists */
3054 next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
3058 /* no child, visit my or the closest ancestor's next sibling */
3059 while (pos != cgroup) {
3060 next = cgroup_next_sibling(pos);
3068 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
3071 * cgroup_rightmost_descendant - return the rightmost descendant of a cgroup
3072 * @pos: cgroup of interest
3074 * Return the rightmost descendant of @pos. If there's no descendant,
3075 * @pos is returned. This can be used during pre-order traversal to skip
3078 * While this function requires RCU read locking, it doesn't require the
3079 * whole traversal to be contained in a single RCU critical section. This
3080 * function will return the correct rightmost descendant as long as @pos is
3083 struct cgroup *cgroup_rightmost_descendant(struct cgroup *pos)
3085 struct cgroup *last, *tmp;
3087 WARN_ON_ONCE(!rcu_read_lock_held());
3091 /* ->prev isn't RCU safe, walk ->next till the end */
3093 list_for_each_entry_rcu(tmp, &last->children, sibling)
3099 EXPORT_SYMBOL_GPL(cgroup_rightmost_descendant);
3101 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3103 struct cgroup *last;
3107 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3115 * cgroup_next_descendant_post - find the next descendant for post-order walk
3116 * @pos: the current position (%NULL to initiate traversal)
3117 * @cgroup: cgroup whose descendants to walk
3119 * To be used by cgroup_for_each_descendant_post(). Find the next
3120 * descendant to visit for post-order traversal of @cgroup's descendants.
3122 * While this function requires RCU read locking, it doesn't require the
3123 * whole traversal to be contained in a single RCU critical section. This
3124 * function will return the correct next descendant as long as both @pos
3125 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3127 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3128 struct cgroup *cgroup)
3130 struct cgroup *next;
3132 WARN_ON_ONCE(!rcu_read_lock_held());
3134 /* if first iteration, visit the leftmost descendant */
3136 next = cgroup_leftmost_descendant(cgroup);
3137 return next != cgroup ? next : NULL;
3140 /* if there's an unvisited sibling, visit its leftmost descendant */
3141 next = cgroup_next_sibling(pos);
3143 return cgroup_leftmost_descendant(next);
3145 /* no sibling left, visit parent */
3147 return next != cgroup ? next : NULL;
3149 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3151 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3152 __acquires(css_set_lock)
3155 * The first time anyone tries to iterate across a cgroup,
3156 * we need to enable the list linking each css_set to its
3157 * tasks, and fix up all existing tasks.
3159 if (!use_task_css_set_links)
3160 cgroup_enable_task_cg_lists();
3162 read_lock(&css_set_lock);
3163 it->cset_link = &cgrp->cset_links;
3164 cgroup_advance_iter(cgrp, it);
3167 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3168 struct cgroup_iter *it)
3170 struct task_struct *res;
3171 struct list_head *l = it->task;
3172 struct cgrp_cset_link *link;
3174 /* If the iterator cg is NULL, we have no tasks */
3177 res = list_entry(l, struct task_struct, cg_list);
3178 /* Advance iterator to find next entry */
3180 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3181 if (l == &link->cset->tasks) {
3182 /* We reached the end of this task list - move on to
3183 * the next cg_cgroup_link */
3184 cgroup_advance_iter(cgrp, it);
3191 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3192 __releases(css_set_lock)
3194 read_unlock(&css_set_lock);
3197 static inline int started_after_time(struct task_struct *t1,
3198 struct timespec *time,
3199 struct task_struct *t2)
3201 int start_diff = timespec_compare(&t1->start_time, time);
3202 if (start_diff > 0) {
3204 } else if (start_diff < 0) {
3208 * Arbitrarily, if two processes started at the same
3209 * time, we'll say that the lower pointer value
3210 * started first. Note that t2 may have exited by now
3211 * so this may not be a valid pointer any longer, but
3212 * that's fine - it still serves to distinguish
3213 * between two tasks started (effectively) simultaneously.
3220 * This function is a callback from heap_insert() and is used to order
3222 * In this case we order the heap in descending task start time.
3224 static inline int started_after(void *p1, void *p2)
3226 struct task_struct *t1 = p1;
3227 struct task_struct *t2 = p2;
3228 return started_after_time(t1, &t2->start_time, t2);
3232 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3233 * @scan: struct cgroup_scanner containing arguments for the scan
3235 * Arguments include pointers to callback functions test_task() and
3237 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3238 * and if it returns true, call process_task() for it also.
3239 * The test_task pointer may be NULL, meaning always true (select all tasks).
3240 * Effectively duplicates cgroup_iter_{start,next,end}()
3241 * but does not lock css_set_lock for the call to process_task().
3242 * The struct cgroup_scanner may be embedded in any structure of the caller's
3244 * It is guaranteed that process_task() will act on every task that
3245 * is a member of the cgroup for the duration of this call. This
3246 * function may or may not call process_task() for tasks that exit
3247 * or move to a different cgroup during the call, or are forked or
3248 * move into the cgroup during the call.
3250 * Note that test_task() may be called with locks held, and may in some
3251 * situations be called multiple times for the same task, so it should
3253 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3254 * pre-allocated and will be used for heap operations (and its "gt" member will
3255 * be overwritten), else a temporary heap will be used (allocation of which
3256 * may cause this function to fail).
3258 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3261 struct cgroup_iter it;
3262 struct task_struct *p, *dropped;
3263 /* Never dereference latest_task, since it's not refcounted */
3264 struct task_struct *latest_task = NULL;
3265 struct ptr_heap tmp_heap;
3266 struct ptr_heap *heap;
3267 struct timespec latest_time = { 0, 0 };
3270 /* The caller supplied our heap and pre-allocated its memory */
3272 heap->gt = &started_after;
3274 /* We need to allocate our own heap memory */
3276 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3278 /* cannot allocate the heap */
3284 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3285 * to determine which are of interest, and using the scanner's
3286 * "process_task" callback to process any of them that need an update.
3287 * Since we don't want to hold any locks during the task updates,
3288 * gather tasks to be processed in a heap structure.
3289 * The heap is sorted by descending task start time.
3290 * If the statically-sized heap fills up, we overflow tasks that
3291 * started later, and in future iterations only consider tasks that
3292 * started after the latest task in the previous pass. This
3293 * guarantees forward progress and that we don't miss any tasks.
3296 cgroup_iter_start(scan->cg, &it);
3297 while ((p = cgroup_iter_next(scan->cg, &it))) {
3299 * Only affect tasks that qualify per the caller's callback,
3300 * if he provided one
3302 if (scan->test_task && !scan->test_task(p, scan))
3305 * Only process tasks that started after the last task
3308 if (!started_after_time(p, &latest_time, latest_task))
3310 dropped = heap_insert(heap, p);
3311 if (dropped == NULL) {
3313 * The new task was inserted; the heap wasn't
3317 } else if (dropped != p) {
3319 * The new task was inserted, and pushed out a
3323 put_task_struct(dropped);
3326 * Else the new task was newer than anything already in
3327 * the heap and wasn't inserted
3330 cgroup_iter_end(scan->cg, &it);
3333 for (i = 0; i < heap->size; i++) {
3334 struct task_struct *q = heap->ptrs[i];
3336 latest_time = q->start_time;
3339 /* Process the task per the caller's callback */
3340 scan->process_task(q, scan);
3344 * If we had to process any tasks at all, scan again
3345 * in case some of them were in the middle of forking
3346 * children that didn't get processed.
3347 * Not the most efficient way to do it, but it avoids
3348 * having to take callback_mutex in the fork path
3352 if (heap == &tmp_heap)
3353 heap_free(&tmp_heap);
3357 static void cgroup_transfer_one_task(struct task_struct *task,
3358 struct cgroup_scanner *scan)
3360 struct cgroup *new_cgroup = scan->data;
3362 mutex_lock(&cgroup_mutex);
3363 cgroup_attach_task(new_cgroup, task, false);
3364 mutex_unlock(&cgroup_mutex);
3368 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3369 * @to: cgroup to which the tasks will be moved
3370 * @from: cgroup in which the tasks currently reside
3372 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3374 struct cgroup_scanner scan;
3377 scan.test_task = NULL; /* select all tasks in cgroup */
3378 scan.process_task = cgroup_transfer_one_task;
3382 return cgroup_scan_tasks(&scan);
3386 * Stuff for reading the 'tasks'/'procs' files.
3388 * Reading this file can return large amounts of data if a cgroup has
3389 * *lots* of attached tasks. So it may need several calls to read(),
3390 * but we cannot guarantee that the information we produce is correct
3391 * unless we produce it entirely atomically.
3395 /* which pidlist file are we talking about? */
3396 enum cgroup_filetype {
3402 * A pidlist is a list of pids that virtually represents the contents of one
3403 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3404 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3407 struct cgroup_pidlist {
3409 * used to find which pidlist is wanted. doesn't change as long as
3410 * this particular list stays in the list.
3412 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3415 /* how many elements the above list has */
3417 /* how many files are using the current array */
3419 /* each of these stored in a list by its cgroup */
3420 struct list_head links;
3421 /* pointer to the cgroup we belong to, for list removal purposes */
3422 struct cgroup *owner;
3423 /* protects the other fields */
3424 struct rw_semaphore mutex;
3428 * The following two functions "fix" the issue where there are more pids
3429 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3430 * TODO: replace with a kernel-wide solution to this problem
3432 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3433 static void *pidlist_allocate(int count)
3435 if (PIDLIST_TOO_LARGE(count))
3436 return vmalloc(count * sizeof(pid_t));
3438 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3440 static void pidlist_free(void *p)
3442 if (is_vmalloc_addr(p))
3449 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3450 * Returns the number of unique elements.
3452 static int pidlist_uniq(pid_t *list, int length)
3457 * we presume the 0th element is unique, so i starts at 1. trivial
3458 * edge cases first; no work needs to be done for either
3460 if (length == 0 || length == 1)
3462 /* src and dest walk down the list; dest counts unique elements */
3463 for (src = 1; src < length; src++) {
3464 /* find next unique element */
3465 while (list[src] == list[src-1]) {
3470 /* dest always points to where the next unique element goes */
3471 list[dest] = list[src];
3478 static int cmppid(const void *a, const void *b)
3480 return *(pid_t *)a - *(pid_t *)b;
3484 * find the appropriate pidlist for our purpose (given procs vs tasks)
3485 * returns with the lock on that pidlist already held, and takes care
3486 * of the use count, or returns NULL with no locks held if we're out of
3489 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3490 enum cgroup_filetype type)
3492 struct cgroup_pidlist *l;
3493 /* don't need task_nsproxy() if we're looking at ourself */
3494 struct pid_namespace *ns = task_active_pid_ns(current);
3497 * We can't drop the pidlist_mutex before taking the l->mutex in case
3498 * the last ref-holder is trying to remove l from the list at the same
3499 * time. Holding the pidlist_mutex precludes somebody taking whichever
3500 * list we find out from under us - compare release_pid_array().
3502 mutex_lock(&cgrp->pidlist_mutex);
3503 list_for_each_entry(l, &cgrp->pidlists, links) {
3504 if (l->key.type == type && l->key.ns == ns) {
3505 /* make sure l doesn't vanish out from under us */
3506 down_write(&l->mutex);
3507 mutex_unlock(&cgrp->pidlist_mutex);
3511 /* entry not found; create a new one */
3512 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3514 mutex_unlock(&cgrp->pidlist_mutex);
3517 init_rwsem(&l->mutex);
3518 down_write(&l->mutex);
3520 l->key.ns = get_pid_ns(ns);
3522 list_add(&l->links, &cgrp->pidlists);
3523 mutex_unlock(&cgrp->pidlist_mutex);
3528 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3530 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3531 struct cgroup_pidlist **lp)
3535 int pid, n = 0; /* used for populating the array */
3536 struct cgroup_iter it;
3537 struct task_struct *tsk;
3538 struct cgroup_pidlist *l;
3541 * If cgroup gets more users after we read count, we won't have
3542 * enough space - tough. This race is indistinguishable to the
3543 * caller from the case that the additional cgroup users didn't
3544 * show up until sometime later on.
3546 length = cgroup_task_count(cgrp);
3547 array = pidlist_allocate(length);
3550 /* now, populate the array */
3551 cgroup_iter_start(cgrp, &it);
3552 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3553 if (unlikely(n == length))
3555 /* get tgid or pid for procs or tasks file respectively */
3556 if (type == CGROUP_FILE_PROCS)
3557 pid = task_tgid_vnr(tsk);
3559 pid = task_pid_vnr(tsk);
3560 if (pid > 0) /* make sure to only use valid results */
3563 cgroup_iter_end(cgrp, &it);
3565 /* now sort & (if procs) strip out duplicates */
3566 sort(array, length, sizeof(pid_t), cmppid, NULL);
3567 if (type == CGROUP_FILE_PROCS)
3568 length = pidlist_uniq(array, length);
3569 l = cgroup_pidlist_find(cgrp, type);
3571 pidlist_free(array);
3574 /* store array, freeing old if necessary - lock already held */
3575 pidlist_free(l->list);
3579 up_write(&l->mutex);
3585 * cgroupstats_build - build and fill cgroupstats
3586 * @stats: cgroupstats to fill information into
3587 * @dentry: A dentry entry belonging to the cgroup for which stats have
3590 * Build and fill cgroupstats so that taskstats can export it to user
3593 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3596 struct cgroup *cgrp;
3597 struct cgroup_iter it;
3598 struct task_struct *tsk;
3601 * Validate dentry by checking the superblock operations,
3602 * and make sure it's a directory.
3604 if (dentry->d_sb->s_op != &cgroup_ops ||
3605 !S_ISDIR(dentry->d_inode->i_mode))
3609 cgrp = dentry->d_fsdata;
3611 cgroup_iter_start(cgrp, &it);
3612 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3613 switch (tsk->state) {
3615 stats->nr_running++;
3617 case TASK_INTERRUPTIBLE:
3618 stats->nr_sleeping++;
3620 case TASK_UNINTERRUPTIBLE:
3621 stats->nr_uninterruptible++;
3624 stats->nr_stopped++;
3627 if (delayacct_is_task_waiting_on_io(tsk))
3628 stats->nr_io_wait++;
3632 cgroup_iter_end(cgrp, &it);
3640 * seq_file methods for the tasks/procs files. The seq_file position is the
3641 * next pid to display; the seq_file iterator is a pointer to the pid
3642 * in the cgroup->l->list array.
3645 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3648 * Initially we receive a position value that corresponds to
3649 * one more than the last pid shown (or 0 on the first call or
3650 * after a seek to the start). Use a binary-search to find the
3651 * next pid to display, if any
3653 struct cgroup_pidlist *l = s->private;
3654 int index = 0, pid = *pos;
3657 down_read(&l->mutex);
3659 int end = l->length;
3661 while (index < end) {
3662 int mid = (index + end) / 2;
3663 if (l->list[mid] == pid) {
3666 } else if (l->list[mid] <= pid)
3672 /* If we're off the end of the array, we're done */
3673 if (index >= l->length)
3675 /* Update the abstract position to be the actual pid that we found */
3676 iter = l->list + index;
3681 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3683 struct cgroup_pidlist *l = s->private;
3687 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3689 struct cgroup_pidlist *l = s->private;
3691 pid_t *end = l->list + l->length;
3693 * Advance to the next pid in the array. If this goes off the
3705 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3707 return seq_printf(s, "%d\n", *(int *)v);
3711 * seq_operations functions for iterating on pidlists through seq_file -
3712 * independent of whether it's tasks or procs
3714 static const struct seq_operations cgroup_pidlist_seq_operations = {
3715 .start = cgroup_pidlist_start,
3716 .stop = cgroup_pidlist_stop,
3717 .next = cgroup_pidlist_next,
3718 .show = cgroup_pidlist_show,
3721 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3724 * the case where we're the last user of this particular pidlist will
3725 * have us remove it from the cgroup's list, which entails taking the
3726 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3727 * pidlist_mutex, we have to take pidlist_mutex first.
3729 mutex_lock(&l->owner->pidlist_mutex);
3730 down_write(&l->mutex);
3731 BUG_ON(!l->use_count);
3732 if (!--l->use_count) {
3733 /* we're the last user if refcount is 0; remove and free */
3734 list_del(&l->links);
3735 mutex_unlock(&l->owner->pidlist_mutex);
3736 pidlist_free(l->list);
3737 put_pid_ns(l->key.ns);
3738 up_write(&l->mutex);
3742 mutex_unlock(&l->owner->pidlist_mutex);
3743 up_write(&l->mutex);
3746 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3748 struct cgroup_pidlist *l;
3749 if (!(file->f_mode & FMODE_READ))
3752 * the seq_file will only be initialized if the file was opened for
3753 * reading; hence we check if it's not null only in that case.
3755 l = ((struct seq_file *)file->private_data)->private;
3756 cgroup_release_pid_array(l);
3757 return seq_release(inode, file);
3760 static const struct file_operations cgroup_pidlist_operations = {
3762 .llseek = seq_lseek,
3763 .write = cgroup_file_write,
3764 .release = cgroup_pidlist_release,
3768 * The following functions handle opens on a file that displays a pidlist
3769 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3772 /* helper function for the two below it */
3773 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3775 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3776 struct cgroup_pidlist *l;
3779 /* Nothing to do for write-only files */
3780 if (!(file->f_mode & FMODE_READ))
3783 /* have the array populated */
3784 retval = pidlist_array_load(cgrp, type, &l);
3787 /* configure file information */
3788 file->f_op = &cgroup_pidlist_operations;
3790 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3792 cgroup_release_pid_array(l);
3795 ((struct seq_file *)file->private_data)->private = l;
3798 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3800 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3802 static int cgroup_procs_open(struct inode *unused, struct file *file)
3804 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3807 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3810 return notify_on_release(cgrp);
3813 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3817 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3819 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3821 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3826 * When dput() is called asynchronously, if umount has been done and
3827 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3828 * there's a small window that vfs will see the root dentry with non-zero
3829 * refcnt and trigger BUG().
3831 * That's why we hold a reference before dput() and drop it right after.
3833 static void cgroup_dput(struct cgroup *cgrp)
3835 struct super_block *sb = cgrp->root->sb;
3837 atomic_inc(&sb->s_active);
3839 deactivate_super(sb);
3843 * Unregister event and free resources.
3845 * Gets called from workqueue.
3847 static void cgroup_event_remove(struct work_struct *work)
3849 struct cgroup_event *event = container_of(work, struct cgroup_event,
3851 struct cgroup *cgrp = event->cgrp;
3853 remove_wait_queue(event->wqh, &event->wait);
3855 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3857 /* Notify userspace the event is going away. */
3858 eventfd_signal(event->eventfd, 1);
3860 eventfd_ctx_put(event->eventfd);
3866 * Gets called on POLLHUP on eventfd when user closes it.
3868 * Called with wqh->lock held and interrupts disabled.
3870 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3871 int sync, void *key)
3873 struct cgroup_event *event = container_of(wait,
3874 struct cgroup_event, wait);
3875 struct cgroup *cgrp = event->cgrp;
3876 unsigned long flags = (unsigned long)key;
3878 if (flags & POLLHUP) {
3880 * If the event has been detached at cgroup removal, we
3881 * can simply return knowing the other side will cleanup
3884 * We can't race against event freeing since the other
3885 * side will require wqh->lock via remove_wait_queue(),
3888 spin_lock(&cgrp->event_list_lock);
3889 if (!list_empty(&event->list)) {
3890 list_del_init(&event->list);
3892 * We are in atomic context, but cgroup_event_remove()
3893 * may sleep, so we have to call it in workqueue.
3895 schedule_work(&event->remove);
3897 spin_unlock(&cgrp->event_list_lock);
3903 static void cgroup_event_ptable_queue_proc(struct file *file,
3904 wait_queue_head_t *wqh, poll_table *pt)
3906 struct cgroup_event *event = container_of(pt,
3907 struct cgroup_event, pt);
3910 add_wait_queue(wqh, &event->wait);
3914 * Parse input and register new cgroup event handler.
3916 * Input must be in format '<event_fd> <control_fd> <args>'.
3917 * Interpretation of args is defined by control file implementation.
3919 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3922 struct cgroup_event *event = NULL;
3923 struct cgroup *cgrp_cfile;
3924 unsigned int efd, cfd;
3925 struct file *efile = NULL;
3926 struct file *cfile = NULL;
3930 efd = simple_strtoul(buffer, &endp, 10);
3935 cfd = simple_strtoul(buffer, &endp, 10);
3936 if ((*endp != ' ') && (*endp != '\0'))
3940 event = kzalloc(sizeof(*event), GFP_KERNEL);
3944 INIT_LIST_HEAD(&event->list);
3945 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3946 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3947 INIT_WORK(&event->remove, cgroup_event_remove);
3949 efile = eventfd_fget(efd);
3950 if (IS_ERR(efile)) {
3951 ret = PTR_ERR(efile);
3955 event->eventfd = eventfd_ctx_fileget(efile);
3956 if (IS_ERR(event->eventfd)) {
3957 ret = PTR_ERR(event->eventfd);
3967 /* the process need read permission on control file */
3968 /* AV: shouldn't we check that it's been opened for read instead? */
3969 ret = inode_permission(file_inode(cfile), MAY_READ);
3973 event->cft = __file_cft(cfile);
3974 if (IS_ERR(event->cft)) {
3975 ret = PTR_ERR(event->cft);
3980 * The file to be monitored must be in the same cgroup as
3981 * cgroup.event_control is.
3983 cgrp_cfile = __d_cgrp(cfile->f_dentry->d_parent);
3984 if (cgrp_cfile != cgrp) {
3989 if (!event->cft->register_event || !event->cft->unregister_event) {
3994 ret = event->cft->register_event(cgrp, event->cft,
3995 event->eventfd, buffer);
3999 efile->f_op->poll(efile, &event->pt);
4002 * Events should be removed after rmdir of cgroup directory, but before
4003 * destroying subsystem state objects. Let's take reference to cgroup
4004 * directory dentry to do that.
4008 spin_lock(&cgrp->event_list_lock);
4009 list_add(&event->list, &cgrp->event_list);
4010 spin_unlock(&cgrp->event_list_lock);
4021 if (event && event->eventfd && !IS_ERR(event->eventfd))
4022 eventfd_ctx_put(event->eventfd);
4024 if (!IS_ERR_OR_NULL(efile))
4032 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
4035 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4038 static int cgroup_clone_children_write(struct cgroup *cgrp,
4043 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4045 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4049 static struct cftype cgroup_base_files[] = {
4051 .name = "cgroup.procs",
4052 .open = cgroup_procs_open,
4053 .write_u64 = cgroup_procs_write,
4054 .release = cgroup_pidlist_release,
4055 .mode = S_IRUGO | S_IWUSR,
4058 .name = "cgroup.event_control",
4059 .write_string = cgroup_write_event_control,
4063 .name = "cgroup.clone_children",
4064 .flags = CFTYPE_INSANE,
4065 .read_u64 = cgroup_clone_children_read,
4066 .write_u64 = cgroup_clone_children_write,
4069 .name = "cgroup.sane_behavior",
4070 .flags = CFTYPE_ONLY_ON_ROOT,
4071 .read_seq_string = cgroup_sane_behavior_show,
4075 * Historical crazy stuff. These don't have "cgroup." prefix and
4076 * don't exist if sane_behavior. If you're depending on these, be
4077 * prepared to be burned.
4081 .flags = CFTYPE_INSANE, /* use "procs" instead */
4082 .open = cgroup_tasks_open,
4083 .write_u64 = cgroup_tasks_write,
4084 .release = cgroup_pidlist_release,
4085 .mode = S_IRUGO | S_IWUSR,
4088 .name = "notify_on_release",
4089 .flags = CFTYPE_INSANE,
4090 .read_u64 = cgroup_read_notify_on_release,
4091 .write_u64 = cgroup_write_notify_on_release,
4094 .name = "release_agent",
4095 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4096 .read_seq_string = cgroup_release_agent_show,
4097 .write_string = cgroup_release_agent_write,
4098 .max_write_len = PATH_MAX,
4104 * cgroup_populate_dir - selectively creation of files in a directory
4105 * @cgrp: target cgroup
4106 * @base_files: true if the base files should be added
4107 * @subsys_mask: mask of the subsystem ids whose files should be added
4109 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
4110 unsigned long subsys_mask)
4113 struct cgroup_subsys *ss;
4116 err = cgroup_addrm_files(cgrp, NULL, cgroup_base_files, true);
4121 /* process cftsets of each subsystem */
4122 for_each_subsys(cgrp->root, ss) {
4123 struct cftype_set *set;
4124 if (!test_bit(ss->subsys_id, &subsys_mask))
4127 list_for_each_entry(set, &ss->cftsets, node)
4128 cgroup_addrm_files(cgrp, ss, set->cfts, true);
4131 /* This cgroup is ready now */
4132 for_each_subsys(cgrp->root, ss) {
4133 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4135 * Update id->css pointer and make this css visible from
4136 * CSS ID functions. This pointer will be dereferened
4137 * from RCU-read-side without locks.
4140 rcu_assign_pointer(css->id->css, css);
4146 static void css_dput_fn(struct work_struct *work)
4148 struct cgroup_subsys_state *css =
4149 container_of(work, struct cgroup_subsys_state, dput_work);
4151 cgroup_dput(css->cgroup);
4154 static void css_release(struct percpu_ref *ref)
4156 struct cgroup_subsys_state *css =
4157 container_of(ref, struct cgroup_subsys_state, refcnt);
4159 schedule_work(&css->dput_work);
4162 static void init_cgroup_css(struct cgroup_subsys_state *css,
4163 struct cgroup_subsys *ss,
4164 struct cgroup *cgrp)
4169 if (cgrp == dummytop)
4170 css->flags |= CSS_ROOT;
4171 BUG_ON(cgrp->subsys[ss->subsys_id]);
4172 cgrp->subsys[ss->subsys_id] = css;
4175 * css holds an extra ref to @cgrp->dentry which is put on the last
4176 * css_put(). dput() requires process context, which css_put() may
4177 * be called without. @css->dput_work will be used to invoke
4178 * dput() asynchronously from css_put().
4180 INIT_WORK(&css->dput_work, css_dput_fn);
4183 /* invoke ->post_create() on a new CSS and mark it online if successful */
4184 static int online_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4188 lockdep_assert_held(&cgroup_mutex);
4191 ret = ss->css_online(cgrp);
4193 cgrp->subsys[ss->subsys_id]->flags |= CSS_ONLINE;
4197 /* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4198 static void offline_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4199 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4201 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4203 lockdep_assert_held(&cgroup_mutex);
4205 if (!(css->flags & CSS_ONLINE))
4208 if (ss->css_offline)
4209 ss->css_offline(cgrp);
4211 cgrp->subsys[ss->subsys_id]->flags &= ~CSS_ONLINE;
4215 * cgroup_create - create a cgroup
4216 * @parent: cgroup that will be parent of the new cgroup
4217 * @dentry: dentry of the new cgroup
4218 * @mode: mode to set on new inode
4220 * Must be called with the mutex on the parent inode held
4222 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4225 static atomic64_t serial_nr_cursor = ATOMIC64_INIT(0);
4226 struct cgroup *cgrp;
4227 struct cgroup_name *name;
4228 struct cgroupfs_root *root = parent->root;
4230 struct cgroup_subsys *ss;
4231 struct super_block *sb = root->sb;
4233 /* allocate the cgroup and its ID, 0 is reserved for the root */
4234 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4238 name = cgroup_alloc_name(dentry);
4241 rcu_assign_pointer(cgrp->name, name);
4243 cgrp->id = ida_simple_get(&root->cgroup_ida, 1, 0, GFP_KERNEL);
4248 * Only live parents can have children. Note that the liveliness
4249 * check isn't strictly necessary because cgroup_mkdir() and
4250 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4251 * anyway so that locking is contained inside cgroup proper and we
4252 * don't get nasty surprises if we ever grow another caller.
4254 if (!cgroup_lock_live_group(parent)) {
4259 /* Grab a reference on the superblock so the hierarchy doesn't
4260 * get deleted on unmount if there are child cgroups. This
4261 * can be done outside cgroup_mutex, since the sb can't
4262 * disappear while someone has an open control file on the
4264 atomic_inc(&sb->s_active);
4266 init_cgroup_housekeeping(cgrp);
4268 dentry->d_fsdata = cgrp;
4269 cgrp->dentry = dentry;
4271 cgrp->parent = parent;
4272 cgrp->root = parent->root;
4274 if (notify_on_release(parent))
4275 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4277 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4278 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4280 for_each_subsys(root, ss) {
4281 struct cgroup_subsys_state *css;
4283 css = ss->css_alloc(cgrp);
4289 err = percpu_ref_init(&css->refcnt, css_release);
4293 init_cgroup_css(css, ss, cgrp);
4296 err = alloc_css_id(ss, parent, cgrp);
4303 * Create directory. cgroup_create_file() returns with the new
4304 * directory locked on success so that it can be populated without
4305 * dropping cgroup_mutex.
4307 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4310 lockdep_assert_held(&dentry->d_inode->i_mutex);
4313 * Assign a monotonically increasing serial number. With the list
4314 * appending below, it guarantees that sibling cgroups are always
4315 * sorted in the ascending serial number order on the parent's
4318 cgrp->serial_nr = atomic64_inc_return(&serial_nr_cursor);
4320 /* allocation complete, commit to creation */
4321 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4322 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4323 root->number_of_cgroups++;
4325 /* each css holds a ref to the cgroup's dentry */
4326 for_each_subsys(root, ss)
4329 /* hold a ref to the parent's dentry */
4330 dget(parent->dentry);
4332 /* creation succeeded, notify subsystems */
4333 for_each_subsys(root, ss) {
4334 err = online_css(ss, cgrp);
4338 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4340 pr_warning("cgroup: %s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4341 current->comm, current->pid, ss->name);
4342 if (!strcmp(ss->name, "memory"))
4343 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4344 ss->warned_broken_hierarchy = true;
4348 err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4352 mutex_unlock(&cgroup_mutex);
4353 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4358 for_each_subsys(root, ss) {
4359 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4362 percpu_ref_cancel_init(&css->refcnt);
4366 mutex_unlock(&cgroup_mutex);
4367 /* Release the reference count that we took on the superblock */
4368 deactivate_super(sb);
4370 ida_simple_remove(&root->cgroup_ida, cgrp->id);
4372 kfree(rcu_dereference_raw(cgrp->name));
4378 cgroup_destroy_locked(cgrp);
4379 mutex_unlock(&cgroup_mutex);
4380 mutex_unlock(&dentry->d_inode->i_mutex);
4384 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4386 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4388 /* the vfs holds inode->i_mutex already */
4389 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4392 static void cgroup_css_killed(struct cgroup *cgrp)
4394 if (!atomic_dec_and_test(&cgrp->css_kill_cnt))
4397 /* percpu ref's of all css's are killed, kick off the next step */
4398 INIT_WORK(&cgrp->destroy_work, cgroup_offline_fn);
4399 schedule_work(&cgrp->destroy_work);
4402 static void css_ref_killed_fn(struct percpu_ref *ref)
4404 struct cgroup_subsys_state *css =
4405 container_of(ref, struct cgroup_subsys_state, refcnt);
4407 cgroup_css_killed(css->cgroup);
4411 * cgroup_destroy_locked - the first stage of cgroup destruction
4412 * @cgrp: cgroup to be destroyed
4414 * css's make use of percpu refcnts whose killing latency shouldn't be
4415 * exposed to userland and are RCU protected. Also, cgroup core needs to
4416 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4417 * invoked. To satisfy all the requirements, destruction is implemented in
4418 * the following two steps.
4420 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4421 * userland visible parts and start killing the percpu refcnts of
4422 * css's. Set up so that the next stage will be kicked off once all
4423 * the percpu refcnts are confirmed to be killed.
4425 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4426 * rest of destruction. Once all cgroup references are gone, the
4427 * cgroup is RCU-freed.
4429 * This function implements s1. After this step, @cgrp is gone as far as
4430 * the userland is concerned and a new cgroup with the same name may be
4431 * created. As cgroup doesn't care about the names internally, this
4432 * doesn't cause any problem.
4434 static int cgroup_destroy_locked(struct cgroup *cgrp)
4435 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4437 struct dentry *d = cgrp->dentry;
4438 struct cgroup_event *event, *tmp;
4439 struct cgroup_subsys *ss;
4442 lockdep_assert_held(&d->d_inode->i_mutex);
4443 lockdep_assert_held(&cgroup_mutex);
4446 * css_set_lock synchronizes access to ->cset_links and prevents
4447 * @cgrp from being removed while __put_css_set() is in progress.
4449 read_lock(&css_set_lock);
4450 empty = list_empty(&cgrp->cset_links) && list_empty(&cgrp->children);
4451 read_unlock(&css_set_lock);
4456 * Block new css_tryget() by killing css refcnts. cgroup core
4457 * guarantees that, by the time ->css_offline() is invoked, no new
4458 * css reference will be given out via css_tryget(). We can't
4459 * simply call percpu_ref_kill() and proceed to offlining css's
4460 * because percpu_ref_kill() doesn't guarantee that the ref is seen
4461 * as killed on all CPUs on return.
4463 * Use percpu_ref_kill_and_confirm() to get notifications as each
4464 * css is confirmed to be seen as killed on all CPUs. The
4465 * notification callback keeps track of the number of css's to be
4466 * killed and schedules cgroup_offline_fn() to perform the rest of
4467 * destruction once the percpu refs of all css's are confirmed to
4470 atomic_set(&cgrp->css_kill_cnt, 1);
4471 for_each_subsys(cgrp->root, ss) {
4472 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4475 * Killing would put the base ref, but we need to keep it
4476 * alive until after ->css_offline.
4478 percpu_ref_get(&css->refcnt);
4480 atomic_inc(&cgrp->css_kill_cnt);
4481 percpu_ref_kill_and_confirm(&css->refcnt, css_ref_killed_fn);
4483 cgroup_css_killed(cgrp);
4486 * Mark @cgrp dead. This prevents further task migration and child
4487 * creation by disabling cgroup_lock_live_group(). Note that
4488 * CGRP_DEAD assertion is depended upon by cgroup_next_sibling() to
4489 * resume iteration after dropping RCU read lock. See
4490 * cgroup_next_sibling() for details.
4492 set_bit(CGRP_DEAD, &cgrp->flags);
4494 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4495 raw_spin_lock(&release_list_lock);
4496 if (!list_empty(&cgrp->release_list))
4497 list_del_init(&cgrp->release_list);
4498 raw_spin_unlock(&release_list_lock);
4501 * Remove @cgrp directory. The removal puts the base ref but we
4502 * aren't quite done with @cgrp yet, so hold onto it.
4505 cgroup_d_remove_dir(d);
4508 * Unregister events and notify userspace.
4509 * Notify userspace about cgroup removing only after rmdir of cgroup
4510 * directory to avoid race between userspace and kernelspace.
4512 spin_lock(&cgrp->event_list_lock);
4513 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4514 list_del_init(&event->list);
4515 schedule_work(&event->remove);
4517 spin_unlock(&cgrp->event_list_lock);
4523 * cgroup_offline_fn - the second step of cgroup destruction
4524 * @work: cgroup->destroy_free_work
4526 * This function is invoked from a work item for a cgroup which is being
4527 * destroyed after the percpu refcnts of all css's are guaranteed to be
4528 * seen as killed on all CPUs, and performs the rest of destruction. This
4529 * is the second step of destruction described in the comment above
4530 * cgroup_destroy_locked().
4532 static void cgroup_offline_fn(struct work_struct *work)
4534 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
4535 struct cgroup *parent = cgrp->parent;
4536 struct dentry *d = cgrp->dentry;
4537 struct cgroup_subsys *ss;
4539 mutex_lock(&cgroup_mutex);
4542 * css_tryget() is guaranteed to fail now. Tell subsystems to
4543 * initate destruction.
4545 for_each_subsys(cgrp->root, ss)
4546 offline_css(ss, cgrp);
4549 * Put the css refs from cgroup_destroy_locked(). Each css holds
4550 * an extra reference to the cgroup's dentry and cgroup removal
4551 * proceeds regardless of css refs. On the last put of each css,
4552 * whenever that may be, the extra dentry ref is put so that dentry
4553 * destruction happens only after all css's are released.
4555 for_each_subsys(cgrp->root, ss)
4556 css_put(cgrp->subsys[ss->subsys_id]);
4558 /* delete this cgroup from parent->children */
4559 list_del_rcu(&cgrp->sibling);
4560 list_del_init(&cgrp->allcg_node);
4564 set_bit(CGRP_RELEASABLE, &parent->flags);
4565 check_for_release(parent);
4567 mutex_unlock(&cgroup_mutex);
4570 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4574 mutex_lock(&cgroup_mutex);
4575 ret = cgroup_destroy_locked(dentry->d_fsdata);
4576 mutex_unlock(&cgroup_mutex);
4581 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4583 INIT_LIST_HEAD(&ss->cftsets);
4586 * base_cftset is embedded in subsys itself, no need to worry about
4589 if (ss->base_cftypes) {
4590 ss->base_cftset.cfts = ss->base_cftypes;
4591 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4595 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4597 struct cgroup_subsys_state *css;
4599 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4601 mutex_lock(&cgroup_mutex);
4603 /* init base cftset */
4604 cgroup_init_cftsets(ss);
4606 /* Create the top cgroup state for this subsystem */
4607 list_add(&ss->sibling, &rootnode.subsys_list);
4608 ss->root = &rootnode;
4609 css = ss->css_alloc(dummytop);
4610 /* We don't handle early failures gracefully */
4611 BUG_ON(IS_ERR(css));
4612 init_cgroup_css(css, ss, dummytop);
4614 /* Update the init_css_set to contain a subsys
4615 * pointer to this state - since the subsystem is
4616 * newly registered, all tasks and hence the
4617 * init_css_set is in the subsystem's top cgroup. */
4618 init_css_set.subsys[ss->subsys_id] = css;
4620 need_forkexit_callback |= ss->fork || ss->exit;
4622 /* At system boot, before all subsystems have been
4623 * registered, no tasks have been forked, so we don't
4624 * need to invoke fork callbacks here. */
4625 BUG_ON(!list_empty(&init_task.tasks));
4627 BUG_ON(online_css(ss, dummytop));
4629 mutex_unlock(&cgroup_mutex);
4631 /* this function shouldn't be used with modular subsystems, since they
4632 * need to register a subsys_id, among other things */
4637 * cgroup_load_subsys: load and register a modular subsystem at runtime
4638 * @ss: the subsystem to load
4640 * This function should be called in a modular subsystem's initcall. If the
4641 * subsystem is built as a module, it will be assigned a new subsys_id and set
4642 * up for use. If the subsystem is built-in anyway, work is delegated to the
4643 * simpler cgroup_init_subsys.
4645 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4647 struct cgroup_subsys_state *css;
4649 struct hlist_node *tmp;
4650 struct css_set *cset;
4653 /* check name and function validity */
4654 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4655 ss->css_alloc == NULL || ss->css_free == NULL)
4659 * we don't support callbacks in modular subsystems. this check is
4660 * before the ss->module check for consistency; a subsystem that could
4661 * be a module should still have no callbacks even if the user isn't
4662 * compiling it as one.
4664 if (ss->fork || ss->exit)
4668 * an optionally modular subsystem is built-in: we want to do nothing,
4669 * since cgroup_init_subsys will have already taken care of it.
4671 if (ss->module == NULL) {
4672 /* a sanity check */
4673 BUG_ON(subsys[ss->subsys_id] != ss);
4677 /* init base cftset */
4678 cgroup_init_cftsets(ss);
4680 mutex_lock(&cgroup_mutex);
4681 subsys[ss->subsys_id] = ss;
4684 * no ss->css_alloc seems to need anything important in the ss
4685 * struct, so this can happen first (i.e. before the rootnode
4688 css = ss->css_alloc(dummytop);
4690 /* failure case - need to deassign the subsys[] slot. */
4691 subsys[ss->subsys_id] = NULL;
4692 mutex_unlock(&cgroup_mutex);
4693 return PTR_ERR(css);
4696 list_add(&ss->sibling, &rootnode.subsys_list);
4697 ss->root = &rootnode;
4699 /* our new subsystem will be attached to the dummy hierarchy. */
4700 init_cgroup_css(css, ss, dummytop);
4701 /* init_idr must be after init_cgroup_css because it sets css->id. */
4703 ret = cgroup_init_idr(ss, css);
4709 * Now we need to entangle the css into the existing css_sets. unlike
4710 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4711 * will need a new pointer to it; done by iterating the css_set_table.
4712 * furthermore, modifying the existing css_sets will corrupt the hash
4713 * table state, so each changed css_set will need its hash recomputed.
4714 * this is all done under the css_set_lock.
4716 write_lock(&css_set_lock);
4717 hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4718 /* skip entries that we already rehashed */
4719 if (cset->subsys[ss->subsys_id])
4721 /* remove existing entry */
4722 hash_del(&cset->hlist);
4724 cset->subsys[ss->subsys_id] = css;
4725 /* recompute hash and restore entry */
4726 key = css_set_hash(cset->subsys);
4727 hash_add(css_set_table, &cset->hlist, key);
4729 write_unlock(&css_set_lock);
4731 ret = online_css(ss, dummytop);
4736 mutex_unlock(&cgroup_mutex);
4740 mutex_unlock(&cgroup_mutex);
4741 /* @ss can't be mounted here as try_module_get() would fail */
4742 cgroup_unload_subsys(ss);
4745 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4748 * cgroup_unload_subsys: unload a modular subsystem
4749 * @ss: the subsystem to unload
4751 * This function should be called in a modular subsystem's exitcall. When this
4752 * function is invoked, the refcount on the subsystem's module will be 0, so
4753 * the subsystem will not be attached to any hierarchy.
4755 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4757 struct cgrp_cset_link *link;
4759 BUG_ON(ss->module == NULL);
4762 * we shouldn't be called if the subsystem is in use, and the use of
4763 * try_module_get in parse_cgroupfs_options should ensure that it
4764 * doesn't start being used while we're killing it off.
4766 BUG_ON(ss->root != &rootnode);
4768 mutex_lock(&cgroup_mutex);
4770 offline_css(ss, dummytop);
4773 idr_destroy(&ss->idr);
4775 /* deassign the subsys_id */
4776 subsys[ss->subsys_id] = NULL;
4778 /* remove subsystem from rootnode's list of subsystems */
4779 list_del_init(&ss->sibling);
4782 * disentangle the css from all css_sets attached to the dummytop. as
4783 * in loading, we need to pay our respects to the hashtable gods.
4785 write_lock(&css_set_lock);
4786 list_for_each_entry(link, &dummytop->cset_links, cset_link) {
4787 struct css_set *cset = link->cset;
4790 hash_del(&cset->hlist);
4791 cset->subsys[ss->subsys_id] = NULL;
4792 key = css_set_hash(cset->subsys);
4793 hash_add(css_set_table, &cset->hlist, key);
4795 write_unlock(&css_set_lock);
4798 * remove subsystem's css from the dummytop and free it - need to
4799 * free before marking as null because ss->css_free needs the
4800 * cgrp->subsys pointer to find their state. note that this also
4801 * takes care of freeing the css_id.
4803 ss->css_free(dummytop);
4804 dummytop->subsys[ss->subsys_id] = NULL;
4806 mutex_unlock(&cgroup_mutex);
4808 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4811 * cgroup_init_early - cgroup initialization at system boot
4813 * Initialize cgroups at system boot, and initialize any
4814 * subsystems that request early init.
4816 int __init cgroup_init_early(void)
4819 atomic_set(&init_css_set.refcount, 1);
4820 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4821 INIT_LIST_HEAD(&init_css_set.tasks);
4822 INIT_HLIST_NODE(&init_css_set.hlist);
4824 init_cgroup_root(&rootnode);
4826 init_task.cgroups = &init_css_set;
4828 init_cgrp_cset_link.cset = &init_css_set;
4829 init_cgrp_cset_link.cgrp = dummytop;
4830 list_add(&init_cgrp_cset_link.cset_link, &rootnode.top_cgroup.cset_links);
4831 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4833 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4834 struct cgroup_subsys *ss = subsys[i];
4836 /* at bootup time, we don't worry about modular subsystems */
4837 if (!ss || ss->module)
4841 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4842 BUG_ON(!ss->css_alloc);
4843 BUG_ON(!ss->css_free);
4844 if (ss->subsys_id != i) {
4845 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4846 ss->name, ss->subsys_id);
4851 cgroup_init_subsys(ss);
4857 * cgroup_init - cgroup initialization
4859 * Register cgroup filesystem and /proc file, and initialize
4860 * any subsystems that didn't request early init.
4862 int __init cgroup_init(void)
4868 err = bdi_init(&cgroup_backing_dev_info);
4872 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4873 struct cgroup_subsys *ss = subsys[i];
4875 /* at bootup time, we don't worry about modular subsystems */
4876 if (!ss || ss->module)
4878 if (!ss->early_init)
4879 cgroup_init_subsys(ss);
4881 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4884 /* Add init_css_set to the hash table */
4885 key = css_set_hash(init_css_set.subsys);
4886 hash_add(css_set_table, &init_css_set.hlist, key);
4888 /* allocate id for the dummy hierarchy */
4889 mutex_lock(&cgroup_mutex);
4890 mutex_lock(&cgroup_root_mutex);
4892 BUG_ON(cgroup_init_root_id(&rootnode));
4894 mutex_unlock(&cgroup_root_mutex);
4895 mutex_unlock(&cgroup_mutex);
4897 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4903 err = register_filesystem(&cgroup_fs_type);
4905 kobject_put(cgroup_kobj);
4909 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4913 bdi_destroy(&cgroup_backing_dev_info);
4919 * proc_cgroup_show()
4920 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4921 * - Used for /proc/<pid>/cgroup.
4922 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4923 * doesn't really matter if tsk->cgroup changes after we read it,
4924 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4925 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4926 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4927 * cgroup to top_cgroup.
4930 /* TODO: Use a proper seq_file iterator */
4931 int proc_cgroup_show(struct seq_file *m, void *v)
4934 struct task_struct *tsk;
4937 struct cgroupfs_root *root;
4940 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4946 tsk = get_pid_task(pid, PIDTYPE_PID);
4952 mutex_lock(&cgroup_mutex);
4954 for_each_active_root(root) {
4955 struct cgroup_subsys *ss;
4956 struct cgroup *cgrp;
4959 seq_printf(m, "%d:", root->hierarchy_id);
4960 for_each_subsys(root, ss)
4961 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4962 if (strlen(root->name))
4963 seq_printf(m, "%sname=%s", count ? "," : "",
4966 cgrp = task_cgroup_from_root(tsk, root);
4967 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4975 mutex_unlock(&cgroup_mutex);
4976 put_task_struct(tsk);
4983 /* Display information about each subsystem and each hierarchy */
4984 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4988 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4990 * ideally we don't want subsystems moving around while we do this.
4991 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4992 * subsys/hierarchy state.
4994 mutex_lock(&cgroup_mutex);
4995 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4996 struct cgroup_subsys *ss = subsys[i];
4999 seq_printf(m, "%s\t%d\t%d\t%d\n",
5000 ss->name, ss->root->hierarchy_id,
5001 ss->root->number_of_cgroups, !ss->disabled);
5003 mutex_unlock(&cgroup_mutex);
5007 static int cgroupstats_open(struct inode *inode, struct file *file)
5009 return single_open(file, proc_cgroupstats_show, NULL);
5012 static const struct file_operations proc_cgroupstats_operations = {
5013 .open = cgroupstats_open,
5015 .llseek = seq_lseek,
5016 .release = single_release,
5020 * cgroup_fork - attach newly forked task to its parents cgroup.
5021 * @child: pointer to task_struct of forking parent process.
5023 * Description: A task inherits its parent's cgroup at fork().
5025 * A pointer to the shared css_set was automatically copied in
5026 * fork.c by dup_task_struct(). However, we ignore that copy, since
5027 * it was not made under the protection of RCU or cgroup_mutex, so
5028 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
5029 * have already changed current->cgroups, allowing the previously
5030 * referenced cgroup group to be removed and freed.
5032 * At the point that cgroup_fork() is called, 'current' is the parent
5033 * task, and the passed argument 'child' points to the child task.
5035 void cgroup_fork(struct task_struct *child)
5038 child->cgroups = current->cgroups;
5039 get_css_set(child->cgroups);
5040 task_unlock(current);
5041 INIT_LIST_HEAD(&child->cg_list);
5045 * cgroup_post_fork - called on a new task after adding it to the task list
5046 * @child: the task in question
5048 * Adds the task to the list running through its css_set if necessary and
5049 * call the subsystem fork() callbacks. Has to be after the task is
5050 * visible on the task list in case we race with the first call to
5051 * cgroup_iter_start() - to guarantee that the new task ends up on its
5054 void cgroup_post_fork(struct task_struct *child)
5059 * use_task_css_set_links is set to 1 before we walk the tasklist
5060 * under the tasklist_lock and we read it here after we added the child
5061 * to the tasklist under the tasklist_lock as well. If the child wasn't
5062 * yet in the tasklist when we walked through it from
5063 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
5064 * should be visible now due to the paired locking and barriers implied
5065 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
5066 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
5069 if (use_task_css_set_links) {
5070 write_lock(&css_set_lock);
5072 if (list_empty(&child->cg_list))
5073 list_add(&child->cg_list, &child->cgroups->tasks);
5075 write_unlock(&css_set_lock);
5079 * Call ss->fork(). This must happen after @child is linked on
5080 * css_set; otherwise, @child might change state between ->fork()
5081 * and addition to css_set.
5083 if (need_forkexit_callback) {
5085 * fork/exit callbacks are supported only for builtin
5086 * subsystems, and the builtin section of the subsys
5087 * array is immutable, so we don't need to lock the
5088 * subsys array here. On the other hand, modular section
5089 * of the array can be freed at module unload, so we
5092 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
5093 struct cgroup_subsys *ss = subsys[i];
5102 * cgroup_exit - detach cgroup from exiting task
5103 * @tsk: pointer to task_struct of exiting process
5104 * @run_callback: run exit callbacks?
5106 * Description: Detach cgroup from @tsk and release it.
5108 * Note that cgroups marked notify_on_release force every task in
5109 * them to take the global cgroup_mutex mutex when exiting.
5110 * This could impact scaling on very large systems. Be reluctant to
5111 * use notify_on_release cgroups where very high task exit scaling
5112 * is required on large systems.
5114 * the_top_cgroup_hack:
5116 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5118 * We call cgroup_exit() while the task is still competent to
5119 * handle notify_on_release(), then leave the task attached to the
5120 * root cgroup in each hierarchy for the remainder of its exit.
5122 * To do this properly, we would increment the reference count on
5123 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5124 * code we would add a second cgroup function call, to drop that
5125 * reference. This would just create an unnecessary hot spot on
5126 * the top_cgroup reference count, to no avail.
5128 * Normally, holding a reference to a cgroup without bumping its
5129 * count is unsafe. The cgroup could go away, or someone could
5130 * attach us to a different cgroup, decrementing the count on
5131 * the first cgroup that we never incremented. But in this case,
5132 * top_cgroup isn't going away, and either task has PF_EXITING set,
5133 * which wards off any cgroup_attach_task() attempts, or task is a failed
5134 * fork, never visible to cgroup_attach_task.
5136 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5138 struct css_set *cset;
5142 * Unlink from the css_set task list if necessary.
5143 * Optimistically check cg_list before taking
5146 if (!list_empty(&tsk->cg_list)) {
5147 write_lock(&css_set_lock);
5148 if (!list_empty(&tsk->cg_list))
5149 list_del_init(&tsk->cg_list);
5150 write_unlock(&css_set_lock);
5153 /* Reassign the task to the init_css_set. */
5155 cset = tsk->cgroups;
5156 tsk->cgroups = &init_css_set;
5158 if (run_callbacks && need_forkexit_callback) {
5160 * fork/exit callbacks are supported only for builtin
5161 * subsystems, see cgroup_post_fork() for details.
5163 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
5164 struct cgroup_subsys *ss = subsys[i];
5167 struct cgroup *old_cgrp =
5168 rcu_dereference_raw(cset->subsys[i])->cgroup;
5169 struct cgroup *cgrp = task_cgroup(tsk, i);
5170 ss->exit(cgrp, old_cgrp, tsk);
5176 put_css_set_taskexit(cset);
5179 static void check_for_release(struct cgroup *cgrp)
5181 if (cgroup_is_releasable(cgrp) &&
5182 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5184 * Control Group is currently removeable. If it's not
5185 * already queued for a userspace notification, queue
5188 int need_schedule_work = 0;
5190 raw_spin_lock(&release_list_lock);
5191 if (!cgroup_is_dead(cgrp) &&
5192 list_empty(&cgrp->release_list)) {
5193 list_add(&cgrp->release_list, &release_list);
5194 need_schedule_work = 1;
5196 raw_spin_unlock(&release_list_lock);
5197 if (need_schedule_work)
5198 schedule_work(&release_agent_work);
5203 * Notify userspace when a cgroup is released, by running the
5204 * configured release agent with the name of the cgroup (path
5205 * relative to the root of cgroup file system) as the argument.
5207 * Most likely, this user command will try to rmdir this cgroup.
5209 * This races with the possibility that some other task will be
5210 * attached to this cgroup before it is removed, or that some other
5211 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5212 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5213 * unused, and this cgroup will be reprieved from its death sentence,
5214 * to continue to serve a useful existence. Next time it's released,
5215 * we will get notified again, if it still has 'notify_on_release' set.
5217 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5218 * means only wait until the task is successfully execve()'d. The
5219 * separate release agent task is forked by call_usermodehelper(),
5220 * then control in this thread returns here, without waiting for the
5221 * release agent task. We don't bother to wait because the caller of
5222 * this routine has no use for the exit status of the release agent
5223 * task, so no sense holding our caller up for that.
5225 static void cgroup_release_agent(struct work_struct *work)
5227 BUG_ON(work != &release_agent_work);
5228 mutex_lock(&cgroup_mutex);
5229 raw_spin_lock(&release_list_lock);
5230 while (!list_empty(&release_list)) {
5231 char *argv[3], *envp[3];
5233 char *pathbuf = NULL, *agentbuf = NULL;
5234 struct cgroup *cgrp = list_entry(release_list.next,
5237 list_del_init(&cgrp->release_list);
5238 raw_spin_unlock(&release_list_lock);
5239 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5242 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5244 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5249 argv[i++] = agentbuf;
5250 argv[i++] = pathbuf;
5254 /* minimal command environment */
5255 envp[i++] = "HOME=/";
5256 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5259 /* Drop the lock while we invoke the usermode helper,
5260 * since the exec could involve hitting disk and hence
5261 * be a slow process */
5262 mutex_unlock(&cgroup_mutex);
5263 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5264 mutex_lock(&cgroup_mutex);
5268 raw_spin_lock(&release_list_lock);
5270 raw_spin_unlock(&release_list_lock);
5271 mutex_unlock(&cgroup_mutex);
5274 static int __init cgroup_disable(char *str)
5279 while ((token = strsep(&str, ",")) != NULL) {
5282 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
5283 struct cgroup_subsys *ss = subsys[i];
5286 * cgroup_disable, being at boot time, can't
5287 * know about module subsystems, so we don't
5290 if (!ss || ss->module)
5293 if (!strcmp(token, ss->name)) {
5295 printk(KERN_INFO "Disabling %s control group"
5296 " subsystem\n", ss->name);
5303 __setup("cgroup_disable=", cgroup_disable);
5306 * Functons for CSS ID.
5309 /* to get ID other than 0, this should be called when !cgroup_is_dead() */
5310 unsigned short css_id(struct cgroup_subsys_state *css)
5312 struct css_id *cssid;
5315 * This css_id() can return correct value when somone has refcnt
5316 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5317 * it's unchanged until freed.
5319 cssid = rcu_dereference_raw(css->id);
5325 EXPORT_SYMBOL_GPL(css_id);
5328 * css_is_ancestor - test "root" css is an ancestor of "child"
5329 * @child: the css to be tested.
5330 * @root: the css supporsed to be an ancestor of the child.
5332 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5333 * this function reads css->id, the caller must hold rcu_read_lock().
5334 * But, considering usual usage, the csses should be valid objects after test.
5335 * Assuming that the caller will do some action to the child if this returns
5336 * returns true, the caller must take "child";s reference count.
5337 * If "child" is valid object and this returns true, "root" is valid, too.
5340 bool css_is_ancestor(struct cgroup_subsys_state *child,
5341 const struct cgroup_subsys_state *root)
5343 struct css_id *child_id;
5344 struct css_id *root_id;
5346 child_id = rcu_dereference(child->id);
5349 root_id = rcu_dereference(root->id);
5352 if (child_id->depth < root_id->depth)
5354 if (child_id->stack[root_id->depth] != root_id->id)
5359 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5361 struct css_id *id = css->id;
5362 /* When this is called before css_id initialization, id can be NULL */
5366 BUG_ON(!ss->use_id);
5368 rcu_assign_pointer(id->css, NULL);
5369 rcu_assign_pointer(css->id, NULL);
5370 spin_lock(&ss->id_lock);
5371 idr_remove(&ss->idr, id->id);
5372 spin_unlock(&ss->id_lock);
5373 kfree_rcu(id, rcu_head);
5375 EXPORT_SYMBOL_GPL(free_css_id);
5378 * This is called by init or create(). Then, calls to this function are
5379 * always serialized (By cgroup_mutex() at create()).
5382 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5384 struct css_id *newid;
5387 BUG_ON(!ss->use_id);
5389 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5390 newid = kzalloc(size, GFP_KERNEL);
5392 return ERR_PTR(-ENOMEM);
5394 idr_preload(GFP_KERNEL);
5395 spin_lock(&ss->id_lock);
5396 /* Don't use 0. allocates an ID of 1-65535 */
5397 ret = idr_alloc(&ss->idr, newid, 1, CSS_ID_MAX + 1, GFP_NOWAIT);
5398 spin_unlock(&ss->id_lock);
5401 /* Returns error when there are no free spaces for new ID.*/
5406 newid->depth = depth;
5410 return ERR_PTR(ret);
5414 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5415 struct cgroup_subsys_state *rootcss)
5417 struct css_id *newid;
5419 spin_lock_init(&ss->id_lock);
5422 newid = get_new_cssid(ss, 0);
5424 return PTR_ERR(newid);
5426 newid->stack[0] = newid->id;
5427 newid->css = rootcss;
5428 rootcss->id = newid;
5432 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5433 struct cgroup *child)
5435 int subsys_id, i, depth = 0;
5436 struct cgroup_subsys_state *parent_css, *child_css;
5437 struct css_id *child_id, *parent_id;
5439 subsys_id = ss->subsys_id;
5440 parent_css = parent->subsys[subsys_id];
5441 child_css = child->subsys[subsys_id];
5442 parent_id = parent_css->id;
5443 depth = parent_id->depth + 1;
5445 child_id = get_new_cssid(ss, depth);
5446 if (IS_ERR(child_id))
5447 return PTR_ERR(child_id);
5449 for (i = 0; i < depth; i++)
5450 child_id->stack[i] = parent_id->stack[i];
5451 child_id->stack[depth] = child_id->id;
5453 * child_id->css pointer will be set after this cgroup is available
5454 * see cgroup_populate_dir()
5456 rcu_assign_pointer(child_css->id, child_id);
5462 * css_lookup - lookup css by id
5463 * @ss: cgroup subsys to be looked into.
5466 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5467 * NULL if not. Should be called under rcu_read_lock()
5469 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5471 struct css_id *cssid = NULL;
5473 BUG_ON(!ss->use_id);
5474 cssid = idr_find(&ss->idr, id);
5476 if (unlikely(!cssid))
5479 return rcu_dereference(cssid->css);
5481 EXPORT_SYMBOL_GPL(css_lookup);
5484 * get corresponding css from file open on cgroupfs directory
5486 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5488 struct cgroup *cgrp;
5489 struct inode *inode;
5490 struct cgroup_subsys_state *css;
5492 inode = file_inode(f);
5493 /* check in cgroup filesystem dir */
5494 if (inode->i_op != &cgroup_dir_inode_operations)
5495 return ERR_PTR(-EBADF);
5497 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5498 return ERR_PTR(-EINVAL);
5501 cgrp = __d_cgrp(f->f_dentry);
5502 css = cgrp->subsys[id];
5503 return css ? css : ERR_PTR(-ENOENT);
5506 #ifdef CONFIG_CGROUP_DEBUG
5507 static struct cgroup_subsys_state *debug_css_alloc(struct cgroup *cont)
5509 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5512 return ERR_PTR(-ENOMEM);
5517 static void debug_css_free(struct cgroup *cont)
5519 kfree(cont->subsys[debug_subsys_id]);
5522 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5524 return cgroup_task_count(cont);
5527 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5529 return (u64)(unsigned long)current->cgroups;
5532 static u64 current_css_set_refcount_read(struct cgroup *cont,
5538 count = atomic_read(¤t->cgroups->refcount);
5543 static int current_css_set_cg_links_read(struct cgroup *cont,
5545 struct seq_file *seq)
5547 struct cgrp_cset_link *link;
5548 struct css_set *cset;
5550 read_lock(&css_set_lock);
5552 cset = rcu_dereference(current->cgroups);
5553 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5554 struct cgroup *c = link->cgrp;
5558 name = c->dentry->d_name.name;
5561 seq_printf(seq, "Root %d group %s\n",
5562 c->root->hierarchy_id, name);
5565 read_unlock(&css_set_lock);
5569 #define MAX_TASKS_SHOWN_PER_CSS 25
5570 static int cgroup_css_links_read(struct cgroup *cont,
5572 struct seq_file *seq)
5574 struct cgrp_cset_link *link;
5576 read_lock(&css_set_lock);
5577 list_for_each_entry(link, &cont->cset_links, cset_link) {
5578 struct css_set *cset = link->cset;
5579 struct task_struct *task;
5581 seq_printf(seq, "css_set %p\n", cset);
5582 list_for_each_entry(task, &cset->tasks, cg_list) {
5583 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5584 seq_puts(seq, " ...\n");
5587 seq_printf(seq, " task %d\n",
5588 task_pid_vnr(task));
5592 read_unlock(&css_set_lock);
5596 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5598 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5601 static struct cftype debug_files[] = {
5603 .name = "taskcount",
5604 .read_u64 = debug_taskcount_read,
5608 .name = "current_css_set",
5609 .read_u64 = current_css_set_read,
5613 .name = "current_css_set_refcount",
5614 .read_u64 = current_css_set_refcount_read,
5618 .name = "current_css_set_cg_links",
5619 .read_seq_string = current_css_set_cg_links_read,
5623 .name = "cgroup_css_links",
5624 .read_seq_string = cgroup_css_links_read,
5628 .name = "releasable",
5629 .read_u64 = releasable_read,
5635 struct cgroup_subsys debug_subsys = {
5637 .css_alloc = debug_css_alloc,
5638 .css_free = debug_css_free,
5639 .subsys_id = debug_subsys_id,
5640 .base_cftypes = debug_files,
5642 #endif /* CONFIG_CGROUP_DEBUG */