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>
34 #include <linux/init_task.h>
35 #include <linux/kernel.h>
36 #include <linux/list.h>
38 #include <linux/mutex.h>
39 #include <linux/mount.h>
40 #include <linux/pagemap.h>
41 #include <linux/proc_fs.h>
42 #include <linux/rcupdate.h>
43 #include <linux/sched.h>
44 #include <linux/backing-dev.h>
45 #include <linux/seq_file.h>
46 #include <linux/slab.h>
47 #include <linux/magic.h>
48 #include <linux/spinlock.h>
49 #include <linux/string.h>
50 #include <linux/sort.h>
51 #include <linux/kmod.h>
52 #include <linux/module.h>
53 #include <linux/delayacct.h>
54 #include <linux/cgroupstats.h>
55 #include <linux/hash.h>
56 #include <linux/namei.h>
57 #include <linux/pid_namespace.h>
58 #include <linux/idr.h>
59 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
60 #include <linux/eventfd.h>
61 #include <linux/poll.h>
62 #include <linux/flex_array.h> /* used in cgroup_attach_proc */
63 #include <linux/kthread.h>
65 #include <linux/atomic.h>
67 /* css deactivation bias, makes css->refcnt negative to deny new trygets */
68 #define CSS_DEACT_BIAS INT_MIN
71 * cgroup_mutex is the master lock. Any modification to cgroup or its
72 * hierarchy must be performed while holding it.
74 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
75 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
76 * release_agent_path and so on. Modifying requires both cgroup_mutex and
77 * cgroup_root_mutex. Readers can acquire either of the two. This is to
78 * break the following locking order cycle.
80 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
81 * B. namespace_sem -> cgroup_mutex
83 * B happens only through cgroup_show_options() and using cgroup_root_mutex
86 static DEFINE_MUTEX(cgroup_mutex);
87 static DEFINE_MUTEX(cgroup_root_mutex);
90 * Generate an array of cgroup subsystem pointers. At boot time, this is
91 * populated with the built in subsystems, and modular subsystems are
92 * registered after that. The mutable section of this array is protected by
95 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
96 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
97 static struct cgroup_subsys *subsys[CGROUP_SUBSYS_COUNT] = {
98 #include <linux/cgroup_subsys.h>
101 #define MAX_CGROUP_ROOT_NAMELEN 64
104 * A cgroupfs_root represents the root of a cgroup hierarchy,
105 * and may be associated with a superblock to form an active
108 struct cgroupfs_root {
109 struct super_block *sb;
112 * The bitmask of subsystems intended to be attached to this
115 unsigned long subsys_mask;
117 /* Unique id for this hierarchy. */
120 /* The bitmask of subsystems currently attached to this hierarchy */
121 unsigned long actual_subsys_mask;
123 /* A list running through the attached subsystems */
124 struct list_head subsys_list;
126 /* The root cgroup for this hierarchy */
127 struct cgroup top_cgroup;
129 /* Tracks how many cgroups are currently defined in hierarchy.*/
130 int number_of_cgroups;
132 /* A list running through the active hierarchies */
133 struct list_head root_list;
135 /* All cgroups on this root, cgroup_mutex protected */
136 struct list_head allcg_list;
138 /* Hierarchy-specific flags */
141 /* The path to use for release notifications. */
142 char release_agent_path[PATH_MAX];
144 /* The name for this hierarchy - may be empty */
145 char name[MAX_CGROUP_ROOT_NAMELEN];
149 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
150 * subsystems that are otherwise unattached - it never has more than a
151 * single cgroup, and all tasks are part of that cgroup.
153 static struct cgroupfs_root rootnode;
156 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
159 struct list_head node;
160 struct dentry *dentry;
165 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
166 * cgroup_subsys->use_id != 0.
168 #define CSS_ID_MAX (65535)
171 * The css to which this ID points. This pointer is set to valid value
172 * after cgroup is populated. If cgroup is removed, this will be NULL.
173 * This pointer is expected to be RCU-safe because destroy()
174 * is called after synchronize_rcu(). But for safe use, css_tryget()
175 * should be used for avoiding race.
177 struct cgroup_subsys_state __rcu *css;
183 * Depth in hierarchy which this ID belongs to.
185 unsigned short depth;
187 * ID is freed by RCU. (and lookup routine is RCU safe.)
189 struct rcu_head rcu_head;
191 * Hierarchy of CSS ID belongs to.
193 unsigned short stack[0]; /* Array of Length (depth+1) */
197 * cgroup_event represents events which userspace want to receive.
199 struct cgroup_event {
201 * Cgroup which the event belongs to.
205 * Control file which the event associated.
209 * eventfd to signal userspace about the event.
211 struct eventfd_ctx *eventfd;
213 * Each of these stored in a list by the cgroup.
215 struct list_head list;
217 * All fields below needed to unregister event when
218 * userspace closes eventfd.
221 wait_queue_head_t *wqh;
223 struct work_struct remove;
226 /* The list of hierarchy roots */
228 static LIST_HEAD(roots);
229 static int root_count;
231 static DEFINE_IDA(hierarchy_ida);
232 static int next_hierarchy_id;
233 static DEFINE_SPINLOCK(hierarchy_id_lock);
235 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
236 #define dummytop (&rootnode.top_cgroup)
238 /* This flag indicates whether tasks in the fork and exit paths should
239 * check for fork/exit handlers to call. This avoids us having to do
240 * extra work in the fork/exit path if none of the subsystems need to
243 static int need_forkexit_callback __read_mostly;
245 static int cgroup_destroy_locked(struct cgroup *cgrp);
247 #ifdef CONFIG_PROVE_LOCKING
248 int cgroup_lock_is_held(void)
250 return lockdep_is_held(&cgroup_mutex);
252 #else /* #ifdef CONFIG_PROVE_LOCKING */
253 int cgroup_lock_is_held(void)
255 return mutex_is_locked(&cgroup_mutex);
257 #endif /* #else #ifdef CONFIG_PROVE_LOCKING */
259 EXPORT_SYMBOL_GPL(cgroup_lock_is_held);
261 static int css_unbias_refcnt(int refcnt)
263 return refcnt >= 0 ? refcnt : refcnt - CSS_DEACT_BIAS;
266 /* the current nr of refs, always >= 0 whether @css is deactivated or not */
267 static int css_refcnt(struct cgroup_subsys_state *css)
269 int v = atomic_read(&css->refcnt);
271 return css_unbias_refcnt(v);
274 /* convenient tests for these bits */
275 inline int cgroup_is_removed(const struct cgroup *cgrp)
277 return test_bit(CGRP_REMOVED, &cgrp->flags);
280 /* bits in struct cgroupfs_root flags field */
282 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
283 ROOT_XATTR, /* supports extended attributes */
286 static int cgroup_is_releasable(const struct cgroup *cgrp)
289 (1 << CGRP_RELEASABLE) |
290 (1 << CGRP_NOTIFY_ON_RELEASE);
291 return (cgrp->flags & bits) == bits;
294 static int notify_on_release(const struct cgroup *cgrp)
296 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
300 * for_each_subsys() allows you to iterate on each subsystem attached to
301 * an active hierarchy
303 #define for_each_subsys(_root, _ss) \
304 list_for_each_entry(_ss, &_root->subsys_list, sibling)
306 /* for_each_active_root() allows you to iterate across the active hierarchies */
307 #define for_each_active_root(_root) \
308 list_for_each_entry(_root, &roots, root_list)
310 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
312 return dentry->d_fsdata;
315 static inline struct cfent *__d_cfe(struct dentry *dentry)
317 return dentry->d_fsdata;
320 static inline struct cftype *__d_cft(struct dentry *dentry)
322 return __d_cfe(dentry)->type;
325 /* the list of cgroups eligible for automatic release. Protected by
326 * release_list_lock */
327 static LIST_HEAD(release_list);
328 static DEFINE_RAW_SPINLOCK(release_list_lock);
329 static void cgroup_release_agent(struct work_struct *work);
330 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
331 static void check_for_release(struct cgroup *cgrp);
333 /* Link structure for associating css_set objects with cgroups */
334 struct cg_cgroup_link {
336 * List running through cg_cgroup_links associated with a
337 * cgroup, anchored on cgroup->css_sets
339 struct list_head cgrp_link_list;
342 * List running through cg_cgroup_links pointing at a
343 * single css_set object, anchored on css_set->cg_links
345 struct list_head cg_link_list;
349 /* The default css_set - used by init and its children prior to any
350 * hierarchies being mounted. It contains a pointer to the root state
351 * for each subsystem. Also used to anchor the list of css_sets. Not
352 * reference-counted, to improve performance when child cgroups
353 * haven't been created.
356 static struct css_set init_css_set;
357 static struct cg_cgroup_link init_css_set_link;
359 static int cgroup_init_idr(struct cgroup_subsys *ss,
360 struct cgroup_subsys_state *css);
362 /* css_set_lock protects the list of css_set objects, and the
363 * chain of tasks off each css_set. Nests outside task->alloc_lock
364 * due to cgroup_iter_start() */
365 static DEFINE_RWLOCK(css_set_lock);
366 static int css_set_count;
369 * hash table for cgroup groups. This improves the performance to find
370 * an existing css_set. This hash doesn't (currently) take into
371 * account cgroups in empty hierarchies.
373 #define CSS_SET_HASH_BITS 7
374 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
375 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
377 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
381 unsigned long tmp = 0UL;
383 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
384 tmp += (unsigned long)css[i];
385 tmp = (tmp >> 16) ^ tmp;
387 index = hash_long(tmp, CSS_SET_HASH_BITS);
389 return &css_set_table[index];
392 /* We don't maintain the lists running through each css_set to its
393 * task until after the first call to cgroup_iter_start(). This
394 * reduces the fork()/exit() overhead for people who have cgroups
395 * compiled into their kernel but not actually in use */
396 static int use_task_css_set_links __read_mostly;
398 static void __put_css_set(struct css_set *cg, int taskexit)
400 struct cg_cgroup_link *link;
401 struct cg_cgroup_link *saved_link;
403 * Ensure that the refcount doesn't hit zero while any readers
404 * can see it. Similar to atomic_dec_and_lock(), but for an
407 if (atomic_add_unless(&cg->refcount, -1, 1))
409 write_lock(&css_set_lock);
410 if (!atomic_dec_and_test(&cg->refcount)) {
411 write_unlock(&css_set_lock);
415 /* This css_set is dead. unlink it and release cgroup refcounts */
416 hlist_del(&cg->hlist);
419 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
421 struct cgroup *cgrp = link->cgrp;
422 list_del(&link->cg_link_list);
423 list_del(&link->cgrp_link_list);
424 if (atomic_dec_and_test(&cgrp->count) &&
425 notify_on_release(cgrp)) {
427 set_bit(CGRP_RELEASABLE, &cgrp->flags);
428 check_for_release(cgrp);
434 write_unlock(&css_set_lock);
435 kfree_rcu(cg, rcu_head);
439 * refcounted get/put for css_set objects
441 static inline void get_css_set(struct css_set *cg)
443 atomic_inc(&cg->refcount);
446 static inline void put_css_set(struct css_set *cg)
448 __put_css_set(cg, 0);
451 static inline void put_css_set_taskexit(struct css_set *cg)
453 __put_css_set(cg, 1);
457 * compare_css_sets - helper function for find_existing_css_set().
458 * @cg: candidate css_set being tested
459 * @old_cg: existing css_set for a task
460 * @new_cgrp: cgroup that's being entered by the task
461 * @template: desired set of css pointers in css_set (pre-calculated)
463 * Returns true if "cg" matches "old_cg" except for the hierarchy
464 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
466 static bool compare_css_sets(struct css_set *cg,
467 struct css_set *old_cg,
468 struct cgroup *new_cgrp,
469 struct cgroup_subsys_state *template[])
471 struct list_head *l1, *l2;
473 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
474 /* Not all subsystems matched */
479 * Compare cgroup pointers in order to distinguish between
480 * different cgroups in heirarchies with no subsystems. We
481 * could get by with just this check alone (and skip the
482 * memcmp above) but on most setups the memcmp check will
483 * avoid the need for this more expensive check on almost all
488 l2 = &old_cg->cg_links;
490 struct cg_cgroup_link *cgl1, *cgl2;
491 struct cgroup *cg1, *cg2;
495 /* See if we reached the end - both lists are equal length. */
496 if (l1 == &cg->cg_links) {
497 BUG_ON(l2 != &old_cg->cg_links);
500 BUG_ON(l2 == &old_cg->cg_links);
502 /* Locate the cgroups associated with these links. */
503 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
504 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
507 /* Hierarchies should be linked in the same order. */
508 BUG_ON(cg1->root != cg2->root);
511 * If this hierarchy is the hierarchy of the cgroup
512 * that's changing, then we need to check that this
513 * css_set points to the new cgroup; if it's any other
514 * hierarchy, then this css_set should point to the
515 * same cgroup as the old css_set.
517 if (cg1->root == new_cgrp->root) {
529 * find_existing_css_set() is a helper for
530 * find_css_set(), and checks to see whether an existing
531 * css_set is suitable.
533 * oldcg: the cgroup group that we're using before the cgroup
536 * cgrp: the cgroup that we're moving into
538 * template: location in which to build the desired set of subsystem
539 * state objects for the new cgroup group
541 static struct css_set *find_existing_css_set(
542 struct css_set *oldcg,
544 struct cgroup_subsys_state *template[])
547 struct cgroupfs_root *root = cgrp->root;
548 struct hlist_head *hhead;
549 struct hlist_node *node;
553 * Build the set of subsystem state objects that we want to see in the
554 * new css_set. while subsystems can change globally, the entries here
555 * won't change, so no need for locking.
557 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
558 if (root->subsys_mask & (1UL << i)) {
559 /* Subsystem is in this hierarchy. So we want
560 * the subsystem state from the new
562 template[i] = cgrp->subsys[i];
564 /* Subsystem is not in this hierarchy, so we
565 * don't want to change the subsystem state */
566 template[i] = oldcg->subsys[i];
570 hhead = css_set_hash(template);
571 hlist_for_each_entry(cg, node, hhead, hlist) {
572 if (!compare_css_sets(cg, oldcg, cgrp, template))
575 /* This css_set matches what we need */
579 /* No existing cgroup group matched */
583 static void free_cg_links(struct list_head *tmp)
585 struct cg_cgroup_link *link;
586 struct cg_cgroup_link *saved_link;
588 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
589 list_del(&link->cgrp_link_list);
595 * allocate_cg_links() allocates "count" cg_cgroup_link structures
596 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
597 * success or a negative error
599 static int allocate_cg_links(int count, struct list_head *tmp)
601 struct cg_cgroup_link *link;
604 for (i = 0; i < count; i++) {
605 link = kmalloc(sizeof(*link), GFP_KERNEL);
610 list_add(&link->cgrp_link_list, tmp);
616 * link_css_set - a helper function to link a css_set to a cgroup
617 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
618 * @cg: the css_set to be linked
619 * @cgrp: the destination cgroup
621 static void link_css_set(struct list_head *tmp_cg_links,
622 struct css_set *cg, struct cgroup *cgrp)
624 struct cg_cgroup_link *link;
626 BUG_ON(list_empty(tmp_cg_links));
627 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
631 atomic_inc(&cgrp->count);
632 list_move(&link->cgrp_link_list, &cgrp->css_sets);
634 * Always add links to the tail of the list so that the list
635 * is sorted by order of hierarchy creation
637 list_add_tail(&link->cg_link_list, &cg->cg_links);
641 * find_css_set() takes an existing cgroup group and a
642 * cgroup object, and returns a css_set object that's
643 * equivalent to the old group, but with the given cgroup
644 * substituted into the appropriate hierarchy. Must be called with
647 static struct css_set *find_css_set(
648 struct css_set *oldcg, struct cgroup *cgrp)
651 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
653 struct list_head tmp_cg_links;
655 struct hlist_head *hhead;
656 struct cg_cgroup_link *link;
658 /* First see if we already have a cgroup group that matches
660 read_lock(&css_set_lock);
661 res = find_existing_css_set(oldcg, cgrp, template);
664 read_unlock(&css_set_lock);
669 res = kmalloc(sizeof(*res), GFP_KERNEL);
673 /* Allocate all the cg_cgroup_link objects that we'll need */
674 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
679 atomic_set(&res->refcount, 1);
680 INIT_LIST_HEAD(&res->cg_links);
681 INIT_LIST_HEAD(&res->tasks);
682 INIT_HLIST_NODE(&res->hlist);
684 /* Copy the set of subsystem state objects generated in
685 * find_existing_css_set() */
686 memcpy(res->subsys, template, sizeof(res->subsys));
688 write_lock(&css_set_lock);
689 /* Add reference counts and links from the new css_set. */
690 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
691 struct cgroup *c = link->cgrp;
692 if (c->root == cgrp->root)
694 link_css_set(&tmp_cg_links, res, c);
697 BUG_ON(!list_empty(&tmp_cg_links));
701 /* Add this cgroup group to the hash table */
702 hhead = css_set_hash(res->subsys);
703 hlist_add_head(&res->hlist, hhead);
705 write_unlock(&css_set_lock);
711 * Return the cgroup for "task" from the given hierarchy. Must be
712 * called with cgroup_mutex held.
714 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
715 struct cgroupfs_root *root)
718 struct cgroup *res = NULL;
720 BUG_ON(!mutex_is_locked(&cgroup_mutex));
721 read_lock(&css_set_lock);
723 * No need to lock the task - since we hold cgroup_mutex the
724 * task can't change groups, so the only thing that can happen
725 * is that it exits and its css is set back to init_css_set.
728 if (css == &init_css_set) {
729 res = &root->top_cgroup;
731 struct cg_cgroup_link *link;
732 list_for_each_entry(link, &css->cg_links, cg_link_list) {
733 struct cgroup *c = link->cgrp;
734 if (c->root == root) {
740 read_unlock(&css_set_lock);
746 * There is one global cgroup mutex. We also require taking
747 * task_lock() when dereferencing a task's cgroup subsys pointers.
748 * See "The task_lock() exception", at the end of this comment.
750 * A task must hold cgroup_mutex to modify cgroups.
752 * Any task can increment and decrement the count field without lock.
753 * So in general, code holding cgroup_mutex can't rely on the count
754 * field not changing. However, if the count goes to zero, then only
755 * cgroup_attach_task() can increment it again. Because a count of zero
756 * means that no tasks are currently attached, therefore there is no
757 * way a task attached to that cgroup can fork (the other way to
758 * increment the count). So code holding cgroup_mutex can safely
759 * assume that if the count is zero, it will stay zero. Similarly, if
760 * a task holds cgroup_mutex on a cgroup with zero count, it
761 * knows that the cgroup won't be removed, as cgroup_rmdir()
764 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
765 * (usually) take cgroup_mutex. These are the two most performance
766 * critical pieces of code here. The exception occurs on cgroup_exit(),
767 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
768 * is taken, and if the cgroup count is zero, a usermode call made
769 * to the release agent with the name of the cgroup (path relative to
770 * the root of cgroup file system) as the argument.
772 * A cgroup can only be deleted if both its 'count' of using tasks
773 * is zero, and its list of 'children' cgroups is empty. Since all
774 * tasks in the system use _some_ cgroup, and since there is always at
775 * least one task in the system (init, pid == 1), therefore, top_cgroup
776 * always has either children cgroups and/or using tasks. So we don't
777 * need a special hack to ensure that top_cgroup cannot be deleted.
779 * The task_lock() exception
781 * The need for this exception arises from the action of
782 * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
783 * another. It does so using cgroup_mutex, however there are
784 * several performance critical places that need to reference
785 * task->cgroup without the expense of grabbing a system global
786 * mutex. Therefore except as noted below, when dereferencing or, as
787 * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
788 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
789 * the task_struct routinely used for such matters.
791 * P.S. One more locking exception. RCU is used to guard the
792 * update of a tasks cgroup pointer by cgroup_attach_task()
796 * cgroup_lock - lock out any changes to cgroup structures
799 void cgroup_lock(void)
801 mutex_lock(&cgroup_mutex);
803 EXPORT_SYMBOL_GPL(cgroup_lock);
806 * cgroup_unlock - release lock on cgroup changes
808 * Undo the lock taken in a previous cgroup_lock() call.
810 void cgroup_unlock(void)
812 mutex_unlock(&cgroup_mutex);
814 EXPORT_SYMBOL_GPL(cgroup_unlock);
817 * A couple of forward declarations required, due to cyclic reference loop:
818 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
819 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
823 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
824 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
825 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
826 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
827 unsigned long subsys_mask);
828 static const struct inode_operations cgroup_dir_inode_operations;
829 static const struct file_operations proc_cgroupstats_operations;
831 static struct backing_dev_info cgroup_backing_dev_info = {
833 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
836 static int alloc_css_id(struct cgroup_subsys *ss,
837 struct cgroup *parent, struct cgroup *child);
839 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
841 struct inode *inode = new_inode(sb);
844 inode->i_ino = get_next_ino();
845 inode->i_mode = mode;
846 inode->i_uid = current_fsuid();
847 inode->i_gid = current_fsgid();
848 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
849 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
854 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
856 /* is dentry a directory ? if so, kfree() associated cgroup */
857 if (S_ISDIR(inode->i_mode)) {
858 struct cgroup *cgrp = dentry->d_fsdata;
859 struct cgroup_subsys *ss;
860 BUG_ON(!(cgroup_is_removed(cgrp)));
861 /* It's possible for external users to be holding css
862 * reference counts on a cgroup; css_put() needs to
863 * be able to access the cgroup after decrementing
864 * the reference count in order to know if it needs to
865 * queue the cgroup to be handled by the release
869 mutex_lock(&cgroup_mutex);
871 * Release the subsystem state objects.
873 for_each_subsys(cgrp->root, ss)
876 cgrp->root->number_of_cgroups--;
877 mutex_unlock(&cgroup_mutex);
880 * Drop the active superblock reference that we took when we
883 deactivate_super(cgrp->root->sb);
886 * if we're getting rid of the cgroup, refcount should ensure
887 * that there are no pidlists left.
889 BUG_ON(!list_empty(&cgrp->pidlists));
891 simple_xattrs_free(&cgrp->xattrs);
893 kfree_rcu(cgrp, rcu_head);
895 struct cfent *cfe = __d_cfe(dentry);
896 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
897 struct cftype *cft = cfe->type;
899 WARN_ONCE(!list_empty(&cfe->node) &&
900 cgrp != &cgrp->root->top_cgroup,
901 "cfe still linked for %s\n", cfe->type->name);
903 simple_xattrs_free(&cft->xattrs);
908 static int cgroup_delete(const struct dentry *d)
913 static void remove_dir(struct dentry *d)
915 struct dentry *parent = dget(d->d_parent);
918 simple_rmdir(parent->d_inode, d);
922 static int cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
926 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
927 lockdep_assert_held(&cgroup_mutex);
929 list_for_each_entry(cfe, &cgrp->files, node) {
930 struct dentry *d = cfe->dentry;
932 if (cft && cfe->type != cft)
937 simple_unlink(cgrp->dentry->d_inode, d);
938 list_del_init(&cfe->node);
947 * cgroup_clear_directory - selective removal of base and subsystem files
948 * @dir: directory containing the files
949 * @base_files: true if the base files should be removed
950 * @subsys_mask: mask of the subsystem ids whose files should be removed
952 static void cgroup_clear_directory(struct dentry *dir, bool base_files,
953 unsigned long subsys_mask)
955 struct cgroup *cgrp = __d_cgrp(dir);
956 struct cgroup_subsys *ss;
958 for_each_subsys(cgrp->root, ss) {
959 struct cftype_set *set;
960 if (!test_bit(ss->subsys_id, &subsys_mask))
962 list_for_each_entry(set, &ss->cftsets, node)
963 cgroup_rm_file(cgrp, set->cfts);
966 while (!list_empty(&cgrp->files))
967 cgroup_rm_file(cgrp, NULL);
972 * NOTE : the dentry must have been dget()'ed
974 static void cgroup_d_remove_dir(struct dentry *dentry)
976 struct dentry *parent;
977 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
979 cgroup_clear_directory(dentry, true, root->subsys_mask);
981 parent = dentry->d_parent;
982 spin_lock(&parent->d_lock);
983 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
984 list_del_init(&dentry->d_u.d_child);
985 spin_unlock(&dentry->d_lock);
986 spin_unlock(&parent->d_lock);
991 * Call with cgroup_mutex held. Drops reference counts on modules, including
992 * any duplicate ones that parse_cgroupfs_options took. If this function
993 * returns an error, no reference counts are touched.
995 static int rebind_subsystems(struct cgroupfs_root *root,
996 unsigned long final_subsys_mask)
998 unsigned long added_mask, removed_mask;
999 struct cgroup *cgrp = &root->top_cgroup;
1002 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1003 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1005 removed_mask = root->actual_subsys_mask & ~final_subsys_mask;
1006 added_mask = final_subsys_mask & ~root->actual_subsys_mask;
1007 /* Check that any added subsystems are currently free */
1008 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1009 unsigned long bit = 1UL << i;
1010 struct cgroup_subsys *ss = subsys[i];
1011 if (!(bit & added_mask))
1014 * Nobody should tell us to do a subsys that doesn't exist:
1015 * parse_cgroupfs_options should catch that case and refcounts
1016 * ensure that subsystems won't disappear once selected.
1019 if (ss->root != &rootnode) {
1020 /* Subsystem isn't free */
1025 /* Currently we don't handle adding/removing subsystems when
1026 * any child cgroups exist. This is theoretically supportable
1027 * but involves complex error handling, so it's being left until
1029 if (root->number_of_cgroups > 1)
1032 /* Process each subsystem */
1033 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1034 struct cgroup_subsys *ss = subsys[i];
1035 unsigned long bit = 1UL << i;
1036 if (bit & added_mask) {
1037 /* We're binding this subsystem to this hierarchy */
1039 BUG_ON(cgrp->subsys[i]);
1040 BUG_ON(!dummytop->subsys[i]);
1041 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
1042 cgrp->subsys[i] = dummytop->subsys[i];
1043 cgrp->subsys[i]->cgroup = cgrp;
1044 list_move(&ss->sibling, &root->subsys_list);
1048 /* refcount was already taken, and we're keeping it */
1049 } else if (bit & removed_mask) {
1050 /* We're removing this subsystem */
1052 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1053 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1056 dummytop->subsys[i]->cgroup = dummytop;
1057 cgrp->subsys[i] = NULL;
1058 subsys[i]->root = &rootnode;
1059 list_move(&ss->sibling, &rootnode.subsys_list);
1060 /* subsystem is now free - drop reference on module */
1061 module_put(ss->module);
1062 } else if (bit & final_subsys_mask) {
1063 /* Subsystem state should already exist */
1065 BUG_ON(!cgrp->subsys[i]);
1067 * a refcount was taken, but we already had one, so
1068 * drop the extra reference.
1070 module_put(ss->module);
1071 #ifdef CONFIG_MODULE_UNLOAD
1072 BUG_ON(ss->module && !module_refcount(ss->module));
1075 /* Subsystem state shouldn't exist */
1076 BUG_ON(cgrp->subsys[i]);
1079 root->subsys_mask = root->actual_subsys_mask = final_subsys_mask;
1085 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1087 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1088 struct cgroup_subsys *ss;
1090 mutex_lock(&cgroup_root_mutex);
1091 for_each_subsys(root, ss)
1092 seq_printf(seq, ",%s", ss->name);
1093 if (test_bit(ROOT_NOPREFIX, &root->flags))
1094 seq_puts(seq, ",noprefix");
1095 if (test_bit(ROOT_XATTR, &root->flags))
1096 seq_puts(seq, ",xattr");
1097 if (strlen(root->release_agent_path))
1098 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1099 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1100 seq_puts(seq, ",clone_children");
1101 if (strlen(root->name))
1102 seq_printf(seq, ",name=%s", root->name);
1103 mutex_unlock(&cgroup_root_mutex);
1107 struct cgroup_sb_opts {
1108 unsigned long subsys_mask;
1109 unsigned long flags;
1110 char *release_agent;
1111 bool cpuset_clone_children;
1113 /* User explicitly requested empty subsystem */
1116 struct cgroupfs_root *new_root;
1121 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1122 * with cgroup_mutex held to protect the subsys[] array. This function takes
1123 * refcounts on subsystems to be used, unless it returns error, in which case
1124 * no refcounts are taken.
1126 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1128 char *token, *o = data;
1129 bool all_ss = false, one_ss = false;
1130 unsigned long mask = (unsigned long)-1;
1132 bool module_pin_failed = false;
1134 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1136 #ifdef CONFIG_CPUSETS
1137 mask = ~(1UL << cpuset_subsys_id);
1140 memset(opts, 0, sizeof(*opts));
1142 while ((token = strsep(&o, ",")) != NULL) {
1145 if (!strcmp(token, "none")) {
1146 /* Explicitly have no subsystems */
1150 if (!strcmp(token, "all")) {
1151 /* Mutually exclusive option 'all' + subsystem name */
1157 if (!strcmp(token, "noprefix")) {
1158 set_bit(ROOT_NOPREFIX, &opts->flags);
1161 if (!strcmp(token, "clone_children")) {
1162 opts->cpuset_clone_children = true;
1165 if (!strcmp(token, "xattr")) {
1166 set_bit(ROOT_XATTR, &opts->flags);
1169 if (!strncmp(token, "release_agent=", 14)) {
1170 /* Specifying two release agents is forbidden */
1171 if (opts->release_agent)
1173 opts->release_agent =
1174 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1175 if (!opts->release_agent)
1179 if (!strncmp(token, "name=", 5)) {
1180 const char *name = token + 5;
1181 /* Can't specify an empty name */
1184 /* Must match [\w.-]+ */
1185 for (i = 0; i < strlen(name); i++) {
1189 if ((c == '.') || (c == '-') || (c == '_'))
1193 /* Specifying two names is forbidden */
1196 opts->name = kstrndup(name,
1197 MAX_CGROUP_ROOT_NAMELEN - 1,
1205 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1206 struct cgroup_subsys *ss = subsys[i];
1209 if (strcmp(token, ss->name))
1214 /* Mutually exclusive option 'all' + subsystem name */
1217 set_bit(i, &opts->subsys_mask);
1222 if (i == CGROUP_SUBSYS_COUNT)
1227 * If the 'all' option was specified select all the subsystems,
1228 * otherwise if 'none', 'name=' and a subsystem name options
1229 * were not specified, let's default to 'all'
1231 if (all_ss || (!one_ss && !opts->none && !opts->name)) {
1232 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1233 struct cgroup_subsys *ss = subsys[i];
1238 set_bit(i, &opts->subsys_mask);
1242 /* Consistency checks */
1245 * Option noprefix was introduced just for backward compatibility
1246 * with the old cpuset, so we allow noprefix only if mounting just
1247 * the cpuset subsystem.
1249 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1250 (opts->subsys_mask & mask))
1254 /* Can't specify "none" and some subsystems */
1255 if (opts->subsys_mask && opts->none)
1259 * We either have to specify by name or by subsystems. (So all
1260 * empty hierarchies must have a name).
1262 if (!opts->subsys_mask && !opts->name)
1266 * Grab references on all the modules we'll need, so the subsystems
1267 * don't dance around before rebind_subsystems attaches them. This may
1268 * take duplicate reference counts on a subsystem that's already used,
1269 * but rebind_subsystems handles this case.
1271 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1272 unsigned long bit = 1UL << i;
1274 if (!(bit & opts->subsys_mask))
1276 if (!try_module_get(subsys[i]->module)) {
1277 module_pin_failed = true;
1281 if (module_pin_failed) {
1283 * oops, one of the modules was going away. this means that we
1284 * raced with a module_delete call, and to the user this is
1285 * essentially a "subsystem doesn't exist" case.
1287 for (i--; i >= 0; i--) {
1288 /* drop refcounts only on the ones we took */
1289 unsigned long bit = 1UL << i;
1291 if (!(bit & opts->subsys_mask))
1293 module_put(subsys[i]->module);
1301 static void drop_parsed_module_refcounts(unsigned long subsys_mask)
1304 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1305 unsigned long bit = 1UL << i;
1307 if (!(bit & subsys_mask))
1309 module_put(subsys[i]->module);
1313 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1316 struct cgroupfs_root *root = sb->s_fs_info;
1317 struct cgroup *cgrp = &root->top_cgroup;
1318 struct cgroup_sb_opts opts;
1319 unsigned long added_mask, removed_mask;
1321 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1322 mutex_lock(&cgroup_mutex);
1323 mutex_lock(&cgroup_root_mutex);
1325 /* See what subsystems are wanted */
1326 ret = parse_cgroupfs_options(data, &opts);
1330 /* See feature-removal-schedule.txt */
1331 if (opts.subsys_mask != root->actual_subsys_mask || opts.release_agent)
1332 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1333 task_tgid_nr(current), current->comm);
1335 added_mask = opts.subsys_mask & ~root->subsys_mask;
1336 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1338 /* Don't allow flags or name to change at remount */
1339 if (opts.flags != root->flags ||
1340 (opts.name && strcmp(opts.name, root->name))) {
1342 drop_parsed_module_refcounts(opts.subsys_mask);
1346 ret = rebind_subsystems(root, opts.subsys_mask);
1348 drop_parsed_module_refcounts(opts.subsys_mask);
1352 /* clear out any existing files and repopulate subsystem files */
1353 cgroup_clear_directory(cgrp->dentry, false, removed_mask);
1354 /* re-populate subsystem files */
1355 cgroup_populate_dir(cgrp, false, added_mask);
1357 if (opts.release_agent)
1358 strcpy(root->release_agent_path, opts.release_agent);
1360 kfree(opts.release_agent);
1362 mutex_unlock(&cgroup_root_mutex);
1363 mutex_unlock(&cgroup_mutex);
1364 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1368 static const struct super_operations cgroup_ops = {
1369 .statfs = simple_statfs,
1370 .drop_inode = generic_delete_inode,
1371 .show_options = cgroup_show_options,
1372 .remount_fs = cgroup_remount,
1375 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1377 INIT_LIST_HEAD(&cgrp->sibling);
1378 INIT_LIST_HEAD(&cgrp->children);
1379 INIT_LIST_HEAD(&cgrp->files);
1380 INIT_LIST_HEAD(&cgrp->css_sets);
1381 INIT_LIST_HEAD(&cgrp->allcg_node);
1382 INIT_LIST_HEAD(&cgrp->release_list);
1383 INIT_LIST_HEAD(&cgrp->pidlists);
1384 mutex_init(&cgrp->pidlist_mutex);
1385 INIT_LIST_HEAD(&cgrp->event_list);
1386 spin_lock_init(&cgrp->event_list_lock);
1387 simple_xattrs_init(&cgrp->xattrs);
1390 static void init_cgroup_root(struct cgroupfs_root *root)
1392 struct cgroup *cgrp = &root->top_cgroup;
1394 INIT_LIST_HEAD(&root->subsys_list);
1395 INIT_LIST_HEAD(&root->root_list);
1396 INIT_LIST_HEAD(&root->allcg_list);
1397 root->number_of_cgroups = 1;
1399 cgrp->top_cgroup = cgrp;
1400 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
1401 init_cgroup_housekeeping(cgrp);
1404 static bool init_root_id(struct cgroupfs_root *root)
1409 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1411 spin_lock(&hierarchy_id_lock);
1412 /* Try to allocate the next unused ID */
1413 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1414 &root->hierarchy_id);
1416 /* Try again starting from 0 */
1417 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1419 next_hierarchy_id = root->hierarchy_id + 1;
1420 } else if (ret != -EAGAIN) {
1421 /* Can only get here if the 31-bit IDR is full ... */
1424 spin_unlock(&hierarchy_id_lock);
1429 static int cgroup_test_super(struct super_block *sb, void *data)
1431 struct cgroup_sb_opts *opts = data;
1432 struct cgroupfs_root *root = sb->s_fs_info;
1434 /* If we asked for a name then it must match */
1435 if (opts->name && strcmp(opts->name, root->name))
1439 * If we asked for subsystems (or explicitly for no
1440 * subsystems) then they must match
1442 if ((opts->subsys_mask || opts->none)
1443 && (opts->subsys_mask != root->subsys_mask))
1449 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1451 struct cgroupfs_root *root;
1453 if (!opts->subsys_mask && !opts->none)
1456 root = kzalloc(sizeof(*root), GFP_KERNEL);
1458 return ERR_PTR(-ENOMEM);
1460 if (!init_root_id(root)) {
1462 return ERR_PTR(-ENOMEM);
1464 init_cgroup_root(root);
1466 root->subsys_mask = opts->subsys_mask;
1467 root->flags = opts->flags;
1468 if (opts->release_agent)
1469 strcpy(root->release_agent_path, opts->release_agent);
1471 strcpy(root->name, opts->name);
1472 if (opts->cpuset_clone_children)
1473 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1477 static void cgroup_drop_root(struct cgroupfs_root *root)
1482 BUG_ON(!root->hierarchy_id);
1483 spin_lock(&hierarchy_id_lock);
1484 ida_remove(&hierarchy_ida, root->hierarchy_id);
1485 spin_unlock(&hierarchy_id_lock);
1489 static int cgroup_set_super(struct super_block *sb, void *data)
1492 struct cgroup_sb_opts *opts = data;
1494 /* If we don't have a new root, we can't set up a new sb */
1495 if (!opts->new_root)
1498 BUG_ON(!opts->subsys_mask && !opts->none);
1500 ret = set_anon_super(sb, NULL);
1504 sb->s_fs_info = opts->new_root;
1505 opts->new_root->sb = sb;
1507 sb->s_blocksize = PAGE_CACHE_SIZE;
1508 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1509 sb->s_magic = CGROUP_SUPER_MAGIC;
1510 sb->s_op = &cgroup_ops;
1515 static int cgroup_get_rootdir(struct super_block *sb)
1517 static const struct dentry_operations cgroup_dops = {
1518 .d_iput = cgroup_diput,
1519 .d_delete = cgroup_delete,
1522 struct inode *inode =
1523 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1528 inode->i_fop = &simple_dir_operations;
1529 inode->i_op = &cgroup_dir_inode_operations;
1530 /* directories start off with i_nlink == 2 (for "." entry) */
1532 sb->s_root = d_make_root(inode);
1535 /* for everything else we want ->d_op set */
1536 sb->s_d_op = &cgroup_dops;
1540 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1541 int flags, const char *unused_dev_name,
1544 struct cgroup_sb_opts opts;
1545 struct cgroupfs_root *root;
1547 struct super_block *sb;
1548 struct cgroupfs_root *new_root;
1549 struct inode *inode;
1551 /* First find the desired set of subsystems */
1552 mutex_lock(&cgroup_mutex);
1553 ret = parse_cgroupfs_options(data, &opts);
1554 mutex_unlock(&cgroup_mutex);
1559 * Allocate a new cgroup root. We may not need it if we're
1560 * reusing an existing hierarchy.
1562 new_root = cgroup_root_from_opts(&opts);
1563 if (IS_ERR(new_root)) {
1564 ret = PTR_ERR(new_root);
1567 opts.new_root = new_root;
1569 /* Locate an existing or new sb for this hierarchy */
1570 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1573 cgroup_drop_root(opts.new_root);
1577 root = sb->s_fs_info;
1579 if (root == opts.new_root) {
1580 /* We used the new root structure, so this is a new hierarchy */
1581 struct list_head tmp_cg_links;
1582 struct cgroup *root_cgrp = &root->top_cgroup;
1583 struct cgroupfs_root *existing_root;
1584 const struct cred *cred;
1587 BUG_ON(sb->s_root != NULL);
1589 ret = cgroup_get_rootdir(sb);
1591 goto drop_new_super;
1592 inode = sb->s_root->d_inode;
1594 mutex_lock(&inode->i_mutex);
1595 mutex_lock(&cgroup_mutex);
1596 mutex_lock(&cgroup_root_mutex);
1598 /* Check for name clashes with existing mounts */
1600 if (strlen(root->name))
1601 for_each_active_root(existing_root)
1602 if (!strcmp(existing_root->name, root->name))
1606 * We're accessing css_set_count without locking
1607 * css_set_lock here, but that's OK - it can only be
1608 * increased by someone holding cgroup_lock, and
1609 * that's us. The worst that can happen is that we
1610 * have some link structures left over
1612 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1616 ret = rebind_subsystems(root, root->subsys_mask);
1617 if (ret == -EBUSY) {
1618 free_cg_links(&tmp_cg_links);
1622 * There must be no failure case after here, since rebinding
1623 * takes care of subsystems' refcounts, which are explicitly
1624 * dropped in the failure exit path.
1627 /* EBUSY should be the only error here */
1630 list_add(&root->root_list, &roots);
1633 sb->s_root->d_fsdata = root_cgrp;
1634 root->top_cgroup.dentry = sb->s_root;
1636 /* Link the top cgroup in this hierarchy into all
1637 * the css_set objects */
1638 write_lock(&css_set_lock);
1639 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1640 struct hlist_head *hhead = &css_set_table[i];
1641 struct hlist_node *node;
1644 hlist_for_each_entry(cg, node, hhead, hlist)
1645 link_css_set(&tmp_cg_links, cg, root_cgrp);
1647 write_unlock(&css_set_lock);
1649 free_cg_links(&tmp_cg_links);
1651 BUG_ON(!list_empty(&root_cgrp->children));
1652 BUG_ON(root->number_of_cgroups != 1);
1654 cred = override_creds(&init_cred);
1655 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1657 mutex_unlock(&cgroup_root_mutex);
1658 mutex_unlock(&cgroup_mutex);
1659 mutex_unlock(&inode->i_mutex);
1662 * We re-used an existing hierarchy - the new root (if
1663 * any) is not needed
1665 cgroup_drop_root(opts.new_root);
1666 /* no subsys rebinding, so refcounts don't change */
1667 drop_parsed_module_refcounts(opts.subsys_mask);
1670 kfree(opts.release_agent);
1672 return dget(sb->s_root);
1675 mutex_unlock(&cgroup_root_mutex);
1676 mutex_unlock(&cgroup_mutex);
1677 mutex_unlock(&inode->i_mutex);
1679 deactivate_locked_super(sb);
1681 drop_parsed_module_refcounts(opts.subsys_mask);
1683 kfree(opts.release_agent);
1685 return ERR_PTR(ret);
1688 static void cgroup_kill_sb(struct super_block *sb) {
1689 struct cgroupfs_root *root = sb->s_fs_info;
1690 struct cgroup *cgrp = &root->top_cgroup;
1692 struct cg_cgroup_link *link;
1693 struct cg_cgroup_link *saved_link;
1697 BUG_ON(root->number_of_cgroups != 1);
1698 BUG_ON(!list_empty(&cgrp->children));
1700 mutex_lock(&cgroup_mutex);
1701 mutex_lock(&cgroup_root_mutex);
1703 /* Rebind all subsystems back to the default hierarchy */
1704 ret = rebind_subsystems(root, 0);
1705 /* Shouldn't be able to fail ... */
1709 * Release all the links from css_sets to this hierarchy's
1712 write_lock(&css_set_lock);
1714 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1716 list_del(&link->cg_link_list);
1717 list_del(&link->cgrp_link_list);
1720 write_unlock(&css_set_lock);
1722 if (!list_empty(&root->root_list)) {
1723 list_del(&root->root_list);
1727 mutex_unlock(&cgroup_root_mutex);
1728 mutex_unlock(&cgroup_mutex);
1730 simple_xattrs_free(&cgrp->xattrs);
1732 kill_litter_super(sb);
1733 cgroup_drop_root(root);
1736 static struct file_system_type cgroup_fs_type = {
1738 .mount = cgroup_mount,
1739 .kill_sb = cgroup_kill_sb,
1742 static struct kobject *cgroup_kobj;
1745 * cgroup_path - generate the path of a cgroup
1746 * @cgrp: the cgroup in question
1747 * @buf: the buffer to write the path into
1748 * @buflen: the length of the buffer
1750 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1751 * reference. Writes path of cgroup into buf. Returns 0 on success,
1754 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1756 struct dentry *dentry = cgrp->dentry;
1759 rcu_lockdep_assert(rcu_read_lock_held() || cgroup_lock_is_held(),
1760 "cgroup_path() called without proper locking");
1762 if (!dentry || cgrp == dummytop) {
1764 * Inactive subsystems have no dentry for their root
1771 start = buf + buflen - 1;
1775 int len = dentry->d_name.len;
1777 if ((start -= len) < buf)
1778 return -ENAMETOOLONG;
1779 memcpy(start, dentry->d_name.name, len);
1780 cgrp = cgrp->parent;
1784 dentry = cgrp->dentry;
1788 return -ENAMETOOLONG;
1791 memmove(buf, start, buf + buflen - start);
1794 EXPORT_SYMBOL_GPL(cgroup_path);
1797 * Control Group taskset
1799 struct task_and_cgroup {
1800 struct task_struct *task;
1801 struct cgroup *cgrp;
1805 struct cgroup_taskset {
1806 struct task_and_cgroup single;
1807 struct flex_array *tc_array;
1810 struct cgroup *cur_cgrp;
1814 * cgroup_taskset_first - reset taskset and return the first task
1815 * @tset: taskset of interest
1817 * @tset iteration is initialized and the first task is returned.
1819 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1821 if (tset->tc_array) {
1823 return cgroup_taskset_next(tset);
1825 tset->cur_cgrp = tset->single.cgrp;
1826 return tset->single.task;
1829 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1832 * cgroup_taskset_next - iterate to the next task in taskset
1833 * @tset: taskset of interest
1835 * Return the next task in @tset. Iteration must have been initialized
1836 * with cgroup_taskset_first().
1838 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1840 struct task_and_cgroup *tc;
1842 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1845 tc = flex_array_get(tset->tc_array, tset->idx++);
1846 tset->cur_cgrp = tc->cgrp;
1849 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1852 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1853 * @tset: taskset of interest
1855 * Return the cgroup for the current (last returned) task of @tset. This
1856 * function must be preceded by either cgroup_taskset_first() or
1857 * cgroup_taskset_next().
1859 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1861 return tset->cur_cgrp;
1863 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1866 * cgroup_taskset_size - return the number of tasks in taskset
1867 * @tset: taskset of interest
1869 int cgroup_taskset_size(struct cgroup_taskset *tset)
1871 return tset->tc_array ? tset->tc_array_len : 1;
1873 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1877 * cgroup_task_migrate - move a task from one cgroup to another.
1879 * 'guarantee' is set if the caller promises that a new css_set for the task
1880 * will already exist. If not set, this function might sleep, and can fail with
1881 * -ENOMEM. Must be called with cgroup_mutex and threadgroup locked.
1883 static void cgroup_task_migrate(struct cgroup *cgrp, struct cgroup *oldcgrp,
1884 struct task_struct *tsk, struct css_set *newcg)
1886 struct css_set *oldcg;
1889 * We are synchronized through threadgroup_lock() against PF_EXITING
1890 * setting such that we can't race against cgroup_exit() changing the
1891 * css_set to init_css_set and dropping the old one.
1893 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1894 oldcg = tsk->cgroups;
1897 rcu_assign_pointer(tsk->cgroups, newcg);
1900 /* Update the css_set linked lists if we're using them */
1901 write_lock(&css_set_lock);
1902 if (!list_empty(&tsk->cg_list))
1903 list_move(&tsk->cg_list, &newcg->tasks);
1904 write_unlock(&css_set_lock);
1907 * We just gained a reference on oldcg by taking it from the task. As
1908 * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1909 * it here; it will be freed under RCU.
1911 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1916 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1917 * @cgrp: the cgroup the task is attaching to
1918 * @tsk: the task to be attached
1920 * Call with cgroup_mutex and threadgroup locked. May take task_lock of
1923 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1926 struct cgroup_subsys *ss, *failed_ss = NULL;
1927 struct cgroup *oldcgrp;
1928 struct cgroupfs_root *root = cgrp->root;
1929 struct cgroup_taskset tset = { };
1930 struct css_set *newcg;
1932 /* @tsk either already exited or can't exit until the end */
1933 if (tsk->flags & PF_EXITING)
1936 /* Nothing to do if the task is already in that cgroup */
1937 oldcgrp = task_cgroup_from_root(tsk, root);
1938 if (cgrp == oldcgrp)
1941 tset.single.task = tsk;
1942 tset.single.cgrp = oldcgrp;
1944 for_each_subsys(root, ss) {
1945 if (ss->can_attach) {
1946 retval = ss->can_attach(cgrp, &tset);
1949 * Remember on which subsystem the can_attach()
1950 * failed, so that we only call cancel_attach()
1951 * against the subsystems whose can_attach()
1952 * succeeded. (See below)
1960 newcg = find_css_set(tsk->cgroups, cgrp);
1966 cgroup_task_migrate(cgrp, oldcgrp, tsk, newcg);
1968 for_each_subsys(root, ss) {
1970 ss->attach(cgrp, &tset);
1976 for_each_subsys(root, ss) {
1977 if (ss == failed_ss)
1979 * This subsystem was the one that failed the
1980 * can_attach() check earlier, so we don't need
1981 * to call cancel_attach() against it or any
1982 * remaining subsystems.
1985 if (ss->cancel_attach)
1986 ss->cancel_attach(cgrp, &tset);
1993 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
1994 * @from: attach to all cgroups of a given task
1995 * @tsk: the task to be attached
1997 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
1999 struct cgroupfs_root *root;
2003 for_each_active_root(root) {
2004 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2006 retval = cgroup_attach_task(from_cg, tsk);
2014 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2017 * cgroup_attach_proc - attach all threads in a threadgroup to a cgroup
2018 * @cgrp: the cgroup to attach to
2019 * @leader: the threadgroup leader task_struct of the group to be attached
2021 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
2022 * task_lock of each thread in leader's threadgroup individually in turn.
2024 static int cgroup_attach_proc(struct cgroup *cgrp, struct task_struct *leader)
2026 int retval, i, group_size;
2027 struct cgroup_subsys *ss, *failed_ss = NULL;
2028 /* guaranteed to be initialized later, but the compiler needs this */
2029 struct cgroupfs_root *root = cgrp->root;
2030 /* threadgroup list cursor and array */
2031 struct task_struct *tsk;
2032 struct task_and_cgroup *tc;
2033 struct flex_array *group;
2034 struct cgroup_taskset tset = { };
2037 * step 0: in order to do expensive, possibly blocking operations for
2038 * every thread, we cannot iterate the thread group list, since it needs
2039 * rcu or tasklist locked. instead, build an array of all threads in the
2040 * group - group_rwsem prevents new threads from appearing, and if
2041 * threads exit, this will just be an over-estimate.
2043 group_size = get_nr_threads(leader);
2044 /* flex_array supports very large thread-groups better than kmalloc. */
2045 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2048 /* pre-allocate to guarantee space while iterating in rcu read-side. */
2049 retval = flex_array_prealloc(group, 0, group_size - 1, GFP_KERNEL);
2051 goto out_free_group_list;
2056 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2057 * already PF_EXITING could be freed from underneath us unless we
2058 * take an rcu_read_lock.
2062 struct task_and_cgroup ent;
2064 /* @tsk either already exited or can't exit until the end */
2065 if (tsk->flags & PF_EXITING)
2068 /* as per above, nr_threads may decrease, but not increase. */
2069 BUG_ON(i >= group_size);
2071 ent.cgrp = task_cgroup_from_root(tsk, root);
2072 /* nothing to do if this task is already in the cgroup */
2073 if (ent.cgrp == cgrp)
2076 * saying GFP_ATOMIC has no effect here because we did prealloc
2077 * earlier, but it's good form to communicate our expectations.
2079 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2080 BUG_ON(retval != 0);
2082 } while_each_thread(leader, tsk);
2084 /* remember the number of threads in the array for later. */
2086 tset.tc_array = group;
2087 tset.tc_array_len = group_size;
2089 /* methods shouldn't be called if no task is actually migrating */
2092 goto out_free_group_list;
2095 * step 1: check that we can legitimately attach to the cgroup.
2097 for_each_subsys(root, ss) {
2098 if (ss->can_attach) {
2099 retval = ss->can_attach(cgrp, &tset);
2102 goto out_cancel_attach;
2108 * step 2: make sure css_sets exist for all threads to be migrated.
2109 * we use find_css_set, which allocates a new one if necessary.
2111 for (i = 0; i < group_size; i++) {
2112 tc = flex_array_get(group, i);
2113 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2116 goto out_put_css_set_refs;
2121 * step 3: now that we're guaranteed success wrt the css_sets,
2122 * proceed to move all tasks to the new cgroup. There are no
2123 * failure cases after here, so this is the commit point.
2125 for (i = 0; i < group_size; i++) {
2126 tc = flex_array_get(group, i);
2127 cgroup_task_migrate(cgrp, tc->cgrp, tc->task, tc->cg);
2129 /* nothing is sensitive to fork() after this point. */
2132 * step 4: do subsystem attach callbacks.
2134 for_each_subsys(root, ss) {
2136 ss->attach(cgrp, &tset);
2140 * step 5: success! and cleanup
2144 out_put_css_set_refs:
2146 for (i = 0; i < group_size; i++) {
2147 tc = flex_array_get(group, i);
2150 put_css_set(tc->cg);
2155 for_each_subsys(root, ss) {
2156 if (ss == failed_ss)
2158 if (ss->cancel_attach)
2159 ss->cancel_attach(cgrp, &tset);
2162 out_free_group_list:
2163 flex_array_free(group);
2168 * Find the task_struct of the task to attach by vpid and pass it along to the
2169 * function to attach either it or all tasks in its threadgroup. Will lock
2170 * cgroup_mutex and threadgroup; may take task_lock of task.
2172 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2174 struct task_struct *tsk;
2175 const struct cred *cred = current_cred(), *tcred;
2178 if (!cgroup_lock_live_group(cgrp))
2184 tsk = find_task_by_vpid(pid);
2188 goto out_unlock_cgroup;
2191 * even if we're attaching all tasks in the thread group, we
2192 * only need to check permissions on one of them.
2194 tcred = __task_cred(tsk);
2195 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2196 !uid_eq(cred->euid, tcred->uid) &&
2197 !uid_eq(cred->euid, tcred->suid)) {
2200 goto out_unlock_cgroup;
2206 tsk = tsk->group_leader;
2209 * Workqueue threads may acquire PF_THREAD_BOUND and become
2210 * trapped in a cpuset, or RT worker may be born in a cgroup
2211 * with no rt_runtime allocated. Just say no.
2213 if (tsk == kthreadd_task || (tsk->flags & PF_THREAD_BOUND)) {
2216 goto out_unlock_cgroup;
2219 get_task_struct(tsk);
2222 threadgroup_lock(tsk);
2224 if (!thread_group_leader(tsk)) {
2226 * a race with de_thread from another thread's exec()
2227 * may strip us of our leadership, if this happens,
2228 * there is no choice but to throw this task away and
2229 * try again; this is
2230 * "double-double-toil-and-trouble-check locking".
2232 threadgroup_unlock(tsk);
2233 put_task_struct(tsk);
2234 goto retry_find_task;
2236 ret = cgroup_attach_proc(cgrp, tsk);
2238 ret = cgroup_attach_task(cgrp, tsk);
2239 threadgroup_unlock(tsk);
2241 put_task_struct(tsk);
2247 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2249 return attach_task_by_pid(cgrp, pid, false);
2252 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2254 return attach_task_by_pid(cgrp, tgid, true);
2258 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
2259 * @cgrp: the cgroup to be checked for liveness
2261 * On success, returns true; the lock should be later released with
2262 * cgroup_unlock(). On failure returns false with no lock held.
2264 bool cgroup_lock_live_group(struct cgroup *cgrp)
2266 mutex_lock(&cgroup_mutex);
2267 if (cgroup_is_removed(cgrp)) {
2268 mutex_unlock(&cgroup_mutex);
2273 EXPORT_SYMBOL_GPL(cgroup_lock_live_group);
2275 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2278 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2279 if (strlen(buffer) >= PATH_MAX)
2281 if (!cgroup_lock_live_group(cgrp))
2283 mutex_lock(&cgroup_root_mutex);
2284 strcpy(cgrp->root->release_agent_path, buffer);
2285 mutex_unlock(&cgroup_root_mutex);
2290 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2291 struct seq_file *seq)
2293 if (!cgroup_lock_live_group(cgrp))
2295 seq_puts(seq, cgrp->root->release_agent_path);
2296 seq_putc(seq, '\n');
2301 /* A buffer size big enough for numbers or short strings */
2302 #define CGROUP_LOCAL_BUFFER_SIZE 64
2304 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2306 const char __user *userbuf,
2307 size_t nbytes, loff_t *unused_ppos)
2309 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2315 if (nbytes >= sizeof(buffer))
2317 if (copy_from_user(buffer, userbuf, nbytes))
2320 buffer[nbytes] = 0; /* nul-terminate */
2321 if (cft->write_u64) {
2322 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2325 retval = cft->write_u64(cgrp, cft, val);
2327 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2330 retval = cft->write_s64(cgrp, cft, val);
2337 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2339 const char __user *userbuf,
2340 size_t nbytes, loff_t *unused_ppos)
2342 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2344 size_t max_bytes = cft->max_write_len;
2345 char *buffer = local_buffer;
2348 max_bytes = sizeof(local_buffer) - 1;
2349 if (nbytes >= max_bytes)
2351 /* Allocate a dynamic buffer if we need one */
2352 if (nbytes >= sizeof(local_buffer)) {
2353 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2357 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2362 buffer[nbytes] = 0; /* nul-terminate */
2363 retval = cft->write_string(cgrp, cft, strstrip(buffer));
2367 if (buffer != local_buffer)
2372 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2373 size_t nbytes, loff_t *ppos)
2375 struct cftype *cft = __d_cft(file->f_dentry);
2376 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2378 if (cgroup_is_removed(cgrp))
2381 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2382 if (cft->write_u64 || cft->write_s64)
2383 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2384 if (cft->write_string)
2385 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2387 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2388 return ret ? ret : nbytes;
2393 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2395 char __user *buf, size_t nbytes,
2398 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2399 u64 val = cft->read_u64(cgrp, cft);
2400 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2402 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2405 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2407 char __user *buf, size_t nbytes,
2410 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2411 s64 val = cft->read_s64(cgrp, cft);
2412 int len = sprintf(tmp, "%lld\n", (long long) val);
2414 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2417 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2418 size_t nbytes, loff_t *ppos)
2420 struct cftype *cft = __d_cft(file->f_dentry);
2421 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2423 if (cgroup_is_removed(cgrp))
2427 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2429 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2431 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2436 * seqfile ops/methods for returning structured data. Currently just
2437 * supports string->u64 maps, but can be extended in future.
2440 struct cgroup_seqfile_state {
2442 struct cgroup *cgroup;
2445 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2447 struct seq_file *sf = cb->state;
2448 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2451 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2453 struct cgroup_seqfile_state *state = m->private;
2454 struct cftype *cft = state->cft;
2455 if (cft->read_map) {
2456 struct cgroup_map_cb cb = {
2457 .fill = cgroup_map_add,
2460 return cft->read_map(state->cgroup, cft, &cb);
2462 return cft->read_seq_string(state->cgroup, cft, m);
2465 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2467 struct seq_file *seq = file->private_data;
2468 kfree(seq->private);
2469 return single_release(inode, file);
2472 static const struct file_operations cgroup_seqfile_operations = {
2474 .write = cgroup_file_write,
2475 .llseek = seq_lseek,
2476 .release = cgroup_seqfile_release,
2479 static int cgroup_file_open(struct inode *inode, struct file *file)
2484 err = generic_file_open(inode, file);
2487 cft = __d_cft(file->f_dentry);
2489 if (cft->read_map || cft->read_seq_string) {
2490 struct cgroup_seqfile_state *state =
2491 kzalloc(sizeof(*state), GFP_USER);
2495 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2496 file->f_op = &cgroup_seqfile_operations;
2497 err = single_open(file, cgroup_seqfile_show, state);
2500 } else if (cft->open)
2501 err = cft->open(inode, file);
2508 static int cgroup_file_release(struct inode *inode, struct file *file)
2510 struct cftype *cft = __d_cft(file->f_dentry);
2512 return cft->release(inode, file);
2517 * cgroup_rename - Only allow simple rename of directories in place.
2519 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2520 struct inode *new_dir, struct dentry *new_dentry)
2522 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2524 if (new_dentry->d_inode)
2526 if (old_dir != new_dir)
2528 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2531 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2533 if (S_ISDIR(dentry->d_inode->i_mode))
2534 return &__d_cgrp(dentry)->xattrs;
2536 return &__d_cft(dentry)->xattrs;
2539 static inline int xattr_enabled(struct dentry *dentry)
2541 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2542 return test_bit(ROOT_XATTR, &root->flags);
2545 static bool is_valid_xattr(const char *name)
2547 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2548 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2553 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2554 const void *val, size_t size, int flags)
2556 if (!xattr_enabled(dentry))
2558 if (!is_valid_xattr(name))
2560 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2563 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2565 if (!xattr_enabled(dentry))
2567 if (!is_valid_xattr(name))
2569 return simple_xattr_remove(__d_xattrs(dentry), name);
2572 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2573 void *buf, size_t size)
2575 if (!xattr_enabled(dentry))
2577 if (!is_valid_xattr(name))
2579 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2582 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2584 if (!xattr_enabled(dentry))
2586 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2589 static const struct file_operations cgroup_file_operations = {
2590 .read = cgroup_file_read,
2591 .write = cgroup_file_write,
2592 .llseek = generic_file_llseek,
2593 .open = cgroup_file_open,
2594 .release = cgroup_file_release,
2597 static const struct inode_operations cgroup_file_inode_operations = {
2598 .setxattr = cgroup_setxattr,
2599 .getxattr = cgroup_getxattr,
2600 .listxattr = cgroup_listxattr,
2601 .removexattr = cgroup_removexattr,
2604 static const struct inode_operations cgroup_dir_inode_operations = {
2605 .lookup = cgroup_lookup,
2606 .mkdir = cgroup_mkdir,
2607 .rmdir = cgroup_rmdir,
2608 .rename = cgroup_rename,
2609 .setxattr = cgroup_setxattr,
2610 .getxattr = cgroup_getxattr,
2611 .listxattr = cgroup_listxattr,
2612 .removexattr = cgroup_removexattr,
2615 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2617 if (dentry->d_name.len > NAME_MAX)
2618 return ERR_PTR(-ENAMETOOLONG);
2619 d_add(dentry, NULL);
2624 * Check if a file is a control file
2626 static inline struct cftype *__file_cft(struct file *file)
2628 if (file->f_dentry->d_inode->i_fop != &cgroup_file_operations)
2629 return ERR_PTR(-EINVAL);
2630 return __d_cft(file->f_dentry);
2633 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2634 struct super_block *sb)
2636 struct inode *inode;
2640 if (dentry->d_inode)
2643 inode = cgroup_new_inode(mode, sb);
2647 if (S_ISDIR(mode)) {
2648 inode->i_op = &cgroup_dir_inode_operations;
2649 inode->i_fop = &simple_dir_operations;
2651 /* start off with i_nlink == 2 (for "." entry) */
2653 inc_nlink(dentry->d_parent->d_inode);
2656 * Control reaches here with cgroup_mutex held.
2657 * @inode->i_mutex should nest outside cgroup_mutex but we
2658 * want to populate it immediately without releasing
2659 * cgroup_mutex. As @inode isn't visible to anyone else
2660 * yet, trylock will always succeed without affecting
2663 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2664 } else if (S_ISREG(mode)) {
2666 inode->i_fop = &cgroup_file_operations;
2667 inode->i_op = &cgroup_file_inode_operations;
2669 d_instantiate(dentry, inode);
2670 dget(dentry); /* Extra count - pin the dentry in core */
2675 * cgroup_file_mode - deduce file mode of a control file
2676 * @cft: the control file in question
2678 * returns cft->mode if ->mode is not 0
2679 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2680 * returns S_IRUGO if it has only a read handler
2681 * returns S_IWUSR if it has only a write hander
2683 static umode_t cgroup_file_mode(const struct cftype *cft)
2690 if (cft->read || cft->read_u64 || cft->read_s64 ||
2691 cft->read_map || cft->read_seq_string)
2694 if (cft->write || cft->write_u64 || cft->write_s64 ||
2695 cft->write_string || cft->trigger)
2701 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2704 struct dentry *dir = cgrp->dentry;
2705 struct cgroup *parent = __d_cgrp(dir);
2706 struct dentry *dentry;
2710 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2712 simple_xattrs_init(&cft->xattrs);
2714 /* does @cft->flags tell us to skip creation on @cgrp? */
2715 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2717 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2720 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2721 strcpy(name, subsys->name);
2724 strcat(name, cft->name);
2726 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2728 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2732 dentry = lookup_one_len(name, dir, strlen(name));
2733 if (IS_ERR(dentry)) {
2734 error = PTR_ERR(dentry);
2738 mode = cgroup_file_mode(cft);
2739 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2741 cfe->type = (void *)cft;
2742 cfe->dentry = dentry;
2743 dentry->d_fsdata = cfe;
2744 list_add_tail(&cfe->node, &parent->files);
2753 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2754 struct cftype cfts[], bool is_add)
2759 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2761 err = cgroup_add_file(cgrp, subsys, cft);
2763 err = cgroup_rm_file(cgrp, cft);
2765 pr_warning("cgroup_addrm_files: failed to %s %s, err=%d\n",
2766 is_add ? "add" : "remove", cft->name, err);
2773 static DEFINE_MUTEX(cgroup_cft_mutex);
2775 static void cgroup_cfts_prepare(void)
2776 __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2779 * Thanks to the entanglement with vfs inode locking, we can't walk
2780 * the existing cgroups under cgroup_mutex and create files.
2781 * Instead, we increment reference on all cgroups and build list of
2782 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2783 * exclusive access to the field.
2785 mutex_lock(&cgroup_cft_mutex);
2786 mutex_lock(&cgroup_mutex);
2789 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2790 struct cftype *cfts, bool is_add)
2791 __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2794 struct cgroup *cgrp, *n;
2796 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2797 if (cfts && ss->root != &rootnode) {
2798 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2800 list_add_tail(&cgrp->cft_q_node, &pending);
2804 mutex_unlock(&cgroup_mutex);
2807 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2808 * files for all cgroups which were created before.
2810 list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2811 struct inode *inode = cgrp->dentry->d_inode;
2813 mutex_lock(&inode->i_mutex);
2814 mutex_lock(&cgroup_mutex);
2815 if (!cgroup_is_removed(cgrp))
2816 cgroup_addrm_files(cgrp, ss, cfts, is_add);
2817 mutex_unlock(&cgroup_mutex);
2818 mutex_unlock(&inode->i_mutex);
2820 list_del_init(&cgrp->cft_q_node);
2824 mutex_unlock(&cgroup_cft_mutex);
2828 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2829 * @ss: target cgroup subsystem
2830 * @cfts: zero-length name terminated array of cftypes
2832 * Register @cfts to @ss. Files described by @cfts are created for all
2833 * existing cgroups to which @ss is attached and all future cgroups will
2834 * have them too. This function can be called anytime whether @ss is
2837 * Returns 0 on successful registration, -errno on failure. Note that this
2838 * function currently returns 0 as long as @cfts registration is successful
2839 * even if some file creation attempts on existing cgroups fail.
2841 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2843 struct cftype_set *set;
2845 set = kzalloc(sizeof(*set), GFP_KERNEL);
2849 cgroup_cfts_prepare();
2851 list_add_tail(&set->node, &ss->cftsets);
2852 cgroup_cfts_commit(ss, cfts, true);
2856 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2859 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2860 * @ss: target cgroup subsystem
2861 * @cfts: zero-length name terminated array of cftypes
2863 * Unregister @cfts from @ss. Files described by @cfts are removed from
2864 * all existing cgroups to which @ss is attached and all future cgroups
2865 * won't have them either. This function can be called anytime whether @ss
2866 * is attached or not.
2868 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2869 * registered with @ss.
2871 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2873 struct cftype_set *set;
2875 cgroup_cfts_prepare();
2877 list_for_each_entry(set, &ss->cftsets, node) {
2878 if (set->cfts == cfts) {
2879 list_del_init(&set->node);
2880 cgroup_cfts_commit(ss, cfts, false);
2885 cgroup_cfts_commit(ss, NULL, false);
2890 * cgroup_task_count - count the number of tasks in a cgroup.
2891 * @cgrp: the cgroup in question
2893 * Return the number of tasks in the cgroup.
2895 int cgroup_task_count(const struct cgroup *cgrp)
2898 struct cg_cgroup_link *link;
2900 read_lock(&css_set_lock);
2901 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2902 count += atomic_read(&link->cg->refcount);
2904 read_unlock(&css_set_lock);
2909 * Advance a list_head iterator. The iterator should be positioned at
2910 * the start of a css_set
2912 static void cgroup_advance_iter(struct cgroup *cgrp,
2913 struct cgroup_iter *it)
2915 struct list_head *l = it->cg_link;
2916 struct cg_cgroup_link *link;
2919 /* Advance to the next non-empty css_set */
2922 if (l == &cgrp->css_sets) {
2926 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2928 } while (list_empty(&cg->tasks));
2930 it->task = cg->tasks.next;
2934 * To reduce the fork() overhead for systems that are not actually
2935 * using their cgroups capability, we don't maintain the lists running
2936 * through each css_set to its tasks until we see the list actually
2937 * used - in other words after the first call to cgroup_iter_start().
2939 static void cgroup_enable_task_cg_lists(void)
2941 struct task_struct *p, *g;
2942 write_lock(&css_set_lock);
2943 use_task_css_set_links = 1;
2945 * We need tasklist_lock because RCU is not safe against
2946 * while_each_thread(). Besides, a forking task that has passed
2947 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2948 * is not guaranteed to have its child immediately visible in the
2949 * tasklist if we walk through it with RCU.
2951 read_lock(&tasklist_lock);
2952 do_each_thread(g, p) {
2955 * We should check if the process is exiting, otherwise
2956 * it will race with cgroup_exit() in that the list
2957 * entry won't be deleted though the process has exited.
2959 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2960 list_add(&p->cg_list, &p->cgroups->tasks);
2962 } while_each_thread(g, p);
2963 read_unlock(&tasklist_lock);
2964 write_unlock(&css_set_lock);
2968 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
2969 * @pos: the current position (%NULL to initiate traversal)
2970 * @cgroup: cgroup whose descendants to walk
2972 * To be used by cgroup_for_each_descendant_pre(). Find the next
2973 * descendant to visit for pre-order traversal of @cgroup's descendants.
2975 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
2976 struct cgroup *cgroup)
2978 struct cgroup *next;
2980 WARN_ON_ONCE(!rcu_read_lock_held());
2982 /* if first iteration, pretend we just visited @cgroup */
2984 if (list_empty(&cgroup->children))
2989 /* visit the first child if exists */
2990 next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
2994 /* no child, visit my or the closest ancestor's next sibling */
2996 next = list_entry_rcu(pos->sibling.next, struct cgroup,
2998 if (&next->sibling != &pos->parent->children)
3002 } while (pos != cgroup);
3006 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
3008 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3010 struct cgroup *last;
3014 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3022 * cgroup_next_descendant_post - find the next descendant for post-order walk
3023 * @pos: the current position (%NULL to initiate traversal)
3024 * @cgroup: cgroup whose descendants to walk
3026 * To be used by cgroup_for_each_descendant_post(). Find the next
3027 * descendant to visit for post-order traversal of @cgroup's descendants.
3029 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3030 struct cgroup *cgroup)
3032 struct cgroup *next;
3034 WARN_ON_ONCE(!rcu_read_lock_held());
3036 /* if first iteration, visit the leftmost descendant */
3038 next = cgroup_leftmost_descendant(cgroup);
3039 return next != cgroup ? next : NULL;
3042 /* if there's an unvisited sibling, visit its leftmost descendant */
3043 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3044 if (&next->sibling != &pos->parent->children)
3045 return cgroup_leftmost_descendant(next);
3047 /* no sibling left, visit parent */
3049 return next != cgroup ? next : NULL;
3051 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3053 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3054 __acquires(css_set_lock)
3057 * The first time anyone tries to iterate across a cgroup,
3058 * we need to enable the list linking each css_set to its
3059 * tasks, and fix up all existing tasks.
3061 if (!use_task_css_set_links)
3062 cgroup_enable_task_cg_lists();
3064 read_lock(&css_set_lock);
3065 it->cg_link = &cgrp->css_sets;
3066 cgroup_advance_iter(cgrp, it);
3069 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3070 struct cgroup_iter *it)
3072 struct task_struct *res;
3073 struct list_head *l = it->task;
3074 struct cg_cgroup_link *link;
3076 /* If the iterator cg is NULL, we have no tasks */
3079 res = list_entry(l, struct task_struct, cg_list);
3080 /* Advance iterator to find next entry */
3082 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3083 if (l == &link->cg->tasks) {
3084 /* We reached the end of this task list - move on to
3085 * the next cg_cgroup_link */
3086 cgroup_advance_iter(cgrp, it);
3093 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3094 __releases(css_set_lock)
3096 read_unlock(&css_set_lock);
3099 static inline int started_after_time(struct task_struct *t1,
3100 struct timespec *time,
3101 struct task_struct *t2)
3103 int start_diff = timespec_compare(&t1->start_time, time);
3104 if (start_diff > 0) {
3106 } else if (start_diff < 0) {
3110 * Arbitrarily, if two processes started at the same
3111 * time, we'll say that the lower pointer value
3112 * started first. Note that t2 may have exited by now
3113 * so this may not be a valid pointer any longer, but
3114 * that's fine - it still serves to distinguish
3115 * between two tasks started (effectively) simultaneously.
3122 * This function is a callback from heap_insert() and is used to order
3124 * In this case we order the heap in descending task start time.
3126 static inline int started_after(void *p1, void *p2)
3128 struct task_struct *t1 = p1;
3129 struct task_struct *t2 = p2;
3130 return started_after_time(t1, &t2->start_time, t2);
3134 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3135 * @scan: struct cgroup_scanner containing arguments for the scan
3137 * Arguments include pointers to callback functions test_task() and
3139 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3140 * and if it returns true, call process_task() for it also.
3141 * The test_task pointer may be NULL, meaning always true (select all tasks).
3142 * Effectively duplicates cgroup_iter_{start,next,end}()
3143 * but does not lock css_set_lock for the call to process_task().
3144 * The struct cgroup_scanner may be embedded in any structure of the caller's
3146 * It is guaranteed that process_task() will act on every task that
3147 * is a member of the cgroup for the duration of this call. This
3148 * function may or may not call process_task() for tasks that exit
3149 * or move to a different cgroup during the call, or are forked or
3150 * move into the cgroup during the call.
3152 * Note that test_task() may be called with locks held, and may in some
3153 * situations be called multiple times for the same task, so it should
3155 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3156 * pre-allocated and will be used for heap operations (and its "gt" member will
3157 * be overwritten), else a temporary heap will be used (allocation of which
3158 * may cause this function to fail).
3160 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3163 struct cgroup_iter it;
3164 struct task_struct *p, *dropped;
3165 /* Never dereference latest_task, since it's not refcounted */
3166 struct task_struct *latest_task = NULL;
3167 struct ptr_heap tmp_heap;
3168 struct ptr_heap *heap;
3169 struct timespec latest_time = { 0, 0 };
3172 /* The caller supplied our heap and pre-allocated its memory */
3174 heap->gt = &started_after;
3176 /* We need to allocate our own heap memory */
3178 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3180 /* cannot allocate the heap */
3186 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3187 * to determine which are of interest, and using the scanner's
3188 * "process_task" callback to process any of them that need an update.
3189 * Since we don't want to hold any locks during the task updates,
3190 * gather tasks to be processed in a heap structure.
3191 * The heap is sorted by descending task start time.
3192 * If the statically-sized heap fills up, we overflow tasks that
3193 * started later, and in future iterations only consider tasks that
3194 * started after the latest task in the previous pass. This
3195 * guarantees forward progress and that we don't miss any tasks.
3198 cgroup_iter_start(scan->cg, &it);
3199 while ((p = cgroup_iter_next(scan->cg, &it))) {
3201 * Only affect tasks that qualify per the caller's callback,
3202 * if he provided one
3204 if (scan->test_task && !scan->test_task(p, scan))
3207 * Only process tasks that started after the last task
3210 if (!started_after_time(p, &latest_time, latest_task))
3212 dropped = heap_insert(heap, p);
3213 if (dropped == NULL) {
3215 * The new task was inserted; the heap wasn't
3219 } else if (dropped != p) {
3221 * The new task was inserted, and pushed out a
3225 put_task_struct(dropped);
3228 * Else the new task was newer than anything already in
3229 * the heap and wasn't inserted
3232 cgroup_iter_end(scan->cg, &it);
3235 for (i = 0; i < heap->size; i++) {
3236 struct task_struct *q = heap->ptrs[i];
3238 latest_time = q->start_time;
3241 /* Process the task per the caller's callback */
3242 scan->process_task(q, scan);
3246 * If we had to process any tasks at all, scan again
3247 * in case some of them were in the middle of forking
3248 * children that didn't get processed.
3249 * Not the most efficient way to do it, but it avoids
3250 * having to take callback_mutex in the fork path
3254 if (heap == &tmp_heap)
3255 heap_free(&tmp_heap);
3260 * Stuff for reading the 'tasks'/'procs' files.
3262 * Reading this file can return large amounts of data if a cgroup has
3263 * *lots* of attached tasks. So it may need several calls to read(),
3264 * but we cannot guarantee that the information we produce is correct
3265 * unless we produce it entirely atomically.
3269 /* which pidlist file are we talking about? */
3270 enum cgroup_filetype {
3276 * A pidlist is a list of pids that virtually represents the contents of one
3277 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3278 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3281 struct cgroup_pidlist {
3283 * used to find which pidlist is wanted. doesn't change as long as
3284 * this particular list stays in the list.
3286 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3289 /* how many elements the above list has */
3291 /* how many files are using the current array */
3293 /* each of these stored in a list by its cgroup */
3294 struct list_head links;
3295 /* pointer to the cgroup we belong to, for list removal purposes */
3296 struct cgroup *owner;
3297 /* protects the other fields */
3298 struct rw_semaphore mutex;
3302 * The following two functions "fix" the issue where there are more pids
3303 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3304 * TODO: replace with a kernel-wide solution to this problem
3306 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3307 static void *pidlist_allocate(int count)
3309 if (PIDLIST_TOO_LARGE(count))
3310 return vmalloc(count * sizeof(pid_t));
3312 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3314 static void pidlist_free(void *p)
3316 if (is_vmalloc_addr(p))
3321 static void *pidlist_resize(void *p, int newcount)
3324 /* note: if new alloc fails, old p will still be valid either way */
3325 if (is_vmalloc_addr(p)) {
3326 newlist = vmalloc(newcount * sizeof(pid_t));
3329 memcpy(newlist, p, newcount * sizeof(pid_t));
3332 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
3338 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3339 * If the new stripped list is sufficiently smaller and there's enough memory
3340 * to allocate a new buffer, will let go of the unneeded memory. Returns the
3341 * number of unique elements.
3343 /* is the size difference enough that we should re-allocate the array? */
3344 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
3345 static int pidlist_uniq(pid_t **p, int length)
3352 * we presume the 0th element is unique, so i starts at 1. trivial
3353 * edge cases first; no work needs to be done for either
3355 if (length == 0 || length == 1)
3357 /* src and dest walk down the list; dest counts unique elements */
3358 for (src = 1; src < length; src++) {
3359 /* find next unique element */
3360 while (list[src] == list[src-1]) {
3365 /* dest always points to where the next unique element goes */
3366 list[dest] = list[src];
3371 * if the length difference is large enough, we want to allocate a
3372 * smaller buffer to save memory. if this fails due to out of memory,
3373 * we'll just stay with what we've got.
3375 if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
3376 newlist = pidlist_resize(list, dest);
3383 static int cmppid(const void *a, const void *b)
3385 return *(pid_t *)a - *(pid_t *)b;
3389 * find the appropriate pidlist for our purpose (given procs vs tasks)
3390 * returns with the lock on that pidlist already held, and takes care
3391 * of the use count, or returns NULL with no locks held if we're out of
3394 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3395 enum cgroup_filetype type)
3397 struct cgroup_pidlist *l;
3398 /* don't need task_nsproxy() if we're looking at ourself */
3399 struct pid_namespace *ns = current->nsproxy->pid_ns;
3402 * We can't drop the pidlist_mutex before taking the l->mutex in case
3403 * the last ref-holder is trying to remove l from the list at the same
3404 * time. Holding the pidlist_mutex precludes somebody taking whichever
3405 * list we find out from under us - compare release_pid_array().
3407 mutex_lock(&cgrp->pidlist_mutex);
3408 list_for_each_entry(l, &cgrp->pidlists, links) {
3409 if (l->key.type == type && l->key.ns == ns) {
3410 /* make sure l doesn't vanish out from under us */
3411 down_write(&l->mutex);
3412 mutex_unlock(&cgrp->pidlist_mutex);
3416 /* entry not found; create a new one */
3417 l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3419 mutex_unlock(&cgrp->pidlist_mutex);
3422 init_rwsem(&l->mutex);
3423 down_write(&l->mutex);
3425 l->key.ns = get_pid_ns(ns);
3426 l->use_count = 0; /* don't increment here */
3429 list_add(&l->links, &cgrp->pidlists);
3430 mutex_unlock(&cgrp->pidlist_mutex);
3435 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3437 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3438 struct cgroup_pidlist **lp)
3442 int pid, n = 0; /* used for populating the array */
3443 struct cgroup_iter it;
3444 struct task_struct *tsk;
3445 struct cgroup_pidlist *l;
3448 * If cgroup gets more users after we read count, we won't have
3449 * enough space - tough. This race is indistinguishable to the
3450 * caller from the case that the additional cgroup users didn't
3451 * show up until sometime later on.
3453 length = cgroup_task_count(cgrp);
3454 array = pidlist_allocate(length);
3457 /* now, populate the array */
3458 cgroup_iter_start(cgrp, &it);
3459 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3460 if (unlikely(n == length))
3462 /* get tgid or pid for procs or tasks file respectively */
3463 if (type == CGROUP_FILE_PROCS)
3464 pid = task_tgid_vnr(tsk);
3466 pid = task_pid_vnr(tsk);
3467 if (pid > 0) /* make sure to only use valid results */
3470 cgroup_iter_end(cgrp, &it);
3472 /* now sort & (if procs) strip out duplicates */
3473 sort(array, length, sizeof(pid_t), cmppid, NULL);
3474 if (type == CGROUP_FILE_PROCS)
3475 length = pidlist_uniq(&array, length);
3476 l = cgroup_pidlist_find(cgrp, type);
3478 pidlist_free(array);
3481 /* store array, freeing old if necessary - lock already held */
3482 pidlist_free(l->list);
3486 up_write(&l->mutex);
3492 * cgroupstats_build - build and fill cgroupstats
3493 * @stats: cgroupstats to fill information into
3494 * @dentry: A dentry entry belonging to the cgroup for which stats have
3497 * Build and fill cgroupstats so that taskstats can export it to user
3500 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3503 struct cgroup *cgrp;
3504 struct cgroup_iter it;
3505 struct task_struct *tsk;
3508 * Validate dentry by checking the superblock operations,
3509 * and make sure it's a directory.
3511 if (dentry->d_sb->s_op != &cgroup_ops ||
3512 !S_ISDIR(dentry->d_inode->i_mode))
3516 cgrp = dentry->d_fsdata;
3518 cgroup_iter_start(cgrp, &it);
3519 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3520 switch (tsk->state) {
3522 stats->nr_running++;
3524 case TASK_INTERRUPTIBLE:
3525 stats->nr_sleeping++;
3527 case TASK_UNINTERRUPTIBLE:
3528 stats->nr_uninterruptible++;
3531 stats->nr_stopped++;
3534 if (delayacct_is_task_waiting_on_io(tsk))
3535 stats->nr_io_wait++;
3539 cgroup_iter_end(cgrp, &it);
3547 * seq_file methods for the tasks/procs files. The seq_file position is the
3548 * next pid to display; the seq_file iterator is a pointer to the pid
3549 * in the cgroup->l->list array.
3552 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3555 * Initially we receive a position value that corresponds to
3556 * one more than the last pid shown (or 0 on the first call or
3557 * after a seek to the start). Use a binary-search to find the
3558 * next pid to display, if any
3560 struct cgroup_pidlist *l = s->private;
3561 int index = 0, pid = *pos;
3564 down_read(&l->mutex);
3566 int end = l->length;
3568 while (index < end) {
3569 int mid = (index + end) / 2;
3570 if (l->list[mid] == pid) {
3573 } else if (l->list[mid] <= pid)
3579 /* If we're off the end of the array, we're done */
3580 if (index >= l->length)
3582 /* Update the abstract position to be the actual pid that we found */
3583 iter = l->list + index;
3588 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3590 struct cgroup_pidlist *l = s->private;
3594 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3596 struct cgroup_pidlist *l = s->private;
3598 pid_t *end = l->list + l->length;
3600 * Advance to the next pid in the array. If this goes off the
3612 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3614 return seq_printf(s, "%d\n", *(int *)v);
3618 * seq_operations functions for iterating on pidlists through seq_file -
3619 * independent of whether it's tasks or procs
3621 static const struct seq_operations cgroup_pidlist_seq_operations = {
3622 .start = cgroup_pidlist_start,
3623 .stop = cgroup_pidlist_stop,
3624 .next = cgroup_pidlist_next,
3625 .show = cgroup_pidlist_show,
3628 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3631 * the case where we're the last user of this particular pidlist will
3632 * have us remove it from the cgroup's list, which entails taking the
3633 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3634 * pidlist_mutex, we have to take pidlist_mutex first.
3636 mutex_lock(&l->owner->pidlist_mutex);
3637 down_write(&l->mutex);
3638 BUG_ON(!l->use_count);
3639 if (!--l->use_count) {
3640 /* we're the last user if refcount is 0; remove and free */
3641 list_del(&l->links);
3642 mutex_unlock(&l->owner->pidlist_mutex);
3643 pidlist_free(l->list);
3644 put_pid_ns(l->key.ns);
3645 up_write(&l->mutex);
3649 mutex_unlock(&l->owner->pidlist_mutex);
3650 up_write(&l->mutex);
3653 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3655 struct cgroup_pidlist *l;
3656 if (!(file->f_mode & FMODE_READ))
3659 * the seq_file will only be initialized if the file was opened for
3660 * reading; hence we check if it's not null only in that case.
3662 l = ((struct seq_file *)file->private_data)->private;
3663 cgroup_release_pid_array(l);
3664 return seq_release(inode, file);
3667 static const struct file_operations cgroup_pidlist_operations = {
3669 .llseek = seq_lseek,
3670 .write = cgroup_file_write,
3671 .release = cgroup_pidlist_release,
3675 * The following functions handle opens on a file that displays a pidlist
3676 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3679 /* helper function for the two below it */
3680 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3682 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3683 struct cgroup_pidlist *l;
3686 /* Nothing to do for write-only files */
3687 if (!(file->f_mode & FMODE_READ))
3690 /* have the array populated */
3691 retval = pidlist_array_load(cgrp, type, &l);
3694 /* configure file information */
3695 file->f_op = &cgroup_pidlist_operations;
3697 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3699 cgroup_release_pid_array(l);
3702 ((struct seq_file *)file->private_data)->private = l;
3705 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3707 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3709 static int cgroup_procs_open(struct inode *unused, struct file *file)
3711 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3714 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3717 return notify_on_release(cgrp);
3720 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3724 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3726 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3728 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3733 * Unregister event and free resources.
3735 * Gets called from workqueue.
3737 static void cgroup_event_remove(struct work_struct *work)
3739 struct cgroup_event *event = container_of(work, struct cgroup_event,
3741 struct cgroup *cgrp = event->cgrp;
3743 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3745 eventfd_ctx_put(event->eventfd);
3751 * Gets called on POLLHUP on eventfd when user closes it.
3753 * Called with wqh->lock held and interrupts disabled.
3755 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3756 int sync, void *key)
3758 struct cgroup_event *event = container_of(wait,
3759 struct cgroup_event, wait);
3760 struct cgroup *cgrp = event->cgrp;
3761 unsigned long flags = (unsigned long)key;
3763 if (flags & POLLHUP) {
3764 __remove_wait_queue(event->wqh, &event->wait);
3765 spin_lock(&cgrp->event_list_lock);
3766 list_del(&event->list);
3767 spin_unlock(&cgrp->event_list_lock);
3769 * We are in atomic context, but cgroup_event_remove() may
3770 * sleep, so we have to call it in workqueue.
3772 schedule_work(&event->remove);
3778 static void cgroup_event_ptable_queue_proc(struct file *file,
3779 wait_queue_head_t *wqh, poll_table *pt)
3781 struct cgroup_event *event = container_of(pt,
3782 struct cgroup_event, pt);
3785 add_wait_queue(wqh, &event->wait);
3789 * Parse input and register new cgroup event handler.
3791 * Input must be in format '<event_fd> <control_fd> <args>'.
3792 * Interpretation of args is defined by control file implementation.
3794 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3797 struct cgroup_event *event = NULL;
3798 unsigned int efd, cfd;
3799 struct file *efile = NULL;
3800 struct file *cfile = NULL;
3804 efd = simple_strtoul(buffer, &endp, 10);
3809 cfd = simple_strtoul(buffer, &endp, 10);
3810 if ((*endp != ' ') && (*endp != '\0'))
3814 event = kzalloc(sizeof(*event), GFP_KERNEL);
3818 INIT_LIST_HEAD(&event->list);
3819 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3820 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3821 INIT_WORK(&event->remove, cgroup_event_remove);
3823 efile = eventfd_fget(efd);
3824 if (IS_ERR(efile)) {
3825 ret = PTR_ERR(efile);
3829 event->eventfd = eventfd_ctx_fileget(efile);
3830 if (IS_ERR(event->eventfd)) {
3831 ret = PTR_ERR(event->eventfd);
3841 /* the process need read permission on control file */
3842 /* AV: shouldn't we check that it's been opened for read instead? */
3843 ret = inode_permission(cfile->f_path.dentry->d_inode, MAY_READ);
3847 event->cft = __file_cft(cfile);
3848 if (IS_ERR(event->cft)) {
3849 ret = PTR_ERR(event->cft);
3853 if (!event->cft->register_event || !event->cft->unregister_event) {
3858 ret = event->cft->register_event(cgrp, event->cft,
3859 event->eventfd, buffer);
3863 if (efile->f_op->poll(efile, &event->pt) & POLLHUP) {
3864 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3870 * Events should be removed after rmdir of cgroup directory, but before
3871 * destroying subsystem state objects. Let's take reference to cgroup
3872 * directory dentry to do that.
3876 spin_lock(&cgrp->event_list_lock);
3877 list_add(&event->list, &cgrp->event_list);
3878 spin_unlock(&cgrp->event_list_lock);
3889 if (event && event->eventfd && !IS_ERR(event->eventfd))
3890 eventfd_ctx_put(event->eventfd);
3892 if (!IS_ERR_OR_NULL(efile))
3900 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
3903 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3906 static int cgroup_clone_children_write(struct cgroup *cgrp,
3911 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3913 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3918 * for the common functions, 'private' gives the type of file
3920 /* for hysterical raisins, we can't put this on the older files */
3921 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3922 static struct cftype files[] = {
3925 .open = cgroup_tasks_open,
3926 .write_u64 = cgroup_tasks_write,
3927 .release = cgroup_pidlist_release,
3928 .mode = S_IRUGO | S_IWUSR,
3931 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
3932 .open = cgroup_procs_open,
3933 .write_u64 = cgroup_procs_write,
3934 .release = cgroup_pidlist_release,
3935 .mode = S_IRUGO | S_IWUSR,
3938 .name = "notify_on_release",
3939 .read_u64 = cgroup_read_notify_on_release,
3940 .write_u64 = cgroup_write_notify_on_release,
3943 .name = CGROUP_FILE_GENERIC_PREFIX "event_control",
3944 .write_string = cgroup_write_event_control,
3948 .name = "cgroup.clone_children",
3949 .read_u64 = cgroup_clone_children_read,
3950 .write_u64 = cgroup_clone_children_write,
3953 .name = "release_agent",
3954 .flags = CFTYPE_ONLY_ON_ROOT,
3955 .read_seq_string = cgroup_release_agent_show,
3956 .write_string = cgroup_release_agent_write,
3957 .max_write_len = PATH_MAX,
3963 * cgroup_populate_dir - selectively creation of files in a directory
3964 * @cgrp: target cgroup
3965 * @base_files: true if the base files should be added
3966 * @subsys_mask: mask of the subsystem ids whose files should be added
3968 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
3969 unsigned long subsys_mask)
3972 struct cgroup_subsys *ss;
3975 err = cgroup_addrm_files(cgrp, NULL, files, true);
3980 /* process cftsets of each subsystem */
3981 for_each_subsys(cgrp->root, ss) {
3982 struct cftype_set *set;
3983 if (!test_bit(ss->subsys_id, &subsys_mask))
3986 list_for_each_entry(set, &ss->cftsets, node)
3987 cgroup_addrm_files(cgrp, ss, set->cfts, true);
3990 /* This cgroup is ready now */
3991 for_each_subsys(cgrp->root, ss) {
3992 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3994 * Update id->css pointer and make this css visible from
3995 * CSS ID functions. This pointer will be dereferened
3996 * from RCU-read-side without locks.
3999 rcu_assign_pointer(css->id->css, css);
4005 static void css_dput_fn(struct work_struct *work)
4007 struct cgroup_subsys_state *css =
4008 container_of(work, struct cgroup_subsys_state, dput_work);
4009 struct dentry *dentry = css->cgroup->dentry;
4010 struct super_block *sb = dentry->d_sb;
4012 atomic_inc(&sb->s_active);
4014 deactivate_super(sb);
4017 static void init_cgroup_css(struct cgroup_subsys_state *css,
4018 struct cgroup_subsys *ss,
4019 struct cgroup *cgrp)
4022 atomic_set(&css->refcnt, 1);
4025 if (cgrp == dummytop)
4026 css->flags |= CSS_ROOT;
4027 BUG_ON(cgrp->subsys[ss->subsys_id]);
4028 cgrp->subsys[ss->subsys_id] = css;
4031 * css holds an extra ref to @cgrp->dentry which is put on the last
4032 * css_put(). dput() requires process context, which css_put() may
4033 * be called without. @css->dput_work will be used to invoke
4034 * dput() asynchronously from css_put().
4036 INIT_WORK(&css->dput_work, css_dput_fn);
4039 /* invoke ->post_create() on a new CSS and mark it online if successful */
4040 static int online_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4044 lockdep_assert_held(&cgroup_mutex);
4047 ret = ss->css_online(cgrp);
4049 cgrp->subsys[ss->subsys_id]->flags |= CSS_ONLINE;
4053 /* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4054 static void offline_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4055 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4057 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4059 lockdep_assert_held(&cgroup_mutex);
4061 if (!(css->flags & CSS_ONLINE))
4065 * css_offline() should be called with cgroup_mutex unlocked. See
4066 * 3fa59dfbc3 ("cgroup: fix potential deadlock in pre_destroy") for
4067 * details. This temporary unlocking should go away once
4068 * cgroup_mutex is unexported from controllers.
4070 if (ss->css_offline) {
4071 mutex_unlock(&cgroup_mutex);
4072 ss->css_offline(cgrp);
4073 mutex_lock(&cgroup_mutex);
4076 cgrp->subsys[ss->subsys_id]->flags &= ~CSS_ONLINE;
4080 * cgroup_create - create a cgroup
4081 * @parent: cgroup that will be parent of the new cgroup
4082 * @dentry: dentry of the new cgroup
4083 * @mode: mode to set on new inode
4085 * Must be called with the mutex on the parent inode held
4087 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4090 struct cgroup *cgrp;
4091 struct cgroupfs_root *root = parent->root;
4093 struct cgroup_subsys *ss;
4094 struct super_block *sb = root->sb;
4096 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4101 * Only live parents can have children. Note that the liveliness
4102 * check isn't strictly necessary because cgroup_mkdir() and
4103 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4104 * anyway so that locking is contained inside cgroup proper and we
4105 * don't get nasty surprises if we ever grow another caller.
4107 if (!cgroup_lock_live_group(parent)) {
4112 /* Grab a reference on the superblock so the hierarchy doesn't
4113 * get deleted on unmount if there are child cgroups. This
4114 * can be done outside cgroup_mutex, since the sb can't
4115 * disappear while someone has an open control file on the
4117 atomic_inc(&sb->s_active);
4119 init_cgroup_housekeeping(cgrp);
4121 cgrp->parent = parent;
4122 cgrp->root = parent->root;
4123 cgrp->top_cgroup = parent->top_cgroup;
4125 if (notify_on_release(parent))
4126 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4128 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4129 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4131 for_each_subsys(root, ss) {
4132 struct cgroup_subsys_state *css;
4134 css = ss->css_alloc(cgrp);
4139 init_cgroup_css(css, ss, cgrp);
4141 err = alloc_css_id(ss, parent, cgrp);
4146 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4148 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",
4149 current->comm, current->pid, ss->name);
4150 if (!strcmp(ss->name, "memory"))
4151 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4152 ss->warned_broken_hierarchy = true;
4157 * Create directory. cgroup_create_file() returns with the new
4158 * directory locked on success so that it can be populated without
4159 * dropping cgroup_mutex.
4161 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4164 lockdep_assert_held(&dentry->d_inode->i_mutex);
4166 /* allocation complete, commit to creation */
4167 dentry->d_fsdata = cgrp;
4168 cgrp->dentry = dentry;
4169 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4170 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4171 root->number_of_cgroups++;
4173 /* each css holds a ref to the cgroup's dentry */
4174 for_each_subsys(root, ss)
4177 /* creation succeeded, notify subsystems */
4178 for_each_subsys(root, ss) {
4179 err = online_css(ss, cgrp);
4184 err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4188 mutex_unlock(&cgroup_mutex);
4189 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4194 for_each_subsys(root, ss) {
4195 if (cgrp->subsys[ss->subsys_id])
4198 mutex_unlock(&cgroup_mutex);
4199 /* Release the reference count that we took on the superblock */
4200 deactivate_super(sb);
4206 cgroup_destroy_locked(cgrp);
4207 mutex_unlock(&cgroup_mutex);
4208 mutex_unlock(&dentry->d_inode->i_mutex);
4212 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4214 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4216 /* the vfs holds inode->i_mutex already */
4217 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4221 * Check the reference count on each subsystem. Since we already
4222 * established that there are no tasks in the cgroup, if the css refcount
4223 * is also 1, then there should be no outstanding references, so the
4224 * subsystem is safe to destroy. We scan across all subsystems rather than
4225 * using the per-hierarchy linked list of mounted subsystems since we can
4226 * be called via check_for_release() with no synchronization other than
4227 * RCU, and the subsystem linked list isn't RCU-safe.
4229 static int cgroup_has_css_refs(struct cgroup *cgrp)
4234 * We won't need to lock the subsys array, because the subsystems
4235 * we're concerned about aren't going anywhere since our cgroup root
4236 * has a reference on them.
4238 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4239 struct cgroup_subsys *ss = subsys[i];
4240 struct cgroup_subsys_state *css;
4242 /* Skip subsystems not present or not in this hierarchy */
4243 if (ss == NULL || ss->root != cgrp->root)
4246 css = cgrp->subsys[ss->subsys_id];
4248 * When called from check_for_release() it's possible
4249 * that by this point the cgroup has been removed
4250 * and the css deleted. But a false-positive doesn't
4251 * matter, since it can only happen if the cgroup
4252 * has been deleted and hence no longer needs the
4253 * release agent to be called anyway.
4255 if (css && css_refcnt(css) > 1)
4261 static int cgroup_destroy_locked(struct cgroup *cgrp)
4262 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4264 struct dentry *d = cgrp->dentry;
4265 struct cgroup *parent = cgrp->parent;
4267 struct cgroup_event *event, *tmp;
4268 struct cgroup_subsys *ss;
4270 lockdep_assert_held(&d->d_inode->i_mutex);
4271 lockdep_assert_held(&cgroup_mutex);
4273 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children))
4277 * Block new css_tryget() by deactivating refcnt and mark @cgrp
4278 * removed. This makes future css_tryget() and child creation
4279 * attempts fail thus maintaining the removal conditions verified
4282 for_each_subsys(cgrp->root, ss) {
4283 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4285 WARN_ON(atomic_read(&css->refcnt) < 0);
4286 atomic_add(CSS_DEACT_BIAS, &css->refcnt);
4288 set_bit(CGRP_REMOVED, &cgrp->flags);
4290 /* tell subsystems to initate destruction */
4291 for_each_subsys(cgrp->root, ss)
4292 offline_css(ss, cgrp);
4295 * Put all the base refs. Each css holds an extra reference to the
4296 * cgroup's dentry and cgroup removal proceeds regardless of css
4297 * refs. On the last put of each css, whenever that may be, the
4298 * extra dentry ref is put so that dentry destruction happens only
4299 * after all css's are released.
4301 for_each_subsys(cgrp->root, ss)
4302 css_put(cgrp->subsys[ss->subsys_id]);
4304 raw_spin_lock(&release_list_lock);
4305 if (!list_empty(&cgrp->release_list))
4306 list_del_init(&cgrp->release_list);
4307 raw_spin_unlock(&release_list_lock);
4309 /* delete this cgroup from parent->children */
4310 list_del_rcu(&cgrp->sibling);
4311 list_del_init(&cgrp->allcg_node);
4314 cgroup_d_remove_dir(d);
4317 set_bit(CGRP_RELEASABLE, &parent->flags);
4318 check_for_release(parent);
4321 * Unregister events and notify userspace.
4322 * Notify userspace about cgroup removing only after rmdir of cgroup
4323 * directory to avoid race between userspace and kernelspace
4325 spin_lock(&cgrp->event_list_lock);
4326 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4327 list_del(&event->list);
4328 remove_wait_queue(event->wqh, &event->wait);
4329 eventfd_signal(event->eventfd, 1);
4330 schedule_work(&event->remove);
4332 spin_unlock(&cgrp->event_list_lock);
4337 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4341 mutex_lock(&cgroup_mutex);
4342 ret = cgroup_destroy_locked(dentry->d_fsdata);
4343 mutex_unlock(&cgroup_mutex);
4348 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4350 INIT_LIST_HEAD(&ss->cftsets);
4353 * base_cftset is embedded in subsys itself, no need to worry about
4356 if (ss->base_cftypes) {
4357 ss->base_cftset.cfts = ss->base_cftypes;
4358 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4362 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4364 struct cgroup_subsys_state *css;
4366 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4368 mutex_lock(&cgroup_mutex);
4370 /* init base cftset */
4371 cgroup_init_cftsets(ss);
4373 /* Create the top cgroup state for this subsystem */
4374 list_add(&ss->sibling, &rootnode.subsys_list);
4375 ss->root = &rootnode;
4376 css = ss->css_alloc(dummytop);
4377 /* We don't handle early failures gracefully */
4378 BUG_ON(IS_ERR(css));
4379 init_cgroup_css(css, ss, dummytop);
4381 /* Update the init_css_set to contain a subsys
4382 * pointer to this state - since the subsystem is
4383 * newly registered, all tasks and hence the
4384 * init_css_set is in the subsystem's top cgroup. */
4385 init_css_set.subsys[ss->subsys_id] = css;
4387 need_forkexit_callback |= ss->fork || ss->exit;
4389 /* At system boot, before all subsystems have been
4390 * registered, no tasks have been forked, so we don't
4391 * need to invoke fork callbacks here. */
4392 BUG_ON(!list_empty(&init_task.tasks));
4395 BUG_ON(online_css(ss, dummytop));
4397 mutex_unlock(&cgroup_mutex);
4399 /* this function shouldn't be used with modular subsystems, since they
4400 * need to register a subsys_id, among other things */
4405 * cgroup_load_subsys: load and register a modular subsystem at runtime
4406 * @ss: the subsystem to load
4408 * This function should be called in a modular subsystem's initcall. If the
4409 * subsystem is built as a module, it will be assigned a new subsys_id and set
4410 * up for use. If the subsystem is built-in anyway, work is delegated to the
4411 * simpler cgroup_init_subsys.
4413 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4415 struct cgroup_subsys_state *css;
4418 /* check name and function validity */
4419 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4420 ss->css_alloc == NULL || ss->css_free == NULL)
4424 * we don't support callbacks in modular subsystems. this check is
4425 * before the ss->module check for consistency; a subsystem that could
4426 * be a module should still have no callbacks even if the user isn't
4427 * compiling it as one.
4429 if (ss->fork || ss->exit)
4433 * an optionally modular subsystem is built-in: we want to do nothing,
4434 * since cgroup_init_subsys will have already taken care of it.
4436 if (ss->module == NULL) {
4437 /* a sanity check */
4438 BUG_ON(subsys[ss->subsys_id] != ss);
4442 /* init base cftset */
4443 cgroup_init_cftsets(ss);
4445 mutex_lock(&cgroup_mutex);
4446 subsys[ss->subsys_id] = ss;
4449 * no ss->css_alloc seems to need anything important in the ss
4450 * struct, so this can happen first (i.e. before the rootnode
4453 css = ss->css_alloc(dummytop);
4455 /* failure case - need to deassign the subsys[] slot. */
4456 subsys[ss->subsys_id] = NULL;
4457 mutex_unlock(&cgroup_mutex);
4458 return PTR_ERR(css);
4461 list_add(&ss->sibling, &rootnode.subsys_list);
4462 ss->root = &rootnode;
4464 /* our new subsystem will be attached to the dummy hierarchy. */
4465 init_cgroup_css(css, ss, dummytop);
4466 /* init_idr must be after init_cgroup_css because it sets css->id. */
4468 ret = cgroup_init_idr(ss, css);
4474 * Now we need to entangle the css into the existing css_sets. unlike
4475 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4476 * will need a new pointer to it; done by iterating the css_set_table.
4477 * furthermore, modifying the existing css_sets will corrupt the hash
4478 * table state, so each changed css_set will need its hash recomputed.
4479 * this is all done under the css_set_lock.
4481 write_lock(&css_set_lock);
4482 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
4484 struct hlist_node *node, *tmp;
4485 struct hlist_head *bucket = &css_set_table[i], *new_bucket;
4487 hlist_for_each_entry_safe(cg, node, tmp, bucket, hlist) {
4488 /* skip entries that we already rehashed */
4489 if (cg->subsys[ss->subsys_id])
4491 /* remove existing entry */
4492 hlist_del(&cg->hlist);
4494 cg->subsys[ss->subsys_id] = css;
4495 /* recompute hash and restore entry */
4496 new_bucket = css_set_hash(cg->subsys);
4497 hlist_add_head(&cg->hlist, new_bucket);
4500 write_unlock(&css_set_lock);
4503 ret = online_css(ss, dummytop);
4508 mutex_unlock(&cgroup_mutex);
4512 mutex_unlock(&cgroup_mutex);
4513 /* @ss can't be mounted here as try_module_get() would fail */
4514 cgroup_unload_subsys(ss);
4517 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4520 * cgroup_unload_subsys: unload a modular subsystem
4521 * @ss: the subsystem to unload
4523 * This function should be called in a modular subsystem's exitcall. When this
4524 * function is invoked, the refcount on the subsystem's module will be 0, so
4525 * the subsystem will not be attached to any hierarchy.
4527 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4529 struct cg_cgroup_link *link;
4530 struct hlist_head *hhead;
4532 BUG_ON(ss->module == NULL);
4535 * we shouldn't be called if the subsystem is in use, and the use of
4536 * try_module_get in parse_cgroupfs_options should ensure that it
4537 * doesn't start being used while we're killing it off.
4539 BUG_ON(ss->root != &rootnode);
4541 mutex_lock(&cgroup_mutex);
4543 offline_css(ss, dummytop);
4547 idr_remove_all(&ss->idr);
4548 idr_destroy(&ss->idr);
4551 /* deassign the subsys_id */
4552 subsys[ss->subsys_id] = NULL;
4554 /* remove subsystem from rootnode's list of subsystems */
4555 list_del_init(&ss->sibling);
4558 * disentangle the css from all css_sets attached to the dummytop. as
4559 * in loading, we need to pay our respects to the hashtable gods.
4561 write_lock(&css_set_lock);
4562 list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
4563 struct css_set *cg = link->cg;
4565 hlist_del(&cg->hlist);
4566 cg->subsys[ss->subsys_id] = NULL;
4567 hhead = css_set_hash(cg->subsys);
4568 hlist_add_head(&cg->hlist, hhead);
4570 write_unlock(&css_set_lock);
4573 * remove subsystem's css from the dummytop and free it - need to
4574 * free before marking as null because ss->css_free needs the
4575 * cgrp->subsys pointer to find their state. note that this also
4576 * takes care of freeing the css_id.
4578 ss->css_free(dummytop);
4579 dummytop->subsys[ss->subsys_id] = NULL;
4581 mutex_unlock(&cgroup_mutex);
4583 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4586 * cgroup_init_early - cgroup initialization at system boot
4588 * Initialize cgroups at system boot, and initialize any
4589 * subsystems that request early init.
4591 int __init cgroup_init_early(void)
4594 atomic_set(&init_css_set.refcount, 1);
4595 INIT_LIST_HEAD(&init_css_set.cg_links);
4596 INIT_LIST_HEAD(&init_css_set.tasks);
4597 INIT_HLIST_NODE(&init_css_set.hlist);
4599 init_cgroup_root(&rootnode);
4601 init_task.cgroups = &init_css_set;
4603 init_css_set_link.cg = &init_css_set;
4604 init_css_set_link.cgrp = dummytop;
4605 list_add(&init_css_set_link.cgrp_link_list,
4606 &rootnode.top_cgroup.css_sets);
4607 list_add(&init_css_set_link.cg_link_list,
4608 &init_css_set.cg_links);
4610 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
4611 INIT_HLIST_HEAD(&css_set_table[i]);
4613 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4614 struct cgroup_subsys *ss = subsys[i];
4616 /* at bootup time, we don't worry about modular subsystems */
4617 if (!ss || ss->module)
4621 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4622 BUG_ON(!ss->css_alloc);
4623 BUG_ON(!ss->css_free);
4624 if (ss->subsys_id != i) {
4625 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4626 ss->name, ss->subsys_id);
4631 cgroup_init_subsys(ss);
4637 * cgroup_init - cgroup initialization
4639 * Register cgroup filesystem and /proc file, and initialize
4640 * any subsystems that didn't request early init.
4642 int __init cgroup_init(void)
4646 struct hlist_head *hhead;
4648 err = bdi_init(&cgroup_backing_dev_info);
4652 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4653 struct cgroup_subsys *ss = subsys[i];
4655 /* at bootup time, we don't worry about modular subsystems */
4656 if (!ss || ss->module)
4658 if (!ss->early_init)
4659 cgroup_init_subsys(ss);
4661 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4664 /* Add init_css_set to the hash table */
4665 hhead = css_set_hash(init_css_set.subsys);
4666 hlist_add_head(&init_css_set.hlist, hhead);
4667 BUG_ON(!init_root_id(&rootnode));
4669 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4675 err = register_filesystem(&cgroup_fs_type);
4677 kobject_put(cgroup_kobj);
4681 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4685 bdi_destroy(&cgroup_backing_dev_info);
4691 * proc_cgroup_show()
4692 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4693 * - Used for /proc/<pid>/cgroup.
4694 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4695 * doesn't really matter if tsk->cgroup changes after we read it,
4696 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4697 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4698 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4699 * cgroup to top_cgroup.
4702 /* TODO: Use a proper seq_file iterator */
4703 static int proc_cgroup_show(struct seq_file *m, void *v)
4706 struct task_struct *tsk;
4709 struct cgroupfs_root *root;
4712 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4718 tsk = get_pid_task(pid, PIDTYPE_PID);
4724 mutex_lock(&cgroup_mutex);
4726 for_each_active_root(root) {
4727 struct cgroup_subsys *ss;
4728 struct cgroup *cgrp;
4731 seq_printf(m, "%d:", root->hierarchy_id);
4732 for_each_subsys(root, ss)
4733 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4734 if (strlen(root->name))
4735 seq_printf(m, "%sname=%s", count ? "," : "",
4738 cgrp = task_cgroup_from_root(tsk, root);
4739 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4747 mutex_unlock(&cgroup_mutex);
4748 put_task_struct(tsk);
4755 static int cgroup_open(struct inode *inode, struct file *file)
4757 struct pid *pid = PROC_I(inode)->pid;
4758 return single_open(file, proc_cgroup_show, pid);
4761 const struct file_operations proc_cgroup_operations = {
4762 .open = cgroup_open,
4764 .llseek = seq_lseek,
4765 .release = single_release,
4768 /* Display information about each subsystem and each hierarchy */
4769 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4773 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4775 * ideally we don't want subsystems moving around while we do this.
4776 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4777 * subsys/hierarchy state.
4779 mutex_lock(&cgroup_mutex);
4780 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4781 struct cgroup_subsys *ss = subsys[i];
4784 seq_printf(m, "%s\t%d\t%d\t%d\n",
4785 ss->name, ss->root->hierarchy_id,
4786 ss->root->number_of_cgroups, !ss->disabled);
4788 mutex_unlock(&cgroup_mutex);
4792 static int cgroupstats_open(struct inode *inode, struct file *file)
4794 return single_open(file, proc_cgroupstats_show, NULL);
4797 static const struct file_operations proc_cgroupstats_operations = {
4798 .open = cgroupstats_open,
4800 .llseek = seq_lseek,
4801 .release = single_release,
4805 * cgroup_fork - attach newly forked task to its parents cgroup.
4806 * @child: pointer to task_struct of forking parent process.
4808 * Description: A task inherits its parent's cgroup at fork().
4810 * A pointer to the shared css_set was automatically copied in
4811 * fork.c by dup_task_struct(). However, we ignore that copy, since
4812 * it was not made under the protection of RCU or cgroup_mutex, so
4813 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4814 * have already changed current->cgroups, allowing the previously
4815 * referenced cgroup group to be removed and freed.
4817 * At the point that cgroup_fork() is called, 'current' is the parent
4818 * task, and the passed argument 'child' points to the child task.
4820 void cgroup_fork(struct task_struct *child)
4823 child->cgroups = current->cgroups;
4824 get_css_set(child->cgroups);
4825 task_unlock(current);
4826 INIT_LIST_HEAD(&child->cg_list);
4830 * cgroup_post_fork - called on a new task after adding it to the task list
4831 * @child: the task in question
4833 * Adds the task to the list running through its css_set if necessary and
4834 * call the subsystem fork() callbacks. Has to be after the task is
4835 * visible on the task list in case we race with the first call to
4836 * cgroup_iter_start() - to guarantee that the new task ends up on its
4839 void cgroup_post_fork(struct task_struct *child)
4844 * use_task_css_set_links is set to 1 before we walk the tasklist
4845 * under the tasklist_lock and we read it here after we added the child
4846 * to the tasklist under the tasklist_lock as well. If the child wasn't
4847 * yet in the tasklist when we walked through it from
4848 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4849 * should be visible now due to the paired locking and barriers implied
4850 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4851 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4854 if (use_task_css_set_links) {
4855 write_lock(&css_set_lock);
4857 if (list_empty(&child->cg_list))
4858 list_add(&child->cg_list, &child->cgroups->tasks);
4860 write_unlock(&css_set_lock);
4864 * Call ss->fork(). This must happen after @child is linked on
4865 * css_set; otherwise, @child might change state between ->fork()
4866 * and addition to css_set.
4868 if (need_forkexit_callback) {
4869 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4870 struct cgroup_subsys *ss = subsys[i];
4873 * fork/exit callbacks are supported only for
4874 * builtin subsystems and we don't need further
4875 * synchronization as they never go away.
4877 if (!ss || ss->module)
4887 * cgroup_exit - detach cgroup from exiting task
4888 * @tsk: pointer to task_struct of exiting process
4889 * @run_callback: run exit callbacks?
4891 * Description: Detach cgroup from @tsk and release it.
4893 * Note that cgroups marked notify_on_release force every task in
4894 * them to take the global cgroup_mutex mutex when exiting.
4895 * This could impact scaling on very large systems. Be reluctant to
4896 * use notify_on_release cgroups where very high task exit scaling
4897 * is required on large systems.
4899 * the_top_cgroup_hack:
4901 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4903 * We call cgroup_exit() while the task is still competent to
4904 * handle notify_on_release(), then leave the task attached to the
4905 * root cgroup in each hierarchy for the remainder of its exit.
4907 * To do this properly, we would increment the reference count on
4908 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4909 * code we would add a second cgroup function call, to drop that
4910 * reference. This would just create an unnecessary hot spot on
4911 * the top_cgroup reference count, to no avail.
4913 * Normally, holding a reference to a cgroup without bumping its
4914 * count is unsafe. The cgroup could go away, or someone could
4915 * attach us to a different cgroup, decrementing the count on
4916 * the first cgroup that we never incremented. But in this case,
4917 * top_cgroup isn't going away, and either task has PF_EXITING set,
4918 * which wards off any cgroup_attach_task() attempts, or task is a failed
4919 * fork, never visible to cgroup_attach_task.
4921 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4927 * Unlink from the css_set task list if necessary.
4928 * Optimistically check cg_list before taking
4931 if (!list_empty(&tsk->cg_list)) {
4932 write_lock(&css_set_lock);
4933 if (!list_empty(&tsk->cg_list))
4934 list_del_init(&tsk->cg_list);
4935 write_unlock(&css_set_lock);
4938 /* Reassign the task to the init_css_set. */
4941 tsk->cgroups = &init_css_set;
4943 if (run_callbacks && need_forkexit_callback) {
4944 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4945 struct cgroup_subsys *ss = subsys[i];
4947 /* modular subsystems can't use callbacks */
4948 if (!ss || ss->module)
4952 struct cgroup *old_cgrp =
4953 rcu_dereference_raw(cg->subsys[i])->cgroup;
4954 struct cgroup *cgrp = task_cgroup(tsk, i);
4955 ss->exit(cgrp, old_cgrp, tsk);
4962 put_css_set_taskexit(cg);
4966 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
4967 * @cgrp: the cgroup in question
4968 * @task: the task in question
4970 * See if @cgrp is a descendant of @task's cgroup in the appropriate
4973 * If we are sending in dummytop, then presumably we are creating
4974 * the top cgroup in the subsystem.
4976 * Called only by the ns (nsproxy) cgroup.
4978 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
4981 struct cgroup *target;
4983 if (cgrp == dummytop)
4986 target = task_cgroup_from_root(task, cgrp->root);
4987 while (cgrp != target && cgrp!= cgrp->top_cgroup)
4988 cgrp = cgrp->parent;
4989 ret = (cgrp == target);
4993 static void check_for_release(struct cgroup *cgrp)
4995 /* All of these checks rely on RCU to keep the cgroup
4996 * structure alive */
4997 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
4998 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
4999 /* Control Group is currently removeable. If it's not
5000 * already queued for a userspace notification, queue
5002 int need_schedule_work = 0;
5003 raw_spin_lock(&release_list_lock);
5004 if (!cgroup_is_removed(cgrp) &&
5005 list_empty(&cgrp->release_list)) {
5006 list_add(&cgrp->release_list, &release_list);
5007 need_schedule_work = 1;
5009 raw_spin_unlock(&release_list_lock);
5010 if (need_schedule_work)
5011 schedule_work(&release_agent_work);
5015 /* Caller must verify that the css is not for root cgroup */
5016 bool __css_tryget(struct cgroup_subsys_state *css)
5021 v = css_refcnt(css);
5022 t = atomic_cmpxchg(&css->refcnt, v, v + 1);
5030 EXPORT_SYMBOL_GPL(__css_tryget);
5032 /* Caller must verify that the css is not for root cgroup */
5033 void __css_put(struct cgroup_subsys_state *css)
5035 struct cgroup *cgrp = css->cgroup;
5039 v = css_unbias_refcnt(atomic_dec_return(&css->refcnt));
5043 if (notify_on_release(cgrp)) {
5044 set_bit(CGRP_RELEASABLE, &cgrp->flags);
5045 check_for_release(cgrp);
5049 schedule_work(&css->dput_work);
5054 EXPORT_SYMBOL_GPL(__css_put);
5057 * Notify userspace when a cgroup is released, by running the
5058 * configured release agent with the name of the cgroup (path
5059 * relative to the root of cgroup file system) as the argument.
5061 * Most likely, this user command will try to rmdir this cgroup.
5063 * This races with the possibility that some other task will be
5064 * attached to this cgroup before it is removed, or that some other
5065 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5066 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5067 * unused, and this cgroup will be reprieved from its death sentence,
5068 * to continue to serve a useful existence. Next time it's released,
5069 * we will get notified again, if it still has 'notify_on_release' set.
5071 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5072 * means only wait until the task is successfully execve()'d. The
5073 * separate release agent task is forked by call_usermodehelper(),
5074 * then control in this thread returns here, without waiting for the
5075 * release agent task. We don't bother to wait because the caller of
5076 * this routine has no use for the exit status of the release agent
5077 * task, so no sense holding our caller up for that.
5079 static void cgroup_release_agent(struct work_struct *work)
5081 BUG_ON(work != &release_agent_work);
5082 mutex_lock(&cgroup_mutex);
5083 raw_spin_lock(&release_list_lock);
5084 while (!list_empty(&release_list)) {
5085 char *argv[3], *envp[3];
5087 char *pathbuf = NULL, *agentbuf = NULL;
5088 struct cgroup *cgrp = list_entry(release_list.next,
5091 list_del_init(&cgrp->release_list);
5092 raw_spin_unlock(&release_list_lock);
5093 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5096 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5098 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5103 argv[i++] = agentbuf;
5104 argv[i++] = pathbuf;
5108 /* minimal command environment */
5109 envp[i++] = "HOME=/";
5110 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5113 /* Drop the lock while we invoke the usermode helper,
5114 * since the exec could involve hitting disk and hence
5115 * be a slow process */
5116 mutex_unlock(&cgroup_mutex);
5117 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5118 mutex_lock(&cgroup_mutex);
5122 raw_spin_lock(&release_list_lock);
5124 raw_spin_unlock(&release_list_lock);
5125 mutex_unlock(&cgroup_mutex);
5128 static int __init cgroup_disable(char *str)
5133 while ((token = strsep(&str, ",")) != NULL) {
5136 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
5137 struct cgroup_subsys *ss = subsys[i];
5140 * cgroup_disable, being at boot time, can't
5141 * know about module subsystems, so we don't
5144 if (!ss || ss->module)
5147 if (!strcmp(token, ss->name)) {
5149 printk(KERN_INFO "Disabling %s control group"
5150 " subsystem\n", ss->name);
5157 __setup("cgroup_disable=", cgroup_disable);
5160 * Functons for CSS ID.
5164 *To get ID other than 0, this should be called when !cgroup_is_removed().
5166 unsigned short css_id(struct cgroup_subsys_state *css)
5168 struct css_id *cssid;
5171 * This css_id() can return correct value when somone has refcnt
5172 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5173 * it's unchanged until freed.
5175 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5181 EXPORT_SYMBOL_GPL(css_id);
5183 unsigned short css_depth(struct cgroup_subsys_state *css)
5185 struct css_id *cssid;
5187 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5190 return cssid->depth;
5193 EXPORT_SYMBOL_GPL(css_depth);
5196 * css_is_ancestor - test "root" css is an ancestor of "child"
5197 * @child: the css to be tested.
5198 * @root: the css supporsed to be an ancestor of the child.
5200 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5201 * this function reads css->id, the caller must hold rcu_read_lock().
5202 * But, considering usual usage, the csses should be valid objects after test.
5203 * Assuming that the caller will do some action to the child if this returns
5204 * returns true, the caller must take "child";s reference count.
5205 * If "child" is valid object and this returns true, "root" is valid, too.
5208 bool css_is_ancestor(struct cgroup_subsys_state *child,
5209 const struct cgroup_subsys_state *root)
5211 struct css_id *child_id;
5212 struct css_id *root_id;
5214 child_id = rcu_dereference(child->id);
5217 root_id = rcu_dereference(root->id);
5220 if (child_id->depth < root_id->depth)
5222 if (child_id->stack[root_id->depth] != root_id->id)
5227 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5229 struct css_id *id = css->id;
5230 /* When this is called before css_id initialization, id can be NULL */
5234 BUG_ON(!ss->use_id);
5236 rcu_assign_pointer(id->css, NULL);
5237 rcu_assign_pointer(css->id, NULL);
5238 spin_lock(&ss->id_lock);
5239 idr_remove(&ss->idr, id->id);
5240 spin_unlock(&ss->id_lock);
5241 kfree_rcu(id, rcu_head);
5243 EXPORT_SYMBOL_GPL(free_css_id);
5246 * This is called by init or create(). Then, calls to this function are
5247 * always serialized (By cgroup_mutex() at create()).
5250 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5252 struct css_id *newid;
5253 int myid, error, size;
5255 BUG_ON(!ss->use_id);
5257 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5258 newid = kzalloc(size, GFP_KERNEL);
5260 return ERR_PTR(-ENOMEM);
5262 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
5266 spin_lock(&ss->id_lock);
5267 /* Don't use 0. allocates an ID of 1-65535 */
5268 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
5269 spin_unlock(&ss->id_lock);
5271 /* Returns error when there are no free spaces for new ID.*/
5276 if (myid > CSS_ID_MAX)
5280 newid->depth = depth;
5284 spin_lock(&ss->id_lock);
5285 idr_remove(&ss->idr, myid);
5286 spin_unlock(&ss->id_lock);
5289 return ERR_PTR(error);
5293 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5294 struct cgroup_subsys_state *rootcss)
5296 struct css_id *newid;
5298 spin_lock_init(&ss->id_lock);
5301 newid = get_new_cssid(ss, 0);
5303 return PTR_ERR(newid);
5305 newid->stack[0] = newid->id;
5306 newid->css = rootcss;
5307 rootcss->id = newid;
5311 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5312 struct cgroup *child)
5314 int subsys_id, i, depth = 0;
5315 struct cgroup_subsys_state *parent_css, *child_css;
5316 struct css_id *child_id, *parent_id;
5318 subsys_id = ss->subsys_id;
5319 parent_css = parent->subsys[subsys_id];
5320 child_css = child->subsys[subsys_id];
5321 parent_id = parent_css->id;
5322 depth = parent_id->depth + 1;
5324 child_id = get_new_cssid(ss, depth);
5325 if (IS_ERR(child_id))
5326 return PTR_ERR(child_id);
5328 for (i = 0; i < depth; i++)
5329 child_id->stack[i] = parent_id->stack[i];
5330 child_id->stack[depth] = child_id->id;
5332 * child_id->css pointer will be set after this cgroup is available
5333 * see cgroup_populate_dir()
5335 rcu_assign_pointer(child_css->id, child_id);
5341 * css_lookup - lookup css by id
5342 * @ss: cgroup subsys to be looked into.
5345 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5346 * NULL if not. Should be called under rcu_read_lock()
5348 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5350 struct css_id *cssid = NULL;
5352 BUG_ON(!ss->use_id);
5353 cssid = idr_find(&ss->idr, id);
5355 if (unlikely(!cssid))
5358 return rcu_dereference(cssid->css);
5360 EXPORT_SYMBOL_GPL(css_lookup);
5363 * css_get_next - lookup next cgroup under specified hierarchy.
5364 * @ss: pointer to subsystem
5365 * @id: current position of iteration.
5366 * @root: pointer to css. search tree under this.
5367 * @foundid: position of found object.
5369 * Search next css under the specified hierarchy of rootid. Calling under
5370 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
5372 struct cgroup_subsys_state *
5373 css_get_next(struct cgroup_subsys *ss, int id,
5374 struct cgroup_subsys_state *root, int *foundid)
5376 struct cgroup_subsys_state *ret = NULL;
5379 int rootid = css_id(root);
5380 int depth = css_depth(root);
5385 BUG_ON(!ss->use_id);
5386 WARN_ON_ONCE(!rcu_read_lock_held());
5388 /* fill start point for scan */
5392 * scan next entry from bitmap(tree), tmpid is updated after
5395 tmp = idr_get_next(&ss->idr, &tmpid);
5398 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
5399 ret = rcu_dereference(tmp->css);
5405 /* continue to scan from next id */
5412 * get corresponding css from file open on cgroupfs directory
5414 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5416 struct cgroup *cgrp;
5417 struct inode *inode;
5418 struct cgroup_subsys_state *css;
5420 inode = f->f_dentry->d_inode;
5421 /* check in cgroup filesystem dir */
5422 if (inode->i_op != &cgroup_dir_inode_operations)
5423 return ERR_PTR(-EBADF);
5425 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5426 return ERR_PTR(-EINVAL);
5429 cgrp = __d_cgrp(f->f_dentry);
5430 css = cgrp->subsys[id];
5431 return css ? css : ERR_PTR(-ENOENT);
5434 #ifdef CONFIG_CGROUP_DEBUG
5435 static struct cgroup_subsys_state *debug_css_alloc(struct cgroup *cont)
5437 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5440 return ERR_PTR(-ENOMEM);
5445 static void debug_css_free(struct cgroup *cont)
5447 kfree(cont->subsys[debug_subsys_id]);
5450 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
5452 return atomic_read(&cont->count);
5455 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5457 return cgroup_task_count(cont);
5460 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5462 return (u64)(unsigned long)current->cgroups;
5465 static u64 current_css_set_refcount_read(struct cgroup *cont,
5471 count = atomic_read(¤t->cgroups->refcount);
5476 static int current_css_set_cg_links_read(struct cgroup *cont,
5478 struct seq_file *seq)
5480 struct cg_cgroup_link *link;
5483 read_lock(&css_set_lock);
5485 cg = rcu_dereference(current->cgroups);
5486 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
5487 struct cgroup *c = link->cgrp;
5491 name = c->dentry->d_name.name;
5494 seq_printf(seq, "Root %d group %s\n",
5495 c->root->hierarchy_id, name);
5498 read_unlock(&css_set_lock);
5502 #define MAX_TASKS_SHOWN_PER_CSS 25
5503 static int cgroup_css_links_read(struct cgroup *cont,
5505 struct seq_file *seq)
5507 struct cg_cgroup_link *link;
5509 read_lock(&css_set_lock);
5510 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
5511 struct css_set *cg = link->cg;
5512 struct task_struct *task;
5514 seq_printf(seq, "css_set %p\n", cg);
5515 list_for_each_entry(task, &cg->tasks, cg_list) {
5516 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5517 seq_puts(seq, " ...\n");
5520 seq_printf(seq, " task %d\n",
5521 task_pid_vnr(task));
5525 read_unlock(&css_set_lock);
5529 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5531 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5534 static struct cftype debug_files[] = {
5536 .name = "cgroup_refcount",
5537 .read_u64 = cgroup_refcount_read,
5540 .name = "taskcount",
5541 .read_u64 = debug_taskcount_read,
5545 .name = "current_css_set",
5546 .read_u64 = current_css_set_read,
5550 .name = "current_css_set_refcount",
5551 .read_u64 = current_css_set_refcount_read,
5555 .name = "current_css_set_cg_links",
5556 .read_seq_string = current_css_set_cg_links_read,
5560 .name = "cgroup_css_links",
5561 .read_seq_string = cgroup_css_links_read,
5565 .name = "releasable",
5566 .read_u64 = releasable_read,
5572 struct cgroup_subsys debug_subsys = {
5574 .css_alloc = debug_css_alloc,
5575 .css_free = debug_css_free,
5576 .subsys_id = debug_subsys_id,
5577 .base_cftypes = debug_files,
5579 #endif /* CONFIG_CGROUP_DEBUG */