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 up to CGROUP_BUILTIN_SUBSYS_COUNT, and modular subsystems are
92 * registered after that. The mutable section of this array is protected by
95 #define SUBSYS(_x) &_x ## _subsys,
96 static struct cgroup_subsys *subsys[CGROUP_SUBSYS_COUNT] = {
97 #include <linux/cgroup_subsys.h>
100 #define MAX_CGROUP_ROOT_NAMELEN 64
103 * A cgroupfs_root represents the root of a cgroup hierarchy,
104 * and may be associated with a superblock to form an active
107 struct cgroupfs_root {
108 struct super_block *sb;
111 * The bitmask of subsystems intended to be attached to this
114 unsigned long subsys_mask;
116 /* Unique id for this hierarchy. */
119 /* The bitmask of subsystems currently attached to this hierarchy */
120 unsigned long actual_subsys_mask;
122 /* A list running through the attached subsystems */
123 struct list_head subsys_list;
125 /* The root cgroup for this hierarchy */
126 struct cgroup top_cgroup;
128 /* Tracks how many cgroups are currently defined in hierarchy.*/
129 int number_of_cgroups;
131 /* A list running through the active hierarchies */
132 struct list_head root_list;
134 /* All cgroups on this root, cgroup_mutex protected */
135 struct list_head allcg_list;
137 /* Hierarchy-specific flags */
140 /* The path to use for release notifications. */
141 char release_agent_path[PATH_MAX];
143 /* The name for this hierarchy - may be empty */
144 char name[MAX_CGROUP_ROOT_NAMELEN];
148 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
149 * subsystems that are otherwise unattached - it never has more than a
150 * single cgroup, and all tasks are part of that cgroup.
152 static struct cgroupfs_root rootnode;
155 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
158 struct list_head node;
159 struct dentry *dentry;
164 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
165 * cgroup_subsys->use_id != 0.
167 #define CSS_ID_MAX (65535)
170 * The css to which this ID points. This pointer is set to valid value
171 * after cgroup is populated. If cgroup is removed, this will be NULL.
172 * This pointer is expected to be RCU-safe because destroy()
173 * is called after synchronize_rcu(). But for safe use, css_is_removed()
174 * css_tryget() should be used for avoiding race.
176 struct cgroup_subsys_state __rcu *css;
182 * Depth in hierarchy which this ID belongs to.
184 unsigned short depth;
186 * ID is freed by RCU. (and lookup routine is RCU safe.)
188 struct rcu_head rcu_head;
190 * Hierarchy of CSS ID belongs to.
192 unsigned short stack[0]; /* Array of Length (depth+1) */
196 * cgroup_event represents events which userspace want to receive.
198 struct cgroup_event {
200 * Cgroup which the event belongs to.
204 * Control file which the event associated.
208 * eventfd to signal userspace about the event.
210 struct eventfd_ctx *eventfd;
212 * Each of these stored in a list by the cgroup.
214 struct list_head list;
216 * All fields below needed to unregister event when
217 * userspace closes eventfd.
220 wait_queue_head_t *wqh;
222 struct work_struct remove;
225 /* The list of hierarchy roots */
227 static LIST_HEAD(roots);
228 static int root_count;
230 static DEFINE_IDA(hierarchy_ida);
231 static int next_hierarchy_id;
232 static DEFINE_SPINLOCK(hierarchy_id_lock);
234 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
235 #define dummytop (&rootnode.top_cgroup)
237 /* This flag indicates whether tasks in the fork and exit paths should
238 * check for fork/exit handlers to call. This avoids us having to do
239 * extra work in the fork/exit path if none of the subsystems need to
242 static int need_forkexit_callback __read_mostly;
244 #ifdef CONFIG_PROVE_LOCKING
245 int cgroup_lock_is_held(void)
247 return lockdep_is_held(&cgroup_mutex);
249 #else /* #ifdef CONFIG_PROVE_LOCKING */
250 int cgroup_lock_is_held(void)
252 return mutex_is_locked(&cgroup_mutex);
254 #endif /* #else #ifdef CONFIG_PROVE_LOCKING */
256 EXPORT_SYMBOL_GPL(cgroup_lock_is_held);
258 static int css_unbias_refcnt(int refcnt)
260 return refcnt >= 0 ? refcnt : refcnt - CSS_DEACT_BIAS;
263 /* the current nr of refs, always >= 0 whether @css is deactivated or not */
264 static int css_refcnt(struct cgroup_subsys_state *css)
266 int v = atomic_read(&css->refcnt);
268 return css_unbias_refcnt(v);
271 /* convenient tests for these bits */
272 inline int cgroup_is_removed(const struct cgroup *cgrp)
274 return test_bit(CGRP_REMOVED, &cgrp->flags);
277 /* bits in struct cgroupfs_root flags field */
279 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
280 ROOT_XATTR, /* supports extended attributes */
283 static int cgroup_is_releasable(const struct cgroup *cgrp)
286 (1 << CGRP_RELEASABLE) |
287 (1 << CGRP_NOTIFY_ON_RELEASE);
288 return (cgrp->flags & bits) == bits;
291 static int notify_on_release(const struct cgroup *cgrp)
293 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
296 static int clone_children(const struct cgroup *cgrp)
298 return test_bit(CGRP_CLONE_CHILDREN, &cgrp->flags);
302 * for_each_subsys() allows you to iterate on each subsystem attached to
303 * an active hierarchy
305 #define for_each_subsys(_root, _ss) \
306 list_for_each_entry(_ss, &_root->subsys_list, sibling)
308 /* for_each_active_root() allows you to iterate across the active hierarchies */
309 #define for_each_active_root(_root) \
310 list_for_each_entry(_root, &roots, root_list)
312 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
314 return dentry->d_fsdata;
317 static inline struct cfent *__d_cfe(struct dentry *dentry)
319 return dentry->d_fsdata;
322 static inline struct cftype *__d_cft(struct dentry *dentry)
324 return __d_cfe(dentry)->type;
327 /* the list of cgroups eligible for automatic release. Protected by
328 * release_list_lock */
329 static LIST_HEAD(release_list);
330 static DEFINE_RAW_SPINLOCK(release_list_lock);
331 static void cgroup_release_agent(struct work_struct *work);
332 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
333 static void check_for_release(struct cgroup *cgrp);
335 /* Link structure for associating css_set objects with cgroups */
336 struct cg_cgroup_link {
338 * List running through cg_cgroup_links associated with a
339 * cgroup, anchored on cgroup->css_sets
341 struct list_head cgrp_link_list;
344 * List running through cg_cgroup_links pointing at a
345 * single css_set object, anchored on css_set->cg_links
347 struct list_head cg_link_list;
351 /* The default css_set - used by init and its children prior to any
352 * hierarchies being mounted. It contains a pointer to the root state
353 * for each subsystem. Also used to anchor the list of css_sets. Not
354 * reference-counted, to improve performance when child cgroups
355 * haven't been created.
358 static struct css_set init_css_set;
359 static struct cg_cgroup_link init_css_set_link;
361 static int cgroup_init_idr(struct cgroup_subsys *ss,
362 struct cgroup_subsys_state *css);
364 /* css_set_lock protects the list of css_set objects, and the
365 * chain of tasks off each css_set. Nests outside task->alloc_lock
366 * due to cgroup_iter_start() */
367 static DEFINE_RWLOCK(css_set_lock);
368 static int css_set_count;
371 * hash table for cgroup groups. This improves the performance to find
372 * an existing css_set. This hash doesn't (currently) take into
373 * account cgroups in empty hierarchies.
375 #define CSS_SET_HASH_BITS 7
376 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
377 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
379 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
383 unsigned long tmp = 0UL;
385 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
386 tmp += (unsigned long)css[i];
387 tmp = (tmp >> 16) ^ tmp;
389 index = hash_long(tmp, CSS_SET_HASH_BITS);
391 return &css_set_table[index];
394 /* We don't maintain the lists running through each css_set to its
395 * task until after the first call to cgroup_iter_start(). This
396 * reduces the fork()/exit() overhead for people who have cgroups
397 * compiled into their kernel but not actually in use */
398 static int use_task_css_set_links __read_mostly;
400 static void __put_css_set(struct css_set *cg, int taskexit)
402 struct cg_cgroup_link *link;
403 struct cg_cgroup_link *saved_link;
405 * Ensure that the refcount doesn't hit zero while any readers
406 * can see it. Similar to atomic_dec_and_lock(), but for an
409 if (atomic_add_unless(&cg->refcount, -1, 1))
411 write_lock(&css_set_lock);
412 if (!atomic_dec_and_test(&cg->refcount)) {
413 write_unlock(&css_set_lock);
417 /* This css_set is dead. unlink it and release cgroup refcounts */
418 hlist_del(&cg->hlist);
421 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
423 struct cgroup *cgrp = link->cgrp;
424 list_del(&link->cg_link_list);
425 list_del(&link->cgrp_link_list);
426 if (atomic_dec_and_test(&cgrp->count) &&
427 notify_on_release(cgrp)) {
429 set_bit(CGRP_RELEASABLE, &cgrp->flags);
430 check_for_release(cgrp);
436 write_unlock(&css_set_lock);
437 kfree_rcu(cg, rcu_head);
441 * refcounted get/put for css_set objects
443 static inline void get_css_set(struct css_set *cg)
445 atomic_inc(&cg->refcount);
448 static inline void put_css_set(struct css_set *cg)
450 __put_css_set(cg, 0);
453 static inline void put_css_set_taskexit(struct css_set *cg)
455 __put_css_set(cg, 1);
459 * compare_css_sets - helper function for find_existing_css_set().
460 * @cg: candidate css_set being tested
461 * @old_cg: existing css_set for a task
462 * @new_cgrp: cgroup that's being entered by the task
463 * @template: desired set of css pointers in css_set (pre-calculated)
465 * Returns true if "cg" matches "old_cg" except for the hierarchy
466 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
468 static bool compare_css_sets(struct css_set *cg,
469 struct css_set *old_cg,
470 struct cgroup *new_cgrp,
471 struct cgroup_subsys_state *template[])
473 struct list_head *l1, *l2;
475 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
476 /* Not all subsystems matched */
481 * Compare cgroup pointers in order to distinguish between
482 * different cgroups in heirarchies with no subsystems. We
483 * could get by with just this check alone (and skip the
484 * memcmp above) but on most setups the memcmp check will
485 * avoid the need for this more expensive check on almost all
490 l2 = &old_cg->cg_links;
492 struct cg_cgroup_link *cgl1, *cgl2;
493 struct cgroup *cg1, *cg2;
497 /* See if we reached the end - both lists are equal length. */
498 if (l1 == &cg->cg_links) {
499 BUG_ON(l2 != &old_cg->cg_links);
502 BUG_ON(l2 == &old_cg->cg_links);
504 /* Locate the cgroups associated with these links. */
505 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
506 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
509 /* Hierarchies should be linked in the same order. */
510 BUG_ON(cg1->root != cg2->root);
513 * If this hierarchy is the hierarchy of the cgroup
514 * that's changing, then we need to check that this
515 * css_set points to the new cgroup; if it's any other
516 * hierarchy, then this css_set should point to the
517 * same cgroup as the old css_set.
519 if (cg1->root == new_cgrp->root) {
531 * find_existing_css_set() is a helper for
532 * find_css_set(), and checks to see whether an existing
533 * css_set is suitable.
535 * oldcg: the cgroup group that we're using before the cgroup
538 * cgrp: the cgroup that we're moving into
540 * template: location in which to build the desired set of subsystem
541 * state objects for the new cgroup group
543 static struct css_set *find_existing_css_set(
544 struct css_set *oldcg,
546 struct cgroup_subsys_state *template[])
549 struct cgroupfs_root *root = cgrp->root;
550 struct hlist_head *hhead;
551 struct hlist_node *node;
555 * Build the set of subsystem state objects that we want to see in the
556 * new css_set. while subsystems can change globally, the entries here
557 * won't change, so no need for locking.
559 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
560 if (root->subsys_mask & (1UL << i)) {
561 /* Subsystem is in this hierarchy. So we want
562 * the subsystem state from the new
564 template[i] = cgrp->subsys[i];
566 /* Subsystem is not in this hierarchy, so we
567 * don't want to change the subsystem state */
568 template[i] = oldcg->subsys[i];
572 hhead = css_set_hash(template);
573 hlist_for_each_entry(cg, node, hhead, hlist) {
574 if (!compare_css_sets(cg, oldcg, cgrp, template))
577 /* This css_set matches what we need */
581 /* No existing cgroup group matched */
585 static void free_cg_links(struct list_head *tmp)
587 struct cg_cgroup_link *link;
588 struct cg_cgroup_link *saved_link;
590 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
591 list_del(&link->cgrp_link_list);
597 * allocate_cg_links() allocates "count" cg_cgroup_link structures
598 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
599 * success or a negative error
601 static int allocate_cg_links(int count, struct list_head *tmp)
603 struct cg_cgroup_link *link;
606 for (i = 0; i < count; i++) {
607 link = kmalloc(sizeof(*link), GFP_KERNEL);
612 list_add(&link->cgrp_link_list, tmp);
618 * link_css_set - a helper function to link a css_set to a cgroup
619 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
620 * @cg: the css_set to be linked
621 * @cgrp: the destination cgroup
623 static void link_css_set(struct list_head *tmp_cg_links,
624 struct css_set *cg, struct cgroup *cgrp)
626 struct cg_cgroup_link *link;
628 BUG_ON(list_empty(tmp_cg_links));
629 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
633 atomic_inc(&cgrp->count);
634 list_move(&link->cgrp_link_list, &cgrp->css_sets);
636 * Always add links to the tail of the list so that the list
637 * is sorted by order of hierarchy creation
639 list_add_tail(&link->cg_link_list, &cg->cg_links);
643 * find_css_set() takes an existing cgroup group and a
644 * cgroup object, and returns a css_set object that's
645 * equivalent to the old group, but with the given cgroup
646 * substituted into the appropriate hierarchy. Must be called with
649 static struct css_set *find_css_set(
650 struct css_set *oldcg, struct cgroup *cgrp)
653 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
655 struct list_head tmp_cg_links;
657 struct hlist_head *hhead;
658 struct cg_cgroup_link *link;
660 /* First see if we already have a cgroup group that matches
662 read_lock(&css_set_lock);
663 res = find_existing_css_set(oldcg, cgrp, template);
666 read_unlock(&css_set_lock);
671 res = kmalloc(sizeof(*res), GFP_KERNEL);
675 /* Allocate all the cg_cgroup_link objects that we'll need */
676 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
681 atomic_set(&res->refcount, 1);
682 INIT_LIST_HEAD(&res->cg_links);
683 INIT_LIST_HEAD(&res->tasks);
684 INIT_HLIST_NODE(&res->hlist);
686 /* Copy the set of subsystem state objects generated in
687 * find_existing_css_set() */
688 memcpy(res->subsys, template, sizeof(res->subsys));
690 write_lock(&css_set_lock);
691 /* Add reference counts and links from the new css_set. */
692 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
693 struct cgroup *c = link->cgrp;
694 if (c->root == cgrp->root)
696 link_css_set(&tmp_cg_links, res, c);
699 BUG_ON(!list_empty(&tmp_cg_links));
703 /* Add this cgroup group to the hash table */
704 hhead = css_set_hash(res->subsys);
705 hlist_add_head(&res->hlist, hhead);
707 write_unlock(&css_set_lock);
713 * Return the cgroup for "task" from the given hierarchy. Must be
714 * called with cgroup_mutex held.
716 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
717 struct cgroupfs_root *root)
720 struct cgroup *res = NULL;
722 BUG_ON(!mutex_is_locked(&cgroup_mutex));
723 read_lock(&css_set_lock);
725 * No need to lock the task - since we hold cgroup_mutex the
726 * task can't change groups, so the only thing that can happen
727 * is that it exits and its css is set back to init_css_set.
730 if (css == &init_css_set) {
731 res = &root->top_cgroup;
733 struct cg_cgroup_link *link;
734 list_for_each_entry(link, &css->cg_links, cg_link_list) {
735 struct cgroup *c = link->cgrp;
736 if (c->root == root) {
742 read_unlock(&css_set_lock);
748 * There is one global cgroup mutex. We also require taking
749 * task_lock() when dereferencing a task's cgroup subsys pointers.
750 * See "The task_lock() exception", at the end of this comment.
752 * A task must hold cgroup_mutex to modify cgroups.
754 * Any task can increment and decrement the count field without lock.
755 * So in general, code holding cgroup_mutex can't rely on the count
756 * field not changing. However, if the count goes to zero, then only
757 * cgroup_attach_task() can increment it again. Because a count of zero
758 * means that no tasks are currently attached, therefore there is no
759 * way a task attached to that cgroup can fork (the other way to
760 * increment the count). So code holding cgroup_mutex can safely
761 * assume that if the count is zero, it will stay zero. Similarly, if
762 * a task holds cgroup_mutex on a cgroup with zero count, it
763 * knows that the cgroup won't be removed, as cgroup_rmdir()
766 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
767 * (usually) take cgroup_mutex. These are the two most performance
768 * critical pieces of code here. The exception occurs on cgroup_exit(),
769 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
770 * is taken, and if the cgroup count is zero, a usermode call made
771 * to the release agent with the name of the cgroup (path relative to
772 * the root of cgroup file system) as the argument.
774 * A cgroup can only be deleted if both its 'count' of using tasks
775 * is zero, and its list of 'children' cgroups is empty. Since all
776 * tasks in the system use _some_ cgroup, and since there is always at
777 * least one task in the system (init, pid == 1), therefore, top_cgroup
778 * always has either children cgroups and/or using tasks. So we don't
779 * need a special hack to ensure that top_cgroup cannot be deleted.
781 * The task_lock() exception
783 * The need for this exception arises from the action of
784 * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
785 * another. It does so using cgroup_mutex, however there are
786 * several performance critical places that need to reference
787 * task->cgroup without the expense of grabbing a system global
788 * mutex. Therefore except as noted below, when dereferencing or, as
789 * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
790 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
791 * the task_struct routinely used for such matters.
793 * P.S. One more locking exception. RCU is used to guard the
794 * update of a tasks cgroup pointer by cgroup_attach_task()
798 * cgroup_lock - lock out any changes to cgroup structures
801 void cgroup_lock(void)
803 mutex_lock(&cgroup_mutex);
805 EXPORT_SYMBOL_GPL(cgroup_lock);
808 * cgroup_unlock - release lock on cgroup changes
810 * Undo the lock taken in a previous cgroup_lock() call.
812 void cgroup_unlock(void)
814 mutex_unlock(&cgroup_mutex);
816 EXPORT_SYMBOL_GPL(cgroup_unlock);
819 * A couple of forward declarations required, due to cyclic reference loop:
820 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
821 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
825 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
826 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
827 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
828 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
829 unsigned long subsys_mask);
830 static const struct inode_operations cgroup_dir_inode_operations;
831 static const struct file_operations proc_cgroupstats_operations;
833 static struct backing_dev_info cgroup_backing_dev_info = {
835 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
838 static int alloc_css_id(struct cgroup_subsys *ss,
839 struct cgroup *parent, struct cgroup *child);
841 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
843 struct inode *inode = new_inode(sb);
846 inode->i_ino = get_next_ino();
847 inode->i_mode = mode;
848 inode->i_uid = current_fsuid();
849 inode->i_gid = current_fsgid();
850 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
851 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
857 * Call subsys's pre_destroy handler.
858 * This is called before css refcnt check.
860 static int cgroup_call_pre_destroy(struct cgroup *cgrp)
862 struct cgroup_subsys *ss;
865 for_each_subsys(cgrp->root, ss) {
866 if (!ss->pre_destroy)
869 ret = ss->pre_destroy(cgrp);
871 /* ->pre_destroy() failure is being deprecated */
872 WARN_ON_ONCE(!ss->__DEPRECATED_clear_css_refs);
880 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
882 /* is dentry a directory ? if so, kfree() associated cgroup */
883 if (S_ISDIR(inode->i_mode)) {
884 struct cgroup *cgrp = dentry->d_fsdata;
885 struct cgroup_subsys *ss;
886 BUG_ON(!(cgroup_is_removed(cgrp)));
887 /* It's possible for external users to be holding css
888 * reference counts on a cgroup; css_put() needs to
889 * be able to access the cgroup after decrementing
890 * the reference count in order to know if it needs to
891 * queue the cgroup to be handled by the release
895 mutex_lock(&cgroup_mutex);
897 * Release the subsystem state objects.
899 for_each_subsys(cgrp->root, ss)
902 cgrp->root->number_of_cgroups--;
903 mutex_unlock(&cgroup_mutex);
906 * Drop the active superblock reference that we took when we
909 deactivate_super(cgrp->root->sb);
912 * if we're getting rid of the cgroup, refcount should ensure
913 * that there are no pidlists left.
915 BUG_ON(!list_empty(&cgrp->pidlists));
917 simple_xattrs_free(&cgrp->xattrs);
919 kfree_rcu(cgrp, rcu_head);
921 struct cfent *cfe = __d_cfe(dentry);
922 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
923 struct cftype *cft = cfe->type;
925 WARN_ONCE(!list_empty(&cfe->node) &&
926 cgrp != &cgrp->root->top_cgroup,
927 "cfe still linked for %s\n", cfe->type->name);
929 simple_xattrs_free(&cft->xattrs);
934 static int cgroup_delete(const struct dentry *d)
939 static void remove_dir(struct dentry *d)
941 struct dentry *parent = dget(d->d_parent);
944 simple_rmdir(parent->d_inode, d);
948 static int cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
952 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
953 lockdep_assert_held(&cgroup_mutex);
955 list_for_each_entry(cfe, &cgrp->files, node) {
956 struct dentry *d = cfe->dentry;
958 if (cft && cfe->type != cft)
963 simple_unlink(cgrp->dentry->d_inode, d);
964 list_del_init(&cfe->node);
973 * cgroup_clear_directory - selective removal of base and subsystem files
974 * @dir: directory containing the files
975 * @base_files: true if the base files should be removed
976 * @subsys_mask: mask of the subsystem ids whose files should be removed
978 static void cgroup_clear_directory(struct dentry *dir, bool base_files,
979 unsigned long subsys_mask)
981 struct cgroup *cgrp = __d_cgrp(dir);
982 struct cgroup_subsys *ss;
984 for_each_subsys(cgrp->root, ss) {
985 struct cftype_set *set;
986 if (!test_bit(ss->subsys_id, &subsys_mask))
988 list_for_each_entry(set, &ss->cftsets, node)
989 cgroup_rm_file(cgrp, set->cfts);
992 while (!list_empty(&cgrp->files))
993 cgroup_rm_file(cgrp, NULL);
998 * NOTE : the dentry must have been dget()'ed
1000 static void cgroup_d_remove_dir(struct dentry *dentry)
1002 struct dentry *parent;
1003 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1005 cgroup_clear_directory(dentry, true, root->subsys_mask);
1007 parent = dentry->d_parent;
1008 spin_lock(&parent->d_lock);
1009 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
1010 list_del_init(&dentry->d_u.d_child);
1011 spin_unlock(&dentry->d_lock);
1012 spin_unlock(&parent->d_lock);
1017 * A queue for waiters to do rmdir() cgroup. A tasks will sleep when
1018 * cgroup->count == 0 && list_empty(&cgroup->children) && subsys has some
1019 * reference to css->refcnt. In general, this refcnt is expected to goes down
1022 * CGRP_WAIT_ON_RMDIR flag is set under cgroup's inode->i_mutex;
1024 static DECLARE_WAIT_QUEUE_HEAD(cgroup_rmdir_waitq);
1026 static void cgroup_wakeup_rmdir_waiter(struct cgroup *cgrp)
1028 if (unlikely(test_and_clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags)))
1029 wake_up_all(&cgroup_rmdir_waitq);
1032 void cgroup_exclude_rmdir(struct cgroup_subsys_state *css)
1037 void cgroup_release_and_wakeup_rmdir(struct cgroup_subsys_state *css)
1039 cgroup_wakeup_rmdir_waiter(css->cgroup);
1044 * Call with cgroup_mutex held. Drops reference counts on modules, including
1045 * any duplicate ones that parse_cgroupfs_options took. If this function
1046 * returns an error, no reference counts are touched.
1048 static int rebind_subsystems(struct cgroupfs_root *root,
1049 unsigned long final_subsys_mask)
1051 unsigned long added_mask, removed_mask;
1052 struct cgroup *cgrp = &root->top_cgroup;
1055 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1056 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1058 removed_mask = root->actual_subsys_mask & ~final_subsys_mask;
1059 added_mask = final_subsys_mask & ~root->actual_subsys_mask;
1060 /* Check that any added subsystems are currently free */
1061 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1062 unsigned long bit = 1UL << i;
1063 struct cgroup_subsys *ss = subsys[i];
1064 if (!(bit & added_mask))
1067 * Nobody should tell us to do a subsys that doesn't exist:
1068 * parse_cgroupfs_options should catch that case and refcounts
1069 * ensure that subsystems won't disappear once selected.
1072 if (ss->root != &rootnode) {
1073 /* Subsystem isn't free */
1078 /* Currently we don't handle adding/removing subsystems when
1079 * any child cgroups exist. This is theoretically supportable
1080 * but involves complex error handling, so it's being left until
1082 if (root->number_of_cgroups > 1)
1085 /* Process each subsystem */
1086 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1087 struct cgroup_subsys *ss = subsys[i];
1088 unsigned long bit = 1UL << i;
1089 if (bit & added_mask) {
1090 /* We're binding this subsystem to this hierarchy */
1092 BUG_ON(cgrp->subsys[i]);
1093 BUG_ON(!dummytop->subsys[i]);
1094 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
1095 cgrp->subsys[i] = dummytop->subsys[i];
1096 cgrp->subsys[i]->cgroup = cgrp;
1097 list_move(&ss->sibling, &root->subsys_list);
1101 /* refcount was already taken, and we're keeping it */
1102 } else if (bit & removed_mask) {
1103 /* We're removing this subsystem */
1105 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1106 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1109 dummytop->subsys[i]->cgroup = dummytop;
1110 cgrp->subsys[i] = NULL;
1111 subsys[i]->root = &rootnode;
1112 list_move(&ss->sibling, &rootnode.subsys_list);
1113 /* subsystem is now free - drop reference on module */
1114 module_put(ss->module);
1115 } else if (bit & final_subsys_mask) {
1116 /* Subsystem state should already exist */
1118 BUG_ON(!cgrp->subsys[i]);
1120 * a refcount was taken, but we already had one, so
1121 * drop the extra reference.
1123 module_put(ss->module);
1124 #ifdef CONFIG_MODULE_UNLOAD
1125 BUG_ON(ss->module && !module_refcount(ss->module));
1128 /* Subsystem state shouldn't exist */
1129 BUG_ON(cgrp->subsys[i]);
1132 root->subsys_mask = root->actual_subsys_mask = final_subsys_mask;
1138 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1140 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1141 struct cgroup_subsys *ss;
1143 mutex_lock(&cgroup_root_mutex);
1144 for_each_subsys(root, ss)
1145 seq_printf(seq, ",%s", ss->name);
1146 if (test_bit(ROOT_NOPREFIX, &root->flags))
1147 seq_puts(seq, ",noprefix");
1148 if (test_bit(ROOT_XATTR, &root->flags))
1149 seq_puts(seq, ",xattr");
1150 if (strlen(root->release_agent_path))
1151 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1152 if (clone_children(&root->top_cgroup))
1153 seq_puts(seq, ",clone_children");
1154 if (strlen(root->name))
1155 seq_printf(seq, ",name=%s", root->name);
1156 mutex_unlock(&cgroup_root_mutex);
1160 struct cgroup_sb_opts {
1161 unsigned long subsys_mask;
1162 unsigned long flags;
1163 char *release_agent;
1164 bool clone_children;
1166 /* User explicitly requested empty subsystem */
1169 struct cgroupfs_root *new_root;
1174 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1175 * with cgroup_mutex held to protect the subsys[] array. This function takes
1176 * refcounts on subsystems to be used, unless it returns error, in which case
1177 * no refcounts are taken.
1179 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1181 char *token, *o = data;
1182 bool all_ss = false, one_ss = false;
1183 unsigned long mask = (unsigned long)-1;
1185 bool module_pin_failed = false;
1187 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1189 #ifdef CONFIG_CPUSETS
1190 mask = ~(1UL << cpuset_subsys_id);
1193 memset(opts, 0, sizeof(*opts));
1195 while ((token = strsep(&o, ",")) != NULL) {
1198 if (!strcmp(token, "none")) {
1199 /* Explicitly have no subsystems */
1203 if (!strcmp(token, "all")) {
1204 /* Mutually exclusive option 'all' + subsystem name */
1210 if (!strcmp(token, "noprefix")) {
1211 set_bit(ROOT_NOPREFIX, &opts->flags);
1214 if (!strcmp(token, "clone_children")) {
1215 opts->clone_children = true;
1218 if (!strcmp(token, "xattr")) {
1219 set_bit(ROOT_XATTR, &opts->flags);
1222 if (!strncmp(token, "release_agent=", 14)) {
1223 /* Specifying two release agents is forbidden */
1224 if (opts->release_agent)
1226 opts->release_agent =
1227 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1228 if (!opts->release_agent)
1232 if (!strncmp(token, "name=", 5)) {
1233 const char *name = token + 5;
1234 /* Can't specify an empty name */
1237 /* Must match [\w.-]+ */
1238 for (i = 0; i < strlen(name); i++) {
1242 if ((c == '.') || (c == '-') || (c == '_'))
1246 /* Specifying two names is forbidden */
1249 opts->name = kstrndup(name,
1250 MAX_CGROUP_ROOT_NAMELEN - 1,
1258 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1259 struct cgroup_subsys *ss = subsys[i];
1262 if (strcmp(token, ss->name))
1267 /* Mutually exclusive option 'all' + subsystem name */
1270 set_bit(i, &opts->subsys_mask);
1275 if (i == CGROUP_SUBSYS_COUNT)
1280 * If the 'all' option was specified select all the subsystems,
1281 * otherwise if 'none', 'name=' and a subsystem name options
1282 * were not specified, let's default to 'all'
1284 if (all_ss || (!one_ss && !opts->none && !opts->name)) {
1285 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1286 struct cgroup_subsys *ss = subsys[i];
1291 set_bit(i, &opts->subsys_mask);
1295 /* Consistency checks */
1298 * Option noprefix was introduced just for backward compatibility
1299 * with the old cpuset, so we allow noprefix only if mounting just
1300 * the cpuset subsystem.
1302 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1303 (opts->subsys_mask & mask))
1307 /* Can't specify "none" and some subsystems */
1308 if (opts->subsys_mask && opts->none)
1312 * We either have to specify by name or by subsystems. (So all
1313 * empty hierarchies must have a name).
1315 if (!opts->subsys_mask && !opts->name)
1319 * Grab references on all the modules we'll need, so the subsystems
1320 * don't dance around before rebind_subsystems attaches them. This may
1321 * take duplicate reference counts on a subsystem that's already used,
1322 * but rebind_subsystems handles this case.
1324 for (i = CGROUP_BUILTIN_SUBSYS_COUNT; i < CGROUP_SUBSYS_COUNT; i++) {
1325 unsigned long bit = 1UL << i;
1327 if (!(bit & opts->subsys_mask))
1329 if (!try_module_get(subsys[i]->module)) {
1330 module_pin_failed = true;
1334 if (module_pin_failed) {
1336 * oops, one of the modules was going away. this means that we
1337 * raced with a module_delete call, and to the user this is
1338 * essentially a "subsystem doesn't exist" case.
1340 for (i--; i >= CGROUP_BUILTIN_SUBSYS_COUNT; i--) {
1341 /* drop refcounts only on the ones we took */
1342 unsigned long bit = 1UL << i;
1344 if (!(bit & opts->subsys_mask))
1346 module_put(subsys[i]->module);
1354 static void drop_parsed_module_refcounts(unsigned long subsys_mask)
1357 for (i = CGROUP_BUILTIN_SUBSYS_COUNT; i < CGROUP_SUBSYS_COUNT; i++) {
1358 unsigned long bit = 1UL << i;
1360 if (!(bit & subsys_mask))
1362 module_put(subsys[i]->module);
1366 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1369 struct cgroupfs_root *root = sb->s_fs_info;
1370 struct cgroup *cgrp = &root->top_cgroup;
1371 struct cgroup_sb_opts opts;
1372 unsigned long added_mask, removed_mask;
1374 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1375 mutex_lock(&cgroup_mutex);
1376 mutex_lock(&cgroup_root_mutex);
1378 /* See what subsystems are wanted */
1379 ret = parse_cgroupfs_options(data, &opts);
1383 /* See feature-removal-schedule.txt */
1384 if (opts.subsys_mask != root->actual_subsys_mask || opts.release_agent)
1385 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1386 task_tgid_nr(current), current->comm);
1388 added_mask = opts.subsys_mask & ~root->subsys_mask;
1389 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1391 /* Don't allow flags or name to change at remount */
1392 if (opts.flags != root->flags ||
1393 (opts.name && strcmp(opts.name, root->name))) {
1395 drop_parsed_module_refcounts(opts.subsys_mask);
1399 ret = rebind_subsystems(root, opts.subsys_mask);
1401 drop_parsed_module_refcounts(opts.subsys_mask);
1405 /* clear out any existing files and repopulate subsystem files */
1406 cgroup_clear_directory(cgrp->dentry, false, removed_mask);
1407 /* re-populate subsystem files */
1408 cgroup_populate_dir(cgrp, false, added_mask);
1410 if (opts.release_agent)
1411 strcpy(root->release_agent_path, opts.release_agent);
1413 kfree(opts.release_agent);
1415 mutex_unlock(&cgroup_root_mutex);
1416 mutex_unlock(&cgroup_mutex);
1417 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1421 static const struct super_operations cgroup_ops = {
1422 .statfs = simple_statfs,
1423 .drop_inode = generic_delete_inode,
1424 .show_options = cgroup_show_options,
1425 .remount_fs = cgroup_remount,
1428 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1430 INIT_LIST_HEAD(&cgrp->sibling);
1431 INIT_LIST_HEAD(&cgrp->children);
1432 INIT_LIST_HEAD(&cgrp->files);
1433 INIT_LIST_HEAD(&cgrp->css_sets);
1434 INIT_LIST_HEAD(&cgrp->release_list);
1435 INIT_LIST_HEAD(&cgrp->pidlists);
1436 mutex_init(&cgrp->pidlist_mutex);
1437 INIT_LIST_HEAD(&cgrp->event_list);
1438 spin_lock_init(&cgrp->event_list_lock);
1439 simple_xattrs_init(&cgrp->xattrs);
1442 static void init_cgroup_root(struct cgroupfs_root *root)
1444 struct cgroup *cgrp = &root->top_cgroup;
1446 INIT_LIST_HEAD(&root->subsys_list);
1447 INIT_LIST_HEAD(&root->root_list);
1448 INIT_LIST_HEAD(&root->allcg_list);
1449 root->number_of_cgroups = 1;
1451 cgrp->top_cgroup = cgrp;
1452 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
1453 init_cgroup_housekeeping(cgrp);
1456 static bool init_root_id(struct cgroupfs_root *root)
1461 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1463 spin_lock(&hierarchy_id_lock);
1464 /* Try to allocate the next unused ID */
1465 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1466 &root->hierarchy_id);
1468 /* Try again starting from 0 */
1469 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1471 next_hierarchy_id = root->hierarchy_id + 1;
1472 } else if (ret != -EAGAIN) {
1473 /* Can only get here if the 31-bit IDR is full ... */
1476 spin_unlock(&hierarchy_id_lock);
1481 static int cgroup_test_super(struct super_block *sb, void *data)
1483 struct cgroup_sb_opts *opts = data;
1484 struct cgroupfs_root *root = sb->s_fs_info;
1486 /* If we asked for a name then it must match */
1487 if (opts->name && strcmp(opts->name, root->name))
1491 * If we asked for subsystems (or explicitly for no
1492 * subsystems) then they must match
1494 if ((opts->subsys_mask || opts->none)
1495 && (opts->subsys_mask != root->subsys_mask))
1501 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1503 struct cgroupfs_root *root;
1505 if (!opts->subsys_mask && !opts->none)
1508 root = kzalloc(sizeof(*root), GFP_KERNEL);
1510 return ERR_PTR(-ENOMEM);
1512 if (!init_root_id(root)) {
1514 return ERR_PTR(-ENOMEM);
1516 init_cgroup_root(root);
1518 root->subsys_mask = opts->subsys_mask;
1519 root->flags = opts->flags;
1520 if (opts->release_agent)
1521 strcpy(root->release_agent_path, opts->release_agent);
1523 strcpy(root->name, opts->name);
1524 if (opts->clone_children)
1525 set_bit(CGRP_CLONE_CHILDREN, &root->top_cgroup.flags);
1529 static void cgroup_drop_root(struct cgroupfs_root *root)
1534 BUG_ON(!root->hierarchy_id);
1535 spin_lock(&hierarchy_id_lock);
1536 ida_remove(&hierarchy_ida, root->hierarchy_id);
1537 spin_unlock(&hierarchy_id_lock);
1541 static int cgroup_set_super(struct super_block *sb, void *data)
1544 struct cgroup_sb_opts *opts = data;
1546 /* If we don't have a new root, we can't set up a new sb */
1547 if (!opts->new_root)
1550 BUG_ON(!opts->subsys_mask && !opts->none);
1552 ret = set_anon_super(sb, NULL);
1556 sb->s_fs_info = opts->new_root;
1557 opts->new_root->sb = sb;
1559 sb->s_blocksize = PAGE_CACHE_SIZE;
1560 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1561 sb->s_magic = CGROUP_SUPER_MAGIC;
1562 sb->s_op = &cgroup_ops;
1567 static int cgroup_get_rootdir(struct super_block *sb)
1569 static const struct dentry_operations cgroup_dops = {
1570 .d_iput = cgroup_diput,
1571 .d_delete = cgroup_delete,
1574 struct inode *inode =
1575 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1580 inode->i_fop = &simple_dir_operations;
1581 inode->i_op = &cgroup_dir_inode_operations;
1582 /* directories start off with i_nlink == 2 (for "." entry) */
1584 sb->s_root = d_make_root(inode);
1587 /* for everything else we want ->d_op set */
1588 sb->s_d_op = &cgroup_dops;
1592 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1593 int flags, const char *unused_dev_name,
1596 struct cgroup_sb_opts opts;
1597 struct cgroupfs_root *root;
1599 struct super_block *sb;
1600 struct cgroupfs_root *new_root;
1601 struct inode *inode;
1603 /* First find the desired set of subsystems */
1604 mutex_lock(&cgroup_mutex);
1605 ret = parse_cgroupfs_options(data, &opts);
1606 mutex_unlock(&cgroup_mutex);
1611 * Allocate a new cgroup root. We may not need it if we're
1612 * reusing an existing hierarchy.
1614 new_root = cgroup_root_from_opts(&opts);
1615 if (IS_ERR(new_root)) {
1616 ret = PTR_ERR(new_root);
1619 opts.new_root = new_root;
1621 /* Locate an existing or new sb for this hierarchy */
1622 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1625 cgroup_drop_root(opts.new_root);
1629 root = sb->s_fs_info;
1631 if (root == opts.new_root) {
1632 /* We used the new root structure, so this is a new hierarchy */
1633 struct list_head tmp_cg_links;
1634 struct cgroup *root_cgrp = &root->top_cgroup;
1635 struct cgroupfs_root *existing_root;
1636 const struct cred *cred;
1639 BUG_ON(sb->s_root != NULL);
1641 ret = cgroup_get_rootdir(sb);
1643 goto drop_new_super;
1644 inode = sb->s_root->d_inode;
1646 mutex_lock(&inode->i_mutex);
1647 mutex_lock(&cgroup_mutex);
1648 mutex_lock(&cgroup_root_mutex);
1650 /* Check for name clashes with existing mounts */
1652 if (strlen(root->name))
1653 for_each_active_root(existing_root)
1654 if (!strcmp(existing_root->name, root->name))
1658 * We're accessing css_set_count without locking
1659 * css_set_lock here, but that's OK - it can only be
1660 * increased by someone holding cgroup_lock, and
1661 * that's us. The worst that can happen is that we
1662 * have some link structures left over
1664 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1668 ret = rebind_subsystems(root, root->subsys_mask);
1669 if (ret == -EBUSY) {
1670 free_cg_links(&tmp_cg_links);
1674 * There must be no failure case after here, since rebinding
1675 * takes care of subsystems' refcounts, which are explicitly
1676 * dropped in the failure exit path.
1679 /* EBUSY should be the only error here */
1682 list_add(&root->root_list, &roots);
1685 sb->s_root->d_fsdata = root_cgrp;
1686 root->top_cgroup.dentry = sb->s_root;
1688 /* Link the top cgroup in this hierarchy into all
1689 * the css_set objects */
1690 write_lock(&css_set_lock);
1691 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1692 struct hlist_head *hhead = &css_set_table[i];
1693 struct hlist_node *node;
1696 hlist_for_each_entry(cg, node, hhead, hlist)
1697 link_css_set(&tmp_cg_links, cg, root_cgrp);
1699 write_unlock(&css_set_lock);
1701 free_cg_links(&tmp_cg_links);
1703 BUG_ON(!list_empty(&root_cgrp->sibling));
1704 BUG_ON(!list_empty(&root_cgrp->children));
1705 BUG_ON(root->number_of_cgroups != 1);
1707 cred = override_creds(&init_cred);
1708 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1710 mutex_unlock(&cgroup_root_mutex);
1711 mutex_unlock(&cgroup_mutex);
1712 mutex_unlock(&inode->i_mutex);
1715 * We re-used an existing hierarchy - the new root (if
1716 * any) is not needed
1718 cgroup_drop_root(opts.new_root);
1719 /* no subsys rebinding, so refcounts don't change */
1720 drop_parsed_module_refcounts(opts.subsys_mask);
1723 kfree(opts.release_agent);
1725 return dget(sb->s_root);
1728 mutex_unlock(&cgroup_root_mutex);
1729 mutex_unlock(&cgroup_mutex);
1730 mutex_unlock(&inode->i_mutex);
1732 deactivate_locked_super(sb);
1734 drop_parsed_module_refcounts(opts.subsys_mask);
1736 kfree(opts.release_agent);
1738 return ERR_PTR(ret);
1741 static void cgroup_kill_sb(struct super_block *sb) {
1742 struct cgroupfs_root *root = sb->s_fs_info;
1743 struct cgroup *cgrp = &root->top_cgroup;
1745 struct cg_cgroup_link *link;
1746 struct cg_cgroup_link *saved_link;
1750 BUG_ON(root->number_of_cgroups != 1);
1751 BUG_ON(!list_empty(&cgrp->children));
1752 BUG_ON(!list_empty(&cgrp->sibling));
1754 mutex_lock(&cgroup_mutex);
1755 mutex_lock(&cgroup_root_mutex);
1757 /* Rebind all subsystems back to the default hierarchy */
1758 ret = rebind_subsystems(root, 0);
1759 /* Shouldn't be able to fail ... */
1763 * Release all the links from css_sets to this hierarchy's
1766 write_lock(&css_set_lock);
1768 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1770 list_del(&link->cg_link_list);
1771 list_del(&link->cgrp_link_list);
1774 write_unlock(&css_set_lock);
1776 if (!list_empty(&root->root_list)) {
1777 list_del(&root->root_list);
1781 mutex_unlock(&cgroup_root_mutex);
1782 mutex_unlock(&cgroup_mutex);
1784 simple_xattrs_free(&cgrp->xattrs);
1786 kill_litter_super(sb);
1787 cgroup_drop_root(root);
1790 static struct file_system_type cgroup_fs_type = {
1792 .mount = cgroup_mount,
1793 .kill_sb = cgroup_kill_sb,
1796 static struct kobject *cgroup_kobj;
1799 * cgroup_path - generate the path of a cgroup
1800 * @cgrp: the cgroup in question
1801 * @buf: the buffer to write the path into
1802 * @buflen: the length of the buffer
1804 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1805 * reference. Writes path of cgroup into buf. Returns 0 on success,
1808 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1811 struct dentry *dentry = rcu_dereference_check(cgrp->dentry,
1812 cgroup_lock_is_held());
1814 if (!dentry || cgrp == dummytop) {
1816 * Inactive subsystems have no dentry for their root
1823 start = buf + buflen;
1827 int len = dentry->d_name.len;
1829 if ((start -= len) < buf)
1830 return -ENAMETOOLONG;
1831 memcpy(start, dentry->d_name.name, len);
1832 cgrp = cgrp->parent;
1836 dentry = rcu_dereference_check(cgrp->dentry,
1837 cgroup_lock_is_held());
1841 return -ENAMETOOLONG;
1844 memmove(buf, start, buf + buflen - start);
1847 EXPORT_SYMBOL_GPL(cgroup_path);
1850 * Control Group taskset
1852 struct task_and_cgroup {
1853 struct task_struct *task;
1854 struct cgroup *cgrp;
1858 struct cgroup_taskset {
1859 struct task_and_cgroup single;
1860 struct flex_array *tc_array;
1863 struct cgroup *cur_cgrp;
1867 * cgroup_taskset_first - reset taskset and return the first task
1868 * @tset: taskset of interest
1870 * @tset iteration is initialized and the first task is returned.
1872 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1874 if (tset->tc_array) {
1876 return cgroup_taskset_next(tset);
1878 tset->cur_cgrp = tset->single.cgrp;
1879 return tset->single.task;
1882 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1885 * cgroup_taskset_next - iterate to the next task in taskset
1886 * @tset: taskset of interest
1888 * Return the next task in @tset. Iteration must have been initialized
1889 * with cgroup_taskset_first().
1891 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1893 struct task_and_cgroup *tc;
1895 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1898 tc = flex_array_get(tset->tc_array, tset->idx++);
1899 tset->cur_cgrp = tc->cgrp;
1902 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1905 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1906 * @tset: taskset of interest
1908 * Return the cgroup for the current (last returned) task of @tset. This
1909 * function must be preceded by either cgroup_taskset_first() or
1910 * cgroup_taskset_next().
1912 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1914 return tset->cur_cgrp;
1916 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1919 * cgroup_taskset_size - return the number of tasks in taskset
1920 * @tset: taskset of interest
1922 int cgroup_taskset_size(struct cgroup_taskset *tset)
1924 return tset->tc_array ? tset->tc_array_len : 1;
1926 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1930 * cgroup_task_migrate - move a task from one cgroup to another.
1932 * 'guarantee' is set if the caller promises that a new css_set for the task
1933 * will already exist. If not set, this function might sleep, and can fail with
1934 * -ENOMEM. Must be called with cgroup_mutex and threadgroup locked.
1936 static void cgroup_task_migrate(struct cgroup *cgrp, struct cgroup *oldcgrp,
1937 struct task_struct *tsk, struct css_set *newcg)
1939 struct css_set *oldcg;
1942 * We are synchronized through threadgroup_lock() against PF_EXITING
1943 * setting such that we can't race against cgroup_exit() changing the
1944 * css_set to init_css_set and dropping the old one.
1946 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1947 oldcg = tsk->cgroups;
1950 rcu_assign_pointer(tsk->cgroups, newcg);
1953 /* Update the css_set linked lists if we're using them */
1954 write_lock(&css_set_lock);
1955 if (!list_empty(&tsk->cg_list))
1956 list_move(&tsk->cg_list, &newcg->tasks);
1957 write_unlock(&css_set_lock);
1960 * We just gained a reference on oldcg by taking it from the task. As
1961 * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1962 * it here; it will be freed under RCU.
1966 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1970 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1971 * @cgrp: the cgroup the task is attaching to
1972 * @tsk: the task to be attached
1974 * Call with cgroup_mutex and threadgroup locked. May take task_lock of
1977 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1980 struct cgroup_subsys *ss, *failed_ss = NULL;
1981 struct cgroup *oldcgrp;
1982 struct cgroupfs_root *root = cgrp->root;
1983 struct cgroup_taskset tset = { };
1984 struct css_set *newcg;
1986 /* @tsk either already exited or can't exit until the end */
1987 if (tsk->flags & PF_EXITING)
1990 /* Nothing to do if the task is already in that cgroup */
1991 oldcgrp = task_cgroup_from_root(tsk, root);
1992 if (cgrp == oldcgrp)
1995 tset.single.task = tsk;
1996 tset.single.cgrp = oldcgrp;
1998 for_each_subsys(root, ss) {
1999 if (ss->can_attach) {
2000 retval = ss->can_attach(cgrp, &tset);
2003 * Remember on which subsystem the can_attach()
2004 * failed, so that we only call cancel_attach()
2005 * against the subsystems whose can_attach()
2006 * succeeded. (See below)
2014 newcg = find_css_set(tsk->cgroups, cgrp);
2020 cgroup_task_migrate(cgrp, oldcgrp, tsk, newcg);
2022 for_each_subsys(root, ss) {
2024 ss->attach(cgrp, &tset);
2030 * wake up rmdir() waiter. the rmdir should fail since the cgroup
2031 * is no longer empty.
2033 cgroup_wakeup_rmdir_waiter(cgrp);
2036 for_each_subsys(root, ss) {
2037 if (ss == failed_ss)
2039 * This subsystem was the one that failed the
2040 * can_attach() check earlier, so we don't need
2041 * to call cancel_attach() against it or any
2042 * remaining subsystems.
2045 if (ss->cancel_attach)
2046 ss->cancel_attach(cgrp, &tset);
2053 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2054 * @from: attach to all cgroups of a given task
2055 * @tsk: the task to be attached
2057 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2059 struct cgroupfs_root *root;
2063 for_each_active_root(root) {
2064 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2066 retval = cgroup_attach_task(from_cg, tsk);
2074 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2077 * cgroup_attach_proc - attach all threads in a threadgroup to a cgroup
2078 * @cgrp: the cgroup to attach to
2079 * @leader: the threadgroup leader task_struct of the group to be attached
2081 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
2082 * task_lock of each thread in leader's threadgroup individually in turn.
2084 static int cgroup_attach_proc(struct cgroup *cgrp, struct task_struct *leader)
2086 int retval, i, group_size;
2087 struct cgroup_subsys *ss, *failed_ss = NULL;
2088 /* guaranteed to be initialized later, but the compiler needs this */
2089 struct cgroupfs_root *root = cgrp->root;
2090 /* threadgroup list cursor and array */
2091 struct task_struct *tsk;
2092 struct task_and_cgroup *tc;
2093 struct flex_array *group;
2094 struct cgroup_taskset tset = { };
2097 * step 0: in order to do expensive, possibly blocking operations for
2098 * every thread, we cannot iterate the thread group list, since it needs
2099 * rcu or tasklist locked. instead, build an array of all threads in the
2100 * group - group_rwsem prevents new threads from appearing, and if
2101 * threads exit, this will just be an over-estimate.
2103 group_size = get_nr_threads(leader);
2104 /* flex_array supports very large thread-groups better than kmalloc. */
2105 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2108 /* pre-allocate to guarantee space while iterating in rcu read-side. */
2109 retval = flex_array_prealloc(group, 0, group_size - 1, GFP_KERNEL);
2111 goto out_free_group_list;
2116 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2117 * already PF_EXITING could be freed from underneath us unless we
2118 * take an rcu_read_lock.
2122 struct task_and_cgroup ent;
2124 /* @tsk either already exited or can't exit until the end */
2125 if (tsk->flags & PF_EXITING)
2128 /* as per above, nr_threads may decrease, but not increase. */
2129 BUG_ON(i >= group_size);
2131 ent.cgrp = task_cgroup_from_root(tsk, root);
2132 /* nothing to do if this task is already in the cgroup */
2133 if (ent.cgrp == cgrp)
2136 * saying GFP_ATOMIC has no effect here because we did prealloc
2137 * earlier, but it's good form to communicate our expectations.
2139 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2140 BUG_ON(retval != 0);
2142 } while_each_thread(leader, tsk);
2144 /* remember the number of threads in the array for later. */
2146 tset.tc_array = group;
2147 tset.tc_array_len = group_size;
2149 /* methods shouldn't be called if no task is actually migrating */
2152 goto out_free_group_list;
2155 * step 1: check that we can legitimately attach to the cgroup.
2157 for_each_subsys(root, ss) {
2158 if (ss->can_attach) {
2159 retval = ss->can_attach(cgrp, &tset);
2162 goto out_cancel_attach;
2168 * step 2: make sure css_sets exist for all threads to be migrated.
2169 * we use find_css_set, which allocates a new one if necessary.
2171 for (i = 0; i < group_size; i++) {
2172 tc = flex_array_get(group, i);
2173 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2176 goto out_put_css_set_refs;
2181 * step 3: now that we're guaranteed success wrt the css_sets,
2182 * proceed to move all tasks to the new cgroup. There are no
2183 * failure cases after here, so this is the commit point.
2185 for (i = 0; i < group_size; i++) {
2186 tc = flex_array_get(group, i);
2187 cgroup_task_migrate(cgrp, tc->cgrp, tc->task, tc->cg);
2189 /* nothing is sensitive to fork() after this point. */
2192 * step 4: do subsystem attach callbacks.
2194 for_each_subsys(root, ss) {
2196 ss->attach(cgrp, &tset);
2200 * step 5: success! and cleanup
2203 cgroup_wakeup_rmdir_waiter(cgrp);
2205 out_put_css_set_refs:
2207 for (i = 0; i < group_size; i++) {
2208 tc = flex_array_get(group, i);
2211 put_css_set(tc->cg);
2216 for_each_subsys(root, ss) {
2217 if (ss == failed_ss)
2219 if (ss->cancel_attach)
2220 ss->cancel_attach(cgrp, &tset);
2223 out_free_group_list:
2224 flex_array_free(group);
2229 * Find the task_struct of the task to attach by vpid and pass it along to the
2230 * function to attach either it or all tasks in its threadgroup. Will lock
2231 * cgroup_mutex and threadgroup; may take task_lock of task.
2233 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2235 struct task_struct *tsk;
2236 const struct cred *cred = current_cred(), *tcred;
2239 if (!cgroup_lock_live_group(cgrp))
2245 tsk = find_task_by_vpid(pid);
2249 goto out_unlock_cgroup;
2252 * even if we're attaching all tasks in the thread group, we
2253 * only need to check permissions on one of them.
2255 tcred = __task_cred(tsk);
2256 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2257 !uid_eq(cred->euid, tcred->uid) &&
2258 !uid_eq(cred->euid, tcred->suid)) {
2261 goto out_unlock_cgroup;
2267 tsk = tsk->group_leader;
2270 * Workqueue threads may acquire PF_THREAD_BOUND and become
2271 * trapped in a cpuset, or RT worker may be born in a cgroup
2272 * with no rt_runtime allocated. Just say no.
2274 if (tsk == kthreadd_task || (tsk->flags & PF_THREAD_BOUND)) {
2277 goto out_unlock_cgroup;
2280 get_task_struct(tsk);
2283 threadgroup_lock(tsk);
2285 if (!thread_group_leader(tsk)) {
2287 * a race with de_thread from another thread's exec()
2288 * may strip us of our leadership, if this happens,
2289 * there is no choice but to throw this task away and
2290 * try again; this is
2291 * "double-double-toil-and-trouble-check locking".
2293 threadgroup_unlock(tsk);
2294 put_task_struct(tsk);
2295 goto retry_find_task;
2297 ret = cgroup_attach_proc(cgrp, tsk);
2299 ret = cgroup_attach_task(cgrp, tsk);
2300 threadgroup_unlock(tsk);
2302 put_task_struct(tsk);
2308 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2310 return attach_task_by_pid(cgrp, pid, false);
2313 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2315 return attach_task_by_pid(cgrp, tgid, true);
2319 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
2320 * @cgrp: the cgroup to be checked for liveness
2322 * On success, returns true; the lock should be later released with
2323 * cgroup_unlock(). On failure returns false with no lock held.
2325 bool cgroup_lock_live_group(struct cgroup *cgrp)
2327 mutex_lock(&cgroup_mutex);
2328 if (cgroup_is_removed(cgrp)) {
2329 mutex_unlock(&cgroup_mutex);
2334 EXPORT_SYMBOL_GPL(cgroup_lock_live_group);
2336 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2339 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2340 if (strlen(buffer) >= PATH_MAX)
2342 if (!cgroup_lock_live_group(cgrp))
2344 mutex_lock(&cgroup_root_mutex);
2345 strcpy(cgrp->root->release_agent_path, buffer);
2346 mutex_unlock(&cgroup_root_mutex);
2351 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2352 struct seq_file *seq)
2354 if (!cgroup_lock_live_group(cgrp))
2356 seq_puts(seq, cgrp->root->release_agent_path);
2357 seq_putc(seq, '\n');
2362 /* A buffer size big enough for numbers or short strings */
2363 #define CGROUP_LOCAL_BUFFER_SIZE 64
2365 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2367 const char __user *userbuf,
2368 size_t nbytes, loff_t *unused_ppos)
2370 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2376 if (nbytes >= sizeof(buffer))
2378 if (copy_from_user(buffer, userbuf, nbytes))
2381 buffer[nbytes] = 0; /* nul-terminate */
2382 if (cft->write_u64) {
2383 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2386 retval = cft->write_u64(cgrp, cft, val);
2388 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2391 retval = cft->write_s64(cgrp, cft, val);
2398 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2400 const char __user *userbuf,
2401 size_t nbytes, loff_t *unused_ppos)
2403 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2405 size_t max_bytes = cft->max_write_len;
2406 char *buffer = local_buffer;
2409 max_bytes = sizeof(local_buffer) - 1;
2410 if (nbytes >= max_bytes)
2412 /* Allocate a dynamic buffer if we need one */
2413 if (nbytes >= sizeof(local_buffer)) {
2414 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2418 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2423 buffer[nbytes] = 0; /* nul-terminate */
2424 retval = cft->write_string(cgrp, cft, strstrip(buffer));
2428 if (buffer != local_buffer)
2433 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2434 size_t nbytes, loff_t *ppos)
2436 struct cftype *cft = __d_cft(file->f_dentry);
2437 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2439 if (cgroup_is_removed(cgrp))
2442 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2443 if (cft->write_u64 || cft->write_s64)
2444 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2445 if (cft->write_string)
2446 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2448 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2449 return ret ? ret : nbytes;
2454 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2456 char __user *buf, size_t nbytes,
2459 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2460 u64 val = cft->read_u64(cgrp, cft);
2461 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2463 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2466 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2468 char __user *buf, size_t nbytes,
2471 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2472 s64 val = cft->read_s64(cgrp, cft);
2473 int len = sprintf(tmp, "%lld\n", (long long) val);
2475 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2478 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2479 size_t nbytes, loff_t *ppos)
2481 struct cftype *cft = __d_cft(file->f_dentry);
2482 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2484 if (cgroup_is_removed(cgrp))
2488 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2490 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2492 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2497 * seqfile ops/methods for returning structured data. Currently just
2498 * supports string->u64 maps, but can be extended in future.
2501 struct cgroup_seqfile_state {
2503 struct cgroup *cgroup;
2506 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2508 struct seq_file *sf = cb->state;
2509 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2512 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2514 struct cgroup_seqfile_state *state = m->private;
2515 struct cftype *cft = state->cft;
2516 if (cft->read_map) {
2517 struct cgroup_map_cb cb = {
2518 .fill = cgroup_map_add,
2521 return cft->read_map(state->cgroup, cft, &cb);
2523 return cft->read_seq_string(state->cgroup, cft, m);
2526 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2528 struct seq_file *seq = file->private_data;
2529 kfree(seq->private);
2530 return single_release(inode, file);
2533 static const struct file_operations cgroup_seqfile_operations = {
2535 .write = cgroup_file_write,
2536 .llseek = seq_lseek,
2537 .release = cgroup_seqfile_release,
2540 static int cgroup_file_open(struct inode *inode, struct file *file)
2545 err = generic_file_open(inode, file);
2548 cft = __d_cft(file->f_dentry);
2550 if (cft->read_map || cft->read_seq_string) {
2551 struct cgroup_seqfile_state *state =
2552 kzalloc(sizeof(*state), GFP_USER);
2556 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2557 file->f_op = &cgroup_seqfile_operations;
2558 err = single_open(file, cgroup_seqfile_show, state);
2561 } else if (cft->open)
2562 err = cft->open(inode, file);
2569 static int cgroup_file_release(struct inode *inode, struct file *file)
2571 struct cftype *cft = __d_cft(file->f_dentry);
2573 return cft->release(inode, file);
2578 * cgroup_rename - Only allow simple rename of directories in place.
2580 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2581 struct inode *new_dir, struct dentry *new_dentry)
2583 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2585 if (new_dentry->d_inode)
2587 if (old_dir != new_dir)
2589 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2592 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2594 if (S_ISDIR(dentry->d_inode->i_mode))
2595 return &__d_cgrp(dentry)->xattrs;
2597 return &__d_cft(dentry)->xattrs;
2600 static inline int xattr_enabled(struct dentry *dentry)
2602 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2603 return test_bit(ROOT_XATTR, &root->flags);
2606 static bool is_valid_xattr(const char *name)
2608 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2609 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2614 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2615 const void *val, size_t size, int flags)
2617 if (!xattr_enabled(dentry))
2619 if (!is_valid_xattr(name))
2621 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2624 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2626 if (!xattr_enabled(dentry))
2628 if (!is_valid_xattr(name))
2630 return simple_xattr_remove(__d_xattrs(dentry), name);
2633 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2634 void *buf, size_t size)
2636 if (!xattr_enabled(dentry))
2638 if (!is_valid_xattr(name))
2640 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2643 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2645 if (!xattr_enabled(dentry))
2647 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2650 static const struct file_operations cgroup_file_operations = {
2651 .read = cgroup_file_read,
2652 .write = cgroup_file_write,
2653 .llseek = generic_file_llseek,
2654 .open = cgroup_file_open,
2655 .release = cgroup_file_release,
2658 static const struct inode_operations cgroup_file_inode_operations = {
2659 .setxattr = cgroup_setxattr,
2660 .getxattr = cgroup_getxattr,
2661 .listxattr = cgroup_listxattr,
2662 .removexattr = cgroup_removexattr,
2665 static const struct inode_operations cgroup_dir_inode_operations = {
2666 .lookup = cgroup_lookup,
2667 .mkdir = cgroup_mkdir,
2668 .rmdir = cgroup_rmdir,
2669 .rename = cgroup_rename,
2670 .setxattr = cgroup_setxattr,
2671 .getxattr = cgroup_getxattr,
2672 .listxattr = cgroup_listxattr,
2673 .removexattr = cgroup_removexattr,
2676 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2678 if (dentry->d_name.len > NAME_MAX)
2679 return ERR_PTR(-ENAMETOOLONG);
2680 d_add(dentry, NULL);
2685 * Check if a file is a control file
2687 static inline struct cftype *__file_cft(struct file *file)
2689 if (file->f_dentry->d_inode->i_fop != &cgroup_file_operations)
2690 return ERR_PTR(-EINVAL);
2691 return __d_cft(file->f_dentry);
2694 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2695 struct super_block *sb)
2697 struct inode *inode;
2701 if (dentry->d_inode)
2704 inode = cgroup_new_inode(mode, sb);
2708 if (S_ISDIR(mode)) {
2709 inode->i_op = &cgroup_dir_inode_operations;
2710 inode->i_fop = &simple_dir_operations;
2712 /* start off with i_nlink == 2 (for "." entry) */
2715 /* start with the directory inode held, so that we can
2716 * populate it without racing with another mkdir */
2717 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
2718 } else if (S_ISREG(mode)) {
2720 inode->i_fop = &cgroup_file_operations;
2721 inode->i_op = &cgroup_file_inode_operations;
2723 d_instantiate(dentry, inode);
2724 dget(dentry); /* Extra count - pin the dentry in core */
2729 * cgroup_create_dir - create a directory for an object.
2730 * @cgrp: the cgroup we create the directory for. It must have a valid
2731 * ->parent field. And we are going to fill its ->dentry field.
2732 * @dentry: dentry of the new cgroup
2733 * @mode: mode to set on new directory.
2735 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
2738 struct dentry *parent;
2741 parent = cgrp->parent->dentry;
2742 error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
2744 dentry->d_fsdata = cgrp;
2745 inc_nlink(parent->d_inode);
2746 rcu_assign_pointer(cgrp->dentry, dentry);
2755 * cgroup_file_mode - deduce file mode of a control file
2756 * @cft: the control file in question
2758 * returns cft->mode if ->mode is not 0
2759 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2760 * returns S_IRUGO if it has only a read handler
2761 * returns S_IWUSR if it has only a write hander
2763 static umode_t cgroup_file_mode(const struct cftype *cft)
2770 if (cft->read || cft->read_u64 || cft->read_s64 ||
2771 cft->read_map || cft->read_seq_string)
2774 if (cft->write || cft->write_u64 || cft->write_s64 ||
2775 cft->write_string || cft->trigger)
2781 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2784 struct dentry *dir = cgrp->dentry;
2785 struct cgroup *parent = __d_cgrp(dir);
2786 struct dentry *dentry;
2790 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2792 simple_xattrs_init(&cft->xattrs);
2794 /* does @cft->flags tell us to skip creation on @cgrp? */
2795 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2797 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2800 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2801 strcpy(name, subsys->name);
2804 strcat(name, cft->name);
2806 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2808 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2812 dentry = lookup_one_len(name, dir, strlen(name));
2813 if (IS_ERR(dentry)) {
2814 error = PTR_ERR(dentry);
2818 mode = cgroup_file_mode(cft);
2819 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2821 cfe->type = (void *)cft;
2822 cfe->dentry = dentry;
2823 dentry->d_fsdata = cfe;
2824 list_add_tail(&cfe->node, &parent->files);
2833 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2834 struct cftype cfts[], bool is_add)
2839 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2841 err = cgroup_add_file(cgrp, subsys, cft);
2843 err = cgroup_rm_file(cgrp, cft);
2845 pr_warning("cgroup_addrm_files: failed to %s %s, err=%d\n",
2846 is_add ? "add" : "remove", cft->name, err);
2853 static DEFINE_MUTEX(cgroup_cft_mutex);
2855 static void cgroup_cfts_prepare(void)
2856 __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2859 * Thanks to the entanglement with vfs inode locking, we can't walk
2860 * the existing cgroups under cgroup_mutex and create files.
2861 * Instead, we increment reference on all cgroups and build list of
2862 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2863 * exclusive access to the field.
2865 mutex_lock(&cgroup_cft_mutex);
2866 mutex_lock(&cgroup_mutex);
2869 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2870 struct cftype *cfts, bool is_add)
2871 __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2874 struct cgroup *cgrp, *n;
2876 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2877 if (cfts && ss->root != &rootnode) {
2878 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2880 list_add_tail(&cgrp->cft_q_node, &pending);
2884 mutex_unlock(&cgroup_mutex);
2887 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2888 * files for all cgroups which were created before.
2890 list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2891 struct inode *inode = cgrp->dentry->d_inode;
2893 mutex_lock(&inode->i_mutex);
2894 mutex_lock(&cgroup_mutex);
2895 if (!cgroup_is_removed(cgrp))
2896 cgroup_addrm_files(cgrp, ss, cfts, is_add);
2897 mutex_unlock(&cgroup_mutex);
2898 mutex_unlock(&inode->i_mutex);
2900 list_del_init(&cgrp->cft_q_node);
2904 mutex_unlock(&cgroup_cft_mutex);
2908 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2909 * @ss: target cgroup subsystem
2910 * @cfts: zero-length name terminated array of cftypes
2912 * Register @cfts to @ss. Files described by @cfts are created for all
2913 * existing cgroups to which @ss is attached and all future cgroups will
2914 * have them too. This function can be called anytime whether @ss is
2917 * Returns 0 on successful registration, -errno on failure. Note that this
2918 * function currently returns 0 as long as @cfts registration is successful
2919 * even if some file creation attempts on existing cgroups fail.
2921 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2923 struct cftype_set *set;
2925 set = kzalloc(sizeof(*set), GFP_KERNEL);
2929 cgroup_cfts_prepare();
2931 list_add_tail(&set->node, &ss->cftsets);
2932 cgroup_cfts_commit(ss, cfts, true);
2936 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2939 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2940 * @ss: target cgroup subsystem
2941 * @cfts: zero-length name terminated array of cftypes
2943 * Unregister @cfts from @ss. Files described by @cfts are removed from
2944 * all existing cgroups to which @ss is attached and all future cgroups
2945 * won't have them either. This function can be called anytime whether @ss
2946 * is attached or not.
2948 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2949 * registered with @ss.
2951 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2953 struct cftype_set *set;
2955 cgroup_cfts_prepare();
2957 list_for_each_entry(set, &ss->cftsets, node) {
2958 if (set->cfts == cfts) {
2959 list_del_init(&set->node);
2960 cgroup_cfts_commit(ss, cfts, false);
2965 cgroup_cfts_commit(ss, NULL, false);
2970 * cgroup_task_count - count the number of tasks in a cgroup.
2971 * @cgrp: the cgroup in question
2973 * Return the number of tasks in the cgroup.
2975 int cgroup_task_count(const struct cgroup *cgrp)
2978 struct cg_cgroup_link *link;
2980 read_lock(&css_set_lock);
2981 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2982 count += atomic_read(&link->cg->refcount);
2984 read_unlock(&css_set_lock);
2989 * Advance a list_head iterator. The iterator should be positioned at
2990 * the start of a css_set
2992 static void cgroup_advance_iter(struct cgroup *cgrp,
2993 struct cgroup_iter *it)
2995 struct list_head *l = it->cg_link;
2996 struct cg_cgroup_link *link;
2999 /* Advance to the next non-empty css_set */
3002 if (l == &cgrp->css_sets) {
3006 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
3008 } while (list_empty(&cg->tasks));
3010 it->task = cg->tasks.next;
3014 * To reduce the fork() overhead for systems that are not actually
3015 * using their cgroups capability, we don't maintain the lists running
3016 * through each css_set to its tasks until we see the list actually
3017 * used - in other words after the first call to cgroup_iter_start().
3019 static void cgroup_enable_task_cg_lists(void)
3021 struct task_struct *p, *g;
3022 write_lock(&css_set_lock);
3023 use_task_css_set_links = 1;
3025 * We need tasklist_lock because RCU is not safe against
3026 * while_each_thread(). Besides, a forking task that has passed
3027 * cgroup_post_fork() without seeing use_task_css_set_links = 1
3028 * is not guaranteed to have its child immediately visible in the
3029 * tasklist if we walk through it with RCU.
3031 read_lock(&tasklist_lock);
3032 do_each_thread(g, p) {
3035 * We should check if the process is exiting, otherwise
3036 * it will race with cgroup_exit() in that the list
3037 * entry won't be deleted though the process has exited.
3039 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
3040 list_add(&p->cg_list, &p->cgroups->tasks);
3042 } while_each_thread(g, p);
3043 read_unlock(&tasklist_lock);
3044 write_unlock(&css_set_lock);
3047 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3048 __acquires(css_set_lock)
3051 * The first time anyone tries to iterate across a cgroup,
3052 * we need to enable the list linking each css_set to its
3053 * tasks, and fix up all existing tasks.
3055 if (!use_task_css_set_links)
3056 cgroup_enable_task_cg_lists();
3058 read_lock(&css_set_lock);
3059 it->cg_link = &cgrp->css_sets;
3060 cgroup_advance_iter(cgrp, it);
3063 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3064 struct cgroup_iter *it)
3066 struct task_struct *res;
3067 struct list_head *l = it->task;
3068 struct cg_cgroup_link *link;
3070 /* If the iterator cg is NULL, we have no tasks */
3073 res = list_entry(l, struct task_struct, cg_list);
3074 /* Advance iterator to find next entry */
3076 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3077 if (l == &link->cg->tasks) {
3078 /* We reached the end of this task list - move on to
3079 * the next cg_cgroup_link */
3080 cgroup_advance_iter(cgrp, it);
3087 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3088 __releases(css_set_lock)
3090 read_unlock(&css_set_lock);
3093 static inline int started_after_time(struct task_struct *t1,
3094 struct timespec *time,
3095 struct task_struct *t2)
3097 int start_diff = timespec_compare(&t1->start_time, time);
3098 if (start_diff > 0) {
3100 } else if (start_diff < 0) {
3104 * Arbitrarily, if two processes started at the same
3105 * time, we'll say that the lower pointer value
3106 * started first. Note that t2 may have exited by now
3107 * so this may not be a valid pointer any longer, but
3108 * that's fine - it still serves to distinguish
3109 * between two tasks started (effectively) simultaneously.
3116 * This function is a callback from heap_insert() and is used to order
3118 * In this case we order the heap in descending task start time.
3120 static inline int started_after(void *p1, void *p2)
3122 struct task_struct *t1 = p1;
3123 struct task_struct *t2 = p2;
3124 return started_after_time(t1, &t2->start_time, t2);
3128 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3129 * @scan: struct cgroup_scanner containing arguments for the scan
3131 * Arguments include pointers to callback functions test_task() and
3133 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3134 * and if it returns true, call process_task() for it also.
3135 * The test_task pointer may be NULL, meaning always true (select all tasks).
3136 * Effectively duplicates cgroup_iter_{start,next,end}()
3137 * but does not lock css_set_lock for the call to process_task().
3138 * The struct cgroup_scanner may be embedded in any structure of the caller's
3140 * It is guaranteed that process_task() will act on every task that
3141 * is a member of the cgroup for the duration of this call. This
3142 * function may or may not call process_task() for tasks that exit
3143 * or move to a different cgroup during the call, or are forked or
3144 * move into the cgroup during the call.
3146 * Note that test_task() may be called with locks held, and may in some
3147 * situations be called multiple times for the same task, so it should
3149 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3150 * pre-allocated and will be used for heap operations (and its "gt" member will
3151 * be overwritten), else a temporary heap will be used (allocation of which
3152 * may cause this function to fail).
3154 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3157 struct cgroup_iter it;
3158 struct task_struct *p, *dropped;
3159 /* Never dereference latest_task, since it's not refcounted */
3160 struct task_struct *latest_task = NULL;
3161 struct ptr_heap tmp_heap;
3162 struct ptr_heap *heap;
3163 struct timespec latest_time = { 0, 0 };
3166 /* The caller supplied our heap and pre-allocated its memory */
3168 heap->gt = &started_after;
3170 /* We need to allocate our own heap memory */
3172 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3174 /* cannot allocate the heap */
3180 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3181 * to determine which are of interest, and using the scanner's
3182 * "process_task" callback to process any of them that need an update.
3183 * Since we don't want to hold any locks during the task updates,
3184 * gather tasks to be processed in a heap structure.
3185 * The heap is sorted by descending task start time.
3186 * If the statically-sized heap fills up, we overflow tasks that
3187 * started later, and in future iterations only consider tasks that
3188 * started after the latest task in the previous pass. This
3189 * guarantees forward progress and that we don't miss any tasks.
3192 cgroup_iter_start(scan->cg, &it);
3193 while ((p = cgroup_iter_next(scan->cg, &it))) {
3195 * Only affect tasks that qualify per the caller's callback,
3196 * if he provided one
3198 if (scan->test_task && !scan->test_task(p, scan))
3201 * Only process tasks that started after the last task
3204 if (!started_after_time(p, &latest_time, latest_task))
3206 dropped = heap_insert(heap, p);
3207 if (dropped == NULL) {
3209 * The new task was inserted; the heap wasn't
3213 } else if (dropped != p) {
3215 * The new task was inserted, and pushed out a
3219 put_task_struct(dropped);
3222 * Else the new task was newer than anything already in
3223 * the heap and wasn't inserted
3226 cgroup_iter_end(scan->cg, &it);
3229 for (i = 0; i < heap->size; i++) {
3230 struct task_struct *q = heap->ptrs[i];
3232 latest_time = q->start_time;
3235 /* Process the task per the caller's callback */
3236 scan->process_task(q, scan);
3240 * If we had to process any tasks at all, scan again
3241 * in case some of them were in the middle of forking
3242 * children that didn't get processed.
3243 * Not the most efficient way to do it, but it avoids
3244 * having to take callback_mutex in the fork path
3248 if (heap == &tmp_heap)
3249 heap_free(&tmp_heap);
3254 * Stuff for reading the 'tasks'/'procs' files.
3256 * Reading this file can return large amounts of data if a cgroup has
3257 * *lots* of attached tasks. So it may need several calls to read(),
3258 * but we cannot guarantee that the information we produce is correct
3259 * unless we produce it entirely atomically.
3263 /* which pidlist file are we talking about? */
3264 enum cgroup_filetype {
3270 * A pidlist is a list of pids that virtually represents the contents of one
3271 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3272 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3275 struct cgroup_pidlist {
3277 * used to find which pidlist is wanted. doesn't change as long as
3278 * this particular list stays in the list.
3280 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3283 /* how many elements the above list has */
3285 /* how many files are using the current array */
3287 /* each of these stored in a list by its cgroup */
3288 struct list_head links;
3289 /* pointer to the cgroup we belong to, for list removal purposes */
3290 struct cgroup *owner;
3291 /* protects the other fields */
3292 struct rw_semaphore mutex;
3296 * The following two functions "fix" the issue where there are more pids
3297 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3298 * TODO: replace with a kernel-wide solution to this problem
3300 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3301 static void *pidlist_allocate(int count)
3303 if (PIDLIST_TOO_LARGE(count))
3304 return vmalloc(count * sizeof(pid_t));
3306 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3308 static void pidlist_free(void *p)
3310 if (is_vmalloc_addr(p))
3315 static void *pidlist_resize(void *p, int newcount)
3318 /* note: if new alloc fails, old p will still be valid either way */
3319 if (is_vmalloc_addr(p)) {
3320 newlist = vmalloc(newcount * sizeof(pid_t));
3323 memcpy(newlist, p, newcount * sizeof(pid_t));
3326 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
3332 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3333 * If the new stripped list is sufficiently smaller and there's enough memory
3334 * to allocate a new buffer, will let go of the unneeded memory. Returns the
3335 * number of unique elements.
3337 /* is the size difference enough that we should re-allocate the array? */
3338 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
3339 static int pidlist_uniq(pid_t **p, int length)
3346 * we presume the 0th element is unique, so i starts at 1. trivial
3347 * edge cases first; no work needs to be done for either
3349 if (length == 0 || length == 1)
3351 /* src and dest walk down the list; dest counts unique elements */
3352 for (src = 1; src < length; src++) {
3353 /* find next unique element */
3354 while (list[src] == list[src-1]) {
3359 /* dest always points to where the next unique element goes */
3360 list[dest] = list[src];
3365 * if the length difference is large enough, we want to allocate a
3366 * smaller buffer to save memory. if this fails due to out of memory,
3367 * we'll just stay with what we've got.
3369 if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
3370 newlist = pidlist_resize(list, dest);
3377 static int cmppid(const void *a, const void *b)
3379 return *(pid_t *)a - *(pid_t *)b;
3383 * find the appropriate pidlist for our purpose (given procs vs tasks)
3384 * returns with the lock on that pidlist already held, and takes care
3385 * of the use count, or returns NULL with no locks held if we're out of
3388 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3389 enum cgroup_filetype type)
3391 struct cgroup_pidlist *l;
3392 /* don't need task_nsproxy() if we're looking at ourself */
3393 struct pid_namespace *ns = current->nsproxy->pid_ns;
3396 * We can't drop the pidlist_mutex before taking the l->mutex in case
3397 * the last ref-holder is trying to remove l from the list at the same
3398 * time. Holding the pidlist_mutex precludes somebody taking whichever
3399 * list we find out from under us - compare release_pid_array().
3401 mutex_lock(&cgrp->pidlist_mutex);
3402 list_for_each_entry(l, &cgrp->pidlists, links) {
3403 if (l->key.type == type && l->key.ns == ns) {
3404 /* make sure l doesn't vanish out from under us */
3405 down_write(&l->mutex);
3406 mutex_unlock(&cgrp->pidlist_mutex);
3410 /* entry not found; create a new one */
3411 l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3413 mutex_unlock(&cgrp->pidlist_mutex);
3416 init_rwsem(&l->mutex);
3417 down_write(&l->mutex);
3419 l->key.ns = get_pid_ns(ns);
3420 l->use_count = 0; /* don't increment here */
3423 list_add(&l->links, &cgrp->pidlists);
3424 mutex_unlock(&cgrp->pidlist_mutex);
3429 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3431 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3432 struct cgroup_pidlist **lp)
3436 int pid, n = 0; /* used for populating the array */
3437 struct cgroup_iter it;
3438 struct task_struct *tsk;
3439 struct cgroup_pidlist *l;
3442 * If cgroup gets more users after we read count, we won't have
3443 * enough space - tough. This race is indistinguishable to the
3444 * caller from the case that the additional cgroup users didn't
3445 * show up until sometime later on.
3447 length = cgroup_task_count(cgrp);
3448 array = pidlist_allocate(length);
3451 /* now, populate the array */
3452 cgroup_iter_start(cgrp, &it);
3453 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3454 if (unlikely(n == length))
3456 /* get tgid or pid for procs or tasks file respectively */
3457 if (type == CGROUP_FILE_PROCS)
3458 pid = task_tgid_vnr(tsk);
3460 pid = task_pid_vnr(tsk);
3461 if (pid > 0) /* make sure to only use valid results */
3464 cgroup_iter_end(cgrp, &it);
3466 /* now sort & (if procs) strip out duplicates */
3467 sort(array, length, sizeof(pid_t), cmppid, NULL);
3468 if (type == CGROUP_FILE_PROCS)
3469 length = pidlist_uniq(&array, length);
3470 l = cgroup_pidlist_find(cgrp, type);
3472 pidlist_free(array);
3475 /* store array, freeing old if necessary - lock already held */
3476 pidlist_free(l->list);
3480 up_write(&l->mutex);
3486 * cgroupstats_build - build and fill cgroupstats
3487 * @stats: cgroupstats to fill information into
3488 * @dentry: A dentry entry belonging to the cgroup for which stats have
3491 * Build and fill cgroupstats so that taskstats can export it to user
3494 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3497 struct cgroup *cgrp;
3498 struct cgroup_iter it;
3499 struct task_struct *tsk;
3502 * Validate dentry by checking the superblock operations,
3503 * and make sure it's a directory.
3505 if (dentry->d_sb->s_op != &cgroup_ops ||
3506 !S_ISDIR(dentry->d_inode->i_mode))
3510 cgrp = dentry->d_fsdata;
3512 cgroup_iter_start(cgrp, &it);
3513 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3514 switch (tsk->state) {
3516 stats->nr_running++;
3518 case TASK_INTERRUPTIBLE:
3519 stats->nr_sleeping++;
3521 case TASK_UNINTERRUPTIBLE:
3522 stats->nr_uninterruptible++;
3525 stats->nr_stopped++;
3528 if (delayacct_is_task_waiting_on_io(tsk))
3529 stats->nr_io_wait++;
3533 cgroup_iter_end(cgrp, &it);
3541 * seq_file methods for the tasks/procs files. The seq_file position is the
3542 * next pid to display; the seq_file iterator is a pointer to the pid
3543 * in the cgroup->l->list array.
3546 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3549 * Initially we receive a position value that corresponds to
3550 * one more than the last pid shown (or 0 on the first call or
3551 * after a seek to the start). Use a binary-search to find the
3552 * next pid to display, if any
3554 struct cgroup_pidlist *l = s->private;
3555 int index = 0, pid = *pos;
3558 down_read(&l->mutex);
3560 int end = l->length;
3562 while (index < end) {
3563 int mid = (index + end) / 2;
3564 if (l->list[mid] == pid) {
3567 } else if (l->list[mid] <= pid)
3573 /* If we're off the end of the array, we're done */
3574 if (index >= l->length)
3576 /* Update the abstract position to be the actual pid that we found */
3577 iter = l->list + index;
3582 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3584 struct cgroup_pidlist *l = s->private;
3588 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3590 struct cgroup_pidlist *l = s->private;
3592 pid_t *end = l->list + l->length;
3594 * Advance to the next pid in the array. If this goes off the
3606 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3608 return seq_printf(s, "%d\n", *(int *)v);
3612 * seq_operations functions for iterating on pidlists through seq_file -
3613 * independent of whether it's tasks or procs
3615 static const struct seq_operations cgroup_pidlist_seq_operations = {
3616 .start = cgroup_pidlist_start,
3617 .stop = cgroup_pidlist_stop,
3618 .next = cgroup_pidlist_next,
3619 .show = cgroup_pidlist_show,
3622 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3625 * the case where we're the last user of this particular pidlist will
3626 * have us remove it from the cgroup's list, which entails taking the
3627 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3628 * pidlist_mutex, we have to take pidlist_mutex first.
3630 mutex_lock(&l->owner->pidlist_mutex);
3631 down_write(&l->mutex);
3632 BUG_ON(!l->use_count);
3633 if (!--l->use_count) {
3634 /* we're the last user if refcount is 0; remove and free */
3635 list_del(&l->links);
3636 mutex_unlock(&l->owner->pidlist_mutex);
3637 pidlist_free(l->list);
3638 put_pid_ns(l->key.ns);
3639 up_write(&l->mutex);
3643 mutex_unlock(&l->owner->pidlist_mutex);
3644 up_write(&l->mutex);
3647 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3649 struct cgroup_pidlist *l;
3650 if (!(file->f_mode & FMODE_READ))
3653 * the seq_file will only be initialized if the file was opened for
3654 * reading; hence we check if it's not null only in that case.
3656 l = ((struct seq_file *)file->private_data)->private;
3657 cgroup_release_pid_array(l);
3658 return seq_release(inode, file);
3661 static const struct file_operations cgroup_pidlist_operations = {
3663 .llseek = seq_lseek,
3664 .write = cgroup_file_write,
3665 .release = cgroup_pidlist_release,
3669 * The following functions handle opens on a file that displays a pidlist
3670 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3673 /* helper function for the two below it */
3674 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3676 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3677 struct cgroup_pidlist *l;
3680 /* Nothing to do for write-only files */
3681 if (!(file->f_mode & FMODE_READ))
3684 /* have the array populated */
3685 retval = pidlist_array_load(cgrp, type, &l);
3688 /* configure file information */
3689 file->f_op = &cgroup_pidlist_operations;
3691 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3693 cgroup_release_pid_array(l);
3696 ((struct seq_file *)file->private_data)->private = l;
3699 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3701 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3703 static int cgroup_procs_open(struct inode *unused, struct file *file)
3705 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3708 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3711 return notify_on_release(cgrp);
3714 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3718 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3720 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3722 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3727 * Unregister event and free resources.
3729 * Gets called from workqueue.
3731 static void cgroup_event_remove(struct work_struct *work)
3733 struct cgroup_event *event = container_of(work, struct cgroup_event,
3735 struct cgroup *cgrp = event->cgrp;
3737 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3739 eventfd_ctx_put(event->eventfd);
3745 * Gets called on POLLHUP on eventfd when user closes it.
3747 * Called with wqh->lock held and interrupts disabled.
3749 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3750 int sync, void *key)
3752 struct cgroup_event *event = container_of(wait,
3753 struct cgroup_event, wait);
3754 struct cgroup *cgrp = event->cgrp;
3755 unsigned long flags = (unsigned long)key;
3757 if (flags & POLLHUP) {
3758 __remove_wait_queue(event->wqh, &event->wait);
3759 spin_lock(&cgrp->event_list_lock);
3760 list_del(&event->list);
3761 spin_unlock(&cgrp->event_list_lock);
3763 * We are in atomic context, but cgroup_event_remove() may
3764 * sleep, so we have to call it in workqueue.
3766 schedule_work(&event->remove);
3772 static void cgroup_event_ptable_queue_proc(struct file *file,
3773 wait_queue_head_t *wqh, poll_table *pt)
3775 struct cgroup_event *event = container_of(pt,
3776 struct cgroup_event, pt);
3779 add_wait_queue(wqh, &event->wait);
3783 * Parse input and register new cgroup event handler.
3785 * Input must be in format '<event_fd> <control_fd> <args>'.
3786 * Interpretation of args is defined by control file implementation.
3788 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3791 struct cgroup_event *event = NULL;
3792 unsigned int efd, cfd;
3793 struct file *efile = NULL;
3794 struct file *cfile = NULL;
3798 efd = simple_strtoul(buffer, &endp, 10);
3803 cfd = simple_strtoul(buffer, &endp, 10);
3804 if ((*endp != ' ') && (*endp != '\0'))
3808 event = kzalloc(sizeof(*event), GFP_KERNEL);
3812 INIT_LIST_HEAD(&event->list);
3813 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3814 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3815 INIT_WORK(&event->remove, cgroup_event_remove);
3817 efile = eventfd_fget(efd);
3818 if (IS_ERR(efile)) {
3819 ret = PTR_ERR(efile);
3823 event->eventfd = eventfd_ctx_fileget(efile);
3824 if (IS_ERR(event->eventfd)) {
3825 ret = PTR_ERR(event->eventfd);
3835 /* the process need read permission on control file */
3836 /* AV: shouldn't we check that it's been opened for read instead? */
3837 ret = inode_permission(cfile->f_path.dentry->d_inode, MAY_READ);
3841 event->cft = __file_cft(cfile);
3842 if (IS_ERR(event->cft)) {
3843 ret = PTR_ERR(event->cft);
3847 if (!event->cft->register_event || !event->cft->unregister_event) {
3852 ret = event->cft->register_event(cgrp, event->cft,
3853 event->eventfd, buffer);
3857 if (efile->f_op->poll(efile, &event->pt) & POLLHUP) {
3858 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3864 * Events should be removed after rmdir of cgroup directory, but before
3865 * destroying subsystem state objects. Let's take reference to cgroup
3866 * directory dentry to do that.
3870 spin_lock(&cgrp->event_list_lock);
3871 list_add(&event->list, &cgrp->event_list);
3872 spin_unlock(&cgrp->event_list_lock);
3883 if (event && event->eventfd && !IS_ERR(event->eventfd))
3884 eventfd_ctx_put(event->eventfd);
3886 if (!IS_ERR_OR_NULL(efile))
3894 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
3897 return clone_children(cgrp);
3900 static int cgroup_clone_children_write(struct cgroup *cgrp,
3905 set_bit(CGRP_CLONE_CHILDREN, &cgrp->flags);
3907 clear_bit(CGRP_CLONE_CHILDREN, &cgrp->flags);
3912 * for the common functions, 'private' gives the type of file
3914 /* for hysterical raisins, we can't put this on the older files */
3915 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3916 static struct cftype files[] = {
3919 .open = cgroup_tasks_open,
3920 .write_u64 = cgroup_tasks_write,
3921 .release = cgroup_pidlist_release,
3922 .mode = S_IRUGO | S_IWUSR,
3925 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
3926 .open = cgroup_procs_open,
3927 .write_u64 = cgroup_procs_write,
3928 .release = cgroup_pidlist_release,
3929 .mode = S_IRUGO | S_IWUSR,
3932 .name = "notify_on_release",
3933 .read_u64 = cgroup_read_notify_on_release,
3934 .write_u64 = cgroup_write_notify_on_release,
3937 .name = CGROUP_FILE_GENERIC_PREFIX "event_control",
3938 .write_string = cgroup_write_event_control,
3942 .name = "cgroup.clone_children",
3943 .read_u64 = cgroup_clone_children_read,
3944 .write_u64 = cgroup_clone_children_write,
3947 .name = "release_agent",
3948 .flags = CFTYPE_ONLY_ON_ROOT,
3949 .read_seq_string = cgroup_release_agent_show,
3950 .write_string = cgroup_release_agent_write,
3951 .max_write_len = PATH_MAX,
3957 * cgroup_populate_dir - selectively creation of files in a directory
3958 * @cgrp: target cgroup
3959 * @base_files: true if the base files should be added
3960 * @subsys_mask: mask of the subsystem ids whose files should be added
3962 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
3963 unsigned long subsys_mask)
3966 struct cgroup_subsys *ss;
3969 err = cgroup_addrm_files(cgrp, NULL, files, true);
3974 /* process cftsets of each subsystem */
3975 for_each_subsys(cgrp->root, ss) {
3976 struct cftype_set *set;
3977 if (!test_bit(ss->subsys_id, &subsys_mask))
3980 list_for_each_entry(set, &ss->cftsets, node)
3981 cgroup_addrm_files(cgrp, ss, set->cfts, true);
3984 /* This cgroup is ready now */
3985 for_each_subsys(cgrp->root, ss) {
3986 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3988 * Update id->css pointer and make this css visible from
3989 * CSS ID functions. This pointer will be dereferened
3990 * from RCU-read-side without locks.
3993 rcu_assign_pointer(css->id->css, css);
3999 static void css_dput_fn(struct work_struct *work)
4001 struct cgroup_subsys_state *css =
4002 container_of(work, struct cgroup_subsys_state, dput_work);
4003 struct dentry *dentry = css->cgroup->dentry;
4004 struct super_block *sb = dentry->d_sb;
4006 atomic_inc(&sb->s_active);
4008 deactivate_super(sb);
4011 static void init_cgroup_css(struct cgroup_subsys_state *css,
4012 struct cgroup_subsys *ss,
4013 struct cgroup *cgrp)
4016 atomic_set(&css->refcnt, 1);
4019 if (cgrp == dummytop)
4020 set_bit(CSS_ROOT, &css->flags);
4021 BUG_ON(cgrp->subsys[ss->subsys_id]);
4022 cgrp->subsys[ss->subsys_id] = css;
4025 * If !clear_css_refs, css holds an extra ref to @cgrp->dentry
4026 * which is put on the last css_put(). dput() requires process
4027 * context, which css_put() may be called without. @css->dput_work
4028 * will be used to invoke dput() asynchronously from css_put().
4030 INIT_WORK(&css->dput_work, css_dput_fn);
4031 if (ss->__DEPRECATED_clear_css_refs)
4032 set_bit(CSS_CLEAR_CSS_REFS, &css->flags);
4036 * cgroup_create - create a cgroup
4037 * @parent: cgroup that will be parent of the new cgroup
4038 * @dentry: dentry of the new cgroup
4039 * @mode: mode to set on new inode
4041 * Must be called with the mutex on the parent inode held
4043 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4046 struct cgroup *cgrp;
4047 struct cgroupfs_root *root = parent->root;
4049 struct cgroup_subsys *ss;
4050 struct super_block *sb = root->sb;
4052 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4056 /* Grab a reference on the superblock so the hierarchy doesn't
4057 * get deleted on unmount if there are child cgroups. This
4058 * can be done outside cgroup_mutex, since the sb can't
4059 * disappear while someone has an open control file on the
4061 atomic_inc(&sb->s_active);
4063 mutex_lock(&cgroup_mutex);
4065 init_cgroup_housekeeping(cgrp);
4067 cgrp->parent = parent;
4068 cgrp->root = parent->root;
4069 cgrp->top_cgroup = parent->top_cgroup;
4071 if (notify_on_release(parent))
4072 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4074 if (clone_children(parent))
4075 set_bit(CGRP_CLONE_CHILDREN, &cgrp->flags);
4077 for_each_subsys(root, ss) {
4078 struct cgroup_subsys_state *css = ss->create(cgrp);
4084 init_cgroup_css(css, ss, cgrp);
4086 err = alloc_css_id(ss, parent, cgrp);
4090 /* At error, ->destroy() callback has to free assigned ID. */
4091 if (clone_children(parent) && ss->post_clone)
4092 ss->post_clone(cgrp);
4095 list_add(&cgrp->sibling, &cgrp->parent->children);
4096 root->number_of_cgroups++;
4098 err = cgroup_create_dir(cgrp, dentry, mode);
4102 /* If !clear_css_refs, each css holds a ref to the cgroup's dentry */
4103 for_each_subsys(root, ss)
4104 if (!ss->__DEPRECATED_clear_css_refs)
4107 /* The cgroup directory was pre-locked for us */
4108 BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
4110 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4112 err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4113 /* If err < 0, we have a half-filled directory - oh well ;) */
4115 mutex_unlock(&cgroup_mutex);
4116 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4122 list_del(&cgrp->sibling);
4123 root->number_of_cgroups--;
4127 for_each_subsys(root, ss) {
4128 if (cgrp->subsys[ss->subsys_id])
4132 mutex_unlock(&cgroup_mutex);
4134 /* Release the reference count that we took on the superblock */
4135 deactivate_super(sb);
4141 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4143 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4145 /* the vfs holds inode->i_mutex already */
4146 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4150 * Check the reference count on each subsystem. Since we already
4151 * established that there are no tasks in the cgroup, if the css refcount
4152 * is also 1, then there should be no outstanding references, so the
4153 * subsystem is safe to destroy. We scan across all subsystems rather than
4154 * using the per-hierarchy linked list of mounted subsystems since we can
4155 * be called via check_for_release() with no synchronization other than
4156 * RCU, and the subsystem linked list isn't RCU-safe.
4158 static int cgroup_has_css_refs(struct cgroup *cgrp)
4163 * We won't need to lock the subsys array, because the subsystems
4164 * we're concerned about aren't going anywhere since our cgroup root
4165 * has a reference on them.
4167 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4168 struct cgroup_subsys *ss = subsys[i];
4169 struct cgroup_subsys_state *css;
4171 /* Skip subsystems not present or not in this hierarchy */
4172 if (ss == NULL || ss->root != cgrp->root)
4175 css = cgrp->subsys[ss->subsys_id];
4177 * When called from check_for_release() it's possible
4178 * that by this point the cgroup has been removed
4179 * and the css deleted. But a false-positive doesn't
4180 * matter, since it can only happen if the cgroup
4181 * has been deleted and hence no longer needs the
4182 * release agent to be called anyway.
4184 if (css && css_refcnt(css) > 1)
4191 * Atomically mark all (or else none) of the cgroup's CSS objects as
4192 * CSS_REMOVED. Return true on success, or false if the cgroup has
4193 * busy subsystems. Call with cgroup_mutex held
4195 * Depending on whether a subsys has __DEPRECATED_clear_css_refs set or
4196 * not, cgroup removal behaves differently.
4198 * If clear is set, css refcnt for the subsystem should be zero before
4199 * cgroup removal can be committed. This is implemented by
4200 * CGRP_WAIT_ON_RMDIR and retry logic around ->pre_destroy(), which may be
4201 * called multiple times until all css refcnts reach zero and is allowed to
4202 * veto removal on any invocation. This behavior is deprecated and will be
4203 * removed as soon as the existing user (memcg) is updated.
4205 * If clear is not set, each css holds an extra reference to the cgroup's
4206 * dentry and cgroup removal proceeds regardless of css refs.
4207 * ->pre_destroy() will be called at least once and is not allowed to fail.
4208 * On the last put of each css, whenever that may be, the extra dentry ref
4209 * is put so that dentry destruction happens only after all css's are
4212 static int cgroup_clear_css_refs(struct cgroup *cgrp)
4214 struct cgroup_subsys *ss;
4215 unsigned long flags;
4216 bool failed = false;
4218 local_irq_save(flags);
4221 * Block new css_tryget() by deactivating refcnt. If all refcnts
4222 * for subsystems w/ clear_css_refs set were 1 at the moment of
4223 * deactivation, we succeeded.
4225 for_each_subsys(cgrp->root, ss) {
4226 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4228 WARN_ON(atomic_read(&css->refcnt) < 0);
4229 atomic_add(CSS_DEACT_BIAS, &css->refcnt);
4231 if (ss->__DEPRECATED_clear_css_refs)
4232 failed |= css_refcnt(css) != 1;
4236 * If succeeded, set REMOVED and put all the base refs; otherwise,
4237 * restore refcnts to positive values. Either way, all in-progress
4238 * css_tryget() will be released.
4240 for_each_subsys(cgrp->root, ss) {
4241 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4244 set_bit(CSS_REMOVED, &css->flags);
4247 atomic_sub(CSS_DEACT_BIAS, &css->refcnt);
4251 local_irq_restore(flags);
4255 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4257 struct cgroup *cgrp = dentry->d_fsdata;
4259 struct cgroup *parent;
4261 struct cgroup_event *event, *tmp;
4264 /* the vfs holds both inode->i_mutex already */
4266 mutex_lock(&cgroup_mutex);
4267 if (atomic_read(&cgrp->count) != 0) {
4268 mutex_unlock(&cgroup_mutex);
4271 if (!list_empty(&cgrp->children)) {
4272 mutex_unlock(&cgroup_mutex);
4275 mutex_unlock(&cgroup_mutex);
4278 * In general, subsystem has no css->refcnt after pre_destroy(). But
4279 * in racy cases, subsystem may have to get css->refcnt after
4280 * pre_destroy() and it makes rmdir return with -EBUSY. This sometimes
4281 * make rmdir return -EBUSY too often. To avoid that, we use waitqueue
4282 * for cgroup's rmdir. CGRP_WAIT_ON_RMDIR is for synchronizing rmdir
4283 * and subsystem's reference count handling. Please see css_get/put
4284 * and css_tryget() and cgroup_wakeup_rmdir_waiter() implementation.
4286 set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
4289 * Call pre_destroy handlers of subsys. Notify subsystems
4290 * that rmdir() request comes.
4292 ret = cgroup_call_pre_destroy(cgrp);
4294 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
4298 mutex_lock(&cgroup_mutex);
4299 parent = cgrp->parent;
4300 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
4301 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
4302 mutex_unlock(&cgroup_mutex);
4305 prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
4306 if (!cgroup_clear_css_refs(cgrp)) {
4307 mutex_unlock(&cgroup_mutex);
4309 * Because someone may call cgroup_wakeup_rmdir_waiter() before
4310 * prepare_to_wait(), we need to check this flag.
4312 if (test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))
4314 finish_wait(&cgroup_rmdir_waitq, &wait);
4315 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
4316 if (signal_pending(current))
4320 /* NO css_tryget() can success after here. */
4321 finish_wait(&cgroup_rmdir_waitq, &wait);
4322 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
4324 raw_spin_lock(&release_list_lock);
4325 set_bit(CGRP_REMOVED, &cgrp->flags);
4326 if (!list_empty(&cgrp->release_list))
4327 list_del_init(&cgrp->release_list);
4328 raw_spin_unlock(&release_list_lock);
4330 /* delete this cgroup from parent->children */
4331 list_del_init(&cgrp->sibling);
4333 list_del_init(&cgrp->allcg_node);
4335 d = dget(cgrp->dentry);
4337 cgroup_d_remove_dir(d);
4340 set_bit(CGRP_RELEASABLE, &parent->flags);
4341 check_for_release(parent);
4344 * Unregister events and notify userspace.
4345 * Notify userspace about cgroup removing only after rmdir of cgroup
4346 * directory to avoid race between userspace and kernelspace
4348 spin_lock(&cgrp->event_list_lock);
4349 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4350 list_del(&event->list);
4351 remove_wait_queue(event->wqh, &event->wait);
4352 eventfd_signal(event->eventfd, 1);
4353 schedule_work(&event->remove);
4355 spin_unlock(&cgrp->event_list_lock);
4357 mutex_unlock(&cgroup_mutex);
4361 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4363 INIT_LIST_HEAD(&ss->cftsets);
4366 * base_cftset is embedded in subsys itself, no need to worry about
4369 if (ss->base_cftypes) {
4370 ss->base_cftset.cfts = ss->base_cftypes;
4371 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4375 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4377 struct cgroup_subsys_state *css;
4379 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4381 /* init base cftset */
4382 cgroup_init_cftsets(ss);
4384 /* Create the top cgroup state for this subsystem */
4385 list_add(&ss->sibling, &rootnode.subsys_list);
4386 ss->root = &rootnode;
4387 css = ss->create(dummytop);
4388 /* We don't handle early failures gracefully */
4389 BUG_ON(IS_ERR(css));
4390 init_cgroup_css(css, ss, dummytop);
4392 /* Update the init_css_set to contain a subsys
4393 * pointer to this state - since the subsystem is
4394 * newly registered, all tasks and hence the
4395 * init_css_set is in the subsystem's top cgroup. */
4396 init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
4398 need_forkexit_callback |= ss->fork || ss->exit;
4400 /* At system boot, before all subsystems have been
4401 * registered, no tasks have been forked, so we don't
4402 * need to invoke fork callbacks here. */
4403 BUG_ON(!list_empty(&init_task.tasks));
4407 /* this function shouldn't be used with modular subsystems, since they
4408 * need to register a subsys_id, among other things */
4413 * cgroup_load_subsys: load and register a modular subsystem at runtime
4414 * @ss: the subsystem to load
4416 * This function should be called in a modular subsystem's initcall. If the
4417 * subsystem is built as a module, it will be assigned a new subsys_id and set
4418 * up for use. If the subsystem is built-in anyway, work is delegated to the
4419 * simpler cgroup_init_subsys.
4421 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4424 struct cgroup_subsys_state *css;
4426 /* check name and function validity */
4427 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4428 ss->create == NULL || ss->destroy == NULL)
4432 * we don't support callbacks in modular subsystems. this check is
4433 * before the ss->module check for consistency; a subsystem that could
4434 * be a module should still have no callbacks even if the user isn't
4435 * compiling it as one.
4437 if (ss->fork || ss->exit)
4441 * an optionally modular subsystem is built-in: we want to do nothing,
4442 * since cgroup_init_subsys will have already taken care of it.
4444 if (ss->module == NULL) {
4445 /* a few sanity checks */
4446 BUG_ON(ss->subsys_id >= CGROUP_BUILTIN_SUBSYS_COUNT);
4447 BUG_ON(subsys[ss->subsys_id] != ss);
4451 /* init base cftset */
4452 cgroup_init_cftsets(ss);
4455 * need to register a subsys id before anything else - for example,
4456 * init_cgroup_css needs it.
4458 mutex_lock(&cgroup_mutex);
4459 /* find the first empty slot in the array */
4460 for (i = CGROUP_BUILTIN_SUBSYS_COUNT; i < CGROUP_SUBSYS_COUNT; i++) {
4461 if (subsys[i] == NULL)
4464 if (i == CGROUP_SUBSYS_COUNT) {
4465 /* maximum number of subsystems already registered! */
4466 mutex_unlock(&cgroup_mutex);
4469 /* assign ourselves the subsys_id */
4474 * no ss->create seems to need anything important in the ss struct, so
4475 * this can happen first (i.e. before the rootnode attachment).
4477 css = ss->create(dummytop);
4479 /* failure case - need to deassign the subsys[] slot. */
4481 mutex_unlock(&cgroup_mutex);
4482 return PTR_ERR(css);
4485 list_add(&ss->sibling, &rootnode.subsys_list);
4486 ss->root = &rootnode;
4488 /* our new subsystem will be attached to the dummy hierarchy. */
4489 init_cgroup_css(css, ss, dummytop);
4490 /* init_idr must be after init_cgroup_css because it sets css->id. */
4492 int ret = cgroup_init_idr(ss, css);
4494 dummytop->subsys[ss->subsys_id] = NULL;
4495 ss->destroy(dummytop);
4497 mutex_unlock(&cgroup_mutex);
4503 * Now we need to entangle the css into the existing css_sets. unlike
4504 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4505 * will need a new pointer to it; done by iterating the css_set_table.
4506 * furthermore, modifying the existing css_sets will corrupt the hash
4507 * table state, so each changed css_set will need its hash recomputed.
4508 * this is all done under the css_set_lock.
4510 write_lock(&css_set_lock);
4511 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
4513 struct hlist_node *node, *tmp;
4514 struct hlist_head *bucket = &css_set_table[i], *new_bucket;
4516 hlist_for_each_entry_safe(cg, node, tmp, bucket, hlist) {
4517 /* skip entries that we already rehashed */
4518 if (cg->subsys[ss->subsys_id])
4520 /* remove existing entry */
4521 hlist_del(&cg->hlist);
4523 cg->subsys[ss->subsys_id] = css;
4524 /* recompute hash and restore entry */
4525 new_bucket = css_set_hash(cg->subsys);
4526 hlist_add_head(&cg->hlist, new_bucket);
4529 write_unlock(&css_set_lock);
4534 mutex_unlock(&cgroup_mutex);
4537 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4540 * cgroup_unload_subsys: unload a modular subsystem
4541 * @ss: the subsystem to unload
4543 * This function should be called in a modular subsystem's exitcall. When this
4544 * function is invoked, the refcount on the subsystem's module will be 0, so
4545 * the subsystem will not be attached to any hierarchy.
4547 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4549 struct cg_cgroup_link *link;
4550 struct hlist_head *hhead;
4552 BUG_ON(ss->module == NULL);
4555 * we shouldn't be called if the subsystem is in use, and the use of
4556 * try_module_get in parse_cgroupfs_options should ensure that it
4557 * doesn't start being used while we're killing it off.
4559 BUG_ON(ss->root != &rootnode);
4561 mutex_lock(&cgroup_mutex);
4562 /* deassign the subsys_id */
4563 BUG_ON(ss->subsys_id < CGROUP_BUILTIN_SUBSYS_COUNT);
4564 subsys[ss->subsys_id] = NULL;
4566 /* remove subsystem from rootnode's list of subsystems */
4567 list_del_init(&ss->sibling);
4570 * disentangle the css from all css_sets attached to the dummytop. as
4571 * in loading, we need to pay our respects to the hashtable gods.
4573 write_lock(&css_set_lock);
4574 list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
4575 struct css_set *cg = link->cg;
4577 hlist_del(&cg->hlist);
4578 BUG_ON(!cg->subsys[ss->subsys_id]);
4579 cg->subsys[ss->subsys_id] = NULL;
4580 hhead = css_set_hash(cg->subsys);
4581 hlist_add_head(&cg->hlist, hhead);
4583 write_unlock(&css_set_lock);
4586 * remove subsystem's css from the dummytop and free it - need to free
4587 * before marking as null because ss->destroy needs the cgrp->subsys
4588 * pointer to find their state. note that this also takes care of
4589 * freeing the css_id.
4591 ss->destroy(dummytop);
4592 dummytop->subsys[ss->subsys_id] = NULL;
4594 mutex_unlock(&cgroup_mutex);
4596 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4599 * cgroup_init_early - cgroup initialization at system boot
4601 * Initialize cgroups at system boot, and initialize any
4602 * subsystems that request early init.
4604 int __init cgroup_init_early(void)
4607 atomic_set(&init_css_set.refcount, 1);
4608 INIT_LIST_HEAD(&init_css_set.cg_links);
4609 INIT_LIST_HEAD(&init_css_set.tasks);
4610 INIT_HLIST_NODE(&init_css_set.hlist);
4612 init_cgroup_root(&rootnode);
4614 init_task.cgroups = &init_css_set;
4616 init_css_set_link.cg = &init_css_set;
4617 init_css_set_link.cgrp = dummytop;
4618 list_add(&init_css_set_link.cgrp_link_list,
4619 &rootnode.top_cgroup.css_sets);
4620 list_add(&init_css_set_link.cg_link_list,
4621 &init_css_set.cg_links);
4623 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
4624 INIT_HLIST_HEAD(&css_set_table[i]);
4626 /* at bootup time, we don't worry about modular subsystems */
4627 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4628 struct cgroup_subsys *ss = subsys[i];
4631 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4632 BUG_ON(!ss->create);
4633 BUG_ON(!ss->destroy);
4634 if (ss->subsys_id != i) {
4635 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4636 ss->name, ss->subsys_id);
4641 cgroup_init_subsys(ss);
4647 * cgroup_init - cgroup initialization
4649 * Register cgroup filesystem and /proc file, and initialize
4650 * any subsystems that didn't request early init.
4652 int __init cgroup_init(void)
4656 struct hlist_head *hhead;
4658 err = bdi_init(&cgroup_backing_dev_info);
4662 /* at bootup time, we don't worry about modular subsystems */
4663 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4664 struct cgroup_subsys *ss = subsys[i];
4665 if (!ss->early_init)
4666 cgroup_init_subsys(ss);
4668 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4671 /* Add init_css_set to the hash table */
4672 hhead = css_set_hash(init_css_set.subsys);
4673 hlist_add_head(&init_css_set.hlist, hhead);
4674 BUG_ON(!init_root_id(&rootnode));
4676 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4682 err = register_filesystem(&cgroup_fs_type);
4684 kobject_put(cgroup_kobj);
4688 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4692 bdi_destroy(&cgroup_backing_dev_info);
4698 * proc_cgroup_show()
4699 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4700 * - Used for /proc/<pid>/cgroup.
4701 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4702 * doesn't really matter if tsk->cgroup changes after we read it,
4703 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4704 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4705 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4706 * cgroup to top_cgroup.
4709 /* TODO: Use a proper seq_file iterator */
4710 static int proc_cgroup_show(struct seq_file *m, void *v)
4713 struct task_struct *tsk;
4716 struct cgroupfs_root *root;
4719 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4725 tsk = get_pid_task(pid, PIDTYPE_PID);
4731 mutex_lock(&cgroup_mutex);
4733 for_each_active_root(root) {
4734 struct cgroup_subsys *ss;
4735 struct cgroup *cgrp;
4738 seq_printf(m, "%d:", root->hierarchy_id);
4739 for_each_subsys(root, ss)
4740 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4741 if (strlen(root->name))
4742 seq_printf(m, "%sname=%s", count ? "," : "",
4745 cgrp = task_cgroup_from_root(tsk, root);
4746 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4754 mutex_unlock(&cgroup_mutex);
4755 put_task_struct(tsk);
4762 static int cgroup_open(struct inode *inode, struct file *file)
4764 struct pid *pid = PROC_I(inode)->pid;
4765 return single_open(file, proc_cgroup_show, pid);
4768 const struct file_operations proc_cgroup_operations = {
4769 .open = cgroup_open,
4771 .llseek = seq_lseek,
4772 .release = single_release,
4775 /* Display information about each subsystem and each hierarchy */
4776 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4780 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4782 * ideally we don't want subsystems moving around while we do this.
4783 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4784 * subsys/hierarchy state.
4786 mutex_lock(&cgroup_mutex);
4787 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4788 struct cgroup_subsys *ss = subsys[i];
4791 seq_printf(m, "%s\t%d\t%d\t%d\n",
4792 ss->name, ss->root->hierarchy_id,
4793 ss->root->number_of_cgroups, !ss->disabled);
4795 mutex_unlock(&cgroup_mutex);
4799 static int cgroupstats_open(struct inode *inode, struct file *file)
4801 return single_open(file, proc_cgroupstats_show, NULL);
4804 static const struct file_operations proc_cgroupstats_operations = {
4805 .open = cgroupstats_open,
4807 .llseek = seq_lseek,
4808 .release = single_release,
4812 * cgroup_fork - attach newly forked task to its parents cgroup.
4813 * @child: pointer to task_struct of forking parent process.
4815 * Description: A task inherits its parent's cgroup at fork().
4817 * A pointer to the shared css_set was automatically copied in
4818 * fork.c by dup_task_struct(). However, we ignore that copy, since
4819 * it was not made under the protection of RCU, cgroup_mutex or
4820 * threadgroup_change_begin(), so it might no longer be a valid
4821 * cgroup pointer. cgroup_attach_task() might have already changed
4822 * current->cgroups, allowing the previously referenced cgroup
4823 * group to be removed and freed.
4825 * Outside the pointer validity we also need to process the css_set
4826 * inheritance between threadgoup_change_begin() and
4827 * threadgoup_change_end(), this way there is no leak in any process
4828 * wide migration performed by cgroup_attach_proc() that could otherwise
4829 * miss a thread because it is too early or too late in the fork stage.
4831 * At the point that cgroup_fork() is called, 'current' is the parent
4832 * task, and the passed argument 'child' points to the child task.
4834 void cgroup_fork(struct task_struct *child)
4837 * We don't need to task_lock() current because current->cgroups
4838 * can't be changed concurrently here. The parent obviously hasn't
4839 * exited and called cgroup_exit(), and we are synchronized against
4840 * cgroup migration through threadgroup_change_begin().
4842 child->cgroups = current->cgroups;
4843 get_css_set(child->cgroups);
4844 INIT_LIST_HEAD(&child->cg_list);
4848 * cgroup_fork_callbacks - run fork callbacks
4849 * @child: the new task
4851 * Called on a new task very soon before adding it to the
4852 * tasklist. No need to take any locks since no-one can
4853 * be operating on this task.
4855 void cgroup_fork_callbacks(struct task_struct *child)
4857 if (need_forkexit_callback) {
4860 * forkexit callbacks are only supported for builtin
4861 * subsystems, and the builtin section of the subsys array is
4862 * immutable, so we don't need to lock the subsys array here.
4864 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4865 struct cgroup_subsys *ss = subsys[i];
4873 * cgroup_post_fork - called on a new task after adding it to the task list
4874 * @child: the task in question
4876 * Adds the task to the list running through its css_set if necessary.
4877 * Has to be after the task is visible on the task list in case we race
4878 * with the first call to cgroup_iter_start() - to guarantee that the
4879 * new task ends up on its list.
4881 void cgroup_post_fork(struct task_struct *child)
4884 * use_task_css_set_links is set to 1 before we walk the tasklist
4885 * under the tasklist_lock and we read it here after we added the child
4886 * to the tasklist under the tasklist_lock as well. If the child wasn't
4887 * yet in the tasklist when we walked through it from
4888 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4889 * should be visible now due to the paired locking and barriers implied
4890 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4891 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4894 if (use_task_css_set_links) {
4895 write_lock(&css_set_lock);
4896 if (list_empty(&child->cg_list)) {
4898 * It's safe to use child->cgroups without task_lock()
4899 * here because we are protected through
4900 * threadgroup_change_begin() against concurrent
4901 * css_set change in cgroup_task_migrate(). Also
4902 * the task can't exit at that point until
4903 * wake_up_new_task() is called, so we are protected
4904 * against cgroup_exit() setting child->cgroup to
4907 list_add(&child->cg_list, &child->cgroups->tasks);
4909 write_unlock(&css_set_lock);
4913 * cgroup_exit - detach cgroup from exiting task
4914 * @tsk: pointer to task_struct of exiting process
4915 * @run_callback: run exit callbacks?
4917 * Description: Detach cgroup from @tsk and release it.
4919 * Note that cgroups marked notify_on_release force every task in
4920 * them to take the global cgroup_mutex mutex when exiting.
4921 * This could impact scaling on very large systems. Be reluctant to
4922 * use notify_on_release cgroups where very high task exit scaling
4923 * is required on large systems.
4925 * the_top_cgroup_hack:
4927 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4929 * We call cgroup_exit() while the task is still competent to
4930 * handle notify_on_release(), then leave the task attached to the
4931 * root cgroup in each hierarchy for the remainder of its exit.
4933 * To do this properly, we would increment the reference count on
4934 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4935 * code we would add a second cgroup function call, to drop that
4936 * reference. This would just create an unnecessary hot spot on
4937 * the top_cgroup reference count, to no avail.
4939 * Normally, holding a reference to a cgroup without bumping its
4940 * count is unsafe. The cgroup could go away, or someone could
4941 * attach us to a different cgroup, decrementing the count on
4942 * the first cgroup that we never incremented. But in this case,
4943 * top_cgroup isn't going away, and either task has PF_EXITING set,
4944 * which wards off any cgroup_attach_task() attempts, or task is a failed
4945 * fork, never visible to cgroup_attach_task.
4947 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4953 * Unlink from the css_set task list if necessary.
4954 * Optimistically check cg_list before taking
4957 if (!list_empty(&tsk->cg_list)) {
4958 write_lock(&css_set_lock);
4959 if (!list_empty(&tsk->cg_list))
4960 list_del_init(&tsk->cg_list);
4961 write_unlock(&css_set_lock);
4964 /* Reassign the task to the init_css_set. */
4967 tsk->cgroups = &init_css_set;
4969 if (run_callbacks && need_forkexit_callback) {
4971 * modular subsystems can't use callbacks, so no need to lock
4974 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4975 struct cgroup_subsys *ss = subsys[i];
4977 struct cgroup *old_cgrp =
4978 rcu_dereference_raw(cg->subsys[i])->cgroup;
4979 struct cgroup *cgrp = task_cgroup(tsk, i);
4980 ss->exit(cgrp, old_cgrp, tsk);
4987 put_css_set_taskexit(cg);
4991 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
4992 * @cgrp: the cgroup in question
4993 * @task: the task in question
4995 * See if @cgrp is a descendant of @task's cgroup in the appropriate
4998 * If we are sending in dummytop, then presumably we are creating
4999 * the top cgroup in the subsystem.
5001 * Called only by the ns (nsproxy) cgroup.
5003 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
5006 struct cgroup *target;
5008 if (cgrp == dummytop)
5011 target = task_cgroup_from_root(task, cgrp->root);
5012 while (cgrp != target && cgrp!= cgrp->top_cgroup)
5013 cgrp = cgrp->parent;
5014 ret = (cgrp == target);
5018 static void check_for_release(struct cgroup *cgrp)
5020 /* All of these checks rely on RCU to keep the cgroup
5021 * structure alive */
5022 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
5023 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
5024 /* Control Group is currently removeable. If it's not
5025 * already queued for a userspace notification, queue
5027 int need_schedule_work = 0;
5028 raw_spin_lock(&release_list_lock);
5029 if (!cgroup_is_removed(cgrp) &&
5030 list_empty(&cgrp->release_list)) {
5031 list_add(&cgrp->release_list, &release_list);
5032 need_schedule_work = 1;
5034 raw_spin_unlock(&release_list_lock);
5035 if (need_schedule_work)
5036 schedule_work(&release_agent_work);
5040 /* Caller must verify that the css is not for root cgroup */
5041 bool __css_tryget(struct cgroup_subsys_state *css)
5044 int v = css_refcnt(css);
5046 if (atomic_cmpxchg(&css->refcnt, v, v + 1) == v)
5049 } while (!test_bit(CSS_REMOVED, &css->flags));
5053 EXPORT_SYMBOL_GPL(__css_tryget);
5055 /* Caller must verify that the css is not for root cgroup */
5056 void __css_put(struct cgroup_subsys_state *css)
5058 struct cgroup *cgrp = css->cgroup;
5062 v = css_unbias_refcnt(atomic_dec_return(&css->refcnt));
5066 if (notify_on_release(cgrp)) {
5067 set_bit(CGRP_RELEASABLE, &cgrp->flags);
5068 check_for_release(cgrp);
5070 cgroup_wakeup_rmdir_waiter(cgrp);
5073 if (!test_bit(CSS_CLEAR_CSS_REFS, &css->flags))
5074 schedule_work(&css->dput_work);
5079 EXPORT_SYMBOL_GPL(__css_put);
5082 * Notify userspace when a cgroup is released, by running the
5083 * configured release agent with the name of the cgroup (path
5084 * relative to the root of cgroup file system) as the argument.
5086 * Most likely, this user command will try to rmdir this cgroup.
5088 * This races with the possibility that some other task will be
5089 * attached to this cgroup before it is removed, or that some other
5090 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5091 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5092 * unused, and this cgroup will be reprieved from its death sentence,
5093 * to continue to serve a useful existence. Next time it's released,
5094 * we will get notified again, if it still has 'notify_on_release' set.
5096 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5097 * means only wait until the task is successfully execve()'d. The
5098 * separate release agent task is forked by call_usermodehelper(),
5099 * then control in this thread returns here, without waiting for the
5100 * release agent task. We don't bother to wait because the caller of
5101 * this routine has no use for the exit status of the release agent
5102 * task, so no sense holding our caller up for that.
5104 static void cgroup_release_agent(struct work_struct *work)
5106 BUG_ON(work != &release_agent_work);
5107 mutex_lock(&cgroup_mutex);
5108 raw_spin_lock(&release_list_lock);
5109 while (!list_empty(&release_list)) {
5110 char *argv[3], *envp[3];
5112 char *pathbuf = NULL, *agentbuf = NULL;
5113 struct cgroup *cgrp = list_entry(release_list.next,
5116 list_del_init(&cgrp->release_list);
5117 raw_spin_unlock(&release_list_lock);
5118 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5121 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5123 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5128 argv[i++] = agentbuf;
5129 argv[i++] = pathbuf;
5133 /* minimal command environment */
5134 envp[i++] = "HOME=/";
5135 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5138 /* Drop the lock while we invoke the usermode helper,
5139 * since the exec could involve hitting disk and hence
5140 * be a slow process */
5141 mutex_unlock(&cgroup_mutex);
5142 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5143 mutex_lock(&cgroup_mutex);
5147 raw_spin_lock(&release_list_lock);
5149 raw_spin_unlock(&release_list_lock);
5150 mutex_unlock(&cgroup_mutex);
5153 static int __init cgroup_disable(char *str)
5158 while ((token = strsep(&str, ",")) != NULL) {
5162 * cgroup_disable, being at boot time, can't know about module
5163 * subsystems, so we don't worry about them.
5165 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
5166 struct cgroup_subsys *ss = subsys[i];
5168 if (!strcmp(token, ss->name)) {
5170 printk(KERN_INFO "Disabling %s control group"
5171 " subsystem\n", ss->name);
5178 __setup("cgroup_disable=", cgroup_disable);
5181 * Functons for CSS ID.
5185 *To get ID other than 0, this should be called when !cgroup_is_removed().
5187 unsigned short css_id(struct cgroup_subsys_state *css)
5189 struct css_id *cssid;
5192 * This css_id() can return correct value when somone has refcnt
5193 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5194 * it's unchanged until freed.
5196 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5202 EXPORT_SYMBOL_GPL(css_id);
5204 unsigned short css_depth(struct cgroup_subsys_state *css)
5206 struct css_id *cssid;
5208 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5211 return cssid->depth;
5214 EXPORT_SYMBOL_GPL(css_depth);
5217 * css_is_ancestor - test "root" css is an ancestor of "child"
5218 * @child: the css to be tested.
5219 * @root: the css supporsed to be an ancestor of the child.
5221 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5222 * this function reads css->id, the caller must hold rcu_read_lock().
5223 * But, considering usual usage, the csses should be valid objects after test.
5224 * Assuming that the caller will do some action to the child if this returns
5225 * returns true, the caller must take "child";s reference count.
5226 * If "child" is valid object and this returns true, "root" is valid, too.
5229 bool css_is_ancestor(struct cgroup_subsys_state *child,
5230 const struct cgroup_subsys_state *root)
5232 struct css_id *child_id;
5233 struct css_id *root_id;
5235 child_id = rcu_dereference(child->id);
5238 root_id = rcu_dereference(root->id);
5241 if (child_id->depth < root_id->depth)
5243 if (child_id->stack[root_id->depth] != root_id->id)
5248 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5250 struct css_id *id = css->id;
5251 /* When this is called before css_id initialization, id can be NULL */
5255 BUG_ON(!ss->use_id);
5257 rcu_assign_pointer(id->css, NULL);
5258 rcu_assign_pointer(css->id, NULL);
5259 spin_lock(&ss->id_lock);
5260 idr_remove(&ss->idr, id->id);
5261 spin_unlock(&ss->id_lock);
5262 kfree_rcu(id, rcu_head);
5264 EXPORT_SYMBOL_GPL(free_css_id);
5267 * This is called by init or create(). Then, calls to this function are
5268 * always serialized (By cgroup_mutex() at create()).
5271 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5273 struct css_id *newid;
5274 int myid, error, size;
5276 BUG_ON(!ss->use_id);
5278 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5279 newid = kzalloc(size, GFP_KERNEL);
5281 return ERR_PTR(-ENOMEM);
5283 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
5287 spin_lock(&ss->id_lock);
5288 /* Don't use 0. allocates an ID of 1-65535 */
5289 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
5290 spin_unlock(&ss->id_lock);
5292 /* Returns error when there are no free spaces for new ID.*/
5297 if (myid > CSS_ID_MAX)
5301 newid->depth = depth;
5305 spin_lock(&ss->id_lock);
5306 idr_remove(&ss->idr, myid);
5307 spin_unlock(&ss->id_lock);
5310 return ERR_PTR(error);
5314 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5315 struct cgroup_subsys_state *rootcss)
5317 struct css_id *newid;
5319 spin_lock_init(&ss->id_lock);
5322 newid = get_new_cssid(ss, 0);
5324 return PTR_ERR(newid);
5326 newid->stack[0] = newid->id;
5327 newid->css = rootcss;
5328 rootcss->id = newid;
5332 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5333 struct cgroup *child)
5335 int subsys_id, i, depth = 0;
5336 struct cgroup_subsys_state *parent_css, *child_css;
5337 struct css_id *child_id, *parent_id;
5339 subsys_id = ss->subsys_id;
5340 parent_css = parent->subsys[subsys_id];
5341 child_css = child->subsys[subsys_id];
5342 parent_id = parent_css->id;
5343 depth = parent_id->depth + 1;
5345 child_id = get_new_cssid(ss, depth);
5346 if (IS_ERR(child_id))
5347 return PTR_ERR(child_id);
5349 for (i = 0; i < depth; i++)
5350 child_id->stack[i] = parent_id->stack[i];
5351 child_id->stack[depth] = child_id->id;
5353 * child_id->css pointer will be set after this cgroup is available
5354 * see cgroup_populate_dir()
5356 rcu_assign_pointer(child_css->id, child_id);
5362 * css_lookup - lookup css by id
5363 * @ss: cgroup subsys to be looked into.
5366 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5367 * NULL if not. Should be called under rcu_read_lock()
5369 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5371 struct css_id *cssid = NULL;
5373 BUG_ON(!ss->use_id);
5374 cssid = idr_find(&ss->idr, id);
5376 if (unlikely(!cssid))
5379 return rcu_dereference(cssid->css);
5381 EXPORT_SYMBOL_GPL(css_lookup);
5384 * css_get_next - lookup next cgroup under specified hierarchy.
5385 * @ss: pointer to subsystem
5386 * @id: current position of iteration.
5387 * @root: pointer to css. search tree under this.
5388 * @foundid: position of found object.
5390 * Search next css under the specified hierarchy of rootid. Calling under
5391 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
5393 struct cgroup_subsys_state *
5394 css_get_next(struct cgroup_subsys *ss, int id,
5395 struct cgroup_subsys_state *root, int *foundid)
5397 struct cgroup_subsys_state *ret = NULL;
5400 int rootid = css_id(root);
5401 int depth = css_depth(root);
5406 BUG_ON(!ss->use_id);
5407 WARN_ON_ONCE(!rcu_read_lock_held());
5409 /* fill start point for scan */
5413 * scan next entry from bitmap(tree), tmpid is updated after
5416 tmp = idr_get_next(&ss->idr, &tmpid);
5419 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
5420 ret = rcu_dereference(tmp->css);
5426 /* continue to scan from next id */
5433 * get corresponding css from file open on cgroupfs directory
5435 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5437 struct cgroup *cgrp;
5438 struct inode *inode;
5439 struct cgroup_subsys_state *css;
5441 inode = f->f_dentry->d_inode;
5442 /* check in cgroup filesystem dir */
5443 if (inode->i_op != &cgroup_dir_inode_operations)
5444 return ERR_PTR(-EBADF);
5446 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5447 return ERR_PTR(-EINVAL);
5450 cgrp = __d_cgrp(f->f_dentry);
5451 css = cgrp->subsys[id];
5452 return css ? css : ERR_PTR(-ENOENT);
5455 #ifdef CONFIG_CGROUP_DEBUG
5456 static struct cgroup_subsys_state *debug_create(struct cgroup *cont)
5458 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5461 return ERR_PTR(-ENOMEM);
5466 static void debug_destroy(struct cgroup *cont)
5468 kfree(cont->subsys[debug_subsys_id]);
5471 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
5473 return atomic_read(&cont->count);
5476 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5478 return cgroup_task_count(cont);
5481 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5483 return (u64)(unsigned long)current->cgroups;
5486 static u64 current_css_set_refcount_read(struct cgroup *cont,
5492 count = atomic_read(¤t->cgroups->refcount);
5497 static int current_css_set_cg_links_read(struct cgroup *cont,
5499 struct seq_file *seq)
5501 struct cg_cgroup_link *link;
5504 read_lock(&css_set_lock);
5506 cg = rcu_dereference(current->cgroups);
5507 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
5508 struct cgroup *c = link->cgrp;
5512 name = c->dentry->d_name.name;
5515 seq_printf(seq, "Root %d group %s\n",
5516 c->root->hierarchy_id, name);
5519 read_unlock(&css_set_lock);
5523 #define MAX_TASKS_SHOWN_PER_CSS 25
5524 static int cgroup_css_links_read(struct cgroup *cont,
5526 struct seq_file *seq)
5528 struct cg_cgroup_link *link;
5530 read_lock(&css_set_lock);
5531 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
5532 struct css_set *cg = link->cg;
5533 struct task_struct *task;
5535 seq_printf(seq, "css_set %p\n", cg);
5536 list_for_each_entry(task, &cg->tasks, cg_list) {
5537 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5538 seq_puts(seq, " ...\n");
5541 seq_printf(seq, " task %d\n",
5542 task_pid_vnr(task));
5546 read_unlock(&css_set_lock);
5550 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5552 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5555 static struct cftype debug_files[] = {
5557 .name = "cgroup_refcount",
5558 .read_u64 = cgroup_refcount_read,
5561 .name = "taskcount",
5562 .read_u64 = debug_taskcount_read,
5566 .name = "current_css_set",
5567 .read_u64 = current_css_set_read,
5571 .name = "current_css_set_refcount",
5572 .read_u64 = current_css_set_refcount_read,
5576 .name = "current_css_set_cg_links",
5577 .read_seq_string = current_css_set_cg_links_read,
5581 .name = "cgroup_css_links",
5582 .read_seq_string = cgroup_css_links_read,
5586 .name = "releasable",
5587 .read_u64 = releasable_read,
5593 struct cgroup_subsys debug_subsys = {
5595 .create = debug_create,
5596 .destroy = debug_destroy,
5597 .subsys_id = debug_subsys_id,
5598 .base_cftypes = debug_files,
5600 #endif /* CONFIG_CGROUP_DEBUG */