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>
63 #include <linux/file.h>
65 #include <linux/atomic.h>
68 * cgroup_mutex is the master lock. Any modification to cgroup or its
69 * hierarchy must be performed while holding it.
71 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
72 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
73 * release_agent_path and so on. Modifying requires both cgroup_mutex and
74 * cgroup_root_mutex. Readers can acquire either of the two. This is to
75 * break the following locking order cycle.
77 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
78 * B. namespace_sem -> cgroup_mutex
80 * B happens only through cgroup_show_options() and using cgroup_root_mutex
83 #ifdef CONFIG_PROVE_RCU
84 DEFINE_MUTEX(cgroup_mutex);
85 EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for lockdep */
87 static DEFINE_MUTEX(cgroup_mutex);
90 static DEFINE_MUTEX(cgroup_root_mutex);
93 * Generate an array of cgroup subsystem pointers. At boot time, this is
94 * populated with the built in subsystems, and modular subsystems are
95 * registered after that. The mutable section of this array is protected by
98 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
99 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
100 static struct cgroup_subsys *cgroup_subsys[CGROUP_SUBSYS_COUNT] = {
101 #include <linux/cgroup_subsys.h>
105 * The dummy hierarchy, reserved for the subsystems that are otherwise
106 * unattached - it never has more than a single cgroup, and all tasks are
107 * part of that cgroup.
109 static struct cgroupfs_root cgroup_dummy_root;
111 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
112 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
115 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
118 struct list_head node;
119 struct dentry *dentry;
121 struct cgroup_subsys_state *css;
124 struct simple_xattrs xattrs;
128 * cgroup_event represents events which userspace want to receive.
130 struct cgroup_event {
132 * css which the event belongs to.
134 struct cgroup_subsys_state *css;
136 * Control file which the event associated.
140 * eventfd to signal userspace about the event.
142 struct eventfd_ctx *eventfd;
144 * Each of these stored in a list by the cgroup.
146 struct list_head list;
148 * All fields below needed to unregister event when
149 * userspace closes eventfd.
152 wait_queue_head_t *wqh;
154 struct work_struct remove;
157 /* The list of hierarchy roots */
159 static LIST_HEAD(cgroup_roots);
160 static int cgroup_root_count;
163 * Hierarchy ID allocation and mapping. It follows the same exclusion
164 * rules as other root ops - both cgroup_mutex and cgroup_root_mutex for
165 * writes, either for reads.
167 static DEFINE_IDR(cgroup_hierarchy_idr);
169 static struct cgroup_name root_cgroup_name = { .name = "/" };
172 * Assign a monotonically increasing serial number to cgroups. It
173 * guarantees cgroups with bigger numbers are newer than those with smaller
174 * numbers. Also, as cgroups are always appended to the parent's
175 * ->children list, it guarantees that sibling cgroups are always sorted in
176 * the ascending serial number order on the list. Protected by
179 static u64 cgroup_serial_nr_next = 1;
181 /* This flag indicates whether tasks in the fork and exit paths should
182 * check for fork/exit handlers to call. This avoids us having to do
183 * extra work in the fork/exit path if none of the subsystems need to
186 static int need_forkexit_callback __read_mostly;
188 static struct cftype cgroup_base_files[];
190 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
191 static int cgroup_destroy_locked(struct cgroup *cgrp);
192 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
196 * cgroup_css - obtain a cgroup's css for the specified subsystem
197 * @cgrp: the cgroup of interest
198 * @ss: the subsystem of interest (%NULL returns the dummy_css)
200 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
201 * function must be called either under cgroup_mutex or rcu_read_lock() and
202 * the caller is responsible for pinning the returned css if it wants to
203 * keep accessing it outside the said locks. This function may return
204 * %NULL if @cgrp doesn't have @subsys_id enabled.
206 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
207 struct cgroup_subsys *ss)
210 return rcu_dereference_check(cgrp->subsys[ss->subsys_id],
211 lockdep_is_held(&cgroup_mutex));
213 return &cgrp->dummy_css;
216 /* convenient tests for these bits */
217 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
219 return test_bit(CGRP_DEAD, &cgrp->flags);
223 * cgroup_is_descendant - test ancestry
224 * @cgrp: the cgroup to be tested
225 * @ancestor: possible ancestor of @cgrp
227 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
228 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
229 * and @ancestor are accessible.
231 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
234 if (cgrp == ancestor)
240 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
242 static int cgroup_is_releasable(const struct cgroup *cgrp)
245 (1 << CGRP_RELEASABLE) |
246 (1 << CGRP_NOTIFY_ON_RELEASE);
247 return (cgrp->flags & bits) == bits;
250 static int notify_on_release(const struct cgroup *cgrp)
252 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
256 * for_each_subsys - iterate all loaded cgroup subsystems
257 * @ss: the iteration cursor
258 * @i: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
260 * Should be called under cgroup_mutex.
262 #define for_each_subsys(ss, i) \
263 for ((i) = 0; (i) < CGROUP_SUBSYS_COUNT; (i)++) \
264 if (({ lockdep_assert_held(&cgroup_mutex); \
265 !((ss) = cgroup_subsys[i]); })) { } \
269 * for_each_builtin_subsys - iterate all built-in cgroup subsystems
270 * @ss: the iteration cursor
271 * @i: the index of @ss, CGROUP_BUILTIN_SUBSYS_COUNT after reaching the end
273 * Bulit-in subsystems are always present and iteration itself doesn't
274 * require any synchronization.
276 #define for_each_builtin_subsys(ss, i) \
277 for ((i) = 0; (i) < CGROUP_BUILTIN_SUBSYS_COUNT && \
278 (((ss) = cgroup_subsys[i]) || true); (i)++)
280 /* iterate each subsystem attached to a hierarchy */
281 #define for_each_root_subsys(root, ss) \
282 list_for_each_entry((ss), &(root)->subsys_list, sibling)
284 /* iterate across the active hierarchies */
285 #define for_each_active_root(root) \
286 list_for_each_entry((root), &cgroup_roots, root_list)
288 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
290 return dentry->d_fsdata;
293 static inline struct cfent *__d_cfe(struct dentry *dentry)
295 return dentry->d_fsdata;
298 static inline struct cftype *__d_cft(struct dentry *dentry)
300 return __d_cfe(dentry)->type;
304 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
305 * @cgrp: the cgroup to be checked for liveness
307 * On success, returns true; the mutex should be later unlocked. On
308 * failure returns false with no lock held.
310 static bool cgroup_lock_live_group(struct cgroup *cgrp)
312 mutex_lock(&cgroup_mutex);
313 if (cgroup_is_dead(cgrp)) {
314 mutex_unlock(&cgroup_mutex);
320 /* the list of cgroups eligible for automatic release. Protected by
321 * release_list_lock */
322 static LIST_HEAD(release_list);
323 static DEFINE_RAW_SPINLOCK(release_list_lock);
324 static void cgroup_release_agent(struct work_struct *work);
325 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
326 static void check_for_release(struct cgroup *cgrp);
329 * A cgroup can be associated with multiple css_sets as different tasks may
330 * belong to different cgroups on different hierarchies. In the other
331 * direction, a css_set is naturally associated with multiple cgroups.
332 * This M:N relationship is represented by the following link structure
333 * which exists for each association and allows traversing the associations
336 struct cgrp_cset_link {
337 /* the cgroup and css_set this link associates */
339 struct css_set *cset;
341 /* list of cgrp_cset_links anchored at cgrp->cset_links */
342 struct list_head cset_link;
344 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
345 struct list_head cgrp_link;
348 /* The default css_set - used by init and its children prior to any
349 * hierarchies being mounted. It contains a pointer to the root state
350 * for each subsystem. Also used to anchor the list of css_sets. Not
351 * reference-counted, to improve performance when child cgroups
352 * haven't been created.
355 static struct css_set init_css_set;
356 static struct cgrp_cset_link init_cgrp_cset_link;
359 * css_set_lock protects the list of css_set objects, and the chain of
360 * tasks off each css_set. Nests outside task->alloc_lock due to
361 * css_task_iter_start().
363 static DEFINE_RWLOCK(css_set_lock);
364 static int css_set_count;
367 * hash table for cgroup groups. This improves the performance to find
368 * an existing css_set. This hash doesn't (currently) take into
369 * account cgroups in empty hierarchies.
371 #define CSS_SET_HASH_BITS 7
372 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
374 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
376 unsigned long key = 0UL;
377 struct cgroup_subsys *ss;
380 for_each_subsys(ss, i)
381 key += (unsigned long)css[i];
382 key = (key >> 16) ^ key;
388 * We don't maintain the lists running through each css_set to its task
389 * until after the first call to css_task_iter_start(). This reduces the
390 * fork()/exit() overhead for people who have cgroups compiled into their
391 * kernel but not actually in use.
393 static int use_task_css_set_links __read_mostly;
395 static void __put_css_set(struct css_set *cset, int taskexit)
397 struct cgrp_cset_link *link, *tmp_link;
400 * Ensure that the refcount doesn't hit zero while any readers
401 * can see it. Similar to atomic_dec_and_lock(), but for an
404 if (atomic_add_unless(&cset->refcount, -1, 1))
406 write_lock(&css_set_lock);
407 if (!atomic_dec_and_test(&cset->refcount)) {
408 write_unlock(&css_set_lock);
412 /* This css_set is dead. unlink it and release cgroup refcounts */
413 hash_del(&cset->hlist);
416 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
417 struct cgroup *cgrp = link->cgrp;
419 list_del(&link->cset_link);
420 list_del(&link->cgrp_link);
422 /* @cgrp can't go away while we're holding css_set_lock */
423 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
425 set_bit(CGRP_RELEASABLE, &cgrp->flags);
426 check_for_release(cgrp);
432 write_unlock(&css_set_lock);
433 kfree_rcu(cset, rcu_head);
437 * refcounted get/put for css_set objects
439 static inline void get_css_set(struct css_set *cset)
441 atomic_inc(&cset->refcount);
444 static inline void put_css_set(struct css_set *cset)
446 __put_css_set(cset, 0);
449 static inline void put_css_set_taskexit(struct css_set *cset)
451 __put_css_set(cset, 1);
455 * compare_css_sets - helper function for find_existing_css_set().
456 * @cset: candidate css_set being tested
457 * @old_cset: existing css_set for a task
458 * @new_cgrp: cgroup that's being entered by the task
459 * @template: desired set of css pointers in css_set (pre-calculated)
461 * Returns true if "cset" matches "old_cset" except for the hierarchy
462 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
464 static bool compare_css_sets(struct css_set *cset,
465 struct css_set *old_cset,
466 struct cgroup *new_cgrp,
467 struct cgroup_subsys_state *template[])
469 struct list_head *l1, *l2;
471 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
472 /* Not all subsystems matched */
477 * Compare cgroup pointers in order to distinguish between
478 * different cgroups in heirarchies with no subsystems. We
479 * could get by with just this check alone (and skip the
480 * memcmp above) but on most setups the memcmp check will
481 * avoid the need for this more expensive check on almost all
485 l1 = &cset->cgrp_links;
486 l2 = &old_cset->cgrp_links;
488 struct cgrp_cset_link *link1, *link2;
489 struct cgroup *cgrp1, *cgrp2;
493 /* See if we reached the end - both lists are equal length. */
494 if (l1 == &cset->cgrp_links) {
495 BUG_ON(l2 != &old_cset->cgrp_links);
498 BUG_ON(l2 == &old_cset->cgrp_links);
500 /* Locate the cgroups associated with these links. */
501 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
502 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
505 /* Hierarchies should be linked in the same order. */
506 BUG_ON(cgrp1->root != cgrp2->root);
509 * If this hierarchy is the hierarchy of the cgroup
510 * that's changing, then we need to check that this
511 * css_set points to the new cgroup; if it's any other
512 * hierarchy, then this css_set should point to the
513 * same cgroup as the old css_set.
515 if (cgrp1->root == new_cgrp->root) {
516 if (cgrp1 != new_cgrp)
527 * find_existing_css_set - init css array and find the matching css_set
528 * @old_cset: the css_set that we're using before the cgroup transition
529 * @cgrp: the cgroup that we're moving into
530 * @template: out param for the new set of csses, should be clear on entry
532 static struct css_set *find_existing_css_set(struct css_set *old_cset,
534 struct cgroup_subsys_state *template[])
536 struct cgroupfs_root *root = cgrp->root;
537 struct cgroup_subsys *ss;
538 struct css_set *cset;
543 * Build the set of subsystem state objects that we want to see in the
544 * new css_set. while subsystems can change globally, the entries here
545 * won't change, so no need for locking.
547 for_each_subsys(ss, i) {
548 if (root->subsys_mask & (1UL << i)) {
549 /* Subsystem is in this hierarchy. So we want
550 * the subsystem state from the new
552 template[i] = cgroup_css(cgrp, ss);
554 /* Subsystem is not in this hierarchy, so we
555 * don't want to change the subsystem state */
556 template[i] = old_cset->subsys[i];
560 key = css_set_hash(template);
561 hash_for_each_possible(css_set_table, cset, hlist, key) {
562 if (!compare_css_sets(cset, old_cset, cgrp, template))
565 /* This css_set matches what we need */
569 /* No existing cgroup group matched */
573 static void free_cgrp_cset_links(struct list_head *links_to_free)
575 struct cgrp_cset_link *link, *tmp_link;
577 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
578 list_del(&link->cset_link);
584 * allocate_cgrp_cset_links - allocate cgrp_cset_links
585 * @count: the number of links to allocate
586 * @tmp_links: list_head the allocated links are put on
588 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
589 * through ->cset_link. Returns 0 on success or -errno.
591 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
593 struct cgrp_cset_link *link;
596 INIT_LIST_HEAD(tmp_links);
598 for (i = 0; i < count; i++) {
599 link = kzalloc(sizeof(*link), GFP_KERNEL);
601 free_cgrp_cset_links(tmp_links);
604 list_add(&link->cset_link, tmp_links);
610 * link_css_set - a helper function to link a css_set to a cgroup
611 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
612 * @cset: the css_set to be linked
613 * @cgrp: the destination cgroup
615 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
618 struct cgrp_cset_link *link;
620 BUG_ON(list_empty(tmp_links));
621 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
624 list_move(&link->cset_link, &cgrp->cset_links);
626 * Always add links to the tail of the list so that the list
627 * is sorted by order of hierarchy creation
629 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
633 * find_css_set - return a new css_set with one cgroup updated
634 * @old_cset: the baseline css_set
635 * @cgrp: the cgroup to be updated
637 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
638 * substituted into the appropriate hierarchy.
640 static struct css_set *find_css_set(struct css_set *old_cset,
643 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
644 struct css_set *cset;
645 struct list_head tmp_links;
646 struct cgrp_cset_link *link;
649 lockdep_assert_held(&cgroup_mutex);
651 /* First see if we already have a cgroup group that matches
653 read_lock(&css_set_lock);
654 cset = find_existing_css_set(old_cset, cgrp, template);
657 read_unlock(&css_set_lock);
662 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
666 /* Allocate all the cgrp_cset_link objects that we'll need */
667 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
672 atomic_set(&cset->refcount, 1);
673 INIT_LIST_HEAD(&cset->cgrp_links);
674 INIT_LIST_HEAD(&cset->tasks);
675 INIT_HLIST_NODE(&cset->hlist);
677 /* Copy the set of subsystem state objects generated in
678 * find_existing_css_set() */
679 memcpy(cset->subsys, template, sizeof(cset->subsys));
681 write_lock(&css_set_lock);
682 /* Add reference counts and links from the new css_set. */
683 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
684 struct cgroup *c = link->cgrp;
686 if (c->root == cgrp->root)
688 link_css_set(&tmp_links, cset, c);
691 BUG_ON(!list_empty(&tmp_links));
695 /* Add this cgroup group to the hash table */
696 key = css_set_hash(cset->subsys);
697 hash_add(css_set_table, &cset->hlist, key);
699 write_unlock(&css_set_lock);
705 * Return the cgroup for "task" from the given hierarchy. Must be
706 * called with cgroup_mutex held.
708 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
709 struct cgroupfs_root *root)
711 struct css_set *cset;
712 struct cgroup *res = NULL;
714 BUG_ON(!mutex_is_locked(&cgroup_mutex));
715 read_lock(&css_set_lock);
717 * No need to lock the task - since we hold cgroup_mutex the
718 * task can't change groups, so the only thing that can happen
719 * is that it exits and its css is set back to init_css_set.
721 cset = task_css_set(task);
722 if (cset == &init_css_set) {
723 res = &root->top_cgroup;
725 struct cgrp_cset_link *link;
727 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
728 struct cgroup *c = link->cgrp;
730 if (c->root == root) {
736 read_unlock(&css_set_lock);
742 * There is one global cgroup mutex. We also require taking
743 * task_lock() when dereferencing a task's cgroup subsys pointers.
744 * See "The task_lock() exception", at the end of this comment.
746 * A task must hold cgroup_mutex to modify cgroups.
748 * Any task can increment and decrement the count field without lock.
749 * So in general, code holding cgroup_mutex can't rely on the count
750 * field not changing. However, if the count goes to zero, then only
751 * cgroup_attach_task() can increment it again. Because a count of zero
752 * means that no tasks are currently attached, therefore there is no
753 * way a task attached to that cgroup can fork (the other way to
754 * increment the count). So code holding cgroup_mutex can safely
755 * assume that if the count is zero, it will stay zero. Similarly, if
756 * a task holds cgroup_mutex on a cgroup with zero count, it
757 * knows that the cgroup won't be removed, as cgroup_rmdir()
760 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
761 * (usually) take cgroup_mutex. These are the two most performance
762 * critical pieces of code here. The exception occurs on cgroup_exit(),
763 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
764 * is taken, and if the cgroup count is zero, a usermode call made
765 * to the release agent with the name of the cgroup (path relative to
766 * the root of cgroup file system) as the argument.
768 * A cgroup can only be deleted if both its 'count' of using tasks
769 * is zero, and its list of 'children' cgroups is empty. Since all
770 * tasks in the system use _some_ cgroup, and since there is always at
771 * least one task in the system (init, pid == 1), therefore, top_cgroup
772 * always has either children cgroups and/or using tasks. So we don't
773 * need a special hack to ensure that top_cgroup cannot be deleted.
775 * The task_lock() exception
777 * The need for this exception arises from the action of
778 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
779 * another. It does so using cgroup_mutex, however there are
780 * several performance critical places that need to reference
781 * task->cgroup without the expense of grabbing a system global
782 * mutex. Therefore except as noted below, when dereferencing or, as
783 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
784 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
785 * the task_struct routinely used for such matters.
787 * P.S. One more locking exception. RCU is used to guard the
788 * update of a tasks cgroup pointer by cgroup_attach_task()
792 * A couple of forward declarations required, due to cyclic reference loop:
793 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
794 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
798 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
799 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
800 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
801 static const struct inode_operations cgroup_dir_inode_operations;
802 static const struct file_operations proc_cgroupstats_operations;
804 static struct backing_dev_info cgroup_backing_dev_info = {
806 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
809 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
811 struct inode *inode = new_inode(sb);
814 inode->i_ino = get_next_ino();
815 inode->i_mode = mode;
816 inode->i_uid = current_fsuid();
817 inode->i_gid = current_fsgid();
818 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
819 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
824 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
826 struct cgroup_name *name;
828 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
831 strcpy(name->name, dentry->d_name.name);
835 static void cgroup_free_fn(struct work_struct *work)
837 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
839 mutex_lock(&cgroup_mutex);
840 cgrp->root->number_of_cgroups--;
841 mutex_unlock(&cgroup_mutex);
844 * We get a ref to the parent's dentry, and put the ref when
845 * this cgroup is being freed, so it's guaranteed that the
846 * parent won't be destroyed before its children.
848 dput(cgrp->parent->dentry);
851 * Drop the active superblock reference that we took when we
852 * created the cgroup. This will free cgrp->root, if we are
853 * holding the last reference to @sb.
855 deactivate_super(cgrp->root->sb);
858 * if we're getting rid of the cgroup, refcount should ensure
859 * that there are no pidlists left.
861 BUG_ON(!list_empty(&cgrp->pidlists));
863 simple_xattrs_free(&cgrp->xattrs);
865 kfree(rcu_dereference_raw(cgrp->name));
869 static void cgroup_free_rcu(struct rcu_head *head)
871 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
873 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
874 schedule_work(&cgrp->destroy_work);
877 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
879 /* is dentry a directory ? if so, kfree() associated cgroup */
880 if (S_ISDIR(inode->i_mode)) {
881 struct cgroup *cgrp = dentry->d_fsdata;
883 BUG_ON(!(cgroup_is_dead(cgrp)));
884 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
886 struct cfent *cfe = __d_cfe(dentry);
887 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
889 WARN_ONCE(!list_empty(&cfe->node) &&
890 cgrp != &cgrp->root->top_cgroup,
891 "cfe still linked for %s\n", cfe->type->name);
892 simple_xattrs_free(&cfe->xattrs);
898 static void remove_dir(struct dentry *d)
900 struct dentry *parent = dget(d->d_parent);
903 simple_rmdir(parent->d_inode, d);
907 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
911 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
912 lockdep_assert_held(&cgroup_mutex);
915 * If we're doing cleanup due to failure of cgroup_create(),
916 * the corresponding @cfe may not exist.
918 list_for_each_entry(cfe, &cgrp->files, node) {
919 struct dentry *d = cfe->dentry;
921 if (cft && cfe->type != cft)
926 simple_unlink(cgrp->dentry->d_inode, d);
927 list_del_init(&cfe->node);
935 * cgroup_clear_dir - remove subsys files in a cgroup directory
936 * @cgrp: target cgroup
937 * @subsys_mask: mask of the subsystem ids whose files should be removed
939 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
941 struct cgroup_subsys *ss;
944 for_each_subsys(ss, i) {
945 struct cftype_set *set;
947 if (!test_bit(i, &subsys_mask))
949 list_for_each_entry(set, &ss->cftsets, node)
950 cgroup_addrm_files(cgrp, set->cfts, false);
955 * NOTE : the dentry must have been dget()'ed
957 static void cgroup_d_remove_dir(struct dentry *dentry)
959 struct dentry *parent;
961 parent = dentry->d_parent;
962 spin_lock(&parent->d_lock);
963 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
964 list_del_init(&dentry->d_u.d_child);
965 spin_unlock(&dentry->d_lock);
966 spin_unlock(&parent->d_lock);
971 * Call with cgroup_mutex held. Drops reference counts on modules, including
972 * any duplicate ones that parse_cgroupfs_options took. If this function
973 * returns an error, no reference counts are touched.
975 static int rebind_subsystems(struct cgroupfs_root *root,
976 unsigned long added_mask, unsigned removed_mask)
978 struct cgroup *cgrp = &root->top_cgroup;
979 struct cgroup_subsys *ss;
980 unsigned long pinned = 0;
983 BUG_ON(!mutex_is_locked(&cgroup_mutex));
984 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
986 /* Check that any added subsystems are currently free */
987 for_each_subsys(ss, i) {
988 if (!(added_mask & (1 << i)))
991 /* is the subsystem mounted elsewhere? */
992 if (ss->root != &cgroup_dummy_root) {
998 if (!try_module_get(ss->module)) {
1005 /* subsys could be missing if unloaded between parsing and here */
1006 if (added_mask != pinned) {
1011 ret = cgroup_populate_dir(cgrp, added_mask);
1016 * Nothing can fail from this point on. Remove files for the
1017 * removed subsystems and rebind each subsystem.
1019 cgroup_clear_dir(cgrp, removed_mask);
1021 for_each_subsys(ss, i) {
1022 unsigned long bit = 1UL << i;
1024 if (bit & added_mask) {
1025 /* We're binding this subsystem to this hierarchy */
1026 BUG_ON(cgroup_css(cgrp, ss));
1027 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
1028 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
1030 rcu_assign_pointer(cgrp->subsys[i],
1031 cgroup_css(cgroup_dummy_top, ss));
1032 cgroup_css(cgrp, ss)->cgroup = cgrp;
1034 list_move(&ss->sibling, &root->subsys_list);
1037 ss->bind(cgroup_css(cgrp, ss));
1039 /* refcount was already taken, and we're keeping it */
1040 root->subsys_mask |= bit;
1041 } else if (bit & removed_mask) {
1042 /* We're removing this subsystem */
1043 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
1044 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
1047 ss->bind(cgroup_css(cgroup_dummy_top, ss));
1049 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
1050 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1052 cgroup_subsys[i]->root = &cgroup_dummy_root;
1053 list_move(&ss->sibling, &cgroup_dummy_root.subsys_list);
1055 /* subsystem is now free - drop reference on module */
1056 module_put(ss->module);
1057 root->subsys_mask &= ~bit;
1062 * Mark @root has finished binding subsystems. @root->subsys_mask
1063 * now matches the bound subsystems.
1065 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1070 for_each_subsys(ss, i)
1071 if (pinned & (1 << i))
1072 module_put(ss->module);
1076 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1078 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1079 struct cgroup_subsys *ss;
1081 mutex_lock(&cgroup_root_mutex);
1082 for_each_root_subsys(root, ss)
1083 seq_printf(seq, ",%s", ss->name);
1084 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1085 seq_puts(seq, ",sane_behavior");
1086 if (root->flags & CGRP_ROOT_NOPREFIX)
1087 seq_puts(seq, ",noprefix");
1088 if (root->flags & CGRP_ROOT_XATTR)
1089 seq_puts(seq, ",xattr");
1090 if (strlen(root->release_agent_path))
1091 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1092 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1093 seq_puts(seq, ",clone_children");
1094 if (strlen(root->name))
1095 seq_printf(seq, ",name=%s", root->name);
1096 mutex_unlock(&cgroup_root_mutex);
1100 struct cgroup_sb_opts {
1101 unsigned long subsys_mask;
1102 unsigned long flags;
1103 char *release_agent;
1104 bool cpuset_clone_children;
1106 /* User explicitly requested empty subsystem */
1109 struct cgroupfs_root *new_root;
1114 * Convert a hierarchy specifier into a bitmask of subsystems and
1115 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1116 * array. This function takes refcounts on subsystems to be used, unless it
1117 * returns error, in which case no refcounts are taken.
1119 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1121 char *token, *o = data;
1122 bool all_ss = false, one_ss = false;
1123 unsigned long mask = (unsigned long)-1;
1124 struct cgroup_subsys *ss;
1127 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1129 #ifdef CONFIG_CPUSETS
1130 mask = ~(1UL << cpuset_subsys_id);
1133 memset(opts, 0, sizeof(*opts));
1135 while ((token = strsep(&o, ",")) != NULL) {
1138 if (!strcmp(token, "none")) {
1139 /* Explicitly have no subsystems */
1143 if (!strcmp(token, "all")) {
1144 /* Mutually exclusive option 'all' + subsystem name */
1150 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1151 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1154 if (!strcmp(token, "noprefix")) {
1155 opts->flags |= CGRP_ROOT_NOPREFIX;
1158 if (!strcmp(token, "clone_children")) {
1159 opts->cpuset_clone_children = true;
1162 if (!strcmp(token, "xattr")) {
1163 opts->flags |= CGRP_ROOT_XATTR;
1166 if (!strncmp(token, "release_agent=", 14)) {
1167 /* Specifying two release agents is forbidden */
1168 if (opts->release_agent)
1170 opts->release_agent =
1171 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1172 if (!opts->release_agent)
1176 if (!strncmp(token, "name=", 5)) {
1177 const char *name = token + 5;
1178 /* Can't specify an empty name */
1181 /* Must match [\w.-]+ */
1182 for (i = 0; i < strlen(name); i++) {
1186 if ((c == '.') || (c == '-') || (c == '_'))
1190 /* Specifying two names is forbidden */
1193 opts->name = kstrndup(name,
1194 MAX_CGROUP_ROOT_NAMELEN - 1,
1202 for_each_subsys(ss, i) {
1203 if (strcmp(token, ss->name))
1208 /* Mutually exclusive option 'all' + subsystem name */
1211 set_bit(i, &opts->subsys_mask);
1216 if (i == CGROUP_SUBSYS_COUNT)
1221 * If the 'all' option was specified select all the subsystems,
1222 * otherwise if 'none', 'name=' and a subsystem name options
1223 * were not specified, let's default to 'all'
1225 if (all_ss || (!one_ss && !opts->none && !opts->name))
1226 for_each_subsys(ss, i)
1228 set_bit(i, &opts->subsys_mask);
1230 /* Consistency checks */
1232 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1233 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1235 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1236 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1240 if (opts->cpuset_clone_children) {
1241 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1247 * Option noprefix was introduced just for backward compatibility
1248 * with the old cpuset, so we allow noprefix only if mounting just
1249 * the cpuset subsystem.
1251 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1255 /* Can't specify "none" and some subsystems */
1256 if (opts->subsys_mask && opts->none)
1260 * We either have to specify by name or by subsystems. (So all
1261 * empty hierarchies must have a name).
1263 if (!opts->subsys_mask && !opts->name)
1269 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1272 struct cgroupfs_root *root = sb->s_fs_info;
1273 struct cgroup *cgrp = &root->top_cgroup;
1274 struct cgroup_sb_opts opts;
1275 unsigned long added_mask, removed_mask;
1277 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1278 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1282 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1283 mutex_lock(&cgroup_mutex);
1284 mutex_lock(&cgroup_root_mutex);
1286 /* See what subsystems are wanted */
1287 ret = parse_cgroupfs_options(data, &opts);
1291 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1292 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1293 task_tgid_nr(current), current->comm);
1295 added_mask = opts.subsys_mask & ~root->subsys_mask;
1296 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1298 /* Don't allow flags or name to change at remount */
1299 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1300 (opts.name && strcmp(opts.name, root->name))) {
1301 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1302 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1303 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1308 /* remounting is not allowed for populated hierarchies */
1309 if (root->number_of_cgroups > 1) {
1314 ret = rebind_subsystems(root, added_mask, removed_mask);
1318 if (opts.release_agent)
1319 strcpy(root->release_agent_path, opts.release_agent);
1321 kfree(opts.release_agent);
1323 mutex_unlock(&cgroup_root_mutex);
1324 mutex_unlock(&cgroup_mutex);
1325 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1329 static const struct super_operations cgroup_ops = {
1330 .statfs = simple_statfs,
1331 .drop_inode = generic_delete_inode,
1332 .show_options = cgroup_show_options,
1333 .remount_fs = cgroup_remount,
1336 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1338 INIT_LIST_HEAD(&cgrp->sibling);
1339 INIT_LIST_HEAD(&cgrp->children);
1340 INIT_LIST_HEAD(&cgrp->files);
1341 INIT_LIST_HEAD(&cgrp->cset_links);
1342 INIT_LIST_HEAD(&cgrp->release_list);
1343 INIT_LIST_HEAD(&cgrp->pidlists);
1344 mutex_init(&cgrp->pidlist_mutex);
1345 cgrp->dummy_css.cgroup = cgrp;
1346 INIT_LIST_HEAD(&cgrp->event_list);
1347 spin_lock_init(&cgrp->event_list_lock);
1348 simple_xattrs_init(&cgrp->xattrs);
1351 static void init_cgroup_root(struct cgroupfs_root *root)
1353 struct cgroup *cgrp = &root->top_cgroup;
1355 INIT_LIST_HEAD(&root->subsys_list);
1356 INIT_LIST_HEAD(&root->root_list);
1357 root->number_of_cgroups = 1;
1359 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1360 init_cgroup_housekeeping(cgrp);
1361 idr_init(&root->cgroup_idr);
1364 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1368 lockdep_assert_held(&cgroup_mutex);
1369 lockdep_assert_held(&cgroup_root_mutex);
1371 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1376 root->hierarchy_id = id;
1380 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1382 lockdep_assert_held(&cgroup_mutex);
1383 lockdep_assert_held(&cgroup_root_mutex);
1385 if (root->hierarchy_id) {
1386 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1387 root->hierarchy_id = 0;
1391 static int cgroup_test_super(struct super_block *sb, void *data)
1393 struct cgroup_sb_opts *opts = data;
1394 struct cgroupfs_root *root = sb->s_fs_info;
1396 /* If we asked for a name then it must match */
1397 if (opts->name && strcmp(opts->name, root->name))
1401 * If we asked for subsystems (or explicitly for no
1402 * subsystems) then they must match
1404 if ((opts->subsys_mask || opts->none)
1405 && (opts->subsys_mask != root->subsys_mask))
1411 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1413 struct cgroupfs_root *root;
1415 if (!opts->subsys_mask && !opts->none)
1418 root = kzalloc(sizeof(*root), GFP_KERNEL);
1420 return ERR_PTR(-ENOMEM);
1422 init_cgroup_root(root);
1425 * We need to set @root->subsys_mask now so that @root can be
1426 * matched by cgroup_test_super() before it finishes
1427 * initialization; otherwise, competing mounts with the same
1428 * options may try to bind the same subsystems instead of waiting
1429 * for the first one leading to unexpected mount errors.
1430 * SUBSYS_BOUND will be set once actual binding is complete.
1432 root->subsys_mask = opts->subsys_mask;
1433 root->flags = opts->flags;
1434 if (opts->release_agent)
1435 strcpy(root->release_agent_path, opts->release_agent);
1437 strcpy(root->name, opts->name);
1438 if (opts->cpuset_clone_children)
1439 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1443 static void cgroup_free_root(struct cgroupfs_root *root)
1446 /* hierarhcy ID shoulid already have been released */
1447 WARN_ON_ONCE(root->hierarchy_id);
1449 idr_destroy(&root->cgroup_idr);
1454 static int cgroup_set_super(struct super_block *sb, void *data)
1457 struct cgroup_sb_opts *opts = data;
1459 /* If we don't have a new root, we can't set up a new sb */
1460 if (!opts->new_root)
1463 BUG_ON(!opts->subsys_mask && !opts->none);
1465 ret = set_anon_super(sb, NULL);
1469 sb->s_fs_info = opts->new_root;
1470 opts->new_root->sb = sb;
1472 sb->s_blocksize = PAGE_CACHE_SIZE;
1473 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1474 sb->s_magic = CGROUP_SUPER_MAGIC;
1475 sb->s_op = &cgroup_ops;
1480 static int cgroup_get_rootdir(struct super_block *sb)
1482 static const struct dentry_operations cgroup_dops = {
1483 .d_iput = cgroup_diput,
1484 .d_delete = always_delete_dentry,
1487 struct inode *inode =
1488 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1493 inode->i_fop = &simple_dir_operations;
1494 inode->i_op = &cgroup_dir_inode_operations;
1495 /* directories start off with i_nlink == 2 (for "." entry) */
1497 sb->s_root = d_make_root(inode);
1500 /* for everything else we want ->d_op set */
1501 sb->s_d_op = &cgroup_dops;
1505 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1506 int flags, const char *unused_dev_name,
1509 struct cgroup_sb_opts opts;
1510 struct cgroupfs_root *root;
1512 struct super_block *sb;
1513 struct cgroupfs_root *new_root;
1514 struct list_head tmp_links;
1515 struct inode *inode;
1516 const struct cred *cred;
1518 /* First find the desired set of subsystems */
1519 mutex_lock(&cgroup_mutex);
1520 ret = parse_cgroupfs_options(data, &opts);
1521 mutex_unlock(&cgroup_mutex);
1526 * Allocate a new cgroup root. We may not need it if we're
1527 * reusing an existing hierarchy.
1529 new_root = cgroup_root_from_opts(&opts);
1530 if (IS_ERR(new_root)) {
1531 ret = PTR_ERR(new_root);
1534 opts.new_root = new_root;
1536 /* Locate an existing or new sb for this hierarchy */
1537 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1540 cgroup_free_root(opts.new_root);
1544 root = sb->s_fs_info;
1546 if (root == opts.new_root) {
1547 /* We used the new root structure, so this is a new hierarchy */
1548 struct cgroup *root_cgrp = &root->top_cgroup;
1549 struct cgroupfs_root *existing_root;
1551 struct css_set *cset;
1553 BUG_ON(sb->s_root != NULL);
1555 ret = cgroup_get_rootdir(sb);
1557 goto drop_new_super;
1558 inode = sb->s_root->d_inode;
1560 mutex_lock(&inode->i_mutex);
1561 mutex_lock(&cgroup_mutex);
1562 mutex_lock(&cgroup_root_mutex);
1564 root_cgrp->id = idr_alloc(&root->cgroup_idr, root_cgrp,
1566 if (root_cgrp->id < 0)
1569 /* Check for name clashes with existing mounts */
1571 if (strlen(root->name))
1572 for_each_active_root(existing_root)
1573 if (!strcmp(existing_root->name, root->name))
1577 * We're accessing css_set_count without locking
1578 * css_set_lock here, but that's OK - it can only be
1579 * increased by someone holding cgroup_lock, and
1580 * that's us. The worst that can happen is that we
1581 * have some link structures left over
1583 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1587 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1588 ret = cgroup_init_root_id(root, 2, 0);
1592 sb->s_root->d_fsdata = root_cgrp;
1593 root_cgrp->dentry = sb->s_root;
1596 * We're inside get_sb() and will call lookup_one_len() to
1597 * create the root files, which doesn't work if SELinux is
1598 * in use. The following cred dancing somehow works around
1599 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1600 * populating new cgroupfs mount") for more details.
1602 cred = override_creds(&init_cred);
1604 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1608 ret = rebind_subsystems(root, root->subsys_mask, 0);
1615 * There must be no failure case after here, since rebinding
1616 * takes care of subsystems' refcounts, which are explicitly
1617 * dropped in the failure exit path.
1620 list_add(&root->root_list, &cgroup_roots);
1621 cgroup_root_count++;
1623 /* Link the top cgroup in this hierarchy into all
1624 * the css_set objects */
1625 write_lock(&css_set_lock);
1626 hash_for_each(css_set_table, i, cset, hlist)
1627 link_css_set(&tmp_links, cset, root_cgrp);
1628 write_unlock(&css_set_lock);
1630 free_cgrp_cset_links(&tmp_links);
1632 BUG_ON(!list_empty(&root_cgrp->children));
1633 BUG_ON(root->number_of_cgroups != 1);
1635 mutex_unlock(&cgroup_root_mutex);
1636 mutex_unlock(&cgroup_mutex);
1637 mutex_unlock(&inode->i_mutex);
1640 * We re-used an existing hierarchy - the new root (if
1641 * any) is not needed
1643 cgroup_free_root(opts.new_root);
1645 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1646 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1647 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1649 goto drop_new_super;
1651 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1656 kfree(opts.release_agent);
1658 return dget(sb->s_root);
1661 free_cgrp_cset_links(&tmp_links);
1662 cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1665 cgroup_exit_root_id(root);
1666 mutex_unlock(&cgroup_root_mutex);
1667 mutex_unlock(&cgroup_mutex);
1668 mutex_unlock(&inode->i_mutex);
1670 deactivate_locked_super(sb);
1672 kfree(opts.release_agent);
1674 return ERR_PTR(ret);
1677 static void cgroup_kill_sb(struct super_block *sb) {
1678 struct cgroupfs_root *root = sb->s_fs_info;
1679 struct cgroup *cgrp = &root->top_cgroup;
1680 struct cgrp_cset_link *link, *tmp_link;
1685 BUG_ON(root->number_of_cgroups != 1);
1686 BUG_ON(!list_empty(&cgrp->children));
1688 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1689 mutex_lock(&cgroup_mutex);
1690 mutex_lock(&cgroup_root_mutex);
1692 /* Rebind all subsystems back to the default hierarchy */
1693 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1694 ret = rebind_subsystems(root, 0, root->subsys_mask);
1695 /* Shouldn't be able to fail ... */
1700 * Release all the links from cset_links to this hierarchy's
1703 write_lock(&css_set_lock);
1705 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1706 list_del(&link->cset_link);
1707 list_del(&link->cgrp_link);
1710 write_unlock(&css_set_lock);
1712 if (!list_empty(&root->root_list)) {
1713 list_del(&root->root_list);
1714 cgroup_root_count--;
1717 cgroup_exit_root_id(root);
1719 mutex_unlock(&cgroup_root_mutex);
1720 mutex_unlock(&cgroup_mutex);
1721 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1723 simple_xattrs_free(&cgrp->xattrs);
1725 kill_litter_super(sb);
1726 cgroup_free_root(root);
1729 static struct file_system_type cgroup_fs_type = {
1731 .mount = cgroup_mount,
1732 .kill_sb = cgroup_kill_sb,
1735 static struct kobject *cgroup_kobj;
1738 * cgroup_path - generate the path of a cgroup
1739 * @cgrp: the cgroup in question
1740 * @buf: the buffer to write the path into
1741 * @buflen: the length of the buffer
1743 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1745 * We can't generate cgroup path using dentry->d_name, as accessing
1746 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1747 * inode's i_mutex, while on the other hand cgroup_path() can be called
1748 * with some irq-safe spinlocks held.
1750 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1752 int ret = -ENAMETOOLONG;
1755 if (!cgrp->parent) {
1756 if (strlcpy(buf, "/", buflen) >= buflen)
1757 return -ENAMETOOLONG;
1761 start = buf + buflen - 1;
1766 const char *name = cgroup_name(cgrp);
1770 if ((start -= len) < buf)
1772 memcpy(start, name, len);
1778 cgrp = cgrp->parent;
1779 } while (cgrp->parent);
1781 memmove(buf, start, buf + buflen - start);
1786 EXPORT_SYMBOL_GPL(cgroup_path);
1789 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1790 * @task: target task
1791 * @buf: the buffer to write the path into
1792 * @buflen: the length of the buffer
1794 * Determine @task's cgroup on the first (the one with the lowest non-zero
1795 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1796 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1797 * cgroup controller callbacks.
1799 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1801 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1803 struct cgroupfs_root *root;
1804 struct cgroup *cgrp;
1805 int hierarchy_id = 1, ret = 0;
1808 return -ENAMETOOLONG;
1810 mutex_lock(&cgroup_mutex);
1812 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1815 cgrp = task_cgroup_from_root(task, root);
1816 ret = cgroup_path(cgrp, buf, buflen);
1818 /* if no hierarchy exists, everyone is in "/" */
1819 memcpy(buf, "/", 2);
1822 mutex_unlock(&cgroup_mutex);
1825 EXPORT_SYMBOL_GPL(task_cgroup_path);
1828 * Control Group taskset
1830 struct task_and_cgroup {
1831 struct task_struct *task;
1832 struct cgroup *cgrp;
1833 struct css_set *cset;
1836 struct cgroup_taskset {
1837 struct task_and_cgroup single;
1838 struct flex_array *tc_array;
1841 struct cgroup *cur_cgrp;
1845 * cgroup_taskset_first - reset taskset and return the first task
1846 * @tset: taskset of interest
1848 * @tset iteration is initialized and the first task is returned.
1850 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1852 if (tset->tc_array) {
1854 return cgroup_taskset_next(tset);
1856 tset->cur_cgrp = tset->single.cgrp;
1857 return tset->single.task;
1860 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1863 * cgroup_taskset_next - iterate to the next task in taskset
1864 * @tset: taskset of interest
1866 * Return the next task in @tset. Iteration must have been initialized
1867 * with cgroup_taskset_first().
1869 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1871 struct task_and_cgroup *tc;
1873 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1876 tc = flex_array_get(tset->tc_array, tset->idx++);
1877 tset->cur_cgrp = tc->cgrp;
1880 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1883 * cgroup_taskset_cur_css - return the matching css for the current task
1884 * @tset: taskset of interest
1885 * @subsys_id: the ID of the target subsystem
1887 * Return the css for the current (last returned) task of @tset for
1888 * subsystem specified by @subsys_id. This function must be preceded by
1889 * either cgroup_taskset_first() or cgroup_taskset_next().
1891 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1894 return cgroup_css(tset->cur_cgrp, cgroup_subsys[subsys_id]);
1896 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1899 * cgroup_taskset_size - return the number of tasks in taskset
1900 * @tset: taskset of interest
1902 int cgroup_taskset_size(struct cgroup_taskset *tset)
1904 return tset->tc_array ? tset->tc_array_len : 1;
1906 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1910 * cgroup_task_migrate - move a task from one cgroup to another.
1912 * Must be called with cgroup_mutex and threadgroup locked.
1914 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1915 struct task_struct *tsk,
1916 struct css_set *new_cset)
1918 struct css_set *old_cset;
1921 * We are synchronized through threadgroup_lock() against PF_EXITING
1922 * setting such that we can't race against cgroup_exit() changing the
1923 * css_set to init_css_set and dropping the old one.
1925 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1926 old_cset = task_css_set(tsk);
1929 rcu_assign_pointer(tsk->cgroups, new_cset);
1932 /* Update the css_set linked lists if we're using them */
1933 write_lock(&css_set_lock);
1934 if (!list_empty(&tsk->cg_list))
1935 list_move(&tsk->cg_list, &new_cset->tasks);
1936 write_unlock(&css_set_lock);
1939 * We just gained a reference on old_cset by taking it from the
1940 * task. As trading it for new_cset is protected by cgroup_mutex,
1941 * we're safe to drop it here; it will be freed under RCU.
1943 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1944 put_css_set(old_cset);
1948 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1949 * @cgrp: the cgroup to attach to
1950 * @tsk: the task or the leader of the threadgroup to be attached
1951 * @threadgroup: attach the whole threadgroup?
1953 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1954 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1956 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1959 int retval, i, group_size;
1960 struct cgroup_subsys *ss, *failed_ss = NULL;
1961 struct cgroupfs_root *root = cgrp->root;
1962 /* threadgroup list cursor and array */
1963 struct task_struct *leader = tsk;
1964 struct task_and_cgroup *tc;
1965 struct flex_array *group;
1966 struct cgroup_taskset tset = { };
1969 * step 0: in order to do expensive, possibly blocking operations for
1970 * every thread, we cannot iterate the thread group list, since it needs
1971 * rcu or tasklist locked. instead, build an array of all threads in the
1972 * group - group_rwsem prevents new threads from appearing, and if
1973 * threads exit, this will just be an over-estimate.
1976 group_size = get_nr_threads(tsk);
1979 /* flex_array supports very large thread-groups better than kmalloc. */
1980 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1983 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1984 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1986 goto out_free_group_list;
1990 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1991 * already PF_EXITING could be freed from underneath us unless we
1992 * take an rcu_read_lock.
1996 struct task_and_cgroup ent;
1998 /* @tsk either already exited or can't exit until the end */
1999 if (tsk->flags & PF_EXITING)
2002 /* as per above, nr_threads may decrease, but not increase. */
2003 BUG_ON(i >= group_size);
2005 ent.cgrp = task_cgroup_from_root(tsk, root);
2006 /* nothing to do if this task is already in the cgroup */
2007 if (ent.cgrp == cgrp)
2010 * saying GFP_ATOMIC has no effect here because we did prealloc
2011 * earlier, but it's good form to communicate our expectations.
2013 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2014 BUG_ON(retval != 0);
2019 } while_each_thread(leader, tsk);
2021 /* remember the number of threads in the array for later. */
2023 tset.tc_array = group;
2024 tset.tc_array_len = group_size;
2026 /* methods shouldn't be called if no task is actually migrating */
2029 goto out_free_group_list;
2032 * step 1: check that we can legitimately attach to the cgroup.
2034 for_each_root_subsys(root, ss) {
2035 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2037 if (ss->can_attach) {
2038 retval = ss->can_attach(css, &tset);
2041 goto out_cancel_attach;
2047 * step 2: make sure css_sets exist for all threads to be migrated.
2048 * we use find_css_set, which allocates a new one if necessary.
2050 for (i = 0; i < group_size; i++) {
2051 struct css_set *old_cset;
2053 tc = flex_array_get(group, i);
2054 old_cset = task_css_set(tc->task);
2055 tc->cset = find_css_set(old_cset, cgrp);
2058 goto out_put_css_set_refs;
2063 * step 3: now that we're guaranteed success wrt the css_sets,
2064 * proceed to move all tasks to the new cgroup. There are no
2065 * failure cases after here, so this is the commit point.
2067 for (i = 0; i < group_size; i++) {
2068 tc = flex_array_get(group, i);
2069 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
2071 /* nothing is sensitive to fork() after this point. */
2074 * step 4: do subsystem attach callbacks.
2076 for_each_root_subsys(root, ss) {
2077 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2080 ss->attach(css, &tset);
2084 * step 5: success! and cleanup
2087 out_put_css_set_refs:
2089 for (i = 0; i < group_size; i++) {
2090 tc = flex_array_get(group, i);
2093 put_css_set(tc->cset);
2098 for_each_root_subsys(root, ss) {
2099 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2101 if (ss == failed_ss)
2103 if (ss->cancel_attach)
2104 ss->cancel_attach(css, &tset);
2107 out_free_group_list:
2108 flex_array_free(group);
2113 * Find the task_struct of the task to attach by vpid and pass it along to the
2114 * function to attach either it or all tasks in its threadgroup. Will lock
2115 * cgroup_mutex and threadgroup; may take task_lock of task.
2117 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2119 struct task_struct *tsk;
2120 const struct cred *cred = current_cred(), *tcred;
2123 if (!cgroup_lock_live_group(cgrp))
2129 tsk = find_task_by_vpid(pid);
2133 goto out_unlock_cgroup;
2136 * even if we're attaching all tasks in the thread group, we
2137 * only need to check permissions on one of them.
2139 tcred = __task_cred(tsk);
2140 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2141 !uid_eq(cred->euid, tcred->uid) &&
2142 !uid_eq(cred->euid, tcred->suid)) {
2145 goto out_unlock_cgroup;
2151 tsk = tsk->group_leader;
2154 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2155 * trapped in a cpuset, or RT worker may be born in a cgroup
2156 * with no rt_runtime allocated. Just say no.
2158 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2161 goto out_unlock_cgroup;
2164 get_task_struct(tsk);
2167 threadgroup_lock(tsk);
2169 if (!thread_group_leader(tsk)) {
2171 * a race with de_thread from another thread's exec()
2172 * may strip us of our leadership, if this happens,
2173 * there is no choice but to throw this task away and
2174 * try again; this is
2175 * "double-double-toil-and-trouble-check locking".
2177 threadgroup_unlock(tsk);
2178 put_task_struct(tsk);
2179 goto retry_find_task;
2183 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2185 threadgroup_unlock(tsk);
2187 put_task_struct(tsk);
2189 mutex_unlock(&cgroup_mutex);
2194 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2195 * @from: attach to all cgroups of a given task
2196 * @tsk: the task to be attached
2198 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2200 struct cgroupfs_root *root;
2203 mutex_lock(&cgroup_mutex);
2204 for_each_active_root(root) {
2205 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2207 retval = cgroup_attach_task(from_cgrp, tsk, false);
2211 mutex_unlock(&cgroup_mutex);
2215 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2217 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2218 struct cftype *cft, u64 pid)
2220 return attach_task_by_pid(css->cgroup, pid, false);
2223 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2224 struct cftype *cft, u64 tgid)
2226 return attach_task_by_pid(css->cgroup, tgid, true);
2229 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2230 struct cftype *cft, const char *buffer)
2232 BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2233 if (strlen(buffer) >= PATH_MAX)
2235 if (!cgroup_lock_live_group(css->cgroup))
2237 mutex_lock(&cgroup_root_mutex);
2238 strcpy(css->cgroup->root->release_agent_path, buffer);
2239 mutex_unlock(&cgroup_root_mutex);
2240 mutex_unlock(&cgroup_mutex);
2244 static int cgroup_release_agent_show(struct cgroup_subsys_state *css,
2245 struct cftype *cft, struct seq_file *seq)
2247 struct cgroup *cgrp = css->cgroup;
2249 if (!cgroup_lock_live_group(cgrp))
2251 seq_puts(seq, cgrp->root->release_agent_path);
2252 seq_putc(seq, '\n');
2253 mutex_unlock(&cgroup_mutex);
2257 static int cgroup_sane_behavior_show(struct cgroup_subsys_state *css,
2258 struct cftype *cft, struct seq_file *seq)
2260 seq_printf(seq, "%d\n", cgroup_sane_behavior(css->cgroup));
2264 /* A buffer size big enough for numbers or short strings */
2265 #define CGROUP_LOCAL_BUFFER_SIZE 64
2267 static ssize_t cgroup_write_X64(struct cgroup_subsys_state *css,
2268 struct cftype *cft, struct file *file,
2269 const char __user *userbuf, size_t nbytes,
2270 loff_t *unused_ppos)
2272 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2278 if (nbytes >= sizeof(buffer))
2280 if (copy_from_user(buffer, userbuf, nbytes))
2283 buffer[nbytes] = 0; /* nul-terminate */
2284 if (cft->write_u64) {
2285 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2288 retval = cft->write_u64(css, cft, val);
2290 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2293 retval = cft->write_s64(css, cft, val);
2300 static ssize_t cgroup_write_string(struct cgroup_subsys_state *css,
2301 struct cftype *cft, struct file *file,
2302 const char __user *userbuf, size_t nbytes,
2303 loff_t *unused_ppos)
2305 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2307 size_t max_bytes = cft->max_write_len;
2308 char *buffer = local_buffer;
2311 max_bytes = sizeof(local_buffer) - 1;
2312 if (nbytes >= max_bytes)
2314 /* Allocate a dynamic buffer if we need one */
2315 if (nbytes >= sizeof(local_buffer)) {
2316 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2320 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2325 buffer[nbytes] = 0; /* nul-terminate */
2326 retval = cft->write_string(css, cft, strstrip(buffer));
2330 if (buffer != local_buffer)
2335 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2336 size_t nbytes, loff_t *ppos)
2338 struct cfent *cfe = __d_cfe(file->f_dentry);
2339 struct cftype *cft = __d_cft(file->f_dentry);
2340 struct cgroup_subsys_state *css = cfe->css;
2343 return cft->write(css, cft, file, buf, nbytes, ppos);
2344 if (cft->write_u64 || cft->write_s64)
2345 return cgroup_write_X64(css, cft, file, buf, nbytes, ppos);
2346 if (cft->write_string)
2347 return cgroup_write_string(css, cft, file, buf, nbytes, ppos);
2349 int ret = cft->trigger(css, (unsigned int)cft->private);
2350 return ret ? ret : nbytes;
2355 static ssize_t cgroup_read_u64(struct cgroup_subsys_state *css,
2356 struct cftype *cft, struct file *file,
2357 char __user *buf, size_t nbytes, loff_t *ppos)
2359 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2360 u64 val = cft->read_u64(css, cft);
2361 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2363 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2366 static ssize_t cgroup_read_s64(struct cgroup_subsys_state *css,
2367 struct cftype *cft, struct file *file,
2368 char __user *buf, size_t nbytes, loff_t *ppos)
2370 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2371 s64 val = cft->read_s64(css, cft);
2372 int len = sprintf(tmp, "%lld\n", (long long) val);
2374 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2377 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2378 size_t nbytes, loff_t *ppos)
2380 struct cfent *cfe = __d_cfe(file->f_dentry);
2381 struct cftype *cft = __d_cft(file->f_dentry);
2382 struct cgroup_subsys_state *css = cfe->css;
2385 return cft->read(css, cft, file, buf, nbytes, ppos);
2387 return cgroup_read_u64(css, cft, file, buf, nbytes, ppos);
2389 return cgroup_read_s64(css, cft, file, buf, nbytes, ppos);
2394 * seqfile ops/methods for returning structured data. Currently just
2395 * supports string->u64 maps, but can be extended in future.
2398 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2400 struct seq_file *sf = cb->state;
2401 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2404 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2406 struct cfent *cfe = m->private;
2407 struct cftype *cft = cfe->type;
2408 struct cgroup_subsys_state *css = cfe->css;
2410 if (cft->read_map) {
2411 struct cgroup_map_cb cb = {
2412 .fill = cgroup_map_add,
2415 return cft->read_map(css, cft, &cb);
2417 return cft->read_seq_string(css, cft, m);
2420 static const struct file_operations cgroup_seqfile_operations = {
2422 .write = cgroup_file_write,
2423 .llseek = seq_lseek,
2424 .release = single_release,
2427 static int cgroup_file_open(struct inode *inode, struct file *file)
2429 struct cfent *cfe = __d_cfe(file->f_dentry);
2430 struct cftype *cft = __d_cft(file->f_dentry);
2431 struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2432 struct cgroup_subsys_state *css;
2435 err = generic_file_open(inode, file);
2440 * If the file belongs to a subsystem, pin the css. Will be
2441 * unpinned either on open failure or release. This ensures that
2442 * @css stays alive for all file operations.
2445 css = cgroup_css(cgrp, cft->ss);
2446 if (cft->ss && !css_tryget(css))
2454 * @cfe->css is used by read/write/close to determine the
2455 * associated css. @file->private_data would be a better place but
2456 * that's already used by seqfile. Multiple accessors may use it
2457 * simultaneously which is okay as the association never changes.
2459 WARN_ON_ONCE(cfe->css && cfe->css != css);
2462 if (cft->read_map || cft->read_seq_string) {
2463 file->f_op = &cgroup_seqfile_operations;
2464 err = single_open(file, cgroup_seqfile_show, cfe);
2465 } else if (cft->open) {
2466 err = cft->open(inode, file);
2474 static int cgroup_file_release(struct inode *inode, struct file *file)
2476 struct cfent *cfe = __d_cfe(file->f_dentry);
2477 struct cftype *cft = __d_cft(file->f_dentry);
2478 struct cgroup_subsys_state *css = cfe->css;
2482 ret = cft->release(inode, file);
2489 * cgroup_rename - Only allow simple rename of directories in place.
2491 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2492 struct inode *new_dir, struct dentry *new_dentry)
2495 struct cgroup_name *name, *old_name;
2496 struct cgroup *cgrp;
2499 * It's convinient to use parent dir's i_mutex to protected
2502 lockdep_assert_held(&old_dir->i_mutex);
2504 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2506 if (new_dentry->d_inode)
2508 if (old_dir != new_dir)
2511 cgrp = __d_cgrp(old_dentry);
2514 * This isn't a proper migration and its usefulness is very
2515 * limited. Disallow if sane_behavior.
2517 if (cgroup_sane_behavior(cgrp))
2520 name = cgroup_alloc_name(new_dentry);
2524 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2530 old_name = rcu_dereference_protected(cgrp->name, true);
2531 rcu_assign_pointer(cgrp->name, name);
2533 kfree_rcu(old_name, rcu_head);
2537 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2539 if (S_ISDIR(dentry->d_inode->i_mode))
2540 return &__d_cgrp(dentry)->xattrs;
2542 return &__d_cfe(dentry)->xattrs;
2545 static inline int xattr_enabled(struct dentry *dentry)
2547 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2548 return root->flags & CGRP_ROOT_XATTR;
2551 static bool is_valid_xattr(const char *name)
2553 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2554 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2559 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2560 const void *val, size_t size, int flags)
2562 if (!xattr_enabled(dentry))
2564 if (!is_valid_xattr(name))
2566 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2569 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2571 if (!xattr_enabled(dentry))
2573 if (!is_valid_xattr(name))
2575 return simple_xattr_remove(__d_xattrs(dentry), name);
2578 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2579 void *buf, size_t size)
2581 if (!xattr_enabled(dentry))
2583 if (!is_valid_xattr(name))
2585 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2588 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2590 if (!xattr_enabled(dentry))
2592 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2595 static const struct file_operations cgroup_file_operations = {
2596 .read = cgroup_file_read,
2597 .write = cgroup_file_write,
2598 .llseek = generic_file_llseek,
2599 .open = cgroup_file_open,
2600 .release = cgroup_file_release,
2603 static const struct inode_operations cgroup_file_inode_operations = {
2604 .setxattr = cgroup_setxattr,
2605 .getxattr = cgroup_getxattr,
2606 .listxattr = cgroup_listxattr,
2607 .removexattr = cgroup_removexattr,
2610 static const struct inode_operations cgroup_dir_inode_operations = {
2611 .lookup = simple_lookup,
2612 .mkdir = cgroup_mkdir,
2613 .rmdir = cgroup_rmdir,
2614 .rename = cgroup_rename,
2615 .setxattr = cgroup_setxattr,
2616 .getxattr = cgroup_getxattr,
2617 .listxattr = cgroup_listxattr,
2618 .removexattr = cgroup_removexattr,
2622 * Check if a file is a control file
2624 static inline struct cftype *__file_cft(struct file *file)
2626 if (file_inode(file)->i_fop != &cgroup_file_operations)
2627 return ERR_PTR(-EINVAL);
2628 return __d_cft(file->f_dentry);
2631 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2632 struct super_block *sb)
2634 struct inode *inode;
2638 if (dentry->d_inode)
2641 inode = cgroup_new_inode(mode, sb);
2645 if (S_ISDIR(mode)) {
2646 inode->i_op = &cgroup_dir_inode_operations;
2647 inode->i_fop = &simple_dir_operations;
2649 /* start off with i_nlink == 2 (for "." entry) */
2651 inc_nlink(dentry->d_parent->d_inode);
2654 * Control reaches here with cgroup_mutex held.
2655 * @inode->i_mutex should nest outside cgroup_mutex but we
2656 * want to populate it immediately without releasing
2657 * cgroup_mutex. As @inode isn't visible to anyone else
2658 * yet, trylock will always succeed without affecting
2661 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2662 } else if (S_ISREG(mode)) {
2664 inode->i_fop = &cgroup_file_operations;
2665 inode->i_op = &cgroup_file_inode_operations;
2667 d_instantiate(dentry, inode);
2668 dget(dentry); /* Extra count - pin the dentry in core */
2673 * cgroup_file_mode - deduce file mode of a control file
2674 * @cft: the control file in question
2676 * returns cft->mode if ->mode is not 0
2677 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2678 * returns S_IRUGO if it has only a read handler
2679 * returns S_IWUSR if it has only a write hander
2681 static umode_t cgroup_file_mode(const struct cftype *cft)
2688 if (cft->read || cft->read_u64 || cft->read_s64 ||
2689 cft->read_map || cft->read_seq_string)
2692 if (cft->write || cft->write_u64 || cft->write_s64 ||
2693 cft->write_string || cft->trigger)
2699 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2701 struct dentry *dir = cgrp->dentry;
2702 struct cgroup *parent = __d_cgrp(dir);
2703 struct dentry *dentry;
2707 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2709 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
2710 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2711 strcpy(name, cft->ss->name);
2714 strcat(name, cft->name);
2716 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2718 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2722 dentry = lookup_one_len(name, dir, strlen(name));
2723 if (IS_ERR(dentry)) {
2724 error = PTR_ERR(dentry);
2728 cfe->type = (void *)cft;
2729 cfe->dentry = dentry;
2730 dentry->d_fsdata = cfe;
2731 simple_xattrs_init(&cfe->xattrs);
2733 mode = cgroup_file_mode(cft);
2734 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2736 list_add_tail(&cfe->node, &parent->files);
2746 * cgroup_addrm_files - add or remove files to a cgroup directory
2747 * @cgrp: the target cgroup
2748 * @cfts: array of cftypes to be added
2749 * @is_add: whether to add or remove
2751 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2752 * For removals, this function never fails. If addition fails, this
2753 * function doesn't remove files already added. The caller is responsible
2756 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2762 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2763 lockdep_assert_held(&cgroup_mutex);
2765 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2766 /* does cft->flags tell us to skip this file on @cgrp? */
2767 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2769 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2771 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2775 ret = cgroup_add_file(cgrp, cft);
2777 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2782 cgroup_rm_file(cgrp, cft);
2788 static void cgroup_cfts_prepare(void)
2789 __acquires(&cgroup_mutex)
2792 * Thanks to the entanglement with vfs inode locking, we can't walk
2793 * the existing cgroups under cgroup_mutex and create files.
2794 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2795 * lock before calling cgroup_addrm_files().
2797 mutex_lock(&cgroup_mutex);
2800 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2801 __releases(&cgroup_mutex)
2804 struct cgroup_subsys *ss = cfts[0].ss;
2805 struct cgroup *root = &ss->root->top_cgroup;
2806 struct super_block *sb = ss->root->sb;
2807 struct dentry *prev = NULL;
2808 struct inode *inode;
2809 struct cgroup_subsys_state *css;
2813 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2814 if (!cfts || ss->root == &cgroup_dummy_root ||
2815 !atomic_inc_not_zero(&sb->s_active)) {
2816 mutex_unlock(&cgroup_mutex);
2821 * All cgroups which are created after we drop cgroup_mutex will
2822 * have the updated set of files, so we only need to update the
2823 * cgroups created before the current @cgroup_serial_nr_next.
2825 update_before = cgroup_serial_nr_next;
2827 mutex_unlock(&cgroup_mutex);
2829 /* add/rm files for all cgroups created before */
2831 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2832 struct cgroup *cgrp = css->cgroup;
2834 if (cgroup_is_dead(cgrp))
2837 inode = cgrp->dentry->d_inode;
2842 prev = cgrp->dentry;
2844 mutex_lock(&inode->i_mutex);
2845 mutex_lock(&cgroup_mutex);
2846 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2847 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2848 mutex_unlock(&cgroup_mutex);
2849 mutex_unlock(&inode->i_mutex);
2857 deactivate_super(sb);
2862 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2863 * @ss: target cgroup subsystem
2864 * @cfts: zero-length name terminated array of cftypes
2866 * Register @cfts to @ss. Files described by @cfts are created for all
2867 * existing cgroups to which @ss is attached and all future cgroups will
2868 * have them too. This function can be called anytime whether @ss is
2871 * Returns 0 on successful registration, -errno on failure. Note that this
2872 * function currently returns 0 as long as @cfts registration is successful
2873 * even if some file creation attempts on existing cgroups fail.
2875 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2877 struct cftype_set *set;
2881 set = kzalloc(sizeof(*set), GFP_KERNEL);
2885 for (cft = cfts; cft->name[0] != '\0'; cft++)
2888 cgroup_cfts_prepare();
2890 list_add_tail(&set->node, &ss->cftsets);
2891 ret = cgroup_cfts_commit(cfts, true);
2893 cgroup_rm_cftypes(cfts);
2896 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2899 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2900 * @cfts: zero-length name terminated array of cftypes
2902 * Unregister @cfts. Files described by @cfts are removed from all
2903 * existing cgroups and all future cgroups won't have them either. This
2904 * function can be called anytime whether @cfts' subsys is attached or not.
2906 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2909 int cgroup_rm_cftypes(struct cftype *cfts)
2911 struct cftype_set *set;
2913 if (!cfts || !cfts[0].ss)
2916 cgroup_cfts_prepare();
2918 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2919 if (set->cfts == cfts) {
2920 list_del(&set->node);
2922 cgroup_cfts_commit(cfts, false);
2927 cgroup_cfts_commit(NULL, false);
2932 * cgroup_task_count - count the number of tasks in a cgroup.
2933 * @cgrp: the cgroup in question
2935 * Return the number of tasks in the cgroup.
2937 int cgroup_task_count(const struct cgroup *cgrp)
2940 struct cgrp_cset_link *link;
2942 read_lock(&css_set_lock);
2943 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2944 count += atomic_read(&link->cset->refcount);
2945 read_unlock(&css_set_lock);
2950 * To reduce the fork() overhead for systems that are not actually using
2951 * their cgroups capability, we don't maintain the lists running through
2952 * each css_set to its tasks until we see the list actually used - in other
2953 * words after the first call to css_task_iter_start().
2955 static void cgroup_enable_task_cg_lists(void)
2957 struct task_struct *p, *g;
2958 write_lock(&css_set_lock);
2959 use_task_css_set_links = 1;
2961 * We need tasklist_lock because RCU is not safe against
2962 * while_each_thread(). Besides, a forking task that has passed
2963 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2964 * is not guaranteed to have its child immediately visible in the
2965 * tasklist if we walk through it with RCU.
2967 read_lock(&tasklist_lock);
2968 do_each_thread(g, p) {
2971 * We should check if the process is exiting, otherwise
2972 * it will race with cgroup_exit() in that the list
2973 * entry won't be deleted though the process has exited.
2975 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2976 list_add(&p->cg_list, &task_css_set(p)->tasks);
2978 } while_each_thread(g, p);
2979 read_unlock(&tasklist_lock);
2980 write_unlock(&css_set_lock);
2984 * css_next_child - find the next child of a given css
2985 * @pos_css: the current position (%NULL to initiate traversal)
2986 * @parent_css: css whose children to walk
2988 * This function returns the next child of @parent_css and should be called
2989 * under RCU read lock. The only requirement is that @parent_css and
2990 * @pos_css are accessible. The next sibling is guaranteed to be returned
2991 * regardless of their states.
2993 struct cgroup_subsys_state *
2994 css_next_child(struct cgroup_subsys_state *pos_css,
2995 struct cgroup_subsys_state *parent_css)
2997 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2998 struct cgroup *cgrp = parent_css->cgroup;
2999 struct cgroup *next;
3001 WARN_ON_ONCE(!rcu_read_lock_held());
3004 * @pos could already have been removed. Once a cgroup is removed,
3005 * its ->sibling.next is no longer updated when its next sibling
3006 * changes. As CGRP_DEAD assertion is serialized and happens
3007 * before the cgroup is taken off the ->sibling list, if we see it
3008 * unasserted, it's guaranteed that the next sibling hasn't
3009 * finished its grace period even if it's already removed, and thus
3010 * safe to dereference from this RCU critical section. If
3011 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3012 * to be visible as %true here.
3014 * If @pos is dead, its next pointer can't be dereferenced;
3015 * however, as each cgroup is given a monotonically increasing
3016 * unique serial number and always appended to the sibling list,
3017 * the next one can be found by walking the parent's children until
3018 * we see a cgroup with higher serial number than @pos's. While
3019 * this path can be slower, it's taken only when either the current
3020 * cgroup is removed or iteration and removal race.
3023 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3024 } else if (likely(!cgroup_is_dead(pos))) {
3025 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3027 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3028 if (next->serial_nr > pos->serial_nr)
3032 if (&next->sibling == &cgrp->children)
3035 return cgroup_css(next, parent_css->ss);
3037 EXPORT_SYMBOL_GPL(css_next_child);
3040 * css_next_descendant_pre - find the next descendant for pre-order walk
3041 * @pos: the current position (%NULL to initiate traversal)
3042 * @root: css whose descendants to walk
3044 * To be used by css_for_each_descendant_pre(). Find the next descendant
3045 * to visit for pre-order traversal of @root's descendants. @root is
3046 * included in the iteration and the first node to be visited.
3048 * While this function requires RCU read locking, it doesn't require the
3049 * whole traversal to be contained in a single RCU critical section. This
3050 * function will return the correct next descendant as long as both @pos
3051 * and @root are accessible and @pos is a descendant of @root.
3053 struct cgroup_subsys_state *
3054 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3055 struct cgroup_subsys_state *root)
3057 struct cgroup_subsys_state *next;
3059 WARN_ON_ONCE(!rcu_read_lock_held());
3061 /* if first iteration, visit @root */
3065 /* visit the first child if exists */
3066 next = css_next_child(NULL, pos);
3070 /* no child, visit my or the closest ancestor's next sibling */
3071 while (pos != root) {
3072 next = css_next_child(pos, css_parent(pos));
3075 pos = css_parent(pos);
3080 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
3083 * css_rightmost_descendant - return the rightmost descendant of a css
3084 * @pos: css of interest
3086 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3087 * is returned. This can be used during pre-order traversal to skip
3090 * While this function requires RCU read locking, it doesn't require the
3091 * whole traversal to be contained in a single RCU critical section. This
3092 * function will return the correct rightmost descendant as long as @pos is
3095 struct cgroup_subsys_state *
3096 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3098 struct cgroup_subsys_state *last, *tmp;
3100 WARN_ON_ONCE(!rcu_read_lock_held());
3104 /* ->prev isn't RCU safe, walk ->next till the end */
3106 css_for_each_child(tmp, last)
3112 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
3114 static struct cgroup_subsys_state *
3115 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3117 struct cgroup_subsys_state *last;
3121 pos = css_next_child(NULL, pos);
3128 * css_next_descendant_post - find the next descendant for post-order walk
3129 * @pos: the current position (%NULL to initiate traversal)
3130 * @root: css whose descendants to walk
3132 * To be used by css_for_each_descendant_post(). Find the next descendant
3133 * to visit for post-order traversal of @root's descendants. @root is
3134 * included in the iteration and the last node to be visited.
3136 * While this function requires RCU read locking, it doesn't require the
3137 * whole traversal to be contained in a single RCU critical section. This
3138 * function will return the correct next descendant as long as both @pos
3139 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3141 struct cgroup_subsys_state *
3142 css_next_descendant_post(struct cgroup_subsys_state *pos,
3143 struct cgroup_subsys_state *root)
3145 struct cgroup_subsys_state *next;
3147 WARN_ON_ONCE(!rcu_read_lock_held());
3149 /* if first iteration, visit leftmost descendant which may be @root */
3151 return css_leftmost_descendant(root);
3153 /* if we visited @root, we're done */
3157 /* if there's an unvisited sibling, visit its leftmost descendant */
3158 next = css_next_child(pos, css_parent(pos));
3160 return css_leftmost_descendant(next);
3162 /* no sibling left, visit parent */
3163 return css_parent(pos);
3165 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3168 * css_advance_task_iter - advance a task itererator to the next css_set
3169 * @it: the iterator to advance
3171 * Advance @it to the next css_set to walk.
3173 static void css_advance_task_iter(struct css_task_iter *it)
3175 struct list_head *l = it->cset_link;
3176 struct cgrp_cset_link *link;
3177 struct css_set *cset;
3179 /* Advance to the next non-empty css_set */
3182 if (l == &it->origin_css->cgroup->cset_links) {
3183 it->cset_link = NULL;
3186 link = list_entry(l, struct cgrp_cset_link, cset_link);
3188 } while (list_empty(&cset->tasks));
3190 it->task = cset->tasks.next;
3194 * css_task_iter_start - initiate task iteration
3195 * @css: the css to walk tasks of
3196 * @it: the task iterator to use
3198 * Initiate iteration through the tasks of @css. The caller can call
3199 * css_task_iter_next() to walk through the tasks until the function
3200 * returns NULL. On completion of iteration, css_task_iter_end() must be
3203 * Note that this function acquires a lock which is released when the
3204 * iteration finishes. The caller can't sleep while iteration is in
3207 void css_task_iter_start(struct cgroup_subsys_state *css,
3208 struct css_task_iter *it)
3209 __acquires(css_set_lock)
3212 * The first time anyone tries to iterate across a css, we need to
3213 * enable the list linking each css_set to its tasks, and fix up
3214 * all existing tasks.
3216 if (!use_task_css_set_links)
3217 cgroup_enable_task_cg_lists();
3219 read_lock(&css_set_lock);
3221 it->origin_css = css;
3222 it->cset_link = &css->cgroup->cset_links;
3224 css_advance_task_iter(it);
3228 * css_task_iter_next - return the next task for the iterator
3229 * @it: the task iterator being iterated
3231 * The "next" function for task iteration. @it should have been
3232 * initialized via css_task_iter_start(). Returns NULL when the iteration
3235 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3237 struct task_struct *res;
3238 struct list_head *l = it->task;
3239 struct cgrp_cset_link *link;
3241 /* If the iterator cg is NULL, we have no tasks */
3244 res = list_entry(l, struct task_struct, cg_list);
3245 /* Advance iterator to find next entry */
3247 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3248 if (l == &link->cset->tasks) {
3250 * We reached the end of this task list - move on to the
3251 * next cgrp_cset_link.
3253 css_advance_task_iter(it);
3261 * css_task_iter_end - finish task iteration
3262 * @it: the task iterator to finish
3264 * Finish task iteration started by css_task_iter_start().
3266 void css_task_iter_end(struct css_task_iter *it)
3267 __releases(css_set_lock)
3269 read_unlock(&css_set_lock);
3272 static inline int started_after_time(struct task_struct *t1,
3273 struct timespec *time,
3274 struct task_struct *t2)
3276 int start_diff = timespec_compare(&t1->start_time, time);
3277 if (start_diff > 0) {
3279 } else if (start_diff < 0) {
3283 * Arbitrarily, if two processes started at the same
3284 * time, we'll say that the lower pointer value
3285 * started first. Note that t2 may have exited by now
3286 * so this may not be a valid pointer any longer, but
3287 * that's fine - it still serves to distinguish
3288 * between two tasks started (effectively) simultaneously.
3295 * This function is a callback from heap_insert() and is used to order
3297 * In this case we order the heap in descending task start time.
3299 static inline int started_after(void *p1, void *p2)
3301 struct task_struct *t1 = p1;
3302 struct task_struct *t2 = p2;
3303 return started_after_time(t1, &t2->start_time, t2);
3307 * css_scan_tasks - iterate though all the tasks in a css
3308 * @css: the css to iterate tasks of
3309 * @test: optional test callback
3310 * @process: process callback
3311 * @data: data passed to @test and @process
3312 * @heap: optional pre-allocated heap used for task iteration
3314 * Iterate through all the tasks in @css, calling @test for each, and if it
3315 * returns %true, call @process for it also.
3317 * @test may be NULL, meaning always true (select all tasks), which
3318 * effectively duplicates css_task_iter_{start,next,end}() but does not
3319 * lock css_set_lock for the call to @process.
3321 * It is guaranteed that @process will act on every task that is a member
3322 * of @css for the duration of this call. This function may or may not
3323 * call @process for tasks that exit or move to a different css during the
3324 * call, or are forked or move into the css during the call.
3326 * Note that @test may be called with locks held, and may in some
3327 * situations be called multiple times for the same task, so it should be
3330 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3331 * heap operations (and its "gt" member will be overwritten), else a
3332 * temporary heap will be used (allocation of which may cause this function
3335 int css_scan_tasks(struct cgroup_subsys_state *css,
3336 bool (*test)(struct task_struct *, void *),
3337 void (*process)(struct task_struct *, void *),
3338 void *data, struct ptr_heap *heap)
3341 struct css_task_iter it;
3342 struct task_struct *p, *dropped;
3343 /* Never dereference latest_task, since it's not refcounted */
3344 struct task_struct *latest_task = NULL;
3345 struct ptr_heap tmp_heap;
3346 struct timespec latest_time = { 0, 0 };
3349 /* The caller supplied our heap and pre-allocated its memory */
3350 heap->gt = &started_after;
3352 /* We need to allocate our own heap memory */
3354 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3356 /* cannot allocate the heap */
3362 * Scan tasks in the css, using the @test callback to determine
3363 * which are of interest, and invoking @process callback on the
3364 * ones which need an update. Since we don't want to hold any
3365 * locks during the task updates, gather tasks to be processed in a
3366 * heap structure. The heap is sorted by descending task start
3367 * time. If the statically-sized heap fills up, we overflow tasks
3368 * that started later, and in future iterations only consider tasks
3369 * that started after the latest task in the previous pass. This
3370 * guarantees forward progress and that we don't miss any tasks.
3373 css_task_iter_start(css, &it);
3374 while ((p = css_task_iter_next(&it))) {
3376 * Only affect tasks that qualify per the caller's callback,
3377 * if he provided one
3379 if (test && !test(p, data))
3382 * Only process tasks that started after the last task
3385 if (!started_after_time(p, &latest_time, latest_task))
3387 dropped = heap_insert(heap, p);
3388 if (dropped == NULL) {
3390 * The new task was inserted; the heap wasn't
3394 } else if (dropped != p) {
3396 * The new task was inserted, and pushed out a
3400 put_task_struct(dropped);
3403 * Else the new task was newer than anything already in
3404 * the heap and wasn't inserted
3407 css_task_iter_end(&it);
3410 for (i = 0; i < heap->size; i++) {
3411 struct task_struct *q = heap->ptrs[i];
3413 latest_time = q->start_time;
3416 /* Process the task per the caller's callback */
3421 * If we had to process any tasks at all, scan again
3422 * in case some of them were in the middle of forking
3423 * children that didn't get processed.
3424 * Not the most efficient way to do it, but it avoids
3425 * having to take callback_mutex in the fork path
3429 if (heap == &tmp_heap)
3430 heap_free(&tmp_heap);
3434 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3436 struct cgroup *new_cgroup = data;
3438 mutex_lock(&cgroup_mutex);
3439 cgroup_attach_task(new_cgroup, task, false);
3440 mutex_unlock(&cgroup_mutex);
3444 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3445 * @to: cgroup to which the tasks will be moved
3446 * @from: cgroup in which the tasks currently reside
3448 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3450 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3455 * Stuff for reading the 'tasks'/'procs' files.
3457 * Reading this file can return large amounts of data if a cgroup has
3458 * *lots* of attached tasks. So it may need several calls to read(),
3459 * but we cannot guarantee that the information we produce is correct
3460 * unless we produce it entirely atomically.
3464 /* which pidlist file are we talking about? */
3465 enum cgroup_filetype {
3471 * A pidlist is a list of pids that virtually represents the contents of one
3472 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3473 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3476 struct cgroup_pidlist {
3478 * used to find which pidlist is wanted. doesn't change as long as
3479 * this particular list stays in the list.
3481 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3484 /* how many elements the above list has */
3486 /* how many files are using the current array */
3488 /* each of these stored in a list by its cgroup */
3489 struct list_head links;
3490 /* pointer to the cgroup we belong to, for list removal purposes */
3491 struct cgroup *owner;
3492 /* protects the other fields */
3493 struct rw_semaphore rwsem;
3497 * The following two functions "fix" the issue where there are more pids
3498 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3499 * TODO: replace with a kernel-wide solution to this problem
3501 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3502 static void *pidlist_allocate(int count)
3504 if (PIDLIST_TOO_LARGE(count))
3505 return vmalloc(count * sizeof(pid_t));
3507 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3509 static void pidlist_free(void *p)
3511 if (is_vmalloc_addr(p))
3518 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3519 * Returns the number of unique elements.
3521 static int pidlist_uniq(pid_t *list, int length)
3526 * we presume the 0th element is unique, so i starts at 1. trivial
3527 * edge cases first; no work needs to be done for either
3529 if (length == 0 || length == 1)
3531 /* src and dest walk down the list; dest counts unique elements */
3532 for (src = 1; src < length; src++) {
3533 /* find next unique element */
3534 while (list[src] == list[src-1]) {
3539 /* dest always points to where the next unique element goes */
3540 list[dest] = list[src];
3547 static int cmppid(const void *a, const void *b)
3549 return *(pid_t *)a - *(pid_t *)b;
3553 * find the appropriate pidlist for our purpose (given procs vs tasks)
3554 * returns with the lock on that pidlist already held, and takes care
3555 * of the use count, or returns NULL with no locks held if we're out of
3558 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3559 enum cgroup_filetype type)
3561 struct cgroup_pidlist *l;
3562 /* don't need task_nsproxy() if we're looking at ourself */
3563 struct pid_namespace *ns = task_active_pid_ns(current);
3566 * We can't drop the pidlist_mutex before taking the l->rwsem in case
3567 * the last ref-holder is trying to remove l from the list at the same
3568 * time. Holding the pidlist_mutex precludes somebody taking whichever
3569 * list we find out from under us - compare release_pid_array().
3571 mutex_lock(&cgrp->pidlist_mutex);
3572 list_for_each_entry(l, &cgrp->pidlists, links) {
3573 if (l->key.type == type && l->key.ns == ns) {
3574 /* make sure l doesn't vanish out from under us */
3575 down_write(&l->rwsem);
3576 mutex_unlock(&cgrp->pidlist_mutex);
3580 /* entry not found; create a new one */
3581 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3583 mutex_unlock(&cgrp->pidlist_mutex);
3586 init_rwsem(&l->rwsem);
3587 down_write(&l->rwsem);
3589 l->key.ns = get_pid_ns(ns);
3591 list_add(&l->links, &cgrp->pidlists);
3592 mutex_unlock(&cgrp->pidlist_mutex);
3597 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3599 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3600 struct cgroup_pidlist **lp)
3604 int pid, n = 0; /* used for populating the array */
3605 struct css_task_iter it;
3606 struct task_struct *tsk;
3607 struct cgroup_pidlist *l;
3610 * If cgroup gets more users after we read count, we won't have
3611 * enough space - tough. This race is indistinguishable to the
3612 * caller from the case that the additional cgroup users didn't
3613 * show up until sometime later on.
3615 length = cgroup_task_count(cgrp);
3616 array = pidlist_allocate(length);
3619 /* now, populate the array */
3620 css_task_iter_start(&cgrp->dummy_css, &it);
3621 while ((tsk = css_task_iter_next(&it))) {
3622 if (unlikely(n == length))
3624 /* get tgid or pid for procs or tasks file respectively */
3625 if (type == CGROUP_FILE_PROCS)
3626 pid = task_tgid_vnr(tsk);
3628 pid = task_pid_vnr(tsk);
3629 if (pid > 0) /* make sure to only use valid results */
3632 css_task_iter_end(&it);
3634 /* now sort & (if procs) strip out duplicates */
3635 sort(array, length, sizeof(pid_t), cmppid, NULL);
3636 if (type == CGROUP_FILE_PROCS)
3637 length = pidlist_uniq(array, length);
3638 l = cgroup_pidlist_find(cgrp, type);
3640 pidlist_free(array);
3643 /* store array, freeing old if necessary - lock already held */
3644 pidlist_free(l->list);
3648 up_write(&l->rwsem);
3654 * cgroupstats_build - build and fill cgroupstats
3655 * @stats: cgroupstats to fill information into
3656 * @dentry: A dentry entry belonging to the cgroup for which stats have
3659 * Build and fill cgroupstats so that taskstats can export it to user
3662 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3665 struct cgroup *cgrp;
3666 struct css_task_iter it;
3667 struct task_struct *tsk;
3670 * Validate dentry by checking the superblock operations,
3671 * and make sure it's a directory.
3673 if (dentry->d_sb->s_op != &cgroup_ops ||
3674 !S_ISDIR(dentry->d_inode->i_mode))
3678 cgrp = dentry->d_fsdata;
3680 css_task_iter_start(&cgrp->dummy_css, &it);
3681 while ((tsk = css_task_iter_next(&it))) {
3682 switch (tsk->state) {
3684 stats->nr_running++;
3686 case TASK_INTERRUPTIBLE:
3687 stats->nr_sleeping++;
3689 case TASK_UNINTERRUPTIBLE:
3690 stats->nr_uninterruptible++;
3693 stats->nr_stopped++;
3696 if (delayacct_is_task_waiting_on_io(tsk))
3697 stats->nr_io_wait++;
3701 css_task_iter_end(&it);
3709 * seq_file methods for the tasks/procs files. The seq_file position is the
3710 * next pid to display; the seq_file iterator is a pointer to the pid
3711 * in the cgroup->l->list array.
3714 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3717 * Initially we receive a position value that corresponds to
3718 * one more than the last pid shown (or 0 on the first call or
3719 * after a seek to the start). Use a binary-search to find the
3720 * next pid to display, if any
3722 struct cgroup_pidlist *l = s->private;
3723 int index = 0, pid = *pos;
3726 down_read(&l->rwsem);
3728 int end = l->length;
3730 while (index < end) {
3731 int mid = (index + end) / 2;
3732 if (l->list[mid] == pid) {
3735 } else if (l->list[mid] <= pid)
3741 /* If we're off the end of the array, we're done */
3742 if (index >= l->length)
3744 /* Update the abstract position to be the actual pid that we found */
3745 iter = l->list + index;
3750 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3752 struct cgroup_pidlist *l = s->private;
3756 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3758 struct cgroup_pidlist *l = s->private;
3760 pid_t *end = l->list + l->length;
3762 * Advance to the next pid in the array. If this goes off the
3774 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3776 return seq_printf(s, "%d\n", *(int *)v);
3780 * seq_operations functions for iterating on pidlists through seq_file -
3781 * independent of whether it's tasks or procs
3783 static const struct seq_operations cgroup_pidlist_seq_operations = {
3784 .start = cgroup_pidlist_start,
3785 .stop = cgroup_pidlist_stop,
3786 .next = cgroup_pidlist_next,
3787 .show = cgroup_pidlist_show,
3790 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3793 * the case where we're the last user of this particular pidlist will
3794 * have us remove it from the cgroup's list, which entails taking the
3795 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3796 * pidlist_mutex, we have to take pidlist_mutex first.
3798 mutex_lock(&l->owner->pidlist_mutex);
3799 down_write(&l->rwsem);
3800 BUG_ON(!l->use_count);
3801 if (!--l->use_count) {
3802 /* we're the last user if refcount is 0; remove and free */
3803 list_del(&l->links);
3804 mutex_unlock(&l->owner->pidlist_mutex);
3805 pidlist_free(l->list);
3806 put_pid_ns(l->key.ns);
3807 up_write(&l->rwsem);
3811 mutex_unlock(&l->owner->pidlist_mutex);
3812 up_write(&l->rwsem);
3815 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3817 struct cgroup_pidlist *l;
3818 if (!(file->f_mode & FMODE_READ))
3821 * the seq_file will only be initialized if the file was opened for
3822 * reading; hence we check if it's not null only in that case.
3824 l = ((struct seq_file *)file->private_data)->private;
3825 cgroup_release_pid_array(l);
3826 return seq_release(inode, file);
3829 static const struct file_operations cgroup_pidlist_operations = {
3831 .llseek = seq_lseek,
3832 .write = cgroup_file_write,
3833 .release = cgroup_pidlist_release,
3837 * The following functions handle opens on a file that displays a pidlist
3838 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3841 /* helper function for the two below it */
3842 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3844 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3845 struct cgroup_pidlist *l;
3848 /* Nothing to do for write-only files */
3849 if (!(file->f_mode & FMODE_READ))
3852 /* have the array populated */
3853 retval = pidlist_array_load(cgrp, type, &l);
3856 /* configure file information */
3857 file->f_op = &cgroup_pidlist_operations;
3859 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3861 cgroup_release_pid_array(l);
3864 ((struct seq_file *)file->private_data)->private = l;
3867 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3869 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3871 static int cgroup_procs_open(struct inode *unused, struct file *file)
3873 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3876 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3879 return notify_on_release(css->cgroup);
3882 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3883 struct cftype *cft, u64 val)
3885 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3887 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3889 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3894 * When dput() is called asynchronously, if umount has been done and
3895 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3896 * there's a small window that vfs will see the root dentry with non-zero
3897 * refcnt and trigger BUG().
3899 * That's why we hold a reference before dput() and drop it right after.
3901 static void cgroup_dput(struct cgroup *cgrp)
3903 struct super_block *sb = cgrp->root->sb;
3905 atomic_inc(&sb->s_active);
3907 deactivate_super(sb);
3911 * Unregister event and free resources.
3913 * Gets called from workqueue.
3915 static void cgroup_event_remove(struct work_struct *work)
3917 struct cgroup_event *event = container_of(work, struct cgroup_event,
3919 struct cgroup_subsys_state *css = event->css;
3921 remove_wait_queue(event->wqh, &event->wait);
3923 event->cft->unregister_event(css, event->cft, event->eventfd);
3925 /* Notify userspace the event is going away. */
3926 eventfd_signal(event->eventfd, 1);
3928 eventfd_ctx_put(event->eventfd);
3934 * Gets called on POLLHUP on eventfd when user closes it.
3936 * Called with wqh->lock held and interrupts disabled.
3938 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3939 int sync, void *key)
3941 struct cgroup_event *event = container_of(wait,
3942 struct cgroup_event, wait);
3943 struct cgroup *cgrp = event->css->cgroup;
3944 unsigned long flags = (unsigned long)key;
3946 if (flags & POLLHUP) {
3948 * If the event has been detached at cgroup removal, we
3949 * can simply return knowing the other side will cleanup
3952 * We can't race against event freeing since the other
3953 * side will require wqh->lock via remove_wait_queue(),
3956 spin_lock(&cgrp->event_list_lock);
3957 if (!list_empty(&event->list)) {
3958 list_del_init(&event->list);
3960 * We are in atomic context, but cgroup_event_remove()
3961 * may sleep, so we have to call it in workqueue.
3963 schedule_work(&event->remove);
3965 spin_unlock(&cgrp->event_list_lock);
3971 static void cgroup_event_ptable_queue_proc(struct file *file,
3972 wait_queue_head_t *wqh, poll_table *pt)
3974 struct cgroup_event *event = container_of(pt,
3975 struct cgroup_event, pt);
3978 add_wait_queue(wqh, &event->wait);
3982 * Parse input and register new cgroup event handler.
3984 * Input must be in format '<event_fd> <control_fd> <args>'.
3985 * Interpretation of args is defined by control file implementation.
3987 static int cgroup_write_event_control(struct cgroup_subsys_state *dummy_css,
3988 struct cftype *cft, const char *buffer)
3990 struct cgroup *cgrp = dummy_css->cgroup;
3991 struct cgroup_event *event;
3992 struct cgroup_subsys_state *cfile_css;
3993 unsigned int efd, cfd;
3999 efd = simple_strtoul(buffer, &endp, 10);
4004 cfd = simple_strtoul(buffer, &endp, 10);
4005 if ((*endp != ' ') && (*endp != '\0'))
4009 event = kzalloc(sizeof(*event), GFP_KERNEL);
4013 INIT_LIST_HEAD(&event->list);
4014 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
4015 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
4016 INIT_WORK(&event->remove, cgroup_event_remove);
4024 event->eventfd = eventfd_ctx_fileget(efile.file);
4025 if (IS_ERR(event->eventfd)) {
4026 ret = PTR_ERR(event->eventfd);
4033 goto out_put_eventfd;
4036 /* the process need read permission on control file */
4037 /* AV: shouldn't we check that it's been opened for read instead? */
4038 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4042 event->cft = __file_cft(cfile.file);
4043 if (IS_ERR(event->cft)) {
4044 ret = PTR_ERR(event->cft);
4048 if (!event->cft->ss) {
4054 * Determine the css of @cfile, verify it belongs to the same
4055 * cgroup as cgroup.event_control, and associate @event with it.
4056 * Remaining events are automatically removed on cgroup destruction
4057 * but the removal is asynchronous, so take an extra ref.
4062 event->css = cgroup_css(cgrp, event->cft->ss);
4063 cfile_css = css_from_dir(cfile.file->f_dentry->d_parent, event->cft->ss);
4064 if (event->css && event->css == cfile_css && css_tryget(event->css))
4071 if (!event->cft->register_event || !event->cft->unregister_event) {
4076 ret = event->cft->register_event(event->css, event->cft,
4077 event->eventfd, buffer);
4081 efile.file->f_op->poll(efile.file, &event->pt);
4083 spin_lock(&cgrp->event_list_lock);
4084 list_add(&event->list, &cgrp->event_list);
4085 spin_unlock(&cgrp->event_list_lock);
4093 css_put(event->css);
4097 eventfd_ctx_put(event->eventfd);
4106 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
4109 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4112 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
4113 struct cftype *cft, u64 val)
4116 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4118 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4122 static struct cftype cgroup_base_files[] = {
4124 .name = "cgroup.procs",
4125 .open = cgroup_procs_open,
4126 .write_u64 = cgroup_procs_write,
4127 .release = cgroup_pidlist_release,
4128 .mode = S_IRUGO | S_IWUSR,
4131 .name = "cgroup.event_control",
4132 .write_string = cgroup_write_event_control,
4136 .name = "cgroup.clone_children",
4137 .flags = CFTYPE_INSANE,
4138 .read_u64 = cgroup_clone_children_read,
4139 .write_u64 = cgroup_clone_children_write,
4142 .name = "cgroup.sane_behavior",
4143 .flags = CFTYPE_ONLY_ON_ROOT,
4144 .read_seq_string = cgroup_sane_behavior_show,
4148 * Historical crazy stuff. These don't have "cgroup." prefix and
4149 * don't exist if sane_behavior. If you're depending on these, be
4150 * prepared to be burned.
4154 .flags = CFTYPE_INSANE, /* use "procs" instead */
4155 .open = cgroup_tasks_open,
4156 .write_u64 = cgroup_tasks_write,
4157 .release = cgroup_pidlist_release,
4158 .mode = S_IRUGO | S_IWUSR,
4161 .name = "notify_on_release",
4162 .flags = CFTYPE_INSANE,
4163 .read_u64 = cgroup_read_notify_on_release,
4164 .write_u64 = cgroup_write_notify_on_release,
4167 .name = "release_agent",
4168 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4169 .read_seq_string = cgroup_release_agent_show,
4170 .write_string = cgroup_release_agent_write,
4171 .max_write_len = PATH_MAX,
4177 * cgroup_populate_dir - create subsys files in a cgroup directory
4178 * @cgrp: target cgroup
4179 * @subsys_mask: mask of the subsystem ids whose files should be added
4181 * On failure, no file is added.
4183 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
4185 struct cgroup_subsys *ss;
4188 /* process cftsets of each subsystem */
4189 for_each_subsys(ss, i) {
4190 struct cftype_set *set;
4192 if (!test_bit(i, &subsys_mask))
4195 list_for_each_entry(set, &ss->cftsets, node) {
4196 ret = cgroup_addrm_files(cgrp, set->cfts, true);
4203 cgroup_clear_dir(cgrp, subsys_mask);
4208 * css destruction is four-stage process.
4210 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4211 * Implemented in kill_css().
4213 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4214 * and thus css_tryget() is guaranteed to fail, the css can be offlined
4215 * by invoking offline_css(). After offlining, the base ref is put.
4216 * Implemented in css_killed_work_fn().
4218 * 3. When the percpu_ref reaches zero, the only possible remaining
4219 * accessors are inside RCU read sections. css_release() schedules the
4222 * 4. After the grace period, the css can be freed. Implemented in
4223 * css_free_work_fn().
4225 * It is actually hairier because both step 2 and 4 require process context
4226 * and thus involve punting to css->destroy_work adding two additional
4227 * steps to the already complex sequence.
4229 static void css_free_work_fn(struct work_struct *work)
4231 struct cgroup_subsys_state *css =
4232 container_of(work, struct cgroup_subsys_state, destroy_work);
4233 struct cgroup *cgrp = css->cgroup;
4236 css_put(css->parent);
4238 css->ss->css_free(css);
4242 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4244 struct cgroup_subsys_state *css =
4245 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4248 * css holds an extra ref to @cgrp->dentry which is put on the last
4249 * css_put(). dput() requires process context which we don't have.
4251 INIT_WORK(&css->destroy_work, css_free_work_fn);
4252 schedule_work(&css->destroy_work);
4255 static void css_release(struct percpu_ref *ref)
4257 struct cgroup_subsys_state *css =
4258 container_of(ref, struct cgroup_subsys_state, refcnt);
4260 call_rcu(&css->rcu_head, css_free_rcu_fn);
4263 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
4264 struct cgroup *cgrp)
4271 css->parent = cgroup_css(cgrp->parent, ss);
4273 css->flags |= CSS_ROOT;
4275 BUG_ON(cgroup_css(cgrp, ss));
4278 /* invoke ->css_online() on a new CSS and mark it online if successful */
4279 static int online_css(struct cgroup_subsys_state *css)
4281 struct cgroup_subsys *ss = css->ss;
4284 lockdep_assert_held(&cgroup_mutex);
4287 ret = ss->css_online(css);
4289 css->flags |= CSS_ONLINE;
4290 css->cgroup->nr_css++;
4291 rcu_assign_pointer(css->cgroup->subsys[ss->subsys_id], css);
4296 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4297 static void offline_css(struct cgroup_subsys_state *css)
4299 struct cgroup_subsys *ss = css->ss;
4301 lockdep_assert_held(&cgroup_mutex);
4303 if (!(css->flags & CSS_ONLINE))
4306 if (ss->css_offline)
4307 ss->css_offline(css);
4309 css->flags &= ~CSS_ONLINE;
4310 css->cgroup->nr_css--;
4311 RCU_INIT_POINTER(css->cgroup->subsys[ss->subsys_id], css);
4315 * cgroup_create - create a cgroup
4316 * @parent: cgroup that will be parent of the new cgroup
4317 * @dentry: dentry of the new cgroup
4318 * @mode: mode to set on new inode
4320 * Must be called with the mutex on the parent inode held
4322 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4325 struct cgroup_subsys_state *css_ar[CGROUP_SUBSYS_COUNT] = { };
4326 struct cgroup *cgrp;
4327 struct cgroup_name *name;
4328 struct cgroupfs_root *root = parent->root;
4330 struct cgroup_subsys *ss;
4331 struct super_block *sb = root->sb;
4333 /* allocate the cgroup and its ID, 0 is reserved for the root */
4334 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4338 name = cgroup_alloc_name(dentry);
4341 rcu_assign_pointer(cgrp->name, name);
4344 * Temporarily set the pointer to NULL, so idr_find() won't return
4345 * a half-baked cgroup.
4347 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4352 * Only live parents can have children. Note that the liveliness
4353 * check isn't strictly necessary because cgroup_mkdir() and
4354 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4355 * anyway so that locking is contained inside cgroup proper and we
4356 * don't get nasty surprises if we ever grow another caller.
4358 if (!cgroup_lock_live_group(parent)) {
4363 /* Grab a reference on the superblock so the hierarchy doesn't
4364 * get deleted on unmount if there are child cgroups. This
4365 * can be done outside cgroup_mutex, since the sb can't
4366 * disappear while someone has an open control file on the
4368 atomic_inc(&sb->s_active);
4370 init_cgroup_housekeeping(cgrp);
4372 dentry->d_fsdata = cgrp;
4373 cgrp->dentry = dentry;
4375 cgrp->parent = parent;
4376 cgrp->dummy_css.parent = &parent->dummy_css;
4377 cgrp->root = parent->root;
4379 if (notify_on_release(parent))
4380 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4382 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4383 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4385 for_each_root_subsys(root, ss) {
4386 struct cgroup_subsys_state *css;
4388 css = ss->css_alloc(cgroup_css(parent, ss));
4393 css_ar[ss->subsys_id] = css;
4395 err = percpu_ref_init(&css->refcnt, css_release);
4399 init_css(css, ss, cgrp);
4403 * Create directory. cgroup_create_file() returns with the new
4404 * directory locked on success so that it can be populated without
4405 * dropping cgroup_mutex.
4407 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4410 lockdep_assert_held(&dentry->d_inode->i_mutex);
4412 cgrp->serial_nr = cgroup_serial_nr_next++;
4414 /* allocation complete, commit to creation */
4415 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4416 root->number_of_cgroups++;
4418 /* each css holds a ref to the cgroup's dentry and the parent css */
4419 for_each_root_subsys(root, ss) {
4420 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4423 css_get(css->parent);
4426 /* hold a ref to the parent's dentry */
4427 dget(parent->dentry);
4429 /* creation succeeded, notify subsystems */
4430 for_each_root_subsys(root, ss) {
4431 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4433 err = online_css(css);
4437 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4439 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",
4440 current->comm, current->pid, ss->name);
4441 if (!strcmp(ss->name, "memory"))
4442 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4443 ss->warned_broken_hierarchy = true;
4447 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4449 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4453 err = cgroup_populate_dir(cgrp, root->subsys_mask);
4457 mutex_unlock(&cgroup_mutex);
4458 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4463 for_each_root_subsys(root, ss) {
4464 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4467 percpu_ref_cancel_init(&css->refcnt);
4471 mutex_unlock(&cgroup_mutex);
4472 /* Release the reference count that we took on the superblock */
4473 deactivate_super(sb);
4475 idr_remove(&root->cgroup_idr, cgrp->id);
4477 kfree(rcu_dereference_raw(cgrp->name));
4483 cgroup_destroy_locked(cgrp);
4484 mutex_unlock(&cgroup_mutex);
4485 mutex_unlock(&dentry->d_inode->i_mutex);
4489 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4491 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4493 /* the vfs holds inode->i_mutex already */
4494 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4498 * This is called when the refcnt of a css is confirmed to be killed.
4499 * css_tryget() is now guaranteed to fail.
4501 static void css_killed_work_fn(struct work_struct *work)
4503 struct cgroup_subsys_state *css =
4504 container_of(work, struct cgroup_subsys_state, destroy_work);
4505 struct cgroup *cgrp = css->cgroup;
4507 mutex_lock(&cgroup_mutex);
4510 * css_tryget() is guaranteed to fail now. Tell subsystems to
4511 * initate destruction.
4516 * If @cgrp is marked dead, it's waiting for refs of all css's to
4517 * be disabled before proceeding to the second phase of cgroup
4518 * destruction. If we are the last one, kick it off.
4520 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4521 cgroup_destroy_css_killed(cgrp);
4523 mutex_unlock(&cgroup_mutex);
4526 * Put the css refs from kill_css(). Each css holds an extra
4527 * reference to the cgroup's dentry and cgroup removal proceeds
4528 * regardless of css refs. On the last put of each css, whenever
4529 * that may be, the extra dentry ref is put so that dentry
4530 * destruction happens only after all css's are released.
4535 /* css kill confirmation processing requires process context, bounce */
4536 static void css_killed_ref_fn(struct percpu_ref *ref)
4538 struct cgroup_subsys_state *css =
4539 container_of(ref, struct cgroup_subsys_state, refcnt);
4541 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4542 schedule_work(&css->destroy_work);
4546 * kill_css - destroy a css
4547 * @css: css to destroy
4549 * This function initiates destruction of @css by removing cgroup interface
4550 * files and putting its base reference. ->css_offline() will be invoked
4551 * asynchronously once css_tryget() is guaranteed to fail and when the
4552 * reference count reaches zero, @css will be released.
4554 static void kill_css(struct cgroup_subsys_state *css)
4556 cgroup_clear_dir(css->cgroup, 1 << css->ss->subsys_id);
4559 * Killing would put the base ref, but we need to keep it alive
4560 * until after ->css_offline().
4565 * cgroup core guarantees that, by the time ->css_offline() is
4566 * invoked, no new css reference will be given out via
4567 * css_tryget(). We can't simply call percpu_ref_kill() and
4568 * proceed to offlining css's because percpu_ref_kill() doesn't
4569 * guarantee that the ref is seen as killed on all CPUs on return.
4571 * Use percpu_ref_kill_and_confirm() to get notifications as each
4572 * css is confirmed to be seen as killed on all CPUs.
4574 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4578 * cgroup_destroy_locked - the first stage of cgroup destruction
4579 * @cgrp: cgroup to be destroyed
4581 * css's make use of percpu refcnts whose killing latency shouldn't be
4582 * exposed to userland and are RCU protected. Also, cgroup core needs to
4583 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4584 * invoked. To satisfy all the requirements, destruction is implemented in
4585 * the following two steps.
4587 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4588 * userland visible parts and start killing the percpu refcnts of
4589 * css's. Set up so that the next stage will be kicked off once all
4590 * the percpu refcnts are confirmed to be killed.
4592 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4593 * rest of destruction. Once all cgroup references are gone, the
4594 * cgroup is RCU-freed.
4596 * This function implements s1. After this step, @cgrp is gone as far as
4597 * the userland is concerned and a new cgroup with the same name may be
4598 * created. As cgroup doesn't care about the names internally, this
4599 * doesn't cause any problem.
4601 static int cgroup_destroy_locked(struct cgroup *cgrp)
4602 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4604 struct dentry *d = cgrp->dentry;
4605 struct cgroup_event *event, *tmp;
4606 struct cgroup_subsys *ss;
4607 struct cgroup *child;
4610 lockdep_assert_held(&d->d_inode->i_mutex);
4611 lockdep_assert_held(&cgroup_mutex);
4614 * css_set_lock synchronizes access to ->cset_links and prevents
4615 * @cgrp from being removed while __put_css_set() is in progress.
4617 read_lock(&css_set_lock);
4618 empty = list_empty(&cgrp->cset_links);
4619 read_unlock(&css_set_lock);
4624 * Make sure there's no live children. We can't test ->children
4625 * emptiness as dead children linger on it while being destroyed;
4626 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4630 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4631 empty = cgroup_is_dead(child);
4640 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4641 * will be invoked to perform the rest of destruction once the
4642 * percpu refs of all css's are confirmed to be killed.
4644 for_each_root_subsys(cgrp->root, ss)
4645 kill_css(cgroup_css(cgrp, ss));
4648 * Mark @cgrp dead. This prevents further task migration and child
4649 * creation by disabling cgroup_lock_live_group(). Note that
4650 * CGRP_DEAD assertion is depended upon by css_next_child() to
4651 * resume iteration after dropping RCU read lock. See
4652 * css_next_child() for details.
4654 set_bit(CGRP_DEAD, &cgrp->flags);
4656 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4657 raw_spin_lock(&release_list_lock);
4658 if (!list_empty(&cgrp->release_list))
4659 list_del_init(&cgrp->release_list);
4660 raw_spin_unlock(&release_list_lock);
4663 * If @cgrp has css's attached, the second stage of cgroup
4664 * destruction is kicked off from css_killed_work_fn() after the
4665 * refs of all attached css's are killed. If @cgrp doesn't have
4666 * any css, we kick it off here.
4669 cgroup_destroy_css_killed(cgrp);
4672 * Clear the base files and remove @cgrp directory. The removal
4673 * puts the base ref but we aren't quite done with @cgrp yet, so
4676 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4678 cgroup_d_remove_dir(d);
4681 * Unregister events and notify userspace.
4682 * Notify userspace about cgroup removing only after rmdir of cgroup
4683 * directory to avoid race between userspace and kernelspace.
4685 spin_lock(&cgrp->event_list_lock);
4686 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4687 list_del_init(&event->list);
4688 schedule_work(&event->remove);
4690 spin_unlock(&cgrp->event_list_lock);
4696 * cgroup_destroy_css_killed - the second step of cgroup destruction
4697 * @work: cgroup->destroy_free_work
4699 * This function is invoked from a work item for a cgroup which is being
4700 * destroyed after all css's are offlined and performs the rest of
4701 * destruction. This is the second step of destruction described in the
4702 * comment above cgroup_destroy_locked().
4704 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4706 struct cgroup *parent = cgrp->parent;
4707 struct dentry *d = cgrp->dentry;
4709 lockdep_assert_held(&cgroup_mutex);
4711 /* delete this cgroup from parent->children */
4712 list_del_rcu(&cgrp->sibling);
4715 * We should remove the cgroup object from idr before its grace
4716 * period starts, so we won't be looking up a cgroup while the
4717 * cgroup is being freed.
4719 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4724 set_bit(CGRP_RELEASABLE, &parent->flags);
4725 check_for_release(parent);
4728 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4732 mutex_lock(&cgroup_mutex);
4733 ret = cgroup_destroy_locked(dentry->d_fsdata);
4734 mutex_unlock(&cgroup_mutex);
4739 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4741 INIT_LIST_HEAD(&ss->cftsets);
4744 * base_cftset is embedded in subsys itself, no need to worry about
4747 if (ss->base_cftypes) {
4750 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4753 ss->base_cftset.cfts = ss->base_cftypes;
4754 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4758 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4760 struct cgroup_subsys_state *css;
4762 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4764 mutex_lock(&cgroup_mutex);
4766 /* init base cftset */
4767 cgroup_init_cftsets(ss);
4769 /* Create the top cgroup state for this subsystem */
4770 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4771 ss->root = &cgroup_dummy_root;
4772 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4773 /* We don't handle early failures gracefully */
4774 BUG_ON(IS_ERR(css));
4775 init_css(css, ss, cgroup_dummy_top);
4777 /* Update the init_css_set to contain a subsys
4778 * pointer to this state - since the subsystem is
4779 * newly registered, all tasks and hence the
4780 * init_css_set is in the subsystem's top cgroup. */
4781 init_css_set.subsys[ss->subsys_id] = css;
4783 need_forkexit_callback |= ss->fork || ss->exit;
4785 /* At system boot, before all subsystems have been
4786 * registered, no tasks have been forked, so we don't
4787 * need to invoke fork callbacks here. */
4788 BUG_ON(!list_empty(&init_task.tasks));
4790 BUG_ON(online_css(css));
4792 mutex_unlock(&cgroup_mutex);
4794 /* this function shouldn't be used with modular subsystems, since they
4795 * need to register a subsys_id, among other things */
4800 * cgroup_load_subsys: load and register a modular subsystem at runtime
4801 * @ss: the subsystem to load
4803 * This function should be called in a modular subsystem's initcall. If the
4804 * subsystem is built as a module, it will be assigned a new subsys_id and set
4805 * up for use. If the subsystem is built-in anyway, work is delegated to the
4806 * simpler cgroup_init_subsys.
4808 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4810 struct cgroup_subsys_state *css;
4812 struct hlist_node *tmp;
4813 struct css_set *cset;
4816 /* check name and function validity */
4817 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4818 ss->css_alloc == NULL || ss->css_free == NULL)
4822 * we don't support callbacks in modular subsystems. this check is
4823 * before the ss->module check for consistency; a subsystem that could
4824 * be a module should still have no callbacks even if the user isn't
4825 * compiling it as one.
4827 if (ss->fork || ss->exit)
4831 * an optionally modular subsystem is built-in: we want to do nothing,
4832 * since cgroup_init_subsys will have already taken care of it.
4834 if (ss->module == NULL) {
4835 /* a sanity check */
4836 BUG_ON(cgroup_subsys[ss->subsys_id] != ss);
4840 /* init base cftset */
4841 cgroup_init_cftsets(ss);
4843 mutex_lock(&cgroup_mutex);
4844 cgroup_subsys[ss->subsys_id] = ss;
4847 * no ss->css_alloc seems to need anything important in the ss
4848 * struct, so this can happen first (i.e. before the dummy root
4851 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4853 /* failure case - need to deassign the cgroup_subsys[] slot. */
4854 cgroup_subsys[ss->subsys_id] = NULL;
4855 mutex_unlock(&cgroup_mutex);
4856 return PTR_ERR(css);
4859 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4860 ss->root = &cgroup_dummy_root;
4862 /* our new subsystem will be attached to the dummy hierarchy. */
4863 init_css(css, ss, cgroup_dummy_top);
4866 * Now we need to entangle the css into the existing css_sets. unlike
4867 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4868 * will need a new pointer to it; done by iterating the css_set_table.
4869 * furthermore, modifying the existing css_sets will corrupt the hash
4870 * table state, so each changed css_set will need its hash recomputed.
4871 * this is all done under the css_set_lock.
4873 write_lock(&css_set_lock);
4874 hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4875 /* skip entries that we already rehashed */
4876 if (cset->subsys[ss->subsys_id])
4878 /* remove existing entry */
4879 hash_del(&cset->hlist);
4881 cset->subsys[ss->subsys_id] = css;
4882 /* recompute hash and restore entry */
4883 key = css_set_hash(cset->subsys);
4884 hash_add(css_set_table, &cset->hlist, key);
4886 write_unlock(&css_set_lock);
4888 ret = online_css(css);
4893 mutex_unlock(&cgroup_mutex);
4897 mutex_unlock(&cgroup_mutex);
4898 /* @ss can't be mounted here as try_module_get() would fail */
4899 cgroup_unload_subsys(ss);
4902 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4905 * cgroup_unload_subsys: unload a modular subsystem
4906 * @ss: the subsystem to unload
4908 * This function should be called in a modular subsystem's exitcall. When this
4909 * function is invoked, the refcount on the subsystem's module will be 0, so
4910 * the subsystem will not be attached to any hierarchy.
4912 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4914 struct cgrp_cset_link *link;
4916 BUG_ON(ss->module == NULL);
4919 * we shouldn't be called if the subsystem is in use, and the use of
4920 * try_module_get() in rebind_subsystems() should ensure that it
4921 * doesn't start being used while we're killing it off.
4923 BUG_ON(ss->root != &cgroup_dummy_root);
4925 mutex_lock(&cgroup_mutex);
4927 offline_css(cgroup_css(cgroup_dummy_top, ss));
4929 /* deassign the subsys_id */
4930 cgroup_subsys[ss->subsys_id] = NULL;
4932 /* remove subsystem from the dummy root's list of subsystems */
4933 list_del_init(&ss->sibling);
4936 * disentangle the css from all css_sets attached to the dummy
4937 * top. as in loading, we need to pay our respects to the hashtable
4940 write_lock(&css_set_lock);
4941 list_for_each_entry(link, &cgroup_dummy_top->cset_links, cset_link) {
4942 struct css_set *cset = link->cset;
4945 hash_del(&cset->hlist);
4946 cset->subsys[ss->subsys_id] = NULL;
4947 key = css_set_hash(cset->subsys);
4948 hash_add(css_set_table, &cset->hlist, key);
4950 write_unlock(&css_set_lock);
4953 * remove subsystem's css from the cgroup_dummy_top and free it -
4954 * need to free before marking as null because ss->css_free needs
4955 * the cgrp->subsys pointer to find their state.
4957 ss->css_free(cgroup_css(cgroup_dummy_top, ss));
4958 RCU_INIT_POINTER(cgroup_dummy_top->subsys[ss->subsys_id], NULL);
4960 mutex_unlock(&cgroup_mutex);
4962 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4965 * cgroup_init_early - cgroup initialization at system boot
4967 * Initialize cgroups at system boot, and initialize any
4968 * subsystems that request early init.
4970 int __init cgroup_init_early(void)
4972 struct cgroup_subsys *ss;
4975 atomic_set(&init_css_set.refcount, 1);
4976 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4977 INIT_LIST_HEAD(&init_css_set.tasks);
4978 INIT_HLIST_NODE(&init_css_set.hlist);
4980 init_cgroup_root(&cgroup_dummy_root);
4981 cgroup_root_count = 1;
4982 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4984 init_cgrp_cset_link.cset = &init_css_set;
4985 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4986 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4987 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4989 /* at bootup time, we don't worry about modular subsystems */
4990 for_each_builtin_subsys(ss, i) {
4992 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4993 BUG_ON(!ss->css_alloc);
4994 BUG_ON(!ss->css_free);
4995 if (ss->subsys_id != i) {
4996 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4997 ss->name, ss->subsys_id);
5002 cgroup_init_subsys(ss);
5008 * cgroup_init - cgroup initialization
5010 * Register cgroup filesystem and /proc file, and initialize
5011 * any subsystems that didn't request early init.
5013 int __init cgroup_init(void)
5015 struct cgroup_subsys *ss;
5019 err = bdi_init(&cgroup_backing_dev_info);
5023 for_each_builtin_subsys(ss, i) {
5024 if (!ss->early_init)
5025 cgroup_init_subsys(ss);
5028 /* allocate id for the dummy hierarchy */
5029 mutex_lock(&cgroup_mutex);
5030 mutex_lock(&cgroup_root_mutex);
5032 /* Add init_css_set to the hash table */
5033 key = css_set_hash(init_css_set.subsys);
5034 hash_add(css_set_table, &init_css_set.hlist, key);
5036 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
5038 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
5042 mutex_unlock(&cgroup_root_mutex);
5043 mutex_unlock(&cgroup_mutex);
5045 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
5051 err = register_filesystem(&cgroup_fs_type);
5053 kobject_put(cgroup_kobj);
5057 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
5061 bdi_destroy(&cgroup_backing_dev_info);
5067 * proc_cgroup_show()
5068 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5069 * - Used for /proc/<pid>/cgroup.
5070 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
5071 * doesn't really matter if tsk->cgroup changes after we read it,
5072 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
5073 * anyway. No need to check that tsk->cgroup != NULL, thanks to
5074 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
5075 * cgroup to top_cgroup.
5078 /* TODO: Use a proper seq_file iterator */
5079 int proc_cgroup_show(struct seq_file *m, void *v)
5082 struct task_struct *tsk;
5085 struct cgroupfs_root *root;
5088 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5094 tsk = get_pid_task(pid, PIDTYPE_PID);
5100 mutex_lock(&cgroup_mutex);
5102 for_each_active_root(root) {
5103 struct cgroup_subsys *ss;
5104 struct cgroup *cgrp;
5107 seq_printf(m, "%d:", root->hierarchy_id);
5108 for_each_root_subsys(root, ss)
5109 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
5110 if (strlen(root->name))
5111 seq_printf(m, "%sname=%s", count ? "," : "",
5114 cgrp = task_cgroup_from_root(tsk, root);
5115 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
5123 mutex_unlock(&cgroup_mutex);
5124 put_task_struct(tsk);
5131 /* Display information about each subsystem and each hierarchy */
5132 static int proc_cgroupstats_show(struct seq_file *m, void *v)
5134 struct cgroup_subsys *ss;
5137 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
5139 * ideally we don't want subsystems moving around while we do this.
5140 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
5141 * subsys/hierarchy state.
5143 mutex_lock(&cgroup_mutex);
5145 for_each_subsys(ss, i)
5146 seq_printf(m, "%s\t%d\t%d\t%d\n",
5147 ss->name, ss->root->hierarchy_id,
5148 ss->root->number_of_cgroups, !ss->disabled);
5150 mutex_unlock(&cgroup_mutex);
5154 static int cgroupstats_open(struct inode *inode, struct file *file)
5156 return single_open(file, proc_cgroupstats_show, NULL);
5159 static const struct file_operations proc_cgroupstats_operations = {
5160 .open = cgroupstats_open,
5162 .llseek = seq_lseek,
5163 .release = single_release,
5167 * cgroup_fork - attach newly forked task to its parents cgroup.
5168 * @child: pointer to task_struct of forking parent process.
5170 * Description: A task inherits its parent's cgroup at fork().
5172 * A pointer to the shared css_set was automatically copied in
5173 * fork.c by dup_task_struct(). However, we ignore that copy, since
5174 * it was not made under the protection of RCU or cgroup_mutex, so
5175 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
5176 * have already changed current->cgroups, allowing the previously
5177 * referenced cgroup group to be removed and freed.
5179 * At the point that cgroup_fork() is called, 'current' is the parent
5180 * task, and the passed argument 'child' points to the child task.
5182 void cgroup_fork(struct task_struct *child)
5185 get_css_set(task_css_set(current));
5186 child->cgroups = current->cgroups;
5187 task_unlock(current);
5188 INIT_LIST_HEAD(&child->cg_list);
5192 * cgroup_post_fork - called on a new task after adding it to the task list
5193 * @child: the task in question
5195 * Adds the task to the list running through its css_set if necessary and
5196 * call the subsystem fork() callbacks. Has to be after the task is
5197 * visible on the task list in case we race with the first call to
5198 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5201 void cgroup_post_fork(struct task_struct *child)
5203 struct cgroup_subsys *ss;
5207 * use_task_css_set_links is set to 1 before we walk the tasklist
5208 * under the tasklist_lock and we read it here after we added the child
5209 * to the tasklist under the tasklist_lock as well. If the child wasn't
5210 * yet in the tasklist when we walked through it from
5211 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
5212 * should be visible now due to the paired locking and barriers implied
5213 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
5214 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
5217 if (use_task_css_set_links) {
5218 write_lock(&css_set_lock);
5220 if (list_empty(&child->cg_list))
5221 list_add(&child->cg_list, &task_css_set(child)->tasks);
5223 write_unlock(&css_set_lock);
5227 * Call ss->fork(). This must happen after @child is linked on
5228 * css_set; otherwise, @child might change state between ->fork()
5229 * and addition to css_set.
5231 if (need_forkexit_callback) {
5233 * fork/exit callbacks are supported only for builtin
5234 * subsystems, and the builtin section of the subsys
5235 * array is immutable, so we don't need to lock the
5236 * subsys array here. On the other hand, modular section
5237 * of the array can be freed at module unload, so we
5240 for_each_builtin_subsys(ss, i)
5247 * cgroup_exit - detach cgroup from exiting task
5248 * @tsk: pointer to task_struct of exiting process
5249 * @run_callback: run exit callbacks?
5251 * Description: Detach cgroup from @tsk and release it.
5253 * Note that cgroups marked notify_on_release force every task in
5254 * them to take the global cgroup_mutex mutex when exiting.
5255 * This could impact scaling on very large systems. Be reluctant to
5256 * use notify_on_release cgroups where very high task exit scaling
5257 * is required on large systems.
5259 * the_top_cgroup_hack:
5261 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5263 * We call cgroup_exit() while the task is still competent to
5264 * handle notify_on_release(), then leave the task attached to the
5265 * root cgroup in each hierarchy for the remainder of its exit.
5267 * To do this properly, we would increment the reference count on
5268 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5269 * code we would add a second cgroup function call, to drop that
5270 * reference. This would just create an unnecessary hot spot on
5271 * the top_cgroup reference count, to no avail.
5273 * Normally, holding a reference to a cgroup without bumping its
5274 * count is unsafe. The cgroup could go away, or someone could
5275 * attach us to a different cgroup, decrementing the count on
5276 * the first cgroup that we never incremented. But in this case,
5277 * top_cgroup isn't going away, and either task has PF_EXITING set,
5278 * which wards off any cgroup_attach_task() attempts, or task is a failed
5279 * fork, never visible to cgroup_attach_task.
5281 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5283 struct cgroup_subsys *ss;
5284 struct css_set *cset;
5288 * Unlink from the css_set task list if necessary.
5289 * Optimistically check cg_list before taking
5292 if (!list_empty(&tsk->cg_list)) {
5293 write_lock(&css_set_lock);
5294 if (!list_empty(&tsk->cg_list))
5295 list_del_init(&tsk->cg_list);
5296 write_unlock(&css_set_lock);
5299 /* Reassign the task to the init_css_set. */
5301 cset = task_css_set(tsk);
5302 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5304 if (run_callbacks && need_forkexit_callback) {
5306 * fork/exit callbacks are supported only for builtin
5307 * subsystems, see cgroup_post_fork() for details.
5309 for_each_builtin_subsys(ss, i) {
5311 struct cgroup_subsys_state *old_css = cset->subsys[i];
5312 struct cgroup_subsys_state *css = task_css(tsk, i);
5314 ss->exit(css, old_css, tsk);
5320 put_css_set_taskexit(cset);
5323 static void check_for_release(struct cgroup *cgrp)
5325 if (cgroup_is_releasable(cgrp) &&
5326 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5328 * Control Group is currently removeable. If it's not
5329 * already queued for a userspace notification, queue
5332 int need_schedule_work = 0;
5334 raw_spin_lock(&release_list_lock);
5335 if (!cgroup_is_dead(cgrp) &&
5336 list_empty(&cgrp->release_list)) {
5337 list_add(&cgrp->release_list, &release_list);
5338 need_schedule_work = 1;
5340 raw_spin_unlock(&release_list_lock);
5341 if (need_schedule_work)
5342 schedule_work(&release_agent_work);
5347 * Notify userspace when a cgroup is released, by running the
5348 * configured release agent with the name of the cgroup (path
5349 * relative to the root of cgroup file system) as the argument.
5351 * Most likely, this user command will try to rmdir this cgroup.
5353 * This races with the possibility that some other task will be
5354 * attached to this cgroup before it is removed, or that some other
5355 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5356 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5357 * unused, and this cgroup will be reprieved from its death sentence,
5358 * to continue to serve a useful existence. Next time it's released,
5359 * we will get notified again, if it still has 'notify_on_release' set.
5361 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5362 * means only wait until the task is successfully execve()'d. The
5363 * separate release agent task is forked by call_usermodehelper(),
5364 * then control in this thread returns here, without waiting for the
5365 * release agent task. We don't bother to wait because the caller of
5366 * this routine has no use for the exit status of the release agent
5367 * task, so no sense holding our caller up for that.
5369 static void cgroup_release_agent(struct work_struct *work)
5371 BUG_ON(work != &release_agent_work);
5372 mutex_lock(&cgroup_mutex);
5373 raw_spin_lock(&release_list_lock);
5374 while (!list_empty(&release_list)) {
5375 char *argv[3], *envp[3];
5377 char *pathbuf = NULL, *agentbuf = NULL;
5378 struct cgroup *cgrp = list_entry(release_list.next,
5381 list_del_init(&cgrp->release_list);
5382 raw_spin_unlock(&release_list_lock);
5383 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5386 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5388 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5393 argv[i++] = agentbuf;
5394 argv[i++] = pathbuf;
5398 /* minimal command environment */
5399 envp[i++] = "HOME=/";
5400 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5403 /* Drop the lock while we invoke the usermode helper,
5404 * since the exec could involve hitting disk and hence
5405 * be a slow process */
5406 mutex_unlock(&cgroup_mutex);
5407 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5408 mutex_lock(&cgroup_mutex);
5412 raw_spin_lock(&release_list_lock);
5414 raw_spin_unlock(&release_list_lock);
5415 mutex_unlock(&cgroup_mutex);
5418 static int __init cgroup_disable(char *str)
5420 struct cgroup_subsys *ss;
5424 while ((token = strsep(&str, ",")) != NULL) {
5429 * cgroup_disable, being at boot time, can't know about
5430 * module subsystems, so we don't worry about them.
5432 for_each_builtin_subsys(ss, i) {
5433 if (!strcmp(token, ss->name)) {
5435 printk(KERN_INFO "Disabling %s control group"
5436 " subsystem\n", ss->name);
5443 __setup("cgroup_disable=", cgroup_disable);
5446 * css_from_dir - get corresponding css from the dentry of a cgroup dir
5447 * @dentry: directory dentry of interest
5448 * @ss: subsystem of interest
5450 * Must be called under RCU read lock. The caller is responsible for
5451 * pinning the returned css if it needs to be accessed outside the RCU
5454 struct cgroup_subsys_state *css_from_dir(struct dentry *dentry,
5455 struct cgroup_subsys *ss)
5457 struct cgroup *cgrp;
5459 WARN_ON_ONCE(!rcu_read_lock_held());
5461 /* is @dentry a cgroup dir? */
5462 if (!dentry->d_inode ||
5463 dentry->d_inode->i_op != &cgroup_dir_inode_operations)
5464 return ERR_PTR(-EBADF);
5466 cgrp = __d_cgrp(dentry);
5467 return cgroup_css(cgrp, ss) ?: ERR_PTR(-ENOENT);
5471 * css_from_id - lookup css by id
5472 * @id: the cgroup id
5473 * @ss: cgroup subsys to be looked into
5475 * Returns the css if there's valid one with @id, otherwise returns NULL.
5476 * Should be called under rcu_read_lock().
5478 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5480 struct cgroup *cgrp;
5482 rcu_lockdep_assert(rcu_read_lock_held() ||
5483 lockdep_is_held(&cgroup_mutex),
5484 "css_from_id() needs proper protection");
5486 cgrp = idr_find(&ss->root->cgroup_idr, id);
5488 return cgroup_css(cgrp, ss);
5492 #ifdef CONFIG_CGROUP_DEBUG
5493 static struct cgroup_subsys_state *
5494 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5496 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5499 return ERR_PTR(-ENOMEM);
5504 static void debug_css_free(struct cgroup_subsys_state *css)
5509 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5512 return cgroup_task_count(css->cgroup);
5515 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5518 return (u64)(unsigned long)current->cgroups;
5521 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5527 count = atomic_read(&task_css_set(current)->refcount);
5532 static int current_css_set_cg_links_read(struct cgroup_subsys_state *css,
5534 struct seq_file *seq)
5536 struct cgrp_cset_link *link;
5537 struct css_set *cset;
5539 read_lock(&css_set_lock);
5541 cset = rcu_dereference(current->cgroups);
5542 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5543 struct cgroup *c = link->cgrp;
5547 name = c->dentry->d_name.name;
5550 seq_printf(seq, "Root %d group %s\n",
5551 c->root->hierarchy_id, name);
5554 read_unlock(&css_set_lock);
5558 #define MAX_TASKS_SHOWN_PER_CSS 25
5559 static int cgroup_css_links_read(struct cgroup_subsys_state *css,
5560 struct cftype *cft, struct seq_file *seq)
5562 struct cgrp_cset_link *link;
5564 read_lock(&css_set_lock);
5565 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5566 struct css_set *cset = link->cset;
5567 struct task_struct *task;
5569 seq_printf(seq, "css_set %p\n", cset);
5570 list_for_each_entry(task, &cset->tasks, cg_list) {
5571 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5572 seq_puts(seq, " ...\n");
5575 seq_printf(seq, " task %d\n",
5576 task_pid_vnr(task));
5580 read_unlock(&css_set_lock);
5584 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5586 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5589 static struct cftype debug_files[] = {
5591 .name = "taskcount",
5592 .read_u64 = debug_taskcount_read,
5596 .name = "current_css_set",
5597 .read_u64 = current_css_set_read,
5601 .name = "current_css_set_refcount",
5602 .read_u64 = current_css_set_refcount_read,
5606 .name = "current_css_set_cg_links",
5607 .read_seq_string = current_css_set_cg_links_read,
5611 .name = "cgroup_css_links",
5612 .read_seq_string = cgroup_css_links_read,
5616 .name = "releasable",
5617 .read_u64 = releasable_read,
5623 struct cgroup_subsys debug_subsys = {
5625 .css_alloc = debug_css_alloc,
5626 .css_free = debug_css_free,
5627 .subsys_id = debug_subsys_id,
5628 .base_cftypes = debug_files,
5630 #endif /* CONFIG_CGROUP_DEBUG */