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/rwsem.h>
46 #include <linux/string.h>
47 #include <linux/sort.h>
48 #include <linux/kmod.h>
49 #include <linux/delayacct.h>
50 #include <linux/cgroupstats.h>
51 #include <linux/hashtable.h>
52 #include <linux/pid_namespace.h>
53 #include <linux/idr.h>
54 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
55 #include <linux/kthread.h>
56 #include <linux/delay.h>
58 #include <linux/atomic.h>
61 * pidlists linger the following amount before being destroyed. The goal
62 * is avoiding frequent destruction in the middle of consecutive read calls
63 * Expiring in the middle is a performance problem not a correctness one.
64 * 1 sec should be enough.
66 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
68 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
72 * cgroup_tree_mutex nests above cgroup_mutex and protects cftypes, file
73 * creation/removal and hierarchy changing operations including cgroup
74 * creation, removal, css association and controller rebinding. This outer
75 * lock is needed mainly to resolve the circular dependency between kernfs
76 * active ref and cgroup_mutex. cgroup_tree_mutex nests above both.
78 static DEFINE_MUTEX(cgroup_tree_mutex);
81 * cgroup_mutex is the master lock. Any modification to cgroup or its
82 * hierarchy must be performed while holding it.
84 * css_set_rwsem protects task->cgroups pointer, the list of css_set
85 * objects, and the chain of tasks off each css_set.
87 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
88 * cgroup.h can use them for lockdep annotations.
90 #ifdef CONFIG_PROVE_RCU
91 DEFINE_MUTEX(cgroup_mutex);
92 DECLARE_RWSEM(css_set_rwsem);
93 EXPORT_SYMBOL_GPL(cgroup_mutex);
94 EXPORT_SYMBOL_GPL(css_set_rwsem);
96 static DEFINE_MUTEX(cgroup_mutex);
97 static DECLARE_RWSEM(css_set_rwsem);
101 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
102 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
104 static DEFINE_SPINLOCK(release_agent_path_lock);
106 #define cgroup_assert_mutexes_or_rcu_locked() \
107 rcu_lockdep_assert(rcu_read_lock_held() || \
108 lockdep_is_held(&cgroup_tree_mutex) || \
109 lockdep_is_held(&cgroup_mutex), \
110 "cgroup_[tree_]mutex or RCU read lock required");
113 * cgroup destruction makes heavy use of work items and there can be a lot
114 * of concurrent destructions. Use a separate workqueue so that cgroup
115 * destruction work items don't end up filling up max_active of system_wq
116 * which may lead to deadlock.
118 static struct workqueue_struct *cgroup_destroy_wq;
121 * pidlist destructions need to be flushed on cgroup destruction. Use a
122 * separate workqueue as flush domain.
124 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
126 /* generate an array of cgroup subsystem pointers */
127 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
128 static struct cgroup_subsys *cgroup_subsys[] = {
129 #include <linux/cgroup_subsys.h>
133 /* array of cgroup subsystem names */
134 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
135 static const char *cgroup_subsys_name[] = {
136 #include <linux/cgroup_subsys.h>
141 * The dummy hierarchy, reserved for the subsystems that are otherwise
142 * unattached - it never has more than a single cgroup, and all tasks are
143 * part of that cgroup.
145 static struct cgroupfs_root cgroup_dummy_root;
147 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
148 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
150 /* The list of hierarchy roots */
152 static LIST_HEAD(cgroup_roots);
153 static int cgroup_root_count;
155 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
156 static DEFINE_IDR(cgroup_hierarchy_idr);
159 * Assign a monotonically increasing serial number to cgroups. It
160 * guarantees cgroups with bigger numbers are newer than those with smaller
161 * numbers. Also, as cgroups are always appended to the parent's
162 * ->children list, it guarantees that sibling cgroups are always sorted in
163 * the ascending serial number order on the list. Protected by
166 static u64 cgroup_serial_nr_next = 1;
168 /* This flag indicates whether tasks in the fork and exit paths should
169 * check for fork/exit handlers to call. This avoids us having to do
170 * extra work in the fork/exit path if none of the subsystems need to
173 static int need_forkexit_callback __read_mostly;
175 static struct cftype cgroup_base_files[];
177 static void cgroup_put(struct cgroup *cgrp);
178 static int rebind_subsystems(struct cgroupfs_root *root,
179 unsigned long added_mask, unsigned removed_mask);
180 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
181 static int cgroup_destroy_locked(struct cgroup *cgrp);
182 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
184 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
187 * cgroup_css - obtain a cgroup's css for the specified subsystem
188 * @cgrp: the cgroup of interest
189 * @ss: the subsystem of interest (%NULL returns the dummy_css)
191 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
192 * function must be called either under cgroup_mutex or rcu_read_lock() and
193 * the caller is responsible for pinning the returned css if it wants to
194 * keep accessing it outside the said locks. This function may return
195 * %NULL if @cgrp doesn't have @subsys_id enabled.
197 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
198 struct cgroup_subsys *ss)
201 return rcu_dereference_check(cgrp->subsys[ss->id],
202 lockdep_is_held(&cgroup_tree_mutex) ||
203 lockdep_is_held(&cgroup_mutex));
205 return &cgrp->dummy_css;
208 /* convenient tests for these bits */
209 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
211 return test_bit(CGRP_DEAD, &cgrp->flags);
214 struct cgroup_subsys_state *seq_css(struct seq_file *seq)
216 struct kernfs_open_file *of = seq->private;
217 struct cgroup *cgrp = of->kn->parent->priv;
218 struct cftype *cft = seq_cft(seq);
221 * This is open and unprotected implementation of cgroup_css().
222 * seq_css() is only called from a kernfs file operation which has
223 * an active reference on the file. Because all the subsystem
224 * files are drained before a css is disassociated with a cgroup,
225 * the matching css from the cgroup's subsys table is guaranteed to
226 * be and stay valid until the enclosing operation is complete.
229 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
231 return &cgrp->dummy_css;
233 EXPORT_SYMBOL_GPL(seq_css);
236 * cgroup_is_descendant - test ancestry
237 * @cgrp: the cgroup to be tested
238 * @ancestor: possible ancestor of @cgrp
240 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
241 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
242 * and @ancestor are accessible.
244 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
247 if (cgrp == ancestor)
254 static int cgroup_is_releasable(const struct cgroup *cgrp)
257 (1 << CGRP_RELEASABLE) |
258 (1 << CGRP_NOTIFY_ON_RELEASE);
259 return (cgrp->flags & bits) == bits;
262 static int notify_on_release(const struct cgroup *cgrp)
264 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
268 * for_each_css - iterate all css's of a cgroup
269 * @css: the iteration cursor
270 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
271 * @cgrp: the target cgroup to iterate css's of
273 * Should be called under cgroup_mutex.
275 #define for_each_css(css, ssid, cgrp) \
276 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
277 if (!((css) = rcu_dereference_check( \
278 (cgrp)->subsys[(ssid)], \
279 lockdep_is_held(&cgroup_tree_mutex) || \
280 lockdep_is_held(&cgroup_mutex)))) { } \
284 * for_each_subsys - iterate all enabled cgroup subsystems
285 * @ss: the iteration cursor
286 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
288 #define for_each_subsys(ss, ssid) \
289 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
290 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
292 /* iterate across the active hierarchies */
293 #define for_each_active_root(root) \
294 list_for_each_entry((root), &cgroup_roots, root_list)
297 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
298 * @cgrp: the cgroup to be checked for liveness
300 * On success, returns true; the mutex should be later unlocked. On
301 * failure returns false with no lock held.
303 static bool cgroup_lock_live_group(struct cgroup *cgrp)
305 mutex_lock(&cgroup_mutex);
306 if (cgroup_is_dead(cgrp)) {
307 mutex_unlock(&cgroup_mutex);
313 /* the list of cgroups eligible for automatic release. Protected by
314 * release_list_lock */
315 static LIST_HEAD(release_list);
316 static DEFINE_RAW_SPINLOCK(release_list_lock);
317 static void cgroup_release_agent(struct work_struct *work);
318 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
319 static void check_for_release(struct cgroup *cgrp);
322 * A cgroup can be associated with multiple css_sets as different tasks may
323 * belong to different cgroups on different hierarchies. In the other
324 * direction, a css_set is naturally associated with multiple cgroups.
325 * This M:N relationship is represented by the following link structure
326 * which exists for each association and allows traversing the associations
329 struct cgrp_cset_link {
330 /* the cgroup and css_set this link associates */
332 struct css_set *cset;
334 /* list of cgrp_cset_links anchored at cgrp->cset_links */
335 struct list_head cset_link;
337 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
338 struct list_head cgrp_link;
341 /* The default css_set - used by init and its children prior to any
342 * hierarchies being mounted. It contains a pointer to the root state
343 * for each subsystem. Also used to anchor the list of css_sets. Not
344 * reference-counted, to improve performance when child cgroups
345 * haven't been created.
348 static struct css_set init_css_set;
349 static struct cgrp_cset_link init_cgrp_cset_link;
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;
373 static void put_css_set_locked(struct css_set *cset, bool taskexit)
375 struct cgrp_cset_link *link, *tmp_link;
377 lockdep_assert_held(&css_set_rwsem);
379 if (!atomic_dec_and_test(&cset->refcount))
382 /* This css_set is dead. unlink it and release cgroup refcounts */
383 hash_del(&cset->hlist);
386 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
387 struct cgroup *cgrp = link->cgrp;
389 list_del(&link->cset_link);
390 list_del(&link->cgrp_link);
392 /* @cgrp can't go away while we're holding css_set_rwsem */
393 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
395 set_bit(CGRP_RELEASABLE, &cgrp->flags);
396 check_for_release(cgrp);
402 kfree_rcu(cset, rcu_head);
405 static void put_css_set(struct css_set *cset, bool taskexit)
408 * Ensure that the refcount doesn't hit zero while any readers
409 * can see it. Similar to atomic_dec_and_lock(), but for an
412 if (atomic_add_unless(&cset->refcount, -1, 1))
415 down_write(&css_set_rwsem);
416 put_css_set_locked(cset, taskexit);
417 up_write(&css_set_rwsem);
421 * refcounted get/put for css_set objects
423 static inline void get_css_set(struct css_set *cset)
425 atomic_inc(&cset->refcount);
429 * compare_css_sets - helper function for find_existing_css_set().
430 * @cset: candidate css_set being tested
431 * @old_cset: existing css_set for a task
432 * @new_cgrp: cgroup that's being entered by the task
433 * @template: desired set of css pointers in css_set (pre-calculated)
435 * Returns true if "cset" matches "old_cset" except for the hierarchy
436 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
438 static bool compare_css_sets(struct css_set *cset,
439 struct css_set *old_cset,
440 struct cgroup *new_cgrp,
441 struct cgroup_subsys_state *template[])
443 struct list_head *l1, *l2;
445 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
446 /* Not all subsystems matched */
451 * Compare cgroup pointers in order to distinguish between
452 * different cgroups in heirarchies with no subsystems. We
453 * could get by with just this check alone (and skip the
454 * memcmp above) but on most setups the memcmp check will
455 * avoid the need for this more expensive check on almost all
459 l1 = &cset->cgrp_links;
460 l2 = &old_cset->cgrp_links;
462 struct cgrp_cset_link *link1, *link2;
463 struct cgroup *cgrp1, *cgrp2;
467 /* See if we reached the end - both lists are equal length. */
468 if (l1 == &cset->cgrp_links) {
469 BUG_ON(l2 != &old_cset->cgrp_links);
472 BUG_ON(l2 == &old_cset->cgrp_links);
474 /* Locate the cgroups associated with these links. */
475 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
476 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
479 /* Hierarchies should be linked in the same order. */
480 BUG_ON(cgrp1->root != cgrp2->root);
483 * If this hierarchy is the hierarchy of the cgroup
484 * that's changing, then we need to check that this
485 * css_set points to the new cgroup; if it's any other
486 * hierarchy, then this css_set should point to the
487 * same cgroup as the old css_set.
489 if (cgrp1->root == new_cgrp->root) {
490 if (cgrp1 != new_cgrp)
501 * find_existing_css_set - init css array and find the matching css_set
502 * @old_cset: the css_set that we're using before the cgroup transition
503 * @cgrp: the cgroup that we're moving into
504 * @template: out param for the new set of csses, should be clear on entry
506 static struct css_set *find_existing_css_set(struct css_set *old_cset,
508 struct cgroup_subsys_state *template[])
510 struct cgroupfs_root *root = cgrp->root;
511 struct cgroup_subsys *ss;
512 struct css_set *cset;
517 * Build the set of subsystem state objects that we want to see in the
518 * new css_set. while subsystems can change globally, the entries here
519 * won't change, so no need for locking.
521 for_each_subsys(ss, i) {
522 if (root->subsys_mask & (1UL << i)) {
523 /* Subsystem is in this hierarchy. So we want
524 * the subsystem state from the new
526 template[i] = cgroup_css(cgrp, ss);
528 /* Subsystem is not in this hierarchy, so we
529 * don't want to change the subsystem state */
530 template[i] = old_cset->subsys[i];
534 key = css_set_hash(template);
535 hash_for_each_possible(css_set_table, cset, hlist, key) {
536 if (!compare_css_sets(cset, old_cset, cgrp, template))
539 /* This css_set matches what we need */
543 /* No existing cgroup group matched */
547 static void free_cgrp_cset_links(struct list_head *links_to_free)
549 struct cgrp_cset_link *link, *tmp_link;
551 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
552 list_del(&link->cset_link);
558 * allocate_cgrp_cset_links - allocate cgrp_cset_links
559 * @count: the number of links to allocate
560 * @tmp_links: list_head the allocated links are put on
562 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
563 * through ->cset_link. Returns 0 on success or -errno.
565 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
567 struct cgrp_cset_link *link;
570 INIT_LIST_HEAD(tmp_links);
572 for (i = 0; i < count; i++) {
573 link = kzalloc(sizeof(*link), GFP_KERNEL);
575 free_cgrp_cset_links(tmp_links);
578 list_add(&link->cset_link, tmp_links);
584 * link_css_set - a helper function to link a css_set to a cgroup
585 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
586 * @cset: the css_set to be linked
587 * @cgrp: the destination cgroup
589 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
592 struct cgrp_cset_link *link;
594 BUG_ON(list_empty(tmp_links));
595 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
598 list_move(&link->cset_link, &cgrp->cset_links);
600 * Always add links to the tail of the list so that the list
601 * is sorted by order of hierarchy creation
603 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
607 * find_css_set - return a new css_set with one cgroup updated
608 * @old_cset: the baseline css_set
609 * @cgrp: the cgroup to be updated
611 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
612 * substituted into the appropriate hierarchy.
614 static struct css_set *find_css_set(struct css_set *old_cset,
617 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
618 struct css_set *cset;
619 struct list_head tmp_links;
620 struct cgrp_cset_link *link;
623 lockdep_assert_held(&cgroup_mutex);
625 /* First see if we already have a cgroup group that matches
627 down_read(&css_set_rwsem);
628 cset = find_existing_css_set(old_cset, cgrp, template);
631 up_read(&css_set_rwsem);
636 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
640 /* Allocate all the cgrp_cset_link objects that we'll need */
641 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
646 atomic_set(&cset->refcount, 1);
647 INIT_LIST_HEAD(&cset->cgrp_links);
648 INIT_LIST_HEAD(&cset->tasks);
649 INIT_LIST_HEAD(&cset->mg_tasks);
650 INIT_LIST_HEAD(&cset->mg_preload_node);
651 INIT_LIST_HEAD(&cset->mg_node);
652 INIT_HLIST_NODE(&cset->hlist);
654 /* Copy the set of subsystem state objects generated in
655 * find_existing_css_set() */
656 memcpy(cset->subsys, template, sizeof(cset->subsys));
658 down_write(&css_set_rwsem);
659 /* Add reference counts and links from the new css_set. */
660 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
661 struct cgroup *c = link->cgrp;
663 if (c->root == cgrp->root)
665 link_css_set(&tmp_links, cset, c);
668 BUG_ON(!list_empty(&tmp_links));
672 /* Add this cgroup group to the hash table */
673 key = css_set_hash(cset->subsys);
674 hash_add(css_set_table, &cset->hlist, key);
676 up_write(&css_set_rwsem);
681 static struct cgroupfs_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
683 struct cgroup *top_cgrp = kf_root->kn->priv;
685 return top_cgrp->root;
688 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
692 lockdep_assert_held(&cgroup_mutex);
694 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
699 root->hierarchy_id = id;
703 static void cgroup_exit_root_id(struct cgroupfs_root *root)
705 lockdep_assert_held(&cgroup_mutex);
707 if (root->hierarchy_id) {
708 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
709 root->hierarchy_id = 0;
713 static void cgroup_free_root(struct cgroupfs_root *root)
716 /* hierarhcy ID shoulid already have been released */
717 WARN_ON_ONCE(root->hierarchy_id);
719 idr_destroy(&root->cgroup_idr);
724 static void cgroup_destroy_root(struct cgroupfs_root *root)
726 struct cgroup *cgrp = &root->top_cgroup;
727 struct cgrp_cset_link *link, *tmp_link;
729 mutex_lock(&cgroup_tree_mutex);
730 mutex_lock(&cgroup_mutex);
732 BUG_ON(atomic_read(&root->nr_cgrps));
733 BUG_ON(!list_empty(&cgrp->children));
735 /* Rebind all subsystems back to the default hierarchy */
736 WARN_ON(rebind_subsystems(root, 0, root->subsys_mask));
739 * Release all the links from cset_links to this hierarchy's
742 down_write(&css_set_rwsem);
744 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
745 list_del(&link->cset_link);
746 list_del(&link->cgrp_link);
749 up_write(&css_set_rwsem);
751 if (!list_empty(&root->root_list)) {
752 list_del(&root->root_list);
756 cgroup_exit_root_id(root);
758 mutex_unlock(&cgroup_mutex);
759 mutex_unlock(&cgroup_tree_mutex);
761 kernfs_destroy_root(root->kf_root);
762 cgroup_free_root(root);
765 /* look up cgroup associated with given css_set on the specified hierarchy */
766 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
767 struct cgroupfs_root *root)
769 struct cgroup *res = NULL;
771 lockdep_assert_held(&cgroup_mutex);
772 lockdep_assert_held(&css_set_rwsem);
774 if (cset == &init_css_set) {
775 res = &root->top_cgroup;
777 struct cgrp_cset_link *link;
779 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
780 struct cgroup *c = link->cgrp;
782 if (c->root == root) {
794 * Return the cgroup for "task" from the given hierarchy. Must be
795 * called with cgroup_mutex and css_set_rwsem held.
797 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
798 struct cgroupfs_root *root)
801 * No need to lock the task - since we hold cgroup_mutex the
802 * task can't change groups, so the only thing that can happen
803 * is that it exits and its css is set back to init_css_set.
805 return cset_cgroup_from_root(task_css_set(task), root);
809 * A task must hold cgroup_mutex to modify cgroups.
811 * Any task can increment and decrement the count field without lock.
812 * So in general, code holding cgroup_mutex can't rely on the count
813 * field not changing. However, if the count goes to zero, then only
814 * cgroup_attach_task() can increment it again. Because a count of zero
815 * means that no tasks are currently attached, therefore there is no
816 * way a task attached to that cgroup can fork (the other way to
817 * increment the count). So code holding cgroup_mutex can safely
818 * assume that if the count is zero, it will stay zero. Similarly, if
819 * a task holds cgroup_mutex on a cgroup with zero count, it
820 * knows that the cgroup won't be removed, as cgroup_rmdir()
823 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
824 * (usually) take cgroup_mutex. These are the two most performance
825 * critical pieces of code here. The exception occurs on cgroup_exit(),
826 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
827 * is taken, and if the cgroup count is zero, a usermode call made
828 * to the release agent with the name of the cgroup (path relative to
829 * the root of cgroup file system) as the argument.
831 * A cgroup can only be deleted if both its 'count' of using tasks
832 * is zero, and its list of 'children' cgroups is empty. Since all
833 * tasks in the system use _some_ cgroup, and since there is always at
834 * least one task in the system (init, pid == 1), therefore, top_cgroup
835 * always has either children cgroups and/or using tasks. So we don't
836 * need a special hack to ensure that top_cgroup cannot be deleted.
838 * P.S. One more locking exception. RCU is used to guard the
839 * update of a tasks cgroup pointer by cgroup_attach_task()
842 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
843 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
844 static const struct file_operations proc_cgroupstats_operations;
846 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
849 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
850 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
851 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
852 cft->ss->name, cft->name);
854 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
859 * cgroup_file_mode - deduce file mode of a control file
860 * @cft: the control file in question
862 * returns cft->mode if ->mode is not 0
863 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
864 * returns S_IRUGO if it has only a read handler
865 * returns S_IWUSR if it has only a write hander
867 static umode_t cgroup_file_mode(const struct cftype *cft)
874 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
877 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
884 static void cgroup_free_fn(struct work_struct *work)
886 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
888 atomic_dec(&cgrp->root->nr_cgrps);
889 cgroup_pidlist_destroy_all(cgrp);
893 * We get a ref to the parent, and put the ref when this
894 * cgroup is being freed, so it's guaranteed that the
895 * parent won't be destroyed before its children.
897 cgroup_put(cgrp->parent);
898 kernfs_put(cgrp->kn);
902 * This is top cgroup's refcnt reaching zero, which
903 * indicates that the root should be released.
905 cgroup_destroy_root(cgrp->root);
909 static void cgroup_free_rcu(struct rcu_head *head)
911 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
913 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
914 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
917 static void cgroup_get(struct cgroup *cgrp)
919 WARN_ON_ONCE(cgroup_is_dead(cgrp));
920 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
921 atomic_inc(&cgrp->refcnt);
924 static void cgroup_put(struct cgroup *cgrp)
926 if (!atomic_dec_and_test(&cgrp->refcnt))
928 if (WARN_ON_ONCE(cgrp->parent && !cgroup_is_dead(cgrp)))
932 * XXX: cgrp->id is only used to look up css's. As cgroup and
933 * css's lifetimes will be decoupled, it should be made
934 * per-subsystem and moved to css->id so that lookups are
935 * successful until the target css is released.
937 mutex_lock(&cgroup_mutex);
938 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
939 mutex_unlock(&cgroup_mutex);
942 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
945 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
947 char name[CGROUP_FILE_NAME_MAX];
949 lockdep_assert_held(&cgroup_tree_mutex);
950 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
954 * cgroup_clear_dir - remove subsys files in a cgroup directory
955 * @cgrp: target cgroup
956 * @subsys_mask: mask of the subsystem ids whose files should be removed
958 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
960 struct cgroup_subsys *ss;
963 for_each_subsys(ss, i) {
966 if (!test_bit(i, &subsys_mask))
968 list_for_each_entry(cfts, &ss->cfts, node)
969 cgroup_addrm_files(cgrp, cfts, false);
973 static int rebind_subsystems(struct cgroupfs_root *root,
974 unsigned long added_mask, unsigned removed_mask)
976 struct cgroup *cgrp = &root->top_cgroup;
977 struct cgroup_subsys *ss;
980 lockdep_assert_held(&cgroup_tree_mutex);
981 lockdep_assert_held(&cgroup_mutex);
983 /* Check that any added subsystems are currently free */
984 for_each_subsys(ss, i)
985 if ((added_mask & (1 << i)) && ss->root != &cgroup_dummy_root)
988 ret = cgroup_populate_dir(cgrp, added_mask);
993 * Nothing can fail from this point on. Remove files for the
994 * removed subsystems and rebind each subsystem.
996 mutex_unlock(&cgroup_mutex);
997 cgroup_clear_dir(cgrp, removed_mask);
998 mutex_lock(&cgroup_mutex);
1000 for_each_subsys(ss, i) {
1001 unsigned long bit = 1UL << i;
1003 if (bit & added_mask) {
1004 /* We're binding this subsystem to this hierarchy */
1005 BUG_ON(cgroup_css(cgrp, ss));
1006 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
1007 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
1009 rcu_assign_pointer(cgrp->subsys[i],
1010 cgroup_css(cgroup_dummy_top, ss));
1011 cgroup_css(cgrp, ss)->cgroup = cgrp;
1015 ss->bind(cgroup_css(cgrp, ss));
1017 /* refcount was already taken, and we're keeping it */
1018 root->subsys_mask |= bit;
1019 } else if (bit & removed_mask) {
1020 /* We're removing this subsystem */
1021 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
1022 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
1025 ss->bind(cgroup_css(cgroup_dummy_top, ss));
1027 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
1028 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1030 cgroup_subsys[i]->root = &cgroup_dummy_root;
1031 root->subsys_mask &= ~bit;
1035 kernfs_activate(cgrp->kn);
1039 static int cgroup_show_options(struct seq_file *seq,
1040 struct kernfs_root *kf_root)
1042 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1043 struct cgroup_subsys *ss;
1046 for_each_subsys(ss, ssid)
1047 if (root->subsys_mask & (1 << ssid))
1048 seq_printf(seq, ",%s", ss->name);
1049 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1050 seq_puts(seq, ",sane_behavior");
1051 if (root->flags & CGRP_ROOT_NOPREFIX)
1052 seq_puts(seq, ",noprefix");
1053 if (root->flags & CGRP_ROOT_XATTR)
1054 seq_puts(seq, ",xattr");
1056 spin_lock(&release_agent_path_lock);
1057 if (strlen(root->release_agent_path))
1058 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1059 spin_unlock(&release_agent_path_lock);
1061 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1062 seq_puts(seq, ",clone_children");
1063 if (strlen(root->name))
1064 seq_printf(seq, ",name=%s", root->name);
1068 struct cgroup_sb_opts {
1069 unsigned long subsys_mask;
1070 unsigned long flags;
1071 char *release_agent;
1072 bool cpuset_clone_children;
1074 /* User explicitly requested empty subsystem */
1079 * Convert a hierarchy specifier into a bitmask of subsystems and
1080 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1081 * array. This function takes refcounts on subsystems to be used, unless it
1082 * returns error, in which case no refcounts are taken.
1084 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1086 char *token, *o = data;
1087 bool all_ss = false, one_ss = false;
1088 unsigned long mask = (unsigned long)-1;
1089 struct cgroup_subsys *ss;
1092 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1094 #ifdef CONFIG_CPUSETS
1095 mask = ~(1UL << cpuset_cgrp_id);
1098 memset(opts, 0, sizeof(*opts));
1100 while ((token = strsep(&o, ",")) != NULL) {
1103 if (!strcmp(token, "none")) {
1104 /* Explicitly have no subsystems */
1108 if (!strcmp(token, "all")) {
1109 /* Mutually exclusive option 'all' + subsystem name */
1115 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1116 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1119 if (!strcmp(token, "noprefix")) {
1120 opts->flags |= CGRP_ROOT_NOPREFIX;
1123 if (!strcmp(token, "clone_children")) {
1124 opts->cpuset_clone_children = true;
1127 if (!strcmp(token, "xattr")) {
1128 opts->flags |= CGRP_ROOT_XATTR;
1131 if (!strncmp(token, "release_agent=", 14)) {
1132 /* Specifying two release agents is forbidden */
1133 if (opts->release_agent)
1135 opts->release_agent =
1136 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1137 if (!opts->release_agent)
1141 if (!strncmp(token, "name=", 5)) {
1142 const char *name = token + 5;
1143 /* Can't specify an empty name */
1146 /* Must match [\w.-]+ */
1147 for (i = 0; i < strlen(name); i++) {
1151 if ((c == '.') || (c == '-') || (c == '_'))
1155 /* Specifying two names is forbidden */
1158 opts->name = kstrndup(name,
1159 MAX_CGROUP_ROOT_NAMELEN - 1,
1167 for_each_subsys(ss, i) {
1168 if (strcmp(token, ss->name))
1173 /* Mutually exclusive option 'all' + subsystem name */
1176 set_bit(i, &opts->subsys_mask);
1181 if (i == CGROUP_SUBSYS_COUNT)
1186 * If the 'all' option was specified select all the subsystems,
1187 * otherwise if 'none', 'name=' and a subsystem name options
1188 * were not specified, let's default to 'all'
1190 if (all_ss || (!one_ss && !opts->none && !opts->name))
1191 for_each_subsys(ss, i)
1193 set_bit(i, &opts->subsys_mask);
1195 /* Consistency checks */
1197 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1198 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1200 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1201 opts->cpuset_clone_children || opts->release_agent ||
1203 pr_err("cgroup: sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1209 * Option noprefix was introduced just for backward compatibility
1210 * with the old cpuset, so we allow noprefix only if mounting just
1211 * the cpuset subsystem.
1213 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1217 /* Can't specify "none" and some subsystems */
1218 if (opts->subsys_mask && opts->none)
1222 * We either have to specify by name or by subsystems. (So all
1223 * empty hierarchies must have a name).
1225 if (!opts->subsys_mask && !opts->name)
1231 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1234 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1235 struct cgroup_sb_opts opts;
1236 unsigned long added_mask, removed_mask;
1238 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1239 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1243 mutex_lock(&cgroup_tree_mutex);
1244 mutex_lock(&cgroup_mutex);
1246 /* See what subsystems are wanted */
1247 ret = parse_cgroupfs_options(data, &opts);
1251 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1252 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1253 task_tgid_nr(current), current->comm);
1255 added_mask = opts.subsys_mask & ~root->subsys_mask;
1256 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1258 /* Don't allow flags or name to change at remount */
1259 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1260 (opts.name && strcmp(opts.name, root->name))) {
1261 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1262 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1263 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1268 /* remounting is not allowed for populated hierarchies */
1269 if (!list_empty(&root->top_cgroup.children)) {
1274 ret = rebind_subsystems(root, added_mask, removed_mask);
1278 if (opts.release_agent) {
1279 spin_lock(&release_agent_path_lock);
1280 strcpy(root->release_agent_path, opts.release_agent);
1281 spin_unlock(&release_agent_path_lock);
1284 kfree(opts.release_agent);
1286 mutex_unlock(&cgroup_mutex);
1287 mutex_unlock(&cgroup_tree_mutex);
1292 * To reduce the fork() overhead for systems that are not actually using
1293 * their cgroups capability, we don't maintain the lists running through
1294 * each css_set to its tasks until we see the list actually used - in other
1295 * words after the first mount.
1297 static bool use_task_css_set_links __read_mostly;
1299 static void cgroup_enable_task_cg_lists(void)
1301 struct task_struct *p, *g;
1303 down_write(&css_set_rwsem);
1305 if (use_task_css_set_links)
1308 use_task_css_set_links = true;
1311 * We need tasklist_lock because RCU is not safe against
1312 * while_each_thread(). Besides, a forking task that has passed
1313 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1314 * is not guaranteed to have its child immediately visible in the
1315 * tasklist if we walk through it with RCU.
1317 read_lock(&tasklist_lock);
1318 do_each_thread(g, p) {
1319 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1320 task_css_set(p) != &init_css_set);
1323 * We should check if the process is exiting, otherwise
1324 * it will race with cgroup_exit() in that the list
1325 * entry won't be deleted though the process has exited.
1326 * Do it while holding siglock so that we don't end up
1327 * racing against cgroup_exit().
1329 spin_lock_irq(&p->sighand->siglock);
1330 if (!(p->flags & PF_EXITING)) {
1331 struct css_set *cset = task_css_set(p);
1333 list_add(&p->cg_list, &cset->tasks);
1336 spin_unlock_irq(&p->sighand->siglock);
1337 } while_each_thread(g, p);
1338 read_unlock(&tasklist_lock);
1340 up_write(&css_set_rwsem);
1343 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1345 atomic_set(&cgrp->refcnt, 1);
1346 INIT_LIST_HEAD(&cgrp->sibling);
1347 INIT_LIST_HEAD(&cgrp->children);
1348 INIT_LIST_HEAD(&cgrp->cset_links);
1349 INIT_LIST_HEAD(&cgrp->release_list);
1350 INIT_LIST_HEAD(&cgrp->pidlists);
1351 mutex_init(&cgrp->pidlist_mutex);
1352 cgrp->dummy_css.cgroup = cgrp;
1355 static void init_cgroup_root(struct cgroupfs_root *root)
1357 struct cgroup *cgrp = &root->top_cgroup;
1359 INIT_LIST_HEAD(&root->root_list);
1360 atomic_set(&root->nr_cgrps, 1);
1362 init_cgroup_housekeeping(cgrp);
1363 idr_init(&root->cgroup_idr);
1366 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1368 struct cgroupfs_root *root;
1370 if (!opts->subsys_mask && !opts->none)
1371 return ERR_PTR(-EINVAL);
1373 root = kzalloc(sizeof(*root), GFP_KERNEL);
1375 return ERR_PTR(-ENOMEM);
1377 init_cgroup_root(root);
1379 root->flags = opts->flags;
1380 if (opts->release_agent)
1381 strcpy(root->release_agent_path, opts->release_agent);
1383 strcpy(root->name, opts->name);
1384 if (opts->cpuset_clone_children)
1385 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1389 static int cgroup_setup_root(struct cgroupfs_root *root, unsigned long ss_mask)
1391 LIST_HEAD(tmp_links);
1392 struct cgroup *root_cgrp = &root->top_cgroup;
1393 struct css_set *cset;
1396 lockdep_assert_held(&cgroup_tree_mutex);
1397 lockdep_assert_held(&cgroup_mutex);
1399 ret = idr_alloc(&root->cgroup_idr, root_cgrp, 0, 1, GFP_KERNEL);
1402 root_cgrp->id = ret;
1405 * We're accessing css_set_count without locking css_set_rwsem here,
1406 * but that's OK - it can only be increased by someone holding
1407 * cgroup_lock, and that's us. The worst that can happen is that we
1408 * have some link structures left over
1410 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1414 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1415 ret = cgroup_init_root_id(root, 2, 0);
1419 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1420 KERNFS_ROOT_CREATE_DEACTIVATED,
1422 if (IS_ERR(root->kf_root)) {
1423 ret = PTR_ERR(root->kf_root);
1426 root_cgrp->kn = root->kf_root->kn;
1428 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1432 ret = rebind_subsystems(root, ss_mask, 0);
1437 * There must be no failure case after here, since rebinding takes
1438 * care of subsystems' refcounts, which are explicitly dropped in
1439 * the failure exit path.
1441 list_add(&root->root_list, &cgroup_roots);
1442 cgroup_root_count++;
1445 * Link the top cgroup in this hierarchy into all the css_set
1448 down_write(&css_set_rwsem);
1449 hash_for_each(css_set_table, i, cset, hlist)
1450 link_css_set(&tmp_links, cset, root_cgrp);
1451 up_write(&css_set_rwsem);
1453 BUG_ON(!list_empty(&root_cgrp->children));
1454 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1456 kernfs_activate(root_cgrp->kn);
1461 kernfs_destroy_root(root->kf_root);
1462 root->kf_root = NULL;
1464 cgroup_exit_root_id(root);
1466 free_cgrp_cset_links(&tmp_links);
1470 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1471 int flags, const char *unused_dev_name,
1474 struct cgroupfs_root *root;
1475 struct cgroup_sb_opts opts;
1476 struct dentry *dentry;
1480 * The first time anyone tries to mount a cgroup, enable the list
1481 * linking each css_set to its tasks and fix up all existing tasks.
1483 if (!use_task_css_set_links)
1484 cgroup_enable_task_cg_lists();
1486 mutex_lock(&cgroup_tree_mutex);
1487 mutex_lock(&cgroup_mutex);
1489 /* First find the desired set of subsystems */
1490 ret = parse_cgroupfs_options(data, &opts);
1494 /* look for a matching existing root */
1495 for_each_active_root(root) {
1496 bool name_match = false;
1499 * If we asked for a name then it must match. Also, if
1500 * name matches but sybsys_mask doesn't, we should fail.
1501 * Remember whether name matched.
1504 if (strcmp(opts.name, root->name))
1510 * If we asked for subsystems (or explicitly for no
1511 * subsystems) then they must match.
1513 if ((opts.subsys_mask || opts.none) &&
1514 (opts.subsys_mask != root->subsys_mask)) {
1521 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1522 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1523 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1527 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1532 * A root's lifetime is governed by its top cgroup. Zero
1533 * ref indicate that the root is being destroyed. Wait for
1534 * destruction to complete so that the subsystems are free.
1535 * We can use wait_queue for the wait but this path is
1536 * super cold. Let's just sleep for a bit and retry.
1538 if (!atomic_inc_not_zero(&root->top_cgroup.refcnt)) {
1539 mutex_unlock(&cgroup_mutex);
1540 mutex_unlock(&cgroup_tree_mutex);
1541 kfree(opts.release_agent);
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, opts.subsys_mask);
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->top_cgroup);
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->top_cgroup);
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 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1597 * @task: target task
1598 * @buf: the buffer to write the path into
1599 * @buflen: the length of the buffer
1601 * Determine @task's cgroup on the first (the one with the lowest non-zero
1602 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1603 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1604 * cgroup controller callbacks.
1606 * Return value is the same as kernfs_path().
1608 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1610 struct cgroupfs_root *root;
1611 struct cgroup *cgrp;
1612 int hierarchy_id = 1;
1615 mutex_lock(&cgroup_mutex);
1616 down_read(&css_set_rwsem);
1618 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1621 cgrp = task_cgroup_from_root(task, root);
1622 path = cgroup_path(cgrp, buf, buflen);
1624 /* if no hierarchy exists, everyone is in "/" */
1625 if (strlcpy(buf, "/", buflen) < buflen)
1629 up_read(&css_set_rwsem);
1630 mutex_unlock(&cgroup_mutex);
1633 EXPORT_SYMBOL_GPL(task_cgroup_path);
1635 /* used to track tasks and other necessary states during migration */
1636 struct cgroup_taskset {
1637 /* the src and dst cset list running through cset->mg_node */
1638 struct list_head src_csets;
1639 struct list_head dst_csets;
1642 * Fields for cgroup_taskset_*() iteration.
1644 * Before migration is committed, the target migration tasks are on
1645 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1646 * the csets on ->dst_csets. ->csets point to either ->src_csets
1647 * or ->dst_csets depending on whether migration is committed.
1649 * ->cur_csets and ->cur_task point to the current task position
1652 struct list_head *csets;
1653 struct css_set *cur_cset;
1654 struct task_struct *cur_task;
1658 * cgroup_taskset_first - reset taskset and return the first task
1659 * @tset: taskset of interest
1661 * @tset iteration is initialized and the first task is returned.
1663 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1665 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1666 tset->cur_task = NULL;
1668 return cgroup_taskset_next(tset);
1672 * cgroup_taskset_next - iterate to the next task in taskset
1673 * @tset: taskset of interest
1675 * Return the next task in @tset. Iteration must have been initialized
1676 * with cgroup_taskset_first().
1678 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1680 struct css_set *cset = tset->cur_cset;
1681 struct task_struct *task = tset->cur_task;
1683 while (&cset->mg_node != tset->csets) {
1685 task = list_first_entry(&cset->mg_tasks,
1686 struct task_struct, cg_list);
1688 task = list_next_entry(task, cg_list);
1690 if (&task->cg_list != &cset->mg_tasks) {
1691 tset->cur_cset = cset;
1692 tset->cur_task = task;
1696 cset = list_next_entry(cset, mg_node);
1704 * cgroup_task_migrate - move a task from one cgroup to another.
1705 * @old_cgrp; the cgroup @tsk is being migrated from
1706 * @tsk: the task being migrated
1707 * @new_cset: the new css_set @tsk is being attached to
1709 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1711 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1712 struct task_struct *tsk,
1713 struct css_set *new_cset)
1715 struct css_set *old_cset;
1717 lockdep_assert_held(&cgroup_mutex);
1718 lockdep_assert_held(&css_set_rwsem);
1721 * We are synchronized through threadgroup_lock() against PF_EXITING
1722 * setting such that we can't race against cgroup_exit() changing the
1723 * css_set to init_css_set and dropping the old one.
1725 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1726 old_cset = task_css_set(tsk);
1728 get_css_set(new_cset);
1729 rcu_assign_pointer(tsk->cgroups, new_cset);
1730 list_move(&tsk->cg_list, &new_cset->mg_tasks);
1733 * We just gained a reference on old_cset by taking it from the
1734 * task. As trading it for new_cset is protected by cgroup_mutex,
1735 * we're safe to drop it here; it will be freed under RCU.
1737 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1738 put_css_set_locked(old_cset, false);
1742 * cgroup_migrate_finish - cleanup after attach
1743 * @preloaded_csets: list of preloaded css_sets
1745 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1746 * those functions for details.
1748 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1750 struct css_set *cset, *tmp_cset;
1752 lockdep_assert_held(&cgroup_mutex);
1754 down_write(&css_set_rwsem);
1755 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1756 cset->mg_src_cgrp = NULL;
1757 cset->mg_dst_cset = NULL;
1758 list_del_init(&cset->mg_preload_node);
1759 put_css_set_locked(cset, false);
1761 up_write(&css_set_rwsem);
1765 * cgroup_migrate_add_src - add a migration source css_set
1766 * @src_cset: the source css_set to add
1767 * @dst_cgrp: the destination cgroup
1768 * @preloaded_csets: list of preloaded css_sets
1770 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1771 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1772 * up by cgroup_migrate_finish().
1774 * This function may be called without holding threadgroup_lock even if the
1775 * target is a process. Threads may be created and destroyed but as long
1776 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1777 * the preloaded css_sets are guaranteed to cover all migrations.
1779 static void cgroup_migrate_add_src(struct css_set *src_cset,
1780 struct cgroup *dst_cgrp,
1781 struct list_head *preloaded_csets)
1783 struct cgroup *src_cgrp;
1785 lockdep_assert_held(&cgroup_mutex);
1786 lockdep_assert_held(&css_set_rwsem);
1788 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
1790 /* nothing to do if this cset already belongs to the cgroup */
1791 if (src_cgrp == dst_cgrp)
1794 if (!list_empty(&src_cset->mg_preload_node))
1797 WARN_ON(src_cset->mg_src_cgrp);
1798 WARN_ON(!list_empty(&src_cset->mg_tasks));
1799 WARN_ON(!list_empty(&src_cset->mg_node));
1801 src_cset->mg_src_cgrp = src_cgrp;
1802 get_css_set(src_cset);
1803 list_add(&src_cset->mg_preload_node, preloaded_csets);
1807 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
1808 * @dst_cgrp: the destination cgroup
1809 * @preloaded_csets: list of preloaded source css_sets
1811 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
1812 * have been preloaded to @preloaded_csets. This function looks up and
1813 * pins all destination css_sets, links each to its source, and put them on
1816 * This function must be called after cgroup_migrate_add_src() has been
1817 * called on each migration source css_set. After migration is performed
1818 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
1821 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
1822 struct list_head *preloaded_csets)
1825 struct css_set *src_cset;
1827 lockdep_assert_held(&cgroup_mutex);
1829 /* look up the dst cset for each src cset and link it to src */
1830 list_for_each_entry(src_cset, preloaded_csets, mg_preload_node) {
1831 struct css_set *dst_cset;
1833 dst_cset = find_css_set(src_cset, dst_cgrp);
1837 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
1838 src_cset->mg_dst_cset = dst_cset;
1840 if (list_empty(&dst_cset->mg_preload_node))
1841 list_add(&dst_cset->mg_preload_node, &csets);
1843 put_css_set(dst_cset, false);
1846 list_splice(&csets, preloaded_csets);
1849 cgroup_migrate_finish(&csets);
1854 * cgroup_migrate - migrate a process or task to a cgroup
1855 * @cgrp: the destination cgroup
1856 * @leader: the leader of the process or the task to migrate
1857 * @threadgroup: whether @leader points to the whole process or a single task
1859 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
1860 * process, the caller must be holding threadgroup_lock of @leader. The
1861 * caller is also responsible for invoking cgroup_migrate_add_src() and
1862 * cgroup_migrate_prepare_dst() on the targets before invoking this
1863 * function and following up with cgroup_migrate_finish().
1865 * As long as a controller's ->can_attach() doesn't fail, this function is
1866 * guaranteed to succeed. This means that, excluding ->can_attach()
1867 * failure, when migrating multiple targets, the success or failure can be
1868 * decided for all targets by invoking group_migrate_prepare_dst() before
1869 * actually starting migrating.
1871 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
1874 struct cgroup_taskset tset = {
1875 .src_csets = LIST_HEAD_INIT(tset.src_csets),
1876 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
1877 .csets = &tset.src_csets,
1879 struct cgroup_subsys_state *css, *failed_css = NULL;
1880 struct css_set *cset, *tmp_cset;
1881 struct task_struct *task, *tmp_task;
1885 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1886 * already PF_EXITING could be freed from underneath us unless we
1887 * take an rcu_read_lock.
1889 down_write(&css_set_rwsem);
1893 /* @task either already exited or can't exit until the end */
1894 if (task->flags & PF_EXITING)
1897 /* leave @task alone if post_fork() hasn't linked it yet */
1898 if (list_empty(&task->cg_list))
1901 cset = task_css_set(task);
1902 if (!cset->mg_src_cgrp)
1905 list_move(&task->cg_list, &cset->mg_tasks);
1906 list_move(&cset->mg_node, &tset.src_csets);
1907 list_move(&cset->mg_dst_cset->mg_node, &tset.dst_csets);
1911 } while_each_thread(leader, task);
1913 up_write(&css_set_rwsem);
1915 /* methods shouldn't be called if no task is actually migrating */
1916 if (list_empty(&tset.src_csets))
1919 /* check that we can legitimately attach to the cgroup */
1920 for_each_css(css, i, cgrp) {
1921 if (css->ss->can_attach) {
1922 ret = css->ss->can_attach(css, &tset);
1925 goto out_cancel_attach;
1931 * Now that we're guaranteed success, proceed to move all tasks to
1932 * the new cgroup. There are no failure cases after here, so this
1933 * is the commit point.
1935 down_write(&css_set_rwsem);
1936 list_for_each_entry(cset, &tset.src_csets, mg_node) {
1937 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
1938 cgroup_task_migrate(cset->mg_src_cgrp, task,
1941 up_write(&css_set_rwsem);
1944 * Migration is committed, all target tasks are now on dst_csets.
1945 * Nothing is sensitive to fork() after this point. Notify
1946 * controllers that migration is complete.
1948 tset.csets = &tset.dst_csets;
1950 for_each_css(css, i, cgrp)
1951 if (css->ss->attach)
1952 css->ss->attach(css, &tset);
1955 goto out_release_tset;
1958 for_each_css(css, i, cgrp) {
1959 if (css == failed_css)
1961 if (css->ss->cancel_attach)
1962 css->ss->cancel_attach(css, &tset);
1965 down_write(&css_set_rwsem);
1966 list_splice_init(&tset.dst_csets, &tset.src_csets);
1967 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
1968 list_splice_init(&cset->mg_tasks, &cset->tasks);
1969 list_del_init(&cset->mg_node);
1971 up_write(&css_set_rwsem);
1976 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1977 * @dst_cgrp: the cgroup to attach to
1978 * @leader: the task or the leader of the threadgroup to be attached
1979 * @threadgroup: attach the whole threadgroup?
1981 * Call holding cgroup_mutex and threadgroup_lock of @leader.
1983 static int cgroup_attach_task(struct cgroup *dst_cgrp,
1984 struct task_struct *leader, bool threadgroup)
1986 LIST_HEAD(preloaded_csets);
1987 struct task_struct *task;
1990 /* look up all src csets */
1991 down_read(&css_set_rwsem);
1995 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
1999 } while_each_thread(leader, task);
2001 up_read(&css_set_rwsem);
2003 /* prepare dst csets and commit */
2004 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2006 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2008 cgroup_migrate_finish(&preloaded_csets);
2013 * Find the task_struct of the task to attach by vpid and pass it along to the
2014 * function to attach either it or all tasks in its threadgroup. Will lock
2015 * cgroup_mutex and threadgroup.
2017 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2019 struct task_struct *tsk;
2020 const struct cred *cred = current_cred(), *tcred;
2023 if (!cgroup_lock_live_group(cgrp))
2029 tsk = find_task_by_vpid(pid);
2033 goto out_unlock_cgroup;
2036 * even if we're attaching all tasks in the thread group, we
2037 * only need to check permissions on one of them.
2039 tcred = __task_cred(tsk);
2040 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2041 !uid_eq(cred->euid, tcred->uid) &&
2042 !uid_eq(cred->euid, tcred->suid)) {
2045 goto out_unlock_cgroup;
2051 tsk = tsk->group_leader;
2054 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2055 * trapped in a cpuset, or RT worker may be born in a cgroup
2056 * with no rt_runtime allocated. Just say no.
2058 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2061 goto out_unlock_cgroup;
2064 get_task_struct(tsk);
2067 threadgroup_lock(tsk);
2069 if (!thread_group_leader(tsk)) {
2071 * a race with de_thread from another thread's exec()
2072 * may strip us of our leadership, if this happens,
2073 * there is no choice but to throw this task away and
2074 * try again; this is
2075 * "double-double-toil-and-trouble-check locking".
2077 threadgroup_unlock(tsk);
2078 put_task_struct(tsk);
2079 goto retry_find_task;
2083 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2085 threadgroup_unlock(tsk);
2087 put_task_struct(tsk);
2089 mutex_unlock(&cgroup_mutex);
2094 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2095 * @from: attach to all cgroups of a given task
2096 * @tsk: the task to be attached
2098 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2100 struct cgroupfs_root *root;
2103 mutex_lock(&cgroup_mutex);
2104 for_each_active_root(root) {
2105 struct cgroup *from_cgrp;
2107 down_read(&css_set_rwsem);
2108 from_cgrp = task_cgroup_from_root(from, root);
2109 up_read(&css_set_rwsem);
2111 retval = cgroup_attach_task(from_cgrp, tsk, false);
2115 mutex_unlock(&cgroup_mutex);
2119 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2121 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2122 struct cftype *cft, u64 pid)
2124 return attach_task_by_pid(css->cgroup, pid, false);
2127 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2128 struct cftype *cft, u64 tgid)
2130 return attach_task_by_pid(css->cgroup, tgid, true);
2133 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2134 struct cftype *cft, const char *buffer)
2136 struct cgroupfs_root *root = css->cgroup->root;
2138 BUILD_BUG_ON(sizeof(root->release_agent_path) < PATH_MAX);
2139 if (!cgroup_lock_live_group(css->cgroup))
2141 spin_lock(&release_agent_path_lock);
2142 strlcpy(root->release_agent_path, buffer,
2143 sizeof(root->release_agent_path));
2144 spin_unlock(&release_agent_path_lock);
2145 mutex_unlock(&cgroup_mutex);
2149 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2151 struct cgroup *cgrp = seq_css(seq)->cgroup;
2153 if (!cgroup_lock_live_group(cgrp))
2155 seq_puts(seq, cgrp->root->release_agent_path);
2156 seq_putc(seq, '\n');
2157 mutex_unlock(&cgroup_mutex);
2161 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2163 struct cgroup *cgrp = seq_css(seq)->cgroup;
2165 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2169 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2170 size_t nbytes, loff_t off)
2172 struct cgroup *cgrp = of->kn->parent->priv;
2173 struct cftype *cft = of->kn->priv;
2174 struct cgroup_subsys_state *css;
2178 * kernfs guarantees that a file isn't deleted with operations in
2179 * flight, which means that the matching css is and stays alive and
2180 * doesn't need to be pinned. The RCU locking is not necessary
2181 * either. It's just for the convenience of using cgroup_css().
2184 css = cgroup_css(cgrp, cft->ss);
2187 if (cft->write_string) {
2188 ret = cft->write_string(css, cft, strstrip(buf));
2189 } else if (cft->write_u64) {
2190 unsigned long long v;
2191 ret = kstrtoull(buf, 0, &v);
2193 ret = cft->write_u64(css, cft, v);
2194 } else if (cft->write_s64) {
2196 ret = kstrtoll(buf, 0, &v);
2198 ret = cft->write_s64(css, cft, v);
2199 } else if (cft->trigger) {
2200 ret = cft->trigger(css, (unsigned int)cft->private);
2205 return ret ?: nbytes;
2208 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2210 return seq_cft(seq)->seq_start(seq, ppos);
2213 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2215 return seq_cft(seq)->seq_next(seq, v, ppos);
2218 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2220 seq_cft(seq)->seq_stop(seq, v);
2223 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2225 struct cftype *cft = seq_cft(m);
2226 struct cgroup_subsys_state *css = seq_css(m);
2229 return cft->seq_show(m, arg);
2232 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2233 else if (cft->read_s64)
2234 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2240 static struct kernfs_ops cgroup_kf_single_ops = {
2241 .atomic_write_len = PAGE_SIZE,
2242 .write = cgroup_file_write,
2243 .seq_show = cgroup_seqfile_show,
2246 static struct kernfs_ops cgroup_kf_ops = {
2247 .atomic_write_len = PAGE_SIZE,
2248 .write = cgroup_file_write,
2249 .seq_start = cgroup_seqfile_start,
2250 .seq_next = cgroup_seqfile_next,
2251 .seq_stop = cgroup_seqfile_stop,
2252 .seq_show = cgroup_seqfile_show,
2256 * cgroup_rename - Only allow simple rename of directories in place.
2258 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2259 const char *new_name_str)
2261 struct cgroup *cgrp = kn->priv;
2264 if (kernfs_type(kn) != KERNFS_DIR)
2266 if (kn->parent != new_parent)
2270 * This isn't a proper migration and its usefulness is very
2271 * limited. Disallow if sane_behavior.
2273 if (cgroup_sane_behavior(cgrp))
2276 mutex_lock(&cgroup_tree_mutex);
2277 mutex_lock(&cgroup_mutex);
2279 ret = kernfs_rename(kn, new_parent, new_name_str);
2281 mutex_unlock(&cgroup_mutex);
2282 mutex_unlock(&cgroup_tree_mutex);
2286 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2288 char name[CGROUP_FILE_NAME_MAX];
2289 struct kernfs_node *kn;
2290 struct lock_class_key *key = NULL;
2292 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2293 key = &cft->lockdep_key;
2295 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2296 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2298 return PTR_ERR_OR_ZERO(kn);
2302 * cgroup_addrm_files - add or remove files to a cgroup directory
2303 * @cgrp: the target cgroup
2304 * @cfts: array of cftypes to be added
2305 * @is_add: whether to add or remove
2307 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2308 * For removals, this function never fails. If addition fails, this
2309 * function doesn't remove files already added. The caller is responsible
2312 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2318 lockdep_assert_held(&cgroup_tree_mutex);
2320 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2321 /* does cft->flags tell us to skip this file on @cgrp? */
2322 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2324 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2326 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2330 ret = cgroup_add_file(cgrp, cft);
2332 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2337 cgroup_rm_file(cgrp, cft);
2343 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2346 struct cgroup_subsys *ss = cfts[0].ss;
2347 struct cgroup *root = &ss->root->top_cgroup;
2348 struct cgroup_subsys_state *css;
2351 lockdep_assert_held(&cgroup_tree_mutex);
2353 /* don't bother if @ss isn't attached */
2354 if (ss->root == &cgroup_dummy_root)
2357 /* add/rm files for all cgroups created before */
2358 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2359 struct cgroup *cgrp = css->cgroup;
2361 if (cgroup_is_dead(cgrp))
2364 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2370 kernfs_activate(root->kn);
2374 static void cgroup_exit_cftypes(struct cftype *cfts)
2378 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2379 /* free copy for custom atomic_write_len, see init_cftypes() */
2380 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2387 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2391 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2392 struct kernfs_ops *kf_ops;
2394 WARN_ON(cft->ss || cft->kf_ops);
2397 kf_ops = &cgroup_kf_ops;
2399 kf_ops = &cgroup_kf_single_ops;
2402 * Ugh... if @cft wants a custom max_write_len, we need to
2403 * make a copy of kf_ops to set its atomic_write_len.
2405 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2406 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
2408 cgroup_exit_cftypes(cfts);
2411 kf_ops->atomic_write_len = cft->max_write_len;
2414 cft->kf_ops = kf_ops;
2421 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
2423 lockdep_assert_held(&cgroup_tree_mutex);
2425 if (!cfts || !cfts[0].ss)
2428 list_del(&cfts->node);
2429 cgroup_apply_cftypes(cfts, false);
2430 cgroup_exit_cftypes(cfts);
2435 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2436 * @cfts: zero-length name terminated array of cftypes
2438 * Unregister @cfts. Files described by @cfts are removed from all
2439 * existing cgroups and all future cgroups won't have them either. This
2440 * function can be called anytime whether @cfts' subsys is attached or not.
2442 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2445 int cgroup_rm_cftypes(struct cftype *cfts)
2449 mutex_lock(&cgroup_tree_mutex);
2450 ret = cgroup_rm_cftypes_locked(cfts);
2451 mutex_unlock(&cgroup_tree_mutex);
2456 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2457 * @ss: target cgroup subsystem
2458 * @cfts: zero-length name terminated array of cftypes
2460 * Register @cfts to @ss. Files described by @cfts are created for all
2461 * existing cgroups to which @ss is attached and all future cgroups will
2462 * have them too. This function can be called anytime whether @ss is
2465 * Returns 0 on successful registration, -errno on failure. Note that this
2466 * function currently returns 0 as long as @cfts registration is successful
2467 * even if some file creation attempts on existing cgroups fail.
2469 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2473 if (!cfts || cfts[0].name[0] == '\0')
2476 ret = cgroup_init_cftypes(ss, cfts);
2480 mutex_lock(&cgroup_tree_mutex);
2482 list_add_tail(&cfts->node, &ss->cfts);
2483 ret = cgroup_apply_cftypes(cfts, true);
2485 cgroup_rm_cftypes_locked(cfts);
2487 mutex_unlock(&cgroup_tree_mutex);
2492 * cgroup_task_count - count the number of tasks in a cgroup.
2493 * @cgrp: the cgroup in question
2495 * Return the number of tasks in the cgroup.
2497 static int cgroup_task_count(const struct cgroup *cgrp)
2500 struct cgrp_cset_link *link;
2502 down_read(&css_set_rwsem);
2503 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2504 count += atomic_read(&link->cset->refcount);
2505 up_read(&css_set_rwsem);
2510 * css_next_child - find the next child of a given css
2511 * @pos_css: the current position (%NULL to initiate traversal)
2512 * @parent_css: css whose children to walk
2514 * This function returns the next child of @parent_css and should be called
2515 * under either cgroup_mutex or RCU read lock. The only requirement is
2516 * that @parent_css and @pos_css are accessible. The next sibling is
2517 * guaranteed to be returned regardless of their states.
2519 struct cgroup_subsys_state *
2520 css_next_child(struct cgroup_subsys_state *pos_css,
2521 struct cgroup_subsys_state *parent_css)
2523 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2524 struct cgroup *cgrp = parent_css->cgroup;
2525 struct cgroup *next;
2527 cgroup_assert_mutexes_or_rcu_locked();
2530 * @pos could already have been removed. Once a cgroup is removed,
2531 * its ->sibling.next is no longer updated when its next sibling
2532 * changes. As CGRP_DEAD assertion is serialized and happens
2533 * before the cgroup is taken off the ->sibling list, if we see it
2534 * unasserted, it's guaranteed that the next sibling hasn't
2535 * finished its grace period even if it's already removed, and thus
2536 * safe to dereference from this RCU critical section. If
2537 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2538 * to be visible as %true here.
2540 * If @pos is dead, its next pointer can't be dereferenced;
2541 * however, as each cgroup is given a monotonically increasing
2542 * unique serial number and always appended to the sibling list,
2543 * the next one can be found by walking the parent's children until
2544 * we see a cgroup with higher serial number than @pos's. While
2545 * this path can be slower, it's taken only when either the current
2546 * cgroup is removed or iteration and removal race.
2549 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2550 } else if (likely(!cgroup_is_dead(pos))) {
2551 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2553 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2554 if (next->serial_nr > pos->serial_nr)
2558 if (&next->sibling == &cgrp->children)
2561 return cgroup_css(next, parent_css->ss);
2565 * css_next_descendant_pre - find the next descendant for pre-order walk
2566 * @pos: the current position (%NULL to initiate traversal)
2567 * @root: css whose descendants to walk
2569 * To be used by css_for_each_descendant_pre(). Find the next descendant
2570 * to visit for pre-order traversal of @root's descendants. @root is
2571 * included in the iteration and the first node to be visited.
2573 * While this function requires cgroup_mutex or RCU read locking, it
2574 * doesn't require the whole traversal to be contained in a single critical
2575 * section. This function will return the correct next descendant as long
2576 * as both @pos and @root are accessible and @pos is a descendant of @root.
2578 struct cgroup_subsys_state *
2579 css_next_descendant_pre(struct cgroup_subsys_state *pos,
2580 struct cgroup_subsys_state *root)
2582 struct cgroup_subsys_state *next;
2584 cgroup_assert_mutexes_or_rcu_locked();
2586 /* if first iteration, visit @root */
2590 /* visit the first child if exists */
2591 next = css_next_child(NULL, pos);
2595 /* no child, visit my or the closest ancestor's next sibling */
2596 while (pos != root) {
2597 next = css_next_child(pos, css_parent(pos));
2600 pos = css_parent(pos);
2607 * css_rightmost_descendant - return the rightmost descendant of a css
2608 * @pos: css of interest
2610 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2611 * is returned. This can be used during pre-order traversal to skip
2614 * While this function requires cgroup_mutex or RCU read locking, it
2615 * doesn't require the whole traversal to be contained in a single critical
2616 * section. This function will return the correct rightmost descendant as
2617 * long as @pos is accessible.
2619 struct cgroup_subsys_state *
2620 css_rightmost_descendant(struct cgroup_subsys_state *pos)
2622 struct cgroup_subsys_state *last, *tmp;
2624 cgroup_assert_mutexes_or_rcu_locked();
2628 /* ->prev isn't RCU safe, walk ->next till the end */
2630 css_for_each_child(tmp, last)
2637 static struct cgroup_subsys_state *
2638 css_leftmost_descendant(struct cgroup_subsys_state *pos)
2640 struct cgroup_subsys_state *last;
2644 pos = css_next_child(NULL, pos);
2651 * css_next_descendant_post - find the next descendant for post-order walk
2652 * @pos: the current position (%NULL to initiate traversal)
2653 * @root: css whose descendants to walk
2655 * To be used by css_for_each_descendant_post(). Find the next descendant
2656 * to visit for post-order traversal of @root's descendants. @root is
2657 * included in the iteration and the last node to be visited.
2659 * While this function requires cgroup_mutex or RCU read locking, it
2660 * doesn't require the whole traversal to be contained in a single critical
2661 * section. This function will return the correct next descendant as long
2662 * as both @pos and @cgroup are accessible and @pos is a descendant of
2665 struct cgroup_subsys_state *
2666 css_next_descendant_post(struct cgroup_subsys_state *pos,
2667 struct cgroup_subsys_state *root)
2669 struct cgroup_subsys_state *next;
2671 cgroup_assert_mutexes_or_rcu_locked();
2673 /* if first iteration, visit leftmost descendant which may be @root */
2675 return css_leftmost_descendant(root);
2677 /* if we visited @root, we're done */
2681 /* if there's an unvisited sibling, visit its leftmost descendant */
2682 next = css_next_child(pos, css_parent(pos));
2684 return css_leftmost_descendant(next);
2686 /* no sibling left, visit parent */
2687 return css_parent(pos);
2691 * css_advance_task_iter - advance a task itererator to the next css_set
2692 * @it: the iterator to advance
2694 * Advance @it to the next css_set to walk.
2696 static void css_advance_task_iter(struct css_task_iter *it)
2698 struct list_head *l = it->cset_link;
2699 struct cgrp_cset_link *link;
2700 struct css_set *cset;
2702 /* Advance to the next non-empty css_set */
2705 if (l == &it->origin_css->cgroup->cset_links) {
2706 it->cset_link = NULL;
2709 link = list_entry(l, struct cgrp_cset_link, cset_link);
2711 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
2715 if (!list_empty(&cset->tasks))
2716 it->task = cset->tasks.next;
2718 it->task = cset->mg_tasks.next;
2722 * css_task_iter_start - initiate task iteration
2723 * @css: the css to walk tasks of
2724 * @it: the task iterator to use
2726 * Initiate iteration through the tasks of @css. The caller can call
2727 * css_task_iter_next() to walk through the tasks until the function
2728 * returns NULL. On completion of iteration, css_task_iter_end() must be
2731 * Note that this function acquires a lock which is released when the
2732 * iteration finishes. The caller can't sleep while iteration is in
2735 void css_task_iter_start(struct cgroup_subsys_state *css,
2736 struct css_task_iter *it)
2737 __acquires(css_set_rwsem)
2739 /* no one should try to iterate before mounting cgroups */
2740 WARN_ON_ONCE(!use_task_css_set_links);
2742 down_read(&css_set_rwsem);
2744 it->origin_css = css;
2745 it->cset_link = &css->cgroup->cset_links;
2747 css_advance_task_iter(it);
2751 * css_task_iter_next - return the next task for the iterator
2752 * @it: the task iterator being iterated
2754 * The "next" function for task iteration. @it should have been
2755 * initialized via css_task_iter_start(). Returns NULL when the iteration
2758 struct task_struct *css_task_iter_next(struct css_task_iter *it)
2760 struct task_struct *res;
2761 struct list_head *l = it->task;
2762 struct cgrp_cset_link *link = list_entry(it->cset_link,
2763 struct cgrp_cset_link, cset_link);
2765 /* If the iterator cg is NULL, we have no tasks */
2768 res = list_entry(l, struct task_struct, cg_list);
2771 * Advance iterator to find next entry. cset->tasks is consumed
2772 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
2777 if (l == &link->cset->tasks)
2778 l = link->cset->mg_tasks.next;
2780 if (l == &link->cset->mg_tasks)
2781 css_advance_task_iter(it);
2789 * css_task_iter_end - finish task iteration
2790 * @it: the task iterator to finish
2792 * Finish task iteration started by css_task_iter_start().
2794 void css_task_iter_end(struct css_task_iter *it)
2795 __releases(css_set_rwsem)
2797 up_read(&css_set_rwsem);
2801 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
2802 * @to: cgroup to which the tasks will be moved
2803 * @from: cgroup in which the tasks currently reside
2805 * Locking rules between cgroup_post_fork() and the migration path
2806 * guarantee that, if a task is forking while being migrated, the new child
2807 * is guaranteed to be either visible in the source cgroup after the
2808 * parent's migration is complete or put into the target cgroup. No task
2809 * can slip out of migration through forking.
2811 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
2813 LIST_HEAD(preloaded_csets);
2814 struct cgrp_cset_link *link;
2815 struct css_task_iter it;
2816 struct task_struct *task;
2819 mutex_lock(&cgroup_mutex);
2821 /* all tasks in @from are being moved, all csets are source */
2822 down_read(&css_set_rwsem);
2823 list_for_each_entry(link, &from->cset_links, cset_link)
2824 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
2825 up_read(&css_set_rwsem);
2827 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
2832 * Migrate tasks one-by-one until @form is empty. This fails iff
2833 * ->can_attach() fails.
2836 css_task_iter_start(&from->dummy_css, &it);
2837 task = css_task_iter_next(&it);
2839 get_task_struct(task);
2840 css_task_iter_end(&it);
2843 ret = cgroup_migrate(to, task, false);
2844 put_task_struct(task);
2846 } while (task && !ret);
2848 cgroup_migrate_finish(&preloaded_csets);
2849 mutex_unlock(&cgroup_mutex);
2854 * Stuff for reading the 'tasks'/'procs' files.
2856 * Reading this file can return large amounts of data if a cgroup has
2857 * *lots* of attached tasks. So it may need several calls to read(),
2858 * but we cannot guarantee that the information we produce is correct
2859 * unless we produce it entirely atomically.
2863 /* which pidlist file are we talking about? */
2864 enum cgroup_filetype {
2870 * A pidlist is a list of pids that virtually represents the contents of one
2871 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
2872 * a pair (one each for procs, tasks) for each pid namespace that's relevant
2875 struct cgroup_pidlist {
2877 * used to find which pidlist is wanted. doesn't change as long as
2878 * this particular list stays in the list.
2880 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
2883 /* how many elements the above list has */
2885 /* each of these stored in a list by its cgroup */
2886 struct list_head links;
2887 /* pointer to the cgroup we belong to, for list removal purposes */
2888 struct cgroup *owner;
2889 /* for delayed destruction */
2890 struct delayed_work destroy_dwork;
2894 * The following two functions "fix" the issue where there are more pids
2895 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
2896 * TODO: replace with a kernel-wide solution to this problem
2898 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
2899 static void *pidlist_allocate(int count)
2901 if (PIDLIST_TOO_LARGE(count))
2902 return vmalloc(count * sizeof(pid_t));
2904 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
2907 static void pidlist_free(void *p)
2909 if (is_vmalloc_addr(p))
2916 * Used to destroy all pidlists lingering waiting for destroy timer. None
2917 * should be left afterwards.
2919 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
2921 struct cgroup_pidlist *l, *tmp_l;
2923 mutex_lock(&cgrp->pidlist_mutex);
2924 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
2925 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
2926 mutex_unlock(&cgrp->pidlist_mutex);
2928 flush_workqueue(cgroup_pidlist_destroy_wq);
2929 BUG_ON(!list_empty(&cgrp->pidlists));
2932 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
2934 struct delayed_work *dwork = to_delayed_work(work);
2935 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
2937 struct cgroup_pidlist *tofree = NULL;
2939 mutex_lock(&l->owner->pidlist_mutex);
2942 * Destroy iff we didn't get queued again. The state won't change
2943 * as destroy_dwork can only be queued while locked.
2945 if (!delayed_work_pending(dwork)) {
2946 list_del(&l->links);
2947 pidlist_free(l->list);
2948 put_pid_ns(l->key.ns);
2952 mutex_unlock(&l->owner->pidlist_mutex);
2957 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
2958 * Returns the number of unique elements.
2960 static int pidlist_uniq(pid_t *list, int length)
2965 * we presume the 0th element is unique, so i starts at 1. trivial
2966 * edge cases first; no work needs to be done for either
2968 if (length == 0 || length == 1)
2970 /* src and dest walk down the list; dest counts unique elements */
2971 for (src = 1; src < length; src++) {
2972 /* find next unique element */
2973 while (list[src] == list[src-1]) {
2978 /* dest always points to where the next unique element goes */
2979 list[dest] = list[src];
2987 * The two pid files - task and cgroup.procs - guaranteed that the result
2988 * is sorted, which forced this whole pidlist fiasco. As pid order is
2989 * different per namespace, each namespace needs differently sorted list,
2990 * making it impossible to use, for example, single rbtree of member tasks
2991 * sorted by task pointer. As pidlists can be fairly large, allocating one
2992 * per open file is dangerous, so cgroup had to implement shared pool of
2993 * pidlists keyed by cgroup and namespace.
2995 * All this extra complexity was caused by the original implementation
2996 * committing to an entirely unnecessary property. In the long term, we
2997 * want to do away with it. Explicitly scramble sort order if
2998 * sane_behavior so that no such expectation exists in the new interface.
3000 * Scrambling is done by swapping every two consecutive bits, which is
3001 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3003 static pid_t pid_fry(pid_t pid)
3005 unsigned a = pid & 0x55555555;
3006 unsigned b = pid & 0xAAAAAAAA;
3008 return (a << 1) | (b >> 1);
3011 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3013 if (cgroup_sane_behavior(cgrp))
3014 return pid_fry(pid);
3019 static int cmppid(const void *a, const void *b)
3021 return *(pid_t *)a - *(pid_t *)b;
3024 static int fried_cmppid(const void *a, const void *b)
3026 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3029 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3030 enum cgroup_filetype type)
3032 struct cgroup_pidlist *l;
3033 /* don't need task_nsproxy() if we're looking at ourself */
3034 struct pid_namespace *ns = task_active_pid_ns(current);
3036 lockdep_assert_held(&cgrp->pidlist_mutex);
3038 list_for_each_entry(l, &cgrp->pidlists, links)
3039 if (l->key.type == type && l->key.ns == ns)
3045 * find the appropriate pidlist for our purpose (given procs vs tasks)
3046 * returns with the lock on that pidlist already held, and takes care
3047 * of the use count, or returns NULL with no locks held if we're out of
3050 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3051 enum cgroup_filetype type)
3053 struct cgroup_pidlist *l;
3055 lockdep_assert_held(&cgrp->pidlist_mutex);
3057 l = cgroup_pidlist_find(cgrp, type);
3061 /* entry not found; create a new one */
3062 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3066 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3068 /* don't need task_nsproxy() if we're looking at ourself */
3069 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3071 list_add(&l->links, &cgrp->pidlists);
3076 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3078 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3079 struct cgroup_pidlist **lp)
3083 int pid, n = 0; /* used for populating the array */
3084 struct css_task_iter it;
3085 struct task_struct *tsk;
3086 struct cgroup_pidlist *l;
3088 lockdep_assert_held(&cgrp->pidlist_mutex);
3091 * If cgroup gets more users after we read count, we won't have
3092 * enough space - tough. This race is indistinguishable to the
3093 * caller from the case that the additional cgroup users didn't
3094 * show up until sometime later on.
3096 length = cgroup_task_count(cgrp);
3097 array = pidlist_allocate(length);
3100 /* now, populate the array */
3101 css_task_iter_start(&cgrp->dummy_css, &it);
3102 while ((tsk = css_task_iter_next(&it))) {
3103 if (unlikely(n == length))
3105 /* get tgid or pid for procs or tasks file respectively */
3106 if (type == CGROUP_FILE_PROCS)
3107 pid = task_tgid_vnr(tsk);
3109 pid = task_pid_vnr(tsk);
3110 if (pid > 0) /* make sure to only use valid results */
3113 css_task_iter_end(&it);
3115 /* now sort & (if procs) strip out duplicates */
3116 if (cgroup_sane_behavior(cgrp))
3117 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3119 sort(array, length, sizeof(pid_t), cmppid, NULL);
3120 if (type == CGROUP_FILE_PROCS)
3121 length = pidlist_uniq(array, length);
3123 l = cgroup_pidlist_find_create(cgrp, type);
3125 mutex_unlock(&cgrp->pidlist_mutex);
3126 pidlist_free(array);
3130 /* store array, freeing old if necessary */
3131 pidlist_free(l->list);
3139 * cgroupstats_build - build and fill cgroupstats
3140 * @stats: cgroupstats to fill information into
3141 * @dentry: A dentry entry belonging to the cgroup for which stats have
3144 * Build and fill cgroupstats so that taskstats can export it to user
3147 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3149 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3150 struct cgroup *cgrp;
3151 struct css_task_iter it;
3152 struct task_struct *tsk;
3154 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3155 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3156 kernfs_type(kn) != KERNFS_DIR)
3159 mutex_lock(&cgroup_mutex);
3162 * We aren't being called from kernfs and there's no guarantee on
3163 * @kn->priv's validity. For this and css_tryget_from_dir(),
3164 * @kn->priv is RCU safe. Let's do the RCU dancing.
3167 cgrp = rcu_dereference(kn->priv);
3168 if (!cgrp || cgroup_is_dead(cgrp)) {
3170 mutex_unlock(&cgroup_mutex);
3175 css_task_iter_start(&cgrp->dummy_css, &it);
3176 while ((tsk = css_task_iter_next(&it))) {
3177 switch (tsk->state) {
3179 stats->nr_running++;
3181 case TASK_INTERRUPTIBLE:
3182 stats->nr_sleeping++;
3184 case TASK_UNINTERRUPTIBLE:
3185 stats->nr_uninterruptible++;
3188 stats->nr_stopped++;
3191 if (delayacct_is_task_waiting_on_io(tsk))
3192 stats->nr_io_wait++;
3196 css_task_iter_end(&it);
3198 mutex_unlock(&cgroup_mutex);
3204 * seq_file methods for the tasks/procs files. The seq_file position is the
3205 * next pid to display; the seq_file iterator is a pointer to the pid
3206 * in the cgroup->l->list array.
3209 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3212 * Initially we receive a position value that corresponds to
3213 * one more than the last pid shown (or 0 on the first call or
3214 * after a seek to the start). Use a binary-search to find the
3215 * next pid to display, if any
3217 struct kernfs_open_file *of = s->private;
3218 struct cgroup *cgrp = seq_css(s)->cgroup;
3219 struct cgroup_pidlist *l;
3220 enum cgroup_filetype type = seq_cft(s)->private;
3221 int index = 0, pid = *pos;
3224 mutex_lock(&cgrp->pidlist_mutex);
3227 * !NULL @of->priv indicates that this isn't the first start()
3228 * after open. If the matching pidlist is around, we can use that.
3229 * Look for it. Note that @of->priv can't be used directly. It
3230 * could already have been destroyed.
3233 of->priv = cgroup_pidlist_find(cgrp, type);
3236 * Either this is the first start() after open or the matching
3237 * pidlist has been destroyed inbetween. Create a new one.
3240 ret = pidlist_array_load(cgrp, type,
3241 (struct cgroup_pidlist **)&of->priv);
3243 return ERR_PTR(ret);
3248 int end = l->length;
3250 while (index < end) {
3251 int mid = (index + end) / 2;
3252 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3255 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3261 /* If we're off the end of the array, we're done */
3262 if (index >= l->length)
3264 /* Update the abstract position to be the actual pid that we found */
3265 iter = l->list + index;
3266 *pos = cgroup_pid_fry(cgrp, *iter);
3270 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3272 struct kernfs_open_file *of = s->private;
3273 struct cgroup_pidlist *l = of->priv;
3276 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3277 CGROUP_PIDLIST_DESTROY_DELAY);
3278 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3281 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3283 struct kernfs_open_file *of = s->private;
3284 struct cgroup_pidlist *l = of->priv;
3286 pid_t *end = l->list + l->length;
3288 * Advance to the next pid in the array. If this goes off the
3295 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3300 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3302 return seq_printf(s, "%d\n", *(int *)v);
3306 * seq_operations functions for iterating on pidlists through seq_file -
3307 * independent of whether it's tasks or procs
3309 static const struct seq_operations cgroup_pidlist_seq_operations = {
3310 .start = cgroup_pidlist_start,
3311 .stop = cgroup_pidlist_stop,
3312 .next = cgroup_pidlist_next,
3313 .show = cgroup_pidlist_show,
3316 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3319 return notify_on_release(css->cgroup);
3322 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3323 struct cftype *cft, u64 val)
3325 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3327 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3329 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3333 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3336 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3339 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3340 struct cftype *cft, u64 val)
3343 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3345 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3349 static struct cftype cgroup_base_files[] = {
3351 .name = "cgroup.procs",
3352 .seq_start = cgroup_pidlist_start,
3353 .seq_next = cgroup_pidlist_next,
3354 .seq_stop = cgroup_pidlist_stop,
3355 .seq_show = cgroup_pidlist_show,
3356 .private = CGROUP_FILE_PROCS,
3357 .write_u64 = cgroup_procs_write,
3358 .mode = S_IRUGO | S_IWUSR,
3361 .name = "cgroup.clone_children",
3362 .flags = CFTYPE_INSANE,
3363 .read_u64 = cgroup_clone_children_read,
3364 .write_u64 = cgroup_clone_children_write,
3367 .name = "cgroup.sane_behavior",
3368 .flags = CFTYPE_ONLY_ON_ROOT,
3369 .seq_show = cgroup_sane_behavior_show,
3373 * Historical crazy stuff. These don't have "cgroup." prefix and
3374 * don't exist if sane_behavior. If you're depending on these, be
3375 * prepared to be burned.
3379 .flags = CFTYPE_INSANE, /* use "procs" instead */
3380 .seq_start = cgroup_pidlist_start,
3381 .seq_next = cgroup_pidlist_next,
3382 .seq_stop = cgroup_pidlist_stop,
3383 .seq_show = cgroup_pidlist_show,
3384 .private = CGROUP_FILE_TASKS,
3385 .write_u64 = cgroup_tasks_write,
3386 .mode = S_IRUGO | S_IWUSR,
3389 .name = "notify_on_release",
3390 .flags = CFTYPE_INSANE,
3391 .read_u64 = cgroup_read_notify_on_release,
3392 .write_u64 = cgroup_write_notify_on_release,
3395 .name = "release_agent",
3396 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3397 .seq_show = cgroup_release_agent_show,
3398 .write_string = cgroup_release_agent_write,
3399 .max_write_len = PATH_MAX - 1,
3405 * cgroup_populate_dir - create subsys files in a cgroup directory
3406 * @cgrp: target cgroup
3407 * @subsys_mask: mask of the subsystem ids whose files should be added
3409 * On failure, no file is added.
3411 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3413 struct cgroup_subsys *ss;
3416 /* process cftsets of each subsystem */
3417 for_each_subsys(ss, i) {
3418 struct cftype *cfts;
3420 if (!test_bit(i, &subsys_mask))
3423 list_for_each_entry(cfts, &ss->cfts, node) {
3424 ret = cgroup_addrm_files(cgrp, cfts, true);
3431 cgroup_clear_dir(cgrp, subsys_mask);
3436 * css destruction is four-stage process.
3438 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3439 * Implemented in kill_css().
3441 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3442 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3443 * by invoking offline_css(). After offlining, the base ref is put.
3444 * Implemented in css_killed_work_fn().
3446 * 3. When the percpu_ref reaches zero, the only possible remaining
3447 * accessors are inside RCU read sections. css_release() schedules the
3450 * 4. After the grace period, the css can be freed. Implemented in
3451 * css_free_work_fn().
3453 * It is actually hairier because both step 2 and 4 require process context
3454 * and thus involve punting to css->destroy_work adding two additional
3455 * steps to the already complex sequence.
3457 static void css_free_work_fn(struct work_struct *work)
3459 struct cgroup_subsys_state *css =
3460 container_of(work, struct cgroup_subsys_state, destroy_work);
3461 struct cgroup *cgrp = css->cgroup;
3464 css_put(css->parent);
3466 css->ss->css_free(css);
3470 static void css_free_rcu_fn(struct rcu_head *rcu_head)
3472 struct cgroup_subsys_state *css =
3473 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
3475 INIT_WORK(&css->destroy_work, css_free_work_fn);
3476 queue_work(cgroup_destroy_wq, &css->destroy_work);
3479 static void css_release(struct percpu_ref *ref)
3481 struct cgroup_subsys_state *css =
3482 container_of(ref, struct cgroup_subsys_state, refcnt);
3484 rcu_assign_pointer(css->cgroup->subsys[css->ss->id], NULL);
3485 call_rcu(&css->rcu_head, css_free_rcu_fn);
3488 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3489 struct cgroup *cgrp)
3496 css->parent = cgroup_css(cgrp->parent, ss);
3498 css->flags |= CSS_ROOT;
3500 BUG_ON(cgroup_css(cgrp, ss));
3503 /* invoke ->css_online() on a new CSS and mark it online if successful */
3504 static int online_css(struct cgroup_subsys_state *css)
3506 struct cgroup_subsys *ss = css->ss;
3509 lockdep_assert_held(&cgroup_tree_mutex);
3510 lockdep_assert_held(&cgroup_mutex);
3513 ret = ss->css_online(css);
3515 css->flags |= CSS_ONLINE;
3516 css->cgroup->nr_css++;
3517 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
3522 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
3523 static void offline_css(struct cgroup_subsys_state *css)
3525 struct cgroup_subsys *ss = css->ss;
3527 lockdep_assert_held(&cgroup_tree_mutex);
3528 lockdep_assert_held(&cgroup_mutex);
3530 if (!(css->flags & CSS_ONLINE))
3533 if (ss->css_offline)
3534 ss->css_offline(css);
3536 css->flags &= ~CSS_ONLINE;
3537 css->cgroup->nr_css--;
3538 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
3542 * create_css - create a cgroup_subsys_state
3543 * @cgrp: the cgroup new css will be associated with
3544 * @ss: the subsys of new css
3546 * Create a new css associated with @cgrp - @ss pair. On success, the new
3547 * css is online and installed in @cgrp with all interface files created.
3548 * Returns 0 on success, -errno on failure.
3550 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
3552 struct cgroup *parent = cgrp->parent;
3553 struct cgroup_subsys_state *css;
3556 lockdep_assert_held(&cgroup_mutex);
3558 css = ss->css_alloc(cgroup_css(parent, ss));
3560 return PTR_ERR(css);
3562 err = percpu_ref_init(&css->refcnt, css_release);
3566 init_css(css, ss, cgrp);
3568 err = cgroup_populate_dir(cgrp, 1 << ss->id);
3572 err = online_css(css);
3577 css_get(css->parent);
3579 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
3581 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",
3582 current->comm, current->pid, ss->name);
3583 if (!strcmp(ss->name, "memory"))
3584 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
3585 ss->warned_broken_hierarchy = true;
3591 percpu_ref_cancel_init(&css->refcnt);
3597 * cgroup_create - create a cgroup
3598 * @parent: cgroup that will be parent of the new cgroup
3599 * @name: name of the new cgroup
3600 * @mode: mode to set on new cgroup
3602 static long cgroup_create(struct cgroup *parent, const char *name,
3605 struct cgroup *cgrp;
3606 struct cgroupfs_root *root = parent->root;
3608 struct cgroup_subsys *ss;
3609 struct kernfs_node *kn;
3611 /* allocate the cgroup and its ID, 0 is reserved for the root */
3612 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
3616 mutex_lock(&cgroup_tree_mutex);
3619 * Only live parents can have children. Note that the liveliness
3620 * check isn't strictly necessary because cgroup_mkdir() and
3621 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
3622 * anyway so that locking is contained inside cgroup proper and we
3623 * don't get nasty surprises if we ever grow another caller.
3625 if (!cgroup_lock_live_group(parent)) {
3627 goto err_unlock_tree;
3631 * Temporarily set the pointer to NULL, so idr_find() won't return
3632 * a half-baked cgroup.
3634 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
3640 init_cgroup_housekeeping(cgrp);
3642 cgrp->parent = parent;
3643 cgrp->dummy_css.parent = &parent->dummy_css;
3644 cgrp->root = parent->root;
3646 if (notify_on_release(parent))
3647 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3649 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
3650 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3652 /* create the directory */
3653 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
3661 * This extra ref will be put in cgroup_free_fn() and guarantees
3662 * that @cgrp->kn is always accessible.
3666 cgrp->serial_nr = cgroup_serial_nr_next++;
3668 /* allocation complete, commit to creation */
3669 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
3670 atomic_inc(&root->nr_cgrps);
3674 * @cgrp is now fully operational. If something fails after this
3675 * point, it'll be released via the normal destruction path.
3677 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
3679 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
3683 /* let's create and online css's */
3684 for_each_subsys(ss, ssid) {
3685 if (root->subsys_mask & (1 << ssid)) {
3686 err = create_css(cgrp, ss);
3692 kernfs_activate(kn);
3694 mutex_unlock(&cgroup_mutex);
3695 mutex_unlock(&cgroup_tree_mutex);
3700 idr_remove(&root->cgroup_idr, cgrp->id);
3702 mutex_unlock(&cgroup_mutex);
3704 mutex_unlock(&cgroup_tree_mutex);
3709 cgroup_destroy_locked(cgrp);
3710 mutex_unlock(&cgroup_mutex);
3711 mutex_unlock(&cgroup_tree_mutex);
3715 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
3718 struct cgroup *parent = parent_kn->priv;
3720 return cgroup_create(parent, name, mode);
3724 * This is called when the refcnt of a css is confirmed to be killed.
3725 * css_tryget() is now guaranteed to fail.
3727 static void css_killed_work_fn(struct work_struct *work)
3729 struct cgroup_subsys_state *css =
3730 container_of(work, struct cgroup_subsys_state, destroy_work);
3731 struct cgroup *cgrp = css->cgroup;
3733 mutex_lock(&cgroup_tree_mutex);
3734 mutex_lock(&cgroup_mutex);
3737 * css_tryget() is guaranteed to fail now. Tell subsystems to
3738 * initate destruction.
3743 * If @cgrp is marked dead, it's waiting for refs of all css's to
3744 * be disabled before proceeding to the second phase of cgroup
3745 * destruction. If we are the last one, kick it off.
3747 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
3748 cgroup_destroy_css_killed(cgrp);
3750 mutex_unlock(&cgroup_mutex);
3751 mutex_unlock(&cgroup_tree_mutex);
3754 * Put the css refs from kill_css(). Each css holds an extra
3755 * reference to the cgroup's dentry and cgroup removal proceeds
3756 * regardless of css refs. On the last put of each css, whenever
3757 * that may be, the extra dentry ref is put so that dentry
3758 * destruction happens only after all css's are released.
3763 /* css kill confirmation processing requires process context, bounce */
3764 static void css_killed_ref_fn(struct percpu_ref *ref)
3766 struct cgroup_subsys_state *css =
3767 container_of(ref, struct cgroup_subsys_state, refcnt);
3769 INIT_WORK(&css->destroy_work, css_killed_work_fn);
3770 queue_work(cgroup_destroy_wq, &css->destroy_work);
3774 * kill_css - destroy a css
3775 * @css: css to destroy
3777 * This function initiates destruction of @css by removing cgroup interface
3778 * files and putting its base reference. ->css_offline() will be invoked
3779 * asynchronously once css_tryget() is guaranteed to fail and when the
3780 * reference count reaches zero, @css will be released.
3782 static void kill_css(struct cgroup_subsys_state *css)
3785 * This must happen before css is disassociated with its cgroup.
3786 * See seq_css() for details.
3788 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
3791 * Killing would put the base ref, but we need to keep it alive
3792 * until after ->css_offline().
3797 * cgroup core guarantees that, by the time ->css_offline() is
3798 * invoked, no new css reference will be given out via
3799 * css_tryget(). We can't simply call percpu_ref_kill() and
3800 * proceed to offlining css's because percpu_ref_kill() doesn't
3801 * guarantee that the ref is seen as killed on all CPUs on return.
3803 * Use percpu_ref_kill_and_confirm() to get notifications as each
3804 * css is confirmed to be seen as killed on all CPUs.
3806 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
3810 * cgroup_destroy_locked - the first stage of cgroup destruction
3811 * @cgrp: cgroup to be destroyed
3813 * css's make use of percpu refcnts whose killing latency shouldn't be
3814 * exposed to userland and are RCU protected. Also, cgroup core needs to
3815 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
3816 * invoked. To satisfy all the requirements, destruction is implemented in
3817 * the following two steps.
3819 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
3820 * userland visible parts and start killing the percpu refcnts of
3821 * css's. Set up so that the next stage will be kicked off once all
3822 * the percpu refcnts are confirmed to be killed.
3824 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
3825 * rest of destruction. Once all cgroup references are gone, the
3826 * cgroup is RCU-freed.
3828 * This function implements s1. After this step, @cgrp is gone as far as
3829 * the userland is concerned and a new cgroup with the same name may be
3830 * created. As cgroup doesn't care about the names internally, this
3831 * doesn't cause any problem.
3833 static int cgroup_destroy_locked(struct cgroup *cgrp)
3834 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
3836 struct cgroup *child;
3837 struct cgroup_subsys_state *css;
3841 lockdep_assert_held(&cgroup_tree_mutex);
3842 lockdep_assert_held(&cgroup_mutex);
3845 * css_set_rwsem synchronizes access to ->cset_links and prevents
3846 * @cgrp from being removed while put_css_set() is in progress.
3848 down_read(&css_set_rwsem);
3849 empty = list_empty(&cgrp->cset_links);
3850 up_read(&css_set_rwsem);
3855 * Make sure there's no live children. We can't test ->children
3856 * emptiness as dead children linger on it while being destroyed;
3857 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
3861 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
3862 empty = cgroup_is_dead(child);
3871 * Mark @cgrp dead. This prevents further task migration and child
3872 * creation by disabling cgroup_lock_live_group(). Note that
3873 * CGRP_DEAD assertion is depended upon by css_next_child() to
3874 * resume iteration after dropping RCU read lock. See
3875 * css_next_child() for details.
3877 set_bit(CGRP_DEAD, &cgrp->flags);
3880 * Initiate massacre of all css's. cgroup_destroy_css_killed()
3881 * will be invoked to perform the rest of destruction once the
3882 * percpu refs of all css's are confirmed to be killed. This
3883 * involves removing the subsystem's files, drop cgroup_mutex.
3885 mutex_unlock(&cgroup_mutex);
3886 for_each_css(css, ssid, cgrp)
3888 mutex_lock(&cgroup_mutex);
3890 /* CGRP_DEAD is set, remove from ->release_list for the last time */
3891 raw_spin_lock(&release_list_lock);
3892 if (!list_empty(&cgrp->release_list))
3893 list_del_init(&cgrp->release_list);
3894 raw_spin_unlock(&release_list_lock);
3897 * If @cgrp has css's attached, the second stage of cgroup
3898 * destruction is kicked off from css_killed_work_fn() after the
3899 * refs of all attached css's are killed. If @cgrp doesn't have
3900 * any css, we kick it off here.
3903 cgroup_destroy_css_killed(cgrp);
3905 /* remove @cgrp directory along with the base files */
3906 mutex_unlock(&cgroup_mutex);
3909 * There are two control paths which try to determine cgroup from
3910 * dentry without going through kernfs - cgroupstats_build() and
3911 * css_tryget_from_dir(). Those are supported by RCU protecting
3912 * clearing of cgrp->kn->priv backpointer, which should happen
3913 * after all files under it have been removed.
3915 kernfs_remove(cgrp->kn); /* @cgrp has an extra ref on its kn */
3916 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
3918 mutex_lock(&cgroup_mutex);
3924 * cgroup_destroy_css_killed - the second step of cgroup destruction
3925 * @work: cgroup->destroy_free_work
3927 * This function is invoked from a work item for a cgroup which is being
3928 * destroyed after all css's are offlined and performs the rest of
3929 * destruction. This is the second step of destruction described in the
3930 * comment above cgroup_destroy_locked().
3932 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
3934 struct cgroup *parent = cgrp->parent;
3936 lockdep_assert_held(&cgroup_tree_mutex);
3937 lockdep_assert_held(&cgroup_mutex);
3939 /* delete this cgroup from parent->children */
3940 list_del_rcu(&cgrp->sibling);
3944 set_bit(CGRP_RELEASABLE, &parent->flags);
3945 check_for_release(parent);
3948 static int cgroup_rmdir(struct kernfs_node *kn)
3950 struct cgroup *cgrp = kn->priv;
3954 * This is self-destruction but @kn can't be removed while this
3955 * callback is in progress. Let's break active protection. Once
3956 * the protection is broken, @cgrp can be destroyed at any point.
3957 * Pin it so that it stays accessible.
3960 kernfs_break_active_protection(kn);
3962 mutex_lock(&cgroup_tree_mutex);
3963 mutex_lock(&cgroup_mutex);
3966 * @cgrp might already have been destroyed while we're trying to
3969 if (!cgroup_is_dead(cgrp))
3970 ret = cgroup_destroy_locked(cgrp);
3972 mutex_unlock(&cgroup_mutex);
3973 mutex_unlock(&cgroup_tree_mutex);
3975 kernfs_unbreak_active_protection(kn);
3980 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
3981 .remount_fs = cgroup_remount,
3982 .show_options = cgroup_show_options,
3983 .mkdir = cgroup_mkdir,
3984 .rmdir = cgroup_rmdir,
3985 .rename = cgroup_rename,
3988 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
3990 struct cgroup_subsys_state *css;
3992 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
3994 mutex_lock(&cgroup_tree_mutex);
3995 mutex_lock(&cgroup_mutex);
3997 INIT_LIST_HEAD(&ss->cfts);
3999 /* Create the top cgroup state for this subsystem */
4000 ss->root = &cgroup_dummy_root;
4001 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4002 /* We don't handle early failures gracefully */
4003 BUG_ON(IS_ERR(css));
4004 init_css(css, ss, cgroup_dummy_top);
4006 /* Update the init_css_set to contain a subsys
4007 * pointer to this state - since the subsystem is
4008 * newly registered, all tasks and hence the
4009 * init_css_set is in the subsystem's top cgroup. */
4010 init_css_set.subsys[ss->id] = css;
4012 need_forkexit_callback |= ss->fork || ss->exit;
4014 /* At system boot, before all subsystems have been
4015 * registered, no tasks have been forked, so we don't
4016 * need to invoke fork callbacks here. */
4017 BUG_ON(!list_empty(&init_task.tasks));
4019 BUG_ON(online_css(css));
4021 mutex_unlock(&cgroup_mutex);
4022 mutex_unlock(&cgroup_tree_mutex);
4026 * cgroup_init_early - cgroup initialization at system boot
4028 * Initialize cgroups at system boot, and initialize any
4029 * subsystems that request early init.
4031 int __init cgroup_init_early(void)
4033 struct cgroup_subsys *ss;
4036 atomic_set(&init_css_set.refcount, 1);
4037 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4038 INIT_LIST_HEAD(&init_css_set.tasks);
4039 INIT_LIST_HEAD(&init_css_set.mg_tasks);
4040 INIT_LIST_HEAD(&init_css_set.mg_preload_node);
4041 INIT_LIST_HEAD(&init_css_set.mg_node);
4042 INIT_HLIST_NODE(&init_css_set.hlist);
4044 init_cgroup_root(&cgroup_dummy_root);
4045 cgroup_root_count = 1;
4046 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4048 init_cgrp_cset_link.cset = &init_css_set;
4049 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4050 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4051 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4053 for_each_subsys(ss, i) {
4054 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4055 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4056 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4058 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4059 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4062 ss->name = cgroup_subsys_name[i];
4065 cgroup_init_subsys(ss);
4071 * cgroup_init - cgroup initialization
4073 * Register cgroup filesystem and /proc file, and initialize
4074 * any subsystems that didn't request early init.
4076 int __init cgroup_init(void)
4078 struct cgroup_subsys *ss;
4082 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4084 for_each_subsys(ss, i) {
4085 if (!ss->early_init)
4086 cgroup_init_subsys(ss);
4089 * cftype registration needs kmalloc and can't be done
4090 * during early_init. Register base cftypes separately.
4092 if (ss->base_cftypes)
4093 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4096 /* allocate id for the dummy hierarchy */
4097 mutex_lock(&cgroup_mutex);
4099 /* Add init_css_set to the hash table */
4100 key = css_set_hash(init_css_set.subsys);
4101 hash_add(css_set_table, &init_css_set.hlist, key);
4103 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4105 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4109 mutex_unlock(&cgroup_mutex);
4111 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4115 err = register_filesystem(&cgroup_fs_type);
4117 kobject_put(cgroup_kobj);
4121 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4125 static int __init cgroup_wq_init(void)
4128 * There isn't much point in executing destruction path in
4129 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4130 * Use 1 for @max_active.
4132 * We would prefer to do this in cgroup_init() above, but that
4133 * is called before init_workqueues(): so leave this until after.
4135 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4136 BUG_ON(!cgroup_destroy_wq);
4139 * Used to destroy pidlists and separate to serve as flush domain.
4140 * Cap @max_active to 1 too.
4142 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4144 BUG_ON(!cgroup_pidlist_destroy_wq);
4148 core_initcall(cgroup_wq_init);
4151 * proc_cgroup_show()
4152 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4153 * - Used for /proc/<pid>/cgroup.
4156 /* TODO: Use a proper seq_file iterator */
4157 int proc_cgroup_show(struct seq_file *m, void *v)
4160 struct task_struct *tsk;
4163 struct cgroupfs_root *root;
4166 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4172 tsk = get_pid_task(pid, PIDTYPE_PID);
4178 mutex_lock(&cgroup_mutex);
4179 down_read(&css_set_rwsem);
4181 for_each_active_root(root) {
4182 struct cgroup_subsys *ss;
4183 struct cgroup *cgrp;
4184 int ssid, count = 0;
4186 seq_printf(m, "%d:", root->hierarchy_id);
4187 for_each_subsys(ss, ssid)
4188 if (root->subsys_mask & (1 << ssid))
4189 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4190 if (strlen(root->name))
4191 seq_printf(m, "%sname=%s", count ? "," : "",
4194 cgrp = task_cgroup_from_root(tsk, root);
4195 path = cgroup_path(cgrp, buf, PATH_MAX);
4197 retval = -ENAMETOOLONG;
4205 up_read(&css_set_rwsem);
4206 mutex_unlock(&cgroup_mutex);
4207 put_task_struct(tsk);
4214 /* Display information about each subsystem and each hierarchy */
4215 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4217 struct cgroup_subsys *ss;
4220 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4222 * ideally we don't want subsystems moving around while we do this.
4223 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4224 * subsys/hierarchy state.
4226 mutex_lock(&cgroup_mutex);
4228 for_each_subsys(ss, i)
4229 seq_printf(m, "%s\t%d\t%d\t%d\n",
4230 ss->name, ss->root->hierarchy_id,
4231 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4233 mutex_unlock(&cgroup_mutex);
4237 static int cgroupstats_open(struct inode *inode, struct file *file)
4239 return single_open(file, proc_cgroupstats_show, NULL);
4242 static const struct file_operations proc_cgroupstats_operations = {
4243 .open = cgroupstats_open,
4245 .llseek = seq_lseek,
4246 .release = single_release,
4250 * cgroup_fork - initialize cgroup related fields during copy_process()
4251 * @child: pointer to task_struct of forking parent process.
4253 * A task is associated with the init_css_set until cgroup_post_fork()
4254 * attaches it to the parent's css_set. Empty cg_list indicates that
4255 * @child isn't holding reference to its css_set.
4257 void cgroup_fork(struct task_struct *child)
4259 RCU_INIT_POINTER(child->cgroups, &init_css_set);
4260 INIT_LIST_HEAD(&child->cg_list);
4264 * cgroup_post_fork - called on a new task after adding it to the task list
4265 * @child: the task in question
4267 * Adds the task to the list running through its css_set if necessary and
4268 * call the subsystem fork() callbacks. Has to be after the task is
4269 * visible on the task list in case we race with the first call to
4270 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4273 void cgroup_post_fork(struct task_struct *child)
4275 struct cgroup_subsys *ss;
4279 * This may race against cgroup_enable_task_cg_links(). As that
4280 * function sets use_task_css_set_links before grabbing
4281 * tasklist_lock and we just went through tasklist_lock to add
4282 * @child, it's guaranteed that either we see the set
4283 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4284 * @child during its iteration.
4286 * If we won the race, @child is associated with %current's
4287 * css_set. Grabbing css_set_rwsem guarantees both that the
4288 * association is stable, and, on completion of the parent's
4289 * migration, @child is visible in the source of migration or
4290 * already in the destination cgroup. This guarantee is necessary
4291 * when implementing operations which need to migrate all tasks of
4292 * a cgroup to another.
4294 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4295 * will remain in init_css_set. This is safe because all tasks are
4296 * in the init_css_set before cg_links is enabled and there's no
4297 * operation which transfers all tasks out of init_css_set.
4299 if (use_task_css_set_links) {
4300 struct css_set *cset;
4302 down_write(&css_set_rwsem);
4303 cset = task_css_set(current);
4304 if (list_empty(&child->cg_list)) {
4305 rcu_assign_pointer(child->cgroups, cset);
4306 list_add(&child->cg_list, &cset->tasks);
4309 up_write(&css_set_rwsem);
4313 * Call ss->fork(). This must happen after @child is linked on
4314 * css_set; otherwise, @child might change state between ->fork()
4315 * and addition to css_set.
4317 if (need_forkexit_callback) {
4318 for_each_subsys(ss, i)
4325 * cgroup_exit - detach cgroup from exiting task
4326 * @tsk: pointer to task_struct of exiting process
4327 * @run_callback: run exit callbacks?
4329 * Description: Detach cgroup from @tsk and release it.
4331 * Note that cgroups marked notify_on_release force every task in
4332 * them to take the global cgroup_mutex mutex when exiting.
4333 * This could impact scaling on very large systems. Be reluctant to
4334 * use notify_on_release cgroups where very high task exit scaling
4335 * is required on large systems.
4337 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
4338 * call cgroup_exit() while the task is still competent to handle
4339 * notify_on_release(), then leave the task attached to the root cgroup in
4340 * each hierarchy for the remainder of its exit. No need to bother with
4341 * init_css_set refcnting. init_css_set never goes away and we can't race
4342 * with migration path - either PF_EXITING is visible to migration path or
4343 * @tsk never got on the tasklist.
4345 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4347 struct cgroup_subsys *ss;
4348 struct css_set *cset;
4349 bool put_cset = false;
4353 * Unlink from @tsk from its css_set. As migration path can't race
4354 * with us, we can check cg_list without grabbing css_set_rwsem.
4356 if (!list_empty(&tsk->cg_list)) {
4357 down_write(&css_set_rwsem);
4358 list_del_init(&tsk->cg_list);
4359 up_write(&css_set_rwsem);
4363 /* Reassign the task to the init_css_set. */
4364 cset = task_css_set(tsk);
4365 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4367 if (run_callbacks && need_forkexit_callback) {
4368 /* see cgroup_post_fork() for details */
4369 for_each_subsys(ss, i) {
4371 struct cgroup_subsys_state *old_css = cset->subsys[i];
4372 struct cgroup_subsys_state *css = task_css(tsk, i);
4374 ss->exit(css, old_css, tsk);
4380 put_css_set(cset, true);
4383 static void check_for_release(struct cgroup *cgrp)
4385 if (cgroup_is_releasable(cgrp) &&
4386 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
4388 * Control Group is currently removeable. If it's not
4389 * already queued for a userspace notification, queue
4392 int need_schedule_work = 0;
4394 raw_spin_lock(&release_list_lock);
4395 if (!cgroup_is_dead(cgrp) &&
4396 list_empty(&cgrp->release_list)) {
4397 list_add(&cgrp->release_list, &release_list);
4398 need_schedule_work = 1;
4400 raw_spin_unlock(&release_list_lock);
4401 if (need_schedule_work)
4402 schedule_work(&release_agent_work);
4407 * Notify userspace when a cgroup is released, by running the
4408 * configured release agent with the name of the cgroup (path
4409 * relative to the root of cgroup file system) as the argument.
4411 * Most likely, this user command will try to rmdir this cgroup.
4413 * This races with the possibility that some other task will be
4414 * attached to this cgroup before it is removed, or that some other
4415 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4416 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4417 * unused, and this cgroup will be reprieved from its death sentence,
4418 * to continue to serve a useful existence. Next time it's released,
4419 * we will get notified again, if it still has 'notify_on_release' set.
4421 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4422 * means only wait until the task is successfully execve()'d. The
4423 * separate release agent task is forked by call_usermodehelper(),
4424 * then control in this thread returns here, without waiting for the
4425 * release agent task. We don't bother to wait because the caller of
4426 * this routine has no use for the exit status of the release agent
4427 * task, so no sense holding our caller up for that.
4429 static void cgroup_release_agent(struct work_struct *work)
4431 BUG_ON(work != &release_agent_work);
4432 mutex_lock(&cgroup_mutex);
4433 raw_spin_lock(&release_list_lock);
4434 while (!list_empty(&release_list)) {
4435 char *argv[3], *envp[3];
4437 char *pathbuf = NULL, *agentbuf = NULL, *path;
4438 struct cgroup *cgrp = list_entry(release_list.next,
4441 list_del_init(&cgrp->release_list);
4442 raw_spin_unlock(&release_list_lock);
4443 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
4446 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
4449 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4454 argv[i++] = agentbuf;
4459 /* minimal command environment */
4460 envp[i++] = "HOME=/";
4461 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4464 /* Drop the lock while we invoke the usermode helper,
4465 * since the exec could involve hitting disk and hence
4466 * be a slow process */
4467 mutex_unlock(&cgroup_mutex);
4468 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4469 mutex_lock(&cgroup_mutex);
4473 raw_spin_lock(&release_list_lock);
4475 raw_spin_unlock(&release_list_lock);
4476 mutex_unlock(&cgroup_mutex);
4479 static int __init cgroup_disable(char *str)
4481 struct cgroup_subsys *ss;
4485 while ((token = strsep(&str, ",")) != NULL) {
4489 for_each_subsys(ss, i) {
4490 if (!strcmp(token, ss->name)) {
4492 printk(KERN_INFO "Disabling %s control group"
4493 " subsystem\n", ss->name);
4500 __setup("cgroup_disable=", cgroup_disable);
4503 * css_tryget_from_dir - get corresponding css from the dentry of a cgroup dir
4504 * @dentry: directory dentry of interest
4505 * @ss: subsystem of interest
4507 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
4508 * to get the corresponding css and return it. If such css doesn't exist
4509 * or can't be pinned, an ERR_PTR value is returned.
4511 struct cgroup_subsys_state *css_tryget_from_dir(struct dentry *dentry,
4512 struct cgroup_subsys *ss)
4514 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
4515 struct cgroup_subsys_state *css = NULL;
4516 struct cgroup *cgrp;
4518 /* is @dentry a cgroup dir? */
4519 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
4520 kernfs_type(kn) != KERNFS_DIR)
4521 return ERR_PTR(-EBADF);
4526 * This path doesn't originate from kernfs and @kn could already
4527 * have been or be removed at any point. @kn->priv is RCU
4528 * protected for this access. See destroy_locked() for details.
4530 cgrp = rcu_dereference(kn->priv);
4532 css = cgroup_css(cgrp, ss);
4534 if (!css || !css_tryget(css))
4535 css = ERR_PTR(-ENOENT);
4542 * css_from_id - lookup css by id
4543 * @id: the cgroup id
4544 * @ss: cgroup subsys to be looked into
4546 * Returns the css if there's valid one with @id, otherwise returns NULL.
4547 * Should be called under rcu_read_lock().
4549 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
4551 struct cgroup *cgrp;
4553 cgroup_assert_mutexes_or_rcu_locked();
4555 cgrp = idr_find(&ss->root->cgroup_idr, id);
4557 return cgroup_css(cgrp, ss);
4561 #ifdef CONFIG_CGROUP_DEBUG
4562 static struct cgroup_subsys_state *
4563 debug_css_alloc(struct cgroup_subsys_state *parent_css)
4565 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4568 return ERR_PTR(-ENOMEM);
4573 static void debug_css_free(struct cgroup_subsys_state *css)
4578 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
4581 return cgroup_task_count(css->cgroup);
4584 static u64 current_css_set_read(struct cgroup_subsys_state *css,
4587 return (u64)(unsigned long)current->cgroups;
4590 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
4596 count = atomic_read(&task_css_set(current)->refcount);
4601 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
4603 struct cgrp_cset_link *link;
4604 struct css_set *cset;
4607 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
4611 down_read(&css_set_rwsem);
4613 cset = rcu_dereference(current->cgroups);
4614 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
4615 struct cgroup *c = link->cgrp;
4616 const char *name = "?";
4618 if (c != cgroup_dummy_top) {
4619 cgroup_name(c, name_buf, NAME_MAX + 1);
4623 seq_printf(seq, "Root %d group %s\n",
4624 c->root->hierarchy_id, name);
4627 up_read(&css_set_rwsem);
4632 #define MAX_TASKS_SHOWN_PER_CSS 25
4633 static int cgroup_css_links_read(struct seq_file *seq, void *v)
4635 struct cgroup_subsys_state *css = seq_css(seq);
4636 struct cgrp_cset_link *link;
4638 down_read(&css_set_rwsem);
4639 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
4640 struct css_set *cset = link->cset;
4641 struct task_struct *task;
4644 seq_printf(seq, "css_set %p\n", cset);
4646 list_for_each_entry(task, &cset->tasks, cg_list) {
4647 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
4649 seq_printf(seq, " task %d\n", task_pid_vnr(task));
4652 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
4653 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
4655 seq_printf(seq, " task %d\n", task_pid_vnr(task));
4659 seq_puts(seq, " ...\n");
4661 up_read(&css_set_rwsem);
4665 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
4667 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
4670 static struct cftype debug_files[] = {
4672 .name = "taskcount",
4673 .read_u64 = debug_taskcount_read,
4677 .name = "current_css_set",
4678 .read_u64 = current_css_set_read,
4682 .name = "current_css_set_refcount",
4683 .read_u64 = current_css_set_refcount_read,
4687 .name = "current_css_set_cg_links",
4688 .seq_show = current_css_set_cg_links_read,
4692 .name = "cgroup_css_links",
4693 .seq_show = cgroup_css_links_read,
4697 .name = "releasable",
4698 .read_u64 = releasable_read,
4704 struct cgroup_subsys debug_cgrp_subsys = {
4705 .css_alloc = debug_css_alloc,
4706 .css_free = debug_css_free,
4707 .base_cftypes = debug_files,
4709 #endif /* CONFIG_CGROUP_DEBUG */