2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/backing-dev.h>
44 #include <linux/seq_file.h>
45 #include <linux/slab.h>
46 #include <linux/magic.h>
47 #include <linux/spinlock.h>
48 #include <linux/string.h>
49 #include <linux/sort.h>
50 #include <linux/kmod.h>
51 #include <linux/module.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hashtable.h>
55 #include <linux/namei.h>
56 #include <linux/pid_namespace.h>
57 #include <linux/idr.h>
58 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
59 #include <linux/eventfd.h>
60 #include <linux/poll.h>
61 #include <linux/flex_array.h> /* used in cgroup_attach_task */
62 #include <linux/kthread.h>
64 #include <linux/atomic.h>
66 /* css deactivation bias, makes css->refcnt negative to deny new trygets */
67 #define CSS_DEACT_BIAS INT_MIN
70 * cgroup_mutex is the master lock. Any modification to cgroup or its
71 * hierarchy must be performed while holding it.
73 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
74 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
75 * release_agent_path and so on. Modifying requires both cgroup_mutex and
76 * cgroup_root_mutex. Readers can acquire either of the two. This is to
77 * break the following locking order cycle.
79 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
80 * B. namespace_sem -> cgroup_mutex
82 * B happens only through cgroup_show_options() and using cgroup_root_mutex
85 #ifdef CONFIG_PROVE_RCU
86 DEFINE_MUTEX(cgroup_mutex);
87 EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for task_subsys_state_check() */
89 static DEFINE_MUTEX(cgroup_mutex);
92 static DEFINE_MUTEX(cgroup_root_mutex);
95 * Generate an array of cgroup subsystem pointers. At boot time, this is
96 * populated with the built in subsystems, and modular subsystems are
97 * registered after that. The mutable section of this array is protected by
100 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
101 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
102 static struct cgroup_subsys *subsys[CGROUP_SUBSYS_COUNT] = {
103 #include <linux/cgroup_subsys.h>
107 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
108 * subsystems that are otherwise unattached - it never has more than a
109 * single cgroup, and all tasks are part of that cgroup.
111 static struct cgroupfs_root rootnode;
114 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
117 struct list_head node;
118 struct dentry *dentry;
123 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
124 * cgroup_subsys->use_id != 0.
126 #define CSS_ID_MAX (65535)
129 * The css to which this ID points. This pointer is set to valid value
130 * after cgroup is populated. If cgroup is removed, this will be NULL.
131 * This pointer is expected to be RCU-safe because destroy()
132 * is called after synchronize_rcu(). But for safe use, css_tryget()
133 * should be used for avoiding race.
135 struct cgroup_subsys_state __rcu *css;
141 * Depth in hierarchy which this ID belongs to.
143 unsigned short depth;
145 * ID is freed by RCU. (and lookup routine is RCU safe.)
147 struct rcu_head rcu_head;
149 * Hierarchy of CSS ID belongs to.
151 unsigned short stack[0]; /* Array of Length (depth+1) */
155 * cgroup_event represents events which userspace want to receive.
157 struct cgroup_event {
159 * Cgroup which the event belongs to.
163 * Control file which the event associated.
167 * eventfd to signal userspace about the event.
169 struct eventfd_ctx *eventfd;
171 * Each of these stored in a list by the cgroup.
173 struct list_head list;
175 * All fields below needed to unregister event when
176 * userspace closes eventfd.
179 wait_queue_head_t *wqh;
181 struct work_struct remove;
184 /* The list of hierarchy roots */
186 static LIST_HEAD(roots);
187 static int root_count;
189 static DEFINE_IDA(hierarchy_ida);
190 static int next_hierarchy_id;
191 static DEFINE_SPINLOCK(hierarchy_id_lock);
193 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
194 #define dummytop (&rootnode.top_cgroup)
196 static struct cgroup_name root_cgroup_name = { .name = "/" };
198 /* This flag indicates whether tasks in the fork and exit paths should
199 * check for fork/exit handlers to call. This avoids us having to do
200 * extra work in the fork/exit path if none of the subsystems need to
203 static int need_forkexit_callback __read_mostly;
205 static int cgroup_destroy_locked(struct cgroup *cgrp);
206 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
207 struct cftype cfts[], bool is_add);
209 static int css_unbias_refcnt(int refcnt)
211 return refcnt >= 0 ? refcnt : refcnt - CSS_DEACT_BIAS;
214 /* the current nr of refs, always >= 0 whether @css is deactivated or not */
215 static int css_refcnt(struct cgroup_subsys_state *css)
217 int v = atomic_read(&css->refcnt);
219 return css_unbias_refcnt(v);
222 /* convenient tests for these bits */
223 inline int cgroup_is_removed(const struct cgroup *cgrp)
225 return test_bit(CGRP_REMOVED, &cgrp->flags);
229 * cgroup_is_descendant - test ancestry
230 * @cgrp: the cgroup to be tested
231 * @ancestor: possible ancestor of @cgrp
233 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
234 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
235 * and @ancestor are accessible.
237 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
240 if (cgrp == ancestor)
246 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
248 static int cgroup_is_releasable(const struct cgroup *cgrp)
251 (1 << CGRP_RELEASABLE) |
252 (1 << CGRP_NOTIFY_ON_RELEASE);
253 return (cgrp->flags & bits) == bits;
256 static int notify_on_release(const struct cgroup *cgrp)
258 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
262 * for_each_subsys() allows you to iterate on each subsystem attached to
263 * an active hierarchy
265 #define for_each_subsys(_root, _ss) \
266 list_for_each_entry(_ss, &_root->subsys_list, sibling)
268 /* for_each_active_root() allows you to iterate across the active hierarchies */
269 #define for_each_active_root(_root) \
270 list_for_each_entry(_root, &roots, root_list)
272 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
274 return dentry->d_fsdata;
277 static inline struct cfent *__d_cfe(struct dentry *dentry)
279 return dentry->d_fsdata;
282 static inline struct cftype *__d_cft(struct dentry *dentry)
284 return __d_cfe(dentry)->type;
288 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
289 * @cgrp: the cgroup to be checked for liveness
291 * On success, returns true; the mutex should be later unlocked. On
292 * failure returns false with no lock held.
294 static bool cgroup_lock_live_group(struct cgroup *cgrp)
296 mutex_lock(&cgroup_mutex);
297 if (cgroup_is_removed(cgrp)) {
298 mutex_unlock(&cgroup_mutex);
304 /* the list of cgroups eligible for automatic release. Protected by
305 * release_list_lock */
306 static LIST_HEAD(release_list);
307 static DEFINE_RAW_SPINLOCK(release_list_lock);
308 static void cgroup_release_agent(struct work_struct *work);
309 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
310 static void check_for_release(struct cgroup *cgrp);
312 /* Link structure for associating css_set objects with cgroups */
313 struct cg_cgroup_link {
315 * List running through cg_cgroup_links associated with a
316 * cgroup, anchored on cgroup->css_sets
318 struct list_head cgrp_link_list;
321 * List running through cg_cgroup_links pointing at a
322 * single css_set object, anchored on css_set->cg_links
324 struct list_head cg_link_list;
328 /* The default css_set - used by init and its children prior to any
329 * hierarchies being mounted. It contains a pointer to the root state
330 * for each subsystem. Also used to anchor the list of css_sets. Not
331 * reference-counted, to improve performance when child cgroups
332 * haven't been created.
335 static struct css_set init_css_set;
336 static struct cg_cgroup_link init_css_set_link;
338 static int cgroup_init_idr(struct cgroup_subsys *ss,
339 struct cgroup_subsys_state *css);
341 /* css_set_lock protects the list of css_set objects, and the
342 * chain of tasks off each css_set. Nests outside task->alloc_lock
343 * due to cgroup_iter_start() */
344 static DEFINE_RWLOCK(css_set_lock);
345 static int css_set_count;
348 * hash table for cgroup groups. This improves the performance to find
349 * an existing css_set. This hash doesn't (currently) take into
350 * account cgroups in empty hierarchies.
352 #define CSS_SET_HASH_BITS 7
353 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
355 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
358 unsigned long key = 0UL;
360 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
361 key += (unsigned long)css[i];
362 key = (key >> 16) ^ key;
367 /* We don't maintain the lists running through each css_set to its
368 * task until after the first call to cgroup_iter_start(). This
369 * reduces the fork()/exit() overhead for people who have cgroups
370 * compiled into their kernel but not actually in use */
371 static int use_task_css_set_links __read_mostly;
373 static void __put_css_set(struct css_set *cg, int taskexit)
375 struct cg_cgroup_link *link;
376 struct cg_cgroup_link *saved_link;
378 * Ensure that the refcount doesn't hit zero while any readers
379 * can see it. Similar to atomic_dec_and_lock(), but for an
382 if (atomic_add_unless(&cg->refcount, -1, 1))
384 write_lock(&css_set_lock);
385 if (!atomic_dec_and_test(&cg->refcount)) {
386 write_unlock(&css_set_lock);
390 /* This css_set is dead. unlink it and release cgroup refcounts */
391 hash_del(&cg->hlist);
394 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
396 struct cgroup *cgrp = link->cgrp;
397 list_del(&link->cg_link_list);
398 list_del(&link->cgrp_link_list);
401 * We may not be holding cgroup_mutex, and if cgrp->count is
402 * dropped to 0 the cgroup can be destroyed at any time, hence
403 * rcu_read_lock is used to keep it alive.
406 if (atomic_dec_and_test(&cgrp->count) &&
407 notify_on_release(cgrp)) {
409 set_bit(CGRP_RELEASABLE, &cgrp->flags);
410 check_for_release(cgrp);
417 write_unlock(&css_set_lock);
418 kfree_rcu(cg, rcu_head);
422 * refcounted get/put for css_set objects
424 static inline void get_css_set(struct css_set *cg)
426 atomic_inc(&cg->refcount);
429 static inline void put_css_set(struct css_set *cg)
431 __put_css_set(cg, 0);
434 static inline void put_css_set_taskexit(struct css_set *cg)
436 __put_css_set(cg, 1);
440 * compare_css_sets - helper function for find_existing_css_set().
441 * @cg: candidate css_set being tested
442 * @old_cg: existing css_set for a task
443 * @new_cgrp: cgroup that's being entered by the task
444 * @template: desired set of css pointers in css_set (pre-calculated)
446 * Returns true if "cg" matches "old_cg" except for the hierarchy
447 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
449 static bool compare_css_sets(struct css_set *cg,
450 struct css_set *old_cg,
451 struct cgroup *new_cgrp,
452 struct cgroup_subsys_state *template[])
454 struct list_head *l1, *l2;
456 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
457 /* Not all subsystems matched */
462 * Compare cgroup pointers in order to distinguish between
463 * different cgroups in heirarchies with no subsystems. We
464 * could get by with just this check alone (and skip the
465 * memcmp above) but on most setups the memcmp check will
466 * avoid the need for this more expensive check on almost all
471 l2 = &old_cg->cg_links;
473 struct cg_cgroup_link *cgl1, *cgl2;
474 struct cgroup *cg1, *cg2;
478 /* See if we reached the end - both lists are equal length. */
479 if (l1 == &cg->cg_links) {
480 BUG_ON(l2 != &old_cg->cg_links);
483 BUG_ON(l2 == &old_cg->cg_links);
485 /* Locate the cgroups associated with these links. */
486 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
487 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
490 /* Hierarchies should be linked in the same order. */
491 BUG_ON(cg1->root != cg2->root);
494 * If this hierarchy is the hierarchy of the cgroup
495 * that's changing, then we need to check that this
496 * css_set points to the new cgroup; if it's any other
497 * hierarchy, then this css_set should point to the
498 * same cgroup as the old css_set.
500 if (cg1->root == new_cgrp->root) {
512 * find_existing_css_set() is a helper for
513 * find_css_set(), and checks to see whether an existing
514 * css_set is suitable.
516 * oldcg: the cgroup group that we're using before the cgroup
519 * cgrp: the cgroup that we're moving into
521 * template: location in which to build the desired set of subsystem
522 * state objects for the new cgroup group
524 static struct css_set *find_existing_css_set(
525 struct css_set *oldcg,
527 struct cgroup_subsys_state *template[])
530 struct cgroupfs_root *root = cgrp->root;
535 * Build the set of subsystem state objects that we want to see in the
536 * new css_set. while subsystems can change globally, the entries here
537 * won't change, so no need for locking.
539 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
540 if (root->subsys_mask & (1UL << i)) {
541 /* Subsystem is in this hierarchy. So we want
542 * the subsystem state from the new
544 template[i] = cgrp->subsys[i];
546 /* Subsystem is not in this hierarchy, so we
547 * don't want to change the subsystem state */
548 template[i] = oldcg->subsys[i];
552 key = css_set_hash(template);
553 hash_for_each_possible(css_set_table, cg, hlist, key) {
554 if (!compare_css_sets(cg, oldcg, cgrp, template))
557 /* This css_set matches what we need */
561 /* No existing cgroup group matched */
565 static void free_cg_links(struct list_head *tmp)
567 struct cg_cgroup_link *link;
568 struct cg_cgroup_link *saved_link;
570 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
571 list_del(&link->cgrp_link_list);
577 * allocate_cg_links() allocates "count" cg_cgroup_link structures
578 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
579 * success or a negative error
581 static int allocate_cg_links(int count, struct list_head *tmp)
583 struct cg_cgroup_link *link;
586 for (i = 0; i < count; i++) {
587 link = kmalloc(sizeof(*link), GFP_KERNEL);
592 list_add(&link->cgrp_link_list, tmp);
598 * link_css_set - a helper function to link a css_set to a cgroup
599 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
600 * @cg: the css_set to be linked
601 * @cgrp: the destination cgroup
603 static void link_css_set(struct list_head *tmp_cg_links,
604 struct css_set *cg, struct cgroup *cgrp)
606 struct cg_cgroup_link *link;
608 BUG_ON(list_empty(tmp_cg_links));
609 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
613 atomic_inc(&cgrp->count);
614 list_move(&link->cgrp_link_list, &cgrp->css_sets);
616 * Always add links to the tail of the list so that the list
617 * is sorted by order of hierarchy creation
619 list_add_tail(&link->cg_link_list, &cg->cg_links);
623 * find_css_set() takes an existing cgroup group and a
624 * cgroup object, and returns a css_set object that's
625 * equivalent to the old group, but with the given cgroup
626 * substituted into the appropriate hierarchy. Must be called with
629 static struct css_set *find_css_set(
630 struct css_set *oldcg, struct cgroup *cgrp)
633 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
635 struct list_head tmp_cg_links;
637 struct cg_cgroup_link *link;
640 /* First see if we already have a cgroup group that matches
642 read_lock(&css_set_lock);
643 res = find_existing_css_set(oldcg, cgrp, template);
646 read_unlock(&css_set_lock);
651 res = kmalloc(sizeof(*res), GFP_KERNEL);
655 /* Allocate all the cg_cgroup_link objects that we'll need */
656 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
661 atomic_set(&res->refcount, 1);
662 INIT_LIST_HEAD(&res->cg_links);
663 INIT_LIST_HEAD(&res->tasks);
664 INIT_HLIST_NODE(&res->hlist);
666 /* Copy the set of subsystem state objects generated in
667 * find_existing_css_set() */
668 memcpy(res->subsys, template, sizeof(res->subsys));
670 write_lock(&css_set_lock);
671 /* Add reference counts and links from the new css_set. */
672 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
673 struct cgroup *c = link->cgrp;
674 if (c->root == cgrp->root)
676 link_css_set(&tmp_cg_links, res, c);
679 BUG_ON(!list_empty(&tmp_cg_links));
683 /* Add this cgroup group to the hash table */
684 key = css_set_hash(res->subsys);
685 hash_add(css_set_table, &res->hlist, key);
687 write_unlock(&css_set_lock);
693 * Return the cgroup for "task" from the given hierarchy. Must be
694 * called with cgroup_mutex held.
696 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
697 struct cgroupfs_root *root)
700 struct cgroup *res = NULL;
702 BUG_ON(!mutex_is_locked(&cgroup_mutex));
703 read_lock(&css_set_lock);
705 * No need to lock the task - since we hold cgroup_mutex the
706 * task can't change groups, so the only thing that can happen
707 * is that it exits and its css is set back to init_css_set.
710 if (css == &init_css_set) {
711 res = &root->top_cgroup;
713 struct cg_cgroup_link *link;
714 list_for_each_entry(link, &css->cg_links, cg_link_list) {
715 struct cgroup *c = link->cgrp;
716 if (c->root == root) {
722 read_unlock(&css_set_lock);
728 * There is one global cgroup mutex. We also require taking
729 * task_lock() when dereferencing a task's cgroup subsys pointers.
730 * See "The task_lock() exception", at the end of this comment.
732 * A task must hold cgroup_mutex to modify cgroups.
734 * Any task can increment and decrement the count field without lock.
735 * So in general, code holding cgroup_mutex can't rely on the count
736 * field not changing. However, if the count goes to zero, then only
737 * cgroup_attach_task() can increment it again. Because a count of zero
738 * means that no tasks are currently attached, therefore there is no
739 * way a task attached to that cgroup can fork (the other way to
740 * increment the count). So code holding cgroup_mutex can safely
741 * assume that if the count is zero, it will stay zero. Similarly, if
742 * a task holds cgroup_mutex on a cgroup with zero count, it
743 * knows that the cgroup won't be removed, as cgroup_rmdir()
746 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
747 * (usually) take cgroup_mutex. These are the two most performance
748 * critical pieces of code here. The exception occurs on cgroup_exit(),
749 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
750 * is taken, and if the cgroup count is zero, a usermode call made
751 * to the release agent with the name of the cgroup (path relative to
752 * the root of cgroup file system) as the argument.
754 * A cgroup can only be deleted if both its 'count' of using tasks
755 * is zero, and its list of 'children' cgroups is empty. Since all
756 * tasks in the system use _some_ cgroup, and since there is always at
757 * least one task in the system (init, pid == 1), therefore, top_cgroup
758 * always has either children cgroups and/or using tasks. So we don't
759 * need a special hack to ensure that top_cgroup cannot be deleted.
761 * The task_lock() exception
763 * The need for this exception arises from the action of
764 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
765 * another. It does so using cgroup_mutex, however there are
766 * several performance critical places that need to reference
767 * task->cgroup without the expense of grabbing a system global
768 * mutex. Therefore except as noted below, when dereferencing or, as
769 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
770 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
771 * the task_struct routinely used for such matters.
773 * P.S. One more locking exception. RCU is used to guard the
774 * update of a tasks cgroup pointer by cgroup_attach_task()
778 * A couple of forward declarations required, due to cyclic reference loop:
779 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
780 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
784 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
785 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
786 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
787 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
788 unsigned long subsys_mask);
789 static const struct inode_operations cgroup_dir_inode_operations;
790 static const struct file_operations proc_cgroupstats_operations;
792 static struct backing_dev_info cgroup_backing_dev_info = {
794 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
797 static int alloc_css_id(struct cgroup_subsys *ss,
798 struct cgroup *parent, struct cgroup *child);
800 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
802 struct inode *inode = new_inode(sb);
805 inode->i_ino = get_next_ino();
806 inode->i_mode = mode;
807 inode->i_uid = current_fsuid();
808 inode->i_gid = current_fsgid();
809 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
810 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
815 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
817 struct cgroup_name *name;
819 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
822 strcpy(name->name, dentry->d_name.name);
826 static void cgroup_free_fn(struct work_struct *work)
828 struct cgroup *cgrp = container_of(work, struct cgroup, free_work);
829 struct cgroup_subsys *ss;
831 mutex_lock(&cgroup_mutex);
833 * Release the subsystem state objects.
835 for_each_subsys(cgrp->root, ss)
838 cgrp->root->number_of_cgroups--;
839 mutex_unlock(&cgroup_mutex);
842 * We get a ref to the parent's dentry, and put the ref when
843 * this cgroup is being freed, so it's guaranteed that the
844 * parent won't be destroyed before its children.
846 dput(cgrp->parent->dentry);
849 * Drop the active superblock reference that we took when we
852 deactivate_super(cgrp->root->sb);
855 * if we're getting rid of the cgroup, refcount should ensure
856 * that there are no pidlists left.
858 BUG_ON(!list_empty(&cgrp->pidlists));
860 simple_xattrs_free(&cgrp->xattrs);
862 ida_simple_remove(&cgrp->root->cgroup_ida, cgrp->id);
863 kfree(rcu_dereference_raw(cgrp->name));
867 static void cgroup_free_rcu(struct rcu_head *head)
869 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
871 schedule_work(&cgrp->free_work);
874 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
876 /* is dentry a directory ? if so, kfree() associated cgroup */
877 if (S_ISDIR(inode->i_mode)) {
878 struct cgroup *cgrp = dentry->d_fsdata;
880 BUG_ON(!(cgroup_is_removed(cgrp)));
881 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
883 struct cfent *cfe = __d_cfe(dentry);
884 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
885 struct cftype *cft = cfe->type;
887 WARN_ONCE(!list_empty(&cfe->node) &&
888 cgrp != &cgrp->root->top_cgroup,
889 "cfe still linked for %s\n", cfe->type->name);
891 simple_xattrs_free(&cft->xattrs);
896 static int cgroup_delete(const struct dentry *d)
901 static void remove_dir(struct dentry *d)
903 struct dentry *parent = dget(d->d_parent);
906 simple_rmdir(parent->d_inode, d);
910 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
914 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
915 lockdep_assert_held(&cgroup_mutex);
918 * If we're doing cleanup due to failure of cgroup_create(),
919 * the corresponding @cfe may not exist.
921 list_for_each_entry(cfe, &cgrp->files, node) {
922 struct dentry *d = cfe->dentry;
924 if (cft && cfe->type != cft)
929 simple_unlink(cgrp->dentry->d_inode, d);
930 list_del_init(&cfe->node);
938 * cgroup_clear_directory - selective removal of base and subsystem files
939 * @dir: directory containing the files
940 * @base_files: true if the base files should be removed
941 * @subsys_mask: mask of the subsystem ids whose files should be removed
943 static void cgroup_clear_directory(struct dentry *dir, bool base_files,
944 unsigned long subsys_mask)
946 struct cgroup *cgrp = __d_cgrp(dir);
947 struct cgroup_subsys *ss;
949 for_each_subsys(cgrp->root, ss) {
950 struct cftype_set *set;
951 if (!test_bit(ss->subsys_id, &subsys_mask))
953 list_for_each_entry(set, &ss->cftsets, node)
954 cgroup_addrm_files(cgrp, NULL, set->cfts, false);
957 while (!list_empty(&cgrp->files))
958 cgroup_rm_file(cgrp, NULL);
963 * NOTE : the dentry must have been dget()'ed
965 static void cgroup_d_remove_dir(struct dentry *dentry)
967 struct dentry *parent;
968 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
970 cgroup_clear_directory(dentry, true, root->subsys_mask);
972 parent = dentry->d_parent;
973 spin_lock(&parent->d_lock);
974 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
975 list_del_init(&dentry->d_u.d_child);
976 spin_unlock(&dentry->d_lock);
977 spin_unlock(&parent->d_lock);
982 * Call with cgroup_mutex held. Drops reference counts on modules, including
983 * any duplicate ones that parse_cgroupfs_options took. If this function
984 * returns an error, no reference counts are touched.
986 static int rebind_subsystems(struct cgroupfs_root *root,
987 unsigned long final_subsys_mask)
989 unsigned long added_mask, removed_mask;
990 struct cgroup *cgrp = &root->top_cgroup;
993 BUG_ON(!mutex_is_locked(&cgroup_mutex));
994 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
996 removed_mask = root->actual_subsys_mask & ~final_subsys_mask;
997 added_mask = final_subsys_mask & ~root->actual_subsys_mask;
998 /* Check that any added subsystems are currently free */
999 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1000 unsigned long bit = 1UL << i;
1001 struct cgroup_subsys *ss = subsys[i];
1002 if (!(bit & added_mask))
1005 * Nobody should tell us to do a subsys that doesn't exist:
1006 * parse_cgroupfs_options should catch that case and refcounts
1007 * ensure that subsystems won't disappear once selected.
1010 if (ss->root != &rootnode) {
1011 /* Subsystem isn't free */
1016 /* Currently we don't handle adding/removing subsystems when
1017 * any child cgroups exist. This is theoretically supportable
1018 * but involves complex error handling, so it's being left until
1020 if (root->number_of_cgroups > 1)
1023 /* Process each subsystem */
1024 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1025 struct cgroup_subsys *ss = subsys[i];
1026 unsigned long bit = 1UL << i;
1027 if (bit & added_mask) {
1028 /* We're binding this subsystem to this hierarchy */
1030 BUG_ON(cgrp->subsys[i]);
1031 BUG_ON(!dummytop->subsys[i]);
1032 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
1033 cgrp->subsys[i] = dummytop->subsys[i];
1034 cgrp->subsys[i]->cgroup = cgrp;
1035 list_move(&ss->sibling, &root->subsys_list);
1039 /* refcount was already taken, and we're keeping it */
1040 } else if (bit & removed_mask) {
1041 /* We're removing this subsystem */
1043 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1044 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1047 dummytop->subsys[i]->cgroup = dummytop;
1048 cgrp->subsys[i] = NULL;
1049 subsys[i]->root = &rootnode;
1050 list_move(&ss->sibling, &rootnode.subsys_list);
1051 /* subsystem is now free - drop reference on module */
1052 module_put(ss->module);
1053 } else if (bit & final_subsys_mask) {
1054 /* Subsystem state should already exist */
1056 BUG_ON(!cgrp->subsys[i]);
1058 * a refcount was taken, but we already had one, so
1059 * drop the extra reference.
1061 module_put(ss->module);
1062 #ifdef CONFIG_MODULE_UNLOAD
1063 BUG_ON(ss->module && !module_refcount(ss->module));
1066 /* Subsystem state shouldn't exist */
1067 BUG_ON(cgrp->subsys[i]);
1070 root->subsys_mask = root->actual_subsys_mask = final_subsys_mask;
1075 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1077 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1078 struct cgroup_subsys *ss;
1080 mutex_lock(&cgroup_root_mutex);
1081 for_each_subsys(root, ss)
1082 seq_printf(seq, ",%s", ss->name);
1083 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1084 seq_puts(seq, ",sane_behavior");
1085 if (root->flags & CGRP_ROOT_NOPREFIX)
1086 seq_puts(seq, ",noprefix");
1087 if (root->flags & CGRP_ROOT_XATTR)
1088 seq_puts(seq, ",xattr");
1089 if (strlen(root->release_agent_path))
1090 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1091 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1092 seq_puts(seq, ",clone_children");
1093 if (strlen(root->name))
1094 seq_printf(seq, ",name=%s", root->name);
1095 mutex_unlock(&cgroup_root_mutex);
1099 struct cgroup_sb_opts {
1100 unsigned long subsys_mask;
1101 unsigned long flags;
1102 char *release_agent;
1103 bool cpuset_clone_children;
1105 /* User explicitly requested empty subsystem */
1108 struct cgroupfs_root *new_root;
1113 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1114 * with cgroup_mutex held to protect the subsys[] array. This function takes
1115 * refcounts on subsystems to be used, unless it returns error, in which case
1116 * no refcounts are taken.
1118 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1120 char *token, *o = data;
1121 bool all_ss = false, one_ss = false;
1122 unsigned long mask = (unsigned long)-1;
1124 bool module_pin_failed = false;
1126 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1128 #ifdef CONFIG_CPUSETS
1129 mask = ~(1UL << cpuset_subsys_id);
1132 memset(opts, 0, sizeof(*opts));
1134 while ((token = strsep(&o, ",")) != NULL) {
1137 if (!strcmp(token, "none")) {
1138 /* Explicitly have no subsystems */
1142 if (!strcmp(token, "all")) {
1143 /* Mutually exclusive option 'all' + subsystem name */
1149 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1150 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1153 if (!strcmp(token, "noprefix")) {
1154 opts->flags |= CGRP_ROOT_NOPREFIX;
1157 if (!strcmp(token, "clone_children")) {
1158 opts->cpuset_clone_children = true;
1161 if (!strcmp(token, "xattr")) {
1162 opts->flags |= CGRP_ROOT_XATTR;
1165 if (!strncmp(token, "release_agent=", 14)) {
1166 /* Specifying two release agents is forbidden */
1167 if (opts->release_agent)
1169 opts->release_agent =
1170 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1171 if (!opts->release_agent)
1175 if (!strncmp(token, "name=", 5)) {
1176 const char *name = token + 5;
1177 /* Can't specify an empty name */
1180 /* Must match [\w.-]+ */
1181 for (i = 0; i < strlen(name); i++) {
1185 if ((c == '.') || (c == '-') || (c == '_'))
1189 /* Specifying two names is forbidden */
1192 opts->name = kstrndup(name,
1193 MAX_CGROUP_ROOT_NAMELEN - 1,
1201 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1202 struct cgroup_subsys *ss = subsys[i];
1205 if (strcmp(token, ss->name))
1210 /* Mutually exclusive option 'all' + subsystem name */
1213 set_bit(i, &opts->subsys_mask);
1218 if (i == CGROUP_SUBSYS_COUNT)
1223 * If the 'all' option was specified select all the subsystems,
1224 * otherwise if 'none', 'name=' and a subsystem name options
1225 * were not specified, let's default to 'all'
1227 if (all_ss || (!one_ss && !opts->none && !opts->name)) {
1228 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1229 struct cgroup_subsys *ss = subsys[i];
1234 set_bit(i, &opts->subsys_mask);
1238 /* Consistency checks */
1240 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1241 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1243 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1244 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1248 if (opts->cpuset_clone_children) {
1249 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1255 * Option noprefix was introduced just for backward compatibility
1256 * with the old cpuset, so we allow noprefix only if mounting just
1257 * the cpuset subsystem.
1259 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1263 /* Can't specify "none" and some subsystems */
1264 if (opts->subsys_mask && opts->none)
1268 * We either have to specify by name or by subsystems. (So all
1269 * empty hierarchies must have a name).
1271 if (!opts->subsys_mask && !opts->name)
1275 * Grab references on all the modules we'll need, so the subsystems
1276 * don't dance around before rebind_subsystems attaches them. This may
1277 * take duplicate reference counts on a subsystem that's already used,
1278 * but rebind_subsystems handles this case.
1280 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1281 unsigned long bit = 1UL << i;
1283 if (!(bit & opts->subsys_mask))
1285 if (!try_module_get(subsys[i]->module)) {
1286 module_pin_failed = true;
1290 if (module_pin_failed) {
1292 * oops, one of the modules was going away. this means that we
1293 * raced with a module_delete call, and to the user this is
1294 * essentially a "subsystem doesn't exist" case.
1296 for (i--; i >= 0; i--) {
1297 /* drop refcounts only on the ones we took */
1298 unsigned long bit = 1UL << i;
1300 if (!(bit & opts->subsys_mask))
1302 module_put(subsys[i]->module);
1310 static void drop_parsed_module_refcounts(unsigned long subsys_mask)
1313 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1314 unsigned long bit = 1UL << i;
1316 if (!(bit & subsys_mask))
1318 module_put(subsys[i]->module);
1322 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1325 struct cgroupfs_root *root = sb->s_fs_info;
1326 struct cgroup *cgrp = &root->top_cgroup;
1327 struct cgroup_sb_opts opts;
1328 unsigned long added_mask, removed_mask;
1330 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1331 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1335 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1336 mutex_lock(&cgroup_mutex);
1337 mutex_lock(&cgroup_root_mutex);
1339 /* See what subsystems are wanted */
1340 ret = parse_cgroupfs_options(data, &opts);
1344 if (opts.subsys_mask != root->actual_subsys_mask || opts.release_agent)
1345 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1346 task_tgid_nr(current), current->comm);
1348 added_mask = opts.subsys_mask & ~root->subsys_mask;
1349 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1351 /* Don't allow flags or name to change at remount */
1352 if (opts.flags != root->flags ||
1353 (opts.name && strcmp(opts.name, root->name))) {
1355 drop_parsed_module_refcounts(opts.subsys_mask);
1360 * Clear out the files of subsystems that should be removed, do
1361 * this before rebind_subsystems, since rebind_subsystems may
1362 * change this hierarchy's subsys_list.
1364 cgroup_clear_directory(cgrp->dentry, false, removed_mask);
1366 ret = rebind_subsystems(root, opts.subsys_mask);
1368 /* rebind_subsystems failed, re-populate the removed files */
1369 cgroup_populate_dir(cgrp, false, removed_mask);
1370 drop_parsed_module_refcounts(opts.subsys_mask);
1374 /* re-populate subsystem files */
1375 cgroup_populate_dir(cgrp, false, added_mask);
1377 if (opts.release_agent)
1378 strcpy(root->release_agent_path, opts.release_agent);
1380 kfree(opts.release_agent);
1382 mutex_unlock(&cgroup_root_mutex);
1383 mutex_unlock(&cgroup_mutex);
1384 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1388 static const struct super_operations cgroup_ops = {
1389 .statfs = simple_statfs,
1390 .drop_inode = generic_delete_inode,
1391 .show_options = cgroup_show_options,
1392 .remount_fs = cgroup_remount,
1395 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1397 INIT_LIST_HEAD(&cgrp->sibling);
1398 INIT_LIST_HEAD(&cgrp->children);
1399 INIT_LIST_HEAD(&cgrp->files);
1400 INIT_LIST_HEAD(&cgrp->css_sets);
1401 INIT_LIST_HEAD(&cgrp->allcg_node);
1402 INIT_LIST_HEAD(&cgrp->release_list);
1403 INIT_LIST_HEAD(&cgrp->pidlists);
1404 INIT_WORK(&cgrp->free_work, cgroup_free_fn);
1405 mutex_init(&cgrp->pidlist_mutex);
1406 INIT_LIST_HEAD(&cgrp->event_list);
1407 spin_lock_init(&cgrp->event_list_lock);
1408 simple_xattrs_init(&cgrp->xattrs);
1411 static void init_cgroup_root(struct cgroupfs_root *root)
1413 struct cgroup *cgrp = &root->top_cgroup;
1415 INIT_LIST_HEAD(&root->subsys_list);
1416 INIT_LIST_HEAD(&root->root_list);
1417 INIT_LIST_HEAD(&root->allcg_list);
1418 root->number_of_cgroups = 1;
1420 cgrp->name = &root_cgroup_name;
1421 init_cgroup_housekeeping(cgrp);
1422 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
1425 static bool init_root_id(struct cgroupfs_root *root)
1430 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1432 spin_lock(&hierarchy_id_lock);
1433 /* Try to allocate the next unused ID */
1434 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1435 &root->hierarchy_id);
1437 /* Try again starting from 0 */
1438 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1440 next_hierarchy_id = root->hierarchy_id + 1;
1441 } else if (ret != -EAGAIN) {
1442 /* Can only get here if the 31-bit IDR is full ... */
1445 spin_unlock(&hierarchy_id_lock);
1450 static int cgroup_test_super(struct super_block *sb, void *data)
1452 struct cgroup_sb_opts *opts = data;
1453 struct cgroupfs_root *root = sb->s_fs_info;
1455 /* If we asked for a name then it must match */
1456 if (opts->name && strcmp(opts->name, root->name))
1460 * If we asked for subsystems (or explicitly for no
1461 * subsystems) then they must match
1463 if ((opts->subsys_mask || opts->none)
1464 && (opts->subsys_mask != root->subsys_mask))
1470 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1472 struct cgroupfs_root *root;
1474 if (!opts->subsys_mask && !opts->none)
1477 root = kzalloc(sizeof(*root), GFP_KERNEL);
1479 return ERR_PTR(-ENOMEM);
1481 if (!init_root_id(root)) {
1483 return ERR_PTR(-ENOMEM);
1485 init_cgroup_root(root);
1487 root->subsys_mask = opts->subsys_mask;
1488 root->flags = opts->flags;
1489 ida_init(&root->cgroup_ida);
1490 if (opts->release_agent)
1491 strcpy(root->release_agent_path, opts->release_agent);
1493 strcpy(root->name, opts->name);
1494 if (opts->cpuset_clone_children)
1495 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1499 static void cgroup_drop_root(struct cgroupfs_root *root)
1504 BUG_ON(!root->hierarchy_id);
1505 spin_lock(&hierarchy_id_lock);
1506 ida_remove(&hierarchy_ida, root->hierarchy_id);
1507 spin_unlock(&hierarchy_id_lock);
1508 ida_destroy(&root->cgroup_ida);
1512 static int cgroup_set_super(struct super_block *sb, void *data)
1515 struct cgroup_sb_opts *opts = data;
1517 /* If we don't have a new root, we can't set up a new sb */
1518 if (!opts->new_root)
1521 BUG_ON(!opts->subsys_mask && !opts->none);
1523 ret = set_anon_super(sb, NULL);
1527 sb->s_fs_info = opts->new_root;
1528 opts->new_root->sb = sb;
1530 sb->s_blocksize = PAGE_CACHE_SIZE;
1531 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1532 sb->s_magic = CGROUP_SUPER_MAGIC;
1533 sb->s_op = &cgroup_ops;
1538 static int cgroup_get_rootdir(struct super_block *sb)
1540 static const struct dentry_operations cgroup_dops = {
1541 .d_iput = cgroup_diput,
1542 .d_delete = cgroup_delete,
1545 struct inode *inode =
1546 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1551 inode->i_fop = &simple_dir_operations;
1552 inode->i_op = &cgroup_dir_inode_operations;
1553 /* directories start off with i_nlink == 2 (for "." entry) */
1555 sb->s_root = d_make_root(inode);
1558 /* for everything else we want ->d_op set */
1559 sb->s_d_op = &cgroup_dops;
1563 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1564 int flags, const char *unused_dev_name,
1567 struct cgroup_sb_opts opts;
1568 struct cgroupfs_root *root;
1570 struct super_block *sb;
1571 struct cgroupfs_root *new_root;
1572 struct inode *inode;
1574 /* First find the desired set of subsystems */
1575 mutex_lock(&cgroup_mutex);
1576 ret = parse_cgroupfs_options(data, &opts);
1577 mutex_unlock(&cgroup_mutex);
1582 * Allocate a new cgroup root. We may not need it if we're
1583 * reusing an existing hierarchy.
1585 new_root = cgroup_root_from_opts(&opts);
1586 if (IS_ERR(new_root)) {
1587 ret = PTR_ERR(new_root);
1590 opts.new_root = new_root;
1592 /* Locate an existing or new sb for this hierarchy */
1593 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1596 cgroup_drop_root(opts.new_root);
1600 root = sb->s_fs_info;
1602 if (root == opts.new_root) {
1603 /* We used the new root structure, so this is a new hierarchy */
1604 struct list_head tmp_cg_links;
1605 struct cgroup *root_cgrp = &root->top_cgroup;
1606 struct cgroupfs_root *existing_root;
1607 const struct cred *cred;
1611 BUG_ON(sb->s_root != NULL);
1613 ret = cgroup_get_rootdir(sb);
1615 goto drop_new_super;
1616 inode = sb->s_root->d_inode;
1618 mutex_lock(&inode->i_mutex);
1619 mutex_lock(&cgroup_mutex);
1620 mutex_lock(&cgroup_root_mutex);
1622 /* Check for name clashes with existing mounts */
1624 if (strlen(root->name))
1625 for_each_active_root(existing_root)
1626 if (!strcmp(existing_root->name, root->name))
1630 * We're accessing css_set_count without locking
1631 * css_set_lock here, but that's OK - it can only be
1632 * increased by someone holding cgroup_lock, and
1633 * that's us. The worst that can happen is that we
1634 * have some link structures left over
1636 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1640 ret = rebind_subsystems(root, root->subsys_mask);
1641 if (ret == -EBUSY) {
1642 free_cg_links(&tmp_cg_links);
1646 * There must be no failure case after here, since rebinding
1647 * takes care of subsystems' refcounts, which are explicitly
1648 * dropped in the failure exit path.
1651 /* EBUSY should be the only error here */
1654 list_add(&root->root_list, &roots);
1657 sb->s_root->d_fsdata = root_cgrp;
1658 root->top_cgroup.dentry = sb->s_root;
1660 /* Link the top cgroup in this hierarchy into all
1661 * the css_set objects */
1662 write_lock(&css_set_lock);
1663 hash_for_each(css_set_table, i, cg, hlist)
1664 link_css_set(&tmp_cg_links, cg, root_cgrp);
1665 write_unlock(&css_set_lock);
1667 free_cg_links(&tmp_cg_links);
1669 BUG_ON(!list_empty(&root_cgrp->children));
1670 BUG_ON(root->number_of_cgroups != 1);
1672 cred = override_creds(&init_cred);
1673 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1675 mutex_unlock(&cgroup_root_mutex);
1676 mutex_unlock(&cgroup_mutex);
1677 mutex_unlock(&inode->i_mutex);
1680 * We re-used an existing hierarchy - the new root (if
1681 * any) is not needed
1683 cgroup_drop_root(opts.new_root);
1685 if (((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) &&
1686 root->flags != opts.flags) {
1687 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1689 goto drop_new_super;
1692 /* no subsys rebinding, so refcounts don't change */
1693 drop_parsed_module_refcounts(opts.subsys_mask);
1696 kfree(opts.release_agent);
1698 return dget(sb->s_root);
1701 mutex_unlock(&cgroup_root_mutex);
1702 mutex_unlock(&cgroup_mutex);
1703 mutex_unlock(&inode->i_mutex);
1705 deactivate_locked_super(sb);
1707 drop_parsed_module_refcounts(opts.subsys_mask);
1709 kfree(opts.release_agent);
1711 return ERR_PTR(ret);
1714 static void cgroup_kill_sb(struct super_block *sb) {
1715 struct cgroupfs_root *root = sb->s_fs_info;
1716 struct cgroup *cgrp = &root->top_cgroup;
1718 struct cg_cgroup_link *link;
1719 struct cg_cgroup_link *saved_link;
1723 BUG_ON(root->number_of_cgroups != 1);
1724 BUG_ON(!list_empty(&cgrp->children));
1726 mutex_lock(&cgroup_mutex);
1727 mutex_lock(&cgroup_root_mutex);
1729 /* Rebind all subsystems back to the default hierarchy */
1730 ret = rebind_subsystems(root, 0);
1731 /* Shouldn't be able to fail ... */
1735 * Release all the links from css_sets to this hierarchy's
1738 write_lock(&css_set_lock);
1740 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1742 list_del(&link->cg_link_list);
1743 list_del(&link->cgrp_link_list);
1746 write_unlock(&css_set_lock);
1748 if (!list_empty(&root->root_list)) {
1749 list_del(&root->root_list);
1753 mutex_unlock(&cgroup_root_mutex);
1754 mutex_unlock(&cgroup_mutex);
1756 simple_xattrs_free(&cgrp->xattrs);
1758 kill_litter_super(sb);
1759 cgroup_drop_root(root);
1762 static struct file_system_type cgroup_fs_type = {
1764 .mount = cgroup_mount,
1765 .kill_sb = cgroup_kill_sb,
1768 static struct kobject *cgroup_kobj;
1771 * cgroup_path - generate the path of a cgroup
1772 * @cgrp: the cgroup in question
1773 * @buf: the buffer to write the path into
1774 * @buflen: the length of the buffer
1776 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1778 * We can't generate cgroup path using dentry->d_name, as accessing
1779 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1780 * inode's i_mutex, while on the other hand cgroup_path() can be called
1781 * with some irq-safe spinlocks held.
1783 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1785 int ret = -ENAMETOOLONG;
1788 if (!cgrp->parent) {
1789 if (strlcpy(buf, "/", buflen) >= buflen)
1790 return -ENAMETOOLONG;
1794 start = buf + buflen - 1;
1799 const char *name = cgroup_name(cgrp);
1803 if ((start -= len) < buf)
1805 memcpy(start, name, len);
1811 cgrp = cgrp->parent;
1812 } while (cgrp->parent);
1814 memmove(buf, start, buf + buflen - start);
1819 EXPORT_SYMBOL_GPL(cgroup_path);
1822 * Control Group taskset
1824 struct task_and_cgroup {
1825 struct task_struct *task;
1826 struct cgroup *cgrp;
1830 struct cgroup_taskset {
1831 struct task_and_cgroup single;
1832 struct flex_array *tc_array;
1835 struct cgroup *cur_cgrp;
1839 * cgroup_taskset_first - reset taskset and return the first task
1840 * @tset: taskset of interest
1842 * @tset iteration is initialized and the first task is returned.
1844 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1846 if (tset->tc_array) {
1848 return cgroup_taskset_next(tset);
1850 tset->cur_cgrp = tset->single.cgrp;
1851 return tset->single.task;
1854 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1857 * cgroup_taskset_next - iterate to the next task in taskset
1858 * @tset: taskset of interest
1860 * Return the next task in @tset. Iteration must have been initialized
1861 * with cgroup_taskset_first().
1863 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1865 struct task_and_cgroup *tc;
1867 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1870 tc = flex_array_get(tset->tc_array, tset->idx++);
1871 tset->cur_cgrp = tc->cgrp;
1874 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1877 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1878 * @tset: taskset of interest
1880 * Return the cgroup for the current (last returned) task of @tset. This
1881 * function must be preceded by either cgroup_taskset_first() or
1882 * cgroup_taskset_next().
1884 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1886 return tset->cur_cgrp;
1888 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1891 * cgroup_taskset_size - return the number of tasks in taskset
1892 * @tset: taskset of interest
1894 int cgroup_taskset_size(struct cgroup_taskset *tset)
1896 return tset->tc_array ? tset->tc_array_len : 1;
1898 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1902 * cgroup_task_migrate - move a task from one cgroup to another.
1904 * Must be called with cgroup_mutex and threadgroup locked.
1906 static void cgroup_task_migrate(struct cgroup *oldcgrp,
1907 struct task_struct *tsk, struct css_set *newcg)
1909 struct css_set *oldcg;
1912 * We are synchronized through threadgroup_lock() against PF_EXITING
1913 * setting such that we can't race against cgroup_exit() changing the
1914 * css_set to init_css_set and dropping the old one.
1916 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1917 oldcg = tsk->cgroups;
1920 rcu_assign_pointer(tsk->cgroups, newcg);
1923 /* Update the css_set linked lists if we're using them */
1924 write_lock(&css_set_lock);
1925 if (!list_empty(&tsk->cg_list))
1926 list_move(&tsk->cg_list, &newcg->tasks);
1927 write_unlock(&css_set_lock);
1930 * We just gained a reference on oldcg by taking it from the task. As
1931 * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1932 * it here; it will be freed under RCU.
1934 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1939 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1940 * @cgrp: the cgroup to attach to
1941 * @tsk: the task or the leader of the threadgroup to be attached
1942 * @threadgroup: attach the whole threadgroup?
1944 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1945 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1947 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1950 int retval, i, group_size;
1951 struct cgroup_subsys *ss, *failed_ss = NULL;
1952 struct cgroupfs_root *root = cgrp->root;
1953 /* threadgroup list cursor and array */
1954 struct task_struct *leader = tsk;
1955 struct task_and_cgroup *tc;
1956 struct flex_array *group;
1957 struct cgroup_taskset tset = { };
1960 * step 0: in order to do expensive, possibly blocking operations for
1961 * every thread, we cannot iterate the thread group list, since it needs
1962 * rcu or tasklist locked. instead, build an array of all threads in the
1963 * group - group_rwsem prevents new threads from appearing, and if
1964 * threads exit, this will just be an over-estimate.
1967 group_size = get_nr_threads(tsk);
1970 /* flex_array supports very large thread-groups better than kmalloc. */
1971 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1974 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1975 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1977 goto out_free_group_list;
1981 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1982 * already PF_EXITING could be freed from underneath us unless we
1983 * take an rcu_read_lock.
1987 struct task_and_cgroup ent;
1989 /* @tsk either already exited or can't exit until the end */
1990 if (tsk->flags & PF_EXITING)
1993 /* as per above, nr_threads may decrease, but not increase. */
1994 BUG_ON(i >= group_size);
1996 ent.cgrp = task_cgroup_from_root(tsk, root);
1997 /* nothing to do if this task is already in the cgroup */
1998 if (ent.cgrp == cgrp)
2001 * saying GFP_ATOMIC has no effect here because we did prealloc
2002 * earlier, but it's good form to communicate our expectations.
2004 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2005 BUG_ON(retval != 0);
2010 } while_each_thread(leader, tsk);
2012 /* remember the number of threads in the array for later. */
2014 tset.tc_array = group;
2015 tset.tc_array_len = group_size;
2017 /* methods shouldn't be called if no task is actually migrating */
2020 goto out_free_group_list;
2023 * step 1: check that we can legitimately attach to the cgroup.
2025 for_each_subsys(root, ss) {
2026 if (ss->can_attach) {
2027 retval = ss->can_attach(cgrp, &tset);
2030 goto out_cancel_attach;
2036 * step 2: make sure css_sets exist for all threads to be migrated.
2037 * we use find_css_set, which allocates a new one if necessary.
2039 for (i = 0; i < group_size; i++) {
2040 tc = flex_array_get(group, i);
2041 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2044 goto out_put_css_set_refs;
2049 * step 3: now that we're guaranteed success wrt the css_sets,
2050 * proceed to move all tasks to the new cgroup. There are no
2051 * failure cases after here, so this is the commit point.
2053 for (i = 0; i < group_size; i++) {
2054 tc = flex_array_get(group, i);
2055 cgroup_task_migrate(tc->cgrp, tc->task, tc->cg);
2057 /* nothing is sensitive to fork() after this point. */
2060 * step 4: do subsystem attach callbacks.
2062 for_each_subsys(root, ss) {
2064 ss->attach(cgrp, &tset);
2068 * step 5: success! and cleanup
2071 out_put_css_set_refs:
2073 for (i = 0; i < group_size; i++) {
2074 tc = flex_array_get(group, i);
2077 put_css_set(tc->cg);
2082 for_each_subsys(root, ss) {
2083 if (ss == failed_ss)
2085 if (ss->cancel_attach)
2086 ss->cancel_attach(cgrp, &tset);
2089 out_free_group_list:
2090 flex_array_free(group);
2095 * Find the task_struct of the task to attach by vpid and pass it along to the
2096 * function to attach either it or all tasks in its threadgroup. Will lock
2097 * cgroup_mutex and threadgroup; may take task_lock of task.
2099 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2101 struct task_struct *tsk;
2102 const struct cred *cred = current_cred(), *tcred;
2105 if (!cgroup_lock_live_group(cgrp))
2111 tsk = find_task_by_vpid(pid);
2115 goto out_unlock_cgroup;
2118 * even if we're attaching all tasks in the thread group, we
2119 * only need to check permissions on one of them.
2121 tcred = __task_cred(tsk);
2122 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2123 !uid_eq(cred->euid, tcred->uid) &&
2124 !uid_eq(cred->euid, tcred->suid)) {
2127 goto out_unlock_cgroup;
2133 tsk = tsk->group_leader;
2136 * Workqueue threads may acquire PF_THREAD_BOUND and become
2137 * trapped in a cpuset, or RT worker may be born in a cgroup
2138 * with no rt_runtime allocated. Just say no.
2140 if (tsk == kthreadd_task || (tsk->flags & PF_THREAD_BOUND)) {
2143 goto out_unlock_cgroup;
2146 get_task_struct(tsk);
2149 threadgroup_lock(tsk);
2151 if (!thread_group_leader(tsk)) {
2153 * a race with de_thread from another thread's exec()
2154 * may strip us of our leadership, if this happens,
2155 * there is no choice but to throw this task away and
2156 * try again; this is
2157 * "double-double-toil-and-trouble-check locking".
2159 threadgroup_unlock(tsk);
2160 put_task_struct(tsk);
2161 goto retry_find_task;
2165 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2167 threadgroup_unlock(tsk);
2169 put_task_struct(tsk);
2171 mutex_unlock(&cgroup_mutex);
2176 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2177 * @from: attach to all cgroups of a given task
2178 * @tsk: the task to be attached
2180 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2182 struct cgroupfs_root *root;
2185 mutex_lock(&cgroup_mutex);
2186 for_each_active_root(root) {
2187 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2189 retval = cgroup_attach_task(from_cg, tsk, false);
2193 mutex_unlock(&cgroup_mutex);
2197 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2199 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2201 return attach_task_by_pid(cgrp, pid, false);
2204 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2206 return attach_task_by_pid(cgrp, tgid, true);
2209 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2212 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2213 if (strlen(buffer) >= PATH_MAX)
2215 if (!cgroup_lock_live_group(cgrp))
2217 mutex_lock(&cgroup_root_mutex);
2218 strcpy(cgrp->root->release_agent_path, buffer);
2219 mutex_unlock(&cgroup_root_mutex);
2220 mutex_unlock(&cgroup_mutex);
2224 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2225 struct seq_file *seq)
2227 if (!cgroup_lock_live_group(cgrp))
2229 seq_puts(seq, cgrp->root->release_agent_path);
2230 seq_putc(seq, '\n');
2231 mutex_unlock(&cgroup_mutex);
2235 static int cgroup_sane_behavior_show(struct cgroup *cgrp, struct cftype *cft,
2236 struct seq_file *seq)
2238 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2242 /* A buffer size big enough for numbers or short strings */
2243 #define CGROUP_LOCAL_BUFFER_SIZE 64
2245 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2247 const char __user *userbuf,
2248 size_t nbytes, loff_t *unused_ppos)
2250 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2256 if (nbytes >= sizeof(buffer))
2258 if (copy_from_user(buffer, userbuf, nbytes))
2261 buffer[nbytes] = 0; /* nul-terminate */
2262 if (cft->write_u64) {
2263 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2266 retval = cft->write_u64(cgrp, cft, val);
2268 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2271 retval = cft->write_s64(cgrp, cft, val);
2278 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2280 const char __user *userbuf,
2281 size_t nbytes, loff_t *unused_ppos)
2283 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2285 size_t max_bytes = cft->max_write_len;
2286 char *buffer = local_buffer;
2289 max_bytes = sizeof(local_buffer) - 1;
2290 if (nbytes >= max_bytes)
2292 /* Allocate a dynamic buffer if we need one */
2293 if (nbytes >= sizeof(local_buffer)) {
2294 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2298 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2303 buffer[nbytes] = 0; /* nul-terminate */
2304 retval = cft->write_string(cgrp, cft, strstrip(buffer));
2308 if (buffer != local_buffer)
2313 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2314 size_t nbytes, loff_t *ppos)
2316 struct cftype *cft = __d_cft(file->f_dentry);
2317 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2319 if (cgroup_is_removed(cgrp))
2322 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2323 if (cft->write_u64 || cft->write_s64)
2324 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2325 if (cft->write_string)
2326 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2328 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2329 return ret ? ret : nbytes;
2334 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2336 char __user *buf, size_t nbytes,
2339 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2340 u64 val = cft->read_u64(cgrp, cft);
2341 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2343 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2346 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2348 char __user *buf, size_t nbytes,
2351 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2352 s64 val = cft->read_s64(cgrp, cft);
2353 int len = sprintf(tmp, "%lld\n", (long long) val);
2355 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2358 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2359 size_t nbytes, loff_t *ppos)
2361 struct cftype *cft = __d_cft(file->f_dentry);
2362 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2364 if (cgroup_is_removed(cgrp))
2368 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2370 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2372 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2377 * seqfile ops/methods for returning structured data. Currently just
2378 * supports string->u64 maps, but can be extended in future.
2381 struct cgroup_seqfile_state {
2383 struct cgroup *cgroup;
2386 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2388 struct seq_file *sf = cb->state;
2389 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2392 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2394 struct cgroup_seqfile_state *state = m->private;
2395 struct cftype *cft = state->cft;
2396 if (cft->read_map) {
2397 struct cgroup_map_cb cb = {
2398 .fill = cgroup_map_add,
2401 return cft->read_map(state->cgroup, cft, &cb);
2403 return cft->read_seq_string(state->cgroup, cft, m);
2406 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2408 struct seq_file *seq = file->private_data;
2409 kfree(seq->private);
2410 return single_release(inode, file);
2413 static const struct file_operations cgroup_seqfile_operations = {
2415 .write = cgroup_file_write,
2416 .llseek = seq_lseek,
2417 .release = cgroup_seqfile_release,
2420 static int cgroup_file_open(struct inode *inode, struct file *file)
2425 err = generic_file_open(inode, file);
2428 cft = __d_cft(file->f_dentry);
2430 if (cft->read_map || cft->read_seq_string) {
2431 struct cgroup_seqfile_state *state =
2432 kzalloc(sizeof(*state), GFP_USER);
2436 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2437 file->f_op = &cgroup_seqfile_operations;
2438 err = single_open(file, cgroup_seqfile_show, state);
2441 } else if (cft->open)
2442 err = cft->open(inode, file);
2449 static int cgroup_file_release(struct inode *inode, struct file *file)
2451 struct cftype *cft = __d_cft(file->f_dentry);
2453 return cft->release(inode, file);
2458 * cgroup_rename - Only allow simple rename of directories in place.
2460 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2461 struct inode *new_dir, struct dentry *new_dentry)
2464 struct cgroup_name *name, *old_name;
2465 struct cgroup *cgrp;
2468 * It's convinient to use parent dir's i_mutex to protected
2471 lockdep_assert_held(&old_dir->i_mutex);
2473 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2475 if (new_dentry->d_inode)
2477 if (old_dir != new_dir)
2480 cgrp = __d_cgrp(old_dentry);
2482 name = cgroup_alloc_name(new_dentry);
2486 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2492 old_name = cgrp->name;
2493 rcu_assign_pointer(cgrp->name, name);
2495 kfree_rcu(old_name, rcu_head);
2499 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2501 if (S_ISDIR(dentry->d_inode->i_mode))
2502 return &__d_cgrp(dentry)->xattrs;
2504 return &__d_cft(dentry)->xattrs;
2507 static inline int xattr_enabled(struct dentry *dentry)
2509 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2510 return root->flags & CGRP_ROOT_XATTR;
2513 static bool is_valid_xattr(const char *name)
2515 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2516 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2521 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2522 const void *val, size_t size, int flags)
2524 if (!xattr_enabled(dentry))
2526 if (!is_valid_xattr(name))
2528 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2531 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2533 if (!xattr_enabled(dentry))
2535 if (!is_valid_xattr(name))
2537 return simple_xattr_remove(__d_xattrs(dentry), name);
2540 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2541 void *buf, size_t size)
2543 if (!xattr_enabled(dentry))
2545 if (!is_valid_xattr(name))
2547 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2550 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2552 if (!xattr_enabled(dentry))
2554 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2557 static const struct file_operations cgroup_file_operations = {
2558 .read = cgroup_file_read,
2559 .write = cgroup_file_write,
2560 .llseek = generic_file_llseek,
2561 .open = cgroup_file_open,
2562 .release = cgroup_file_release,
2565 static const struct inode_operations cgroup_file_inode_operations = {
2566 .setxattr = cgroup_setxattr,
2567 .getxattr = cgroup_getxattr,
2568 .listxattr = cgroup_listxattr,
2569 .removexattr = cgroup_removexattr,
2572 static const struct inode_operations cgroup_dir_inode_operations = {
2573 .lookup = cgroup_lookup,
2574 .mkdir = cgroup_mkdir,
2575 .rmdir = cgroup_rmdir,
2576 .rename = cgroup_rename,
2577 .setxattr = cgroup_setxattr,
2578 .getxattr = cgroup_getxattr,
2579 .listxattr = cgroup_listxattr,
2580 .removexattr = cgroup_removexattr,
2583 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2585 if (dentry->d_name.len > NAME_MAX)
2586 return ERR_PTR(-ENAMETOOLONG);
2587 d_add(dentry, NULL);
2592 * Check if a file is a control file
2594 static inline struct cftype *__file_cft(struct file *file)
2596 if (file_inode(file)->i_fop != &cgroup_file_operations)
2597 return ERR_PTR(-EINVAL);
2598 return __d_cft(file->f_dentry);
2601 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2602 struct super_block *sb)
2604 struct inode *inode;
2608 if (dentry->d_inode)
2611 inode = cgroup_new_inode(mode, sb);
2615 if (S_ISDIR(mode)) {
2616 inode->i_op = &cgroup_dir_inode_operations;
2617 inode->i_fop = &simple_dir_operations;
2619 /* start off with i_nlink == 2 (for "." entry) */
2621 inc_nlink(dentry->d_parent->d_inode);
2624 * Control reaches here with cgroup_mutex held.
2625 * @inode->i_mutex should nest outside cgroup_mutex but we
2626 * want to populate it immediately without releasing
2627 * cgroup_mutex. As @inode isn't visible to anyone else
2628 * yet, trylock will always succeed without affecting
2631 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2632 } else if (S_ISREG(mode)) {
2634 inode->i_fop = &cgroup_file_operations;
2635 inode->i_op = &cgroup_file_inode_operations;
2637 d_instantiate(dentry, inode);
2638 dget(dentry); /* Extra count - pin the dentry in core */
2643 * cgroup_file_mode - deduce file mode of a control file
2644 * @cft: the control file in question
2646 * returns cft->mode if ->mode is not 0
2647 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2648 * returns S_IRUGO if it has only a read handler
2649 * returns S_IWUSR if it has only a write hander
2651 static umode_t cgroup_file_mode(const struct cftype *cft)
2658 if (cft->read || cft->read_u64 || cft->read_s64 ||
2659 cft->read_map || cft->read_seq_string)
2662 if (cft->write || cft->write_u64 || cft->write_s64 ||
2663 cft->write_string || cft->trigger)
2669 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2672 struct dentry *dir = cgrp->dentry;
2673 struct cgroup *parent = __d_cgrp(dir);
2674 struct dentry *dentry;
2678 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2680 simple_xattrs_init(&cft->xattrs);
2682 if (subsys && !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2683 strcpy(name, subsys->name);
2686 strcat(name, cft->name);
2688 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2690 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2694 dentry = lookup_one_len(name, dir, strlen(name));
2695 if (IS_ERR(dentry)) {
2696 error = PTR_ERR(dentry);
2700 mode = cgroup_file_mode(cft);
2701 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2703 cfe->type = (void *)cft;
2704 cfe->dentry = dentry;
2705 dentry->d_fsdata = cfe;
2706 list_add_tail(&cfe->node, &parent->files);
2715 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2716 struct cftype cfts[], bool is_add)
2721 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2722 /* does cft->flags tell us to skip this file on @cgrp? */
2723 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2725 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2727 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2731 err = cgroup_add_file(cgrp, subsys, cft);
2733 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2737 cgroup_rm_file(cgrp, cft);
2743 static DEFINE_MUTEX(cgroup_cft_mutex);
2745 static void cgroup_cfts_prepare(void)
2746 __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2749 * Thanks to the entanglement with vfs inode locking, we can't walk
2750 * the existing cgroups under cgroup_mutex and create files.
2751 * Instead, we increment reference on all cgroups and build list of
2752 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2753 * exclusive access to the field.
2755 mutex_lock(&cgroup_cft_mutex);
2756 mutex_lock(&cgroup_mutex);
2759 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2760 struct cftype *cfts, bool is_add)
2761 __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2764 struct cgroup *cgrp, *n;
2766 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2767 if (cfts && ss->root != &rootnode) {
2768 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2770 list_add_tail(&cgrp->cft_q_node, &pending);
2774 mutex_unlock(&cgroup_mutex);
2777 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2778 * files for all cgroups which were created before.
2780 list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2781 struct inode *inode = cgrp->dentry->d_inode;
2783 mutex_lock(&inode->i_mutex);
2784 mutex_lock(&cgroup_mutex);
2785 if (!cgroup_is_removed(cgrp))
2786 cgroup_addrm_files(cgrp, ss, cfts, is_add);
2787 mutex_unlock(&cgroup_mutex);
2788 mutex_unlock(&inode->i_mutex);
2790 list_del_init(&cgrp->cft_q_node);
2794 mutex_unlock(&cgroup_cft_mutex);
2798 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2799 * @ss: target cgroup subsystem
2800 * @cfts: zero-length name terminated array of cftypes
2802 * Register @cfts to @ss. Files described by @cfts are created for all
2803 * existing cgroups to which @ss is attached and all future cgroups will
2804 * have them too. This function can be called anytime whether @ss is
2807 * Returns 0 on successful registration, -errno on failure. Note that this
2808 * function currently returns 0 as long as @cfts registration is successful
2809 * even if some file creation attempts on existing cgroups fail.
2811 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2813 struct cftype_set *set;
2815 set = kzalloc(sizeof(*set), GFP_KERNEL);
2819 cgroup_cfts_prepare();
2821 list_add_tail(&set->node, &ss->cftsets);
2822 cgroup_cfts_commit(ss, cfts, true);
2826 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2829 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2830 * @ss: target cgroup subsystem
2831 * @cfts: zero-length name terminated array of cftypes
2833 * Unregister @cfts from @ss. Files described by @cfts are removed from
2834 * all existing cgroups to which @ss is attached and all future cgroups
2835 * won't have them either. This function can be called anytime whether @ss
2836 * is attached or not.
2838 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2839 * registered with @ss.
2841 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2843 struct cftype_set *set;
2845 cgroup_cfts_prepare();
2847 list_for_each_entry(set, &ss->cftsets, node) {
2848 if (set->cfts == cfts) {
2849 list_del_init(&set->node);
2850 cgroup_cfts_commit(ss, cfts, false);
2855 cgroup_cfts_commit(ss, NULL, false);
2860 * cgroup_task_count - count the number of tasks in a cgroup.
2861 * @cgrp: the cgroup in question
2863 * Return the number of tasks in the cgroup.
2865 int cgroup_task_count(const struct cgroup *cgrp)
2868 struct cg_cgroup_link *link;
2870 read_lock(&css_set_lock);
2871 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2872 count += atomic_read(&link->cg->refcount);
2874 read_unlock(&css_set_lock);
2879 * Advance a list_head iterator. The iterator should be positioned at
2880 * the start of a css_set
2882 static void cgroup_advance_iter(struct cgroup *cgrp,
2883 struct cgroup_iter *it)
2885 struct list_head *l = it->cg_link;
2886 struct cg_cgroup_link *link;
2889 /* Advance to the next non-empty css_set */
2892 if (l == &cgrp->css_sets) {
2896 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2898 } while (list_empty(&cg->tasks));
2900 it->task = cg->tasks.next;
2904 * To reduce the fork() overhead for systems that are not actually
2905 * using their cgroups capability, we don't maintain the lists running
2906 * through each css_set to its tasks until we see the list actually
2907 * used - in other words after the first call to cgroup_iter_start().
2909 static void cgroup_enable_task_cg_lists(void)
2911 struct task_struct *p, *g;
2912 write_lock(&css_set_lock);
2913 use_task_css_set_links = 1;
2915 * We need tasklist_lock because RCU is not safe against
2916 * while_each_thread(). Besides, a forking task that has passed
2917 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2918 * is not guaranteed to have its child immediately visible in the
2919 * tasklist if we walk through it with RCU.
2921 read_lock(&tasklist_lock);
2922 do_each_thread(g, p) {
2925 * We should check if the process is exiting, otherwise
2926 * it will race with cgroup_exit() in that the list
2927 * entry won't be deleted though the process has exited.
2929 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2930 list_add(&p->cg_list, &p->cgroups->tasks);
2932 } while_each_thread(g, p);
2933 read_unlock(&tasklist_lock);
2934 write_unlock(&css_set_lock);
2938 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
2939 * @pos: the current position (%NULL to initiate traversal)
2940 * @cgroup: cgroup whose descendants to walk
2942 * To be used by cgroup_for_each_descendant_pre(). Find the next
2943 * descendant to visit for pre-order traversal of @cgroup's descendants.
2945 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
2946 struct cgroup *cgroup)
2948 struct cgroup *next;
2950 WARN_ON_ONCE(!rcu_read_lock_held());
2952 /* if first iteration, pretend we just visited @cgroup */
2954 if (list_empty(&cgroup->children))
2959 /* visit the first child if exists */
2960 next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
2964 /* no child, visit my or the closest ancestor's next sibling */
2966 next = list_entry_rcu(pos->sibling.next, struct cgroup,
2968 if (&next->sibling != &pos->parent->children)
2972 } while (pos != cgroup);
2976 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
2979 * cgroup_rightmost_descendant - return the rightmost descendant of a cgroup
2980 * @pos: cgroup of interest
2982 * Return the rightmost descendant of @pos. If there's no descendant,
2983 * @pos is returned. This can be used during pre-order traversal to skip
2986 struct cgroup *cgroup_rightmost_descendant(struct cgroup *pos)
2988 struct cgroup *last, *tmp;
2990 WARN_ON_ONCE(!rcu_read_lock_held());
2994 /* ->prev isn't RCU safe, walk ->next till the end */
2996 list_for_each_entry_rcu(tmp, &last->children, sibling)
3002 EXPORT_SYMBOL_GPL(cgroup_rightmost_descendant);
3004 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3006 struct cgroup *last;
3010 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3018 * cgroup_next_descendant_post - find the next descendant for post-order walk
3019 * @pos: the current position (%NULL to initiate traversal)
3020 * @cgroup: cgroup whose descendants to walk
3022 * To be used by cgroup_for_each_descendant_post(). Find the next
3023 * descendant to visit for post-order traversal of @cgroup's descendants.
3025 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3026 struct cgroup *cgroup)
3028 struct cgroup *next;
3030 WARN_ON_ONCE(!rcu_read_lock_held());
3032 /* if first iteration, visit the leftmost descendant */
3034 next = cgroup_leftmost_descendant(cgroup);
3035 return next != cgroup ? next : NULL;
3038 /* if there's an unvisited sibling, visit its leftmost descendant */
3039 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3040 if (&next->sibling != &pos->parent->children)
3041 return cgroup_leftmost_descendant(next);
3043 /* no sibling left, visit parent */
3045 return next != cgroup ? next : NULL;
3047 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3049 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3050 __acquires(css_set_lock)
3053 * The first time anyone tries to iterate across a cgroup,
3054 * we need to enable the list linking each css_set to its
3055 * tasks, and fix up all existing tasks.
3057 if (!use_task_css_set_links)
3058 cgroup_enable_task_cg_lists();
3060 read_lock(&css_set_lock);
3061 it->cg_link = &cgrp->css_sets;
3062 cgroup_advance_iter(cgrp, it);
3065 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3066 struct cgroup_iter *it)
3068 struct task_struct *res;
3069 struct list_head *l = it->task;
3070 struct cg_cgroup_link *link;
3072 /* If the iterator cg is NULL, we have no tasks */
3075 res = list_entry(l, struct task_struct, cg_list);
3076 /* Advance iterator to find next entry */
3078 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3079 if (l == &link->cg->tasks) {
3080 /* We reached the end of this task list - move on to
3081 * the next cg_cgroup_link */
3082 cgroup_advance_iter(cgrp, it);
3089 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3090 __releases(css_set_lock)
3092 read_unlock(&css_set_lock);
3095 static inline int started_after_time(struct task_struct *t1,
3096 struct timespec *time,
3097 struct task_struct *t2)
3099 int start_diff = timespec_compare(&t1->start_time, time);
3100 if (start_diff > 0) {
3102 } else if (start_diff < 0) {
3106 * Arbitrarily, if two processes started at the same
3107 * time, we'll say that the lower pointer value
3108 * started first. Note that t2 may have exited by now
3109 * so this may not be a valid pointer any longer, but
3110 * that's fine - it still serves to distinguish
3111 * between two tasks started (effectively) simultaneously.
3118 * This function is a callback from heap_insert() and is used to order
3120 * In this case we order the heap in descending task start time.
3122 static inline int started_after(void *p1, void *p2)
3124 struct task_struct *t1 = p1;
3125 struct task_struct *t2 = p2;
3126 return started_after_time(t1, &t2->start_time, t2);
3130 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3131 * @scan: struct cgroup_scanner containing arguments for the scan
3133 * Arguments include pointers to callback functions test_task() and
3135 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3136 * and if it returns true, call process_task() for it also.
3137 * The test_task pointer may be NULL, meaning always true (select all tasks).
3138 * Effectively duplicates cgroup_iter_{start,next,end}()
3139 * but does not lock css_set_lock for the call to process_task().
3140 * The struct cgroup_scanner may be embedded in any structure of the caller's
3142 * It is guaranteed that process_task() will act on every task that
3143 * is a member of the cgroup for the duration of this call. This
3144 * function may or may not call process_task() for tasks that exit
3145 * or move to a different cgroup during the call, or are forked or
3146 * move into the cgroup during the call.
3148 * Note that test_task() may be called with locks held, and may in some
3149 * situations be called multiple times for the same task, so it should
3151 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3152 * pre-allocated and will be used for heap operations (and its "gt" member will
3153 * be overwritten), else a temporary heap will be used (allocation of which
3154 * may cause this function to fail).
3156 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3159 struct cgroup_iter it;
3160 struct task_struct *p, *dropped;
3161 /* Never dereference latest_task, since it's not refcounted */
3162 struct task_struct *latest_task = NULL;
3163 struct ptr_heap tmp_heap;
3164 struct ptr_heap *heap;
3165 struct timespec latest_time = { 0, 0 };
3168 /* The caller supplied our heap and pre-allocated its memory */
3170 heap->gt = &started_after;
3172 /* We need to allocate our own heap memory */
3174 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3176 /* cannot allocate the heap */
3182 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3183 * to determine which are of interest, and using the scanner's
3184 * "process_task" callback to process any of them that need an update.
3185 * Since we don't want to hold any locks during the task updates,
3186 * gather tasks to be processed in a heap structure.
3187 * The heap is sorted by descending task start time.
3188 * If the statically-sized heap fills up, we overflow tasks that
3189 * started later, and in future iterations only consider tasks that
3190 * started after the latest task in the previous pass. This
3191 * guarantees forward progress and that we don't miss any tasks.
3194 cgroup_iter_start(scan->cg, &it);
3195 while ((p = cgroup_iter_next(scan->cg, &it))) {
3197 * Only affect tasks that qualify per the caller's callback,
3198 * if he provided one
3200 if (scan->test_task && !scan->test_task(p, scan))
3203 * Only process tasks that started after the last task
3206 if (!started_after_time(p, &latest_time, latest_task))
3208 dropped = heap_insert(heap, p);
3209 if (dropped == NULL) {
3211 * The new task was inserted; the heap wasn't
3215 } else if (dropped != p) {
3217 * The new task was inserted, and pushed out a
3221 put_task_struct(dropped);
3224 * Else the new task was newer than anything already in
3225 * the heap and wasn't inserted
3228 cgroup_iter_end(scan->cg, &it);
3231 for (i = 0; i < heap->size; i++) {
3232 struct task_struct *q = heap->ptrs[i];
3234 latest_time = q->start_time;
3237 /* Process the task per the caller's callback */
3238 scan->process_task(q, scan);
3242 * If we had to process any tasks at all, scan again
3243 * in case some of them were in the middle of forking
3244 * children that didn't get processed.
3245 * Not the most efficient way to do it, but it avoids
3246 * having to take callback_mutex in the fork path
3250 if (heap == &tmp_heap)
3251 heap_free(&tmp_heap);
3255 static void cgroup_transfer_one_task(struct task_struct *task,
3256 struct cgroup_scanner *scan)
3258 struct cgroup *new_cgroup = scan->data;
3260 mutex_lock(&cgroup_mutex);
3261 cgroup_attach_task(new_cgroup, task, false);
3262 mutex_unlock(&cgroup_mutex);
3266 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3267 * @to: cgroup to which the tasks will be moved
3268 * @from: cgroup in which the tasks currently reside
3270 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3272 struct cgroup_scanner scan;
3275 scan.test_task = NULL; /* select all tasks in cgroup */
3276 scan.process_task = cgroup_transfer_one_task;
3280 return cgroup_scan_tasks(&scan);
3284 * Stuff for reading the 'tasks'/'procs' files.
3286 * Reading this file can return large amounts of data if a cgroup has
3287 * *lots* of attached tasks. So it may need several calls to read(),
3288 * but we cannot guarantee that the information we produce is correct
3289 * unless we produce it entirely atomically.
3293 /* which pidlist file are we talking about? */
3294 enum cgroup_filetype {
3300 * A pidlist is a list of pids that virtually represents the contents of one
3301 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3302 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3305 struct cgroup_pidlist {
3307 * used to find which pidlist is wanted. doesn't change as long as
3308 * this particular list stays in the list.
3310 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3313 /* how many elements the above list has */
3315 /* how many files are using the current array */
3317 /* each of these stored in a list by its cgroup */
3318 struct list_head links;
3319 /* pointer to the cgroup we belong to, for list removal purposes */
3320 struct cgroup *owner;
3321 /* protects the other fields */
3322 struct rw_semaphore mutex;
3326 * The following two functions "fix" the issue where there are more pids
3327 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3328 * TODO: replace with a kernel-wide solution to this problem
3330 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3331 static void *pidlist_allocate(int count)
3333 if (PIDLIST_TOO_LARGE(count))
3334 return vmalloc(count * sizeof(pid_t));
3336 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3338 static void pidlist_free(void *p)
3340 if (is_vmalloc_addr(p))
3347 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3348 * Returns the number of unique elements.
3350 static int pidlist_uniq(pid_t *list, int length)
3355 * we presume the 0th element is unique, so i starts at 1. trivial
3356 * edge cases first; no work needs to be done for either
3358 if (length == 0 || length == 1)
3360 /* src and dest walk down the list; dest counts unique elements */
3361 for (src = 1; src < length; src++) {
3362 /* find next unique element */
3363 while (list[src] == list[src-1]) {
3368 /* dest always points to where the next unique element goes */
3369 list[dest] = list[src];
3376 static int cmppid(const void *a, const void *b)
3378 return *(pid_t *)a - *(pid_t *)b;
3382 * find the appropriate pidlist for our purpose (given procs vs tasks)
3383 * returns with the lock on that pidlist already held, and takes care
3384 * of the use count, or returns NULL with no locks held if we're out of
3387 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3388 enum cgroup_filetype type)
3390 struct cgroup_pidlist *l;
3391 /* don't need task_nsproxy() if we're looking at ourself */
3392 struct pid_namespace *ns = task_active_pid_ns(current);
3395 * We can't drop the pidlist_mutex before taking the l->mutex in case
3396 * the last ref-holder is trying to remove l from the list at the same
3397 * time. Holding the pidlist_mutex precludes somebody taking whichever
3398 * list we find out from under us - compare release_pid_array().
3400 mutex_lock(&cgrp->pidlist_mutex);
3401 list_for_each_entry(l, &cgrp->pidlists, links) {
3402 if (l->key.type == type && l->key.ns == ns) {
3403 /* make sure l doesn't vanish out from under us */
3404 down_write(&l->mutex);
3405 mutex_unlock(&cgrp->pidlist_mutex);
3409 /* entry not found; create a new one */
3410 l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3412 mutex_unlock(&cgrp->pidlist_mutex);
3415 init_rwsem(&l->mutex);
3416 down_write(&l->mutex);
3418 l->key.ns = get_pid_ns(ns);
3419 l->use_count = 0; /* don't increment here */
3422 list_add(&l->links, &cgrp->pidlists);
3423 mutex_unlock(&cgrp->pidlist_mutex);
3428 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3430 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3431 struct cgroup_pidlist **lp)
3435 int pid, n = 0; /* used for populating the array */
3436 struct cgroup_iter it;
3437 struct task_struct *tsk;
3438 struct cgroup_pidlist *l;
3441 * If cgroup gets more users after we read count, we won't have
3442 * enough space - tough. This race is indistinguishable to the
3443 * caller from the case that the additional cgroup users didn't
3444 * show up until sometime later on.
3446 length = cgroup_task_count(cgrp);
3447 array = pidlist_allocate(length);
3450 /* now, populate the array */
3451 cgroup_iter_start(cgrp, &it);
3452 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3453 if (unlikely(n == length))
3455 /* get tgid or pid for procs or tasks file respectively */
3456 if (type == CGROUP_FILE_PROCS)
3457 pid = task_tgid_vnr(tsk);
3459 pid = task_pid_vnr(tsk);
3460 if (pid > 0) /* make sure to only use valid results */
3463 cgroup_iter_end(cgrp, &it);
3465 /* now sort & (if procs) strip out duplicates */
3466 sort(array, length, sizeof(pid_t), cmppid, NULL);
3467 if (type == CGROUP_FILE_PROCS)
3468 length = pidlist_uniq(array, length);
3469 l = cgroup_pidlist_find(cgrp, type);
3471 pidlist_free(array);
3474 /* store array, freeing old if necessary - lock already held */
3475 pidlist_free(l->list);
3479 up_write(&l->mutex);
3485 * cgroupstats_build - build and fill cgroupstats
3486 * @stats: cgroupstats to fill information into
3487 * @dentry: A dentry entry belonging to the cgroup for which stats have
3490 * Build and fill cgroupstats so that taskstats can export it to user
3493 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3496 struct cgroup *cgrp;
3497 struct cgroup_iter it;
3498 struct task_struct *tsk;
3501 * Validate dentry by checking the superblock operations,
3502 * and make sure it's a directory.
3504 if (dentry->d_sb->s_op != &cgroup_ops ||
3505 !S_ISDIR(dentry->d_inode->i_mode))
3509 cgrp = dentry->d_fsdata;
3511 cgroup_iter_start(cgrp, &it);
3512 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3513 switch (tsk->state) {
3515 stats->nr_running++;
3517 case TASK_INTERRUPTIBLE:
3518 stats->nr_sleeping++;
3520 case TASK_UNINTERRUPTIBLE:
3521 stats->nr_uninterruptible++;
3524 stats->nr_stopped++;
3527 if (delayacct_is_task_waiting_on_io(tsk))
3528 stats->nr_io_wait++;
3532 cgroup_iter_end(cgrp, &it);
3540 * seq_file methods for the tasks/procs files. The seq_file position is the
3541 * next pid to display; the seq_file iterator is a pointer to the pid
3542 * in the cgroup->l->list array.
3545 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3548 * Initially we receive a position value that corresponds to
3549 * one more than the last pid shown (or 0 on the first call or
3550 * after a seek to the start). Use a binary-search to find the
3551 * next pid to display, if any
3553 struct cgroup_pidlist *l = s->private;
3554 int index = 0, pid = *pos;
3557 down_read(&l->mutex);
3559 int end = l->length;
3561 while (index < end) {
3562 int mid = (index + end) / 2;
3563 if (l->list[mid] == pid) {
3566 } else if (l->list[mid] <= pid)
3572 /* If we're off the end of the array, we're done */
3573 if (index >= l->length)
3575 /* Update the abstract position to be the actual pid that we found */
3576 iter = l->list + index;
3581 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3583 struct cgroup_pidlist *l = s->private;
3587 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3589 struct cgroup_pidlist *l = s->private;
3591 pid_t *end = l->list + l->length;
3593 * Advance to the next pid in the array. If this goes off the
3605 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3607 return seq_printf(s, "%d\n", *(int *)v);
3611 * seq_operations functions for iterating on pidlists through seq_file -
3612 * independent of whether it's tasks or procs
3614 static const struct seq_operations cgroup_pidlist_seq_operations = {
3615 .start = cgroup_pidlist_start,
3616 .stop = cgroup_pidlist_stop,
3617 .next = cgroup_pidlist_next,
3618 .show = cgroup_pidlist_show,
3621 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3624 * the case where we're the last user of this particular pidlist will
3625 * have us remove it from the cgroup's list, which entails taking the
3626 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3627 * pidlist_mutex, we have to take pidlist_mutex first.
3629 mutex_lock(&l->owner->pidlist_mutex);
3630 down_write(&l->mutex);
3631 BUG_ON(!l->use_count);
3632 if (!--l->use_count) {
3633 /* we're the last user if refcount is 0; remove and free */
3634 list_del(&l->links);
3635 mutex_unlock(&l->owner->pidlist_mutex);
3636 pidlist_free(l->list);
3637 put_pid_ns(l->key.ns);
3638 up_write(&l->mutex);
3642 mutex_unlock(&l->owner->pidlist_mutex);
3643 up_write(&l->mutex);
3646 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3648 struct cgroup_pidlist *l;
3649 if (!(file->f_mode & FMODE_READ))
3652 * the seq_file will only be initialized if the file was opened for
3653 * reading; hence we check if it's not null only in that case.
3655 l = ((struct seq_file *)file->private_data)->private;
3656 cgroup_release_pid_array(l);
3657 return seq_release(inode, file);
3660 static const struct file_operations cgroup_pidlist_operations = {
3662 .llseek = seq_lseek,
3663 .write = cgroup_file_write,
3664 .release = cgroup_pidlist_release,
3668 * The following functions handle opens on a file that displays a pidlist
3669 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3672 /* helper function for the two below it */
3673 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3675 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3676 struct cgroup_pidlist *l;
3679 /* Nothing to do for write-only files */
3680 if (!(file->f_mode & FMODE_READ))
3683 /* have the array populated */
3684 retval = pidlist_array_load(cgrp, type, &l);
3687 /* configure file information */
3688 file->f_op = &cgroup_pidlist_operations;
3690 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3692 cgroup_release_pid_array(l);
3695 ((struct seq_file *)file->private_data)->private = l;
3698 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3700 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3702 static int cgroup_procs_open(struct inode *unused, struct file *file)
3704 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3707 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3710 return notify_on_release(cgrp);
3713 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3717 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3719 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3721 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3726 * Unregister event and free resources.
3728 * Gets called from workqueue.
3730 static void cgroup_event_remove(struct work_struct *work)
3732 struct cgroup_event *event = container_of(work, struct cgroup_event,
3734 struct cgroup *cgrp = event->cgrp;
3736 remove_wait_queue(event->wqh, &event->wait);
3738 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3740 /* Notify userspace the event is going away. */
3741 eventfd_signal(event->eventfd, 1);
3743 eventfd_ctx_put(event->eventfd);
3749 * Gets called on POLLHUP on eventfd when user closes it.
3751 * Called with wqh->lock held and interrupts disabled.
3753 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3754 int sync, void *key)
3756 struct cgroup_event *event = container_of(wait,
3757 struct cgroup_event, wait);
3758 struct cgroup *cgrp = event->cgrp;
3759 unsigned long flags = (unsigned long)key;
3761 if (flags & POLLHUP) {
3763 * If the event has been detached at cgroup removal, we
3764 * can simply return knowing the other side will cleanup
3767 * We can't race against event freeing since the other
3768 * side will require wqh->lock via remove_wait_queue(),
3771 spin_lock(&cgrp->event_list_lock);
3772 if (!list_empty(&event->list)) {
3773 list_del_init(&event->list);
3775 * We are in atomic context, but cgroup_event_remove()
3776 * may sleep, so we have to call it in workqueue.
3778 schedule_work(&event->remove);
3780 spin_unlock(&cgrp->event_list_lock);
3786 static void cgroup_event_ptable_queue_proc(struct file *file,
3787 wait_queue_head_t *wqh, poll_table *pt)
3789 struct cgroup_event *event = container_of(pt,
3790 struct cgroup_event, pt);
3793 add_wait_queue(wqh, &event->wait);
3797 * Parse input and register new cgroup event handler.
3799 * Input must be in format '<event_fd> <control_fd> <args>'.
3800 * Interpretation of args is defined by control file implementation.
3802 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3805 struct cgroup_event *event = NULL;
3806 struct cgroup *cgrp_cfile;
3807 unsigned int efd, cfd;
3808 struct file *efile = NULL;
3809 struct file *cfile = NULL;
3813 efd = simple_strtoul(buffer, &endp, 10);
3818 cfd = simple_strtoul(buffer, &endp, 10);
3819 if ((*endp != ' ') && (*endp != '\0'))
3823 event = kzalloc(sizeof(*event), GFP_KERNEL);
3827 INIT_LIST_HEAD(&event->list);
3828 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3829 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3830 INIT_WORK(&event->remove, cgroup_event_remove);
3832 efile = eventfd_fget(efd);
3833 if (IS_ERR(efile)) {
3834 ret = PTR_ERR(efile);
3838 event->eventfd = eventfd_ctx_fileget(efile);
3839 if (IS_ERR(event->eventfd)) {
3840 ret = PTR_ERR(event->eventfd);
3850 /* the process need read permission on control file */
3851 /* AV: shouldn't we check that it's been opened for read instead? */
3852 ret = inode_permission(file_inode(cfile), MAY_READ);
3856 event->cft = __file_cft(cfile);
3857 if (IS_ERR(event->cft)) {
3858 ret = PTR_ERR(event->cft);
3863 * The file to be monitored must be in the same cgroup as
3864 * cgroup.event_control is.
3866 cgrp_cfile = __d_cgrp(cfile->f_dentry->d_parent);
3867 if (cgrp_cfile != cgrp) {
3872 if (!event->cft->register_event || !event->cft->unregister_event) {
3877 ret = event->cft->register_event(cgrp, event->cft,
3878 event->eventfd, buffer);
3883 * Events should be removed after rmdir of cgroup directory, but before
3884 * destroying subsystem state objects. Let's take reference to cgroup
3885 * directory dentry to do that.
3889 spin_lock(&cgrp->event_list_lock);
3890 list_add(&event->list, &cgrp->event_list);
3891 spin_unlock(&cgrp->event_list_lock);
3902 if (event && event->eventfd && !IS_ERR(event->eventfd))
3903 eventfd_ctx_put(event->eventfd);
3905 if (!IS_ERR_OR_NULL(efile))
3913 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
3916 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3919 static int cgroup_clone_children_write(struct cgroup *cgrp,
3924 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3926 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3931 * for the common functions, 'private' gives the type of file
3933 /* for hysterical raisins, we can't put this on the older files */
3934 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3935 static struct cftype files[] = {
3938 .open = cgroup_tasks_open,
3939 .write_u64 = cgroup_tasks_write,
3940 .release = cgroup_pidlist_release,
3941 .mode = S_IRUGO | S_IWUSR,
3944 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
3945 .open = cgroup_procs_open,
3946 .write_u64 = cgroup_procs_write,
3947 .release = cgroup_pidlist_release,
3948 .mode = S_IRUGO | S_IWUSR,
3951 .name = "notify_on_release",
3952 .read_u64 = cgroup_read_notify_on_release,
3953 .write_u64 = cgroup_write_notify_on_release,
3956 .name = CGROUP_FILE_GENERIC_PREFIX "event_control",
3957 .write_string = cgroup_write_event_control,
3961 .name = "cgroup.clone_children",
3962 .flags = CFTYPE_INSANE,
3963 .read_u64 = cgroup_clone_children_read,
3964 .write_u64 = cgroup_clone_children_write,
3967 .name = "cgroup.sane_behavior",
3968 .flags = CFTYPE_ONLY_ON_ROOT,
3969 .read_seq_string = cgroup_sane_behavior_show,
3972 .name = "release_agent",
3973 .flags = CFTYPE_ONLY_ON_ROOT,
3974 .read_seq_string = cgroup_release_agent_show,
3975 .write_string = cgroup_release_agent_write,
3976 .max_write_len = PATH_MAX,
3982 * cgroup_populate_dir - selectively creation of files in a directory
3983 * @cgrp: target cgroup
3984 * @base_files: true if the base files should be added
3985 * @subsys_mask: mask of the subsystem ids whose files should be added
3987 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
3988 unsigned long subsys_mask)
3991 struct cgroup_subsys *ss;
3994 err = cgroup_addrm_files(cgrp, NULL, files, true);
3999 /* process cftsets of each subsystem */
4000 for_each_subsys(cgrp->root, ss) {
4001 struct cftype_set *set;
4002 if (!test_bit(ss->subsys_id, &subsys_mask))
4005 list_for_each_entry(set, &ss->cftsets, node)
4006 cgroup_addrm_files(cgrp, ss, set->cfts, true);
4009 /* This cgroup is ready now */
4010 for_each_subsys(cgrp->root, ss) {
4011 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4013 * Update id->css pointer and make this css visible from
4014 * CSS ID functions. This pointer will be dereferened
4015 * from RCU-read-side without locks.
4018 rcu_assign_pointer(css->id->css, css);
4024 static void css_dput_fn(struct work_struct *work)
4026 struct cgroup_subsys_state *css =
4027 container_of(work, struct cgroup_subsys_state, dput_work);
4028 struct dentry *dentry = css->cgroup->dentry;
4029 struct super_block *sb = dentry->d_sb;
4031 atomic_inc(&sb->s_active);
4033 deactivate_super(sb);
4036 static void init_cgroup_css(struct cgroup_subsys_state *css,
4037 struct cgroup_subsys *ss,
4038 struct cgroup *cgrp)
4041 atomic_set(&css->refcnt, 1);
4044 if (cgrp == dummytop)
4045 css->flags |= CSS_ROOT;
4046 BUG_ON(cgrp->subsys[ss->subsys_id]);
4047 cgrp->subsys[ss->subsys_id] = css;
4050 * css holds an extra ref to @cgrp->dentry which is put on the last
4051 * css_put(). dput() requires process context, which css_put() may
4052 * be called without. @css->dput_work will be used to invoke
4053 * dput() asynchronously from css_put().
4055 INIT_WORK(&css->dput_work, css_dput_fn);
4058 /* invoke ->post_create() on a new CSS and mark it online if successful */
4059 static int online_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4063 lockdep_assert_held(&cgroup_mutex);
4066 ret = ss->css_online(cgrp);
4068 cgrp->subsys[ss->subsys_id]->flags |= CSS_ONLINE;
4072 /* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4073 static void offline_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4074 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4076 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4078 lockdep_assert_held(&cgroup_mutex);
4080 if (!(css->flags & CSS_ONLINE))
4083 if (ss->css_offline)
4084 ss->css_offline(cgrp);
4086 cgrp->subsys[ss->subsys_id]->flags &= ~CSS_ONLINE;
4090 * cgroup_create - create a cgroup
4091 * @parent: cgroup that will be parent of the new cgroup
4092 * @dentry: dentry of the new cgroup
4093 * @mode: mode to set on new inode
4095 * Must be called with the mutex on the parent inode held
4097 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4100 struct cgroup *cgrp;
4101 struct cgroup_name *name;
4102 struct cgroupfs_root *root = parent->root;
4104 struct cgroup_subsys *ss;
4105 struct super_block *sb = root->sb;
4107 /* allocate the cgroup and its ID, 0 is reserved for the root */
4108 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4112 name = cgroup_alloc_name(dentry);
4115 rcu_assign_pointer(cgrp->name, name);
4117 cgrp->id = ida_simple_get(&root->cgroup_ida, 1, 0, GFP_KERNEL);
4122 * Only live parents can have children. Note that the liveliness
4123 * check isn't strictly necessary because cgroup_mkdir() and
4124 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4125 * anyway so that locking is contained inside cgroup proper and we
4126 * don't get nasty surprises if we ever grow another caller.
4128 if (!cgroup_lock_live_group(parent)) {
4133 /* Grab a reference on the superblock so the hierarchy doesn't
4134 * get deleted on unmount if there are child cgroups. This
4135 * can be done outside cgroup_mutex, since the sb can't
4136 * disappear while someone has an open control file on the
4138 atomic_inc(&sb->s_active);
4140 init_cgroup_housekeeping(cgrp);
4142 dentry->d_fsdata = cgrp;
4143 cgrp->dentry = dentry;
4145 cgrp->parent = parent;
4146 cgrp->root = parent->root;
4148 if (notify_on_release(parent))
4149 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4151 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4152 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4154 for_each_subsys(root, ss) {
4155 struct cgroup_subsys_state *css;
4157 css = ss->css_alloc(cgrp);
4162 init_cgroup_css(css, ss, cgrp);
4164 err = alloc_css_id(ss, parent, cgrp);
4171 * Create directory. cgroup_create_file() returns with the new
4172 * directory locked on success so that it can be populated without
4173 * dropping cgroup_mutex.
4175 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4178 lockdep_assert_held(&dentry->d_inode->i_mutex);
4180 /* allocation complete, commit to creation */
4181 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4182 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4183 root->number_of_cgroups++;
4185 /* each css holds a ref to the cgroup's dentry */
4186 for_each_subsys(root, ss)
4189 /* hold a ref to the parent's dentry */
4190 dget(parent->dentry);
4192 /* creation succeeded, notify subsystems */
4193 for_each_subsys(root, ss) {
4194 err = online_css(ss, cgrp);
4198 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4200 pr_warning("cgroup: %s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4201 current->comm, current->pid, ss->name);
4202 if (!strcmp(ss->name, "memory"))
4203 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4204 ss->warned_broken_hierarchy = true;
4208 err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4212 mutex_unlock(&cgroup_mutex);
4213 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4218 for_each_subsys(root, ss) {
4219 if (cgrp->subsys[ss->subsys_id])
4222 mutex_unlock(&cgroup_mutex);
4223 /* Release the reference count that we took on the superblock */
4224 deactivate_super(sb);
4226 ida_simple_remove(&root->cgroup_ida, cgrp->id);
4228 kfree(rcu_dereference_raw(cgrp->name));
4234 cgroup_destroy_locked(cgrp);
4235 mutex_unlock(&cgroup_mutex);
4236 mutex_unlock(&dentry->d_inode->i_mutex);
4240 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4242 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4244 /* the vfs holds inode->i_mutex already */
4245 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4248 static int cgroup_destroy_locked(struct cgroup *cgrp)
4249 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4251 struct dentry *d = cgrp->dentry;
4252 struct cgroup *parent = cgrp->parent;
4253 struct cgroup_event *event, *tmp;
4254 struct cgroup_subsys *ss;
4256 lockdep_assert_held(&d->d_inode->i_mutex);
4257 lockdep_assert_held(&cgroup_mutex);
4259 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children))
4263 * Block new css_tryget() by deactivating refcnt and mark @cgrp
4264 * removed. This makes future css_tryget() and child creation
4265 * attempts fail thus maintaining the removal conditions verified
4268 for_each_subsys(cgrp->root, ss) {
4269 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4271 WARN_ON(atomic_read(&css->refcnt) < 0);
4272 atomic_add(CSS_DEACT_BIAS, &css->refcnt);
4274 set_bit(CGRP_REMOVED, &cgrp->flags);
4276 /* tell subsystems to initate destruction */
4277 for_each_subsys(cgrp->root, ss)
4278 offline_css(ss, cgrp);
4281 * Put all the base refs. Each css holds an extra reference to the
4282 * cgroup's dentry and cgroup removal proceeds regardless of css
4283 * refs. On the last put of each css, whenever that may be, the
4284 * extra dentry ref is put so that dentry destruction happens only
4285 * after all css's are released.
4287 for_each_subsys(cgrp->root, ss)
4288 css_put(cgrp->subsys[ss->subsys_id]);
4290 raw_spin_lock(&release_list_lock);
4291 if (!list_empty(&cgrp->release_list))
4292 list_del_init(&cgrp->release_list);
4293 raw_spin_unlock(&release_list_lock);
4295 /* delete this cgroup from parent->children */
4296 list_del_rcu(&cgrp->sibling);
4297 list_del_init(&cgrp->allcg_node);
4300 cgroup_d_remove_dir(d);
4303 set_bit(CGRP_RELEASABLE, &parent->flags);
4304 check_for_release(parent);
4307 * Unregister events and notify userspace.
4308 * Notify userspace about cgroup removing only after rmdir of cgroup
4309 * directory to avoid race between userspace and kernelspace.
4311 spin_lock(&cgrp->event_list_lock);
4312 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4313 list_del_init(&event->list);
4314 schedule_work(&event->remove);
4316 spin_unlock(&cgrp->event_list_lock);
4321 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4325 mutex_lock(&cgroup_mutex);
4326 ret = cgroup_destroy_locked(dentry->d_fsdata);
4327 mutex_unlock(&cgroup_mutex);
4332 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4334 INIT_LIST_HEAD(&ss->cftsets);
4337 * base_cftset is embedded in subsys itself, no need to worry about
4340 if (ss->base_cftypes) {
4341 ss->base_cftset.cfts = ss->base_cftypes;
4342 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4346 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4348 struct cgroup_subsys_state *css;
4350 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4352 mutex_lock(&cgroup_mutex);
4354 /* init base cftset */
4355 cgroup_init_cftsets(ss);
4357 /* Create the top cgroup state for this subsystem */
4358 list_add(&ss->sibling, &rootnode.subsys_list);
4359 ss->root = &rootnode;
4360 css = ss->css_alloc(dummytop);
4361 /* We don't handle early failures gracefully */
4362 BUG_ON(IS_ERR(css));
4363 init_cgroup_css(css, ss, dummytop);
4365 /* Update the init_css_set to contain a subsys
4366 * pointer to this state - since the subsystem is
4367 * newly registered, all tasks and hence the
4368 * init_css_set is in the subsystem's top cgroup. */
4369 init_css_set.subsys[ss->subsys_id] = css;
4371 need_forkexit_callback |= ss->fork || ss->exit;
4373 /* At system boot, before all subsystems have been
4374 * registered, no tasks have been forked, so we don't
4375 * need to invoke fork callbacks here. */
4376 BUG_ON(!list_empty(&init_task.tasks));
4379 BUG_ON(online_css(ss, dummytop));
4381 mutex_unlock(&cgroup_mutex);
4383 /* this function shouldn't be used with modular subsystems, since they
4384 * need to register a subsys_id, among other things */
4389 * cgroup_load_subsys: load and register a modular subsystem at runtime
4390 * @ss: the subsystem to load
4392 * This function should be called in a modular subsystem's initcall. If the
4393 * subsystem is built as a module, it will be assigned a new subsys_id and set
4394 * up for use. If the subsystem is built-in anyway, work is delegated to the
4395 * simpler cgroup_init_subsys.
4397 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4399 struct cgroup_subsys_state *css;
4401 struct hlist_node *tmp;
4405 /* check name and function validity */
4406 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4407 ss->css_alloc == NULL || ss->css_free == NULL)
4411 * we don't support callbacks in modular subsystems. this check is
4412 * before the ss->module check for consistency; a subsystem that could
4413 * be a module should still have no callbacks even if the user isn't
4414 * compiling it as one.
4416 if (ss->fork || ss->exit)
4420 * an optionally modular subsystem is built-in: we want to do nothing,
4421 * since cgroup_init_subsys will have already taken care of it.
4423 if (ss->module == NULL) {
4424 /* a sanity check */
4425 BUG_ON(subsys[ss->subsys_id] != ss);
4429 /* init base cftset */
4430 cgroup_init_cftsets(ss);
4432 mutex_lock(&cgroup_mutex);
4433 subsys[ss->subsys_id] = ss;
4436 * no ss->css_alloc seems to need anything important in the ss
4437 * struct, so this can happen first (i.e. before the rootnode
4440 css = ss->css_alloc(dummytop);
4442 /* failure case - need to deassign the subsys[] slot. */
4443 subsys[ss->subsys_id] = NULL;
4444 mutex_unlock(&cgroup_mutex);
4445 return PTR_ERR(css);
4448 list_add(&ss->sibling, &rootnode.subsys_list);
4449 ss->root = &rootnode;
4451 /* our new subsystem will be attached to the dummy hierarchy. */
4452 init_cgroup_css(css, ss, dummytop);
4453 /* init_idr must be after init_cgroup_css because it sets css->id. */
4455 ret = cgroup_init_idr(ss, css);
4461 * Now we need to entangle the css into the existing css_sets. unlike
4462 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4463 * will need a new pointer to it; done by iterating the css_set_table.
4464 * furthermore, modifying the existing css_sets will corrupt the hash
4465 * table state, so each changed css_set will need its hash recomputed.
4466 * this is all done under the css_set_lock.
4468 write_lock(&css_set_lock);
4469 hash_for_each_safe(css_set_table, i, tmp, cg, hlist) {
4470 /* skip entries that we already rehashed */
4471 if (cg->subsys[ss->subsys_id])
4473 /* remove existing entry */
4474 hash_del(&cg->hlist);
4476 cg->subsys[ss->subsys_id] = css;
4477 /* recompute hash and restore entry */
4478 key = css_set_hash(cg->subsys);
4479 hash_add(css_set_table, &cg->hlist, key);
4481 write_unlock(&css_set_lock);
4484 ret = online_css(ss, dummytop);
4489 mutex_unlock(&cgroup_mutex);
4493 mutex_unlock(&cgroup_mutex);
4494 /* @ss can't be mounted here as try_module_get() would fail */
4495 cgroup_unload_subsys(ss);
4498 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4501 * cgroup_unload_subsys: unload a modular subsystem
4502 * @ss: the subsystem to unload
4504 * This function should be called in a modular subsystem's exitcall. When this
4505 * function is invoked, the refcount on the subsystem's module will be 0, so
4506 * the subsystem will not be attached to any hierarchy.
4508 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4510 struct cg_cgroup_link *link;
4512 BUG_ON(ss->module == NULL);
4515 * we shouldn't be called if the subsystem is in use, and the use of
4516 * try_module_get in parse_cgroupfs_options should ensure that it
4517 * doesn't start being used while we're killing it off.
4519 BUG_ON(ss->root != &rootnode);
4521 mutex_lock(&cgroup_mutex);
4523 offline_css(ss, dummytop);
4527 idr_destroy(&ss->idr);
4529 /* deassign the subsys_id */
4530 subsys[ss->subsys_id] = NULL;
4532 /* remove subsystem from rootnode's list of subsystems */
4533 list_del_init(&ss->sibling);
4536 * disentangle the css from all css_sets attached to the dummytop. as
4537 * in loading, we need to pay our respects to the hashtable gods.
4539 write_lock(&css_set_lock);
4540 list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
4541 struct css_set *cg = link->cg;
4544 hash_del(&cg->hlist);
4545 cg->subsys[ss->subsys_id] = NULL;
4546 key = css_set_hash(cg->subsys);
4547 hash_add(css_set_table, &cg->hlist, key);
4549 write_unlock(&css_set_lock);
4552 * remove subsystem's css from the dummytop and free it - need to
4553 * free before marking as null because ss->css_free needs the
4554 * cgrp->subsys pointer to find their state. note that this also
4555 * takes care of freeing the css_id.
4557 ss->css_free(dummytop);
4558 dummytop->subsys[ss->subsys_id] = NULL;
4560 mutex_unlock(&cgroup_mutex);
4562 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4565 * cgroup_init_early - cgroup initialization at system boot
4567 * Initialize cgroups at system boot, and initialize any
4568 * subsystems that request early init.
4570 int __init cgroup_init_early(void)
4573 atomic_set(&init_css_set.refcount, 1);
4574 INIT_LIST_HEAD(&init_css_set.cg_links);
4575 INIT_LIST_HEAD(&init_css_set.tasks);
4576 INIT_HLIST_NODE(&init_css_set.hlist);
4578 init_cgroup_root(&rootnode);
4580 init_task.cgroups = &init_css_set;
4582 init_css_set_link.cg = &init_css_set;
4583 init_css_set_link.cgrp = dummytop;
4584 list_add(&init_css_set_link.cgrp_link_list,
4585 &rootnode.top_cgroup.css_sets);
4586 list_add(&init_css_set_link.cg_link_list,
4587 &init_css_set.cg_links);
4589 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4590 struct cgroup_subsys *ss = subsys[i];
4592 /* at bootup time, we don't worry about modular subsystems */
4593 if (!ss || ss->module)
4597 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4598 BUG_ON(!ss->css_alloc);
4599 BUG_ON(!ss->css_free);
4600 if (ss->subsys_id != i) {
4601 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4602 ss->name, ss->subsys_id);
4607 cgroup_init_subsys(ss);
4613 * cgroup_init - cgroup initialization
4615 * Register cgroup filesystem and /proc file, and initialize
4616 * any subsystems that didn't request early init.
4618 int __init cgroup_init(void)
4624 err = bdi_init(&cgroup_backing_dev_info);
4628 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4629 struct cgroup_subsys *ss = subsys[i];
4631 /* at bootup time, we don't worry about modular subsystems */
4632 if (!ss || ss->module)
4634 if (!ss->early_init)
4635 cgroup_init_subsys(ss);
4637 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4640 /* Add init_css_set to the hash table */
4641 key = css_set_hash(init_css_set.subsys);
4642 hash_add(css_set_table, &init_css_set.hlist, key);
4643 BUG_ON(!init_root_id(&rootnode));
4645 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4651 err = register_filesystem(&cgroup_fs_type);
4653 kobject_put(cgroup_kobj);
4657 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4661 bdi_destroy(&cgroup_backing_dev_info);
4667 * proc_cgroup_show()
4668 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4669 * - Used for /proc/<pid>/cgroup.
4670 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4671 * doesn't really matter if tsk->cgroup changes after we read it,
4672 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4673 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4674 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4675 * cgroup to top_cgroup.
4678 /* TODO: Use a proper seq_file iterator */
4679 static int proc_cgroup_show(struct seq_file *m, void *v)
4682 struct task_struct *tsk;
4685 struct cgroupfs_root *root;
4688 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4694 tsk = get_pid_task(pid, PIDTYPE_PID);
4700 mutex_lock(&cgroup_mutex);
4702 for_each_active_root(root) {
4703 struct cgroup_subsys *ss;
4704 struct cgroup *cgrp;
4707 seq_printf(m, "%d:", root->hierarchy_id);
4708 for_each_subsys(root, ss)
4709 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4710 if (strlen(root->name))
4711 seq_printf(m, "%sname=%s", count ? "," : "",
4714 cgrp = task_cgroup_from_root(tsk, root);
4715 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4723 mutex_unlock(&cgroup_mutex);
4724 put_task_struct(tsk);
4731 static int cgroup_open(struct inode *inode, struct file *file)
4733 struct pid *pid = PROC_I(inode)->pid;
4734 return single_open(file, proc_cgroup_show, pid);
4737 const struct file_operations proc_cgroup_operations = {
4738 .open = cgroup_open,
4740 .llseek = seq_lseek,
4741 .release = single_release,
4744 /* Display information about each subsystem and each hierarchy */
4745 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4749 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4751 * ideally we don't want subsystems moving around while we do this.
4752 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4753 * subsys/hierarchy state.
4755 mutex_lock(&cgroup_mutex);
4756 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4757 struct cgroup_subsys *ss = subsys[i];
4760 seq_printf(m, "%s\t%d\t%d\t%d\n",
4761 ss->name, ss->root->hierarchy_id,
4762 ss->root->number_of_cgroups, !ss->disabled);
4764 mutex_unlock(&cgroup_mutex);
4768 static int cgroupstats_open(struct inode *inode, struct file *file)
4770 return single_open(file, proc_cgroupstats_show, NULL);
4773 static const struct file_operations proc_cgroupstats_operations = {
4774 .open = cgroupstats_open,
4776 .llseek = seq_lseek,
4777 .release = single_release,
4781 * cgroup_fork - attach newly forked task to its parents cgroup.
4782 * @child: pointer to task_struct of forking parent process.
4784 * Description: A task inherits its parent's cgroup at fork().
4786 * A pointer to the shared css_set was automatically copied in
4787 * fork.c by dup_task_struct(). However, we ignore that copy, since
4788 * it was not made under the protection of RCU or cgroup_mutex, so
4789 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4790 * have already changed current->cgroups, allowing the previously
4791 * referenced cgroup group to be removed and freed.
4793 * At the point that cgroup_fork() is called, 'current' is the parent
4794 * task, and the passed argument 'child' points to the child task.
4796 void cgroup_fork(struct task_struct *child)
4799 child->cgroups = current->cgroups;
4800 get_css_set(child->cgroups);
4801 task_unlock(current);
4802 INIT_LIST_HEAD(&child->cg_list);
4806 * cgroup_post_fork - called on a new task after adding it to the task list
4807 * @child: the task in question
4809 * Adds the task to the list running through its css_set if necessary and
4810 * call the subsystem fork() callbacks. Has to be after the task is
4811 * visible on the task list in case we race with the first call to
4812 * cgroup_iter_start() - to guarantee that the new task ends up on its
4815 void cgroup_post_fork(struct task_struct *child)
4820 * use_task_css_set_links is set to 1 before we walk the tasklist
4821 * under the tasklist_lock and we read it here after we added the child
4822 * to the tasklist under the tasklist_lock as well. If the child wasn't
4823 * yet in the tasklist when we walked through it from
4824 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4825 * should be visible now due to the paired locking and barriers implied
4826 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4827 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4830 if (use_task_css_set_links) {
4831 write_lock(&css_set_lock);
4833 if (list_empty(&child->cg_list))
4834 list_add(&child->cg_list, &child->cgroups->tasks);
4836 write_unlock(&css_set_lock);
4840 * Call ss->fork(). This must happen after @child is linked on
4841 * css_set; otherwise, @child might change state between ->fork()
4842 * and addition to css_set.
4844 if (need_forkexit_callback) {
4846 * fork/exit callbacks are supported only for builtin
4847 * subsystems, and the builtin section of the subsys
4848 * array is immutable, so we don't need to lock the
4849 * subsys array here. On the other hand, modular section
4850 * of the array can be freed at module unload, so we
4853 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4854 struct cgroup_subsys *ss = subsys[i];
4863 * cgroup_exit - detach cgroup from exiting task
4864 * @tsk: pointer to task_struct of exiting process
4865 * @run_callback: run exit callbacks?
4867 * Description: Detach cgroup from @tsk and release it.
4869 * Note that cgroups marked notify_on_release force every task in
4870 * them to take the global cgroup_mutex mutex when exiting.
4871 * This could impact scaling on very large systems. Be reluctant to
4872 * use notify_on_release cgroups where very high task exit scaling
4873 * is required on large systems.
4875 * the_top_cgroup_hack:
4877 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4879 * We call cgroup_exit() while the task is still competent to
4880 * handle notify_on_release(), then leave the task attached to the
4881 * root cgroup in each hierarchy for the remainder of its exit.
4883 * To do this properly, we would increment the reference count on
4884 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4885 * code we would add a second cgroup function call, to drop that
4886 * reference. This would just create an unnecessary hot spot on
4887 * the top_cgroup reference count, to no avail.
4889 * Normally, holding a reference to a cgroup without bumping its
4890 * count is unsafe. The cgroup could go away, or someone could
4891 * attach us to a different cgroup, decrementing the count on
4892 * the first cgroup that we never incremented. But in this case,
4893 * top_cgroup isn't going away, and either task has PF_EXITING set,
4894 * which wards off any cgroup_attach_task() attempts, or task is a failed
4895 * fork, never visible to cgroup_attach_task.
4897 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4903 * Unlink from the css_set task list if necessary.
4904 * Optimistically check cg_list before taking
4907 if (!list_empty(&tsk->cg_list)) {
4908 write_lock(&css_set_lock);
4909 if (!list_empty(&tsk->cg_list))
4910 list_del_init(&tsk->cg_list);
4911 write_unlock(&css_set_lock);
4914 /* Reassign the task to the init_css_set. */
4917 tsk->cgroups = &init_css_set;
4919 if (run_callbacks && need_forkexit_callback) {
4921 * fork/exit callbacks are supported only for builtin
4922 * subsystems, see cgroup_post_fork() for details.
4924 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4925 struct cgroup_subsys *ss = subsys[i];
4928 struct cgroup *old_cgrp =
4929 rcu_dereference_raw(cg->subsys[i])->cgroup;
4930 struct cgroup *cgrp = task_cgroup(tsk, i);
4931 ss->exit(cgrp, old_cgrp, tsk);
4937 put_css_set_taskexit(cg);
4940 static void check_for_release(struct cgroup *cgrp)
4942 /* All of these checks rely on RCU to keep the cgroup
4943 * structure alive */
4944 if (cgroup_is_releasable(cgrp) &&
4945 !atomic_read(&cgrp->count) && list_empty(&cgrp->children)) {
4947 * Control Group is currently removeable. If it's not
4948 * already queued for a userspace notification, queue
4951 int need_schedule_work = 0;
4953 raw_spin_lock(&release_list_lock);
4954 if (!cgroup_is_removed(cgrp) &&
4955 list_empty(&cgrp->release_list)) {
4956 list_add(&cgrp->release_list, &release_list);
4957 need_schedule_work = 1;
4959 raw_spin_unlock(&release_list_lock);
4960 if (need_schedule_work)
4961 schedule_work(&release_agent_work);
4965 /* Caller must verify that the css is not for root cgroup */
4966 bool __css_tryget(struct cgroup_subsys_state *css)
4971 v = css_refcnt(css);
4972 t = atomic_cmpxchg(&css->refcnt, v, v + 1);
4980 EXPORT_SYMBOL_GPL(__css_tryget);
4982 /* Caller must verify that the css is not for root cgroup */
4983 void __css_put(struct cgroup_subsys_state *css)
4987 v = css_unbias_refcnt(atomic_dec_return(&css->refcnt));
4989 schedule_work(&css->dput_work);
4991 EXPORT_SYMBOL_GPL(__css_put);
4994 * Notify userspace when a cgroup is released, by running the
4995 * configured release agent with the name of the cgroup (path
4996 * relative to the root of cgroup file system) as the argument.
4998 * Most likely, this user command will try to rmdir this cgroup.
5000 * This races with the possibility that some other task will be
5001 * attached to this cgroup before it is removed, or that some other
5002 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5003 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5004 * unused, and this cgroup will be reprieved from its death sentence,
5005 * to continue to serve a useful existence. Next time it's released,
5006 * we will get notified again, if it still has 'notify_on_release' set.
5008 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5009 * means only wait until the task is successfully execve()'d. The
5010 * separate release agent task is forked by call_usermodehelper(),
5011 * then control in this thread returns here, without waiting for the
5012 * release agent task. We don't bother to wait because the caller of
5013 * this routine has no use for the exit status of the release agent
5014 * task, so no sense holding our caller up for that.
5016 static void cgroup_release_agent(struct work_struct *work)
5018 BUG_ON(work != &release_agent_work);
5019 mutex_lock(&cgroup_mutex);
5020 raw_spin_lock(&release_list_lock);
5021 while (!list_empty(&release_list)) {
5022 char *argv[3], *envp[3];
5024 char *pathbuf = NULL, *agentbuf = NULL;
5025 struct cgroup *cgrp = list_entry(release_list.next,
5028 list_del_init(&cgrp->release_list);
5029 raw_spin_unlock(&release_list_lock);
5030 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5033 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5035 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5040 argv[i++] = agentbuf;
5041 argv[i++] = pathbuf;
5045 /* minimal command environment */
5046 envp[i++] = "HOME=/";
5047 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5050 /* Drop the lock while we invoke the usermode helper,
5051 * since the exec could involve hitting disk and hence
5052 * be a slow process */
5053 mutex_unlock(&cgroup_mutex);
5054 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5055 mutex_lock(&cgroup_mutex);
5059 raw_spin_lock(&release_list_lock);
5061 raw_spin_unlock(&release_list_lock);
5062 mutex_unlock(&cgroup_mutex);
5065 static int __init cgroup_disable(char *str)
5070 while ((token = strsep(&str, ",")) != NULL) {
5073 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
5074 struct cgroup_subsys *ss = subsys[i];
5077 * cgroup_disable, being at boot time, can't
5078 * know about module subsystems, so we don't
5081 if (!ss || ss->module)
5084 if (!strcmp(token, ss->name)) {
5086 printk(KERN_INFO "Disabling %s control group"
5087 " subsystem\n", ss->name);
5094 __setup("cgroup_disable=", cgroup_disable);
5097 * Functons for CSS ID.
5101 *To get ID other than 0, this should be called when !cgroup_is_removed().
5103 unsigned short css_id(struct cgroup_subsys_state *css)
5105 struct css_id *cssid;
5108 * This css_id() can return correct value when somone has refcnt
5109 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5110 * it's unchanged until freed.
5112 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5118 EXPORT_SYMBOL_GPL(css_id);
5120 unsigned short css_depth(struct cgroup_subsys_state *css)
5122 struct css_id *cssid;
5124 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5127 return cssid->depth;
5130 EXPORT_SYMBOL_GPL(css_depth);
5133 * css_is_ancestor - test "root" css is an ancestor of "child"
5134 * @child: the css to be tested.
5135 * @root: the css supporsed to be an ancestor of the child.
5137 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5138 * this function reads css->id, the caller must hold rcu_read_lock().
5139 * But, considering usual usage, the csses should be valid objects after test.
5140 * Assuming that the caller will do some action to the child if this returns
5141 * returns true, the caller must take "child";s reference count.
5142 * If "child" is valid object and this returns true, "root" is valid, too.
5145 bool css_is_ancestor(struct cgroup_subsys_state *child,
5146 const struct cgroup_subsys_state *root)
5148 struct css_id *child_id;
5149 struct css_id *root_id;
5151 child_id = rcu_dereference(child->id);
5154 root_id = rcu_dereference(root->id);
5157 if (child_id->depth < root_id->depth)
5159 if (child_id->stack[root_id->depth] != root_id->id)
5164 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5166 struct css_id *id = css->id;
5167 /* When this is called before css_id initialization, id can be NULL */
5171 BUG_ON(!ss->use_id);
5173 rcu_assign_pointer(id->css, NULL);
5174 rcu_assign_pointer(css->id, NULL);
5175 spin_lock(&ss->id_lock);
5176 idr_remove(&ss->idr, id->id);
5177 spin_unlock(&ss->id_lock);
5178 kfree_rcu(id, rcu_head);
5180 EXPORT_SYMBOL_GPL(free_css_id);
5183 * This is called by init or create(). Then, calls to this function are
5184 * always serialized (By cgroup_mutex() at create()).
5187 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5189 struct css_id *newid;
5192 BUG_ON(!ss->use_id);
5194 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5195 newid = kzalloc(size, GFP_KERNEL);
5197 return ERR_PTR(-ENOMEM);
5199 idr_preload(GFP_KERNEL);
5200 spin_lock(&ss->id_lock);
5201 /* Don't use 0. allocates an ID of 1-65535 */
5202 ret = idr_alloc(&ss->idr, newid, 1, CSS_ID_MAX + 1, GFP_NOWAIT);
5203 spin_unlock(&ss->id_lock);
5206 /* Returns error when there are no free spaces for new ID.*/
5211 newid->depth = depth;
5215 return ERR_PTR(ret);
5219 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5220 struct cgroup_subsys_state *rootcss)
5222 struct css_id *newid;
5224 spin_lock_init(&ss->id_lock);
5227 newid = get_new_cssid(ss, 0);
5229 return PTR_ERR(newid);
5231 newid->stack[0] = newid->id;
5232 newid->css = rootcss;
5233 rootcss->id = newid;
5237 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5238 struct cgroup *child)
5240 int subsys_id, i, depth = 0;
5241 struct cgroup_subsys_state *parent_css, *child_css;
5242 struct css_id *child_id, *parent_id;
5244 subsys_id = ss->subsys_id;
5245 parent_css = parent->subsys[subsys_id];
5246 child_css = child->subsys[subsys_id];
5247 parent_id = parent_css->id;
5248 depth = parent_id->depth + 1;
5250 child_id = get_new_cssid(ss, depth);
5251 if (IS_ERR(child_id))
5252 return PTR_ERR(child_id);
5254 for (i = 0; i < depth; i++)
5255 child_id->stack[i] = parent_id->stack[i];
5256 child_id->stack[depth] = child_id->id;
5258 * child_id->css pointer will be set after this cgroup is available
5259 * see cgroup_populate_dir()
5261 rcu_assign_pointer(child_css->id, child_id);
5267 * css_lookup - lookup css by id
5268 * @ss: cgroup subsys to be looked into.
5271 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5272 * NULL if not. Should be called under rcu_read_lock()
5274 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5276 struct css_id *cssid = NULL;
5278 BUG_ON(!ss->use_id);
5279 cssid = idr_find(&ss->idr, id);
5281 if (unlikely(!cssid))
5284 return rcu_dereference(cssid->css);
5286 EXPORT_SYMBOL_GPL(css_lookup);
5289 * css_get_next - lookup next cgroup under specified hierarchy.
5290 * @ss: pointer to subsystem
5291 * @id: current position of iteration.
5292 * @root: pointer to css. search tree under this.
5293 * @foundid: position of found object.
5295 * Search next css under the specified hierarchy of rootid. Calling under
5296 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
5298 struct cgroup_subsys_state *
5299 css_get_next(struct cgroup_subsys *ss, int id,
5300 struct cgroup_subsys_state *root, int *foundid)
5302 struct cgroup_subsys_state *ret = NULL;
5305 int rootid = css_id(root);
5306 int depth = css_depth(root);
5311 BUG_ON(!ss->use_id);
5312 WARN_ON_ONCE(!rcu_read_lock_held());
5314 /* fill start point for scan */
5318 * scan next entry from bitmap(tree), tmpid is updated after
5321 tmp = idr_get_next(&ss->idr, &tmpid);
5324 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
5325 ret = rcu_dereference(tmp->css);
5331 /* continue to scan from next id */
5338 * get corresponding css from file open on cgroupfs directory
5340 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5342 struct cgroup *cgrp;
5343 struct inode *inode;
5344 struct cgroup_subsys_state *css;
5346 inode = file_inode(f);
5347 /* check in cgroup filesystem dir */
5348 if (inode->i_op != &cgroup_dir_inode_operations)
5349 return ERR_PTR(-EBADF);
5351 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5352 return ERR_PTR(-EINVAL);
5355 cgrp = __d_cgrp(f->f_dentry);
5356 css = cgrp->subsys[id];
5357 return css ? css : ERR_PTR(-ENOENT);
5360 #ifdef CONFIG_CGROUP_DEBUG
5361 static struct cgroup_subsys_state *debug_css_alloc(struct cgroup *cont)
5363 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5366 return ERR_PTR(-ENOMEM);
5371 static void debug_css_free(struct cgroup *cont)
5373 kfree(cont->subsys[debug_subsys_id]);
5376 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
5378 return atomic_read(&cont->count);
5381 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5383 return cgroup_task_count(cont);
5386 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5388 return (u64)(unsigned long)current->cgroups;
5391 static u64 current_css_set_refcount_read(struct cgroup *cont,
5397 count = atomic_read(¤t->cgroups->refcount);
5402 static int current_css_set_cg_links_read(struct cgroup *cont,
5404 struct seq_file *seq)
5406 struct cg_cgroup_link *link;
5409 read_lock(&css_set_lock);
5411 cg = rcu_dereference(current->cgroups);
5412 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
5413 struct cgroup *c = link->cgrp;
5417 name = c->dentry->d_name.name;
5420 seq_printf(seq, "Root %d group %s\n",
5421 c->root->hierarchy_id, name);
5424 read_unlock(&css_set_lock);
5428 #define MAX_TASKS_SHOWN_PER_CSS 25
5429 static int cgroup_css_links_read(struct cgroup *cont,
5431 struct seq_file *seq)
5433 struct cg_cgroup_link *link;
5435 read_lock(&css_set_lock);
5436 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
5437 struct css_set *cg = link->cg;
5438 struct task_struct *task;
5440 seq_printf(seq, "css_set %p\n", cg);
5441 list_for_each_entry(task, &cg->tasks, cg_list) {
5442 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5443 seq_puts(seq, " ...\n");
5446 seq_printf(seq, " task %d\n",
5447 task_pid_vnr(task));
5451 read_unlock(&css_set_lock);
5455 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5457 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5460 static struct cftype debug_files[] = {
5462 .name = "cgroup_refcount",
5463 .read_u64 = cgroup_refcount_read,
5466 .name = "taskcount",
5467 .read_u64 = debug_taskcount_read,
5471 .name = "current_css_set",
5472 .read_u64 = current_css_set_read,
5476 .name = "current_css_set_refcount",
5477 .read_u64 = current_css_set_refcount_read,
5481 .name = "current_css_set_cg_links",
5482 .read_seq_string = current_css_set_cg_links_read,
5486 .name = "cgroup_css_links",
5487 .read_seq_string = cgroup_css_links_read,
5491 .name = "releasable",
5492 .read_u64 = releasable_read,
5498 struct cgroup_subsys debug_subsys = {
5500 .css_alloc = debug_css_alloc,
5501 .css_free = debug_css_free,
5502 .subsys_id = debug_subsys_id,
5503 .base_cftypes = debug_files,
5505 #endif /* CONFIG_CGROUP_DEBUG */