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 #ifdef CONFIG_PROVE_RCU
85 DEFINE_MUTEX(cgroup_mutex);
86 EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for lockdep */
88 static DEFINE_MUTEX(cgroup_mutex);
92 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
93 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
95 static DEFINE_SPINLOCK(release_agent_path_lock);
97 #define cgroup_assert_mutexes_or_rcu_locked() \
98 rcu_lockdep_assert(rcu_read_lock_held() || \
99 lockdep_is_held(&cgroup_tree_mutex) || \
100 lockdep_is_held(&cgroup_mutex), \
101 "cgroup_[tree_]mutex or RCU read lock required");
104 * cgroup destruction makes heavy use of work items and there can be a lot
105 * of concurrent destructions. Use a separate workqueue so that cgroup
106 * destruction work items don't end up filling up max_active of system_wq
107 * which may lead to deadlock.
109 static struct workqueue_struct *cgroup_destroy_wq;
112 * pidlist destructions need to be flushed on cgroup destruction. Use a
113 * separate workqueue as flush domain.
115 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
117 /* generate an array of cgroup subsystem pointers */
118 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
119 static struct cgroup_subsys *cgroup_subsys[] = {
120 #include <linux/cgroup_subsys.h>
124 /* array of cgroup subsystem names */
125 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
126 static const char *cgroup_subsys_name[] = {
127 #include <linux/cgroup_subsys.h>
132 * The dummy hierarchy, reserved for the subsystems that are otherwise
133 * unattached - it never has more than a single cgroup, and all tasks are
134 * part of that cgroup.
136 static struct cgroupfs_root cgroup_dummy_root;
138 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
139 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
141 /* The list of hierarchy roots */
143 static LIST_HEAD(cgroup_roots);
144 static int cgroup_root_count;
146 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
147 static DEFINE_IDR(cgroup_hierarchy_idr);
150 * Assign a monotonically increasing serial number to cgroups. It
151 * guarantees cgroups with bigger numbers are newer than those with smaller
152 * numbers. Also, as cgroups are always appended to the parent's
153 * ->children list, it guarantees that sibling cgroups are always sorted in
154 * the ascending serial number order on the list. Protected by
157 static u64 cgroup_serial_nr_next = 1;
159 /* This flag indicates whether tasks in the fork and exit paths should
160 * check for fork/exit handlers to call. This avoids us having to do
161 * extra work in the fork/exit path if none of the subsystems need to
164 static int need_forkexit_callback __read_mostly;
166 static struct cftype cgroup_base_files[];
168 static void cgroup_put(struct cgroup *cgrp);
169 static int rebind_subsystems(struct cgroupfs_root *root,
170 unsigned long added_mask, unsigned removed_mask);
171 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
172 static int cgroup_destroy_locked(struct cgroup *cgrp);
173 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
175 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
178 * cgroup_css - obtain a cgroup's css for the specified subsystem
179 * @cgrp: the cgroup of interest
180 * @ss: the subsystem of interest (%NULL returns the dummy_css)
182 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
183 * function must be called either under cgroup_mutex or rcu_read_lock() and
184 * the caller is responsible for pinning the returned css if it wants to
185 * keep accessing it outside the said locks. This function may return
186 * %NULL if @cgrp doesn't have @subsys_id enabled.
188 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
189 struct cgroup_subsys *ss)
192 return rcu_dereference_check(cgrp->subsys[ss->id],
193 lockdep_is_held(&cgroup_tree_mutex) ||
194 lockdep_is_held(&cgroup_mutex));
196 return &cgrp->dummy_css;
199 /* convenient tests for these bits */
200 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
202 return test_bit(CGRP_DEAD, &cgrp->flags);
205 struct cgroup_subsys_state *seq_css(struct seq_file *seq)
207 struct kernfs_open_file *of = seq->private;
208 struct cgroup *cgrp = of->kn->parent->priv;
209 struct cftype *cft = seq_cft(seq);
212 * This is open and unprotected implementation of cgroup_css().
213 * seq_css() is only called from a kernfs file operation which has
214 * an active reference on the file. Because all the subsystem
215 * files are drained before a css is disassociated with a cgroup,
216 * the matching css from the cgroup's subsys table is guaranteed to
217 * be and stay valid until the enclosing operation is complete.
220 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
222 return &cgrp->dummy_css;
224 EXPORT_SYMBOL_GPL(seq_css);
227 * cgroup_is_descendant - test ancestry
228 * @cgrp: the cgroup to be tested
229 * @ancestor: possible ancestor of @cgrp
231 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
232 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
233 * and @ancestor are accessible.
235 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
238 if (cgrp == ancestor)
245 static int cgroup_is_releasable(const struct cgroup *cgrp)
248 (1 << CGRP_RELEASABLE) |
249 (1 << CGRP_NOTIFY_ON_RELEASE);
250 return (cgrp->flags & bits) == bits;
253 static int notify_on_release(const struct cgroup *cgrp)
255 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
259 * for_each_css - iterate all css's of a cgroup
260 * @css: the iteration cursor
261 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
262 * @cgrp: the target cgroup to iterate css's of
264 * Should be called under cgroup_mutex.
266 #define for_each_css(css, ssid, cgrp) \
267 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
268 if (!((css) = rcu_dereference_check( \
269 (cgrp)->subsys[(ssid)], \
270 lockdep_is_held(&cgroup_tree_mutex) || \
271 lockdep_is_held(&cgroup_mutex)))) { } \
275 * for_each_subsys - iterate all enabled cgroup subsystems
276 * @ss: the iteration cursor
277 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
279 #define for_each_subsys(ss, ssid) \
280 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
281 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
283 /* iterate across the active hierarchies */
284 #define for_each_active_root(root) \
285 list_for_each_entry((root), &cgroup_roots, root_list)
288 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
289 * @cgrp: the cgroup to be checked for liveness
291 * On success, returns true; the mutex should be later unlocked. On
292 * failure returns false with no lock held.
294 static bool cgroup_lock_live_group(struct cgroup *cgrp)
296 mutex_lock(&cgroup_mutex);
297 if (cgroup_is_dead(cgrp)) {
298 mutex_unlock(&cgroup_mutex);
304 /* the list of cgroups eligible for automatic release. Protected by
305 * release_list_lock */
306 static LIST_HEAD(release_list);
307 static DEFINE_RAW_SPINLOCK(release_list_lock);
308 static void cgroup_release_agent(struct work_struct *work);
309 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
310 static void check_for_release(struct cgroup *cgrp);
313 * A cgroup can be associated with multiple css_sets as different tasks may
314 * belong to different cgroups on different hierarchies. In the other
315 * direction, a css_set is naturally associated with multiple cgroups.
316 * This M:N relationship is represented by the following link structure
317 * which exists for each association and allows traversing the associations
320 struct cgrp_cset_link {
321 /* the cgroup and css_set this link associates */
323 struct css_set *cset;
325 /* list of cgrp_cset_links anchored at cgrp->cset_links */
326 struct list_head cset_link;
328 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
329 struct list_head cgrp_link;
332 /* The default css_set - used by init and its children prior to any
333 * hierarchies being mounted. It contains a pointer to the root state
334 * for each subsystem. Also used to anchor the list of css_sets. Not
335 * reference-counted, to improve performance when child cgroups
336 * haven't been created.
339 static struct css_set init_css_set;
340 static struct cgrp_cset_link init_cgrp_cset_link;
343 * css_set_rwsem protects the list of css_set objects, and the chain of
344 * tasks off each css_set.
346 static DECLARE_RWSEM(css_set_rwsem);
347 static int css_set_count;
350 * hash table for cgroup groups. This improves the performance to find
351 * an existing css_set. This hash doesn't (currently) take into
352 * account cgroups in empty hierarchies.
354 #define CSS_SET_HASH_BITS 7
355 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
357 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
359 unsigned long key = 0UL;
360 struct cgroup_subsys *ss;
363 for_each_subsys(ss, i)
364 key += (unsigned long)css[i];
365 key = (key >> 16) ^ key;
370 static void put_css_set_locked(struct css_set *cset, bool taskexit)
372 struct cgrp_cset_link *link, *tmp_link;
374 lockdep_assert_held(&css_set_rwsem);
376 if (!atomic_dec_and_test(&cset->refcount))
379 /* This css_set is dead. unlink it and release cgroup refcounts */
380 hash_del(&cset->hlist);
383 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
384 struct cgroup *cgrp = link->cgrp;
386 list_del(&link->cset_link);
387 list_del(&link->cgrp_link);
389 /* @cgrp can't go away while we're holding css_set_rwsem */
390 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
392 set_bit(CGRP_RELEASABLE, &cgrp->flags);
393 check_for_release(cgrp);
399 kfree_rcu(cset, rcu_head);
402 static void put_css_set(struct css_set *cset, bool taskexit)
405 * Ensure that the refcount doesn't hit zero while any readers
406 * can see it. Similar to atomic_dec_and_lock(), but for an
409 if (atomic_add_unless(&cset->refcount, -1, 1))
412 down_write(&css_set_rwsem);
413 put_css_set_locked(cset, taskexit);
414 up_write(&css_set_rwsem);
418 * refcounted get/put for css_set objects
420 static inline void get_css_set(struct css_set *cset)
422 atomic_inc(&cset->refcount);
426 * compare_css_sets - helper function for find_existing_css_set().
427 * @cset: candidate css_set being tested
428 * @old_cset: existing css_set for a task
429 * @new_cgrp: cgroup that's being entered by the task
430 * @template: desired set of css pointers in css_set (pre-calculated)
432 * Returns true if "cset" matches "old_cset" except for the hierarchy
433 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
435 static bool compare_css_sets(struct css_set *cset,
436 struct css_set *old_cset,
437 struct cgroup *new_cgrp,
438 struct cgroup_subsys_state *template[])
440 struct list_head *l1, *l2;
442 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
443 /* Not all subsystems matched */
448 * Compare cgroup pointers in order to distinguish between
449 * different cgroups in heirarchies with no subsystems. We
450 * could get by with just this check alone (and skip the
451 * memcmp above) but on most setups the memcmp check will
452 * avoid the need for this more expensive check on almost all
456 l1 = &cset->cgrp_links;
457 l2 = &old_cset->cgrp_links;
459 struct cgrp_cset_link *link1, *link2;
460 struct cgroup *cgrp1, *cgrp2;
464 /* See if we reached the end - both lists are equal length. */
465 if (l1 == &cset->cgrp_links) {
466 BUG_ON(l2 != &old_cset->cgrp_links);
469 BUG_ON(l2 == &old_cset->cgrp_links);
471 /* Locate the cgroups associated with these links. */
472 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
473 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
476 /* Hierarchies should be linked in the same order. */
477 BUG_ON(cgrp1->root != cgrp2->root);
480 * If this hierarchy is the hierarchy of the cgroup
481 * that's changing, then we need to check that this
482 * css_set points to the new cgroup; if it's any other
483 * hierarchy, then this css_set should point to the
484 * same cgroup as the old css_set.
486 if (cgrp1->root == new_cgrp->root) {
487 if (cgrp1 != new_cgrp)
498 * find_existing_css_set - init css array and find the matching css_set
499 * @old_cset: the css_set that we're using before the cgroup transition
500 * @cgrp: the cgroup that we're moving into
501 * @template: out param for the new set of csses, should be clear on entry
503 static struct css_set *find_existing_css_set(struct css_set *old_cset,
505 struct cgroup_subsys_state *template[])
507 struct cgroupfs_root *root = cgrp->root;
508 struct cgroup_subsys *ss;
509 struct css_set *cset;
514 * Build the set of subsystem state objects that we want to see in the
515 * new css_set. while subsystems can change globally, the entries here
516 * won't change, so no need for locking.
518 for_each_subsys(ss, i) {
519 if (root->subsys_mask & (1UL << i)) {
520 /* Subsystem is in this hierarchy. So we want
521 * the subsystem state from the new
523 template[i] = cgroup_css(cgrp, ss);
525 /* Subsystem is not in this hierarchy, so we
526 * don't want to change the subsystem state */
527 template[i] = old_cset->subsys[i];
531 key = css_set_hash(template);
532 hash_for_each_possible(css_set_table, cset, hlist, key) {
533 if (!compare_css_sets(cset, old_cset, cgrp, template))
536 /* This css_set matches what we need */
540 /* No existing cgroup group matched */
544 static void free_cgrp_cset_links(struct list_head *links_to_free)
546 struct cgrp_cset_link *link, *tmp_link;
548 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
549 list_del(&link->cset_link);
555 * allocate_cgrp_cset_links - allocate cgrp_cset_links
556 * @count: the number of links to allocate
557 * @tmp_links: list_head the allocated links are put on
559 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
560 * through ->cset_link. Returns 0 on success or -errno.
562 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
564 struct cgrp_cset_link *link;
567 INIT_LIST_HEAD(tmp_links);
569 for (i = 0; i < count; i++) {
570 link = kzalloc(sizeof(*link), GFP_KERNEL);
572 free_cgrp_cset_links(tmp_links);
575 list_add(&link->cset_link, tmp_links);
581 * link_css_set - a helper function to link a css_set to a cgroup
582 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
583 * @cset: the css_set to be linked
584 * @cgrp: the destination cgroup
586 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
589 struct cgrp_cset_link *link;
591 BUG_ON(list_empty(tmp_links));
592 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
595 list_move(&link->cset_link, &cgrp->cset_links);
597 * Always add links to the tail of the list so that the list
598 * is sorted by order of hierarchy creation
600 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
604 * find_css_set - return a new css_set with one cgroup updated
605 * @old_cset: the baseline css_set
606 * @cgrp: the cgroup to be updated
608 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
609 * substituted into the appropriate hierarchy.
611 static struct css_set *find_css_set(struct css_set *old_cset,
614 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
615 struct css_set *cset;
616 struct list_head tmp_links;
617 struct cgrp_cset_link *link;
620 lockdep_assert_held(&cgroup_mutex);
622 /* First see if we already have a cgroup group that matches
624 down_read(&css_set_rwsem);
625 cset = find_existing_css_set(old_cset, cgrp, template);
628 up_read(&css_set_rwsem);
633 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
637 /* Allocate all the cgrp_cset_link objects that we'll need */
638 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
643 atomic_set(&cset->refcount, 1);
644 INIT_LIST_HEAD(&cset->cgrp_links);
645 INIT_LIST_HEAD(&cset->tasks);
646 INIT_LIST_HEAD(&cset->mg_tasks);
647 INIT_LIST_HEAD(&cset->mg_preload_node);
648 INIT_LIST_HEAD(&cset->mg_node);
649 INIT_HLIST_NODE(&cset->hlist);
651 /* Copy the set of subsystem state objects generated in
652 * find_existing_css_set() */
653 memcpy(cset->subsys, template, sizeof(cset->subsys));
655 down_write(&css_set_rwsem);
656 /* Add reference counts and links from the new css_set. */
657 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
658 struct cgroup *c = link->cgrp;
660 if (c->root == cgrp->root)
662 link_css_set(&tmp_links, cset, c);
665 BUG_ON(!list_empty(&tmp_links));
669 /* Add this cgroup group to the hash table */
670 key = css_set_hash(cset->subsys);
671 hash_add(css_set_table, &cset->hlist, key);
673 up_write(&css_set_rwsem);
678 static struct cgroupfs_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
680 struct cgroup *top_cgrp = kf_root->kn->priv;
682 return top_cgrp->root;
685 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
689 lockdep_assert_held(&cgroup_mutex);
691 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
696 root->hierarchy_id = id;
700 static void cgroup_exit_root_id(struct cgroupfs_root *root)
702 lockdep_assert_held(&cgroup_mutex);
704 if (root->hierarchy_id) {
705 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
706 root->hierarchy_id = 0;
710 static void cgroup_free_root(struct cgroupfs_root *root)
713 /* hierarhcy ID shoulid already have been released */
714 WARN_ON_ONCE(root->hierarchy_id);
716 idr_destroy(&root->cgroup_idr);
721 static void cgroup_destroy_root(struct cgroupfs_root *root)
723 struct cgroup *cgrp = &root->top_cgroup;
724 struct cgrp_cset_link *link, *tmp_link;
726 mutex_lock(&cgroup_tree_mutex);
727 mutex_lock(&cgroup_mutex);
729 BUG_ON(atomic_read(&root->nr_cgrps));
730 BUG_ON(!list_empty(&cgrp->children));
732 /* Rebind all subsystems back to the default hierarchy */
733 WARN_ON(rebind_subsystems(root, 0, root->subsys_mask));
736 * Release all the links from cset_links to this hierarchy's
739 down_write(&css_set_rwsem);
741 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
742 list_del(&link->cset_link);
743 list_del(&link->cgrp_link);
746 up_write(&css_set_rwsem);
748 if (!list_empty(&root->root_list)) {
749 list_del(&root->root_list);
753 cgroup_exit_root_id(root);
755 mutex_unlock(&cgroup_mutex);
756 mutex_unlock(&cgroup_tree_mutex);
758 kernfs_destroy_root(root->kf_root);
759 cgroup_free_root(root);
762 /* look up cgroup associated with given css_set on the specified hierarchy */
763 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
764 struct cgroupfs_root *root)
766 struct cgroup *res = NULL;
768 lockdep_assert_held(&cgroup_mutex);
769 lockdep_assert_held(&css_set_rwsem);
771 if (cset == &init_css_set) {
772 res = &root->top_cgroup;
774 struct cgrp_cset_link *link;
776 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
777 struct cgroup *c = link->cgrp;
779 if (c->root == root) {
791 * Return the cgroup for "task" from the given hierarchy. Must be
792 * called with cgroup_mutex and css_set_rwsem held.
794 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
795 struct cgroupfs_root *root)
798 * No need to lock the task - since we hold cgroup_mutex the
799 * task can't change groups, so the only thing that can happen
800 * is that it exits and its css is set back to init_css_set.
802 return cset_cgroup_from_root(task_css_set(task), root);
806 * There is one global cgroup mutex. We also require taking
807 * task_lock() when dereferencing a task's cgroup subsys pointers.
808 * See "The task_lock() exception", at the end of this comment.
810 * A task must hold cgroup_mutex to modify cgroups.
812 * Any task can increment and decrement the count field without lock.
813 * So in general, code holding cgroup_mutex can't rely on the count
814 * field not changing. However, if the count goes to zero, then only
815 * cgroup_attach_task() can increment it again. Because a count of zero
816 * means that no tasks are currently attached, therefore there is no
817 * way a task attached to that cgroup can fork (the other way to
818 * increment the count). So code holding cgroup_mutex can safely
819 * assume that if the count is zero, it will stay zero. Similarly, if
820 * a task holds cgroup_mutex on a cgroup with zero count, it
821 * knows that the cgroup won't be removed, as cgroup_rmdir()
824 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
825 * (usually) take cgroup_mutex. These are the two most performance
826 * critical pieces of code here. The exception occurs on cgroup_exit(),
827 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
828 * is taken, and if the cgroup count is zero, a usermode call made
829 * to the release agent with the name of the cgroup (path relative to
830 * the root of cgroup file system) as the argument.
832 * A cgroup can only be deleted if both its 'count' of using tasks
833 * is zero, and its list of 'children' cgroups is empty. Since all
834 * tasks in the system use _some_ cgroup, and since there is always at
835 * least one task in the system (init, pid == 1), therefore, top_cgroup
836 * always has either children cgroups and/or using tasks. So we don't
837 * need a special hack to ensure that top_cgroup cannot be deleted.
839 * The task_lock() exception
841 * The need for this exception arises from the action of
842 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
843 * another. It does so using cgroup_mutex, however there are
844 * several performance critical places that need to reference
845 * task->cgroup without the expense of grabbing a system global
846 * mutex. Therefore except as noted below, when dereferencing or, as
847 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
848 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
849 * the task_struct routinely used for such matters.
851 * P.S. One more locking exception. RCU is used to guard the
852 * update of a tasks cgroup pointer by cgroup_attach_task()
855 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
856 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
857 static const struct file_operations proc_cgroupstats_operations;
859 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
862 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
863 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
864 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
865 cft->ss->name, cft->name);
867 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
872 * cgroup_file_mode - deduce file mode of a control file
873 * @cft: the control file in question
875 * returns cft->mode if ->mode is not 0
876 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
877 * returns S_IRUGO if it has only a read handler
878 * returns S_IWUSR if it has only a write hander
880 static umode_t cgroup_file_mode(const struct cftype *cft)
887 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
890 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
897 static void cgroup_free_fn(struct work_struct *work)
899 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
901 atomic_dec(&cgrp->root->nr_cgrps);
902 cgroup_pidlist_destroy_all(cgrp);
906 * We get a ref to the parent, and put the ref when this
907 * cgroup is being freed, so it's guaranteed that the
908 * parent won't be destroyed before its children.
910 cgroup_put(cgrp->parent);
911 kernfs_put(cgrp->kn);
915 * This is top cgroup's refcnt reaching zero, which
916 * indicates that the root should be released.
918 cgroup_destroy_root(cgrp->root);
922 static void cgroup_free_rcu(struct rcu_head *head)
924 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
926 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
927 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
930 static void cgroup_get(struct cgroup *cgrp)
932 WARN_ON_ONCE(cgroup_is_dead(cgrp));
933 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
934 atomic_inc(&cgrp->refcnt);
937 static void cgroup_put(struct cgroup *cgrp)
939 if (!atomic_dec_and_test(&cgrp->refcnt))
941 if (WARN_ON_ONCE(cgrp->parent && !cgroup_is_dead(cgrp)))
945 * XXX: cgrp->id is only used to look up css's. As cgroup and
946 * css's lifetimes will be decoupled, it should be made
947 * per-subsystem and moved to css->id so that lookups are
948 * successful until the target css is released.
950 mutex_lock(&cgroup_mutex);
951 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
952 mutex_unlock(&cgroup_mutex);
955 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
958 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
960 char name[CGROUP_FILE_NAME_MAX];
962 lockdep_assert_held(&cgroup_tree_mutex);
963 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
967 * cgroup_clear_dir - remove subsys files in a cgroup directory
968 * @cgrp: target cgroup
969 * @subsys_mask: mask of the subsystem ids whose files should be removed
971 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
973 struct cgroup_subsys *ss;
976 for_each_subsys(ss, i) {
979 if (!test_bit(i, &subsys_mask))
981 list_for_each_entry(cfts, &ss->cfts, node)
982 cgroup_addrm_files(cgrp, cfts, false);
986 static int rebind_subsystems(struct cgroupfs_root *root,
987 unsigned long added_mask, unsigned removed_mask)
989 struct cgroup *cgrp = &root->top_cgroup;
990 struct cgroup_subsys *ss;
993 lockdep_assert_held(&cgroup_tree_mutex);
994 lockdep_assert_held(&cgroup_mutex);
996 /* Check that any added subsystems are currently free */
997 for_each_subsys(ss, i)
998 if ((added_mask & (1 << i)) && ss->root != &cgroup_dummy_root)
1001 ret = cgroup_populate_dir(cgrp, added_mask);
1006 * Nothing can fail from this point on. Remove files for the
1007 * removed subsystems and rebind each subsystem.
1009 mutex_unlock(&cgroup_mutex);
1010 cgroup_clear_dir(cgrp, removed_mask);
1011 mutex_lock(&cgroup_mutex);
1013 for_each_subsys(ss, i) {
1014 unsigned long bit = 1UL << i;
1016 if (bit & added_mask) {
1017 /* We're binding this subsystem to this hierarchy */
1018 BUG_ON(cgroup_css(cgrp, ss));
1019 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
1020 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
1022 rcu_assign_pointer(cgrp->subsys[i],
1023 cgroup_css(cgroup_dummy_top, ss));
1024 cgroup_css(cgrp, ss)->cgroup = cgrp;
1028 ss->bind(cgroup_css(cgrp, ss));
1030 /* refcount was already taken, and we're keeping it */
1031 root->subsys_mask |= bit;
1032 } else if (bit & removed_mask) {
1033 /* We're removing this subsystem */
1034 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
1035 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
1038 ss->bind(cgroup_css(cgroup_dummy_top, ss));
1040 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
1041 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1043 cgroup_subsys[i]->root = &cgroup_dummy_root;
1044 root->subsys_mask &= ~bit;
1048 kernfs_activate(cgrp->kn);
1052 static int cgroup_show_options(struct seq_file *seq,
1053 struct kernfs_root *kf_root)
1055 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1056 struct cgroup_subsys *ss;
1059 for_each_subsys(ss, ssid)
1060 if (root->subsys_mask & (1 << ssid))
1061 seq_printf(seq, ",%s", ss->name);
1062 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1063 seq_puts(seq, ",sane_behavior");
1064 if (root->flags & CGRP_ROOT_NOPREFIX)
1065 seq_puts(seq, ",noprefix");
1066 if (root->flags & CGRP_ROOT_XATTR)
1067 seq_puts(seq, ",xattr");
1069 spin_lock(&release_agent_path_lock);
1070 if (strlen(root->release_agent_path))
1071 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1072 spin_unlock(&release_agent_path_lock);
1074 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1075 seq_puts(seq, ",clone_children");
1076 if (strlen(root->name))
1077 seq_printf(seq, ",name=%s", root->name);
1081 struct cgroup_sb_opts {
1082 unsigned long subsys_mask;
1083 unsigned long flags;
1084 char *release_agent;
1085 bool cpuset_clone_children;
1087 /* User explicitly requested empty subsystem */
1092 * Convert a hierarchy specifier into a bitmask of subsystems and
1093 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1094 * array. This function takes refcounts on subsystems to be used, unless it
1095 * returns error, in which case no refcounts are taken.
1097 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1099 char *token, *o = data;
1100 bool all_ss = false, one_ss = false;
1101 unsigned long mask = (unsigned long)-1;
1102 struct cgroup_subsys *ss;
1105 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1107 #ifdef CONFIG_CPUSETS
1108 mask = ~(1UL << cpuset_cgrp_id);
1111 memset(opts, 0, sizeof(*opts));
1113 while ((token = strsep(&o, ",")) != NULL) {
1116 if (!strcmp(token, "none")) {
1117 /* Explicitly have no subsystems */
1121 if (!strcmp(token, "all")) {
1122 /* Mutually exclusive option 'all' + subsystem name */
1128 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1129 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1132 if (!strcmp(token, "noprefix")) {
1133 opts->flags |= CGRP_ROOT_NOPREFIX;
1136 if (!strcmp(token, "clone_children")) {
1137 opts->cpuset_clone_children = true;
1140 if (!strcmp(token, "xattr")) {
1141 opts->flags |= CGRP_ROOT_XATTR;
1144 if (!strncmp(token, "release_agent=", 14)) {
1145 /* Specifying two release agents is forbidden */
1146 if (opts->release_agent)
1148 opts->release_agent =
1149 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1150 if (!opts->release_agent)
1154 if (!strncmp(token, "name=", 5)) {
1155 const char *name = token + 5;
1156 /* Can't specify an empty name */
1159 /* Must match [\w.-]+ */
1160 for (i = 0; i < strlen(name); i++) {
1164 if ((c == '.') || (c == '-') || (c == '_'))
1168 /* Specifying two names is forbidden */
1171 opts->name = kstrndup(name,
1172 MAX_CGROUP_ROOT_NAMELEN - 1,
1180 for_each_subsys(ss, i) {
1181 if (strcmp(token, ss->name))
1186 /* Mutually exclusive option 'all' + subsystem name */
1189 set_bit(i, &opts->subsys_mask);
1194 if (i == CGROUP_SUBSYS_COUNT)
1199 * If the 'all' option was specified select all the subsystems,
1200 * otherwise if 'none', 'name=' and a subsystem name options
1201 * were not specified, let's default to 'all'
1203 if (all_ss || (!one_ss && !opts->none && !opts->name))
1204 for_each_subsys(ss, i)
1206 set_bit(i, &opts->subsys_mask);
1208 /* Consistency checks */
1210 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1211 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1213 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1214 opts->cpuset_clone_children || opts->release_agent ||
1216 pr_err("cgroup: sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1222 * Option noprefix was introduced just for backward compatibility
1223 * with the old cpuset, so we allow noprefix only if mounting just
1224 * the cpuset subsystem.
1226 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1230 /* Can't specify "none" and some subsystems */
1231 if (opts->subsys_mask && opts->none)
1235 * We either have to specify by name or by subsystems. (So all
1236 * empty hierarchies must have a name).
1238 if (!opts->subsys_mask && !opts->name)
1244 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1247 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1248 struct cgroup_sb_opts opts;
1249 unsigned long added_mask, removed_mask;
1251 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1252 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1256 mutex_lock(&cgroup_tree_mutex);
1257 mutex_lock(&cgroup_mutex);
1259 /* See what subsystems are wanted */
1260 ret = parse_cgroupfs_options(data, &opts);
1264 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1265 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1266 task_tgid_nr(current), current->comm);
1268 added_mask = opts.subsys_mask & ~root->subsys_mask;
1269 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1271 /* Don't allow flags or name to change at remount */
1272 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1273 (opts.name && strcmp(opts.name, root->name))) {
1274 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1275 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1276 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1281 /* remounting is not allowed for populated hierarchies */
1282 if (!list_empty(&root->top_cgroup.children)) {
1287 ret = rebind_subsystems(root, added_mask, removed_mask);
1291 if (opts.release_agent) {
1292 spin_lock(&release_agent_path_lock);
1293 strcpy(root->release_agent_path, opts.release_agent);
1294 spin_unlock(&release_agent_path_lock);
1297 kfree(opts.release_agent);
1299 mutex_unlock(&cgroup_mutex);
1300 mutex_unlock(&cgroup_tree_mutex);
1305 * To reduce the fork() overhead for systems that are not actually using
1306 * their cgroups capability, we don't maintain the lists running through
1307 * each css_set to its tasks until we see the list actually used - in other
1308 * words after the first mount.
1310 static bool use_task_css_set_links __read_mostly;
1312 static void cgroup_enable_task_cg_lists(void)
1314 struct task_struct *p, *g;
1316 down_write(&css_set_rwsem);
1318 if (use_task_css_set_links)
1321 use_task_css_set_links = true;
1324 * We need tasklist_lock because RCU is not safe against
1325 * while_each_thread(). Besides, a forking task that has passed
1326 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1327 * is not guaranteed to have its child immediately visible in the
1328 * tasklist if we walk through it with RCU.
1330 read_lock(&tasklist_lock);
1331 do_each_thread(g, p) {
1334 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1335 task_css_set(p) != &init_css_set);
1338 * We should check if the process is exiting, otherwise
1339 * it will race with cgroup_exit() in that the list
1340 * entry won't be deleted though the process has exited.
1341 * Do it while holding siglock so that we don't end up
1342 * racing against cgroup_exit().
1344 spin_lock_irq(&p->sighand->siglock);
1345 if (!(p->flags & PF_EXITING))
1346 list_add(&p->cg_list, &task_css_set(p)->tasks);
1347 spin_unlock_irq(&p->sighand->siglock);
1350 } while_each_thread(g, p);
1351 read_unlock(&tasklist_lock);
1353 up_write(&css_set_rwsem);
1356 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1358 atomic_set(&cgrp->refcnt, 1);
1359 INIT_LIST_HEAD(&cgrp->sibling);
1360 INIT_LIST_HEAD(&cgrp->children);
1361 INIT_LIST_HEAD(&cgrp->cset_links);
1362 INIT_LIST_HEAD(&cgrp->release_list);
1363 INIT_LIST_HEAD(&cgrp->pidlists);
1364 mutex_init(&cgrp->pidlist_mutex);
1365 cgrp->dummy_css.cgroup = cgrp;
1368 static void init_cgroup_root(struct cgroupfs_root *root)
1370 struct cgroup *cgrp = &root->top_cgroup;
1372 INIT_LIST_HEAD(&root->root_list);
1373 atomic_set(&root->nr_cgrps, 1);
1375 init_cgroup_housekeeping(cgrp);
1376 idr_init(&root->cgroup_idr);
1379 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1381 struct cgroupfs_root *root;
1383 if (!opts->subsys_mask && !opts->none)
1384 return ERR_PTR(-EINVAL);
1386 root = kzalloc(sizeof(*root), GFP_KERNEL);
1388 return ERR_PTR(-ENOMEM);
1390 init_cgroup_root(root);
1392 root->flags = opts->flags;
1393 if (opts->release_agent)
1394 strcpy(root->release_agent_path, opts->release_agent);
1396 strcpy(root->name, opts->name);
1397 if (opts->cpuset_clone_children)
1398 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1402 static int cgroup_setup_root(struct cgroupfs_root *root, unsigned long ss_mask)
1404 LIST_HEAD(tmp_links);
1405 struct cgroup *root_cgrp = &root->top_cgroup;
1406 struct css_set *cset;
1409 lockdep_assert_held(&cgroup_tree_mutex);
1410 lockdep_assert_held(&cgroup_mutex);
1412 ret = idr_alloc(&root->cgroup_idr, root_cgrp, 0, 1, GFP_KERNEL);
1415 root_cgrp->id = ret;
1418 * We're accessing css_set_count without locking css_set_rwsem here,
1419 * but that's OK - it can only be increased by someone holding
1420 * cgroup_lock, and that's us. The worst that can happen is that we
1421 * have some link structures left over
1423 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1427 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1428 ret = cgroup_init_root_id(root, 2, 0);
1432 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1433 KERNFS_ROOT_CREATE_DEACTIVATED,
1435 if (IS_ERR(root->kf_root)) {
1436 ret = PTR_ERR(root->kf_root);
1439 root_cgrp->kn = root->kf_root->kn;
1441 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1445 ret = rebind_subsystems(root, ss_mask, 0);
1450 * There must be no failure case after here, since rebinding takes
1451 * care of subsystems' refcounts, which are explicitly dropped in
1452 * the failure exit path.
1454 list_add(&root->root_list, &cgroup_roots);
1455 cgroup_root_count++;
1458 * Link the top cgroup in this hierarchy into all the css_set
1461 down_write(&css_set_rwsem);
1462 hash_for_each(css_set_table, i, cset, hlist)
1463 link_css_set(&tmp_links, cset, root_cgrp);
1464 up_write(&css_set_rwsem);
1466 BUG_ON(!list_empty(&root_cgrp->children));
1467 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1469 kernfs_activate(root_cgrp->kn);
1474 kernfs_destroy_root(root->kf_root);
1475 root->kf_root = NULL;
1477 cgroup_exit_root_id(root);
1479 free_cgrp_cset_links(&tmp_links);
1483 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1484 int flags, const char *unused_dev_name,
1487 struct cgroupfs_root *root;
1488 struct cgroup_sb_opts opts;
1489 struct dentry *dentry;
1493 * The first time anyone tries to mount a cgroup, enable the list
1494 * linking each css_set to its tasks and fix up all existing tasks.
1496 if (!use_task_css_set_links)
1497 cgroup_enable_task_cg_lists();
1499 mutex_lock(&cgroup_tree_mutex);
1500 mutex_lock(&cgroup_mutex);
1502 /* First find the desired set of subsystems */
1503 ret = parse_cgroupfs_options(data, &opts);
1507 /* look for a matching existing root */
1508 for_each_active_root(root) {
1509 bool name_match = false;
1512 * If we asked for a name then it must match. Also, if
1513 * name matches but sybsys_mask doesn't, we should fail.
1514 * Remember whether name matched.
1517 if (strcmp(opts.name, root->name))
1523 * If we asked for subsystems (or explicitly for no
1524 * subsystems) then they must match.
1526 if ((opts.subsys_mask || opts.none) &&
1527 (opts.subsys_mask != root->subsys_mask)) {
1534 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1535 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1536 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1540 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1545 * A root's lifetime is governed by its top cgroup. Zero
1546 * ref indicate that the root is being destroyed. Wait for
1547 * destruction to complete so that the subsystems are free.
1548 * We can use wait_queue for the wait but this path is
1549 * super cold. Let's just sleep for a bit and retry.
1551 if (!atomic_inc_not_zero(&root->top_cgroup.refcnt)) {
1552 mutex_unlock(&cgroup_mutex);
1553 mutex_unlock(&cgroup_tree_mutex);
1554 kfree(opts.release_agent);
1564 /* no such thing, create a new one */
1565 root = cgroup_root_from_opts(&opts);
1567 ret = PTR_ERR(root);
1571 ret = cgroup_setup_root(root, opts.subsys_mask);
1573 cgroup_free_root(root);
1576 mutex_unlock(&cgroup_mutex);
1577 mutex_unlock(&cgroup_tree_mutex);
1579 kfree(opts.release_agent);
1583 return ERR_PTR(ret);
1585 dentry = kernfs_mount(fs_type, flags, root->kf_root);
1587 cgroup_put(&root->top_cgroup);
1591 static void cgroup_kill_sb(struct super_block *sb)
1593 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1594 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1596 cgroup_put(&root->top_cgroup);
1600 static struct file_system_type cgroup_fs_type = {
1602 .mount = cgroup_mount,
1603 .kill_sb = cgroup_kill_sb,
1606 static struct kobject *cgroup_kobj;
1609 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1610 * @task: target task
1611 * @buf: the buffer to write the path into
1612 * @buflen: the length of the buffer
1614 * Determine @task's cgroup on the first (the one with the lowest non-zero
1615 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1616 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1617 * cgroup controller callbacks.
1619 * Return value is the same as kernfs_path().
1621 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1623 struct cgroupfs_root *root;
1624 struct cgroup *cgrp;
1625 int hierarchy_id = 1;
1628 mutex_lock(&cgroup_mutex);
1629 down_read(&css_set_rwsem);
1631 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1634 cgrp = task_cgroup_from_root(task, root);
1635 path = cgroup_path(cgrp, buf, buflen);
1637 /* if no hierarchy exists, everyone is in "/" */
1638 if (strlcpy(buf, "/", buflen) < buflen)
1642 up_read(&css_set_rwsem);
1643 mutex_unlock(&cgroup_mutex);
1646 EXPORT_SYMBOL_GPL(task_cgroup_path);
1648 /* used to track tasks and other necessary states during migration */
1649 struct cgroup_taskset {
1650 /* the src and dst cset list running through cset->mg_node */
1651 struct list_head src_csets;
1652 struct list_head dst_csets;
1655 * Fields for cgroup_taskset_*() iteration.
1657 * Before migration is committed, the target migration tasks are on
1658 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1659 * the csets on ->dst_csets. ->csets point to either ->src_csets
1660 * or ->dst_csets depending on whether migration is committed.
1662 * ->cur_csets and ->cur_task point to the current task position
1665 struct list_head *csets;
1666 struct css_set *cur_cset;
1667 struct task_struct *cur_task;
1671 * cgroup_taskset_first - reset taskset and return the first task
1672 * @tset: taskset of interest
1674 * @tset iteration is initialized and the first task is returned.
1676 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1678 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1679 tset->cur_task = NULL;
1681 return cgroup_taskset_next(tset);
1685 * cgroup_taskset_next - iterate to the next task in taskset
1686 * @tset: taskset of interest
1688 * Return the next task in @tset. Iteration must have been initialized
1689 * with cgroup_taskset_first().
1691 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1693 struct css_set *cset = tset->cur_cset;
1694 struct task_struct *task = tset->cur_task;
1696 while (&cset->mg_node != tset->csets) {
1698 task = list_first_entry(&cset->mg_tasks,
1699 struct task_struct, cg_list);
1701 task = list_next_entry(task, cg_list);
1703 if (&task->cg_list != &cset->mg_tasks) {
1704 tset->cur_cset = cset;
1705 tset->cur_task = task;
1709 cset = list_next_entry(cset, mg_node);
1717 * cgroup_task_migrate - move a task from one cgroup to another.
1718 * @old_cgrp; the cgroup @tsk is being migrated from
1719 * @tsk: the task being migrated
1720 * @new_cset: the new css_set @tsk is being attached to
1722 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1724 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1725 struct task_struct *tsk,
1726 struct css_set *new_cset)
1728 struct css_set *old_cset;
1730 lockdep_assert_held(&cgroup_mutex);
1731 lockdep_assert_held(&css_set_rwsem);
1734 * We are synchronized through threadgroup_lock() against PF_EXITING
1735 * setting such that we can't race against cgroup_exit() changing the
1736 * css_set to init_css_set and dropping the old one.
1738 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1739 old_cset = task_css_set(tsk);
1741 get_css_set(new_cset);
1744 rcu_assign_pointer(tsk->cgroups, new_cset);
1747 list_move(&tsk->cg_list, &new_cset->mg_tasks);
1750 * We just gained a reference on old_cset by taking it from the
1751 * task. As trading it for new_cset is protected by cgroup_mutex,
1752 * we're safe to drop it here; it will be freed under RCU.
1754 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1755 put_css_set_locked(old_cset, false);
1759 * cgroup_migrate_finish - cleanup after attach
1760 * @preloaded_csets: list of preloaded css_sets
1762 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1763 * those functions for details.
1765 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1767 struct css_set *cset, *tmp_cset;
1769 lockdep_assert_held(&cgroup_mutex);
1771 down_write(&css_set_rwsem);
1772 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1773 cset->mg_src_cgrp = NULL;
1774 cset->mg_dst_cset = NULL;
1775 list_del_init(&cset->mg_preload_node);
1776 put_css_set_locked(cset, false);
1778 up_write(&css_set_rwsem);
1782 * cgroup_migrate_add_src - add a migration source css_set
1783 * @src_cset: the source css_set to add
1784 * @dst_cgrp: the destination cgroup
1785 * @preloaded_csets: list of preloaded css_sets
1787 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1788 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1789 * up by cgroup_migrate_finish().
1791 * This function may be called without holding threadgroup_lock even if the
1792 * target is a process. Threads may be created and destroyed but as long
1793 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1794 * the preloaded css_sets are guaranteed to cover all migrations.
1796 static void cgroup_migrate_add_src(struct css_set *src_cset,
1797 struct cgroup *dst_cgrp,
1798 struct list_head *preloaded_csets)
1800 struct cgroup *src_cgrp;
1802 lockdep_assert_held(&cgroup_mutex);
1803 lockdep_assert_held(&css_set_rwsem);
1805 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
1807 /* nothing to do if this cset already belongs to the cgroup */
1808 if (src_cgrp == dst_cgrp)
1811 if (!list_empty(&src_cset->mg_preload_node))
1814 WARN_ON(src_cset->mg_src_cgrp);
1815 WARN_ON(!list_empty(&src_cset->mg_tasks));
1816 WARN_ON(!list_empty(&src_cset->mg_node));
1818 src_cset->mg_src_cgrp = src_cgrp;
1819 get_css_set(src_cset);
1820 list_add(&src_cset->mg_preload_node, preloaded_csets);
1824 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
1825 * @dst_cgrp: the destination cgroup
1826 * @preloaded_csets: list of preloaded source css_sets
1828 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
1829 * have been preloaded to @preloaded_csets. This function looks up and
1830 * pins all destination css_sets, links each to its source, and put them on
1833 * This function must be called after cgroup_migrate_add_src() has been
1834 * called on each migration source css_set. After migration is performed
1835 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
1838 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
1839 struct list_head *preloaded_csets)
1842 struct css_set *src_cset;
1844 lockdep_assert_held(&cgroup_mutex);
1846 /* look up the dst cset for each src cset and link it to src */
1847 list_for_each_entry(src_cset, preloaded_csets, mg_preload_node) {
1848 struct css_set *dst_cset;
1850 dst_cset = find_css_set(src_cset, dst_cgrp);
1854 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
1855 src_cset->mg_dst_cset = dst_cset;
1857 if (list_empty(&dst_cset->mg_preload_node))
1858 list_add(&dst_cset->mg_preload_node, &csets);
1860 put_css_set(dst_cset, false);
1863 list_splice(&csets, preloaded_csets);
1866 cgroup_migrate_finish(&csets);
1871 * cgroup_migrate - migrate a process or task to a cgroup
1872 * @cgrp: the destination cgroup
1873 * @leader: the leader of the process or the task to migrate
1874 * @threadgroup: whether @leader points to the whole process or a single task
1876 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
1877 * process, the caller must be holding threadgroup_lock of @leader. The
1878 * caller is also responsible for invoking cgroup_migrate_add_src() and
1879 * cgroup_migrate_prepare_dst() on the targets before invoking this
1880 * function and following up with cgroup_migrate_finish().
1882 * As long as a controller's ->can_attach() doesn't fail, this function is
1883 * guaranteed to succeed. This means that, excluding ->can_attach()
1884 * failure, when migrating multiple targets, the success or failure can be
1885 * decided for all targets by invoking group_migrate_prepare_dst() before
1886 * actually starting migrating.
1888 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
1891 struct cgroup_taskset tset = {
1892 .src_csets = LIST_HEAD_INIT(tset.src_csets),
1893 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
1894 .csets = &tset.src_csets,
1896 struct cgroup_subsys_state *css, *failed_css = NULL;
1897 struct css_set *cset, *tmp_cset;
1898 struct task_struct *task, *tmp_task;
1902 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1903 * already PF_EXITING could be freed from underneath us unless we
1904 * take an rcu_read_lock.
1906 down_write(&css_set_rwsem);
1910 /* @task either already exited or can't exit until the end */
1911 if (task->flags & PF_EXITING)
1914 cset = task_css_set(task);
1915 if (!cset->mg_src_cgrp)
1918 list_move(&task->cg_list, &cset->mg_tasks);
1919 list_move(&cset->mg_node, &tset.src_csets);
1920 list_move(&cset->mg_dst_cset->mg_node, &tset.dst_csets);
1924 } while_each_thread(leader, task);
1926 up_write(&css_set_rwsem);
1928 /* methods shouldn't be called if no task is actually migrating */
1929 if (list_empty(&tset.src_csets))
1932 /* check that we can legitimately attach to the cgroup */
1933 for_each_css(css, i, cgrp) {
1934 if (css->ss->can_attach) {
1935 ret = css->ss->can_attach(css, &tset);
1938 goto out_cancel_attach;
1944 * Now that we're guaranteed success, proceed to move all tasks to
1945 * the new cgroup. There are no failure cases after here, so this
1946 * is the commit point.
1948 down_write(&css_set_rwsem);
1949 list_for_each_entry(cset, &tset.src_csets, mg_node) {
1950 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
1951 cgroup_task_migrate(cset->mg_src_cgrp, task,
1954 up_write(&css_set_rwsem);
1957 * Migration is committed, all target tasks are now on dst_csets.
1958 * Nothing is sensitive to fork() after this point. Notify
1959 * controllers that migration is complete.
1961 tset.csets = &tset.dst_csets;
1963 for_each_css(css, i, cgrp)
1964 if (css->ss->attach)
1965 css->ss->attach(css, &tset);
1968 goto out_release_tset;
1971 for_each_css(css, i, cgrp) {
1972 if (css == failed_css)
1974 if (css->ss->cancel_attach)
1975 css->ss->cancel_attach(css, &tset);
1978 down_write(&css_set_rwsem);
1979 list_splice_init(&tset.dst_csets, &tset.src_csets);
1980 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
1981 list_splice_init(&cset->mg_tasks, &cset->tasks);
1982 list_del_init(&cset->mg_node);
1984 up_write(&css_set_rwsem);
1989 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1990 * @dst_cgrp: the cgroup to attach to
1991 * @leader: the task or the leader of the threadgroup to be attached
1992 * @threadgroup: attach the whole threadgroup?
1994 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1995 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1997 static int cgroup_attach_task(struct cgroup *dst_cgrp,
1998 struct task_struct *leader, bool threadgroup)
2000 LIST_HEAD(preloaded_csets);
2001 struct task_struct *task;
2004 /* look up all src csets */
2005 down_read(&css_set_rwsem);
2009 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2013 } while_each_thread(leader, task);
2015 up_read(&css_set_rwsem);
2017 /* prepare dst csets and commit */
2018 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2020 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2022 cgroup_migrate_finish(&preloaded_csets);
2027 * Find the task_struct of the task to attach by vpid and pass it along to the
2028 * function to attach either it or all tasks in its threadgroup. Will lock
2029 * cgroup_mutex and threadgroup; may take task_lock of task.
2031 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2033 struct task_struct *tsk;
2034 const struct cred *cred = current_cred(), *tcred;
2037 if (!cgroup_lock_live_group(cgrp))
2043 tsk = find_task_by_vpid(pid);
2047 goto out_unlock_cgroup;
2050 * even if we're attaching all tasks in the thread group, we
2051 * only need to check permissions on one of them.
2053 tcred = __task_cred(tsk);
2054 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2055 !uid_eq(cred->euid, tcred->uid) &&
2056 !uid_eq(cred->euid, tcred->suid)) {
2059 goto out_unlock_cgroup;
2065 tsk = tsk->group_leader;
2068 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2069 * trapped in a cpuset, or RT worker may be born in a cgroup
2070 * with no rt_runtime allocated. Just say no.
2072 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2075 goto out_unlock_cgroup;
2078 get_task_struct(tsk);
2081 threadgroup_lock(tsk);
2083 if (!thread_group_leader(tsk)) {
2085 * a race with de_thread from another thread's exec()
2086 * may strip us of our leadership, if this happens,
2087 * there is no choice but to throw this task away and
2088 * try again; this is
2089 * "double-double-toil-and-trouble-check locking".
2091 threadgroup_unlock(tsk);
2092 put_task_struct(tsk);
2093 goto retry_find_task;
2097 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2099 threadgroup_unlock(tsk);
2101 put_task_struct(tsk);
2103 mutex_unlock(&cgroup_mutex);
2108 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2109 * @from: attach to all cgroups of a given task
2110 * @tsk: the task to be attached
2112 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2114 struct cgroupfs_root *root;
2117 mutex_lock(&cgroup_mutex);
2118 for_each_active_root(root) {
2119 struct cgroup *from_cgrp;
2121 down_read(&css_set_rwsem);
2122 from_cgrp = task_cgroup_from_root(from, root);
2123 up_read(&css_set_rwsem);
2125 retval = cgroup_attach_task(from_cgrp, tsk, false);
2129 mutex_unlock(&cgroup_mutex);
2133 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2135 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2136 struct cftype *cft, u64 pid)
2138 return attach_task_by_pid(css->cgroup, pid, false);
2141 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2142 struct cftype *cft, u64 tgid)
2144 return attach_task_by_pid(css->cgroup, tgid, true);
2147 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2148 struct cftype *cft, const char *buffer)
2150 struct cgroupfs_root *root = css->cgroup->root;
2152 BUILD_BUG_ON(sizeof(root->release_agent_path) < PATH_MAX);
2153 if (!cgroup_lock_live_group(css->cgroup))
2155 spin_lock(&release_agent_path_lock);
2156 strlcpy(root->release_agent_path, buffer,
2157 sizeof(root->release_agent_path));
2158 spin_unlock(&release_agent_path_lock);
2159 mutex_unlock(&cgroup_mutex);
2163 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2165 struct cgroup *cgrp = seq_css(seq)->cgroup;
2167 if (!cgroup_lock_live_group(cgrp))
2169 seq_puts(seq, cgrp->root->release_agent_path);
2170 seq_putc(seq, '\n');
2171 mutex_unlock(&cgroup_mutex);
2175 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2177 struct cgroup *cgrp = seq_css(seq)->cgroup;
2179 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2183 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2184 size_t nbytes, loff_t off)
2186 struct cgroup *cgrp = of->kn->parent->priv;
2187 struct cftype *cft = of->kn->priv;
2188 struct cgroup_subsys_state *css;
2192 * kernfs guarantees that a file isn't deleted with operations in
2193 * flight, which means that the matching css is and stays alive and
2194 * doesn't need to be pinned. The RCU locking is not necessary
2195 * either. It's just for the convenience of using cgroup_css().
2198 css = cgroup_css(cgrp, cft->ss);
2201 if (cft->write_string) {
2202 ret = cft->write_string(css, cft, strstrip(buf));
2203 } else if (cft->write_u64) {
2204 unsigned long long v;
2205 ret = kstrtoull(buf, 0, &v);
2207 ret = cft->write_u64(css, cft, v);
2208 } else if (cft->write_s64) {
2210 ret = kstrtoll(buf, 0, &v);
2212 ret = cft->write_s64(css, cft, v);
2213 } else if (cft->trigger) {
2214 ret = cft->trigger(css, (unsigned int)cft->private);
2219 return ret ?: nbytes;
2222 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2224 return seq_cft(seq)->seq_start(seq, ppos);
2227 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2229 return seq_cft(seq)->seq_next(seq, v, ppos);
2232 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2234 seq_cft(seq)->seq_stop(seq, v);
2237 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2239 struct cftype *cft = seq_cft(m);
2240 struct cgroup_subsys_state *css = seq_css(m);
2243 return cft->seq_show(m, arg);
2246 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2247 else if (cft->read_s64)
2248 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2254 static struct kernfs_ops cgroup_kf_single_ops = {
2255 .atomic_write_len = PAGE_SIZE,
2256 .write = cgroup_file_write,
2257 .seq_show = cgroup_seqfile_show,
2260 static struct kernfs_ops cgroup_kf_ops = {
2261 .atomic_write_len = PAGE_SIZE,
2262 .write = cgroup_file_write,
2263 .seq_start = cgroup_seqfile_start,
2264 .seq_next = cgroup_seqfile_next,
2265 .seq_stop = cgroup_seqfile_stop,
2266 .seq_show = cgroup_seqfile_show,
2270 * cgroup_rename - Only allow simple rename of directories in place.
2272 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2273 const char *new_name_str)
2275 struct cgroup *cgrp = kn->priv;
2278 if (kernfs_type(kn) != KERNFS_DIR)
2280 if (kn->parent != new_parent)
2284 * This isn't a proper migration and its usefulness is very
2285 * limited. Disallow if sane_behavior.
2287 if (cgroup_sane_behavior(cgrp))
2290 mutex_lock(&cgroup_tree_mutex);
2291 mutex_lock(&cgroup_mutex);
2293 ret = kernfs_rename(kn, new_parent, new_name_str);
2295 mutex_unlock(&cgroup_mutex);
2296 mutex_unlock(&cgroup_tree_mutex);
2300 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2302 char name[CGROUP_FILE_NAME_MAX];
2303 struct kernfs_node *kn;
2304 struct lock_class_key *key = NULL;
2306 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2307 key = &cft->lockdep_key;
2309 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2310 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2312 return PTR_ERR_OR_ZERO(kn);
2316 * cgroup_addrm_files - add or remove files to a cgroup directory
2317 * @cgrp: the target cgroup
2318 * @cfts: array of cftypes to be added
2319 * @is_add: whether to add or remove
2321 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2322 * For removals, this function never fails. If addition fails, this
2323 * function doesn't remove files already added. The caller is responsible
2326 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2332 lockdep_assert_held(&cgroup_tree_mutex);
2334 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2335 /* does cft->flags tell us to skip this file on @cgrp? */
2336 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2338 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2340 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2344 ret = cgroup_add_file(cgrp, cft);
2346 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2351 cgroup_rm_file(cgrp, cft);
2357 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2360 struct cgroup_subsys *ss = cfts[0].ss;
2361 struct cgroup *root = &ss->root->top_cgroup;
2362 struct cgroup_subsys_state *css;
2365 lockdep_assert_held(&cgroup_tree_mutex);
2367 /* don't bother if @ss isn't attached */
2368 if (ss->root == &cgroup_dummy_root)
2371 /* add/rm files for all cgroups created before */
2372 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2373 struct cgroup *cgrp = css->cgroup;
2375 if (cgroup_is_dead(cgrp))
2378 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2384 kernfs_activate(root->kn);
2388 static void cgroup_exit_cftypes(struct cftype *cfts)
2392 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2393 /* free copy for custom atomic_write_len, see init_cftypes() */
2394 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2401 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2405 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2406 struct kernfs_ops *kf_ops;
2408 WARN_ON(cft->ss || cft->kf_ops);
2411 kf_ops = &cgroup_kf_ops;
2413 kf_ops = &cgroup_kf_single_ops;
2416 * Ugh... if @cft wants a custom max_write_len, we need to
2417 * make a copy of kf_ops to set its atomic_write_len.
2419 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2420 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
2422 cgroup_exit_cftypes(cfts);
2425 kf_ops->atomic_write_len = cft->max_write_len;
2428 cft->kf_ops = kf_ops;
2435 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
2437 lockdep_assert_held(&cgroup_tree_mutex);
2439 if (!cfts || !cfts[0].ss)
2442 list_del(&cfts->node);
2443 cgroup_apply_cftypes(cfts, false);
2444 cgroup_exit_cftypes(cfts);
2449 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2450 * @cfts: zero-length name terminated array of cftypes
2452 * Unregister @cfts. Files described by @cfts are removed from all
2453 * existing cgroups and all future cgroups won't have them either. This
2454 * function can be called anytime whether @cfts' subsys is attached or not.
2456 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2459 int cgroup_rm_cftypes(struct cftype *cfts)
2463 mutex_lock(&cgroup_tree_mutex);
2464 ret = cgroup_rm_cftypes_locked(cfts);
2465 mutex_unlock(&cgroup_tree_mutex);
2470 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2471 * @ss: target cgroup subsystem
2472 * @cfts: zero-length name terminated array of cftypes
2474 * Register @cfts to @ss. Files described by @cfts are created for all
2475 * existing cgroups to which @ss is attached and all future cgroups will
2476 * have them too. This function can be called anytime whether @ss is
2479 * Returns 0 on successful registration, -errno on failure. Note that this
2480 * function currently returns 0 as long as @cfts registration is successful
2481 * even if some file creation attempts on existing cgroups fail.
2483 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2487 if (!cfts || cfts[0].name[0] == '\0')
2490 ret = cgroup_init_cftypes(ss, cfts);
2494 mutex_lock(&cgroup_tree_mutex);
2496 list_add_tail(&cfts->node, &ss->cfts);
2497 ret = cgroup_apply_cftypes(cfts, true);
2499 cgroup_rm_cftypes_locked(cfts);
2501 mutex_unlock(&cgroup_tree_mutex);
2506 * cgroup_task_count - count the number of tasks in a cgroup.
2507 * @cgrp: the cgroup in question
2509 * Return the number of tasks in the cgroup.
2511 static int cgroup_task_count(const struct cgroup *cgrp)
2514 struct cgrp_cset_link *link;
2516 down_read(&css_set_rwsem);
2517 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2518 count += atomic_read(&link->cset->refcount);
2519 up_read(&css_set_rwsem);
2524 * css_next_child - find the next child of a given css
2525 * @pos_css: the current position (%NULL to initiate traversal)
2526 * @parent_css: css whose children to walk
2528 * This function returns the next child of @parent_css and should be called
2529 * under either cgroup_mutex or RCU read lock. The only requirement is
2530 * that @parent_css and @pos_css are accessible. The next sibling is
2531 * guaranteed to be returned regardless of their states.
2533 struct cgroup_subsys_state *
2534 css_next_child(struct cgroup_subsys_state *pos_css,
2535 struct cgroup_subsys_state *parent_css)
2537 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2538 struct cgroup *cgrp = parent_css->cgroup;
2539 struct cgroup *next;
2541 cgroup_assert_mutexes_or_rcu_locked();
2544 * @pos could already have been removed. Once a cgroup is removed,
2545 * its ->sibling.next is no longer updated when its next sibling
2546 * changes. As CGRP_DEAD assertion is serialized and happens
2547 * before the cgroup is taken off the ->sibling list, if we see it
2548 * unasserted, it's guaranteed that the next sibling hasn't
2549 * finished its grace period even if it's already removed, and thus
2550 * safe to dereference from this RCU critical section. If
2551 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2552 * to be visible as %true here.
2554 * If @pos is dead, its next pointer can't be dereferenced;
2555 * however, as each cgroup is given a monotonically increasing
2556 * unique serial number and always appended to the sibling list,
2557 * the next one can be found by walking the parent's children until
2558 * we see a cgroup with higher serial number than @pos's. While
2559 * this path can be slower, it's taken only when either the current
2560 * cgroup is removed or iteration and removal race.
2563 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2564 } else if (likely(!cgroup_is_dead(pos))) {
2565 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2567 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2568 if (next->serial_nr > pos->serial_nr)
2572 if (&next->sibling == &cgrp->children)
2575 return cgroup_css(next, parent_css->ss);
2579 * css_next_descendant_pre - find the next descendant for pre-order walk
2580 * @pos: the current position (%NULL to initiate traversal)
2581 * @root: css whose descendants to walk
2583 * To be used by css_for_each_descendant_pre(). Find the next descendant
2584 * to visit for pre-order traversal of @root's descendants. @root is
2585 * included in the iteration and the first node to be visited.
2587 * While this function requires cgroup_mutex or RCU read locking, it
2588 * doesn't require the whole traversal to be contained in a single critical
2589 * section. This function will return the correct next descendant as long
2590 * as both @pos and @root are accessible and @pos is a descendant of @root.
2592 struct cgroup_subsys_state *
2593 css_next_descendant_pre(struct cgroup_subsys_state *pos,
2594 struct cgroup_subsys_state *root)
2596 struct cgroup_subsys_state *next;
2598 cgroup_assert_mutexes_or_rcu_locked();
2600 /* if first iteration, visit @root */
2604 /* visit the first child if exists */
2605 next = css_next_child(NULL, pos);
2609 /* no child, visit my or the closest ancestor's next sibling */
2610 while (pos != root) {
2611 next = css_next_child(pos, css_parent(pos));
2614 pos = css_parent(pos);
2621 * css_rightmost_descendant - return the rightmost descendant of a css
2622 * @pos: css of interest
2624 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2625 * is returned. This can be used during pre-order traversal to skip
2628 * While this function requires cgroup_mutex or RCU read locking, it
2629 * doesn't require the whole traversal to be contained in a single critical
2630 * section. This function will return the correct rightmost descendant as
2631 * long as @pos is accessible.
2633 struct cgroup_subsys_state *
2634 css_rightmost_descendant(struct cgroup_subsys_state *pos)
2636 struct cgroup_subsys_state *last, *tmp;
2638 cgroup_assert_mutexes_or_rcu_locked();
2642 /* ->prev isn't RCU safe, walk ->next till the end */
2644 css_for_each_child(tmp, last)
2651 static struct cgroup_subsys_state *
2652 css_leftmost_descendant(struct cgroup_subsys_state *pos)
2654 struct cgroup_subsys_state *last;
2658 pos = css_next_child(NULL, pos);
2665 * css_next_descendant_post - find the next descendant for post-order walk
2666 * @pos: the current position (%NULL to initiate traversal)
2667 * @root: css whose descendants to walk
2669 * To be used by css_for_each_descendant_post(). Find the next descendant
2670 * to visit for post-order traversal of @root's descendants. @root is
2671 * included in the iteration and the last node to be visited.
2673 * While this function requires cgroup_mutex or RCU read locking, it
2674 * doesn't require the whole traversal to be contained in a single critical
2675 * section. This function will return the correct next descendant as long
2676 * as both @pos and @cgroup are accessible and @pos is a descendant of
2679 struct cgroup_subsys_state *
2680 css_next_descendant_post(struct cgroup_subsys_state *pos,
2681 struct cgroup_subsys_state *root)
2683 struct cgroup_subsys_state *next;
2685 cgroup_assert_mutexes_or_rcu_locked();
2687 /* if first iteration, visit leftmost descendant which may be @root */
2689 return css_leftmost_descendant(root);
2691 /* if we visited @root, we're done */
2695 /* if there's an unvisited sibling, visit its leftmost descendant */
2696 next = css_next_child(pos, css_parent(pos));
2698 return css_leftmost_descendant(next);
2700 /* no sibling left, visit parent */
2701 return css_parent(pos);
2705 * css_advance_task_iter - advance a task itererator to the next css_set
2706 * @it: the iterator to advance
2708 * Advance @it to the next css_set to walk.
2710 static void css_advance_task_iter(struct css_task_iter *it)
2712 struct list_head *l = it->cset_link;
2713 struct cgrp_cset_link *link;
2714 struct css_set *cset;
2716 /* Advance to the next non-empty css_set */
2719 if (l == &it->origin_css->cgroup->cset_links) {
2720 it->cset_link = NULL;
2723 link = list_entry(l, struct cgrp_cset_link, cset_link);
2725 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
2729 if (!list_empty(&cset->tasks))
2730 it->task = cset->tasks.next;
2732 it->task = cset->mg_tasks.next;
2736 * css_task_iter_start - initiate task iteration
2737 * @css: the css to walk tasks of
2738 * @it: the task iterator to use
2740 * Initiate iteration through the tasks of @css. The caller can call
2741 * css_task_iter_next() to walk through the tasks until the function
2742 * returns NULL. On completion of iteration, css_task_iter_end() must be
2745 * Note that this function acquires a lock which is released when the
2746 * iteration finishes. The caller can't sleep while iteration is in
2749 void css_task_iter_start(struct cgroup_subsys_state *css,
2750 struct css_task_iter *it)
2751 __acquires(css_set_rwsem)
2753 /* no one should try to iterate before mounting cgroups */
2754 WARN_ON_ONCE(!use_task_css_set_links);
2756 down_read(&css_set_rwsem);
2758 it->origin_css = css;
2759 it->cset_link = &css->cgroup->cset_links;
2761 css_advance_task_iter(it);
2765 * css_task_iter_next - return the next task for the iterator
2766 * @it: the task iterator being iterated
2768 * The "next" function for task iteration. @it should have been
2769 * initialized via css_task_iter_start(). Returns NULL when the iteration
2772 struct task_struct *css_task_iter_next(struct css_task_iter *it)
2774 struct task_struct *res;
2775 struct list_head *l = it->task;
2776 struct cgrp_cset_link *link = list_entry(it->cset_link,
2777 struct cgrp_cset_link, cset_link);
2779 /* If the iterator cg is NULL, we have no tasks */
2782 res = list_entry(l, struct task_struct, cg_list);
2785 * Advance iterator to find next entry. cset->tasks is consumed
2786 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
2791 if (l == &link->cset->tasks)
2792 l = link->cset->mg_tasks.next;
2794 if (l == &link->cset->mg_tasks)
2795 css_advance_task_iter(it);
2803 * css_task_iter_end - finish task iteration
2804 * @it: the task iterator to finish
2806 * Finish task iteration started by css_task_iter_start().
2808 void css_task_iter_end(struct css_task_iter *it)
2809 __releases(css_set_rwsem)
2811 up_read(&css_set_rwsem);
2815 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
2816 * @to: cgroup to which the tasks will be moved
2817 * @from: cgroup in which the tasks currently reside
2819 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
2821 struct css_task_iter it;
2822 struct task_struct *task;
2826 css_task_iter_start(&from->dummy_css, &it);
2827 task = css_task_iter_next(&it);
2829 get_task_struct(task);
2830 css_task_iter_end(&it);
2833 mutex_lock(&cgroup_mutex);
2834 ret = cgroup_attach_task(to, task, false);
2835 mutex_unlock(&cgroup_mutex);
2836 put_task_struct(task);
2838 } while (task && !ret);
2844 * Stuff for reading the 'tasks'/'procs' files.
2846 * Reading this file can return large amounts of data if a cgroup has
2847 * *lots* of attached tasks. So it may need several calls to read(),
2848 * but we cannot guarantee that the information we produce is correct
2849 * unless we produce it entirely atomically.
2853 /* which pidlist file are we talking about? */
2854 enum cgroup_filetype {
2860 * A pidlist is a list of pids that virtually represents the contents of one
2861 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
2862 * a pair (one each for procs, tasks) for each pid namespace that's relevant
2865 struct cgroup_pidlist {
2867 * used to find which pidlist is wanted. doesn't change as long as
2868 * this particular list stays in the list.
2870 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
2873 /* how many elements the above list has */
2875 /* each of these stored in a list by its cgroup */
2876 struct list_head links;
2877 /* pointer to the cgroup we belong to, for list removal purposes */
2878 struct cgroup *owner;
2879 /* for delayed destruction */
2880 struct delayed_work destroy_dwork;
2884 * The following two functions "fix" the issue where there are more pids
2885 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
2886 * TODO: replace with a kernel-wide solution to this problem
2888 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
2889 static void *pidlist_allocate(int count)
2891 if (PIDLIST_TOO_LARGE(count))
2892 return vmalloc(count * sizeof(pid_t));
2894 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
2897 static void pidlist_free(void *p)
2899 if (is_vmalloc_addr(p))
2906 * Used to destroy all pidlists lingering waiting for destroy timer. None
2907 * should be left afterwards.
2909 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
2911 struct cgroup_pidlist *l, *tmp_l;
2913 mutex_lock(&cgrp->pidlist_mutex);
2914 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
2915 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
2916 mutex_unlock(&cgrp->pidlist_mutex);
2918 flush_workqueue(cgroup_pidlist_destroy_wq);
2919 BUG_ON(!list_empty(&cgrp->pidlists));
2922 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
2924 struct delayed_work *dwork = to_delayed_work(work);
2925 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
2927 struct cgroup_pidlist *tofree = NULL;
2929 mutex_lock(&l->owner->pidlist_mutex);
2932 * Destroy iff we didn't get queued again. The state won't change
2933 * as destroy_dwork can only be queued while locked.
2935 if (!delayed_work_pending(dwork)) {
2936 list_del(&l->links);
2937 pidlist_free(l->list);
2938 put_pid_ns(l->key.ns);
2942 mutex_unlock(&l->owner->pidlist_mutex);
2947 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
2948 * Returns the number of unique elements.
2950 static int pidlist_uniq(pid_t *list, int length)
2955 * we presume the 0th element is unique, so i starts at 1. trivial
2956 * edge cases first; no work needs to be done for either
2958 if (length == 0 || length == 1)
2960 /* src and dest walk down the list; dest counts unique elements */
2961 for (src = 1; src < length; src++) {
2962 /* find next unique element */
2963 while (list[src] == list[src-1]) {
2968 /* dest always points to where the next unique element goes */
2969 list[dest] = list[src];
2977 * The two pid files - task and cgroup.procs - guaranteed that the result
2978 * is sorted, which forced this whole pidlist fiasco. As pid order is
2979 * different per namespace, each namespace needs differently sorted list,
2980 * making it impossible to use, for example, single rbtree of member tasks
2981 * sorted by task pointer. As pidlists can be fairly large, allocating one
2982 * per open file is dangerous, so cgroup had to implement shared pool of
2983 * pidlists keyed by cgroup and namespace.
2985 * All this extra complexity was caused by the original implementation
2986 * committing to an entirely unnecessary property. In the long term, we
2987 * want to do away with it. Explicitly scramble sort order if
2988 * sane_behavior so that no such expectation exists in the new interface.
2990 * Scrambling is done by swapping every two consecutive bits, which is
2991 * non-identity one-to-one mapping which disturbs sort order sufficiently.
2993 static pid_t pid_fry(pid_t pid)
2995 unsigned a = pid & 0x55555555;
2996 unsigned b = pid & 0xAAAAAAAA;
2998 return (a << 1) | (b >> 1);
3001 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3003 if (cgroup_sane_behavior(cgrp))
3004 return pid_fry(pid);
3009 static int cmppid(const void *a, const void *b)
3011 return *(pid_t *)a - *(pid_t *)b;
3014 static int fried_cmppid(const void *a, const void *b)
3016 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3019 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3020 enum cgroup_filetype type)
3022 struct cgroup_pidlist *l;
3023 /* don't need task_nsproxy() if we're looking at ourself */
3024 struct pid_namespace *ns = task_active_pid_ns(current);
3026 lockdep_assert_held(&cgrp->pidlist_mutex);
3028 list_for_each_entry(l, &cgrp->pidlists, links)
3029 if (l->key.type == type && l->key.ns == ns)
3035 * find the appropriate pidlist for our purpose (given procs vs tasks)
3036 * returns with the lock on that pidlist already held, and takes care
3037 * of the use count, or returns NULL with no locks held if we're out of
3040 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3041 enum cgroup_filetype type)
3043 struct cgroup_pidlist *l;
3045 lockdep_assert_held(&cgrp->pidlist_mutex);
3047 l = cgroup_pidlist_find(cgrp, type);
3051 /* entry not found; create a new one */
3052 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3056 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3058 /* don't need task_nsproxy() if we're looking at ourself */
3059 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3061 list_add(&l->links, &cgrp->pidlists);
3066 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3068 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3069 struct cgroup_pidlist **lp)
3073 int pid, n = 0; /* used for populating the array */
3074 struct css_task_iter it;
3075 struct task_struct *tsk;
3076 struct cgroup_pidlist *l;
3078 lockdep_assert_held(&cgrp->pidlist_mutex);
3081 * If cgroup gets more users after we read count, we won't have
3082 * enough space - tough. This race is indistinguishable to the
3083 * caller from the case that the additional cgroup users didn't
3084 * show up until sometime later on.
3086 length = cgroup_task_count(cgrp);
3087 array = pidlist_allocate(length);
3090 /* now, populate the array */
3091 css_task_iter_start(&cgrp->dummy_css, &it);
3092 while ((tsk = css_task_iter_next(&it))) {
3093 if (unlikely(n == length))
3095 /* get tgid or pid for procs or tasks file respectively */
3096 if (type == CGROUP_FILE_PROCS)
3097 pid = task_tgid_vnr(tsk);
3099 pid = task_pid_vnr(tsk);
3100 if (pid > 0) /* make sure to only use valid results */
3103 css_task_iter_end(&it);
3105 /* now sort & (if procs) strip out duplicates */
3106 if (cgroup_sane_behavior(cgrp))
3107 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3109 sort(array, length, sizeof(pid_t), cmppid, NULL);
3110 if (type == CGROUP_FILE_PROCS)
3111 length = pidlist_uniq(array, length);
3113 l = cgroup_pidlist_find_create(cgrp, type);
3115 mutex_unlock(&cgrp->pidlist_mutex);
3116 pidlist_free(array);
3120 /* store array, freeing old if necessary */
3121 pidlist_free(l->list);
3129 * cgroupstats_build - build and fill cgroupstats
3130 * @stats: cgroupstats to fill information into
3131 * @dentry: A dentry entry belonging to the cgroup for which stats have
3134 * Build and fill cgroupstats so that taskstats can export it to user
3137 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3139 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3140 struct cgroup *cgrp;
3141 struct css_task_iter it;
3142 struct task_struct *tsk;
3144 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3145 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3146 kernfs_type(kn) != KERNFS_DIR)
3149 mutex_lock(&cgroup_mutex);
3152 * We aren't being called from kernfs and there's no guarantee on
3153 * @kn->priv's validity. For this and css_tryget_from_dir(),
3154 * @kn->priv is RCU safe. Let's do the RCU dancing.
3157 cgrp = rcu_dereference(kn->priv);
3158 if (!cgrp || cgroup_is_dead(cgrp)) {
3160 mutex_unlock(&cgroup_mutex);
3165 css_task_iter_start(&cgrp->dummy_css, &it);
3166 while ((tsk = css_task_iter_next(&it))) {
3167 switch (tsk->state) {
3169 stats->nr_running++;
3171 case TASK_INTERRUPTIBLE:
3172 stats->nr_sleeping++;
3174 case TASK_UNINTERRUPTIBLE:
3175 stats->nr_uninterruptible++;
3178 stats->nr_stopped++;
3181 if (delayacct_is_task_waiting_on_io(tsk))
3182 stats->nr_io_wait++;
3186 css_task_iter_end(&it);
3188 mutex_unlock(&cgroup_mutex);
3194 * seq_file methods for the tasks/procs files. The seq_file position is the
3195 * next pid to display; the seq_file iterator is a pointer to the pid
3196 * in the cgroup->l->list array.
3199 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3202 * Initially we receive a position value that corresponds to
3203 * one more than the last pid shown (or 0 on the first call or
3204 * after a seek to the start). Use a binary-search to find the
3205 * next pid to display, if any
3207 struct kernfs_open_file *of = s->private;
3208 struct cgroup *cgrp = seq_css(s)->cgroup;
3209 struct cgroup_pidlist *l;
3210 enum cgroup_filetype type = seq_cft(s)->private;
3211 int index = 0, pid = *pos;
3214 mutex_lock(&cgrp->pidlist_mutex);
3217 * !NULL @of->priv indicates that this isn't the first start()
3218 * after open. If the matching pidlist is around, we can use that.
3219 * Look for it. Note that @of->priv can't be used directly. It
3220 * could already have been destroyed.
3223 of->priv = cgroup_pidlist_find(cgrp, type);
3226 * Either this is the first start() after open or the matching
3227 * pidlist has been destroyed inbetween. Create a new one.
3230 ret = pidlist_array_load(cgrp, type,
3231 (struct cgroup_pidlist **)&of->priv);
3233 return ERR_PTR(ret);
3238 int end = l->length;
3240 while (index < end) {
3241 int mid = (index + end) / 2;
3242 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3245 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3251 /* If we're off the end of the array, we're done */
3252 if (index >= l->length)
3254 /* Update the abstract position to be the actual pid that we found */
3255 iter = l->list + index;
3256 *pos = cgroup_pid_fry(cgrp, *iter);
3260 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3262 struct kernfs_open_file *of = s->private;
3263 struct cgroup_pidlist *l = of->priv;
3266 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3267 CGROUP_PIDLIST_DESTROY_DELAY);
3268 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3271 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3273 struct kernfs_open_file *of = s->private;
3274 struct cgroup_pidlist *l = of->priv;
3276 pid_t *end = l->list + l->length;
3278 * Advance to the next pid in the array. If this goes off the
3285 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3290 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3292 return seq_printf(s, "%d\n", *(int *)v);
3296 * seq_operations functions for iterating on pidlists through seq_file -
3297 * independent of whether it's tasks or procs
3299 static const struct seq_operations cgroup_pidlist_seq_operations = {
3300 .start = cgroup_pidlist_start,
3301 .stop = cgroup_pidlist_stop,
3302 .next = cgroup_pidlist_next,
3303 .show = cgroup_pidlist_show,
3306 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3309 return notify_on_release(css->cgroup);
3312 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3313 struct cftype *cft, u64 val)
3315 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3317 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3319 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3323 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3326 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3329 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3330 struct cftype *cft, u64 val)
3333 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3335 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3339 static struct cftype cgroup_base_files[] = {
3341 .name = "cgroup.procs",
3342 .seq_start = cgroup_pidlist_start,
3343 .seq_next = cgroup_pidlist_next,
3344 .seq_stop = cgroup_pidlist_stop,
3345 .seq_show = cgroup_pidlist_show,
3346 .private = CGROUP_FILE_PROCS,
3347 .write_u64 = cgroup_procs_write,
3348 .mode = S_IRUGO | S_IWUSR,
3351 .name = "cgroup.clone_children",
3352 .flags = CFTYPE_INSANE,
3353 .read_u64 = cgroup_clone_children_read,
3354 .write_u64 = cgroup_clone_children_write,
3357 .name = "cgroup.sane_behavior",
3358 .flags = CFTYPE_ONLY_ON_ROOT,
3359 .seq_show = cgroup_sane_behavior_show,
3363 * Historical crazy stuff. These don't have "cgroup." prefix and
3364 * don't exist if sane_behavior. If you're depending on these, be
3365 * prepared to be burned.
3369 .flags = CFTYPE_INSANE, /* use "procs" instead */
3370 .seq_start = cgroup_pidlist_start,
3371 .seq_next = cgroup_pidlist_next,
3372 .seq_stop = cgroup_pidlist_stop,
3373 .seq_show = cgroup_pidlist_show,
3374 .private = CGROUP_FILE_TASKS,
3375 .write_u64 = cgroup_tasks_write,
3376 .mode = S_IRUGO | S_IWUSR,
3379 .name = "notify_on_release",
3380 .flags = CFTYPE_INSANE,
3381 .read_u64 = cgroup_read_notify_on_release,
3382 .write_u64 = cgroup_write_notify_on_release,
3385 .name = "release_agent",
3386 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3387 .seq_show = cgroup_release_agent_show,
3388 .write_string = cgroup_release_agent_write,
3389 .max_write_len = PATH_MAX - 1,
3395 * cgroup_populate_dir - create subsys files in a cgroup directory
3396 * @cgrp: target cgroup
3397 * @subsys_mask: mask of the subsystem ids whose files should be added
3399 * On failure, no file is added.
3401 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3403 struct cgroup_subsys *ss;
3406 /* process cftsets of each subsystem */
3407 for_each_subsys(ss, i) {
3408 struct cftype *cfts;
3410 if (!test_bit(i, &subsys_mask))
3413 list_for_each_entry(cfts, &ss->cfts, node) {
3414 ret = cgroup_addrm_files(cgrp, cfts, true);
3421 cgroup_clear_dir(cgrp, subsys_mask);
3426 * css destruction is four-stage process.
3428 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3429 * Implemented in kill_css().
3431 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3432 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3433 * by invoking offline_css(). After offlining, the base ref is put.
3434 * Implemented in css_killed_work_fn().
3436 * 3. When the percpu_ref reaches zero, the only possible remaining
3437 * accessors are inside RCU read sections. css_release() schedules the
3440 * 4. After the grace period, the css can be freed. Implemented in
3441 * css_free_work_fn().
3443 * It is actually hairier because both step 2 and 4 require process context
3444 * and thus involve punting to css->destroy_work adding two additional
3445 * steps to the already complex sequence.
3447 static void css_free_work_fn(struct work_struct *work)
3449 struct cgroup_subsys_state *css =
3450 container_of(work, struct cgroup_subsys_state, destroy_work);
3451 struct cgroup *cgrp = css->cgroup;
3454 css_put(css->parent);
3456 css->ss->css_free(css);
3460 static void css_free_rcu_fn(struct rcu_head *rcu_head)
3462 struct cgroup_subsys_state *css =
3463 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
3465 INIT_WORK(&css->destroy_work, css_free_work_fn);
3466 queue_work(cgroup_destroy_wq, &css->destroy_work);
3469 static void css_release(struct percpu_ref *ref)
3471 struct cgroup_subsys_state *css =
3472 container_of(ref, struct cgroup_subsys_state, refcnt);
3474 rcu_assign_pointer(css->cgroup->subsys[css->ss->id], NULL);
3475 call_rcu(&css->rcu_head, css_free_rcu_fn);
3478 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3479 struct cgroup *cgrp)
3486 css->parent = cgroup_css(cgrp->parent, ss);
3488 css->flags |= CSS_ROOT;
3490 BUG_ON(cgroup_css(cgrp, ss));
3493 /* invoke ->css_online() on a new CSS and mark it online if successful */
3494 static int online_css(struct cgroup_subsys_state *css)
3496 struct cgroup_subsys *ss = css->ss;
3499 lockdep_assert_held(&cgroup_tree_mutex);
3500 lockdep_assert_held(&cgroup_mutex);
3503 ret = ss->css_online(css);
3505 css->flags |= CSS_ONLINE;
3506 css->cgroup->nr_css++;
3507 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
3512 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
3513 static void offline_css(struct cgroup_subsys_state *css)
3515 struct cgroup_subsys *ss = css->ss;
3517 lockdep_assert_held(&cgroup_tree_mutex);
3518 lockdep_assert_held(&cgroup_mutex);
3520 if (!(css->flags & CSS_ONLINE))
3523 if (ss->css_offline)
3524 ss->css_offline(css);
3526 css->flags &= ~CSS_ONLINE;
3527 css->cgroup->nr_css--;
3528 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
3532 * create_css - create a cgroup_subsys_state
3533 * @cgrp: the cgroup new css will be associated with
3534 * @ss: the subsys of new css
3536 * Create a new css associated with @cgrp - @ss pair. On success, the new
3537 * css is online and installed in @cgrp with all interface files created.
3538 * Returns 0 on success, -errno on failure.
3540 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
3542 struct cgroup *parent = cgrp->parent;
3543 struct cgroup_subsys_state *css;
3546 lockdep_assert_held(&cgroup_mutex);
3548 css = ss->css_alloc(cgroup_css(parent, ss));
3550 return PTR_ERR(css);
3552 err = percpu_ref_init(&css->refcnt, css_release);
3556 init_css(css, ss, cgrp);
3558 err = cgroup_populate_dir(cgrp, 1 << ss->id);
3562 err = online_css(css);
3567 css_get(css->parent);
3569 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
3571 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",
3572 current->comm, current->pid, ss->name);
3573 if (!strcmp(ss->name, "memory"))
3574 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
3575 ss->warned_broken_hierarchy = true;
3581 percpu_ref_cancel_init(&css->refcnt);
3587 * cgroup_create - create a cgroup
3588 * @parent: cgroup that will be parent of the new cgroup
3589 * @name: name of the new cgroup
3590 * @mode: mode to set on new cgroup
3592 static long cgroup_create(struct cgroup *parent, const char *name,
3595 struct cgroup *cgrp;
3596 struct cgroupfs_root *root = parent->root;
3598 struct cgroup_subsys *ss;
3599 struct kernfs_node *kn;
3601 /* allocate the cgroup and its ID, 0 is reserved for the root */
3602 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
3606 mutex_lock(&cgroup_tree_mutex);
3609 * Only live parents can have children. Note that the liveliness
3610 * check isn't strictly necessary because cgroup_mkdir() and
3611 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
3612 * anyway so that locking is contained inside cgroup proper and we
3613 * don't get nasty surprises if we ever grow another caller.
3615 if (!cgroup_lock_live_group(parent)) {
3617 goto err_unlock_tree;
3621 * Temporarily set the pointer to NULL, so idr_find() won't return
3622 * a half-baked cgroup.
3624 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
3630 init_cgroup_housekeeping(cgrp);
3632 cgrp->parent = parent;
3633 cgrp->dummy_css.parent = &parent->dummy_css;
3634 cgrp->root = parent->root;
3636 if (notify_on_release(parent))
3637 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3639 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
3640 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3642 /* create the directory */
3643 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
3651 * This extra ref will be put in cgroup_free_fn() and guarantees
3652 * that @cgrp->kn is always accessible.
3656 cgrp->serial_nr = cgroup_serial_nr_next++;
3658 /* allocation complete, commit to creation */
3659 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
3660 atomic_inc(&root->nr_cgrps);
3664 * @cgrp is now fully operational. If something fails after this
3665 * point, it'll be released via the normal destruction path.
3667 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
3669 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
3673 /* let's create and online css's */
3674 for_each_subsys(ss, ssid) {
3675 if (root->subsys_mask & (1 << ssid)) {
3676 err = create_css(cgrp, ss);
3682 kernfs_activate(kn);
3684 mutex_unlock(&cgroup_mutex);
3685 mutex_unlock(&cgroup_tree_mutex);
3690 idr_remove(&root->cgroup_idr, cgrp->id);
3692 mutex_unlock(&cgroup_mutex);
3694 mutex_unlock(&cgroup_tree_mutex);
3699 cgroup_destroy_locked(cgrp);
3700 mutex_unlock(&cgroup_mutex);
3701 mutex_unlock(&cgroup_tree_mutex);
3705 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
3708 struct cgroup *parent = parent_kn->priv;
3710 return cgroup_create(parent, name, mode);
3714 * This is called when the refcnt of a css is confirmed to be killed.
3715 * css_tryget() is now guaranteed to fail.
3717 static void css_killed_work_fn(struct work_struct *work)
3719 struct cgroup_subsys_state *css =
3720 container_of(work, struct cgroup_subsys_state, destroy_work);
3721 struct cgroup *cgrp = css->cgroup;
3723 mutex_lock(&cgroup_tree_mutex);
3724 mutex_lock(&cgroup_mutex);
3727 * css_tryget() is guaranteed to fail now. Tell subsystems to
3728 * initate destruction.
3733 * If @cgrp is marked dead, it's waiting for refs of all css's to
3734 * be disabled before proceeding to the second phase of cgroup
3735 * destruction. If we are the last one, kick it off.
3737 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
3738 cgroup_destroy_css_killed(cgrp);
3740 mutex_unlock(&cgroup_mutex);
3741 mutex_unlock(&cgroup_tree_mutex);
3744 * Put the css refs from kill_css(). Each css holds an extra
3745 * reference to the cgroup's dentry and cgroup removal proceeds
3746 * regardless of css refs. On the last put of each css, whenever
3747 * that may be, the extra dentry ref is put so that dentry
3748 * destruction happens only after all css's are released.
3753 /* css kill confirmation processing requires process context, bounce */
3754 static void css_killed_ref_fn(struct percpu_ref *ref)
3756 struct cgroup_subsys_state *css =
3757 container_of(ref, struct cgroup_subsys_state, refcnt);
3759 INIT_WORK(&css->destroy_work, css_killed_work_fn);
3760 queue_work(cgroup_destroy_wq, &css->destroy_work);
3764 * kill_css - destroy a css
3765 * @css: css to destroy
3767 * This function initiates destruction of @css by removing cgroup interface
3768 * files and putting its base reference. ->css_offline() will be invoked
3769 * asynchronously once css_tryget() is guaranteed to fail and when the
3770 * reference count reaches zero, @css will be released.
3772 static void kill_css(struct cgroup_subsys_state *css)
3775 * This must happen before css is disassociated with its cgroup.
3776 * See seq_css() for details.
3778 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
3781 * Killing would put the base ref, but we need to keep it alive
3782 * until after ->css_offline().
3787 * cgroup core guarantees that, by the time ->css_offline() is
3788 * invoked, no new css reference will be given out via
3789 * css_tryget(). We can't simply call percpu_ref_kill() and
3790 * proceed to offlining css's because percpu_ref_kill() doesn't
3791 * guarantee that the ref is seen as killed on all CPUs on return.
3793 * Use percpu_ref_kill_and_confirm() to get notifications as each
3794 * css is confirmed to be seen as killed on all CPUs.
3796 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
3800 * cgroup_destroy_locked - the first stage of cgroup destruction
3801 * @cgrp: cgroup to be destroyed
3803 * css's make use of percpu refcnts whose killing latency shouldn't be
3804 * exposed to userland and are RCU protected. Also, cgroup core needs to
3805 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
3806 * invoked. To satisfy all the requirements, destruction is implemented in
3807 * the following two steps.
3809 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
3810 * userland visible parts and start killing the percpu refcnts of
3811 * css's. Set up so that the next stage will be kicked off once all
3812 * the percpu refcnts are confirmed to be killed.
3814 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
3815 * rest of destruction. Once all cgroup references are gone, the
3816 * cgroup is RCU-freed.
3818 * This function implements s1. After this step, @cgrp is gone as far as
3819 * the userland is concerned and a new cgroup with the same name may be
3820 * created. As cgroup doesn't care about the names internally, this
3821 * doesn't cause any problem.
3823 static int cgroup_destroy_locked(struct cgroup *cgrp)
3824 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
3826 struct cgroup *child;
3827 struct cgroup_subsys_state *css;
3831 lockdep_assert_held(&cgroup_tree_mutex);
3832 lockdep_assert_held(&cgroup_mutex);
3835 * css_set_rwsem synchronizes access to ->cset_links and prevents
3836 * @cgrp from being removed while put_css_set() is in progress.
3838 down_read(&css_set_rwsem);
3839 empty = list_empty(&cgrp->cset_links);
3840 up_read(&css_set_rwsem);
3845 * Make sure there's no live children. We can't test ->children
3846 * emptiness as dead children linger on it while being destroyed;
3847 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
3851 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
3852 empty = cgroup_is_dead(child);
3861 * Initiate massacre of all css's. cgroup_destroy_css_killed()
3862 * will be invoked to perform the rest of destruction once the
3863 * percpu refs of all css's are confirmed to be killed. This
3864 * involves removing the subsystem's files, drop cgroup_mutex.
3866 mutex_unlock(&cgroup_mutex);
3867 for_each_css(css, ssid, cgrp)
3869 mutex_lock(&cgroup_mutex);
3872 * Mark @cgrp dead. This prevents further task migration and child
3873 * creation by disabling cgroup_lock_live_group(). Note that
3874 * CGRP_DEAD assertion is depended upon by css_next_child() to
3875 * resume iteration after dropping RCU read lock. See
3876 * css_next_child() for details.
3878 set_bit(CGRP_DEAD, &cgrp->flags);
3880 /* CGRP_DEAD is set, remove from ->release_list for the last time */
3881 raw_spin_lock(&release_list_lock);
3882 if (!list_empty(&cgrp->release_list))
3883 list_del_init(&cgrp->release_list);
3884 raw_spin_unlock(&release_list_lock);
3887 * If @cgrp has css's attached, the second stage of cgroup
3888 * destruction is kicked off from css_killed_work_fn() after the
3889 * refs of all attached css's are killed. If @cgrp doesn't have
3890 * any css, we kick it off here.
3893 cgroup_destroy_css_killed(cgrp);
3895 /* remove @cgrp directory along with the base files */
3896 mutex_unlock(&cgroup_mutex);
3899 * There are two control paths which try to determine cgroup from
3900 * dentry without going through kernfs - cgroupstats_build() and
3901 * css_tryget_from_dir(). Those are supported by RCU protecting
3902 * clearing of cgrp->kn->priv backpointer, which should happen
3903 * after all files under it have been removed.
3905 kernfs_remove(cgrp->kn); /* @cgrp has an extra ref on its kn */
3906 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
3908 mutex_lock(&cgroup_mutex);
3914 * cgroup_destroy_css_killed - the second step of cgroup destruction
3915 * @work: cgroup->destroy_free_work
3917 * This function is invoked from a work item for a cgroup which is being
3918 * destroyed after all css's are offlined and performs the rest of
3919 * destruction. This is the second step of destruction described in the
3920 * comment above cgroup_destroy_locked().
3922 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
3924 struct cgroup *parent = cgrp->parent;
3926 lockdep_assert_held(&cgroup_tree_mutex);
3927 lockdep_assert_held(&cgroup_mutex);
3929 /* delete this cgroup from parent->children */
3930 list_del_rcu(&cgrp->sibling);
3934 set_bit(CGRP_RELEASABLE, &parent->flags);
3935 check_for_release(parent);
3938 static int cgroup_rmdir(struct kernfs_node *kn)
3940 struct cgroup *cgrp = kn->priv;
3944 * This is self-destruction but @kn can't be removed while this
3945 * callback is in progress. Let's break active protection. Once
3946 * the protection is broken, @cgrp can be destroyed at any point.
3947 * Pin it so that it stays accessible.
3950 kernfs_break_active_protection(kn);
3952 mutex_lock(&cgroup_tree_mutex);
3953 mutex_lock(&cgroup_mutex);
3956 * @cgrp might already have been destroyed while we're trying to
3959 if (!cgroup_is_dead(cgrp))
3960 ret = cgroup_destroy_locked(cgrp);
3962 mutex_unlock(&cgroup_mutex);
3963 mutex_unlock(&cgroup_tree_mutex);
3965 kernfs_unbreak_active_protection(kn);
3970 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
3971 .remount_fs = cgroup_remount,
3972 .show_options = cgroup_show_options,
3973 .mkdir = cgroup_mkdir,
3974 .rmdir = cgroup_rmdir,
3975 .rename = cgroup_rename,
3978 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
3980 struct cgroup_subsys_state *css;
3982 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
3984 mutex_lock(&cgroup_tree_mutex);
3985 mutex_lock(&cgroup_mutex);
3987 INIT_LIST_HEAD(&ss->cfts);
3989 /* Create the top cgroup state for this subsystem */
3990 ss->root = &cgroup_dummy_root;
3991 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
3992 /* We don't handle early failures gracefully */
3993 BUG_ON(IS_ERR(css));
3994 init_css(css, ss, cgroup_dummy_top);
3996 /* Update the init_css_set to contain a subsys
3997 * pointer to this state - since the subsystem is
3998 * newly registered, all tasks and hence the
3999 * init_css_set is in the subsystem's top cgroup. */
4000 init_css_set.subsys[ss->id] = css;
4002 need_forkexit_callback |= ss->fork || ss->exit;
4004 /* At system boot, before all subsystems have been
4005 * registered, no tasks have been forked, so we don't
4006 * need to invoke fork callbacks here. */
4007 BUG_ON(!list_empty(&init_task.tasks));
4009 BUG_ON(online_css(css));
4011 mutex_unlock(&cgroup_mutex);
4012 mutex_unlock(&cgroup_tree_mutex);
4016 * cgroup_init_early - cgroup initialization at system boot
4018 * Initialize cgroups at system boot, and initialize any
4019 * subsystems that request early init.
4021 int __init cgroup_init_early(void)
4023 struct cgroup_subsys *ss;
4026 atomic_set(&init_css_set.refcount, 1);
4027 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4028 INIT_LIST_HEAD(&init_css_set.tasks);
4029 INIT_LIST_HEAD(&init_css_set.mg_tasks);
4030 INIT_LIST_HEAD(&init_css_set.mg_preload_node);
4031 INIT_LIST_HEAD(&init_css_set.mg_node);
4032 INIT_HLIST_NODE(&init_css_set.hlist);
4034 init_cgroup_root(&cgroup_dummy_root);
4035 cgroup_root_count = 1;
4036 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4038 init_cgrp_cset_link.cset = &init_css_set;
4039 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4040 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4041 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4043 for_each_subsys(ss, i) {
4044 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4045 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4046 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4048 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4049 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4052 ss->name = cgroup_subsys_name[i];
4055 cgroup_init_subsys(ss);
4061 * cgroup_init - cgroup initialization
4063 * Register cgroup filesystem and /proc file, and initialize
4064 * any subsystems that didn't request early init.
4066 int __init cgroup_init(void)
4068 struct cgroup_subsys *ss;
4072 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4074 for_each_subsys(ss, i) {
4075 if (!ss->early_init)
4076 cgroup_init_subsys(ss);
4079 * cftype registration needs kmalloc and can't be done
4080 * during early_init. Register base cftypes separately.
4082 if (ss->base_cftypes)
4083 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4086 /* allocate id for the dummy hierarchy */
4087 mutex_lock(&cgroup_mutex);
4089 /* Add init_css_set to the hash table */
4090 key = css_set_hash(init_css_set.subsys);
4091 hash_add(css_set_table, &init_css_set.hlist, key);
4093 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4095 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4099 mutex_unlock(&cgroup_mutex);
4101 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4105 err = register_filesystem(&cgroup_fs_type);
4107 kobject_put(cgroup_kobj);
4111 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4115 static int __init cgroup_wq_init(void)
4118 * There isn't much point in executing destruction path in
4119 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4120 * Use 1 for @max_active.
4122 * We would prefer to do this in cgroup_init() above, but that
4123 * is called before init_workqueues(): so leave this until after.
4125 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4126 BUG_ON(!cgroup_destroy_wq);
4129 * Used to destroy pidlists and separate to serve as flush domain.
4130 * Cap @max_active to 1 too.
4132 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4134 BUG_ON(!cgroup_pidlist_destroy_wq);
4138 core_initcall(cgroup_wq_init);
4141 * proc_cgroup_show()
4142 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4143 * - Used for /proc/<pid>/cgroup.
4144 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4145 * doesn't really matter if tsk->cgroup changes after we read it,
4146 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4147 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4148 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4149 * cgroup to top_cgroup.
4152 /* TODO: Use a proper seq_file iterator */
4153 int proc_cgroup_show(struct seq_file *m, void *v)
4156 struct task_struct *tsk;
4159 struct cgroupfs_root *root;
4162 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4168 tsk = get_pid_task(pid, PIDTYPE_PID);
4174 mutex_lock(&cgroup_mutex);
4175 down_read(&css_set_rwsem);
4177 for_each_active_root(root) {
4178 struct cgroup_subsys *ss;
4179 struct cgroup *cgrp;
4180 int ssid, count = 0;
4182 seq_printf(m, "%d:", root->hierarchy_id);
4183 for_each_subsys(ss, ssid)
4184 if (root->subsys_mask & (1 << ssid))
4185 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4186 if (strlen(root->name))
4187 seq_printf(m, "%sname=%s", count ? "," : "",
4190 cgrp = task_cgroup_from_root(tsk, root);
4191 path = cgroup_path(cgrp, buf, PATH_MAX);
4193 retval = -ENAMETOOLONG;
4201 up_read(&css_set_rwsem);
4202 mutex_unlock(&cgroup_mutex);
4203 put_task_struct(tsk);
4210 /* Display information about each subsystem and each hierarchy */
4211 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4213 struct cgroup_subsys *ss;
4216 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4218 * ideally we don't want subsystems moving around while we do this.
4219 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4220 * subsys/hierarchy state.
4222 mutex_lock(&cgroup_mutex);
4224 for_each_subsys(ss, i)
4225 seq_printf(m, "%s\t%d\t%d\t%d\n",
4226 ss->name, ss->root->hierarchy_id,
4227 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4229 mutex_unlock(&cgroup_mutex);
4233 static int cgroupstats_open(struct inode *inode, struct file *file)
4235 return single_open(file, proc_cgroupstats_show, NULL);
4238 static const struct file_operations proc_cgroupstats_operations = {
4239 .open = cgroupstats_open,
4241 .llseek = seq_lseek,
4242 .release = single_release,
4246 * cgroup_fork - attach newly forked task to its parents cgroup.
4247 * @child: pointer to task_struct of forking parent process.
4249 * Description: A task inherits its parent's cgroup at fork().
4251 * A pointer to the shared css_set was automatically copied in
4252 * fork.c by dup_task_struct(). However, we ignore that copy, since
4253 * it was not made under the protection of RCU or cgroup_mutex, so
4254 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4255 * have already changed current->cgroups, allowing the previously
4256 * referenced cgroup group to be removed and freed.
4258 * At the point that cgroup_fork() is called, 'current' is the parent
4259 * task, and the passed argument 'child' points to the child task.
4261 void cgroup_fork(struct task_struct *child)
4264 get_css_set(task_css_set(current));
4265 child->cgroups = current->cgroups;
4266 task_unlock(current);
4267 INIT_LIST_HEAD(&child->cg_list);
4271 * cgroup_post_fork - called on a new task after adding it to the task list
4272 * @child: the task in question
4274 * Adds the task to the list running through its css_set if necessary and
4275 * call the subsystem fork() callbacks. Has to be after the task is
4276 * visible on the task list in case we race with the first call to
4277 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4280 void cgroup_post_fork(struct task_struct *child)
4282 struct cgroup_subsys *ss;
4286 * use_task_css_set_links is set to 1 before we walk the tasklist
4287 * under the tasklist_lock and we read it here after we added the child
4288 * to the tasklist under the tasklist_lock as well. If the child wasn't
4289 * yet in the tasklist when we walked through it from
4290 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4291 * should be visible now due to the paired locking and barriers implied
4292 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4293 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4296 if (use_task_css_set_links) {
4297 down_write(&css_set_rwsem);
4299 if (list_empty(&child->cg_list))
4300 list_add(&child->cg_list, &task_css_set(child)->tasks);
4302 up_write(&css_set_rwsem);
4306 * Call ss->fork(). This must happen after @child is linked on
4307 * css_set; otherwise, @child might change state between ->fork()
4308 * and addition to css_set.
4310 if (need_forkexit_callback) {
4311 for_each_subsys(ss, i)
4318 * cgroup_exit - detach cgroup from exiting task
4319 * @tsk: pointer to task_struct of exiting process
4320 * @run_callback: run exit callbacks?
4322 * Description: Detach cgroup from @tsk and release it.
4324 * Note that cgroups marked notify_on_release force every task in
4325 * them to take the global cgroup_mutex mutex when exiting.
4326 * This could impact scaling on very large systems. Be reluctant to
4327 * use notify_on_release cgroups where very high task exit scaling
4328 * is required on large systems.
4330 * the_top_cgroup_hack:
4332 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4334 * We call cgroup_exit() while the task is still competent to
4335 * handle notify_on_release(), then leave the task attached to the
4336 * root cgroup in each hierarchy for the remainder of its exit.
4338 * To do this properly, we would increment the reference count on
4339 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4340 * code we would add a second cgroup function call, to drop that
4341 * reference. This would just create an unnecessary hot spot on
4342 * the top_cgroup reference count, to no avail.
4344 * Normally, holding a reference to a cgroup without bumping its
4345 * count is unsafe. The cgroup could go away, or someone could
4346 * attach us to a different cgroup, decrementing the count on
4347 * the first cgroup that we never incremented. But in this case,
4348 * top_cgroup isn't going away, and either task has PF_EXITING set,
4349 * which wards off any cgroup_attach_task() attempts, or task is a failed
4350 * fork, never visible to cgroup_attach_task.
4352 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4354 struct cgroup_subsys *ss;
4355 struct css_set *cset;
4359 * Unlink from the css_set task list if necessary. Optimistically
4360 * check cg_list before taking css_set_rwsem.
4362 if (!list_empty(&tsk->cg_list)) {
4363 down_write(&css_set_rwsem);
4364 if (!list_empty(&tsk->cg_list))
4365 list_del_init(&tsk->cg_list);
4366 up_write(&css_set_rwsem);
4369 /* Reassign the task to the init_css_set. */
4371 cset = task_css_set(tsk);
4372 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4374 if (run_callbacks && need_forkexit_callback) {
4375 /* see cgroup_post_fork() for details */
4376 for_each_subsys(ss, i) {
4378 struct cgroup_subsys_state *old_css = cset->subsys[i];
4379 struct cgroup_subsys_state *css = task_css(tsk, i);
4381 ss->exit(css, old_css, tsk);
4387 put_css_set(cset, true);
4390 static void check_for_release(struct cgroup *cgrp)
4392 if (cgroup_is_releasable(cgrp) &&
4393 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
4395 * Control Group is currently removeable. If it's not
4396 * already queued for a userspace notification, queue
4399 int need_schedule_work = 0;
4401 raw_spin_lock(&release_list_lock);
4402 if (!cgroup_is_dead(cgrp) &&
4403 list_empty(&cgrp->release_list)) {
4404 list_add(&cgrp->release_list, &release_list);
4405 need_schedule_work = 1;
4407 raw_spin_unlock(&release_list_lock);
4408 if (need_schedule_work)
4409 schedule_work(&release_agent_work);
4414 * Notify userspace when a cgroup is released, by running the
4415 * configured release agent with the name of the cgroup (path
4416 * relative to the root of cgroup file system) as the argument.
4418 * Most likely, this user command will try to rmdir this cgroup.
4420 * This races with the possibility that some other task will be
4421 * attached to this cgroup before it is removed, or that some other
4422 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4423 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4424 * unused, and this cgroup will be reprieved from its death sentence,
4425 * to continue to serve a useful existence. Next time it's released,
4426 * we will get notified again, if it still has 'notify_on_release' set.
4428 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4429 * means only wait until the task is successfully execve()'d. The
4430 * separate release agent task is forked by call_usermodehelper(),
4431 * then control in this thread returns here, without waiting for the
4432 * release agent task. We don't bother to wait because the caller of
4433 * this routine has no use for the exit status of the release agent
4434 * task, so no sense holding our caller up for that.
4436 static void cgroup_release_agent(struct work_struct *work)
4438 BUG_ON(work != &release_agent_work);
4439 mutex_lock(&cgroup_mutex);
4440 raw_spin_lock(&release_list_lock);
4441 while (!list_empty(&release_list)) {
4442 char *argv[3], *envp[3];
4444 char *pathbuf = NULL, *agentbuf = NULL, *path;
4445 struct cgroup *cgrp = list_entry(release_list.next,
4448 list_del_init(&cgrp->release_list);
4449 raw_spin_unlock(&release_list_lock);
4450 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
4453 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
4456 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4461 argv[i++] = agentbuf;
4466 /* minimal command environment */
4467 envp[i++] = "HOME=/";
4468 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4471 /* Drop the lock while we invoke the usermode helper,
4472 * since the exec could involve hitting disk and hence
4473 * be a slow process */
4474 mutex_unlock(&cgroup_mutex);
4475 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4476 mutex_lock(&cgroup_mutex);
4480 raw_spin_lock(&release_list_lock);
4482 raw_spin_unlock(&release_list_lock);
4483 mutex_unlock(&cgroup_mutex);
4486 static int __init cgroup_disable(char *str)
4488 struct cgroup_subsys *ss;
4492 while ((token = strsep(&str, ",")) != NULL) {
4496 for_each_subsys(ss, i) {
4497 if (!strcmp(token, ss->name)) {
4499 printk(KERN_INFO "Disabling %s control group"
4500 " subsystem\n", ss->name);
4507 __setup("cgroup_disable=", cgroup_disable);
4510 * css_tryget_from_dir - get corresponding css from the dentry of a cgroup dir
4511 * @dentry: directory dentry of interest
4512 * @ss: subsystem of interest
4514 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
4515 * to get the corresponding css and return it. If such css doesn't exist
4516 * or can't be pinned, an ERR_PTR value is returned.
4518 struct cgroup_subsys_state *css_tryget_from_dir(struct dentry *dentry,
4519 struct cgroup_subsys *ss)
4521 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
4522 struct cgroup_subsys_state *css = NULL;
4523 struct cgroup *cgrp;
4525 /* is @dentry a cgroup dir? */
4526 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
4527 kernfs_type(kn) != KERNFS_DIR)
4528 return ERR_PTR(-EBADF);
4533 * This path doesn't originate from kernfs and @kn could already
4534 * have been or be removed at any point. @kn->priv is RCU
4535 * protected for this access. See destroy_locked() for details.
4537 cgrp = rcu_dereference(kn->priv);
4539 css = cgroup_css(cgrp, ss);
4541 if (!css || !css_tryget(css))
4542 css = ERR_PTR(-ENOENT);
4549 * css_from_id - lookup css by id
4550 * @id: the cgroup id
4551 * @ss: cgroup subsys to be looked into
4553 * Returns the css if there's valid one with @id, otherwise returns NULL.
4554 * Should be called under rcu_read_lock().
4556 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
4558 struct cgroup *cgrp;
4560 cgroup_assert_mutexes_or_rcu_locked();
4562 cgrp = idr_find(&ss->root->cgroup_idr, id);
4564 return cgroup_css(cgrp, ss);
4568 #ifdef CONFIG_CGROUP_DEBUG
4569 static struct cgroup_subsys_state *
4570 debug_css_alloc(struct cgroup_subsys_state *parent_css)
4572 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4575 return ERR_PTR(-ENOMEM);
4580 static void debug_css_free(struct cgroup_subsys_state *css)
4585 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
4588 return cgroup_task_count(css->cgroup);
4591 static u64 current_css_set_read(struct cgroup_subsys_state *css,
4594 return (u64)(unsigned long)current->cgroups;
4597 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
4603 count = atomic_read(&task_css_set(current)->refcount);
4608 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
4610 struct cgrp_cset_link *link;
4611 struct css_set *cset;
4614 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
4618 down_read(&css_set_rwsem);
4620 cset = rcu_dereference(current->cgroups);
4621 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
4622 struct cgroup *c = link->cgrp;
4623 const char *name = "?";
4625 if (c != cgroup_dummy_top) {
4626 cgroup_name(c, name_buf, NAME_MAX + 1);
4630 seq_printf(seq, "Root %d group %s\n",
4631 c->root->hierarchy_id, name);
4634 up_read(&css_set_rwsem);
4639 #define MAX_TASKS_SHOWN_PER_CSS 25
4640 static int cgroup_css_links_read(struct seq_file *seq, void *v)
4642 struct cgroup_subsys_state *css = seq_css(seq);
4643 struct cgrp_cset_link *link;
4645 down_read(&css_set_rwsem);
4646 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
4647 struct css_set *cset = link->cset;
4648 struct task_struct *task;
4651 seq_printf(seq, "css_set %p\n", cset);
4653 list_for_each_entry(task, &cset->tasks, cg_list) {
4654 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
4656 seq_printf(seq, " task %d\n", task_pid_vnr(task));
4659 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
4660 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
4662 seq_printf(seq, " task %d\n", task_pid_vnr(task));
4666 seq_puts(seq, " ...\n");
4668 up_read(&css_set_rwsem);
4672 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
4674 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
4677 static struct cftype debug_files[] = {
4679 .name = "taskcount",
4680 .read_u64 = debug_taskcount_read,
4684 .name = "current_css_set",
4685 .read_u64 = current_css_set_read,
4689 .name = "current_css_set_refcount",
4690 .read_u64 = current_css_set_refcount_read,
4694 .name = "current_css_set_cg_links",
4695 .seq_show = current_css_set_cg_links_read,
4699 .name = "cgroup_css_links",
4700 .seq_show = cgroup_css_links_read,
4704 .name = "releasable",
4705 .read_u64 = releasable_read,
4711 struct cgroup_subsys debug_cgrp_subsys = {
4712 .css_alloc = debug_css_alloc,
4713 .css_free = debug_css_free,
4714 .base_cftypes = debug_files,
4716 #endif /* CONFIG_CGROUP_DEBUG */