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/slab.h>
44 #include <linux/spinlock.h>
45 #include <linux/string.h>
46 #include <linux/sort.h>
47 #include <linux/kmod.h>
48 #include <linux/delayacct.h>
49 #include <linux/cgroupstats.h>
50 #include <linux/hashtable.h>
51 #include <linux/pid_namespace.h>
52 #include <linux/idr.h>
53 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
54 #include <linux/flex_array.h> /* used in cgroup_attach_task */
55 #include <linux/kthread.h>
57 #include <linux/atomic.h>
60 * pidlists linger the following amount before being destroyed. The goal
61 * is avoiding frequent destruction in the middle of consecutive read calls
62 * Expiring in the middle is a performance problem not a correctness one.
63 * 1 sec should be enough.
65 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
67 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
71 * cgroup_tree_mutex nests above cgroup_mutex and protects cftypes, file
72 * creation/removal and hierarchy changing operations including cgroup
73 * creation, removal, css association and controller rebinding. This outer
74 * lock is needed mainly to resolve the circular dependency between kernfs
75 * active ref and cgroup_mutex. cgroup_tree_mutex nests above both.
77 static DEFINE_MUTEX(cgroup_tree_mutex);
80 * cgroup_mutex is the master lock. Any modification to cgroup or its
81 * hierarchy must be performed while holding it.
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);
91 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
92 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
94 static DEFINE_SPINLOCK(release_agent_path_lock);
96 #define cgroup_assert_mutexes_or_rcu_locked() \
97 rcu_lockdep_assert(rcu_read_lock_held() || \
98 lockdep_is_held(&cgroup_tree_mutex) || \
99 lockdep_is_held(&cgroup_mutex), \
100 "cgroup_[tree_]mutex or RCU read lock required");
103 * cgroup destruction makes heavy use of work items and there can be a lot
104 * of concurrent destructions. Use a separate workqueue so that cgroup
105 * destruction work items don't end up filling up max_active of system_wq
106 * which may lead to deadlock.
108 static struct workqueue_struct *cgroup_destroy_wq;
111 * pidlist destructions need to be flushed on cgroup destruction. Use a
112 * separate workqueue as flush domain.
114 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
116 /* generate an array of cgroup subsystem pointers */
117 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
118 static struct cgroup_subsys *cgroup_subsys[] = {
119 #include <linux/cgroup_subsys.h>
123 /* array of cgroup subsystem names */
124 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
125 static const char *cgroup_subsys_name[] = {
126 #include <linux/cgroup_subsys.h>
131 * The dummy hierarchy, reserved for the subsystems that are otherwise
132 * unattached - it never has more than a single cgroup, and all tasks are
133 * part of that cgroup.
135 static struct cgroupfs_root cgroup_dummy_root;
137 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
138 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
140 /* The list of hierarchy roots */
142 static LIST_HEAD(cgroup_roots);
143 static int cgroup_root_count;
145 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
146 static DEFINE_IDR(cgroup_hierarchy_idr);
148 static struct cgroup_name root_cgroup_name = { .name = "/" };
151 * Assign a monotonically increasing serial number to cgroups. It
152 * guarantees cgroups with bigger numbers are newer than those with smaller
153 * numbers. Also, as cgroups are always appended to the parent's
154 * ->children list, it guarantees that sibling cgroups are always sorted in
155 * the ascending serial number order on the list. Protected by
158 static u64 cgroup_serial_nr_next = 1;
160 /* This flag indicates whether tasks in the fork and exit paths should
161 * check for fork/exit handlers to call. This avoids us having to do
162 * extra work in the fork/exit path if none of the subsystems need to
165 static int need_forkexit_callback __read_mostly;
167 static struct cftype cgroup_base_files[];
169 static void cgroup_put(struct cgroup *cgrp);
170 static int rebind_subsystems(struct cgroupfs_root *root,
171 unsigned long added_mask, unsigned removed_mask);
172 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
173 static int cgroup_destroy_locked(struct cgroup *cgrp);
174 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
176 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
179 * cgroup_css - obtain a cgroup's css for the specified subsystem
180 * @cgrp: the cgroup of interest
181 * @ss: the subsystem of interest (%NULL returns the dummy_css)
183 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
184 * function must be called either under cgroup_mutex or rcu_read_lock() and
185 * the caller is responsible for pinning the returned css if it wants to
186 * keep accessing it outside the said locks. This function may return
187 * %NULL if @cgrp doesn't have @subsys_id enabled.
189 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
190 struct cgroup_subsys *ss)
193 return rcu_dereference_check(cgrp->subsys[ss->id],
194 lockdep_is_held(&cgroup_tree_mutex) ||
195 lockdep_is_held(&cgroup_mutex));
197 return &cgrp->dummy_css;
200 /* convenient tests for these bits */
201 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
203 return test_bit(CGRP_DEAD, &cgrp->flags);
206 struct cgroup_subsys_state *seq_css(struct seq_file *seq)
208 struct kernfs_open_file *of = seq->private;
209 struct cgroup *cgrp = of->kn->parent->priv;
210 struct cftype *cft = seq_cft(seq);
213 * This is open and unprotected implementation of cgroup_css().
214 * seq_css() is only called from a kernfs file operation which has
215 * an active reference on the file. Because all the subsystem
216 * files are drained before a css is disassociated with a cgroup,
217 * the matching css from the cgroup's subsys table is guaranteed to
218 * be and stay valid until the enclosing operation is complete.
221 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
223 return &cgrp->dummy_css;
225 EXPORT_SYMBOL_GPL(seq_css);
228 * cgroup_is_descendant - test ancestry
229 * @cgrp: the cgroup to be tested
230 * @ancestor: possible ancestor of @cgrp
232 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
233 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
234 * and @ancestor are accessible.
236 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
239 if (cgrp == ancestor)
245 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
247 static int cgroup_is_releasable(const struct cgroup *cgrp)
250 (1 << CGRP_RELEASABLE) |
251 (1 << CGRP_NOTIFY_ON_RELEASE);
252 return (cgrp->flags & bits) == bits;
255 static int notify_on_release(const struct cgroup *cgrp)
257 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
261 * for_each_css - iterate all css's of a cgroup
262 * @css: the iteration cursor
263 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
264 * @cgrp: the target cgroup to iterate css's of
266 * Should be called under cgroup_mutex.
268 #define for_each_css(css, ssid, cgrp) \
269 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
270 if (!((css) = rcu_dereference_check( \
271 (cgrp)->subsys[(ssid)], \
272 lockdep_is_held(&cgroup_tree_mutex) || \
273 lockdep_is_held(&cgroup_mutex)))) { } \
277 * for_each_subsys - iterate all enabled cgroup subsystems
278 * @ss: the iteration cursor
279 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
281 #define for_each_subsys(ss, ssid) \
282 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
283 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
285 /* iterate across the active hierarchies */
286 #define for_each_active_root(root) \
287 list_for_each_entry((root), &cgroup_roots, root_list)
290 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
291 * @cgrp: the cgroup to be checked for liveness
293 * On success, returns true; the mutex should be later unlocked. On
294 * failure returns false with no lock held.
296 static bool cgroup_lock_live_group(struct cgroup *cgrp)
298 mutex_lock(&cgroup_mutex);
299 if (cgroup_is_dead(cgrp)) {
300 mutex_unlock(&cgroup_mutex);
306 /* the list of cgroups eligible for automatic release. Protected by
307 * release_list_lock */
308 static LIST_HEAD(release_list);
309 static DEFINE_RAW_SPINLOCK(release_list_lock);
310 static void cgroup_release_agent(struct work_struct *work);
311 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
312 static void check_for_release(struct cgroup *cgrp);
315 * A cgroup can be associated with multiple css_sets as different tasks may
316 * belong to different cgroups on different hierarchies. In the other
317 * direction, a css_set is naturally associated with multiple cgroups.
318 * This M:N relationship is represented by the following link structure
319 * which exists for each association and allows traversing the associations
322 struct cgrp_cset_link {
323 /* the cgroup and css_set this link associates */
325 struct css_set *cset;
327 /* list of cgrp_cset_links anchored at cgrp->cset_links */
328 struct list_head cset_link;
330 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
331 struct list_head cgrp_link;
334 /* The default css_set - used by init and its children prior to any
335 * hierarchies being mounted. It contains a pointer to the root state
336 * for each subsystem. Also used to anchor the list of css_sets. Not
337 * reference-counted, to improve performance when child cgroups
338 * haven't been created.
341 static struct css_set init_css_set;
342 static struct cgrp_cset_link init_cgrp_cset_link;
345 * css_set_lock protects the list of css_set objects, and the chain of
346 * tasks off each css_set. Nests outside task->alloc_lock due to
347 * css_task_iter_start().
349 static DEFINE_RWLOCK(css_set_lock);
350 static int css_set_count;
353 * hash table for cgroup groups. This improves the performance to find
354 * an existing css_set. This hash doesn't (currently) take into
355 * account cgroups in empty hierarchies.
357 #define CSS_SET_HASH_BITS 7
358 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
360 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
362 unsigned long key = 0UL;
363 struct cgroup_subsys *ss;
366 for_each_subsys(ss, i)
367 key += (unsigned long)css[i];
368 key = (key >> 16) ^ key;
374 * We don't maintain the lists running through each css_set to its task
375 * until after the first call to css_task_iter_start(). This reduces the
376 * fork()/exit() overhead for people who have cgroups compiled into their
377 * kernel but not actually in use.
379 static int use_task_css_set_links __read_mostly;
381 static void __put_css_set(struct css_set *cset, int taskexit)
383 struct cgrp_cset_link *link, *tmp_link;
386 * Ensure that the refcount doesn't hit zero while any readers
387 * can see it. Similar to atomic_dec_and_lock(), but for an
390 if (atomic_add_unless(&cset->refcount, -1, 1))
392 write_lock(&css_set_lock);
393 if (!atomic_dec_and_test(&cset->refcount)) {
394 write_unlock(&css_set_lock);
398 /* This css_set is dead. unlink it and release cgroup refcounts */
399 hash_del(&cset->hlist);
402 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
403 struct cgroup *cgrp = link->cgrp;
405 list_del(&link->cset_link);
406 list_del(&link->cgrp_link);
408 /* @cgrp can't go away while we're holding css_set_lock */
409 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
411 set_bit(CGRP_RELEASABLE, &cgrp->flags);
412 check_for_release(cgrp);
418 write_unlock(&css_set_lock);
419 kfree_rcu(cset, rcu_head);
423 * refcounted get/put for css_set objects
425 static inline void get_css_set(struct css_set *cset)
427 atomic_inc(&cset->refcount);
430 static inline void put_css_set(struct css_set *cset)
432 __put_css_set(cset, 0);
435 static inline void put_css_set_taskexit(struct css_set *cset)
437 __put_css_set(cset, 1);
441 * compare_css_sets - helper function for find_existing_css_set().
442 * @cset: candidate css_set being tested
443 * @old_cset: existing css_set for a task
444 * @new_cgrp: cgroup that's being entered by the task
445 * @template: desired set of css pointers in css_set (pre-calculated)
447 * Returns true if "cset" matches "old_cset" except for the hierarchy
448 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
450 static bool compare_css_sets(struct css_set *cset,
451 struct css_set *old_cset,
452 struct cgroup *new_cgrp,
453 struct cgroup_subsys_state *template[])
455 struct list_head *l1, *l2;
457 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
458 /* Not all subsystems matched */
463 * Compare cgroup pointers in order to distinguish between
464 * different cgroups in heirarchies with no subsystems. We
465 * could get by with just this check alone (and skip the
466 * memcmp above) but on most setups the memcmp check will
467 * avoid the need for this more expensive check on almost all
471 l1 = &cset->cgrp_links;
472 l2 = &old_cset->cgrp_links;
474 struct cgrp_cset_link *link1, *link2;
475 struct cgroup *cgrp1, *cgrp2;
479 /* See if we reached the end - both lists are equal length. */
480 if (l1 == &cset->cgrp_links) {
481 BUG_ON(l2 != &old_cset->cgrp_links);
484 BUG_ON(l2 == &old_cset->cgrp_links);
486 /* Locate the cgroups associated with these links. */
487 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
488 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
491 /* Hierarchies should be linked in the same order. */
492 BUG_ON(cgrp1->root != cgrp2->root);
495 * If this hierarchy is the hierarchy of the cgroup
496 * that's changing, then we need to check that this
497 * css_set points to the new cgroup; if it's any other
498 * hierarchy, then this css_set should point to the
499 * same cgroup as the old css_set.
501 if (cgrp1->root == new_cgrp->root) {
502 if (cgrp1 != new_cgrp)
513 * find_existing_css_set - init css array and find the matching css_set
514 * @old_cset: the css_set that we're using before the cgroup transition
515 * @cgrp: the cgroup that we're moving into
516 * @template: out param for the new set of csses, should be clear on entry
518 static struct css_set *find_existing_css_set(struct css_set *old_cset,
520 struct cgroup_subsys_state *template[])
522 struct cgroupfs_root *root = cgrp->root;
523 struct cgroup_subsys *ss;
524 struct css_set *cset;
529 * Build the set of subsystem state objects that we want to see in the
530 * new css_set. while subsystems can change globally, the entries here
531 * won't change, so no need for locking.
533 for_each_subsys(ss, i) {
534 if (root->subsys_mask & (1UL << i)) {
535 /* Subsystem is in this hierarchy. So we want
536 * the subsystem state from the new
538 template[i] = cgroup_css(cgrp, ss);
540 /* Subsystem is not in this hierarchy, so we
541 * don't want to change the subsystem state */
542 template[i] = old_cset->subsys[i];
546 key = css_set_hash(template);
547 hash_for_each_possible(css_set_table, cset, hlist, key) {
548 if (!compare_css_sets(cset, old_cset, cgrp, template))
551 /* This css_set matches what we need */
555 /* No existing cgroup group matched */
559 static void free_cgrp_cset_links(struct list_head *links_to_free)
561 struct cgrp_cset_link *link, *tmp_link;
563 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
564 list_del(&link->cset_link);
570 * allocate_cgrp_cset_links - allocate cgrp_cset_links
571 * @count: the number of links to allocate
572 * @tmp_links: list_head the allocated links are put on
574 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
575 * through ->cset_link. Returns 0 on success or -errno.
577 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
579 struct cgrp_cset_link *link;
582 INIT_LIST_HEAD(tmp_links);
584 for (i = 0; i < count; i++) {
585 link = kzalloc(sizeof(*link), GFP_KERNEL);
587 free_cgrp_cset_links(tmp_links);
590 list_add(&link->cset_link, tmp_links);
596 * link_css_set - a helper function to link a css_set to a cgroup
597 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
598 * @cset: the css_set to be linked
599 * @cgrp: the destination cgroup
601 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
604 struct cgrp_cset_link *link;
606 BUG_ON(list_empty(tmp_links));
607 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
610 list_move(&link->cset_link, &cgrp->cset_links);
612 * Always add links to the tail of the list so that the list
613 * is sorted by order of hierarchy creation
615 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
619 * find_css_set - return a new css_set with one cgroup updated
620 * @old_cset: the baseline css_set
621 * @cgrp: the cgroup to be updated
623 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
624 * substituted into the appropriate hierarchy.
626 static struct css_set *find_css_set(struct css_set *old_cset,
629 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
630 struct css_set *cset;
631 struct list_head tmp_links;
632 struct cgrp_cset_link *link;
635 lockdep_assert_held(&cgroup_mutex);
637 /* First see if we already have a cgroup group that matches
639 read_lock(&css_set_lock);
640 cset = find_existing_css_set(old_cset, cgrp, template);
643 read_unlock(&css_set_lock);
648 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
652 /* Allocate all the cgrp_cset_link objects that we'll need */
653 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
658 atomic_set(&cset->refcount, 1);
659 INIT_LIST_HEAD(&cset->cgrp_links);
660 INIT_LIST_HEAD(&cset->tasks);
661 INIT_HLIST_NODE(&cset->hlist);
663 /* Copy the set of subsystem state objects generated in
664 * find_existing_css_set() */
665 memcpy(cset->subsys, template, sizeof(cset->subsys));
667 write_lock(&css_set_lock);
668 /* Add reference counts and links from the new css_set. */
669 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
670 struct cgroup *c = link->cgrp;
672 if (c->root == cgrp->root)
674 link_css_set(&tmp_links, cset, c);
677 BUG_ON(!list_empty(&tmp_links));
681 /* Add this cgroup group to the hash table */
682 key = css_set_hash(cset->subsys);
683 hash_add(css_set_table, &cset->hlist, key);
685 write_unlock(&css_set_lock);
690 static struct cgroupfs_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
692 struct cgroup *top_cgrp = kf_root->kn->priv;
694 return top_cgrp->root;
697 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
701 lockdep_assert_held(&cgroup_mutex);
703 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
708 root->hierarchy_id = id;
712 static void cgroup_exit_root_id(struct cgroupfs_root *root)
714 lockdep_assert_held(&cgroup_mutex);
716 if (root->hierarchy_id) {
717 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
718 root->hierarchy_id = 0;
722 static void cgroup_free_root(struct cgroupfs_root *root)
725 /* hierarhcy ID shoulid already have been released */
726 WARN_ON_ONCE(root->hierarchy_id);
728 idr_destroy(&root->cgroup_idr);
733 static void cgroup_get_root(struct cgroupfs_root *root)
736 * The caller must ensure that @root is alive, which can be
737 * achieved by holding a ref on one of the member cgroups or
738 * following a registered reference to @root while holding
741 WARN_ON_ONCE(atomic_read(&root->refcnt) <= 0);
742 atomic_inc(&root->refcnt);
745 static void cgroup_put_root(struct cgroupfs_root *root)
747 struct cgroup *cgrp = &root->top_cgroup;
748 struct cgrp_cset_link *link, *tmp_link;
752 * @root's refcnt reaching zero and its deregistration should be
753 * atomic w.r.t. cgroup_tree_mutex. This ensures that
754 * cgroup_get_root() is safe to invoke if @root is registered.
756 mutex_lock(&cgroup_tree_mutex);
757 if (!atomic_dec_and_test(&root->refcnt)) {
758 mutex_unlock(&cgroup_tree_mutex);
761 mutex_lock(&cgroup_mutex);
763 BUG_ON(root->number_of_cgroups != 1);
764 BUG_ON(!list_empty(&cgrp->children));
766 /* Rebind all subsystems back to the default hierarchy */
767 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
768 ret = rebind_subsystems(root, 0, root->subsys_mask);
769 /* Shouldn't be able to fail ... */
774 * Release all the links from cset_links to this hierarchy's
777 write_lock(&css_set_lock);
779 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
780 list_del(&link->cset_link);
781 list_del(&link->cgrp_link);
784 write_unlock(&css_set_lock);
786 if (!list_empty(&root->root_list)) {
787 list_del(&root->root_list);
791 cgroup_exit_root_id(root);
793 mutex_unlock(&cgroup_mutex);
794 mutex_unlock(&cgroup_tree_mutex);
796 kernfs_destroy_root(root->kf_root);
797 cgroup_free_root(root);
801 * Return the cgroup for "task" from the given hierarchy. Must be
802 * called with cgroup_mutex held.
804 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
805 struct cgroupfs_root *root)
807 struct css_set *cset;
808 struct cgroup *res = NULL;
810 BUG_ON(!mutex_is_locked(&cgroup_mutex));
811 read_lock(&css_set_lock);
813 * No need to lock the task - since we hold cgroup_mutex the
814 * task can't change groups, so the only thing that can happen
815 * is that it exits and its css is set back to init_css_set.
817 cset = task_css_set(task);
818 if (cset == &init_css_set) {
819 res = &root->top_cgroup;
821 struct cgrp_cset_link *link;
823 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
824 struct cgroup *c = link->cgrp;
826 if (c->root == root) {
832 read_unlock(&css_set_lock);
838 * There is one global cgroup mutex. We also require taking
839 * task_lock() when dereferencing a task's cgroup subsys pointers.
840 * See "The task_lock() exception", at the end of this comment.
842 * A task must hold cgroup_mutex to modify cgroups.
844 * Any task can increment and decrement the count field without lock.
845 * So in general, code holding cgroup_mutex can't rely on the count
846 * field not changing. However, if the count goes to zero, then only
847 * cgroup_attach_task() can increment it again. Because a count of zero
848 * means that no tasks are currently attached, therefore there is no
849 * way a task attached to that cgroup can fork (the other way to
850 * increment the count). So code holding cgroup_mutex can safely
851 * assume that if the count is zero, it will stay zero. Similarly, if
852 * a task holds cgroup_mutex on a cgroup with zero count, it
853 * knows that the cgroup won't be removed, as cgroup_rmdir()
856 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
857 * (usually) take cgroup_mutex. These are the two most performance
858 * critical pieces of code here. The exception occurs on cgroup_exit(),
859 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
860 * is taken, and if the cgroup count is zero, a usermode call made
861 * to the release agent with the name of the cgroup (path relative to
862 * the root of cgroup file system) as the argument.
864 * A cgroup can only be deleted if both its 'count' of using tasks
865 * is zero, and its list of 'children' cgroups is empty. Since all
866 * tasks in the system use _some_ cgroup, and since there is always at
867 * least one task in the system (init, pid == 1), therefore, top_cgroup
868 * always has either children cgroups and/or using tasks. So we don't
869 * need a special hack to ensure that top_cgroup cannot be deleted.
871 * The task_lock() exception
873 * The need for this exception arises from the action of
874 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
875 * another. It does so using cgroup_mutex, however there are
876 * several performance critical places that need to reference
877 * task->cgroup without the expense of grabbing a system global
878 * mutex. Therefore except as noted below, when dereferencing or, as
879 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
880 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
881 * the task_struct routinely used for such matters.
883 * P.S. One more locking exception. RCU is used to guard the
884 * update of a tasks cgroup pointer by cgroup_attach_task()
887 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
888 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
889 static const struct file_operations proc_cgroupstats_operations;
891 static struct cgroup_name *cgroup_alloc_name(const char *name_str)
893 struct cgroup_name *name;
895 name = kmalloc(sizeof(*name) + strlen(name_str) + 1, GFP_KERNEL);
898 strcpy(name->name, name_str);
902 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
905 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
906 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
907 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
908 cft->ss->name, cft->name);
910 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
915 * cgroup_file_mode - deduce file mode of a control file
916 * @cft: the control file in question
918 * returns cft->mode if ->mode is not 0
919 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
920 * returns S_IRUGO if it has only a read handler
921 * returns S_IWUSR if it has only a write hander
923 static umode_t cgroup_file_mode(const struct cftype *cft)
930 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
933 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
940 static void cgroup_free_fn(struct work_struct *work)
942 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
944 mutex_lock(&cgroup_mutex);
945 cgrp->root->number_of_cgroups--;
946 mutex_unlock(&cgroup_mutex);
949 * We get a ref to the parent, and put the ref when this cgroup is
950 * being freed, so it's guaranteed that the parent won't be
951 * destroyed before its children.
953 cgroup_put(cgrp->parent);
955 /* put the root reference that we took when we created the cgroup */
956 cgroup_put_root(cgrp->root);
958 cgroup_pidlist_destroy_all(cgrp);
960 kfree(rcu_dereference_raw(cgrp->name));
964 static void cgroup_free_rcu(struct rcu_head *head)
966 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
968 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
969 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
972 static void cgroup_get(struct cgroup *cgrp)
974 WARN_ON_ONCE(cgroup_is_dead(cgrp));
975 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
976 atomic_inc(&cgrp->refcnt);
979 static void cgroup_put(struct cgroup *cgrp)
981 if (!atomic_dec_and_test(&cgrp->refcnt))
983 if (WARN_ON_ONCE(!cgroup_is_dead(cgrp)))
987 * XXX: cgrp->id is only used to look up css's. As cgroup and
988 * css's lifetimes will be decoupled, it should be made
989 * per-subsystem and moved to css->id so that lookups are
990 * successful until the target css is released.
992 mutex_lock(&cgroup_mutex);
993 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
994 mutex_unlock(&cgroup_mutex);
997 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
1000 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1002 char name[CGROUP_FILE_NAME_MAX];
1004 lockdep_assert_held(&cgroup_tree_mutex);
1005 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1009 * cgroup_clear_dir - remove subsys files in a cgroup directory
1010 * @cgrp: target cgroup
1011 * @subsys_mask: mask of the subsystem ids whose files should be removed
1013 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
1015 struct cgroup_subsys *ss;
1018 for_each_subsys(ss, i) {
1019 struct cftype_set *set;
1021 if (!test_bit(i, &subsys_mask))
1023 list_for_each_entry(set, &ss->cftsets, node)
1024 cgroup_addrm_files(cgrp, set->cfts, false);
1028 static int rebind_subsystems(struct cgroupfs_root *root,
1029 unsigned long added_mask, unsigned removed_mask)
1031 struct cgroup *cgrp = &root->top_cgroup;
1032 struct cgroup_subsys *ss;
1035 lockdep_assert_held(&cgroup_tree_mutex);
1036 lockdep_assert_held(&cgroup_mutex);
1038 /* Check that any added subsystems are currently free */
1039 for_each_subsys(ss, i)
1040 if ((added_mask & (1 << i)) && ss->root != &cgroup_dummy_root)
1043 ret = cgroup_populate_dir(cgrp, added_mask);
1048 * Nothing can fail from this point on. Remove files for the
1049 * removed subsystems and rebind each subsystem.
1051 mutex_unlock(&cgroup_mutex);
1052 cgroup_clear_dir(cgrp, removed_mask);
1053 mutex_lock(&cgroup_mutex);
1055 for_each_subsys(ss, i) {
1056 unsigned long bit = 1UL << i;
1058 if (bit & added_mask) {
1059 /* We're binding this subsystem to this hierarchy */
1060 BUG_ON(cgroup_css(cgrp, ss));
1061 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
1062 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
1064 rcu_assign_pointer(cgrp->subsys[i],
1065 cgroup_css(cgroup_dummy_top, ss));
1066 cgroup_css(cgrp, ss)->cgroup = cgrp;
1070 ss->bind(cgroup_css(cgrp, ss));
1072 /* refcount was already taken, and we're keeping it */
1073 root->subsys_mask |= bit;
1074 } else if (bit & removed_mask) {
1075 /* We're removing this subsystem */
1076 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
1077 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
1080 ss->bind(cgroup_css(cgroup_dummy_top, ss));
1082 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
1083 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1085 cgroup_subsys[i]->root = &cgroup_dummy_root;
1086 root->subsys_mask &= ~bit;
1091 * Mark @root has finished binding subsystems. @root->subsys_mask
1092 * now matches the bound subsystems.
1094 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1095 kernfs_activate(cgrp->kn);
1100 static int cgroup_show_options(struct seq_file *seq,
1101 struct kernfs_root *kf_root)
1103 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1104 struct cgroup_subsys *ss;
1107 for_each_subsys(ss, ssid)
1108 if (root->subsys_mask & (1 << ssid))
1109 seq_printf(seq, ",%s", ss->name);
1110 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1111 seq_puts(seq, ",sane_behavior");
1112 if (root->flags & CGRP_ROOT_NOPREFIX)
1113 seq_puts(seq, ",noprefix");
1114 if (root->flags & CGRP_ROOT_XATTR)
1115 seq_puts(seq, ",xattr");
1117 spin_lock(&release_agent_path_lock);
1118 if (strlen(root->release_agent_path))
1119 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1120 spin_unlock(&release_agent_path_lock);
1122 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1123 seq_puts(seq, ",clone_children");
1124 if (strlen(root->name))
1125 seq_printf(seq, ",name=%s", root->name);
1129 struct cgroup_sb_opts {
1130 unsigned long subsys_mask;
1131 unsigned long flags;
1132 char *release_agent;
1133 bool cpuset_clone_children;
1135 /* User explicitly requested empty subsystem */
1140 * Convert a hierarchy specifier into a bitmask of subsystems and
1141 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1142 * array. This function takes refcounts on subsystems to be used, unless it
1143 * returns error, in which case no refcounts are taken.
1145 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1147 char *token, *o = data;
1148 bool all_ss = false, one_ss = false;
1149 unsigned long mask = (unsigned long)-1;
1150 struct cgroup_subsys *ss;
1153 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1155 #ifdef CONFIG_CPUSETS
1156 mask = ~(1UL << cpuset_cgrp_id);
1159 memset(opts, 0, sizeof(*opts));
1161 while ((token = strsep(&o, ",")) != NULL) {
1164 if (!strcmp(token, "none")) {
1165 /* Explicitly have no subsystems */
1169 if (!strcmp(token, "all")) {
1170 /* Mutually exclusive option 'all' + subsystem name */
1176 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1177 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1180 if (!strcmp(token, "noprefix")) {
1181 opts->flags |= CGRP_ROOT_NOPREFIX;
1184 if (!strcmp(token, "clone_children")) {
1185 opts->cpuset_clone_children = true;
1188 if (!strcmp(token, "xattr")) {
1189 opts->flags |= CGRP_ROOT_XATTR;
1192 if (!strncmp(token, "release_agent=", 14)) {
1193 /* Specifying two release agents is forbidden */
1194 if (opts->release_agent)
1196 opts->release_agent =
1197 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1198 if (!opts->release_agent)
1202 if (!strncmp(token, "name=", 5)) {
1203 const char *name = token + 5;
1204 /* Can't specify an empty name */
1207 /* Must match [\w.-]+ */
1208 for (i = 0; i < strlen(name); i++) {
1212 if ((c == '.') || (c == '-') || (c == '_'))
1216 /* Specifying two names is forbidden */
1219 opts->name = kstrndup(name,
1220 MAX_CGROUP_ROOT_NAMELEN - 1,
1228 for_each_subsys(ss, i) {
1229 if (strcmp(token, ss->name))
1234 /* Mutually exclusive option 'all' + subsystem name */
1237 set_bit(i, &opts->subsys_mask);
1242 if (i == CGROUP_SUBSYS_COUNT)
1247 * If the 'all' option was specified select all the subsystems,
1248 * otherwise if 'none', 'name=' and a subsystem name options
1249 * were not specified, let's default to 'all'
1251 if (all_ss || (!one_ss && !opts->none && !opts->name))
1252 for_each_subsys(ss, i)
1254 set_bit(i, &opts->subsys_mask);
1256 /* Consistency checks */
1258 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1259 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1261 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1262 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1266 if (opts->cpuset_clone_children) {
1267 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1273 * Option noprefix was introduced just for backward compatibility
1274 * with the old cpuset, so we allow noprefix only if mounting just
1275 * the cpuset subsystem.
1277 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1281 /* Can't specify "none" and some subsystems */
1282 if (opts->subsys_mask && opts->none)
1286 * We either have to specify by name or by subsystems. (So all
1287 * empty hierarchies must have a name).
1289 if (!opts->subsys_mask && !opts->name)
1295 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1298 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1299 struct cgroup_sb_opts opts;
1300 unsigned long added_mask, removed_mask;
1302 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1303 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1307 mutex_lock(&cgroup_tree_mutex);
1308 mutex_lock(&cgroup_mutex);
1310 /* See what subsystems are wanted */
1311 ret = parse_cgroupfs_options(data, &opts);
1315 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1316 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1317 task_tgid_nr(current), current->comm);
1319 added_mask = opts.subsys_mask & ~root->subsys_mask;
1320 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1322 /* Don't allow flags or name to change at remount */
1323 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1324 (opts.name && strcmp(opts.name, root->name))) {
1325 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1326 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1327 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1332 /* remounting is not allowed for populated hierarchies */
1333 if (root->number_of_cgroups > 1) {
1338 ret = rebind_subsystems(root, added_mask, removed_mask);
1342 if (opts.release_agent) {
1343 spin_lock(&release_agent_path_lock);
1344 strcpy(root->release_agent_path, opts.release_agent);
1345 spin_unlock(&release_agent_path_lock);
1348 kfree(opts.release_agent);
1350 mutex_unlock(&cgroup_mutex);
1351 mutex_unlock(&cgroup_tree_mutex);
1355 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1357 atomic_set(&cgrp->refcnt, 1);
1358 INIT_LIST_HEAD(&cgrp->sibling);
1359 INIT_LIST_HEAD(&cgrp->children);
1360 INIT_LIST_HEAD(&cgrp->cset_links);
1361 INIT_LIST_HEAD(&cgrp->release_list);
1362 INIT_LIST_HEAD(&cgrp->pidlists);
1363 mutex_init(&cgrp->pidlist_mutex);
1364 cgrp->dummy_css.cgroup = cgrp;
1367 static void init_cgroup_root(struct cgroupfs_root *root)
1369 struct cgroup *cgrp = &root->top_cgroup;
1371 atomic_set(&root->refcnt, 1);
1372 INIT_LIST_HEAD(&root->root_list);
1373 root->number_of_cgroups = 1;
1375 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1376 init_cgroup_housekeeping(cgrp);
1377 idr_init(&root->cgroup_idr);
1380 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1382 struct cgroupfs_root *root;
1384 if (!opts->subsys_mask && !opts->none)
1385 return ERR_PTR(-EINVAL);
1387 root = kzalloc(sizeof(*root), GFP_KERNEL);
1389 return ERR_PTR(-ENOMEM);
1391 init_cgroup_root(root);
1394 * We need to set @root->subsys_mask now so that @root can be
1395 * matched by cgroup_test_super() before it finishes
1396 * initialization; otherwise, competing mounts with the same
1397 * options may try to bind the same subsystems instead of waiting
1398 * for the first one leading to unexpected mount errors.
1399 * SUBSYS_BOUND will be set once actual binding is complete.
1401 root->subsys_mask = opts->subsys_mask;
1402 root->flags = opts->flags;
1403 if (opts->release_agent)
1404 strcpy(root->release_agent_path, opts->release_agent);
1406 strcpy(root->name, opts->name);
1407 if (opts->cpuset_clone_children)
1408 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1412 static int cgroup_setup_root(struct cgroupfs_root *root)
1414 LIST_HEAD(tmp_links);
1415 struct cgroup *root_cgrp = &root->top_cgroup;
1416 struct css_set *cset;
1419 lockdep_assert_held(&cgroup_tree_mutex);
1420 lockdep_assert_held(&cgroup_mutex);
1422 ret = idr_alloc(&root->cgroup_idr, root_cgrp, 0, 1, GFP_KERNEL);
1425 root_cgrp->id = ret;
1428 * We're accessing css_set_count without locking css_set_lock here,
1429 * but that's OK - it can only be increased by someone holding
1430 * cgroup_lock, and that's us. The worst that can happen is that we
1431 * have some link structures left over
1433 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1437 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1438 ret = cgroup_init_root_id(root, 2, 0);
1442 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1443 KERNFS_ROOT_CREATE_DEACTIVATED,
1445 if (IS_ERR(root->kf_root)) {
1446 ret = PTR_ERR(root->kf_root);
1449 root_cgrp->kn = root->kf_root->kn;
1451 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1455 ret = rebind_subsystems(root, root->subsys_mask, 0);
1460 * There must be no failure case after here, since rebinding takes
1461 * care of subsystems' refcounts, which are explicitly dropped in
1462 * the failure exit path.
1464 list_add(&root->root_list, &cgroup_roots);
1465 cgroup_root_count++;
1468 * Link the top cgroup in this hierarchy into all the css_set
1471 write_lock(&css_set_lock);
1472 hash_for_each(css_set_table, i, cset, hlist)
1473 link_css_set(&tmp_links, cset, root_cgrp);
1474 write_unlock(&css_set_lock);
1476 BUG_ON(!list_empty(&root_cgrp->children));
1477 BUG_ON(root->number_of_cgroups != 1);
1479 kernfs_activate(root_cgrp->kn);
1484 kernfs_destroy_root(root->kf_root);
1485 root->kf_root = NULL;
1487 cgroup_exit_root_id(root);
1489 free_cgrp_cset_links(&tmp_links);
1493 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1494 int flags, const char *unused_dev_name,
1497 struct cgroupfs_root *root;
1498 struct cgroup_sb_opts opts;
1499 struct dentry *dentry;
1502 mutex_lock(&cgroup_tree_mutex);
1503 mutex_lock(&cgroup_mutex);
1505 /* First find the desired set of subsystems */
1506 ret = parse_cgroupfs_options(data, &opts);
1510 /* look for a matching existing root */
1511 for_each_active_root(root) {
1512 bool name_match = false;
1515 * If we asked for a name then it must match. Also, if
1516 * name matches but sybsys_mask doesn't, we should fail.
1517 * Remember whether name matched.
1520 if (strcmp(opts.name, root->name))
1526 * If we asked for subsystems (or explicitly for no
1527 * subsystems) then they must match.
1529 if ((opts.subsys_mask || opts.none) &&
1530 (opts.subsys_mask != root->subsys_mask)) {
1537 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1538 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1539 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1543 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1547 cgroup_get_root(root);
1551 /* no such thing, create a new one */
1552 root = cgroup_root_from_opts(&opts);
1554 ret = PTR_ERR(root);
1558 ret = cgroup_setup_root(root);
1560 cgroup_free_root(root);
1563 mutex_unlock(&cgroup_mutex);
1564 mutex_unlock(&cgroup_tree_mutex);
1566 kfree(opts.release_agent);
1570 return ERR_PTR(ret);
1572 dentry = kernfs_mount(fs_type, flags, root->kf_root);
1574 cgroup_put_root(root);
1578 static void cgroup_kill_sb(struct super_block *sb)
1580 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1581 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1583 cgroup_put_root(root);
1587 static struct file_system_type cgroup_fs_type = {
1589 .mount = cgroup_mount,
1590 .kill_sb = cgroup_kill_sb,
1593 static struct kobject *cgroup_kobj;
1596 * cgroup_path - generate the path of a cgroup
1597 * @cgrp: the cgroup in question
1598 * @buf: the buffer to write the path into
1599 * @buflen: the length of the buffer
1601 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1603 * We can't generate cgroup path using dentry->d_name, as accessing
1604 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1605 * inode's i_mutex, while on the other hand cgroup_path() can be called
1606 * with some irq-safe spinlocks held.
1608 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1610 int ret = -ENAMETOOLONG;
1613 if (!cgrp->parent) {
1614 if (strlcpy(buf, "/", buflen) >= buflen)
1615 return -ENAMETOOLONG;
1619 start = buf + buflen - 1;
1624 const char *name = cgroup_name(cgrp);
1628 if ((start -= len) < buf)
1630 memcpy(start, name, len);
1636 cgrp = cgrp->parent;
1637 } while (cgrp->parent);
1639 memmove(buf, start, buf + buflen - start);
1644 EXPORT_SYMBOL_GPL(cgroup_path);
1647 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1648 * @task: target task
1649 * @buf: the buffer to write the path into
1650 * @buflen: the length of the buffer
1652 * Determine @task's cgroup on the first (the one with the lowest non-zero
1653 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1654 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1655 * cgroup controller callbacks.
1657 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1659 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1661 struct cgroupfs_root *root;
1662 struct cgroup *cgrp;
1663 int hierarchy_id = 1, ret = 0;
1666 return -ENAMETOOLONG;
1668 mutex_lock(&cgroup_mutex);
1670 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1673 cgrp = task_cgroup_from_root(task, root);
1674 ret = cgroup_path(cgrp, buf, buflen);
1676 /* if no hierarchy exists, everyone is in "/" */
1677 memcpy(buf, "/", 2);
1680 mutex_unlock(&cgroup_mutex);
1683 EXPORT_SYMBOL_GPL(task_cgroup_path);
1686 * Control Group taskset
1688 struct task_and_cgroup {
1689 struct task_struct *task;
1690 struct cgroup *cgrp;
1691 struct css_set *cset;
1694 struct cgroup_taskset {
1695 struct task_and_cgroup single;
1696 struct flex_array *tc_array;
1699 struct cgroup *cur_cgrp;
1703 * cgroup_taskset_first - reset taskset and return the first task
1704 * @tset: taskset of interest
1706 * @tset iteration is initialized and the first task is returned.
1708 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1710 if (tset->tc_array) {
1712 return cgroup_taskset_next(tset);
1714 tset->cur_cgrp = tset->single.cgrp;
1715 return tset->single.task;
1718 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1721 * cgroup_taskset_next - iterate to the next task in taskset
1722 * @tset: taskset of interest
1724 * Return the next task in @tset. Iteration must have been initialized
1725 * with cgroup_taskset_first().
1727 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1729 struct task_and_cgroup *tc;
1731 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1734 tc = flex_array_get(tset->tc_array, tset->idx++);
1735 tset->cur_cgrp = tc->cgrp;
1738 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1741 * cgroup_taskset_cur_css - return the matching css for the current task
1742 * @tset: taskset of interest
1743 * @subsys_id: the ID of the target subsystem
1745 * Return the css for the current (last returned) task of @tset for
1746 * subsystem specified by @subsys_id. This function must be preceded by
1747 * either cgroup_taskset_first() or cgroup_taskset_next().
1749 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1752 return cgroup_css(tset->cur_cgrp, cgroup_subsys[subsys_id]);
1754 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1757 * cgroup_taskset_size - return the number of tasks in taskset
1758 * @tset: taskset of interest
1760 int cgroup_taskset_size(struct cgroup_taskset *tset)
1762 return tset->tc_array ? tset->tc_array_len : 1;
1764 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1768 * cgroup_task_migrate - move a task from one cgroup to another.
1770 * Must be called with cgroup_mutex and threadgroup locked.
1772 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1773 struct task_struct *tsk,
1774 struct css_set *new_cset)
1776 struct css_set *old_cset;
1779 * We are synchronized through threadgroup_lock() against PF_EXITING
1780 * setting such that we can't race against cgroup_exit() changing the
1781 * css_set to init_css_set and dropping the old one.
1783 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1784 old_cset = task_css_set(tsk);
1787 rcu_assign_pointer(tsk->cgroups, new_cset);
1790 /* Update the css_set linked lists if we're using them */
1791 write_lock(&css_set_lock);
1792 if (!list_empty(&tsk->cg_list))
1793 list_move(&tsk->cg_list, &new_cset->tasks);
1794 write_unlock(&css_set_lock);
1797 * We just gained a reference on old_cset by taking it from the
1798 * task. As trading it for new_cset is protected by cgroup_mutex,
1799 * we're safe to drop it here; it will be freed under RCU.
1801 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1802 put_css_set(old_cset);
1806 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1807 * @cgrp: the cgroup to attach to
1808 * @tsk: the task or the leader of the threadgroup to be attached
1809 * @threadgroup: attach the whole threadgroup?
1811 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1812 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1814 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1817 int retval, i, group_size;
1818 struct cgroupfs_root *root = cgrp->root;
1819 struct cgroup_subsys_state *css, *failed_css = NULL;
1820 /* threadgroup list cursor and array */
1821 struct task_struct *leader = tsk;
1822 struct task_and_cgroup *tc;
1823 struct flex_array *group;
1824 struct cgroup_taskset tset = { };
1827 * step 0: in order to do expensive, possibly blocking operations for
1828 * every thread, we cannot iterate the thread group list, since it needs
1829 * rcu or tasklist locked. instead, build an array of all threads in the
1830 * group - group_rwsem prevents new threads from appearing, and if
1831 * threads exit, this will just be an over-estimate.
1834 group_size = get_nr_threads(tsk);
1837 /* flex_array supports very large thread-groups better than kmalloc. */
1838 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1841 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1842 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1844 goto out_free_group_list;
1848 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1849 * already PF_EXITING could be freed from underneath us unless we
1850 * take an rcu_read_lock.
1854 struct task_and_cgroup ent;
1856 /* @tsk either already exited or can't exit until the end */
1857 if (tsk->flags & PF_EXITING)
1860 /* as per above, nr_threads may decrease, but not increase. */
1861 BUG_ON(i >= group_size);
1863 ent.cgrp = task_cgroup_from_root(tsk, root);
1864 /* nothing to do if this task is already in the cgroup */
1865 if (ent.cgrp == cgrp)
1868 * saying GFP_ATOMIC has no effect here because we did prealloc
1869 * earlier, but it's good form to communicate our expectations.
1871 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
1872 BUG_ON(retval != 0);
1877 } while_each_thread(leader, tsk);
1879 /* remember the number of threads in the array for later. */
1881 tset.tc_array = group;
1882 tset.tc_array_len = group_size;
1884 /* methods shouldn't be called if no task is actually migrating */
1887 goto out_free_group_list;
1890 * step 1: check that we can legitimately attach to the cgroup.
1892 for_each_css(css, i, cgrp) {
1893 if (css->ss->can_attach) {
1894 retval = css->ss->can_attach(css, &tset);
1897 goto out_cancel_attach;
1903 * step 2: make sure css_sets exist for all threads to be migrated.
1904 * we use find_css_set, which allocates a new one if necessary.
1906 for (i = 0; i < group_size; i++) {
1907 struct css_set *old_cset;
1909 tc = flex_array_get(group, i);
1910 old_cset = task_css_set(tc->task);
1911 tc->cset = find_css_set(old_cset, cgrp);
1914 goto out_put_css_set_refs;
1919 * step 3: now that we're guaranteed success wrt the css_sets,
1920 * proceed to move all tasks to the new cgroup. There are no
1921 * failure cases after here, so this is the commit point.
1923 for (i = 0; i < group_size; i++) {
1924 tc = flex_array_get(group, i);
1925 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
1927 /* nothing is sensitive to fork() after this point. */
1930 * step 4: do subsystem attach callbacks.
1932 for_each_css(css, i, cgrp)
1933 if (css->ss->attach)
1934 css->ss->attach(css, &tset);
1937 * step 5: success! and cleanup
1940 out_put_css_set_refs:
1942 for (i = 0; i < group_size; i++) {
1943 tc = flex_array_get(group, i);
1946 put_css_set(tc->cset);
1951 for_each_css(css, i, cgrp) {
1952 if (css == failed_css)
1954 if (css->ss->cancel_attach)
1955 css->ss->cancel_attach(css, &tset);
1958 out_free_group_list:
1959 flex_array_free(group);
1964 * Find the task_struct of the task to attach by vpid and pass it along to the
1965 * function to attach either it or all tasks in its threadgroup. Will lock
1966 * cgroup_mutex and threadgroup; may take task_lock of task.
1968 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
1970 struct task_struct *tsk;
1971 const struct cred *cred = current_cred(), *tcred;
1974 if (!cgroup_lock_live_group(cgrp))
1980 tsk = find_task_by_vpid(pid);
1984 goto out_unlock_cgroup;
1987 * even if we're attaching all tasks in the thread group, we
1988 * only need to check permissions on one of them.
1990 tcred = __task_cred(tsk);
1991 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
1992 !uid_eq(cred->euid, tcred->uid) &&
1993 !uid_eq(cred->euid, tcred->suid)) {
1996 goto out_unlock_cgroup;
2002 tsk = tsk->group_leader;
2005 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2006 * trapped in a cpuset, or RT worker may be born in a cgroup
2007 * with no rt_runtime allocated. Just say no.
2009 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2012 goto out_unlock_cgroup;
2015 get_task_struct(tsk);
2018 threadgroup_lock(tsk);
2020 if (!thread_group_leader(tsk)) {
2022 * a race with de_thread from another thread's exec()
2023 * may strip us of our leadership, if this happens,
2024 * there is no choice but to throw this task away and
2025 * try again; this is
2026 * "double-double-toil-and-trouble-check locking".
2028 threadgroup_unlock(tsk);
2029 put_task_struct(tsk);
2030 goto retry_find_task;
2034 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2036 threadgroup_unlock(tsk);
2038 put_task_struct(tsk);
2040 mutex_unlock(&cgroup_mutex);
2045 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2046 * @from: attach to all cgroups of a given task
2047 * @tsk: the task to be attached
2049 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2051 struct cgroupfs_root *root;
2054 mutex_lock(&cgroup_mutex);
2055 for_each_active_root(root) {
2056 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2058 retval = cgroup_attach_task(from_cgrp, tsk, false);
2062 mutex_unlock(&cgroup_mutex);
2066 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2068 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2069 struct cftype *cft, u64 pid)
2071 return attach_task_by_pid(css->cgroup, pid, false);
2074 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2075 struct cftype *cft, u64 tgid)
2077 return attach_task_by_pid(css->cgroup, tgid, true);
2080 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2081 struct cftype *cft, const char *buffer)
2083 struct cgroupfs_root *root = css->cgroup->root;
2085 BUILD_BUG_ON(sizeof(root->release_agent_path) < PATH_MAX);
2086 if (!cgroup_lock_live_group(css->cgroup))
2088 spin_lock(&release_agent_path_lock);
2089 strlcpy(root->release_agent_path, buffer,
2090 sizeof(root->release_agent_path));
2091 spin_unlock(&release_agent_path_lock);
2092 mutex_unlock(&cgroup_mutex);
2096 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2098 struct cgroup *cgrp = seq_css(seq)->cgroup;
2100 if (!cgroup_lock_live_group(cgrp))
2102 seq_puts(seq, cgrp->root->release_agent_path);
2103 seq_putc(seq, '\n');
2104 mutex_unlock(&cgroup_mutex);
2108 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2110 struct cgroup *cgrp = seq_css(seq)->cgroup;
2112 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2116 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2117 size_t nbytes, loff_t off)
2119 struct cgroup *cgrp = of->kn->parent->priv;
2120 struct cftype *cft = of->kn->priv;
2121 struct cgroup_subsys_state *css;
2125 * kernfs guarantees that a file isn't deleted with operations in
2126 * flight, which means that the matching css is and stays alive and
2127 * doesn't need to be pinned. The RCU locking is not necessary
2128 * either. It's just for the convenience of using cgroup_css().
2131 css = cgroup_css(cgrp, cft->ss);
2134 if (cft->write_string) {
2135 ret = cft->write_string(css, cft, strstrip(buf));
2136 } else if (cft->write_u64) {
2137 unsigned long long v;
2138 ret = kstrtoull(buf, 0, &v);
2140 ret = cft->write_u64(css, cft, v);
2141 } else if (cft->write_s64) {
2143 ret = kstrtoll(buf, 0, &v);
2145 ret = cft->write_s64(css, cft, v);
2146 } else if (cft->trigger) {
2147 ret = cft->trigger(css, (unsigned int)cft->private);
2152 return ret ?: nbytes;
2155 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2157 return seq_cft(seq)->seq_start(seq, ppos);
2160 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2162 return seq_cft(seq)->seq_next(seq, v, ppos);
2165 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2167 seq_cft(seq)->seq_stop(seq, v);
2170 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2172 struct cftype *cft = seq_cft(m);
2173 struct cgroup_subsys_state *css = seq_css(m);
2176 return cft->seq_show(m, arg);
2179 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2180 else if (cft->read_s64)
2181 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2187 static struct kernfs_ops cgroup_kf_single_ops = {
2188 .atomic_write_len = PAGE_SIZE,
2189 .write = cgroup_file_write,
2190 .seq_show = cgroup_seqfile_show,
2193 static struct kernfs_ops cgroup_kf_ops = {
2194 .atomic_write_len = PAGE_SIZE,
2195 .write = cgroup_file_write,
2196 .seq_start = cgroup_seqfile_start,
2197 .seq_next = cgroup_seqfile_next,
2198 .seq_stop = cgroup_seqfile_stop,
2199 .seq_show = cgroup_seqfile_show,
2203 * cgroup_rename - Only allow simple rename of directories in place.
2205 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2206 const char *new_name_str)
2208 struct cgroup *cgrp = kn->priv;
2209 struct cgroup_name *name, *old_name;
2212 if (kernfs_type(kn) != KERNFS_DIR)
2214 if (kn->parent != new_parent)
2218 * This isn't a proper migration and its usefulness is very
2219 * limited. Disallow if sane_behavior.
2221 if (cgroup_sane_behavior(cgrp))
2224 name = cgroup_alloc_name(new_name_str);
2228 mutex_lock(&cgroup_tree_mutex);
2229 mutex_lock(&cgroup_mutex);
2231 ret = kernfs_rename(kn, new_parent, new_name_str);
2233 old_name = rcu_dereference_protected(cgrp->name, true);
2234 rcu_assign_pointer(cgrp->name, name);
2239 mutex_unlock(&cgroup_mutex);
2240 mutex_unlock(&cgroup_tree_mutex);
2242 kfree_rcu(old_name, rcu_head);
2246 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2248 char name[CGROUP_FILE_NAME_MAX];
2249 struct kernfs_node *kn;
2250 struct lock_class_key *key = NULL;
2252 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2253 key = &cft->lockdep_key;
2255 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2256 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2264 * cgroup_addrm_files - add or remove files to a cgroup directory
2265 * @cgrp: the target cgroup
2266 * @cfts: array of cftypes to be added
2267 * @is_add: whether to add or remove
2269 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2270 * For removals, this function never fails. If addition fails, this
2271 * function doesn't remove files already added. The caller is responsible
2274 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2280 lockdep_assert_held(&cgroup_tree_mutex);
2282 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2283 /* does cft->flags tell us to skip this file on @cgrp? */
2284 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2286 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2288 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2292 ret = cgroup_add_file(cgrp, cft);
2294 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2299 cgroup_rm_file(cgrp, cft);
2305 static void cgroup_cfts_prepare(void)
2306 __acquires(&cgroup_mutex)
2309 * Thanks to the entanglement with vfs inode locking, we can't walk
2310 * the existing cgroups under cgroup_mutex and create files.
2311 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2312 * lock before calling cgroup_addrm_files().
2314 mutex_lock(&cgroup_tree_mutex);
2315 mutex_lock(&cgroup_mutex);
2318 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2319 __releases(&cgroup_mutex)
2322 struct cgroup_subsys *ss = cfts[0].ss;
2323 struct cgroup *root = &ss->root->top_cgroup;
2324 struct cgroup *prev = NULL;
2325 struct cgroup_subsys_state *css;
2329 mutex_unlock(&cgroup_mutex);
2331 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2332 if (!cfts || ss->root == &cgroup_dummy_root) {
2333 mutex_unlock(&cgroup_tree_mutex);
2337 cgroup_get_root(ss->root);
2340 * All cgroups which are created after we drop cgroup_mutex will
2341 * have the updated set of files, so we only need to update the
2342 * cgroups created before the current @cgroup_serial_nr_next.
2344 update_before = cgroup_serial_nr_next;
2346 /* add/rm files for all cgroups created before */
2347 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2348 struct cgroup *cgrp = css->cgroup;
2350 if (cgroup_is_dead(cgrp))
2358 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp)) {
2359 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2361 kernfs_activate(cgrp->kn);
2366 mutex_unlock(&cgroup_tree_mutex);
2368 cgroup_put_root(ss->root);
2372 static void cgroup_exit_cftypes(struct cftype *cfts)
2376 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2377 /* free copy for custom atomic_write_len, see init_cftypes() */
2378 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2385 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2389 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2390 struct kernfs_ops *kf_ops;
2393 kf_ops = &cgroup_kf_ops;
2395 kf_ops = &cgroup_kf_single_ops;
2398 * Ugh... if @cft wants a custom max_write_len, we need to
2399 * make a copy of kf_ops to set its atomic_write_len.
2401 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2402 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
2404 cgroup_exit_cftypes(cfts);
2407 kf_ops->atomic_write_len = cft->max_write_len;
2410 cft->kf_ops = kf_ops;
2418 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2419 * @ss: target cgroup subsystem
2420 * @cfts: zero-length name terminated array of cftypes
2422 * Register @cfts to @ss. Files described by @cfts are created for all
2423 * existing cgroups to which @ss is attached and all future cgroups will
2424 * have them too. This function can be called anytime whether @ss is
2427 * Returns 0 on successful registration, -errno on failure. Note that this
2428 * function currently returns 0 as long as @cfts registration is successful
2429 * even if some file creation attempts on existing cgroups fail.
2431 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2433 struct cftype_set *set;
2436 set = kzalloc(sizeof(*set), GFP_KERNEL);
2440 ret = cgroup_init_cftypes(ss, cfts);
2444 cgroup_cfts_prepare();
2446 list_add_tail(&set->node, &ss->cftsets);
2447 ret = cgroup_cfts_commit(cfts, true);
2449 cgroup_rm_cftypes(cfts);
2452 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2455 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2456 * @cfts: zero-length name terminated array of cftypes
2458 * Unregister @cfts. Files described by @cfts are removed from all
2459 * existing cgroups and all future cgroups won't have them either. This
2460 * function can be called anytime whether @cfts' subsys is attached or not.
2462 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2465 int cgroup_rm_cftypes(struct cftype *cfts)
2467 struct cftype *found = NULL;
2468 struct cftype_set *set;
2470 if (!cfts || !cfts[0].ss)
2473 cgroup_cfts_prepare();
2475 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2476 if (set->cfts == cfts) {
2477 list_del(&set->node);
2484 cgroup_cfts_commit(found, false);
2485 cgroup_exit_cftypes(cfts);
2486 return found ? 0 : -ENOENT;
2490 * cgroup_task_count - count the number of tasks in a cgroup.
2491 * @cgrp: the cgroup in question
2493 * Return the number of tasks in the cgroup.
2495 int cgroup_task_count(const struct cgroup *cgrp)
2498 struct cgrp_cset_link *link;
2500 read_lock(&css_set_lock);
2501 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2502 count += atomic_read(&link->cset->refcount);
2503 read_unlock(&css_set_lock);
2508 * To reduce the fork() overhead for systems that are not actually using
2509 * their cgroups capability, we don't maintain the lists running through
2510 * each css_set to its tasks until we see the list actually used - in other
2511 * words after the first call to css_task_iter_start().
2513 static void cgroup_enable_task_cg_lists(void)
2515 struct task_struct *p, *g;
2516 write_lock(&css_set_lock);
2517 use_task_css_set_links = 1;
2519 * We need tasklist_lock because RCU is not safe against
2520 * while_each_thread(). Besides, a forking task that has passed
2521 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2522 * is not guaranteed to have its child immediately visible in the
2523 * tasklist if we walk through it with RCU.
2525 read_lock(&tasklist_lock);
2526 do_each_thread(g, p) {
2529 * We should check if the process is exiting, otherwise
2530 * it will race with cgroup_exit() in that the list
2531 * entry won't be deleted though the process has exited.
2533 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2534 list_add(&p->cg_list, &task_css_set(p)->tasks);
2536 } while_each_thread(g, p);
2537 read_unlock(&tasklist_lock);
2538 write_unlock(&css_set_lock);
2542 * css_next_child - find the next child of a given css
2543 * @pos_css: the current position (%NULL to initiate traversal)
2544 * @parent_css: css whose children to walk
2546 * This function returns the next child of @parent_css and should be called
2547 * under either cgroup_mutex or RCU read lock. The only requirement is
2548 * that @parent_css and @pos_css are accessible. The next sibling is
2549 * guaranteed to be returned regardless of their states.
2551 struct cgroup_subsys_state *
2552 css_next_child(struct cgroup_subsys_state *pos_css,
2553 struct cgroup_subsys_state *parent_css)
2555 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2556 struct cgroup *cgrp = parent_css->cgroup;
2557 struct cgroup *next;
2559 cgroup_assert_mutexes_or_rcu_locked();
2562 * @pos could already have been removed. Once a cgroup is removed,
2563 * its ->sibling.next is no longer updated when its next sibling
2564 * changes. As CGRP_DEAD assertion is serialized and happens
2565 * before the cgroup is taken off the ->sibling list, if we see it
2566 * unasserted, it's guaranteed that the next sibling hasn't
2567 * finished its grace period even if it's already removed, and thus
2568 * safe to dereference from this RCU critical section. If
2569 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2570 * to be visible as %true here.
2572 * If @pos is dead, its next pointer can't be dereferenced;
2573 * however, as each cgroup is given a monotonically increasing
2574 * unique serial number and always appended to the sibling list,
2575 * the next one can be found by walking the parent's children until
2576 * we see a cgroup with higher serial number than @pos's. While
2577 * this path can be slower, it's taken only when either the current
2578 * cgroup is removed or iteration and removal race.
2581 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2582 } else if (likely(!cgroup_is_dead(pos))) {
2583 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2585 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2586 if (next->serial_nr > pos->serial_nr)
2590 if (&next->sibling == &cgrp->children)
2593 return cgroup_css(next, parent_css->ss);
2595 EXPORT_SYMBOL_GPL(css_next_child);
2598 * css_next_descendant_pre - find the next descendant for pre-order walk
2599 * @pos: the current position (%NULL to initiate traversal)
2600 * @root: css whose descendants to walk
2602 * To be used by css_for_each_descendant_pre(). Find the next descendant
2603 * to visit for pre-order traversal of @root's descendants. @root is
2604 * included in the iteration and the first node to be visited.
2606 * While this function requires cgroup_mutex or RCU read locking, it
2607 * doesn't require the whole traversal to be contained in a single critical
2608 * section. This function will return the correct next descendant as long
2609 * as both @pos and @root are accessible and @pos is a descendant of @root.
2611 struct cgroup_subsys_state *
2612 css_next_descendant_pre(struct cgroup_subsys_state *pos,
2613 struct cgroup_subsys_state *root)
2615 struct cgroup_subsys_state *next;
2617 cgroup_assert_mutexes_or_rcu_locked();
2619 /* if first iteration, visit @root */
2623 /* visit the first child if exists */
2624 next = css_next_child(NULL, pos);
2628 /* no child, visit my or the closest ancestor's next sibling */
2629 while (pos != root) {
2630 next = css_next_child(pos, css_parent(pos));
2633 pos = css_parent(pos);
2638 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
2641 * css_rightmost_descendant - return the rightmost descendant of a css
2642 * @pos: css of interest
2644 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2645 * is returned. This can be used during pre-order traversal to skip
2648 * While this function requires cgroup_mutex or RCU read locking, it
2649 * doesn't require the whole traversal to be contained in a single critical
2650 * section. This function will return the correct rightmost descendant as
2651 * long as @pos is accessible.
2653 struct cgroup_subsys_state *
2654 css_rightmost_descendant(struct cgroup_subsys_state *pos)
2656 struct cgroup_subsys_state *last, *tmp;
2658 cgroup_assert_mutexes_or_rcu_locked();
2662 /* ->prev isn't RCU safe, walk ->next till the end */
2664 css_for_each_child(tmp, last)
2670 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
2672 static struct cgroup_subsys_state *
2673 css_leftmost_descendant(struct cgroup_subsys_state *pos)
2675 struct cgroup_subsys_state *last;
2679 pos = css_next_child(NULL, pos);
2686 * css_next_descendant_post - find the next descendant for post-order walk
2687 * @pos: the current position (%NULL to initiate traversal)
2688 * @root: css whose descendants to walk
2690 * To be used by css_for_each_descendant_post(). Find the next descendant
2691 * to visit for post-order traversal of @root's descendants. @root is
2692 * included in the iteration and the last node to be visited.
2694 * While this function requires cgroup_mutex or RCU read locking, it
2695 * doesn't require the whole traversal to be contained in a single critical
2696 * section. This function will return the correct next descendant as long
2697 * as both @pos and @cgroup are accessible and @pos is a descendant of
2700 struct cgroup_subsys_state *
2701 css_next_descendant_post(struct cgroup_subsys_state *pos,
2702 struct cgroup_subsys_state *root)
2704 struct cgroup_subsys_state *next;
2706 cgroup_assert_mutexes_or_rcu_locked();
2708 /* if first iteration, visit leftmost descendant which may be @root */
2710 return css_leftmost_descendant(root);
2712 /* if we visited @root, we're done */
2716 /* if there's an unvisited sibling, visit its leftmost descendant */
2717 next = css_next_child(pos, css_parent(pos));
2719 return css_leftmost_descendant(next);
2721 /* no sibling left, visit parent */
2722 return css_parent(pos);
2724 EXPORT_SYMBOL_GPL(css_next_descendant_post);
2727 * css_advance_task_iter - advance a task itererator to the next css_set
2728 * @it: the iterator to advance
2730 * Advance @it to the next css_set to walk.
2732 static void css_advance_task_iter(struct css_task_iter *it)
2734 struct list_head *l = it->cset_link;
2735 struct cgrp_cset_link *link;
2736 struct css_set *cset;
2738 /* Advance to the next non-empty css_set */
2741 if (l == &it->origin_css->cgroup->cset_links) {
2742 it->cset_link = NULL;
2745 link = list_entry(l, struct cgrp_cset_link, cset_link);
2747 } while (list_empty(&cset->tasks));
2749 it->task = cset->tasks.next;
2753 * css_task_iter_start - initiate task iteration
2754 * @css: the css to walk tasks of
2755 * @it: the task iterator to use
2757 * Initiate iteration through the tasks of @css. The caller can call
2758 * css_task_iter_next() to walk through the tasks until the function
2759 * returns NULL. On completion of iteration, css_task_iter_end() must be
2762 * Note that this function acquires a lock which is released when the
2763 * iteration finishes. The caller can't sleep while iteration is in
2766 void css_task_iter_start(struct cgroup_subsys_state *css,
2767 struct css_task_iter *it)
2768 __acquires(css_set_lock)
2771 * The first time anyone tries to iterate across a css, we need to
2772 * enable the list linking each css_set to its tasks, and fix up
2773 * all existing tasks.
2775 if (!use_task_css_set_links)
2776 cgroup_enable_task_cg_lists();
2778 read_lock(&css_set_lock);
2780 it->origin_css = css;
2781 it->cset_link = &css->cgroup->cset_links;
2783 css_advance_task_iter(it);
2787 * css_task_iter_next - return the next task for the iterator
2788 * @it: the task iterator being iterated
2790 * The "next" function for task iteration. @it should have been
2791 * initialized via css_task_iter_start(). Returns NULL when the iteration
2794 struct task_struct *css_task_iter_next(struct css_task_iter *it)
2796 struct task_struct *res;
2797 struct list_head *l = it->task;
2798 struct cgrp_cset_link *link;
2800 /* If the iterator cg is NULL, we have no tasks */
2803 res = list_entry(l, struct task_struct, cg_list);
2804 /* Advance iterator to find next entry */
2806 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
2807 if (l == &link->cset->tasks) {
2809 * We reached the end of this task list - move on to the
2810 * next cgrp_cset_link.
2812 css_advance_task_iter(it);
2820 * css_task_iter_end - finish task iteration
2821 * @it: the task iterator to finish
2823 * Finish task iteration started by css_task_iter_start().
2825 void css_task_iter_end(struct css_task_iter *it)
2826 __releases(css_set_lock)
2828 read_unlock(&css_set_lock);
2831 static inline int started_after_time(struct task_struct *t1,
2832 struct timespec *time,
2833 struct task_struct *t2)
2835 int start_diff = timespec_compare(&t1->start_time, time);
2836 if (start_diff > 0) {
2838 } else if (start_diff < 0) {
2842 * Arbitrarily, if two processes started at the same
2843 * time, we'll say that the lower pointer value
2844 * started first. Note that t2 may have exited by now
2845 * so this may not be a valid pointer any longer, but
2846 * that's fine - it still serves to distinguish
2847 * between two tasks started (effectively) simultaneously.
2854 * This function is a callback from heap_insert() and is used to order
2856 * In this case we order the heap in descending task start time.
2858 static inline int started_after(void *p1, void *p2)
2860 struct task_struct *t1 = p1;
2861 struct task_struct *t2 = p2;
2862 return started_after_time(t1, &t2->start_time, t2);
2866 * css_scan_tasks - iterate though all the tasks in a css
2867 * @css: the css to iterate tasks of
2868 * @test: optional test callback
2869 * @process: process callback
2870 * @data: data passed to @test and @process
2871 * @heap: optional pre-allocated heap used for task iteration
2873 * Iterate through all the tasks in @css, calling @test for each, and if it
2874 * returns %true, call @process for it also.
2876 * @test may be NULL, meaning always true (select all tasks), which
2877 * effectively duplicates css_task_iter_{start,next,end}() but does not
2878 * lock css_set_lock for the call to @process.
2880 * It is guaranteed that @process will act on every task that is a member
2881 * of @css for the duration of this call. This function may or may not
2882 * call @process for tasks that exit or move to a different css during the
2883 * call, or are forked or move into the css during the call.
2885 * Note that @test may be called with locks held, and may in some
2886 * situations be called multiple times for the same task, so it should be
2889 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
2890 * heap operations (and its "gt" member will be overwritten), else a
2891 * temporary heap will be used (allocation of which may cause this function
2894 int css_scan_tasks(struct cgroup_subsys_state *css,
2895 bool (*test)(struct task_struct *, void *),
2896 void (*process)(struct task_struct *, void *),
2897 void *data, struct ptr_heap *heap)
2900 struct css_task_iter it;
2901 struct task_struct *p, *dropped;
2902 /* Never dereference latest_task, since it's not refcounted */
2903 struct task_struct *latest_task = NULL;
2904 struct ptr_heap tmp_heap;
2905 struct timespec latest_time = { 0, 0 };
2908 /* The caller supplied our heap and pre-allocated its memory */
2909 heap->gt = &started_after;
2911 /* We need to allocate our own heap memory */
2913 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2915 /* cannot allocate the heap */
2921 * Scan tasks in the css, using the @test callback to determine
2922 * which are of interest, and invoking @process callback on the
2923 * ones which need an update. Since we don't want to hold any
2924 * locks during the task updates, gather tasks to be processed in a
2925 * heap structure. The heap is sorted by descending task start
2926 * time. If the statically-sized heap fills up, we overflow tasks
2927 * that started later, and in future iterations only consider tasks
2928 * that started after the latest task in the previous pass. This
2929 * guarantees forward progress and that we don't miss any tasks.
2932 css_task_iter_start(css, &it);
2933 while ((p = css_task_iter_next(&it))) {
2935 * Only affect tasks that qualify per the caller's callback,
2936 * if he provided one
2938 if (test && !test(p, data))
2941 * Only process tasks that started after the last task
2944 if (!started_after_time(p, &latest_time, latest_task))
2946 dropped = heap_insert(heap, p);
2947 if (dropped == NULL) {
2949 * The new task was inserted; the heap wasn't
2953 } else if (dropped != p) {
2955 * The new task was inserted, and pushed out a
2959 put_task_struct(dropped);
2962 * Else the new task was newer than anything already in
2963 * the heap and wasn't inserted
2966 css_task_iter_end(&it);
2969 for (i = 0; i < heap->size; i++) {
2970 struct task_struct *q = heap->ptrs[i];
2972 latest_time = q->start_time;
2975 /* Process the task per the caller's callback */
2980 * If we had to process any tasks at all, scan again
2981 * in case some of them were in the middle of forking
2982 * children that didn't get processed.
2983 * Not the most efficient way to do it, but it avoids
2984 * having to take callback_mutex in the fork path
2988 if (heap == &tmp_heap)
2989 heap_free(&tmp_heap);
2993 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
2995 struct cgroup *new_cgroup = data;
2997 mutex_lock(&cgroup_mutex);
2998 cgroup_attach_task(new_cgroup, task, false);
2999 mutex_unlock(&cgroup_mutex);
3003 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3004 * @to: cgroup to which the tasks will be moved
3005 * @from: cgroup in which the tasks currently reside
3007 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3009 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3014 * Stuff for reading the 'tasks'/'procs' files.
3016 * Reading this file can return large amounts of data if a cgroup has
3017 * *lots* of attached tasks. So it may need several calls to read(),
3018 * but we cannot guarantee that the information we produce is correct
3019 * unless we produce it entirely atomically.
3023 /* which pidlist file are we talking about? */
3024 enum cgroup_filetype {
3030 * A pidlist is a list of pids that virtually represents the contents of one
3031 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3032 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3035 struct cgroup_pidlist {
3037 * used to find which pidlist is wanted. doesn't change as long as
3038 * this particular list stays in the list.
3040 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3043 /* how many elements the above list has */
3045 /* each of these stored in a list by its cgroup */
3046 struct list_head links;
3047 /* pointer to the cgroup we belong to, for list removal purposes */
3048 struct cgroup *owner;
3049 /* for delayed destruction */
3050 struct delayed_work destroy_dwork;
3054 * The following two functions "fix" the issue where there are more pids
3055 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3056 * TODO: replace with a kernel-wide solution to this problem
3058 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3059 static void *pidlist_allocate(int count)
3061 if (PIDLIST_TOO_LARGE(count))
3062 return vmalloc(count * sizeof(pid_t));
3064 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3067 static void pidlist_free(void *p)
3069 if (is_vmalloc_addr(p))
3076 * Used to destroy all pidlists lingering waiting for destroy timer. None
3077 * should be left afterwards.
3079 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3081 struct cgroup_pidlist *l, *tmp_l;
3083 mutex_lock(&cgrp->pidlist_mutex);
3084 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3085 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3086 mutex_unlock(&cgrp->pidlist_mutex);
3088 flush_workqueue(cgroup_pidlist_destroy_wq);
3089 BUG_ON(!list_empty(&cgrp->pidlists));
3092 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3094 struct delayed_work *dwork = to_delayed_work(work);
3095 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3097 struct cgroup_pidlist *tofree = NULL;
3099 mutex_lock(&l->owner->pidlist_mutex);
3102 * Destroy iff we didn't get queued again. The state won't change
3103 * as destroy_dwork can only be queued while locked.
3105 if (!delayed_work_pending(dwork)) {
3106 list_del(&l->links);
3107 pidlist_free(l->list);
3108 put_pid_ns(l->key.ns);
3112 mutex_unlock(&l->owner->pidlist_mutex);
3117 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3118 * Returns the number of unique elements.
3120 static int pidlist_uniq(pid_t *list, int length)
3125 * we presume the 0th element is unique, so i starts at 1. trivial
3126 * edge cases first; no work needs to be done for either
3128 if (length == 0 || length == 1)
3130 /* src and dest walk down the list; dest counts unique elements */
3131 for (src = 1; src < length; src++) {
3132 /* find next unique element */
3133 while (list[src] == list[src-1]) {
3138 /* dest always points to where the next unique element goes */
3139 list[dest] = list[src];
3147 * The two pid files - task and cgroup.procs - guaranteed that the result
3148 * is sorted, which forced this whole pidlist fiasco. As pid order is
3149 * different per namespace, each namespace needs differently sorted list,
3150 * making it impossible to use, for example, single rbtree of member tasks
3151 * sorted by task pointer. As pidlists can be fairly large, allocating one
3152 * per open file is dangerous, so cgroup had to implement shared pool of
3153 * pidlists keyed by cgroup and namespace.
3155 * All this extra complexity was caused by the original implementation
3156 * committing to an entirely unnecessary property. In the long term, we
3157 * want to do away with it. Explicitly scramble sort order if
3158 * sane_behavior so that no such expectation exists in the new interface.
3160 * Scrambling is done by swapping every two consecutive bits, which is
3161 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3163 static pid_t pid_fry(pid_t pid)
3165 unsigned a = pid & 0x55555555;
3166 unsigned b = pid & 0xAAAAAAAA;
3168 return (a << 1) | (b >> 1);
3171 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3173 if (cgroup_sane_behavior(cgrp))
3174 return pid_fry(pid);
3179 static int cmppid(const void *a, const void *b)
3181 return *(pid_t *)a - *(pid_t *)b;
3184 static int fried_cmppid(const void *a, const void *b)
3186 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3189 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3190 enum cgroup_filetype type)
3192 struct cgroup_pidlist *l;
3193 /* don't need task_nsproxy() if we're looking at ourself */
3194 struct pid_namespace *ns = task_active_pid_ns(current);
3196 lockdep_assert_held(&cgrp->pidlist_mutex);
3198 list_for_each_entry(l, &cgrp->pidlists, links)
3199 if (l->key.type == type && l->key.ns == ns)
3205 * find the appropriate pidlist for our purpose (given procs vs tasks)
3206 * returns with the lock on that pidlist already held, and takes care
3207 * of the use count, or returns NULL with no locks held if we're out of
3210 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3211 enum cgroup_filetype type)
3213 struct cgroup_pidlist *l;
3215 lockdep_assert_held(&cgrp->pidlist_mutex);
3217 l = cgroup_pidlist_find(cgrp, type);
3221 /* entry not found; create a new one */
3222 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3226 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3228 /* don't need task_nsproxy() if we're looking at ourself */
3229 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3231 list_add(&l->links, &cgrp->pidlists);
3236 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3238 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3239 struct cgroup_pidlist **lp)
3243 int pid, n = 0; /* used for populating the array */
3244 struct css_task_iter it;
3245 struct task_struct *tsk;
3246 struct cgroup_pidlist *l;
3248 lockdep_assert_held(&cgrp->pidlist_mutex);
3251 * If cgroup gets more users after we read count, we won't have
3252 * enough space - tough. This race is indistinguishable to the
3253 * caller from the case that the additional cgroup users didn't
3254 * show up until sometime later on.
3256 length = cgroup_task_count(cgrp);
3257 array = pidlist_allocate(length);
3260 /* now, populate the array */
3261 css_task_iter_start(&cgrp->dummy_css, &it);
3262 while ((tsk = css_task_iter_next(&it))) {
3263 if (unlikely(n == length))
3265 /* get tgid or pid for procs or tasks file respectively */
3266 if (type == CGROUP_FILE_PROCS)
3267 pid = task_tgid_vnr(tsk);
3269 pid = task_pid_vnr(tsk);
3270 if (pid > 0) /* make sure to only use valid results */
3273 css_task_iter_end(&it);
3275 /* now sort & (if procs) strip out duplicates */
3276 if (cgroup_sane_behavior(cgrp))
3277 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3279 sort(array, length, sizeof(pid_t), cmppid, NULL);
3280 if (type == CGROUP_FILE_PROCS)
3281 length = pidlist_uniq(array, length);
3283 l = cgroup_pidlist_find_create(cgrp, type);
3285 mutex_unlock(&cgrp->pidlist_mutex);
3286 pidlist_free(array);
3290 /* store array, freeing old if necessary */
3291 pidlist_free(l->list);
3299 * cgroupstats_build - build and fill cgroupstats
3300 * @stats: cgroupstats to fill information into
3301 * @dentry: A dentry entry belonging to the cgroup for which stats have
3304 * Build and fill cgroupstats so that taskstats can export it to user
3307 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3309 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3310 struct cgroup *cgrp;
3311 struct css_task_iter it;
3312 struct task_struct *tsk;
3314 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3315 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3316 kernfs_type(kn) != KERNFS_DIR)
3320 * We aren't being called from kernfs and there's no guarantee on
3321 * @kn->priv's validity. For this and css_tryget_from_dir(),
3322 * @kn->priv is RCU safe. Let's do the RCU dancing.
3325 cgrp = rcu_dereference(kn->priv);
3331 css_task_iter_start(&cgrp->dummy_css, &it);
3332 while ((tsk = css_task_iter_next(&it))) {
3333 switch (tsk->state) {
3335 stats->nr_running++;
3337 case TASK_INTERRUPTIBLE:
3338 stats->nr_sleeping++;
3340 case TASK_UNINTERRUPTIBLE:
3341 stats->nr_uninterruptible++;
3344 stats->nr_stopped++;
3347 if (delayacct_is_task_waiting_on_io(tsk))
3348 stats->nr_io_wait++;
3352 css_task_iter_end(&it);
3360 * seq_file methods for the tasks/procs files. The seq_file position is the
3361 * next pid to display; the seq_file iterator is a pointer to the pid
3362 * in the cgroup->l->list array.
3365 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3368 * Initially we receive a position value that corresponds to
3369 * one more than the last pid shown (or 0 on the first call or
3370 * after a seek to the start). Use a binary-search to find the
3371 * next pid to display, if any
3373 struct kernfs_open_file *of = s->private;
3374 struct cgroup *cgrp = seq_css(s)->cgroup;
3375 struct cgroup_pidlist *l;
3376 enum cgroup_filetype type = seq_cft(s)->private;
3377 int index = 0, pid = *pos;
3380 mutex_lock(&cgrp->pidlist_mutex);
3383 * !NULL @of->priv indicates that this isn't the first start()
3384 * after open. If the matching pidlist is around, we can use that.
3385 * Look for it. Note that @of->priv can't be used directly. It
3386 * could already have been destroyed.
3389 of->priv = cgroup_pidlist_find(cgrp, type);
3392 * Either this is the first start() after open or the matching
3393 * pidlist has been destroyed inbetween. Create a new one.
3396 ret = pidlist_array_load(cgrp, type,
3397 (struct cgroup_pidlist **)&of->priv);
3399 return ERR_PTR(ret);
3404 int end = l->length;
3406 while (index < end) {
3407 int mid = (index + end) / 2;
3408 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3411 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3417 /* If we're off the end of the array, we're done */
3418 if (index >= l->length)
3420 /* Update the abstract position to be the actual pid that we found */
3421 iter = l->list + index;
3422 *pos = cgroup_pid_fry(cgrp, *iter);
3426 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3428 struct kernfs_open_file *of = s->private;
3429 struct cgroup_pidlist *l = of->priv;
3432 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3433 CGROUP_PIDLIST_DESTROY_DELAY);
3434 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3437 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3439 struct kernfs_open_file *of = s->private;
3440 struct cgroup_pidlist *l = of->priv;
3442 pid_t *end = l->list + l->length;
3444 * Advance to the next pid in the array. If this goes off the
3451 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3456 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3458 return seq_printf(s, "%d\n", *(int *)v);
3462 * seq_operations functions for iterating on pidlists through seq_file -
3463 * independent of whether it's tasks or procs
3465 static const struct seq_operations cgroup_pidlist_seq_operations = {
3466 .start = cgroup_pidlist_start,
3467 .stop = cgroup_pidlist_stop,
3468 .next = cgroup_pidlist_next,
3469 .show = cgroup_pidlist_show,
3472 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3475 return notify_on_release(css->cgroup);
3478 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3479 struct cftype *cft, u64 val)
3481 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3483 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3485 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3489 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3492 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3495 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3496 struct cftype *cft, u64 val)
3499 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3501 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3505 static struct cftype cgroup_base_files[] = {
3507 .name = "cgroup.procs",
3508 .seq_start = cgroup_pidlist_start,
3509 .seq_next = cgroup_pidlist_next,
3510 .seq_stop = cgroup_pidlist_stop,
3511 .seq_show = cgroup_pidlist_show,
3512 .private = CGROUP_FILE_PROCS,
3513 .write_u64 = cgroup_procs_write,
3514 .mode = S_IRUGO | S_IWUSR,
3517 .name = "cgroup.clone_children",
3518 .flags = CFTYPE_INSANE,
3519 .read_u64 = cgroup_clone_children_read,
3520 .write_u64 = cgroup_clone_children_write,
3523 .name = "cgroup.sane_behavior",
3524 .flags = CFTYPE_ONLY_ON_ROOT,
3525 .seq_show = cgroup_sane_behavior_show,
3529 * Historical crazy stuff. These don't have "cgroup." prefix and
3530 * don't exist if sane_behavior. If you're depending on these, be
3531 * prepared to be burned.
3535 .flags = CFTYPE_INSANE, /* use "procs" instead */
3536 .seq_start = cgroup_pidlist_start,
3537 .seq_next = cgroup_pidlist_next,
3538 .seq_stop = cgroup_pidlist_stop,
3539 .seq_show = cgroup_pidlist_show,
3540 .private = CGROUP_FILE_TASKS,
3541 .write_u64 = cgroup_tasks_write,
3542 .mode = S_IRUGO | S_IWUSR,
3545 .name = "notify_on_release",
3546 .flags = CFTYPE_INSANE,
3547 .read_u64 = cgroup_read_notify_on_release,
3548 .write_u64 = cgroup_write_notify_on_release,
3551 .name = "release_agent",
3552 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3553 .seq_show = cgroup_release_agent_show,
3554 .write_string = cgroup_release_agent_write,
3555 .max_write_len = PATH_MAX - 1,
3561 * cgroup_populate_dir - create subsys files in a cgroup directory
3562 * @cgrp: target cgroup
3563 * @subsys_mask: mask of the subsystem ids whose files should be added
3565 * On failure, no file is added.
3567 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3569 struct cgroup_subsys *ss;
3572 /* process cftsets of each subsystem */
3573 for_each_subsys(ss, i) {
3574 struct cftype_set *set;
3576 if (!test_bit(i, &subsys_mask))
3579 list_for_each_entry(set, &ss->cftsets, node) {
3580 ret = cgroup_addrm_files(cgrp, set->cfts, true);
3587 cgroup_clear_dir(cgrp, subsys_mask);
3592 * css destruction is four-stage process.
3594 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3595 * Implemented in kill_css().
3597 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3598 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3599 * by invoking offline_css(). After offlining, the base ref is put.
3600 * Implemented in css_killed_work_fn().
3602 * 3. When the percpu_ref reaches zero, the only possible remaining
3603 * accessors are inside RCU read sections. css_release() schedules the
3606 * 4. After the grace period, the css can be freed. Implemented in
3607 * css_free_work_fn().
3609 * It is actually hairier because both step 2 and 4 require process context
3610 * and thus involve punting to css->destroy_work adding two additional
3611 * steps to the already complex sequence.
3613 static void css_free_work_fn(struct work_struct *work)
3615 struct cgroup_subsys_state *css =
3616 container_of(work, struct cgroup_subsys_state, destroy_work);
3617 struct cgroup *cgrp = css->cgroup;
3620 css_put(css->parent);
3622 css->ss->css_free(css);
3626 static void css_free_rcu_fn(struct rcu_head *rcu_head)
3628 struct cgroup_subsys_state *css =
3629 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
3631 INIT_WORK(&css->destroy_work, css_free_work_fn);
3632 queue_work(cgroup_destroy_wq, &css->destroy_work);
3635 static void css_release(struct percpu_ref *ref)
3637 struct cgroup_subsys_state *css =
3638 container_of(ref, struct cgroup_subsys_state, refcnt);
3640 rcu_assign_pointer(css->cgroup->subsys[css->ss->id], NULL);
3641 call_rcu(&css->rcu_head, css_free_rcu_fn);
3644 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3645 struct cgroup *cgrp)
3652 css->parent = cgroup_css(cgrp->parent, ss);
3654 css->flags |= CSS_ROOT;
3656 BUG_ON(cgroup_css(cgrp, ss));
3659 /* invoke ->css_online() on a new CSS and mark it online if successful */
3660 static int online_css(struct cgroup_subsys_state *css)
3662 struct cgroup_subsys *ss = css->ss;
3665 lockdep_assert_held(&cgroup_tree_mutex);
3666 lockdep_assert_held(&cgroup_mutex);
3669 ret = ss->css_online(css);
3671 css->flags |= CSS_ONLINE;
3672 css->cgroup->nr_css++;
3673 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
3678 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
3679 static void offline_css(struct cgroup_subsys_state *css)
3681 struct cgroup_subsys *ss = css->ss;
3683 lockdep_assert_held(&cgroup_tree_mutex);
3684 lockdep_assert_held(&cgroup_mutex);
3686 if (!(css->flags & CSS_ONLINE))
3689 if (ss->css_offline)
3690 ss->css_offline(css);
3692 css->flags &= ~CSS_ONLINE;
3693 css->cgroup->nr_css--;
3694 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
3698 * create_css - create a cgroup_subsys_state
3699 * @cgrp: the cgroup new css will be associated with
3700 * @ss: the subsys of new css
3702 * Create a new css associated with @cgrp - @ss pair. On success, the new
3703 * css is online and installed in @cgrp with all interface files created.
3704 * Returns 0 on success, -errno on failure.
3706 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
3708 struct cgroup *parent = cgrp->parent;
3709 struct cgroup_subsys_state *css;
3712 lockdep_assert_held(&cgroup_mutex);
3714 css = ss->css_alloc(cgroup_css(parent, ss));
3716 return PTR_ERR(css);
3718 err = percpu_ref_init(&css->refcnt, css_release);
3722 init_css(css, ss, cgrp);
3724 err = cgroup_populate_dir(cgrp, 1 << ss->id);
3728 err = online_css(css);
3733 css_get(css->parent);
3735 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
3737 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",
3738 current->comm, current->pid, ss->name);
3739 if (!strcmp(ss->name, "memory"))
3740 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
3741 ss->warned_broken_hierarchy = true;
3747 percpu_ref_cancel_init(&css->refcnt);
3753 * cgroup_create - create a cgroup
3754 * @parent: cgroup that will be parent of the new cgroup
3755 * @name_str: name of the new cgroup
3756 * @mode: mode to set on new cgroup
3758 static long cgroup_create(struct cgroup *parent, const char *name_str,
3761 struct cgroup *cgrp;
3762 struct cgroup_name *name;
3763 struct cgroupfs_root *root = parent->root;
3765 struct cgroup_subsys *ss;
3766 struct kernfs_node *kn;
3768 /* allocate the cgroup and its ID, 0 is reserved for the root */
3769 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
3773 name = cgroup_alloc_name(name_str);
3778 rcu_assign_pointer(cgrp->name, name);
3780 mutex_lock(&cgroup_tree_mutex);
3783 * Only live parents can have children. Note that the liveliness
3784 * check isn't strictly necessary because cgroup_mkdir() and
3785 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
3786 * anyway so that locking is contained inside cgroup proper and we
3787 * don't get nasty surprises if we ever grow another caller.
3789 if (!cgroup_lock_live_group(parent)) {
3791 goto err_unlock_tree;
3795 * Temporarily set the pointer to NULL, so idr_find() won't return
3796 * a half-baked cgroup.
3798 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
3804 init_cgroup_housekeeping(cgrp);
3806 cgrp->parent = parent;
3807 cgrp->dummy_css.parent = &parent->dummy_css;
3808 cgrp->root = parent->root;
3810 if (notify_on_release(parent))
3811 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3813 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
3814 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3816 /* create the directory */
3817 kn = kernfs_create_dir(parent->kn, name->name, mode, cgrp);
3824 cgrp->serial_nr = cgroup_serial_nr_next++;
3826 /* allocation complete, commit to creation */
3827 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
3828 root->number_of_cgroups++;
3831 * Grab a reference on the root and parent so that they don't get
3832 * deleted while there are child cgroups.
3834 cgroup_get_root(root);
3838 * @cgrp is now fully operational. If something fails after this
3839 * point, it'll be released via the normal destruction path.
3841 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
3843 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
3847 /* let's create and online css's */
3848 for_each_subsys(ss, ssid) {
3849 if (root->subsys_mask & (1 << ssid)) {
3850 err = create_css(cgrp, ss);
3856 kernfs_activate(kn);
3858 mutex_unlock(&cgroup_mutex);
3859 mutex_unlock(&cgroup_tree_mutex);
3864 idr_remove(&root->cgroup_idr, cgrp->id);
3866 mutex_unlock(&cgroup_mutex);
3868 mutex_unlock(&cgroup_tree_mutex);
3869 kfree(rcu_dereference_raw(cgrp->name));
3875 cgroup_destroy_locked(cgrp);
3876 mutex_unlock(&cgroup_mutex);
3877 mutex_unlock(&cgroup_tree_mutex);
3881 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
3884 struct cgroup *parent = parent_kn->priv;
3886 return cgroup_create(parent, name, mode);
3890 * This is called when the refcnt of a css is confirmed to be killed.
3891 * css_tryget() is now guaranteed to fail.
3893 static void css_killed_work_fn(struct work_struct *work)
3895 struct cgroup_subsys_state *css =
3896 container_of(work, struct cgroup_subsys_state, destroy_work);
3897 struct cgroup *cgrp = css->cgroup;
3899 mutex_lock(&cgroup_tree_mutex);
3900 mutex_lock(&cgroup_mutex);
3903 * css_tryget() is guaranteed to fail now. Tell subsystems to
3904 * initate destruction.
3909 * If @cgrp is marked dead, it's waiting for refs of all css's to
3910 * be disabled before proceeding to the second phase of cgroup
3911 * destruction. If we are the last one, kick it off.
3913 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
3914 cgroup_destroy_css_killed(cgrp);
3916 mutex_unlock(&cgroup_mutex);
3917 mutex_unlock(&cgroup_tree_mutex);
3920 * Put the css refs from kill_css(). Each css holds an extra
3921 * reference to the cgroup's dentry and cgroup removal proceeds
3922 * regardless of css refs. On the last put of each css, whenever
3923 * that may be, the extra dentry ref is put so that dentry
3924 * destruction happens only after all css's are released.
3929 /* css kill confirmation processing requires process context, bounce */
3930 static void css_killed_ref_fn(struct percpu_ref *ref)
3932 struct cgroup_subsys_state *css =
3933 container_of(ref, struct cgroup_subsys_state, refcnt);
3935 INIT_WORK(&css->destroy_work, css_killed_work_fn);
3936 queue_work(cgroup_destroy_wq, &css->destroy_work);
3940 * kill_css - destroy a css
3941 * @css: css to destroy
3943 * This function initiates destruction of @css by removing cgroup interface
3944 * files and putting its base reference. ->css_offline() will be invoked
3945 * asynchronously once css_tryget() is guaranteed to fail and when the
3946 * reference count reaches zero, @css will be released.
3948 static void kill_css(struct cgroup_subsys_state *css)
3951 * This must happen before css is disassociated with its cgroup.
3952 * See seq_css() for details.
3954 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
3957 * Killing would put the base ref, but we need to keep it alive
3958 * until after ->css_offline().
3963 * cgroup core guarantees that, by the time ->css_offline() is
3964 * invoked, no new css reference will be given out via
3965 * css_tryget(). We can't simply call percpu_ref_kill() and
3966 * proceed to offlining css's because percpu_ref_kill() doesn't
3967 * guarantee that the ref is seen as killed on all CPUs on return.
3969 * Use percpu_ref_kill_and_confirm() to get notifications as each
3970 * css is confirmed to be seen as killed on all CPUs.
3972 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
3976 * cgroup_destroy_locked - the first stage of cgroup destruction
3977 * @cgrp: cgroup to be destroyed
3979 * css's make use of percpu refcnts whose killing latency shouldn't be
3980 * exposed to userland and are RCU protected. Also, cgroup core needs to
3981 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
3982 * invoked. To satisfy all the requirements, destruction is implemented in
3983 * the following two steps.
3985 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
3986 * userland visible parts and start killing the percpu refcnts of
3987 * css's. Set up so that the next stage will be kicked off once all
3988 * the percpu refcnts are confirmed to be killed.
3990 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
3991 * rest of destruction. Once all cgroup references are gone, the
3992 * cgroup is RCU-freed.
3994 * This function implements s1. After this step, @cgrp is gone as far as
3995 * the userland is concerned and a new cgroup with the same name may be
3996 * created. As cgroup doesn't care about the names internally, this
3997 * doesn't cause any problem.
3999 static int cgroup_destroy_locked(struct cgroup *cgrp)
4000 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4002 struct cgroup *child;
4003 struct cgroup_subsys_state *css;
4004 struct kernfs_node *kn;
4008 lockdep_assert_held(&cgroup_tree_mutex);
4009 lockdep_assert_held(&cgroup_mutex);
4012 * css_set_lock synchronizes access to ->cset_links and prevents
4013 * @cgrp from being removed while __put_css_set() is in progress.
4015 read_lock(&css_set_lock);
4016 empty = list_empty(&cgrp->cset_links);
4017 read_unlock(&css_set_lock);
4022 * Make sure there's no live children. We can't test ->children
4023 * emptiness as dead children linger on it while being destroyed;
4024 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4028 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4029 empty = cgroup_is_dead(child);
4038 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4039 * will be invoked to perform the rest of destruction once the
4040 * percpu refs of all css's are confirmed to be killed. This
4041 * involves removing the subsystem's files, drop cgroup_mutex.
4043 mutex_unlock(&cgroup_mutex);
4044 for_each_css(css, ssid, cgrp)
4046 mutex_lock(&cgroup_mutex);
4049 * Mark @cgrp dead. This prevents further task migration and child
4050 * creation by disabling cgroup_lock_live_group(). Note that
4051 * CGRP_DEAD assertion is depended upon by css_next_child() to
4052 * resume iteration after dropping RCU read lock. See
4053 * css_next_child() for details.
4055 set_bit(CGRP_DEAD, &cgrp->flags);
4057 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4058 raw_spin_lock(&release_list_lock);
4059 if (!list_empty(&cgrp->release_list))
4060 list_del_init(&cgrp->release_list);
4061 raw_spin_unlock(&release_list_lock);
4064 * If @cgrp has css's attached, the second stage of cgroup
4065 * destruction is kicked off from css_killed_work_fn() after the
4066 * refs of all attached css's are killed. If @cgrp doesn't have
4067 * any css, we kick it off here.
4070 cgroup_destroy_css_killed(cgrp);
4072 /* remove @cgrp directory along with the base files */
4073 mutex_unlock(&cgroup_mutex);
4076 * There are two control paths which try to determine cgroup from
4077 * dentry without going through kernfs - cgroupstats_build() and
4078 * css_tryget_from_dir(). Those are supported by RCU protecting
4079 * clearing of cgrp->kn->priv backpointer, which should happen
4080 * after all files under it have been removed.
4085 kernfs_remove(cgrp->kn);
4087 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
4090 mutex_lock(&cgroup_mutex);
4096 * cgroup_destroy_css_killed - the second step of cgroup destruction
4097 * @work: cgroup->destroy_free_work
4099 * This function is invoked from a work item for a cgroup which is being
4100 * destroyed after all css's are offlined and performs the rest of
4101 * destruction. This is the second step of destruction described in the
4102 * comment above cgroup_destroy_locked().
4104 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4106 struct cgroup *parent = cgrp->parent;
4108 lockdep_assert_held(&cgroup_tree_mutex);
4109 lockdep_assert_held(&cgroup_mutex);
4111 /* delete this cgroup from parent->children */
4112 list_del_rcu(&cgrp->sibling);
4116 set_bit(CGRP_RELEASABLE, &parent->flags);
4117 check_for_release(parent);
4120 static int cgroup_rmdir(struct kernfs_node *kn)
4122 struct cgroup *cgrp = kn->priv;
4126 * This is self-destruction but @kn can't be removed while this
4127 * callback is in progress. Let's break active protection. Once
4128 * the protection is broken, @cgrp can be destroyed at any point.
4129 * Pin it so that it stays accessible.
4132 kernfs_break_active_protection(kn);
4134 mutex_lock(&cgroup_tree_mutex);
4135 mutex_lock(&cgroup_mutex);
4138 * @cgrp might already have been destroyed while we're trying to
4141 if (!cgroup_is_dead(cgrp))
4142 ret = cgroup_destroy_locked(cgrp);
4144 mutex_unlock(&cgroup_mutex);
4145 mutex_unlock(&cgroup_tree_mutex);
4147 kernfs_unbreak_active_protection(kn);
4152 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4153 .remount_fs = cgroup_remount,
4154 .show_options = cgroup_show_options,
4155 .mkdir = cgroup_mkdir,
4156 .rmdir = cgroup_rmdir,
4157 .rename = cgroup_rename,
4160 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4162 struct cgroup_subsys_state *css;
4164 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4166 mutex_lock(&cgroup_tree_mutex);
4167 mutex_lock(&cgroup_mutex);
4169 INIT_LIST_HEAD(&ss->cftsets);
4171 /* Create the top cgroup state for this subsystem */
4172 ss->root = &cgroup_dummy_root;
4173 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4174 /* We don't handle early failures gracefully */
4175 BUG_ON(IS_ERR(css));
4176 init_css(css, ss, cgroup_dummy_top);
4178 /* Update the init_css_set to contain a subsys
4179 * pointer to this state - since the subsystem is
4180 * newly registered, all tasks and hence the
4181 * init_css_set is in the subsystem's top cgroup. */
4182 init_css_set.subsys[ss->id] = css;
4184 need_forkexit_callback |= ss->fork || ss->exit;
4186 /* At system boot, before all subsystems have been
4187 * registered, no tasks have been forked, so we don't
4188 * need to invoke fork callbacks here. */
4189 BUG_ON(!list_empty(&init_task.tasks));
4191 BUG_ON(online_css(css));
4193 mutex_unlock(&cgroup_mutex);
4194 mutex_unlock(&cgroup_tree_mutex);
4198 * cgroup_init_early - cgroup initialization at system boot
4200 * Initialize cgroups at system boot, and initialize any
4201 * subsystems that request early init.
4203 int __init cgroup_init_early(void)
4205 struct cgroup_subsys *ss;
4208 atomic_set(&init_css_set.refcount, 1);
4209 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4210 INIT_LIST_HEAD(&init_css_set.tasks);
4211 INIT_HLIST_NODE(&init_css_set.hlist);
4213 init_cgroup_root(&cgroup_dummy_root);
4214 cgroup_root_count = 1;
4215 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4217 init_cgrp_cset_link.cset = &init_css_set;
4218 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4219 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4220 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4222 for_each_subsys(ss, i) {
4223 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4224 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4225 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4227 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4228 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4231 ss->name = cgroup_subsys_name[i];
4234 cgroup_init_subsys(ss);
4240 * cgroup_init - cgroup initialization
4242 * Register cgroup filesystem and /proc file, and initialize
4243 * any subsystems that didn't request early init.
4245 int __init cgroup_init(void)
4247 struct cgroup_subsys *ss;
4251 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4253 for_each_subsys(ss, i) {
4254 if (!ss->early_init)
4255 cgroup_init_subsys(ss);
4258 * cftype registration needs kmalloc and can't be done
4259 * during early_init. Register base cftypes separately.
4261 if (ss->base_cftypes)
4262 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4265 /* allocate id for the dummy hierarchy */
4266 mutex_lock(&cgroup_mutex);
4268 /* Add init_css_set to the hash table */
4269 key = css_set_hash(init_css_set.subsys);
4270 hash_add(css_set_table, &init_css_set.hlist, key);
4272 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4274 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4278 mutex_unlock(&cgroup_mutex);
4280 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4284 err = register_filesystem(&cgroup_fs_type);
4286 kobject_put(cgroup_kobj);
4290 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4294 static int __init cgroup_wq_init(void)
4297 * There isn't much point in executing destruction path in
4298 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4300 * XXX: Must be ordered to make sure parent is offlined after
4301 * children. The ordering requirement is for memcg where a
4302 * parent's offline may wait for a child's leading to deadlock. In
4303 * the long term, this should be fixed from memcg side.
4305 * We would prefer to do this in cgroup_init() above, but that
4306 * is called before init_workqueues(): so leave this until after.
4308 cgroup_destroy_wq = alloc_ordered_workqueue("cgroup_destroy", 0);
4309 BUG_ON(!cgroup_destroy_wq);
4312 * Used to destroy pidlists and separate to serve as flush domain.
4313 * Cap @max_active to 1 too.
4315 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4317 BUG_ON(!cgroup_pidlist_destroy_wq);
4321 core_initcall(cgroup_wq_init);
4324 * proc_cgroup_show()
4325 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4326 * - Used for /proc/<pid>/cgroup.
4327 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4328 * doesn't really matter if tsk->cgroup changes after we read it,
4329 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4330 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4331 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4332 * cgroup to top_cgroup.
4335 /* TODO: Use a proper seq_file iterator */
4336 int proc_cgroup_show(struct seq_file *m, void *v)
4339 struct task_struct *tsk;
4342 struct cgroupfs_root *root;
4345 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4351 tsk = get_pid_task(pid, PIDTYPE_PID);
4357 mutex_lock(&cgroup_mutex);
4359 for_each_active_root(root) {
4360 struct cgroup_subsys *ss;
4361 struct cgroup *cgrp;
4362 int ssid, count = 0;
4364 seq_printf(m, "%d:", root->hierarchy_id);
4365 for_each_subsys(ss, ssid)
4366 if (root->subsys_mask & (1 << ssid))
4367 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4368 if (strlen(root->name))
4369 seq_printf(m, "%sname=%s", count ? "," : "",
4372 cgrp = task_cgroup_from_root(tsk, root);
4373 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4381 mutex_unlock(&cgroup_mutex);
4382 put_task_struct(tsk);
4389 /* Display information about each subsystem and each hierarchy */
4390 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4392 struct cgroup_subsys *ss;
4395 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4397 * ideally we don't want subsystems moving around while we do this.
4398 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4399 * subsys/hierarchy state.
4401 mutex_lock(&cgroup_mutex);
4403 for_each_subsys(ss, i)
4404 seq_printf(m, "%s\t%d\t%d\t%d\n",
4405 ss->name, ss->root->hierarchy_id,
4406 ss->root->number_of_cgroups, !ss->disabled);
4408 mutex_unlock(&cgroup_mutex);
4412 static int cgroupstats_open(struct inode *inode, struct file *file)
4414 return single_open(file, proc_cgroupstats_show, NULL);
4417 static const struct file_operations proc_cgroupstats_operations = {
4418 .open = cgroupstats_open,
4420 .llseek = seq_lseek,
4421 .release = single_release,
4425 * cgroup_fork - attach newly forked task to its parents cgroup.
4426 * @child: pointer to task_struct of forking parent process.
4428 * Description: A task inherits its parent's cgroup at fork().
4430 * A pointer to the shared css_set was automatically copied in
4431 * fork.c by dup_task_struct(). However, we ignore that copy, since
4432 * it was not made under the protection of RCU or cgroup_mutex, so
4433 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4434 * have already changed current->cgroups, allowing the previously
4435 * referenced cgroup group to be removed and freed.
4437 * At the point that cgroup_fork() is called, 'current' is the parent
4438 * task, and the passed argument 'child' points to the child task.
4440 void cgroup_fork(struct task_struct *child)
4443 get_css_set(task_css_set(current));
4444 child->cgroups = current->cgroups;
4445 task_unlock(current);
4446 INIT_LIST_HEAD(&child->cg_list);
4450 * cgroup_post_fork - called on a new task after adding it to the task list
4451 * @child: the task in question
4453 * Adds the task to the list running through its css_set if necessary and
4454 * call the subsystem fork() callbacks. Has to be after the task is
4455 * visible on the task list in case we race with the first call to
4456 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4459 void cgroup_post_fork(struct task_struct *child)
4461 struct cgroup_subsys *ss;
4465 * use_task_css_set_links is set to 1 before we walk the tasklist
4466 * under the tasklist_lock and we read it here after we added the child
4467 * to the tasklist under the tasklist_lock as well. If the child wasn't
4468 * yet in the tasklist when we walked through it from
4469 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4470 * should be visible now due to the paired locking and barriers implied
4471 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4472 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4475 if (use_task_css_set_links) {
4476 write_lock(&css_set_lock);
4478 if (list_empty(&child->cg_list))
4479 list_add(&child->cg_list, &task_css_set(child)->tasks);
4481 write_unlock(&css_set_lock);
4485 * Call ss->fork(). This must happen after @child is linked on
4486 * css_set; otherwise, @child might change state between ->fork()
4487 * and addition to css_set.
4489 if (need_forkexit_callback) {
4490 for_each_subsys(ss, i)
4497 * cgroup_exit - detach cgroup from exiting task
4498 * @tsk: pointer to task_struct of exiting process
4499 * @run_callback: run exit callbacks?
4501 * Description: Detach cgroup from @tsk and release it.
4503 * Note that cgroups marked notify_on_release force every task in
4504 * them to take the global cgroup_mutex mutex when exiting.
4505 * This could impact scaling on very large systems. Be reluctant to
4506 * use notify_on_release cgroups where very high task exit scaling
4507 * is required on large systems.
4509 * the_top_cgroup_hack:
4511 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4513 * We call cgroup_exit() while the task is still competent to
4514 * handle notify_on_release(), then leave the task attached to the
4515 * root cgroup in each hierarchy for the remainder of its exit.
4517 * To do this properly, we would increment the reference count on
4518 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4519 * code we would add a second cgroup function call, to drop that
4520 * reference. This would just create an unnecessary hot spot on
4521 * the top_cgroup reference count, to no avail.
4523 * Normally, holding a reference to a cgroup without bumping its
4524 * count is unsafe. The cgroup could go away, or someone could
4525 * attach us to a different cgroup, decrementing the count on
4526 * the first cgroup that we never incremented. But in this case,
4527 * top_cgroup isn't going away, and either task has PF_EXITING set,
4528 * which wards off any cgroup_attach_task() attempts, or task is a failed
4529 * fork, never visible to cgroup_attach_task.
4531 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4533 struct cgroup_subsys *ss;
4534 struct css_set *cset;
4538 * Unlink from the css_set task list if necessary.
4539 * Optimistically check cg_list before taking
4542 if (!list_empty(&tsk->cg_list)) {
4543 write_lock(&css_set_lock);
4544 if (!list_empty(&tsk->cg_list))
4545 list_del_init(&tsk->cg_list);
4546 write_unlock(&css_set_lock);
4549 /* Reassign the task to the init_css_set. */
4551 cset = task_css_set(tsk);
4552 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4554 if (run_callbacks && need_forkexit_callback) {
4555 /* see cgroup_post_fork() for details */
4556 for_each_subsys(ss, i) {
4558 struct cgroup_subsys_state *old_css = cset->subsys[i];
4559 struct cgroup_subsys_state *css = task_css(tsk, i);
4561 ss->exit(css, old_css, tsk);
4567 put_css_set_taskexit(cset);
4570 static void check_for_release(struct cgroup *cgrp)
4572 if (cgroup_is_releasable(cgrp) &&
4573 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
4575 * Control Group is currently removeable. If it's not
4576 * already queued for a userspace notification, queue
4579 int need_schedule_work = 0;
4581 raw_spin_lock(&release_list_lock);
4582 if (!cgroup_is_dead(cgrp) &&
4583 list_empty(&cgrp->release_list)) {
4584 list_add(&cgrp->release_list, &release_list);
4585 need_schedule_work = 1;
4587 raw_spin_unlock(&release_list_lock);
4588 if (need_schedule_work)
4589 schedule_work(&release_agent_work);
4594 * Notify userspace when a cgroup is released, by running the
4595 * configured release agent with the name of the cgroup (path
4596 * relative to the root of cgroup file system) as the argument.
4598 * Most likely, this user command will try to rmdir this cgroup.
4600 * This races with the possibility that some other task will be
4601 * attached to this cgroup before it is removed, or that some other
4602 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4603 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4604 * unused, and this cgroup will be reprieved from its death sentence,
4605 * to continue to serve a useful existence. Next time it's released,
4606 * we will get notified again, if it still has 'notify_on_release' set.
4608 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4609 * means only wait until the task is successfully execve()'d. The
4610 * separate release agent task is forked by call_usermodehelper(),
4611 * then control in this thread returns here, without waiting for the
4612 * release agent task. We don't bother to wait because the caller of
4613 * this routine has no use for the exit status of the release agent
4614 * task, so no sense holding our caller up for that.
4616 static void cgroup_release_agent(struct work_struct *work)
4618 BUG_ON(work != &release_agent_work);
4619 mutex_lock(&cgroup_mutex);
4620 raw_spin_lock(&release_list_lock);
4621 while (!list_empty(&release_list)) {
4622 char *argv[3], *envp[3];
4624 char *pathbuf = NULL, *agentbuf = NULL;
4625 struct cgroup *cgrp = list_entry(release_list.next,
4628 list_del_init(&cgrp->release_list);
4629 raw_spin_unlock(&release_list_lock);
4630 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4633 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
4635 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4640 argv[i++] = agentbuf;
4641 argv[i++] = pathbuf;
4645 /* minimal command environment */
4646 envp[i++] = "HOME=/";
4647 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4650 /* Drop the lock while we invoke the usermode helper,
4651 * since the exec could involve hitting disk and hence
4652 * be a slow process */
4653 mutex_unlock(&cgroup_mutex);
4654 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4655 mutex_lock(&cgroup_mutex);
4659 raw_spin_lock(&release_list_lock);
4661 raw_spin_unlock(&release_list_lock);
4662 mutex_unlock(&cgroup_mutex);
4665 static int __init cgroup_disable(char *str)
4667 struct cgroup_subsys *ss;
4671 while ((token = strsep(&str, ",")) != NULL) {
4675 for_each_subsys(ss, i) {
4676 if (!strcmp(token, ss->name)) {
4678 printk(KERN_INFO "Disabling %s control group"
4679 " subsystem\n", ss->name);
4686 __setup("cgroup_disable=", cgroup_disable);
4689 * css_tryget_from_dir - get corresponding css from the dentry of a cgroup dir
4690 * @dentry: directory dentry of interest
4691 * @ss: subsystem of interest
4693 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
4694 * to get the corresponding css and return it. If such css doesn't exist
4695 * or can't be pinned, an ERR_PTR value is returned.
4697 struct cgroup_subsys_state *css_tryget_from_dir(struct dentry *dentry,
4698 struct cgroup_subsys *ss)
4700 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
4701 struct cgroup_subsys_state *css = NULL;
4702 struct cgroup *cgrp;
4704 /* is @dentry a cgroup dir? */
4705 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
4706 kernfs_type(kn) != KERNFS_DIR)
4707 return ERR_PTR(-EBADF);
4712 * This path doesn't originate from kernfs and @kn could already
4713 * have been or be removed at any point. @kn->priv is RCU
4714 * protected for this access. See destroy_locked() for details.
4716 cgrp = rcu_dereference(kn->priv);
4718 css = cgroup_css(cgrp, ss);
4720 if (!css || !css_tryget(css))
4721 css = ERR_PTR(-ENOENT);
4728 * css_from_id - lookup css by id
4729 * @id: the cgroup id
4730 * @ss: cgroup subsys to be looked into
4732 * Returns the css if there's valid one with @id, otherwise returns NULL.
4733 * Should be called under rcu_read_lock().
4735 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
4737 struct cgroup *cgrp;
4739 cgroup_assert_mutexes_or_rcu_locked();
4741 cgrp = idr_find(&ss->root->cgroup_idr, id);
4743 return cgroup_css(cgrp, ss);
4747 #ifdef CONFIG_CGROUP_DEBUG
4748 static struct cgroup_subsys_state *
4749 debug_css_alloc(struct cgroup_subsys_state *parent_css)
4751 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4754 return ERR_PTR(-ENOMEM);
4759 static void debug_css_free(struct cgroup_subsys_state *css)
4764 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
4767 return cgroup_task_count(css->cgroup);
4770 static u64 current_css_set_read(struct cgroup_subsys_state *css,
4773 return (u64)(unsigned long)current->cgroups;
4776 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
4782 count = atomic_read(&task_css_set(current)->refcount);
4787 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
4789 struct cgrp_cset_link *link;
4790 struct css_set *cset;
4792 read_lock(&css_set_lock);
4794 cset = rcu_dereference(current->cgroups);
4795 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
4796 struct cgroup *c = link->cgrp;
4797 const char *name = "?";
4799 if (c != cgroup_dummy_top)
4800 name = cgroup_name(c);
4802 seq_printf(seq, "Root %d group %s\n",
4803 c->root->hierarchy_id, name);
4806 read_unlock(&css_set_lock);
4810 #define MAX_TASKS_SHOWN_PER_CSS 25
4811 static int cgroup_css_links_read(struct seq_file *seq, void *v)
4813 struct cgroup_subsys_state *css = seq_css(seq);
4814 struct cgrp_cset_link *link;
4816 read_lock(&css_set_lock);
4817 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
4818 struct css_set *cset = link->cset;
4819 struct task_struct *task;
4821 seq_printf(seq, "css_set %p\n", cset);
4822 list_for_each_entry(task, &cset->tasks, cg_list) {
4823 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
4824 seq_puts(seq, " ...\n");
4827 seq_printf(seq, " task %d\n",
4828 task_pid_vnr(task));
4832 read_unlock(&css_set_lock);
4836 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
4838 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
4841 static struct cftype debug_files[] = {
4843 .name = "taskcount",
4844 .read_u64 = debug_taskcount_read,
4848 .name = "current_css_set",
4849 .read_u64 = current_css_set_read,
4853 .name = "current_css_set_refcount",
4854 .read_u64 = current_css_set_refcount_read,
4858 .name = "current_css_set_cg_links",
4859 .seq_show = current_css_set_cg_links_read,
4863 .name = "cgroup_css_links",
4864 .seq_show = cgroup_css_links_read,
4868 .name = "releasable",
4869 .read_u64 = releasable_read,
4875 struct cgroup_subsys debug_cgrp_subsys = {
4876 .css_alloc = debug_css_alloc,
4877 .css_free = debug_css_free,
4878 .base_cftypes = debug_files,
4880 #endif /* CONFIG_CGROUP_DEBUG */