2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/slab.h>
44 #include <linux/spinlock.h>
45 #include <linux/string.h>
46 #include <linux/sort.h>
47 #include <linux/kmod.h>
48 #include <linux/delayacct.h>
49 #include <linux/cgroupstats.h>
50 #include <linux/hashtable.h>
51 #include <linux/pid_namespace.h>
52 #include <linux/idr.h>
53 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
54 #include <linux/flex_array.h> /* used in cgroup_attach_task */
55 #include <linux/kthread.h>
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)
244 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
246 static int cgroup_is_releasable(const struct cgroup *cgrp)
249 (1 << CGRP_RELEASABLE) |
250 (1 << CGRP_NOTIFY_ON_RELEASE);
251 return (cgrp->flags & bits) == bits;
254 static int notify_on_release(const struct cgroup *cgrp)
256 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
260 * for_each_css - iterate all css's of a cgroup
261 * @css: the iteration cursor
262 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
263 * @cgrp: the target cgroup to iterate css's of
265 * Should be called under cgroup_mutex.
267 #define for_each_css(css, ssid, cgrp) \
268 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
269 if (!((css) = rcu_dereference_check( \
270 (cgrp)->subsys[(ssid)], \
271 lockdep_is_held(&cgroup_tree_mutex) || \
272 lockdep_is_held(&cgroup_mutex)))) { } \
276 * for_each_subsys - iterate all enabled cgroup subsystems
277 * @ss: the iteration cursor
278 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
280 #define for_each_subsys(ss, ssid) \
281 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
282 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
284 /* iterate across the active hierarchies */
285 #define for_each_active_root(root) \
286 list_for_each_entry((root), &cgroup_roots, root_list)
289 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
290 * @cgrp: the cgroup to be checked for liveness
292 * On success, returns true; the mutex should be later unlocked. On
293 * failure returns false with no lock held.
295 static bool cgroup_lock_live_group(struct cgroup *cgrp)
297 mutex_lock(&cgroup_mutex);
298 if (cgroup_is_dead(cgrp)) {
299 mutex_unlock(&cgroup_mutex);
305 /* the list of cgroups eligible for automatic release. Protected by
306 * release_list_lock */
307 static LIST_HEAD(release_list);
308 static DEFINE_RAW_SPINLOCK(release_list_lock);
309 static void cgroup_release_agent(struct work_struct *work);
310 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
311 static void check_for_release(struct cgroup *cgrp);
314 * A cgroup can be associated with multiple css_sets as different tasks may
315 * belong to different cgroups on different hierarchies. In the other
316 * direction, a css_set is naturally associated with multiple cgroups.
317 * This M:N relationship is represented by the following link structure
318 * which exists for each association and allows traversing the associations
321 struct cgrp_cset_link {
322 /* the cgroup and css_set this link associates */
324 struct css_set *cset;
326 /* list of cgrp_cset_links anchored at cgrp->cset_links */
327 struct list_head cset_link;
329 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
330 struct list_head cgrp_link;
333 /* The default css_set - used by init and its children prior to any
334 * hierarchies being mounted. It contains a pointer to the root state
335 * for each subsystem. Also used to anchor the list of css_sets. Not
336 * reference-counted, to improve performance when child cgroups
337 * haven't been created.
340 static struct css_set init_css_set;
341 static struct cgrp_cset_link init_cgrp_cset_link;
344 * css_set_lock protects the list of css_set objects, and the chain of
345 * tasks off each css_set. Nests outside task->alloc_lock due to
346 * css_task_iter_start().
348 static DEFINE_RWLOCK(css_set_lock);
349 static int css_set_count;
352 * hash table for cgroup groups. This improves the performance to find
353 * an existing css_set. This hash doesn't (currently) take into
354 * account cgroups in empty hierarchies.
356 #define CSS_SET_HASH_BITS 7
357 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
359 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
361 unsigned long key = 0UL;
362 struct cgroup_subsys *ss;
365 for_each_subsys(ss, i)
366 key += (unsigned long)css[i];
367 key = (key >> 16) ^ key;
372 static void __put_css_set(struct css_set *cset, int taskexit)
374 struct cgrp_cset_link *link, *tmp_link;
377 * Ensure that the refcount doesn't hit zero while any readers
378 * can see it. Similar to atomic_dec_and_lock(), but for an
381 if (atomic_add_unless(&cset->refcount, -1, 1))
383 write_lock(&css_set_lock);
384 if (!atomic_dec_and_test(&cset->refcount)) {
385 write_unlock(&css_set_lock);
389 /* This css_set is dead. unlink it and release cgroup refcounts */
390 hash_del(&cset->hlist);
393 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
394 struct cgroup *cgrp = link->cgrp;
396 list_del(&link->cset_link);
397 list_del(&link->cgrp_link);
399 /* @cgrp can't go away while we're holding css_set_lock */
400 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
402 set_bit(CGRP_RELEASABLE, &cgrp->flags);
403 check_for_release(cgrp);
409 write_unlock(&css_set_lock);
410 kfree_rcu(cset, rcu_head);
414 * refcounted get/put for css_set objects
416 static inline void get_css_set(struct css_set *cset)
418 atomic_inc(&cset->refcount);
421 static inline void put_css_set(struct css_set *cset)
423 __put_css_set(cset, 0);
426 static inline void put_css_set_taskexit(struct css_set *cset)
428 __put_css_set(cset, 1);
432 * compare_css_sets - helper function for find_existing_css_set().
433 * @cset: candidate css_set being tested
434 * @old_cset: existing css_set for a task
435 * @new_cgrp: cgroup that's being entered by the task
436 * @template: desired set of css pointers in css_set (pre-calculated)
438 * Returns true if "cset" matches "old_cset" except for the hierarchy
439 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
441 static bool compare_css_sets(struct css_set *cset,
442 struct css_set *old_cset,
443 struct cgroup *new_cgrp,
444 struct cgroup_subsys_state *template[])
446 struct list_head *l1, *l2;
448 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
449 /* Not all subsystems matched */
454 * Compare cgroup pointers in order to distinguish between
455 * different cgroups in heirarchies with no subsystems. We
456 * could get by with just this check alone (and skip the
457 * memcmp above) but on most setups the memcmp check will
458 * avoid the need for this more expensive check on almost all
462 l1 = &cset->cgrp_links;
463 l2 = &old_cset->cgrp_links;
465 struct cgrp_cset_link *link1, *link2;
466 struct cgroup *cgrp1, *cgrp2;
470 /* See if we reached the end - both lists are equal length. */
471 if (l1 == &cset->cgrp_links) {
472 BUG_ON(l2 != &old_cset->cgrp_links);
475 BUG_ON(l2 == &old_cset->cgrp_links);
477 /* Locate the cgroups associated with these links. */
478 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
479 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
482 /* Hierarchies should be linked in the same order. */
483 BUG_ON(cgrp1->root != cgrp2->root);
486 * If this hierarchy is the hierarchy of the cgroup
487 * that's changing, then we need to check that this
488 * css_set points to the new cgroup; if it's any other
489 * hierarchy, then this css_set should point to the
490 * same cgroup as the old css_set.
492 if (cgrp1->root == new_cgrp->root) {
493 if (cgrp1 != new_cgrp)
504 * find_existing_css_set - init css array and find the matching css_set
505 * @old_cset: the css_set that we're using before the cgroup transition
506 * @cgrp: the cgroup that we're moving into
507 * @template: out param for the new set of csses, should be clear on entry
509 static struct css_set *find_existing_css_set(struct css_set *old_cset,
511 struct cgroup_subsys_state *template[])
513 struct cgroupfs_root *root = cgrp->root;
514 struct cgroup_subsys *ss;
515 struct css_set *cset;
520 * Build the set of subsystem state objects that we want to see in the
521 * new css_set. while subsystems can change globally, the entries here
522 * won't change, so no need for locking.
524 for_each_subsys(ss, i) {
525 if (root->subsys_mask & (1UL << i)) {
526 /* Subsystem is in this hierarchy. So we want
527 * the subsystem state from the new
529 template[i] = cgroup_css(cgrp, ss);
531 /* Subsystem is not in this hierarchy, so we
532 * don't want to change the subsystem state */
533 template[i] = old_cset->subsys[i];
537 key = css_set_hash(template);
538 hash_for_each_possible(css_set_table, cset, hlist, key) {
539 if (!compare_css_sets(cset, old_cset, cgrp, template))
542 /* This css_set matches what we need */
546 /* No existing cgroup group matched */
550 static void free_cgrp_cset_links(struct list_head *links_to_free)
552 struct cgrp_cset_link *link, *tmp_link;
554 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
555 list_del(&link->cset_link);
561 * allocate_cgrp_cset_links - allocate cgrp_cset_links
562 * @count: the number of links to allocate
563 * @tmp_links: list_head the allocated links are put on
565 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
566 * through ->cset_link. Returns 0 on success or -errno.
568 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
570 struct cgrp_cset_link *link;
573 INIT_LIST_HEAD(tmp_links);
575 for (i = 0; i < count; i++) {
576 link = kzalloc(sizeof(*link), GFP_KERNEL);
578 free_cgrp_cset_links(tmp_links);
581 list_add(&link->cset_link, tmp_links);
587 * link_css_set - a helper function to link a css_set to a cgroup
588 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
589 * @cset: the css_set to be linked
590 * @cgrp: the destination cgroup
592 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
595 struct cgrp_cset_link *link;
597 BUG_ON(list_empty(tmp_links));
598 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
601 list_move(&link->cset_link, &cgrp->cset_links);
603 * Always add links to the tail of the list so that the list
604 * is sorted by order of hierarchy creation
606 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
610 * find_css_set - return a new css_set with one cgroup updated
611 * @old_cset: the baseline css_set
612 * @cgrp: the cgroup to be updated
614 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
615 * substituted into the appropriate hierarchy.
617 static struct css_set *find_css_set(struct css_set *old_cset,
620 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
621 struct css_set *cset;
622 struct list_head tmp_links;
623 struct cgrp_cset_link *link;
626 lockdep_assert_held(&cgroup_mutex);
628 /* First see if we already have a cgroup group that matches
630 read_lock(&css_set_lock);
631 cset = find_existing_css_set(old_cset, cgrp, template);
634 read_unlock(&css_set_lock);
639 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
643 /* Allocate all the cgrp_cset_link objects that we'll need */
644 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
649 atomic_set(&cset->refcount, 1);
650 INIT_LIST_HEAD(&cset->cgrp_links);
651 INIT_LIST_HEAD(&cset->tasks);
652 INIT_HLIST_NODE(&cset->hlist);
654 /* Copy the set of subsystem state objects generated in
655 * find_existing_css_set() */
656 memcpy(cset->subsys, template, sizeof(cset->subsys));
658 write_lock(&css_set_lock);
659 /* Add reference counts and links from the new css_set. */
660 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
661 struct cgroup *c = link->cgrp;
663 if (c->root == cgrp->root)
665 link_css_set(&tmp_links, cset, c);
668 BUG_ON(!list_empty(&tmp_links));
672 /* Add this cgroup group to the hash table */
673 key = css_set_hash(cset->subsys);
674 hash_add(css_set_table, &cset->hlist, key);
676 write_unlock(&css_set_lock);
681 static struct cgroupfs_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
683 struct cgroup *top_cgrp = kf_root->kn->priv;
685 return top_cgrp->root;
688 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
692 lockdep_assert_held(&cgroup_mutex);
694 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
699 root->hierarchy_id = id;
703 static void cgroup_exit_root_id(struct cgroupfs_root *root)
705 lockdep_assert_held(&cgroup_mutex);
707 if (root->hierarchy_id) {
708 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
709 root->hierarchy_id = 0;
713 static void cgroup_free_root(struct cgroupfs_root *root)
716 /* hierarhcy ID shoulid already have been released */
717 WARN_ON_ONCE(root->hierarchy_id);
719 idr_destroy(&root->cgroup_idr);
724 static void cgroup_destroy_root(struct cgroupfs_root *root)
726 struct cgroup *cgrp = &root->top_cgroup;
727 struct cgrp_cset_link *link, *tmp_link;
729 mutex_lock(&cgroup_tree_mutex);
730 mutex_lock(&cgroup_mutex);
732 BUG_ON(atomic_read(&root->nr_cgrps));
733 BUG_ON(!list_empty(&cgrp->children));
735 /* Rebind all subsystems back to the default hierarchy */
736 WARN_ON(rebind_subsystems(root, 0, root->subsys_mask));
739 * Release all the links from cset_links to this hierarchy's
742 write_lock(&css_set_lock);
744 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
745 list_del(&link->cset_link);
746 list_del(&link->cgrp_link);
749 write_unlock(&css_set_lock);
751 if (!list_empty(&root->root_list)) {
752 list_del(&root->root_list);
756 cgroup_exit_root_id(root);
758 mutex_unlock(&cgroup_mutex);
759 mutex_unlock(&cgroup_tree_mutex);
761 kernfs_destroy_root(root->kf_root);
762 cgroup_free_root(root);
766 * Return the cgroup for "task" from the given hierarchy. Must be
767 * called with cgroup_mutex held.
769 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
770 struct cgroupfs_root *root)
772 struct css_set *cset;
773 struct cgroup *res = NULL;
775 BUG_ON(!mutex_is_locked(&cgroup_mutex));
776 read_lock(&css_set_lock);
778 * No need to lock the task - since we hold cgroup_mutex the
779 * task can't change groups, so the only thing that can happen
780 * is that it exits and its css is set back to init_css_set.
782 cset = task_css_set(task);
783 if (cset == &init_css_set) {
784 res = &root->top_cgroup;
786 struct cgrp_cset_link *link;
788 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
789 struct cgroup *c = link->cgrp;
791 if (c->root == root) {
797 read_unlock(&css_set_lock);
803 * There is one global cgroup mutex. We also require taking
804 * task_lock() when dereferencing a task's cgroup subsys pointers.
805 * See "The task_lock() exception", at the end of this comment.
807 * A task must hold cgroup_mutex to modify cgroups.
809 * Any task can increment and decrement the count field without lock.
810 * So in general, code holding cgroup_mutex can't rely on the count
811 * field not changing. However, if the count goes to zero, then only
812 * cgroup_attach_task() can increment it again. Because a count of zero
813 * means that no tasks are currently attached, therefore there is no
814 * way a task attached to that cgroup can fork (the other way to
815 * increment the count). So code holding cgroup_mutex can safely
816 * assume that if the count is zero, it will stay zero. Similarly, if
817 * a task holds cgroup_mutex on a cgroup with zero count, it
818 * knows that the cgroup won't be removed, as cgroup_rmdir()
821 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
822 * (usually) take cgroup_mutex. These are the two most performance
823 * critical pieces of code here. The exception occurs on cgroup_exit(),
824 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
825 * is taken, and if the cgroup count is zero, a usermode call made
826 * to the release agent with the name of the cgroup (path relative to
827 * the root of cgroup file system) as the argument.
829 * A cgroup can only be deleted if both its 'count' of using tasks
830 * is zero, and its list of 'children' cgroups is empty. Since all
831 * tasks in the system use _some_ cgroup, and since there is always at
832 * least one task in the system (init, pid == 1), therefore, top_cgroup
833 * always has either children cgroups and/or using tasks. So we don't
834 * need a special hack to ensure that top_cgroup cannot be deleted.
836 * The task_lock() exception
838 * The need for this exception arises from the action of
839 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
840 * another. It does so using cgroup_mutex, however there are
841 * several performance critical places that need to reference
842 * task->cgroup without the expense of grabbing a system global
843 * mutex. Therefore except as noted below, when dereferencing or, as
844 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
845 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
846 * the task_struct routinely used for such matters.
848 * P.S. One more locking exception. RCU is used to guard the
849 * update of a tasks cgroup pointer by cgroup_attach_task()
852 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
853 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
854 static const struct file_operations proc_cgroupstats_operations;
856 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
859 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
860 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
861 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
862 cft->ss->name, cft->name);
864 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
869 * cgroup_file_mode - deduce file mode of a control file
870 * @cft: the control file in question
872 * returns cft->mode if ->mode is not 0
873 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
874 * returns S_IRUGO if it has only a read handler
875 * returns S_IWUSR if it has only a write hander
877 static umode_t cgroup_file_mode(const struct cftype *cft)
884 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
887 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
894 static void cgroup_free_fn(struct work_struct *work)
896 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
898 atomic_dec(&cgrp->root->nr_cgrps);
899 cgroup_pidlist_destroy_all(cgrp);
903 * We get a ref to the parent, and put the ref when this
904 * cgroup is being freed, so it's guaranteed that the
905 * parent won't be destroyed before its children.
907 cgroup_put(cgrp->parent);
908 kernfs_put(cgrp->kn);
912 * This is top cgroup's refcnt reaching zero, which
913 * indicates that the root should be released.
915 cgroup_destroy_root(cgrp->root);
919 static void cgroup_free_rcu(struct rcu_head *head)
921 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
923 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
924 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
927 static void cgroup_get(struct cgroup *cgrp)
929 WARN_ON_ONCE(cgroup_is_dead(cgrp));
930 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
931 atomic_inc(&cgrp->refcnt);
934 static void cgroup_put(struct cgroup *cgrp)
936 if (!atomic_dec_and_test(&cgrp->refcnt))
938 if (WARN_ON_ONCE(cgrp->parent && !cgroup_is_dead(cgrp)))
942 * XXX: cgrp->id is only used to look up css's. As cgroup and
943 * css's lifetimes will be decoupled, it should be made
944 * per-subsystem and moved to css->id so that lookups are
945 * successful until the target css is released.
947 mutex_lock(&cgroup_mutex);
948 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
949 mutex_unlock(&cgroup_mutex);
952 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
955 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
957 char name[CGROUP_FILE_NAME_MAX];
959 lockdep_assert_held(&cgroup_tree_mutex);
960 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
964 * cgroup_clear_dir - remove subsys files in a cgroup directory
965 * @cgrp: target cgroup
966 * @subsys_mask: mask of the subsystem ids whose files should be removed
968 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
970 struct cgroup_subsys *ss;
973 for_each_subsys(ss, i) {
976 if (!test_bit(i, &subsys_mask))
978 list_for_each_entry(cfts, &ss->cfts, node)
979 cgroup_addrm_files(cgrp, cfts, false);
983 static int rebind_subsystems(struct cgroupfs_root *root,
984 unsigned long added_mask, unsigned removed_mask)
986 struct cgroup *cgrp = &root->top_cgroup;
987 struct cgroup_subsys *ss;
990 lockdep_assert_held(&cgroup_tree_mutex);
991 lockdep_assert_held(&cgroup_mutex);
993 /* Check that any added subsystems are currently free */
994 for_each_subsys(ss, i)
995 if ((added_mask & (1 << i)) && ss->root != &cgroup_dummy_root)
998 ret = cgroup_populate_dir(cgrp, added_mask);
1003 * Nothing can fail from this point on. Remove files for the
1004 * removed subsystems and rebind each subsystem.
1006 mutex_unlock(&cgroup_mutex);
1007 cgroup_clear_dir(cgrp, removed_mask);
1008 mutex_lock(&cgroup_mutex);
1010 for_each_subsys(ss, i) {
1011 unsigned long bit = 1UL << i;
1013 if (bit & added_mask) {
1014 /* We're binding this subsystem to this hierarchy */
1015 BUG_ON(cgroup_css(cgrp, ss));
1016 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
1017 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
1019 rcu_assign_pointer(cgrp->subsys[i],
1020 cgroup_css(cgroup_dummy_top, ss));
1021 cgroup_css(cgrp, ss)->cgroup = cgrp;
1025 ss->bind(cgroup_css(cgrp, ss));
1027 /* refcount was already taken, and we're keeping it */
1028 root->subsys_mask |= bit;
1029 } else if (bit & removed_mask) {
1030 /* We're removing this subsystem */
1031 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
1032 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
1035 ss->bind(cgroup_css(cgroup_dummy_top, ss));
1037 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
1038 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1040 cgroup_subsys[i]->root = &cgroup_dummy_root;
1041 root->subsys_mask &= ~bit;
1045 kernfs_activate(cgrp->kn);
1049 static int cgroup_show_options(struct seq_file *seq,
1050 struct kernfs_root *kf_root)
1052 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1053 struct cgroup_subsys *ss;
1056 for_each_subsys(ss, ssid)
1057 if (root->subsys_mask & (1 << ssid))
1058 seq_printf(seq, ",%s", ss->name);
1059 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1060 seq_puts(seq, ",sane_behavior");
1061 if (root->flags & CGRP_ROOT_NOPREFIX)
1062 seq_puts(seq, ",noprefix");
1063 if (root->flags & CGRP_ROOT_XATTR)
1064 seq_puts(seq, ",xattr");
1066 spin_lock(&release_agent_path_lock);
1067 if (strlen(root->release_agent_path))
1068 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1069 spin_unlock(&release_agent_path_lock);
1071 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1072 seq_puts(seq, ",clone_children");
1073 if (strlen(root->name))
1074 seq_printf(seq, ",name=%s", root->name);
1078 struct cgroup_sb_opts {
1079 unsigned long subsys_mask;
1080 unsigned long flags;
1081 char *release_agent;
1082 bool cpuset_clone_children;
1084 /* User explicitly requested empty subsystem */
1089 * Convert a hierarchy specifier into a bitmask of subsystems and
1090 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1091 * array. This function takes refcounts on subsystems to be used, unless it
1092 * returns error, in which case no refcounts are taken.
1094 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1096 char *token, *o = data;
1097 bool all_ss = false, one_ss = false;
1098 unsigned long mask = (unsigned long)-1;
1099 struct cgroup_subsys *ss;
1102 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1104 #ifdef CONFIG_CPUSETS
1105 mask = ~(1UL << cpuset_cgrp_id);
1108 memset(opts, 0, sizeof(*opts));
1110 while ((token = strsep(&o, ",")) != NULL) {
1113 if (!strcmp(token, "none")) {
1114 /* Explicitly have no subsystems */
1118 if (!strcmp(token, "all")) {
1119 /* Mutually exclusive option 'all' + subsystem name */
1125 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1126 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1129 if (!strcmp(token, "noprefix")) {
1130 opts->flags |= CGRP_ROOT_NOPREFIX;
1133 if (!strcmp(token, "clone_children")) {
1134 opts->cpuset_clone_children = true;
1137 if (!strcmp(token, "xattr")) {
1138 opts->flags |= CGRP_ROOT_XATTR;
1141 if (!strncmp(token, "release_agent=", 14)) {
1142 /* Specifying two release agents is forbidden */
1143 if (opts->release_agent)
1145 opts->release_agent =
1146 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1147 if (!opts->release_agent)
1151 if (!strncmp(token, "name=", 5)) {
1152 const char *name = token + 5;
1153 /* Can't specify an empty name */
1156 /* Must match [\w.-]+ */
1157 for (i = 0; i < strlen(name); i++) {
1161 if ((c == '.') || (c == '-') || (c == '_'))
1165 /* Specifying two names is forbidden */
1168 opts->name = kstrndup(name,
1169 MAX_CGROUP_ROOT_NAMELEN - 1,
1177 for_each_subsys(ss, i) {
1178 if (strcmp(token, ss->name))
1183 /* Mutually exclusive option 'all' + subsystem name */
1186 set_bit(i, &opts->subsys_mask);
1191 if (i == CGROUP_SUBSYS_COUNT)
1196 * If the 'all' option was specified select all the subsystems,
1197 * otherwise if 'none', 'name=' and a subsystem name options
1198 * were not specified, let's default to 'all'
1200 if (all_ss || (!one_ss && !opts->none && !opts->name))
1201 for_each_subsys(ss, i)
1203 set_bit(i, &opts->subsys_mask);
1205 /* Consistency checks */
1207 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1208 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1210 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1211 opts->cpuset_clone_children || opts->release_agent ||
1213 pr_err("cgroup: sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1219 * Option noprefix was introduced just for backward compatibility
1220 * with the old cpuset, so we allow noprefix only if mounting just
1221 * the cpuset subsystem.
1223 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1227 /* Can't specify "none" and some subsystems */
1228 if (opts->subsys_mask && opts->none)
1232 * We either have to specify by name or by subsystems. (So all
1233 * empty hierarchies must have a name).
1235 if (!opts->subsys_mask && !opts->name)
1241 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1244 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1245 struct cgroup_sb_opts opts;
1246 unsigned long added_mask, removed_mask;
1248 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1249 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1253 mutex_lock(&cgroup_tree_mutex);
1254 mutex_lock(&cgroup_mutex);
1256 /* See what subsystems are wanted */
1257 ret = parse_cgroupfs_options(data, &opts);
1261 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1262 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1263 task_tgid_nr(current), current->comm);
1265 added_mask = opts.subsys_mask & ~root->subsys_mask;
1266 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1268 /* Don't allow flags or name to change at remount */
1269 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1270 (opts.name && strcmp(opts.name, root->name))) {
1271 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1272 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1273 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1278 /* remounting is not allowed for populated hierarchies */
1279 if (!list_empty(&root->top_cgroup.children)) {
1284 ret = rebind_subsystems(root, added_mask, removed_mask);
1288 if (opts.release_agent) {
1289 spin_lock(&release_agent_path_lock);
1290 strcpy(root->release_agent_path, opts.release_agent);
1291 spin_unlock(&release_agent_path_lock);
1294 kfree(opts.release_agent);
1296 mutex_unlock(&cgroup_mutex);
1297 mutex_unlock(&cgroup_tree_mutex);
1302 * To reduce the fork() overhead for systems that are not actually using
1303 * their cgroups capability, we don't maintain the lists running through
1304 * each css_set to its tasks until we see the list actually used - in other
1305 * words after the first mount.
1307 static bool use_task_css_set_links __read_mostly;
1309 static void cgroup_enable_task_cg_lists(void)
1311 struct task_struct *p, *g;
1313 write_lock(&css_set_lock);
1315 if (use_task_css_set_links)
1318 use_task_css_set_links = true;
1321 * We need tasklist_lock because RCU is not safe against
1322 * while_each_thread(). Besides, a forking task that has passed
1323 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1324 * is not guaranteed to have its child immediately visible in the
1325 * tasklist if we walk through it with RCU.
1327 read_lock(&tasklist_lock);
1328 do_each_thread(g, p) {
1331 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1332 task_css_set(p) != &init_css_set);
1335 * We should check if the process is exiting, otherwise
1336 * it will race with cgroup_exit() in that the list
1337 * entry won't be deleted though the process has exited.
1339 if (!(p->flags & PF_EXITING))
1340 list_add(&p->cg_list, &task_css_set(p)->tasks);
1343 } while_each_thread(g, p);
1344 read_unlock(&tasklist_lock);
1346 write_unlock(&css_set_lock);
1349 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1351 atomic_set(&cgrp->refcnt, 1);
1352 INIT_LIST_HEAD(&cgrp->sibling);
1353 INIT_LIST_HEAD(&cgrp->children);
1354 INIT_LIST_HEAD(&cgrp->cset_links);
1355 INIT_LIST_HEAD(&cgrp->release_list);
1356 INIT_LIST_HEAD(&cgrp->pidlists);
1357 mutex_init(&cgrp->pidlist_mutex);
1358 cgrp->dummy_css.cgroup = cgrp;
1361 static void init_cgroup_root(struct cgroupfs_root *root)
1363 struct cgroup *cgrp = &root->top_cgroup;
1365 INIT_LIST_HEAD(&root->root_list);
1366 atomic_set(&root->nr_cgrps, 1);
1368 init_cgroup_housekeeping(cgrp);
1369 idr_init(&root->cgroup_idr);
1372 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1374 struct cgroupfs_root *root;
1376 if (!opts->subsys_mask && !opts->none)
1377 return ERR_PTR(-EINVAL);
1379 root = kzalloc(sizeof(*root), GFP_KERNEL);
1381 return ERR_PTR(-ENOMEM);
1383 init_cgroup_root(root);
1385 root->flags = opts->flags;
1386 if (opts->release_agent)
1387 strcpy(root->release_agent_path, opts->release_agent);
1389 strcpy(root->name, opts->name);
1390 if (opts->cpuset_clone_children)
1391 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1395 static int cgroup_setup_root(struct cgroupfs_root *root, unsigned long ss_mask)
1397 LIST_HEAD(tmp_links);
1398 struct cgroup *root_cgrp = &root->top_cgroup;
1399 struct css_set *cset;
1402 lockdep_assert_held(&cgroup_tree_mutex);
1403 lockdep_assert_held(&cgroup_mutex);
1405 ret = idr_alloc(&root->cgroup_idr, root_cgrp, 0, 1, GFP_KERNEL);
1408 root_cgrp->id = ret;
1411 * We're accessing css_set_count without locking css_set_lock here,
1412 * but that's OK - it can only be increased by someone holding
1413 * cgroup_lock, and that's us. The worst that can happen is that we
1414 * have some link structures left over
1416 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1420 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1421 ret = cgroup_init_root_id(root, 2, 0);
1425 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1426 KERNFS_ROOT_CREATE_DEACTIVATED,
1428 if (IS_ERR(root->kf_root)) {
1429 ret = PTR_ERR(root->kf_root);
1432 root_cgrp->kn = root->kf_root->kn;
1434 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1438 ret = rebind_subsystems(root, ss_mask, 0);
1443 * There must be no failure case after here, since rebinding takes
1444 * care of subsystems' refcounts, which are explicitly dropped in
1445 * the failure exit path.
1447 list_add(&root->root_list, &cgroup_roots);
1448 cgroup_root_count++;
1451 * Link the top cgroup in this hierarchy into all the css_set
1454 write_lock(&css_set_lock);
1455 hash_for_each(css_set_table, i, cset, hlist)
1456 link_css_set(&tmp_links, cset, root_cgrp);
1457 write_unlock(&css_set_lock);
1459 BUG_ON(!list_empty(&root_cgrp->children));
1460 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1462 kernfs_activate(root_cgrp->kn);
1467 kernfs_destroy_root(root->kf_root);
1468 root->kf_root = NULL;
1470 cgroup_exit_root_id(root);
1472 free_cgrp_cset_links(&tmp_links);
1476 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1477 int flags, const char *unused_dev_name,
1480 struct cgroupfs_root *root;
1481 struct cgroup_sb_opts opts;
1482 struct dentry *dentry;
1486 * The first time anyone tries to mount a cgroup, enable the list
1487 * linking each css_set to its tasks and fix up all existing tasks.
1489 if (!use_task_css_set_links)
1490 cgroup_enable_task_cg_lists();
1492 mutex_lock(&cgroup_tree_mutex);
1493 mutex_lock(&cgroup_mutex);
1495 /* First find the desired set of subsystems */
1496 ret = parse_cgroupfs_options(data, &opts);
1500 /* look for a matching existing root */
1501 for_each_active_root(root) {
1502 bool name_match = false;
1505 * If we asked for a name then it must match. Also, if
1506 * name matches but sybsys_mask doesn't, we should fail.
1507 * Remember whether name matched.
1510 if (strcmp(opts.name, root->name))
1516 * If we asked for subsystems (or explicitly for no
1517 * subsystems) then they must match.
1519 if ((opts.subsys_mask || opts.none) &&
1520 (opts.subsys_mask != root->subsys_mask)) {
1527 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1528 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1529 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1533 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1538 * A root's lifetime is governed by its top cgroup. Zero
1539 * ref indicate that the root is being destroyed. Wait for
1540 * destruction to complete so that the subsystems are free.
1541 * We can use wait_queue for the wait but this path is
1542 * super cold. Let's just sleep for a bit and retry.
1544 if (!atomic_inc_not_zero(&root->top_cgroup.refcnt)) {
1545 mutex_unlock(&cgroup_mutex);
1546 mutex_unlock(&cgroup_tree_mutex);
1555 /* no such thing, create a new one */
1556 root = cgroup_root_from_opts(&opts);
1558 ret = PTR_ERR(root);
1562 ret = cgroup_setup_root(root, opts.subsys_mask);
1564 cgroup_free_root(root);
1567 mutex_unlock(&cgroup_mutex);
1568 mutex_unlock(&cgroup_tree_mutex);
1570 kfree(opts.release_agent);
1574 return ERR_PTR(ret);
1576 dentry = kernfs_mount(fs_type, flags, root->kf_root);
1578 cgroup_put(&root->top_cgroup);
1582 static void cgroup_kill_sb(struct super_block *sb)
1584 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1585 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1587 cgroup_put(&root->top_cgroup);
1591 static struct file_system_type cgroup_fs_type = {
1593 .mount = cgroup_mount,
1594 .kill_sb = cgroup_kill_sb,
1597 static struct kobject *cgroup_kobj;
1600 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1601 * @task: target task
1602 * @buf: the buffer to write the path into
1603 * @buflen: the length of the buffer
1605 * Determine @task's cgroup on the first (the one with the lowest non-zero
1606 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1607 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1608 * cgroup controller callbacks.
1610 * Return value is the same as kernfs_path().
1612 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1614 struct cgroupfs_root *root;
1615 struct cgroup *cgrp;
1616 int hierarchy_id = 1;
1619 mutex_lock(&cgroup_mutex);
1621 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1624 cgrp = task_cgroup_from_root(task, root);
1625 path = cgroup_path(cgrp, buf, buflen);
1627 /* if no hierarchy exists, everyone is in "/" */
1628 if (strlcpy(buf, "/", buflen) < buflen)
1632 mutex_unlock(&cgroup_mutex);
1635 EXPORT_SYMBOL_GPL(task_cgroup_path);
1638 * Control Group taskset
1640 struct task_and_cgroup {
1641 struct task_struct *task;
1642 struct cgroup *cgrp;
1643 struct css_set *cset;
1646 struct cgroup_taskset {
1647 struct task_and_cgroup single;
1648 struct flex_array *tc_array;
1651 struct cgroup *cur_cgrp;
1655 * cgroup_taskset_first - reset taskset and return the first task
1656 * @tset: taskset of interest
1658 * @tset iteration is initialized and the first task is returned.
1660 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1662 if (tset->tc_array) {
1664 return cgroup_taskset_next(tset);
1666 tset->cur_cgrp = tset->single.cgrp;
1667 return tset->single.task;
1670 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1673 * cgroup_taskset_next - iterate to the next task in taskset
1674 * @tset: taskset of interest
1676 * Return the next task in @tset. Iteration must have been initialized
1677 * with cgroup_taskset_first().
1679 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1681 struct task_and_cgroup *tc;
1683 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1686 tc = flex_array_get(tset->tc_array, tset->idx++);
1687 tset->cur_cgrp = tc->cgrp;
1690 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1693 * cgroup_taskset_cur_css - return the matching css for the current task
1694 * @tset: taskset of interest
1695 * @subsys_id: the ID of the target subsystem
1697 * Return the css for the current (last returned) task of @tset for
1698 * subsystem specified by @subsys_id. This function must be preceded by
1699 * either cgroup_taskset_first() or cgroup_taskset_next().
1701 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1704 return cgroup_css(tset->cur_cgrp, cgroup_subsys[subsys_id]);
1706 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1709 * cgroup_taskset_size - return the number of tasks in taskset
1710 * @tset: taskset of interest
1712 int cgroup_taskset_size(struct cgroup_taskset *tset)
1714 return tset->tc_array ? tset->tc_array_len : 1;
1716 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1720 * cgroup_task_migrate - move a task from one cgroup to another.
1722 * Must be called with cgroup_mutex and threadgroup 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;
1731 * We are synchronized through threadgroup_lock() against PF_EXITING
1732 * setting such that we can't race against cgroup_exit() changing the
1733 * css_set to init_css_set and dropping the old one.
1735 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1736 old_cset = task_css_set(tsk);
1739 rcu_assign_pointer(tsk->cgroups, new_cset);
1742 write_lock(&css_set_lock);
1743 list_move(&tsk->cg_list, &new_cset->tasks);
1744 write_unlock(&css_set_lock);
1747 * We just gained a reference on old_cset by taking it from the
1748 * task. As trading it for new_cset is protected by cgroup_mutex,
1749 * we're safe to drop it here; it will be freed under RCU.
1751 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1752 put_css_set(old_cset);
1756 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1757 * @cgrp: the cgroup to attach to
1758 * @tsk: the task or the leader of the threadgroup to be attached
1759 * @threadgroup: attach the whole threadgroup?
1761 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1762 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1764 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1767 int retval, i, group_size;
1768 struct cgroupfs_root *root = cgrp->root;
1769 struct cgroup_subsys_state *css, *failed_css = NULL;
1770 /* threadgroup list cursor and array */
1771 struct task_struct *leader = tsk;
1772 struct task_and_cgroup *tc;
1773 struct flex_array *group;
1774 struct cgroup_taskset tset = { };
1777 * step 0: in order to do expensive, possibly blocking operations for
1778 * every thread, we cannot iterate the thread group list, since it needs
1779 * rcu or tasklist locked. instead, build an array of all threads in the
1780 * group - group_rwsem prevents new threads from appearing, and if
1781 * threads exit, this will just be an over-estimate.
1784 group_size = get_nr_threads(tsk);
1787 /* flex_array supports very large thread-groups better than kmalloc. */
1788 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1791 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1792 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1794 goto out_free_group_list;
1798 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1799 * already PF_EXITING could be freed from underneath us unless we
1800 * take an rcu_read_lock.
1804 struct task_and_cgroup ent;
1806 /* @tsk either already exited or can't exit until the end */
1807 if (tsk->flags & PF_EXITING)
1810 /* as per above, nr_threads may decrease, but not increase. */
1811 BUG_ON(i >= group_size);
1813 ent.cgrp = task_cgroup_from_root(tsk, root);
1814 /* nothing to do if this task is already in the cgroup */
1815 if (ent.cgrp == cgrp)
1818 * saying GFP_ATOMIC has no effect here because we did prealloc
1819 * earlier, but it's good form to communicate our expectations.
1821 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
1822 BUG_ON(retval != 0);
1827 } while_each_thread(leader, tsk);
1829 /* remember the number of threads in the array for later. */
1831 tset.tc_array = group;
1832 tset.tc_array_len = group_size;
1834 /* methods shouldn't be called if no task is actually migrating */
1837 goto out_free_group_list;
1840 * step 1: check that we can legitimately attach to the cgroup.
1842 for_each_css(css, i, cgrp) {
1843 if (css->ss->can_attach) {
1844 retval = css->ss->can_attach(css, &tset);
1847 goto out_cancel_attach;
1853 * step 2: make sure css_sets exist for all threads to be migrated.
1854 * we use find_css_set, which allocates a new one if necessary.
1856 for (i = 0; i < group_size; i++) {
1857 struct css_set *old_cset;
1859 tc = flex_array_get(group, i);
1860 old_cset = task_css_set(tc->task);
1861 tc->cset = find_css_set(old_cset, cgrp);
1864 goto out_put_css_set_refs;
1869 * step 3: now that we're guaranteed success wrt the css_sets,
1870 * proceed to move all tasks to the new cgroup. There are no
1871 * failure cases after here, so this is the commit point.
1873 for (i = 0; i < group_size; i++) {
1874 tc = flex_array_get(group, i);
1875 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
1877 /* nothing is sensitive to fork() after this point. */
1880 * step 4: do subsystem attach callbacks.
1882 for_each_css(css, i, cgrp)
1883 if (css->ss->attach)
1884 css->ss->attach(css, &tset);
1887 * step 5: success! and cleanup
1890 out_put_css_set_refs:
1892 for (i = 0; i < group_size; i++) {
1893 tc = flex_array_get(group, i);
1896 put_css_set(tc->cset);
1901 for_each_css(css, i, cgrp) {
1902 if (css == failed_css)
1904 if (css->ss->cancel_attach)
1905 css->ss->cancel_attach(css, &tset);
1908 out_free_group_list:
1909 flex_array_free(group);
1914 * Find the task_struct of the task to attach by vpid and pass it along to the
1915 * function to attach either it or all tasks in its threadgroup. Will lock
1916 * cgroup_mutex and threadgroup; may take task_lock of task.
1918 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
1920 struct task_struct *tsk;
1921 const struct cred *cred = current_cred(), *tcred;
1924 if (!cgroup_lock_live_group(cgrp))
1930 tsk = find_task_by_vpid(pid);
1934 goto out_unlock_cgroup;
1937 * even if we're attaching all tasks in the thread group, we
1938 * only need to check permissions on one of them.
1940 tcred = __task_cred(tsk);
1941 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
1942 !uid_eq(cred->euid, tcred->uid) &&
1943 !uid_eq(cred->euid, tcred->suid)) {
1946 goto out_unlock_cgroup;
1952 tsk = tsk->group_leader;
1955 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
1956 * trapped in a cpuset, or RT worker may be born in a cgroup
1957 * with no rt_runtime allocated. Just say no.
1959 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
1962 goto out_unlock_cgroup;
1965 get_task_struct(tsk);
1968 threadgroup_lock(tsk);
1970 if (!thread_group_leader(tsk)) {
1972 * a race with de_thread from another thread's exec()
1973 * may strip us of our leadership, if this happens,
1974 * there is no choice but to throw this task away and
1975 * try again; this is
1976 * "double-double-toil-and-trouble-check locking".
1978 threadgroup_unlock(tsk);
1979 put_task_struct(tsk);
1980 goto retry_find_task;
1984 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
1986 threadgroup_unlock(tsk);
1988 put_task_struct(tsk);
1990 mutex_unlock(&cgroup_mutex);
1995 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
1996 * @from: attach to all cgroups of a given task
1997 * @tsk: the task to be attached
1999 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2001 struct cgroupfs_root *root;
2004 mutex_lock(&cgroup_mutex);
2005 for_each_active_root(root) {
2006 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2008 retval = cgroup_attach_task(from_cgrp, tsk, false);
2012 mutex_unlock(&cgroup_mutex);
2016 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2018 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2019 struct cftype *cft, u64 pid)
2021 return attach_task_by_pid(css->cgroup, pid, false);
2024 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2025 struct cftype *cft, u64 tgid)
2027 return attach_task_by_pid(css->cgroup, tgid, true);
2030 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2031 struct cftype *cft, const char *buffer)
2033 struct cgroupfs_root *root = css->cgroup->root;
2035 BUILD_BUG_ON(sizeof(root->release_agent_path) < PATH_MAX);
2036 if (!cgroup_lock_live_group(css->cgroup))
2038 spin_lock(&release_agent_path_lock);
2039 strlcpy(root->release_agent_path, buffer,
2040 sizeof(root->release_agent_path));
2041 spin_unlock(&release_agent_path_lock);
2042 mutex_unlock(&cgroup_mutex);
2046 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2048 struct cgroup *cgrp = seq_css(seq)->cgroup;
2050 if (!cgroup_lock_live_group(cgrp))
2052 seq_puts(seq, cgrp->root->release_agent_path);
2053 seq_putc(seq, '\n');
2054 mutex_unlock(&cgroup_mutex);
2058 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2060 struct cgroup *cgrp = seq_css(seq)->cgroup;
2062 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2066 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2067 size_t nbytes, loff_t off)
2069 struct cgroup *cgrp = of->kn->parent->priv;
2070 struct cftype *cft = of->kn->priv;
2071 struct cgroup_subsys_state *css;
2075 * kernfs guarantees that a file isn't deleted with operations in
2076 * flight, which means that the matching css is and stays alive and
2077 * doesn't need to be pinned. The RCU locking is not necessary
2078 * either. It's just for the convenience of using cgroup_css().
2081 css = cgroup_css(cgrp, cft->ss);
2084 if (cft->write_string) {
2085 ret = cft->write_string(css, cft, strstrip(buf));
2086 } else if (cft->write_u64) {
2087 unsigned long long v;
2088 ret = kstrtoull(buf, 0, &v);
2090 ret = cft->write_u64(css, cft, v);
2091 } else if (cft->write_s64) {
2093 ret = kstrtoll(buf, 0, &v);
2095 ret = cft->write_s64(css, cft, v);
2096 } else if (cft->trigger) {
2097 ret = cft->trigger(css, (unsigned int)cft->private);
2102 return ret ?: nbytes;
2105 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2107 return seq_cft(seq)->seq_start(seq, ppos);
2110 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2112 return seq_cft(seq)->seq_next(seq, v, ppos);
2115 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2117 seq_cft(seq)->seq_stop(seq, v);
2120 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2122 struct cftype *cft = seq_cft(m);
2123 struct cgroup_subsys_state *css = seq_css(m);
2126 return cft->seq_show(m, arg);
2129 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2130 else if (cft->read_s64)
2131 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2137 static struct kernfs_ops cgroup_kf_single_ops = {
2138 .atomic_write_len = PAGE_SIZE,
2139 .write = cgroup_file_write,
2140 .seq_show = cgroup_seqfile_show,
2143 static struct kernfs_ops cgroup_kf_ops = {
2144 .atomic_write_len = PAGE_SIZE,
2145 .write = cgroup_file_write,
2146 .seq_start = cgroup_seqfile_start,
2147 .seq_next = cgroup_seqfile_next,
2148 .seq_stop = cgroup_seqfile_stop,
2149 .seq_show = cgroup_seqfile_show,
2153 * cgroup_rename - Only allow simple rename of directories in place.
2155 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2156 const char *new_name_str)
2158 struct cgroup *cgrp = kn->priv;
2161 if (kernfs_type(kn) != KERNFS_DIR)
2163 if (kn->parent != new_parent)
2167 * This isn't a proper migration and its usefulness is very
2168 * limited. Disallow if sane_behavior.
2170 if (cgroup_sane_behavior(cgrp))
2173 mutex_lock(&cgroup_tree_mutex);
2174 mutex_lock(&cgroup_mutex);
2176 ret = kernfs_rename(kn, new_parent, new_name_str);
2178 mutex_unlock(&cgroup_mutex);
2179 mutex_unlock(&cgroup_tree_mutex);
2183 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2185 char name[CGROUP_FILE_NAME_MAX];
2186 struct kernfs_node *kn;
2187 struct lock_class_key *key = NULL;
2189 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2190 key = &cft->lockdep_key;
2192 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2193 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2201 * cgroup_addrm_files - add or remove files to a cgroup directory
2202 * @cgrp: the target cgroup
2203 * @cfts: array of cftypes to be added
2204 * @is_add: whether to add or remove
2206 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2207 * For removals, this function never fails. If addition fails, this
2208 * function doesn't remove files already added. The caller is responsible
2211 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2217 lockdep_assert_held(&cgroup_tree_mutex);
2219 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2220 /* does cft->flags tell us to skip this file on @cgrp? */
2221 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2223 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2225 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2229 ret = cgroup_add_file(cgrp, cft);
2231 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2236 cgroup_rm_file(cgrp, cft);
2242 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2245 struct cgroup_subsys *ss = cfts[0].ss;
2246 struct cgroup *root = &ss->root->top_cgroup;
2247 struct cgroup_subsys_state *css;
2250 lockdep_assert_held(&cgroup_tree_mutex);
2252 /* don't bother if @ss isn't attached */
2253 if (ss->root == &cgroup_dummy_root)
2256 /* add/rm files for all cgroups created before */
2257 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2258 struct cgroup *cgrp = css->cgroup;
2260 if (cgroup_is_dead(cgrp))
2263 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2269 kernfs_activate(root->kn);
2273 static void cgroup_exit_cftypes(struct cftype *cfts)
2277 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2278 /* free copy for custom atomic_write_len, see init_cftypes() */
2279 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2286 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2290 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2291 struct kernfs_ops *kf_ops;
2293 WARN_ON(cft->ss || cft->kf_ops);
2296 kf_ops = &cgroup_kf_ops;
2298 kf_ops = &cgroup_kf_single_ops;
2301 * Ugh... if @cft wants a custom max_write_len, we need to
2302 * make a copy of kf_ops to set its atomic_write_len.
2304 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2305 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
2307 cgroup_exit_cftypes(cfts);
2310 kf_ops->atomic_write_len = cft->max_write_len;
2313 cft->kf_ops = kf_ops;
2320 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
2322 lockdep_assert_held(&cgroup_tree_mutex);
2324 if (!cfts || !cfts[0].ss)
2327 list_del(&cfts->node);
2328 cgroup_apply_cftypes(cfts, false);
2329 cgroup_exit_cftypes(cfts);
2334 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2335 * @cfts: zero-length name terminated array of cftypes
2337 * Unregister @cfts. Files described by @cfts are removed from all
2338 * existing cgroups and all future cgroups won't have them either. This
2339 * function can be called anytime whether @cfts' subsys is attached or not.
2341 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2344 int cgroup_rm_cftypes(struct cftype *cfts)
2348 mutex_lock(&cgroup_tree_mutex);
2349 ret = cgroup_rm_cftypes_locked(cfts);
2350 mutex_unlock(&cgroup_tree_mutex);
2355 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2356 * @ss: target cgroup subsystem
2357 * @cfts: zero-length name terminated array of cftypes
2359 * Register @cfts to @ss. Files described by @cfts are created for all
2360 * existing cgroups to which @ss is attached and all future cgroups will
2361 * have them too. This function can be called anytime whether @ss is
2364 * Returns 0 on successful registration, -errno on failure. Note that this
2365 * function currently returns 0 as long as @cfts registration is successful
2366 * even if some file creation attempts on existing cgroups fail.
2368 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2372 ret = cgroup_init_cftypes(ss, cfts);
2376 mutex_lock(&cgroup_tree_mutex);
2378 list_add_tail(&cfts->node, &ss->cfts);
2379 ret = cgroup_apply_cftypes(cfts, true);
2381 cgroup_rm_cftypes_locked(cfts);
2383 mutex_unlock(&cgroup_tree_mutex);
2386 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2389 * cgroup_task_count - count the number of tasks in a cgroup.
2390 * @cgrp: the cgroup in question
2392 * Return the number of tasks in the cgroup.
2394 int cgroup_task_count(const struct cgroup *cgrp)
2397 struct cgrp_cset_link *link;
2399 read_lock(&css_set_lock);
2400 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2401 count += atomic_read(&link->cset->refcount);
2402 read_unlock(&css_set_lock);
2407 * css_next_child - find the next child of a given css
2408 * @pos_css: the current position (%NULL to initiate traversal)
2409 * @parent_css: css whose children to walk
2411 * This function returns the next child of @parent_css and should be called
2412 * under either cgroup_mutex or RCU read lock. The only requirement is
2413 * that @parent_css and @pos_css are accessible. The next sibling is
2414 * guaranteed to be returned regardless of their states.
2416 struct cgroup_subsys_state *
2417 css_next_child(struct cgroup_subsys_state *pos_css,
2418 struct cgroup_subsys_state *parent_css)
2420 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2421 struct cgroup *cgrp = parent_css->cgroup;
2422 struct cgroup *next;
2424 cgroup_assert_mutexes_or_rcu_locked();
2427 * @pos could already have been removed. Once a cgroup is removed,
2428 * its ->sibling.next is no longer updated when its next sibling
2429 * changes. As CGRP_DEAD assertion is serialized and happens
2430 * before the cgroup is taken off the ->sibling list, if we see it
2431 * unasserted, it's guaranteed that the next sibling hasn't
2432 * finished its grace period even if it's already removed, and thus
2433 * safe to dereference from this RCU critical section. If
2434 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2435 * to be visible as %true here.
2437 * If @pos is dead, its next pointer can't be dereferenced;
2438 * however, as each cgroup is given a monotonically increasing
2439 * unique serial number and always appended to the sibling list,
2440 * the next one can be found by walking the parent's children until
2441 * we see a cgroup with higher serial number than @pos's. While
2442 * this path can be slower, it's taken only when either the current
2443 * cgroup is removed or iteration and removal race.
2446 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2447 } else if (likely(!cgroup_is_dead(pos))) {
2448 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2450 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2451 if (next->serial_nr > pos->serial_nr)
2455 if (&next->sibling == &cgrp->children)
2458 return cgroup_css(next, parent_css->ss);
2460 EXPORT_SYMBOL_GPL(css_next_child);
2463 * css_next_descendant_pre - find the next descendant for pre-order walk
2464 * @pos: the current position (%NULL to initiate traversal)
2465 * @root: css whose descendants to walk
2467 * To be used by css_for_each_descendant_pre(). Find the next descendant
2468 * to visit for pre-order traversal of @root's descendants. @root is
2469 * included in the iteration and the first node to be visited.
2471 * While this function requires cgroup_mutex or RCU read locking, it
2472 * doesn't require the whole traversal to be contained in a single critical
2473 * section. This function will return the correct next descendant as long
2474 * as both @pos and @root are accessible and @pos is a descendant of @root.
2476 struct cgroup_subsys_state *
2477 css_next_descendant_pre(struct cgroup_subsys_state *pos,
2478 struct cgroup_subsys_state *root)
2480 struct cgroup_subsys_state *next;
2482 cgroup_assert_mutexes_or_rcu_locked();
2484 /* if first iteration, visit @root */
2488 /* visit the first child if exists */
2489 next = css_next_child(NULL, pos);
2493 /* no child, visit my or the closest ancestor's next sibling */
2494 while (pos != root) {
2495 next = css_next_child(pos, css_parent(pos));
2498 pos = css_parent(pos);
2503 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
2506 * css_rightmost_descendant - return the rightmost descendant of a css
2507 * @pos: css of interest
2509 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2510 * is returned. This can be used during pre-order traversal to skip
2513 * While this function requires cgroup_mutex or RCU read locking, it
2514 * doesn't require the whole traversal to be contained in a single critical
2515 * section. This function will return the correct rightmost descendant as
2516 * long as @pos is accessible.
2518 struct cgroup_subsys_state *
2519 css_rightmost_descendant(struct cgroup_subsys_state *pos)
2521 struct cgroup_subsys_state *last, *tmp;
2523 cgroup_assert_mutexes_or_rcu_locked();
2527 /* ->prev isn't RCU safe, walk ->next till the end */
2529 css_for_each_child(tmp, last)
2535 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
2537 static struct cgroup_subsys_state *
2538 css_leftmost_descendant(struct cgroup_subsys_state *pos)
2540 struct cgroup_subsys_state *last;
2544 pos = css_next_child(NULL, pos);
2551 * css_next_descendant_post - find the next descendant for post-order walk
2552 * @pos: the current position (%NULL to initiate traversal)
2553 * @root: css whose descendants to walk
2555 * To be used by css_for_each_descendant_post(). Find the next descendant
2556 * to visit for post-order traversal of @root's descendants. @root is
2557 * included in the iteration and the last node to be visited.
2559 * While this function requires cgroup_mutex or RCU read locking, it
2560 * doesn't require the whole traversal to be contained in a single critical
2561 * section. This function will return the correct next descendant as long
2562 * as both @pos and @cgroup are accessible and @pos is a descendant of
2565 struct cgroup_subsys_state *
2566 css_next_descendant_post(struct cgroup_subsys_state *pos,
2567 struct cgroup_subsys_state *root)
2569 struct cgroup_subsys_state *next;
2571 cgroup_assert_mutexes_or_rcu_locked();
2573 /* if first iteration, visit leftmost descendant which may be @root */
2575 return css_leftmost_descendant(root);
2577 /* if we visited @root, we're done */
2581 /* if there's an unvisited sibling, visit its leftmost descendant */
2582 next = css_next_child(pos, css_parent(pos));
2584 return css_leftmost_descendant(next);
2586 /* no sibling left, visit parent */
2587 return css_parent(pos);
2589 EXPORT_SYMBOL_GPL(css_next_descendant_post);
2592 * css_advance_task_iter - advance a task itererator to the next css_set
2593 * @it: the iterator to advance
2595 * Advance @it to the next css_set to walk.
2597 static void css_advance_task_iter(struct css_task_iter *it)
2599 struct list_head *l = it->cset_link;
2600 struct cgrp_cset_link *link;
2601 struct css_set *cset;
2603 /* Advance to the next non-empty css_set */
2606 if (l == &it->origin_css->cgroup->cset_links) {
2607 it->cset_link = NULL;
2610 link = list_entry(l, struct cgrp_cset_link, cset_link);
2612 } while (list_empty(&cset->tasks));
2614 it->task = cset->tasks.next;
2618 * css_task_iter_start - initiate task iteration
2619 * @css: the css to walk tasks of
2620 * @it: the task iterator to use
2622 * Initiate iteration through the tasks of @css. The caller can call
2623 * css_task_iter_next() to walk through the tasks until the function
2624 * returns NULL. On completion of iteration, css_task_iter_end() must be
2627 * Note that this function acquires a lock which is released when the
2628 * iteration finishes. The caller can't sleep while iteration is in
2631 void css_task_iter_start(struct cgroup_subsys_state *css,
2632 struct css_task_iter *it)
2633 __acquires(css_set_lock)
2635 /* no one should try to iterate before mounting cgroups */
2636 WARN_ON_ONCE(!use_task_css_set_links);
2638 read_lock(&css_set_lock);
2640 it->origin_css = css;
2641 it->cset_link = &css->cgroup->cset_links;
2643 css_advance_task_iter(it);
2647 * css_task_iter_next - return the next task for the iterator
2648 * @it: the task iterator being iterated
2650 * The "next" function for task iteration. @it should have been
2651 * initialized via css_task_iter_start(). Returns NULL when the iteration
2654 struct task_struct *css_task_iter_next(struct css_task_iter *it)
2656 struct task_struct *res;
2657 struct list_head *l = it->task;
2658 struct cgrp_cset_link *link;
2660 /* If the iterator cg is NULL, we have no tasks */
2663 res = list_entry(l, struct task_struct, cg_list);
2664 /* Advance iterator to find next entry */
2666 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
2667 if (l == &link->cset->tasks) {
2669 * We reached the end of this task list - move on to the
2670 * next cgrp_cset_link.
2672 css_advance_task_iter(it);
2680 * css_task_iter_end - finish task iteration
2681 * @it: the task iterator to finish
2683 * Finish task iteration started by css_task_iter_start().
2685 void css_task_iter_end(struct css_task_iter *it)
2686 __releases(css_set_lock)
2688 read_unlock(&css_set_lock);
2691 static inline int started_after_time(struct task_struct *t1,
2692 struct timespec *time,
2693 struct task_struct *t2)
2695 int start_diff = timespec_compare(&t1->start_time, time);
2696 if (start_diff > 0) {
2698 } else if (start_diff < 0) {
2702 * Arbitrarily, if two processes started at the same
2703 * time, we'll say that the lower pointer value
2704 * started first. Note that t2 may have exited by now
2705 * so this may not be a valid pointer any longer, but
2706 * that's fine - it still serves to distinguish
2707 * between two tasks started (effectively) simultaneously.
2714 * This function is a callback from heap_insert() and is used to order
2716 * In this case we order the heap in descending task start time.
2718 static inline int started_after(void *p1, void *p2)
2720 struct task_struct *t1 = p1;
2721 struct task_struct *t2 = p2;
2722 return started_after_time(t1, &t2->start_time, t2);
2726 * css_scan_tasks - iterate though all the tasks in a css
2727 * @css: the css to iterate tasks of
2728 * @test: optional test callback
2729 * @process: process callback
2730 * @data: data passed to @test and @process
2731 * @heap: optional pre-allocated heap used for task iteration
2733 * Iterate through all the tasks in @css, calling @test for each, and if it
2734 * returns %true, call @process for it also.
2736 * @test may be NULL, meaning always true (select all tasks), which
2737 * effectively duplicates css_task_iter_{start,next,end}() but does not
2738 * lock css_set_lock for the call to @process.
2740 * It is guaranteed that @process will act on every task that is a member
2741 * of @css for the duration of this call. This function may or may not
2742 * call @process for tasks that exit or move to a different css during the
2743 * call, or are forked or move into the css during the call.
2745 * Note that @test may be called with locks held, and may in some
2746 * situations be called multiple times for the same task, so it should be
2749 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
2750 * heap operations (and its "gt" member will be overwritten), else a
2751 * temporary heap will be used (allocation of which may cause this function
2754 int css_scan_tasks(struct cgroup_subsys_state *css,
2755 bool (*test)(struct task_struct *, void *),
2756 void (*process)(struct task_struct *, void *),
2757 void *data, struct ptr_heap *heap)
2760 struct css_task_iter it;
2761 struct task_struct *p, *dropped;
2762 /* Never dereference latest_task, since it's not refcounted */
2763 struct task_struct *latest_task = NULL;
2764 struct ptr_heap tmp_heap;
2765 struct timespec latest_time = { 0, 0 };
2768 /* The caller supplied our heap and pre-allocated its memory */
2769 heap->gt = &started_after;
2771 /* We need to allocate our own heap memory */
2773 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2775 /* cannot allocate the heap */
2781 * Scan tasks in the css, using the @test callback to determine
2782 * which are of interest, and invoking @process callback on the
2783 * ones which need an update. Since we don't want to hold any
2784 * locks during the task updates, gather tasks to be processed in a
2785 * heap structure. The heap is sorted by descending task start
2786 * time. If the statically-sized heap fills up, we overflow tasks
2787 * that started later, and in future iterations only consider tasks
2788 * that started after the latest task in the previous pass. This
2789 * guarantees forward progress and that we don't miss any tasks.
2792 css_task_iter_start(css, &it);
2793 while ((p = css_task_iter_next(&it))) {
2795 * Only affect tasks that qualify per the caller's callback,
2796 * if he provided one
2798 if (test && !test(p, data))
2801 * Only process tasks that started after the last task
2804 if (!started_after_time(p, &latest_time, latest_task))
2806 dropped = heap_insert(heap, p);
2807 if (dropped == NULL) {
2809 * The new task was inserted; the heap wasn't
2813 } else if (dropped != p) {
2815 * The new task was inserted, and pushed out a
2819 put_task_struct(dropped);
2822 * Else the new task was newer than anything already in
2823 * the heap and wasn't inserted
2826 css_task_iter_end(&it);
2829 for (i = 0; i < heap->size; i++) {
2830 struct task_struct *q = heap->ptrs[i];
2832 latest_time = q->start_time;
2835 /* Process the task per the caller's callback */
2840 * If we had to process any tasks at all, scan again
2841 * in case some of them were in the middle of forking
2842 * children that didn't get processed.
2843 * Not the most efficient way to do it, but it avoids
2844 * having to take callback_mutex in the fork path
2848 if (heap == &tmp_heap)
2849 heap_free(&tmp_heap);
2853 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
2855 struct cgroup *new_cgroup = data;
2857 mutex_lock(&cgroup_mutex);
2858 cgroup_attach_task(new_cgroup, task, false);
2859 mutex_unlock(&cgroup_mutex);
2863 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
2864 * @to: cgroup to which the tasks will be moved
2865 * @from: cgroup in which the tasks currently reside
2867 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
2869 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
2874 * Stuff for reading the 'tasks'/'procs' files.
2876 * Reading this file can return large amounts of data if a cgroup has
2877 * *lots* of attached tasks. So it may need several calls to read(),
2878 * but we cannot guarantee that the information we produce is correct
2879 * unless we produce it entirely atomically.
2883 /* which pidlist file are we talking about? */
2884 enum cgroup_filetype {
2890 * A pidlist is a list of pids that virtually represents the contents of one
2891 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
2892 * a pair (one each for procs, tasks) for each pid namespace that's relevant
2895 struct cgroup_pidlist {
2897 * used to find which pidlist is wanted. doesn't change as long as
2898 * this particular list stays in the list.
2900 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
2903 /* how many elements the above list has */
2905 /* each of these stored in a list by its cgroup */
2906 struct list_head links;
2907 /* pointer to the cgroup we belong to, for list removal purposes */
2908 struct cgroup *owner;
2909 /* for delayed destruction */
2910 struct delayed_work destroy_dwork;
2914 * The following two functions "fix" the issue where there are more pids
2915 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
2916 * TODO: replace with a kernel-wide solution to this problem
2918 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
2919 static void *pidlist_allocate(int count)
2921 if (PIDLIST_TOO_LARGE(count))
2922 return vmalloc(count * sizeof(pid_t));
2924 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
2927 static void pidlist_free(void *p)
2929 if (is_vmalloc_addr(p))
2936 * Used to destroy all pidlists lingering waiting for destroy timer. None
2937 * should be left afterwards.
2939 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
2941 struct cgroup_pidlist *l, *tmp_l;
2943 mutex_lock(&cgrp->pidlist_mutex);
2944 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
2945 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
2946 mutex_unlock(&cgrp->pidlist_mutex);
2948 flush_workqueue(cgroup_pidlist_destroy_wq);
2949 BUG_ON(!list_empty(&cgrp->pidlists));
2952 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
2954 struct delayed_work *dwork = to_delayed_work(work);
2955 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
2957 struct cgroup_pidlist *tofree = NULL;
2959 mutex_lock(&l->owner->pidlist_mutex);
2962 * Destroy iff we didn't get queued again. The state won't change
2963 * as destroy_dwork can only be queued while locked.
2965 if (!delayed_work_pending(dwork)) {
2966 list_del(&l->links);
2967 pidlist_free(l->list);
2968 put_pid_ns(l->key.ns);
2972 mutex_unlock(&l->owner->pidlist_mutex);
2977 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
2978 * Returns the number of unique elements.
2980 static int pidlist_uniq(pid_t *list, int length)
2985 * we presume the 0th element is unique, so i starts at 1. trivial
2986 * edge cases first; no work needs to be done for either
2988 if (length == 0 || length == 1)
2990 /* src and dest walk down the list; dest counts unique elements */
2991 for (src = 1; src < length; src++) {
2992 /* find next unique element */
2993 while (list[src] == list[src-1]) {
2998 /* dest always points to where the next unique element goes */
2999 list[dest] = list[src];
3007 * The two pid files - task and cgroup.procs - guaranteed that the result
3008 * is sorted, which forced this whole pidlist fiasco. As pid order is
3009 * different per namespace, each namespace needs differently sorted list,
3010 * making it impossible to use, for example, single rbtree of member tasks
3011 * sorted by task pointer. As pidlists can be fairly large, allocating one
3012 * per open file is dangerous, so cgroup had to implement shared pool of
3013 * pidlists keyed by cgroup and namespace.
3015 * All this extra complexity was caused by the original implementation
3016 * committing to an entirely unnecessary property. In the long term, we
3017 * want to do away with it. Explicitly scramble sort order if
3018 * sane_behavior so that no such expectation exists in the new interface.
3020 * Scrambling is done by swapping every two consecutive bits, which is
3021 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3023 static pid_t pid_fry(pid_t pid)
3025 unsigned a = pid & 0x55555555;
3026 unsigned b = pid & 0xAAAAAAAA;
3028 return (a << 1) | (b >> 1);
3031 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3033 if (cgroup_sane_behavior(cgrp))
3034 return pid_fry(pid);
3039 static int cmppid(const void *a, const void *b)
3041 return *(pid_t *)a - *(pid_t *)b;
3044 static int fried_cmppid(const void *a, const void *b)
3046 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3049 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3050 enum cgroup_filetype type)
3052 struct cgroup_pidlist *l;
3053 /* don't need task_nsproxy() if we're looking at ourself */
3054 struct pid_namespace *ns = task_active_pid_ns(current);
3056 lockdep_assert_held(&cgrp->pidlist_mutex);
3058 list_for_each_entry(l, &cgrp->pidlists, links)
3059 if (l->key.type == type && l->key.ns == ns)
3065 * find the appropriate pidlist for our purpose (given procs vs tasks)
3066 * returns with the lock on that pidlist already held, and takes care
3067 * of the use count, or returns NULL with no locks held if we're out of
3070 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3071 enum cgroup_filetype type)
3073 struct cgroup_pidlist *l;
3075 lockdep_assert_held(&cgrp->pidlist_mutex);
3077 l = cgroup_pidlist_find(cgrp, type);
3081 /* entry not found; create a new one */
3082 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3086 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3088 /* don't need task_nsproxy() if we're looking at ourself */
3089 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3091 list_add(&l->links, &cgrp->pidlists);
3096 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3098 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3099 struct cgroup_pidlist **lp)
3103 int pid, n = 0; /* used for populating the array */
3104 struct css_task_iter it;
3105 struct task_struct *tsk;
3106 struct cgroup_pidlist *l;
3108 lockdep_assert_held(&cgrp->pidlist_mutex);
3111 * If cgroup gets more users after we read count, we won't have
3112 * enough space - tough. This race is indistinguishable to the
3113 * caller from the case that the additional cgroup users didn't
3114 * show up until sometime later on.
3116 length = cgroup_task_count(cgrp);
3117 array = pidlist_allocate(length);
3120 /* now, populate the array */
3121 css_task_iter_start(&cgrp->dummy_css, &it);
3122 while ((tsk = css_task_iter_next(&it))) {
3123 if (unlikely(n == length))
3125 /* get tgid or pid for procs or tasks file respectively */
3126 if (type == CGROUP_FILE_PROCS)
3127 pid = task_tgid_vnr(tsk);
3129 pid = task_pid_vnr(tsk);
3130 if (pid > 0) /* make sure to only use valid results */
3133 css_task_iter_end(&it);
3135 /* now sort & (if procs) strip out duplicates */
3136 if (cgroup_sane_behavior(cgrp))
3137 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3139 sort(array, length, sizeof(pid_t), cmppid, NULL);
3140 if (type == CGROUP_FILE_PROCS)
3141 length = pidlist_uniq(array, length);
3143 l = cgroup_pidlist_find_create(cgrp, type);
3145 mutex_unlock(&cgrp->pidlist_mutex);
3146 pidlist_free(array);
3150 /* store array, freeing old if necessary */
3151 pidlist_free(l->list);
3159 * cgroupstats_build - build and fill cgroupstats
3160 * @stats: cgroupstats to fill information into
3161 * @dentry: A dentry entry belonging to the cgroup for which stats have
3164 * Build and fill cgroupstats so that taskstats can export it to user
3167 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3169 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3170 struct cgroup *cgrp;
3171 struct css_task_iter it;
3172 struct task_struct *tsk;
3174 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3175 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3176 kernfs_type(kn) != KERNFS_DIR)
3180 * We aren't being called from kernfs and there's no guarantee on
3181 * @kn->priv's validity. For this and css_tryget_from_dir(),
3182 * @kn->priv is RCU safe. Let's do the RCU dancing.
3185 cgrp = rcu_dereference(kn->priv);
3191 css_task_iter_start(&cgrp->dummy_css, &it);
3192 while ((tsk = css_task_iter_next(&it))) {
3193 switch (tsk->state) {
3195 stats->nr_running++;
3197 case TASK_INTERRUPTIBLE:
3198 stats->nr_sleeping++;
3200 case TASK_UNINTERRUPTIBLE:
3201 stats->nr_uninterruptible++;
3204 stats->nr_stopped++;
3207 if (delayacct_is_task_waiting_on_io(tsk))
3208 stats->nr_io_wait++;
3212 css_task_iter_end(&it);
3220 * seq_file methods for the tasks/procs files. The seq_file position is the
3221 * next pid to display; the seq_file iterator is a pointer to the pid
3222 * in the cgroup->l->list array.
3225 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3228 * Initially we receive a position value that corresponds to
3229 * one more than the last pid shown (or 0 on the first call or
3230 * after a seek to the start). Use a binary-search to find the
3231 * next pid to display, if any
3233 struct kernfs_open_file *of = s->private;
3234 struct cgroup *cgrp = seq_css(s)->cgroup;
3235 struct cgroup_pidlist *l;
3236 enum cgroup_filetype type = seq_cft(s)->private;
3237 int index = 0, pid = *pos;
3240 mutex_lock(&cgrp->pidlist_mutex);
3243 * !NULL @of->priv indicates that this isn't the first start()
3244 * after open. If the matching pidlist is around, we can use that.
3245 * Look for it. Note that @of->priv can't be used directly. It
3246 * could already have been destroyed.
3249 of->priv = cgroup_pidlist_find(cgrp, type);
3252 * Either this is the first start() after open or the matching
3253 * pidlist has been destroyed inbetween. Create a new one.
3256 ret = pidlist_array_load(cgrp, type,
3257 (struct cgroup_pidlist **)&of->priv);
3259 return ERR_PTR(ret);
3264 int end = l->length;
3266 while (index < end) {
3267 int mid = (index + end) / 2;
3268 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3271 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3277 /* If we're off the end of the array, we're done */
3278 if (index >= l->length)
3280 /* Update the abstract position to be the actual pid that we found */
3281 iter = l->list + index;
3282 *pos = cgroup_pid_fry(cgrp, *iter);
3286 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3288 struct kernfs_open_file *of = s->private;
3289 struct cgroup_pidlist *l = of->priv;
3292 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3293 CGROUP_PIDLIST_DESTROY_DELAY);
3294 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3297 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3299 struct kernfs_open_file *of = s->private;
3300 struct cgroup_pidlist *l = of->priv;
3302 pid_t *end = l->list + l->length;
3304 * Advance to the next pid in the array. If this goes off the
3311 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3316 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3318 return seq_printf(s, "%d\n", *(int *)v);
3322 * seq_operations functions for iterating on pidlists through seq_file -
3323 * independent of whether it's tasks or procs
3325 static const struct seq_operations cgroup_pidlist_seq_operations = {
3326 .start = cgroup_pidlist_start,
3327 .stop = cgroup_pidlist_stop,
3328 .next = cgroup_pidlist_next,
3329 .show = cgroup_pidlist_show,
3332 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3335 return notify_on_release(css->cgroup);
3338 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3339 struct cftype *cft, u64 val)
3341 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3343 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3345 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3349 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3352 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3355 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3356 struct cftype *cft, u64 val)
3359 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3361 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3365 static struct cftype cgroup_base_files[] = {
3367 .name = "cgroup.procs",
3368 .seq_start = cgroup_pidlist_start,
3369 .seq_next = cgroup_pidlist_next,
3370 .seq_stop = cgroup_pidlist_stop,
3371 .seq_show = cgroup_pidlist_show,
3372 .private = CGROUP_FILE_PROCS,
3373 .write_u64 = cgroup_procs_write,
3374 .mode = S_IRUGO | S_IWUSR,
3377 .name = "cgroup.clone_children",
3378 .flags = CFTYPE_INSANE,
3379 .read_u64 = cgroup_clone_children_read,
3380 .write_u64 = cgroup_clone_children_write,
3383 .name = "cgroup.sane_behavior",
3384 .flags = CFTYPE_ONLY_ON_ROOT,
3385 .seq_show = cgroup_sane_behavior_show,
3389 * Historical crazy stuff. These don't have "cgroup." prefix and
3390 * don't exist if sane_behavior. If you're depending on these, be
3391 * prepared to be burned.
3395 .flags = CFTYPE_INSANE, /* use "procs" instead */
3396 .seq_start = cgroup_pidlist_start,
3397 .seq_next = cgroup_pidlist_next,
3398 .seq_stop = cgroup_pidlist_stop,
3399 .seq_show = cgroup_pidlist_show,
3400 .private = CGROUP_FILE_TASKS,
3401 .write_u64 = cgroup_tasks_write,
3402 .mode = S_IRUGO | S_IWUSR,
3405 .name = "notify_on_release",
3406 .flags = CFTYPE_INSANE,
3407 .read_u64 = cgroup_read_notify_on_release,
3408 .write_u64 = cgroup_write_notify_on_release,
3411 .name = "release_agent",
3412 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3413 .seq_show = cgroup_release_agent_show,
3414 .write_string = cgroup_release_agent_write,
3415 .max_write_len = PATH_MAX - 1,
3421 * cgroup_populate_dir - create subsys files in a cgroup directory
3422 * @cgrp: target cgroup
3423 * @subsys_mask: mask of the subsystem ids whose files should be added
3425 * On failure, no file is added.
3427 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3429 struct cgroup_subsys *ss;
3432 /* process cftsets of each subsystem */
3433 for_each_subsys(ss, i) {
3434 struct cftype *cfts;
3436 if (!test_bit(i, &subsys_mask))
3439 list_for_each_entry(cfts, &ss->cfts, node) {
3440 ret = cgroup_addrm_files(cgrp, cfts, true);
3447 cgroup_clear_dir(cgrp, subsys_mask);
3452 * css destruction is four-stage process.
3454 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3455 * Implemented in kill_css().
3457 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3458 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3459 * by invoking offline_css(). After offlining, the base ref is put.
3460 * Implemented in css_killed_work_fn().
3462 * 3. When the percpu_ref reaches zero, the only possible remaining
3463 * accessors are inside RCU read sections. css_release() schedules the
3466 * 4. After the grace period, the css can be freed. Implemented in
3467 * css_free_work_fn().
3469 * It is actually hairier because both step 2 and 4 require process context
3470 * and thus involve punting to css->destroy_work adding two additional
3471 * steps to the already complex sequence.
3473 static void css_free_work_fn(struct work_struct *work)
3475 struct cgroup_subsys_state *css =
3476 container_of(work, struct cgroup_subsys_state, destroy_work);
3477 struct cgroup *cgrp = css->cgroup;
3480 css_put(css->parent);
3482 css->ss->css_free(css);
3486 static void css_free_rcu_fn(struct rcu_head *rcu_head)
3488 struct cgroup_subsys_state *css =
3489 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
3491 INIT_WORK(&css->destroy_work, css_free_work_fn);
3492 queue_work(cgroup_destroy_wq, &css->destroy_work);
3495 static void css_release(struct percpu_ref *ref)
3497 struct cgroup_subsys_state *css =
3498 container_of(ref, struct cgroup_subsys_state, refcnt);
3500 rcu_assign_pointer(css->cgroup->subsys[css->ss->id], NULL);
3501 call_rcu(&css->rcu_head, css_free_rcu_fn);
3504 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3505 struct cgroup *cgrp)
3512 css->parent = cgroup_css(cgrp->parent, ss);
3514 css->flags |= CSS_ROOT;
3516 BUG_ON(cgroup_css(cgrp, ss));
3519 /* invoke ->css_online() on a new CSS and mark it online if successful */
3520 static int online_css(struct cgroup_subsys_state *css)
3522 struct cgroup_subsys *ss = css->ss;
3525 lockdep_assert_held(&cgroup_tree_mutex);
3526 lockdep_assert_held(&cgroup_mutex);
3529 ret = ss->css_online(css);
3531 css->flags |= CSS_ONLINE;
3532 css->cgroup->nr_css++;
3533 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
3538 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
3539 static void offline_css(struct cgroup_subsys_state *css)
3541 struct cgroup_subsys *ss = css->ss;
3543 lockdep_assert_held(&cgroup_tree_mutex);
3544 lockdep_assert_held(&cgroup_mutex);
3546 if (!(css->flags & CSS_ONLINE))
3549 if (ss->css_offline)
3550 ss->css_offline(css);
3552 css->flags &= ~CSS_ONLINE;
3553 css->cgroup->nr_css--;
3554 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
3558 * create_css - create a cgroup_subsys_state
3559 * @cgrp: the cgroup new css will be associated with
3560 * @ss: the subsys of new css
3562 * Create a new css associated with @cgrp - @ss pair. On success, the new
3563 * css is online and installed in @cgrp with all interface files created.
3564 * Returns 0 on success, -errno on failure.
3566 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
3568 struct cgroup *parent = cgrp->parent;
3569 struct cgroup_subsys_state *css;
3572 lockdep_assert_held(&cgroup_mutex);
3574 css = ss->css_alloc(cgroup_css(parent, ss));
3576 return PTR_ERR(css);
3578 err = percpu_ref_init(&css->refcnt, css_release);
3582 init_css(css, ss, cgrp);
3584 err = cgroup_populate_dir(cgrp, 1 << ss->id);
3588 err = online_css(css);
3593 css_get(css->parent);
3595 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
3597 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",
3598 current->comm, current->pid, ss->name);
3599 if (!strcmp(ss->name, "memory"))
3600 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
3601 ss->warned_broken_hierarchy = true;
3607 percpu_ref_cancel_init(&css->refcnt);
3613 * cgroup_create - create a cgroup
3614 * @parent: cgroup that will be parent of the new cgroup
3615 * @name: name of the new cgroup
3616 * @mode: mode to set on new cgroup
3618 static long cgroup_create(struct cgroup *parent, const char *name,
3621 struct cgroup *cgrp;
3622 struct cgroupfs_root *root = parent->root;
3624 struct cgroup_subsys *ss;
3625 struct kernfs_node *kn;
3627 /* allocate the cgroup and its ID, 0 is reserved for the root */
3628 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
3632 mutex_lock(&cgroup_tree_mutex);
3635 * Only live parents can have children. Note that the liveliness
3636 * check isn't strictly necessary because cgroup_mkdir() and
3637 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
3638 * anyway so that locking is contained inside cgroup proper and we
3639 * don't get nasty surprises if we ever grow another caller.
3641 if (!cgroup_lock_live_group(parent)) {
3643 goto err_unlock_tree;
3647 * Temporarily set the pointer to NULL, so idr_find() won't return
3648 * a half-baked cgroup.
3650 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
3656 init_cgroup_housekeeping(cgrp);
3658 cgrp->parent = parent;
3659 cgrp->dummy_css.parent = &parent->dummy_css;
3660 cgrp->root = parent->root;
3662 if (notify_on_release(parent))
3663 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3665 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
3666 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3668 /* create the directory */
3669 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
3677 * This extra ref will be put in cgroup_free_fn() and guarantees
3678 * that @cgrp->kn is always accessible.
3682 cgrp->serial_nr = cgroup_serial_nr_next++;
3684 /* allocation complete, commit to creation */
3685 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
3686 atomic_inc(&root->nr_cgrps);
3690 * @cgrp is now fully operational. If something fails after this
3691 * point, it'll be released via the normal destruction path.
3693 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
3695 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
3699 /* let's create and online css's */
3700 for_each_subsys(ss, ssid) {
3701 if (root->subsys_mask & (1 << ssid)) {
3702 err = create_css(cgrp, ss);
3708 kernfs_activate(kn);
3710 mutex_unlock(&cgroup_mutex);
3711 mutex_unlock(&cgroup_tree_mutex);
3716 idr_remove(&root->cgroup_idr, cgrp->id);
3718 mutex_unlock(&cgroup_mutex);
3720 mutex_unlock(&cgroup_tree_mutex);
3725 cgroup_destroy_locked(cgrp);
3726 mutex_unlock(&cgroup_mutex);
3727 mutex_unlock(&cgroup_tree_mutex);
3731 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
3734 struct cgroup *parent = parent_kn->priv;
3736 return cgroup_create(parent, name, mode);
3740 * This is called when the refcnt of a css is confirmed to be killed.
3741 * css_tryget() is now guaranteed to fail.
3743 static void css_killed_work_fn(struct work_struct *work)
3745 struct cgroup_subsys_state *css =
3746 container_of(work, struct cgroup_subsys_state, destroy_work);
3747 struct cgroup *cgrp = css->cgroup;
3749 mutex_lock(&cgroup_tree_mutex);
3750 mutex_lock(&cgroup_mutex);
3753 * css_tryget() is guaranteed to fail now. Tell subsystems to
3754 * initate destruction.
3759 * If @cgrp is marked dead, it's waiting for refs of all css's to
3760 * be disabled before proceeding to the second phase of cgroup
3761 * destruction. If we are the last one, kick it off.
3763 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
3764 cgroup_destroy_css_killed(cgrp);
3766 mutex_unlock(&cgroup_mutex);
3767 mutex_unlock(&cgroup_tree_mutex);
3770 * Put the css refs from kill_css(). Each css holds an extra
3771 * reference to the cgroup's dentry and cgroup removal proceeds
3772 * regardless of css refs. On the last put of each css, whenever
3773 * that may be, the extra dentry ref is put so that dentry
3774 * destruction happens only after all css's are released.
3779 /* css kill confirmation processing requires process context, bounce */
3780 static void css_killed_ref_fn(struct percpu_ref *ref)
3782 struct cgroup_subsys_state *css =
3783 container_of(ref, struct cgroup_subsys_state, refcnt);
3785 INIT_WORK(&css->destroy_work, css_killed_work_fn);
3786 queue_work(cgroup_destroy_wq, &css->destroy_work);
3790 * kill_css - destroy a css
3791 * @css: css to destroy
3793 * This function initiates destruction of @css by removing cgroup interface
3794 * files and putting its base reference. ->css_offline() will be invoked
3795 * asynchronously once css_tryget() is guaranteed to fail and when the
3796 * reference count reaches zero, @css will be released.
3798 static void kill_css(struct cgroup_subsys_state *css)
3801 * This must happen before css is disassociated with its cgroup.
3802 * See seq_css() for details.
3804 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
3807 * Killing would put the base ref, but we need to keep it alive
3808 * until after ->css_offline().
3813 * cgroup core guarantees that, by the time ->css_offline() is
3814 * invoked, no new css reference will be given out via
3815 * css_tryget(). We can't simply call percpu_ref_kill() and
3816 * proceed to offlining css's because percpu_ref_kill() doesn't
3817 * guarantee that the ref is seen as killed on all CPUs on return.
3819 * Use percpu_ref_kill_and_confirm() to get notifications as each
3820 * css is confirmed to be seen as killed on all CPUs.
3822 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
3826 * cgroup_destroy_locked - the first stage of cgroup destruction
3827 * @cgrp: cgroup to be destroyed
3829 * css's make use of percpu refcnts whose killing latency shouldn't be
3830 * exposed to userland and are RCU protected. Also, cgroup core needs to
3831 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
3832 * invoked. To satisfy all the requirements, destruction is implemented in
3833 * the following two steps.
3835 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
3836 * userland visible parts and start killing the percpu refcnts of
3837 * css's. Set up so that the next stage will be kicked off once all
3838 * the percpu refcnts are confirmed to be killed.
3840 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
3841 * rest of destruction. Once all cgroup references are gone, the
3842 * cgroup is RCU-freed.
3844 * This function implements s1. After this step, @cgrp is gone as far as
3845 * the userland is concerned and a new cgroup with the same name may be
3846 * created. As cgroup doesn't care about the names internally, this
3847 * doesn't cause any problem.
3849 static int cgroup_destroy_locked(struct cgroup *cgrp)
3850 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
3852 struct cgroup *child;
3853 struct cgroup_subsys_state *css;
3857 lockdep_assert_held(&cgroup_tree_mutex);
3858 lockdep_assert_held(&cgroup_mutex);
3861 * css_set_lock synchronizes access to ->cset_links and prevents
3862 * @cgrp from being removed while __put_css_set() is in progress.
3864 read_lock(&css_set_lock);
3865 empty = list_empty(&cgrp->cset_links);
3866 read_unlock(&css_set_lock);
3871 * Make sure there's no live children. We can't test ->children
3872 * emptiness as dead children linger on it while being destroyed;
3873 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
3877 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
3878 empty = cgroup_is_dead(child);
3887 * Initiate massacre of all css's. cgroup_destroy_css_killed()
3888 * will be invoked to perform the rest of destruction once the
3889 * percpu refs of all css's are confirmed to be killed. This
3890 * involves removing the subsystem's files, drop cgroup_mutex.
3892 mutex_unlock(&cgroup_mutex);
3893 for_each_css(css, ssid, cgrp)
3895 mutex_lock(&cgroup_mutex);
3898 * Mark @cgrp dead. This prevents further task migration and child
3899 * creation by disabling cgroup_lock_live_group(). Note that
3900 * CGRP_DEAD assertion is depended upon by css_next_child() to
3901 * resume iteration after dropping RCU read lock. See
3902 * css_next_child() for details.
3904 set_bit(CGRP_DEAD, &cgrp->flags);
3906 /* CGRP_DEAD is set, remove from ->release_list for the last time */
3907 raw_spin_lock(&release_list_lock);
3908 if (!list_empty(&cgrp->release_list))
3909 list_del_init(&cgrp->release_list);
3910 raw_spin_unlock(&release_list_lock);
3913 * If @cgrp has css's attached, the second stage of cgroup
3914 * destruction is kicked off from css_killed_work_fn() after the
3915 * refs of all attached css's are killed. If @cgrp doesn't have
3916 * any css, we kick it off here.
3919 cgroup_destroy_css_killed(cgrp);
3921 /* remove @cgrp directory along with the base files */
3922 mutex_unlock(&cgroup_mutex);
3925 * There are two control paths which try to determine cgroup from
3926 * dentry without going through kernfs - cgroupstats_build() and
3927 * css_tryget_from_dir(). Those are supported by RCU protecting
3928 * clearing of cgrp->kn->priv backpointer, which should happen
3929 * after all files under it have been removed.
3931 kernfs_remove(cgrp->kn); /* @cgrp has an extra ref on its kn */
3932 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
3934 mutex_lock(&cgroup_mutex);
3940 * cgroup_destroy_css_killed - the second step of cgroup destruction
3941 * @work: cgroup->destroy_free_work
3943 * This function is invoked from a work item for a cgroup which is being
3944 * destroyed after all css's are offlined and performs the rest of
3945 * destruction. This is the second step of destruction described in the
3946 * comment above cgroup_destroy_locked().
3948 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
3950 struct cgroup *parent = cgrp->parent;
3952 lockdep_assert_held(&cgroup_tree_mutex);
3953 lockdep_assert_held(&cgroup_mutex);
3955 /* delete this cgroup from parent->children */
3956 list_del_rcu(&cgrp->sibling);
3960 set_bit(CGRP_RELEASABLE, &parent->flags);
3961 check_for_release(parent);
3964 static int cgroup_rmdir(struct kernfs_node *kn)
3966 struct cgroup *cgrp = kn->priv;
3970 * This is self-destruction but @kn can't be removed while this
3971 * callback is in progress. Let's break active protection. Once
3972 * the protection is broken, @cgrp can be destroyed at any point.
3973 * Pin it so that it stays accessible.
3976 kernfs_break_active_protection(kn);
3978 mutex_lock(&cgroup_tree_mutex);
3979 mutex_lock(&cgroup_mutex);
3982 * @cgrp might already have been destroyed while we're trying to
3985 if (!cgroup_is_dead(cgrp))
3986 ret = cgroup_destroy_locked(cgrp);
3988 mutex_unlock(&cgroup_mutex);
3989 mutex_unlock(&cgroup_tree_mutex);
3991 kernfs_unbreak_active_protection(kn);
3996 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
3997 .remount_fs = cgroup_remount,
3998 .show_options = cgroup_show_options,
3999 .mkdir = cgroup_mkdir,
4000 .rmdir = cgroup_rmdir,
4001 .rename = cgroup_rename,
4004 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4006 struct cgroup_subsys_state *css;
4008 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4010 mutex_lock(&cgroup_tree_mutex);
4011 mutex_lock(&cgroup_mutex);
4013 INIT_LIST_HEAD(&ss->cfts);
4015 /* Create the top cgroup state for this subsystem */
4016 ss->root = &cgroup_dummy_root;
4017 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4018 /* We don't handle early failures gracefully */
4019 BUG_ON(IS_ERR(css));
4020 init_css(css, ss, cgroup_dummy_top);
4022 /* Update the init_css_set to contain a subsys
4023 * pointer to this state - since the subsystem is
4024 * newly registered, all tasks and hence the
4025 * init_css_set is in the subsystem's top cgroup. */
4026 init_css_set.subsys[ss->id] = css;
4028 need_forkexit_callback |= ss->fork || ss->exit;
4030 /* At system boot, before all subsystems have been
4031 * registered, no tasks have been forked, so we don't
4032 * need to invoke fork callbacks here. */
4033 BUG_ON(!list_empty(&init_task.tasks));
4035 BUG_ON(online_css(css));
4037 mutex_unlock(&cgroup_mutex);
4038 mutex_unlock(&cgroup_tree_mutex);
4042 * cgroup_init_early - cgroup initialization at system boot
4044 * Initialize cgroups at system boot, and initialize any
4045 * subsystems that request early init.
4047 int __init cgroup_init_early(void)
4049 struct cgroup_subsys *ss;
4052 atomic_set(&init_css_set.refcount, 1);
4053 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4054 INIT_LIST_HEAD(&init_css_set.tasks);
4055 INIT_HLIST_NODE(&init_css_set.hlist);
4057 init_cgroup_root(&cgroup_dummy_root);
4058 cgroup_root_count = 1;
4059 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4061 init_cgrp_cset_link.cset = &init_css_set;
4062 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4063 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4064 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4066 for_each_subsys(ss, i) {
4067 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4068 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4069 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4071 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4072 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4075 ss->name = cgroup_subsys_name[i];
4078 cgroup_init_subsys(ss);
4084 * cgroup_init - cgroup initialization
4086 * Register cgroup filesystem and /proc file, and initialize
4087 * any subsystems that didn't request early init.
4089 int __init cgroup_init(void)
4091 struct cgroup_subsys *ss;
4095 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4097 for_each_subsys(ss, i) {
4098 if (!ss->early_init)
4099 cgroup_init_subsys(ss);
4102 * cftype registration needs kmalloc and can't be done
4103 * during early_init. Register base cftypes separately.
4105 if (ss->base_cftypes)
4106 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4109 /* allocate id for the dummy hierarchy */
4110 mutex_lock(&cgroup_mutex);
4112 /* Add init_css_set to the hash table */
4113 key = css_set_hash(init_css_set.subsys);
4114 hash_add(css_set_table, &init_css_set.hlist, key);
4116 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4118 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4122 mutex_unlock(&cgroup_mutex);
4124 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4128 err = register_filesystem(&cgroup_fs_type);
4130 kobject_put(cgroup_kobj);
4134 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4138 static int __init cgroup_wq_init(void)
4141 * There isn't much point in executing destruction path in
4142 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4144 * XXX: Must be ordered to make sure parent is offlined after
4145 * children. The ordering requirement is for memcg where a
4146 * parent's offline may wait for a child's leading to deadlock. In
4147 * the long term, this should be fixed from memcg side.
4149 * We would prefer to do this in cgroup_init() above, but that
4150 * is called before init_workqueues(): so leave this until after.
4152 cgroup_destroy_wq = alloc_ordered_workqueue("cgroup_destroy", 0);
4153 BUG_ON(!cgroup_destroy_wq);
4156 * Used to destroy pidlists and separate to serve as flush domain.
4157 * Cap @max_active to 1 too.
4159 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4161 BUG_ON(!cgroup_pidlist_destroy_wq);
4165 core_initcall(cgroup_wq_init);
4168 * proc_cgroup_show()
4169 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4170 * - Used for /proc/<pid>/cgroup.
4171 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4172 * doesn't really matter if tsk->cgroup changes after we read it,
4173 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4174 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4175 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4176 * cgroup to top_cgroup.
4179 /* TODO: Use a proper seq_file iterator */
4180 int proc_cgroup_show(struct seq_file *m, void *v)
4183 struct task_struct *tsk;
4186 struct cgroupfs_root *root;
4189 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4195 tsk = get_pid_task(pid, PIDTYPE_PID);
4201 mutex_lock(&cgroup_mutex);
4203 for_each_active_root(root) {
4204 struct cgroup_subsys *ss;
4205 struct cgroup *cgrp;
4206 int ssid, count = 0;
4208 seq_printf(m, "%d:", root->hierarchy_id);
4209 for_each_subsys(ss, ssid)
4210 if (root->subsys_mask & (1 << ssid))
4211 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4212 if (strlen(root->name))
4213 seq_printf(m, "%sname=%s", count ? "," : "",
4216 cgrp = task_cgroup_from_root(tsk, root);
4217 path = cgroup_path(cgrp, buf, PATH_MAX);
4219 retval = -ENAMETOOLONG;
4227 mutex_unlock(&cgroup_mutex);
4228 put_task_struct(tsk);
4235 /* Display information about each subsystem and each hierarchy */
4236 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4238 struct cgroup_subsys *ss;
4241 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4243 * ideally we don't want subsystems moving around while we do this.
4244 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4245 * subsys/hierarchy state.
4247 mutex_lock(&cgroup_mutex);
4249 for_each_subsys(ss, i)
4250 seq_printf(m, "%s\t%d\t%d\t%d\n",
4251 ss->name, ss->root->hierarchy_id,
4252 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4254 mutex_unlock(&cgroup_mutex);
4258 static int cgroupstats_open(struct inode *inode, struct file *file)
4260 return single_open(file, proc_cgroupstats_show, NULL);
4263 static const struct file_operations proc_cgroupstats_operations = {
4264 .open = cgroupstats_open,
4266 .llseek = seq_lseek,
4267 .release = single_release,
4271 * cgroup_fork - attach newly forked task to its parents cgroup.
4272 * @child: pointer to task_struct of forking parent process.
4274 * Description: A task inherits its parent's cgroup at fork().
4276 * A pointer to the shared css_set was automatically copied in
4277 * fork.c by dup_task_struct(). However, we ignore that copy, since
4278 * it was not made under the protection of RCU or cgroup_mutex, so
4279 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4280 * have already changed current->cgroups, allowing the previously
4281 * referenced cgroup group to be removed and freed.
4283 * At the point that cgroup_fork() is called, 'current' is the parent
4284 * task, and the passed argument 'child' points to the child task.
4286 void cgroup_fork(struct task_struct *child)
4289 get_css_set(task_css_set(current));
4290 child->cgroups = current->cgroups;
4291 task_unlock(current);
4292 INIT_LIST_HEAD(&child->cg_list);
4296 * cgroup_post_fork - called on a new task after adding it to the task list
4297 * @child: the task in question
4299 * Adds the task to the list running through its css_set if necessary and
4300 * call the subsystem fork() callbacks. Has to be after the task is
4301 * visible on the task list in case we race with the first call to
4302 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4305 void cgroup_post_fork(struct task_struct *child)
4307 struct cgroup_subsys *ss;
4311 * use_task_css_set_links is set to 1 before we walk the tasklist
4312 * under the tasklist_lock and we read it here after we added the child
4313 * to the tasklist under the tasklist_lock as well. If the child wasn't
4314 * yet in the tasklist when we walked through it from
4315 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4316 * should be visible now due to the paired locking and barriers implied
4317 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4318 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4321 if (use_task_css_set_links) {
4322 write_lock(&css_set_lock);
4324 if (list_empty(&child->cg_list))
4325 list_add(&child->cg_list, &task_css_set(child)->tasks);
4327 write_unlock(&css_set_lock);
4331 * Call ss->fork(). This must happen after @child is linked on
4332 * css_set; otherwise, @child might change state between ->fork()
4333 * and addition to css_set.
4335 if (need_forkexit_callback) {
4336 for_each_subsys(ss, i)
4343 * cgroup_exit - detach cgroup from exiting task
4344 * @tsk: pointer to task_struct of exiting process
4345 * @run_callback: run exit callbacks?
4347 * Description: Detach cgroup from @tsk and release it.
4349 * Note that cgroups marked notify_on_release force every task in
4350 * them to take the global cgroup_mutex mutex when exiting.
4351 * This could impact scaling on very large systems. Be reluctant to
4352 * use notify_on_release cgroups where very high task exit scaling
4353 * is required on large systems.
4355 * the_top_cgroup_hack:
4357 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4359 * We call cgroup_exit() while the task is still competent to
4360 * handle notify_on_release(), then leave the task attached to the
4361 * root cgroup in each hierarchy for the remainder of its exit.
4363 * To do this properly, we would increment the reference count on
4364 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4365 * code we would add a second cgroup function call, to drop that
4366 * reference. This would just create an unnecessary hot spot on
4367 * the top_cgroup reference count, to no avail.
4369 * Normally, holding a reference to a cgroup without bumping its
4370 * count is unsafe. The cgroup could go away, or someone could
4371 * attach us to a different cgroup, decrementing the count on
4372 * the first cgroup that we never incremented. But in this case,
4373 * top_cgroup isn't going away, and either task has PF_EXITING set,
4374 * which wards off any cgroup_attach_task() attempts, or task is a failed
4375 * fork, never visible to cgroup_attach_task.
4377 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4379 struct cgroup_subsys *ss;
4380 struct css_set *cset;
4384 * Unlink from the css_set task list if necessary.
4385 * Optimistically check cg_list before taking
4388 if (!list_empty(&tsk->cg_list)) {
4389 write_lock(&css_set_lock);
4390 if (!list_empty(&tsk->cg_list))
4391 list_del_init(&tsk->cg_list);
4392 write_unlock(&css_set_lock);
4395 /* Reassign the task to the init_css_set. */
4397 cset = task_css_set(tsk);
4398 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4400 if (run_callbacks && need_forkexit_callback) {
4401 /* see cgroup_post_fork() for details */
4402 for_each_subsys(ss, i) {
4404 struct cgroup_subsys_state *old_css = cset->subsys[i];
4405 struct cgroup_subsys_state *css = task_css(tsk, i);
4407 ss->exit(css, old_css, tsk);
4413 put_css_set_taskexit(cset);
4416 static void check_for_release(struct cgroup *cgrp)
4418 if (cgroup_is_releasable(cgrp) &&
4419 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
4421 * Control Group is currently removeable. If it's not
4422 * already queued for a userspace notification, queue
4425 int need_schedule_work = 0;
4427 raw_spin_lock(&release_list_lock);
4428 if (!cgroup_is_dead(cgrp) &&
4429 list_empty(&cgrp->release_list)) {
4430 list_add(&cgrp->release_list, &release_list);
4431 need_schedule_work = 1;
4433 raw_spin_unlock(&release_list_lock);
4434 if (need_schedule_work)
4435 schedule_work(&release_agent_work);
4440 * Notify userspace when a cgroup is released, by running the
4441 * configured release agent with the name of the cgroup (path
4442 * relative to the root of cgroup file system) as the argument.
4444 * Most likely, this user command will try to rmdir this cgroup.
4446 * This races with the possibility that some other task will be
4447 * attached to this cgroup before it is removed, or that some other
4448 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4449 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4450 * unused, and this cgroup will be reprieved from its death sentence,
4451 * to continue to serve a useful existence. Next time it's released,
4452 * we will get notified again, if it still has 'notify_on_release' set.
4454 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4455 * means only wait until the task is successfully execve()'d. The
4456 * separate release agent task is forked by call_usermodehelper(),
4457 * then control in this thread returns here, without waiting for the
4458 * release agent task. We don't bother to wait because the caller of
4459 * this routine has no use for the exit status of the release agent
4460 * task, so no sense holding our caller up for that.
4462 static void cgroup_release_agent(struct work_struct *work)
4464 BUG_ON(work != &release_agent_work);
4465 mutex_lock(&cgroup_mutex);
4466 raw_spin_lock(&release_list_lock);
4467 while (!list_empty(&release_list)) {
4468 char *argv[3], *envp[3];
4470 char *pathbuf = NULL, *agentbuf = NULL, *path;
4471 struct cgroup *cgrp = list_entry(release_list.next,
4474 list_del_init(&cgrp->release_list);
4475 raw_spin_unlock(&release_list_lock);
4476 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
4479 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
4482 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4487 argv[i++] = agentbuf;
4492 /* minimal command environment */
4493 envp[i++] = "HOME=/";
4494 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4497 /* Drop the lock while we invoke the usermode helper,
4498 * since the exec could involve hitting disk and hence
4499 * be a slow process */
4500 mutex_unlock(&cgroup_mutex);
4501 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4502 mutex_lock(&cgroup_mutex);
4506 raw_spin_lock(&release_list_lock);
4508 raw_spin_unlock(&release_list_lock);
4509 mutex_unlock(&cgroup_mutex);
4512 static int __init cgroup_disable(char *str)
4514 struct cgroup_subsys *ss;
4518 while ((token = strsep(&str, ",")) != NULL) {
4522 for_each_subsys(ss, i) {
4523 if (!strcmp(token, ss->name)) {
4525 printk(KERN_INFO "Disabling %s control group"
4526 " subsystem\n", ss->name);
4533 __setup("cgroup_disable=", cgroup_disable);
4536 * css_tryget_from_dir - get corresponding css from the dentry of a cgroup dir
4537 * @dentry: directory dentry of interest
4538 * @ss: subsystem of interest
4540 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
4541 * to get the corresponding css and return it. If such css doesn't exist
4542 * or can't be pinned, an ERR_PTR value is returned.
4544 struct cgroup_subsys_state *css_tryget_from_dir(struct dentry *dentry,
4545 struct cgroup_subsys *ss)
4547 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
4548 struct cgroup_subsys_state *css = NULL;
4549 struct cgroup *cgrp;
4551 /* is @dentry a cgroup dir? */
4552 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
4553 kernfs_type(kn) != KERNFS_DIR)
4554 return ERR_PTR(-EBADF);
4559 * This path doesn't originate from kernfs and @kn could already
4560 * have been or be removed at any point. @kn->priv is RCU
4561 * protected for this access. See destroy_locked() for details.
4563 cgrp = rcu_dereference(kn->priv);
4565 css = cgroup_css(cgrp, ss);
4567 if (!css || !css_tryget(css))
4568 css = ERR_PTR(-ENOENT);
4575 * css_from_id - lookup css by id
4576 * @id: the cgroup id
4577 * @ss: cgroup subsys to be looked into
4579 * Returns the css if there's valid one with @id, otherwise returns NULL.
4580 * Should be called under rcu_read_lock().
4582 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
4584 struct cgroup *cgrp;
4586 cgroup_assert_mutexes_or_rcu_locked();
4588 cgrp = idr_find(&ss->root->cgroup_idr, id);
4590 return cgroup_css(cgrp, ss);
4594 #ifdef CONFIG_CGROUP_DEBUG
4595 static struct cgroup_subsys_state *
4596 debug_css_alloc(struct cgroup_subsys_state *parent_css)
4598 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4601 return ERR_PTR(-ENOMEM);
4606 static void debug_css_free(struct cgroup_subsys_state *css)
4611 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
4614 return cgroup_task_count(css->cgroup);
4617 static u64 current_css_set_read(struct cgroup_subsys_state *css,
4620 return (u64)(unsigned long)current->cgroups;
4623 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
4629 count = atomic_read(&task_css_set(current)->refcount);
4634 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
4636 struct cgrp_cset_link *link;
4637 struct css_set *cset;
4640 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
4644 read_lock(&css_set_lock);
4646 cset = rcu_dereference(current->cgroups);
4647 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
4648 struct cgroup *c = link->cgrp;
4649 const char *name = "?";
4651 if (c != cgroup_dummy_top) {
4652 cgroup_name(c, name_buf, NAME_MAX + 1);
4656 seq_printf(seq, "Root %d group %s\n",
4657 c->root->hierarchy_id, name);
4660 read_unlock(&css_set_lock);
4665 #define MAX_TASKS_SHOWN_PER_CSS 25
4666 static int cgroup_css_links_read(struct seq_file *seq, void *v)
4668 struct cgroup_subsys_state *css = seq_css(seq);
4669 struct cgrp_cset_link *link;
4671 read_lock(&css_set_lock);
4672 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
4673 struct css_set *cset = link->cset;
4674 struct task_struct *task;
4676 seq_printf(seq, "css_set %p\n", cset);
4677 list_for_each_entry(task, &cset->tasks, cg_list) {
4678 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
4679 seq_puts(seq, " ...\n");
4682 seq_printf(seq, " task %d\n",
4683 task_pid_vnr(task));
4687 read_unlock(&css_set_lock);
4691 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
4693 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
4696 static struct cftype debug_files[] = {
4698 .name = "taskcount",
4699 .read_u64 = debug_taskcount_read,
4703 .name = "current_css_set",
4704 .read_u64 = current_css_set_read,
4708 .name = "current_css_set_refcount",
4709 .read_u64 = current_css_set_refcount_read,
4713 .name = "current_css_set_cg_links",
4714 .seq_show = current_css_set_cg_links_read,
4718 .name = "cgroup_css_links",
4719 .seq_show = cgroup_css_links_read,
4723 .name = "releasable",
4724 .read_u64 = releasable_read,
4730 struct cgroup_subsys debug_cgrp_subsys = {
4731 .css_alloc = debug_css_alloc,
4732 .css_free = debug_css_free,
4733 .base_cftypes = debug_files,
4735 #endif /* CONFIG_CGROUP_DEBUG */