2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/slab.h>
44 #include <linux/spinlock.h>
45 #include <linux/rwsem.h>
46 #include <linux/string.h>
47 #include <linux/sort.h>
48 #include <linux/kmod.h>
49 #include <linux/delayacct.h>
50 #include <linux/cgroupstats.h>
51 #include <linux/hashtable.h>
52 #include <linux/pid_namespace.h>
53 #include <linux/idr.h>
54 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
55 #include <linux/kthread.h>
56 #include <linux/delay.h>
58 #include <linux/atomic.h>
61 * pidlists linger the following amount before being destroyed. The goal
62 * is avoiding frequent destruction in the middle of consecutive read calls
63 * Expiring in the middle is a performance problem not a correctness one.
64 * 1 sec should be enough.
66 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
68 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
72 * cgroup_tree_mutex nests above cgroup_mutex and protects cftypes, file
73 * creation/removal and hierarchy changing operations including cgroup
74 * creation, removal, css association and controller rebinding. This outer
75 * lock is needed mainly to resolve the circular dependency between kernfs
76 * active ref and cgroup_mutex. cgroup_tree_mutex nests above both.
78 static DEFINE_MUTEX(cgroup_tree_mutex);
81 * cgroup_mutex is the master lock. Any modification to cgroup or its
82 * hierarchy must be performed while holding it.
84 * css_set_rwsem protects task->cgroups pointer, the list of css_set
85 * objects, and the chain of tasks off each css_set.
87 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
88 * cgroup.h can use them for lockdep annotations.
90 #ifdef CONFIG_PROVE_RCU
91 DEFINE_MUTEX(cgroup_mutex);
92 DECLARE_RWSEM(css_set_rwsem);
93 EXPORT_SYMBOL_GPL(cgroup_mutex);
94 EXPORT_SYMBOL_GPL(css_set_rwsem);
96 static DEFINE_MUTEX(cgroup_mutex);
97 static DECLARE_RWSEM(css_set_rwsem);
101 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
102 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
104 static DEFINE_SPINLOCK(release_agent_path_lock);
106 #define cgroup_assert_mutexes_or_rcu_locked() \
107 rcu_lockdep_assert(rcu_read_lock_held() || \
108 lockdep_is_held(&cgroup_tree_mutex) || \
109 lockdep_is_held(&cgroup_mutex), \
110 "cgroup_[tree_]mutex or RCU read lock required");
113 * cgroup destruction makes heavy use of work items and there can be a lot
114 * of concurrent destructions. Use a separate workqueue so that cgroup
115 * destruction work items don't end up filling up max_active of system_wq
116 * which may lead to deadlock.
118 static struct workqueue_struct *cgroup_destroy_wq;
121 * pidlist destructions need to be flushed on cgroup destruction. Use a
122 * separate workqueue as flush domain.
124 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
126 /* generate an array of cgroup subsystem pointers */
127 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
128 static struct cgroup_subsys *cgroup_subsys[] = {
129 #include <linux/cgroup_subsys.h>
133 /* array of cgroup subsystem names */
134 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
135 static const char *cgroup_subsys_name[] = {
136 #include <linux/cgroup_subsys.h>
141 * The dummy hierarchy, reserved for the subsystems that are otherwise
142 * unattached - it never has more than a single cgroup, and all tasks are
143 * part of that cgroup.
145 static struct cgroupfs_root cgroup_dummy_root;
147 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
148 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
150 /* The list of hierarchy roots */
152 static LIST_HEAD(cgroup_roots);
153 static int cgroup_root_count;
155 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
156 static DEFINE_IDR(cgroup_hierarchy_idr);
159 * Assign a monotonically increasing serial number to cgroups. It
160 * guarantees cgroups with bigger numbers are newer than those with smaller
161 * numbers. Also, as cgroups are always appended to the parent's
162 * ->children list, it guarantees that sibling cgroups are always sorted in
163 * the ascending serial number order on the list. Protected by
166 static u64 cgroup_serial_nr_next = 1;
168 /* This flag indicates whether tasks in the fork and exit paths should
169 * check for fork/exit handlers to call. This avoids us having to do
170 * extra work in the fork/exit path if none of the subsystems need to
173 static int need_forkexit_callback __read_mostly;
175 static struct cftype cgroup_base_files[];
177 static void cgroup_put(struct cgroup *cgrp);
178 static int rebind_subsystems(struct cgroupfs_root *dst_root,
179 unsigned long ss_mask);
180 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
181 static int cgroup_destroy_locked(struct cgroup *cgrp);
182 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
184 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
187 * cgroup_css - obtain a cgroup's css for the specified subsystem
188 * @cgrp: the cgroup of interest
189 * @ss: the subsystem of interest (%NULL returns the dummy_css)
191 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
192 * function must be called either under cgroup_mutex or rcu_read_lock() and
193 * the caller is responsible for pinning the returned css if it wants to
194 * keep accessing it outside the said locks. This function may return
195 * %NULL if @cgrp doesn't have @subsys_id enabled.
197 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
198 struct cgroup_subsys *ss)
201 return rcu_dereference_check(cgrp->subsys[ss->id],
202 lockdep_is_held(&cgroup_tree_mutex) ||
203 lockdep_is_held(&cgroup_mutex));
205 return &cgrp->dummy_css;
208 /* convenient tests for these bits */
209 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
211 return test_bit(CGRP_DEAD, &cgrp->flags);
214 struct cgroup_subsys_state *seq_css(struct seq_file *seq)
216 struct kernfs_open_file *of = seq->private;
217 struct cgroup *cgrp = of->kn->parent->priv;
218 struct cftype *cft = seq_cft(seq);
221 * This is open and unprotected implementation of cgroup_css().
222 * seq_css() is only called from a kernfs file operation which has
223 * an active reference on the file. Because all the subsystem
224 * files are drained before a css is disassociated with a cgroup,
225 * the matching css from the cgroup's subsys table is guaranteed to
226 * be and stay valid until the enclosing operation is complete.
229 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
231 return &cgrp->dummy_css;
233 EXPORT_SYMBOL_GPL(seq_css);
236 * cgroup_is_descendant - test ancestry
237 * @cgrp: the cgroup to be tested
238 * @ancestor: possible ancestor of @cgrp
240 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
241 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
242 * and @ancestor are accessible.
244 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
247 if (cgrp == ancestor)
254 static int cgroup_is_releasable(const struct cgroup *cgrp)
257 (1 << CGRP_RELEASABLE) |
258 (1 << CGRP_NOTIFY_ON_RELEASE);
259 return (cgrp->flags & bits) == bits;
262 static int notify_on_release(const struct cgroup *cgrp)
264 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
268 * for_each_css - iterate all css's of a cgroup
269 * @css: the iteration cursor
270 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
271 * @cgrp: the target cgroup to iterate css's of
273 * Should be called under cgroup_mutex.
275 #define for_each_css(css, ssid, cgrp) \
276 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
277 if (!((css) = rcu_dereference_check( \
278 (cgrp)->subsys[(ssid)], \
279 lockdep_is_held(&cgroup_tree_mutex) || \
280 lockdep_is_held(&cgroup_mutex)))) { } \
284 * for_each_subsys - iterate all enabled cgroup subsystems
285 * @ss: the iteration cursor
286 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
288 #define for_each_subsys(ss, ssid) \
289 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
290 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
292 /* iterate across the hierarchies */
293 #define for_each_root(root) \
294 list_for_each_entry((root), &cgroup_roots, root_list)
297 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
298 * @cgrp: the cgroup to be checked for liveness
300 * On success, returns true; the mutex should be later unlocked. On
301 * failure returns false with no lock held.
303 static bool cgroup_lock_live_group(struct cgroup *cgrp)
305 mutex_lock(&cgroup_mutex);
306 if (cgroup_is_dead(cgrp)) {
307 mutex_unlock(&cgroup_mutex);
313 /* the list of cgroups eligible for automatic release. Protected by
314 * release_list_lock */
315 static LIST_HEAD(release_list);
316 static DEFINE_RAW_SPINLOCK(release_list_lock);
317 static void cgroup_release_agent(struct work_struct *work);
318 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
319 static void check_for_release(struct cgroup *cgrp);
322 * A cgroup can be associated with multiple css_sets as different tasks may
323 * belong to different cgroups on different hierarchies. In the other
324 * direction, a css_set is naturally associated with multiple cgroups.
325 * This M:N relationship is represented by the following link structure
326 * which exists for each association and allows traversing the associations
329 struct cgrp_cset_link {
330 /* the cgroup and css_set this link associates */
332 struct css_set *cset;
334 /* list of cgrp_cset_links anchored at cgrp->cset_links */
335 struct list_head cset_link;
337 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
338 struct list_head cgrp_link;
342 * The default css_set - used by init and its children prior to any
343 * hierarchies being mounted. It contains a pointer to the root state
344 * for each subsystem. Also used to anchor the list of css_sets. Not
345 * reference-counted, to improve performance when child cgroups
346 * haven't been created.
348 static struct css_set init_css_set = {
349 .refcount = ATOMIC_INIT(1),
350 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
351 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
352 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
353 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
354 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
357 static int css_set_count = 1; /* 1 for init_css_set */
360 * hash table for cgroup groups. This improves the performance to find
361 * an existing css_set. This hash doesn't (currently) take into
362 * account cgroups in empty hierarchies.
364 #define CSS_SET_HASH_BITS 7
365 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
367 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
369 unsigned long key = 0UL;
370 struct cgroup_subsys *ss;
373 for_each_subsys(ss, i)
374 key += (unsigned long)css[i];
375 key = (key >> 16) ^ key;
380 static void put_css_set_locked(struct css_set *cset, bool taskexit)
382 struct cgrp_cset_link *link, *tmp_link;
384 lockdep_assert_held(&css_set_rwsem);
386 if (!atomic_dec_and_test(&cset->refcount))
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_rwsem */
400 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
402 set_bit(CGRP_RELEASABLE, &cgrp->flags);
403 check_for_release(cgrp);
409 kfree_rcu(cset, rcu_head);
412 static void put_css_set(struct css_set *cset, bool taskexit)
415 * Ensure that the refcount doesn't hit zero while any readers
416 * can see it. Similar to atomic_dec_and_lock(), but for an
419 if (atomic_add_unless(&cset->refcount, -1, 1))
422 down_write(&css_set_rwsem);
423 put_css_set_locked(cset, taskexit);
424 up_write(&css_set_rwsem);
428 * refcounted get/put for css_set objects
430 static inline void get_css_set(struct css_set *cset)
432 atomic_inc(&cset->refcount);
436 * compare_css_sets - helper function for find_existing_css_set().
437 * @cset: candidate css_set being tested
438 * @old_cset: existing css_set for a task
439 * @new_cgrp: cgroup that's being entered by the task
440 * @template: desired set of css pointers in css_set (pre-calculated)
442 * Returns true if "cset" matches "old_cset" except for the hierarchy
443 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
445 static bool compare_css_sets(struct css_set *cset,
446 struct css_set *old_cset,
447 struct cgroup *new_cgrp,
448 struct cgroup_subsys_state *template[])
450 struct list_head *l1, *l2;
452 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
453 /* Not all subsystems matched */
458 * Compare cgroup pointers in order to distinguish between
459 * different cgroups in heirarchies with no subsystems. We
460 * could get by with just this check alone (and skip the
461 * memcmp above) but on most setups the memcmp check will
462 * avoid the need for this more expensive check on almost all
466 l1 = &cset->cgrp_links;
467 l2 = &old_cset->cgrp_links;
469 struct cgrp_cset_link *link1, *link2;
470 struct cgroup *cgrp1, *cgrp2;
474 /* See if we reached the end - both lists are equal length. */
475 if (l1 == &cset->cgrp_links) {
476 BUG_ON(l2 != &old_cset->cgrp_links);
479 BUG_ON(l2 == &old_cset->cgrp_links);
481 /* Locate the cgroups associated with these links. */
482 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
483 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
486 /* Hierarchies should be linked in the same order. */
487 BUG_ON(cgrp1->root != cgrp2->root);
490 * If this hierarchy is the hierarchy of the cgroup
491 * that's changing, then we need to check that this
492 * css_set points to the new cgroup; if it's any other
493 * hierarchy, then this css_set should point to the
494 * same cgroup as the old css_set.
496 if (cgrp1->root == new_cgrp->root) {
497 if (cgrp1 != new_cgrp)
508 * find_existing_css_set - init css array and find the matching css_set
509 * @old_cset: the css_set that we're using before the cgroup transition
510 * @cgrp: the cgroup that we're moving into
511 * @template: out param for the new set of csses, should be clear on entry
513 static struct css_set *find_existing_css_set(struct css_set *old_cset,
515 struct cgroup_subsys_state *template[])
517 struct cgroupfs_root *root = cgrp->root;
518 struct cgroup_subsys *ss;
519 struct css_set *cset;
524 * Build the set of subsystem state objects that we want to see in the
525 * new css_set. while subsystems can change globally, the entries here
526 * won't change, so no need for locking.
528 for_each_subsys(ss, i) {
529 if (root->top_cgroup.subsys_mask & (1UL << i)) {
530 /* Subsystem is in this hierarchy. So we want
531 * the subsystem state from the new
533 template[i] = cgroup_css(cgrp, ss);
535 /* Subsystem is not in this hierarchy, so we
536 * don't want to change the subsystem state */
537 template[i] = old_cset->subsys[i];
541 key = css_set_hash(template);
542 hash_for_each_possible(css_set_table, cset, hlist, key) {
543 if (!compare_css_sets(cset, old_cset, cgrp, template))
546 /* This css_set matches what we need */
550 /* No existing cgroup group matched */
554 static void free_cgrp_cset_links(struct list_head *links_to_free)
556 struct cgrp_cset_link *link, *tmp_link;
558 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
559 list_del(&link->cset_link);
565 * allocate_cgrp_cset_links - allocate cgrp_cset_links
566 * @count: the number of links to allocate
567 * @tmp_links: list_head the allocated links are put on
569 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
570 * through ->cset_link. Returns 0 on success or -errno.
572 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
574 struct cgrp_cset_link *link;
577 INIT_LIST_HEAD(tmp_links);
579 for (i = 0; i < count; i++) {
580 link = kzalloc(sizeof(*link), GFP_KERNEL);
582 free_cgrp_cset_links(tmp_links);
585 list_add(&link->cset_link, tmp_links);
591 * link_css_set - a helper function to link a css_set to a cgroup
592 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
593 * @cset: the css_set to be linked
594 * @cgrp: the destination cgroup
596 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
599 struct cgrp_cset_link *link;
601 BUG_ON(list_empty(tmp_links));
602 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
605 list_move(&link->cset_link, &cgrp->cset_links);
607 * Always add links to the tail of the list so that the list
608 * is sorted by order of hierarchy creation
610 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
614 * find_css_set - return a new css_set with one cgroup updated
615 * @old_cset: the baseline css_set
616 * @cgrp: the cgroup to be updated
618 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
619 * substituted into the appropriate hierarchy.
621 static struct css_set *find_css_set(struct css_set *old_cset,
624 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
625 struct css_set *cset;
626 struct list_head tmp_links;
627 struct cgrp_cset_link *link;
630 lockdep_assert_held(&cgroup_mutex);
632 /* First see if we already have a cgroup group that matches
634 down_read(&css_set_rwsem);
635 cset = find_existing_css_set(old_cset, cgrp, template);
638 up_read(&css_set_rwsem);
643 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
647 /* Allocate all the cgrp_cset_link objects that we'll need */
648 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
653 atomic_set(&cset->refcount, 1);
654 INIT_LIST_HEAD(&cset->cgrp_links);
655 INIT_LIST_HEAD(&cset->tasks);
656 INIT_LIST_HEAD(&cset->mg_tasks);
657 INIT_LIST_HEAD(&cset->mg_preload_node);
658 INIT_LIST_HEAD(&cset->mg_node);
659 INIT_HLIST_NODE(&cset->hlist);
661 /* Copy the set of subsystem state objects generated in
662 * find_existing_css_set() */
663 memcpy(cset->subsys, template, sizeof(cset->subsys));
665 down_write(&css_set_rwsem);
666 /* Add reference counts and links from the new css_set. */
667 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
668 struct cgroup *c = link->cgrp;
670 if (c->root == cgrp->root)
672 link_css_set(&tmp_links, cset, c);
675 BUG_ON(!list_empty(&tmp_links));
679 /* Add this cgroup group to the hash table */
680 key = css_set_hash(cset->subsys);
681 hash_add(css_set_table, &cset->hlist, key);
683 up_write(&css_set_rwsem);
688 static struct cgroupfs_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
690 struct cgroup *top_cgrp = kf_root->kn->priv;
692 return top_cgrp->root;
695 static int cgroup_init_root_id(struct cgroupfs_root *root)
699 lockdep_assert_held(&cgroup_mutex);
701 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
705 root->hierarchy_id = id;
709 static void cgroup_exit_root_id(struct cgroupfs_root *root)
711 lockdep_assert_held(&cgroup_mutex);
713 if (root->hierarchy_id) {
714 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
715 root->hierarchy_id = 0;
719 static void cgroup_free_root(struct cgroupfs_root *root)
722 /* hierarhcy ID shoulid already have been released */
723 WARN_ON_ONCE(root->hierarchy_id);
725 idr_destroy(&root->cgroup_idr);
730 static void cgroup_destroy_root(struct cgroupfs_root *root)
732 struct cgroup *cgrp = &root->top_cgroup;
733 struct cgrp_cset_link *link, *tmp_link;
735 mutex_lock(&cgroup_tree_mutex);
736 mutex_lock(&cgroup_mutex);
738 BUG_ON(atomic_read(&root->nr_cgrps));
739 BUG_ON(!list_empty(&cgrp->children));
741 /* Rebind all subsystems back to the default hierarchy */
742 rebind_subsystems(&cgroup_dummy_root, cgrp->subsys_mask);
745 * Release all the links from cset_links to this hierarchy's
748 down_write(&css_set_rwsem);
750 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
751 list_del(&link->cset_link);
752 list_del(&link->cgrp_link);
755 up_write(&css_set_rwsem);
757 if (!list_empty(&root->root_list)) {
758 list_del(&root->root_list);
762 cgroup_exit_root_id(root);
764 mutex_unlock(&cgroup_mutex);
765 mutex_unlock(&cgroup_tree_mutex);
767 kernfs_destroy_root(root->kf_root);
768 cgroup_free_root(root);
771 /* look up cgroup associated with given css_set on the specified hierarchy */
772 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
773 struct cgroupfs_root *root)
775 struct cgroup *res = NULL;
777 lockdep_assert_held(&cgroup_mutex);
778 lockdep_assert_held(&css_set_rwsem);
780 if (cset == &init_css_set) {
781 res = &root->top_cgroup;
783 struct cgrp_cset_link *link;
785 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
786 struct cgroup *c = link->cgrp;
788 if (c->root == root) {
800 * Return the cgroup for "task" from the given hierarchy. Must be
801 * called with cgroup_mutex and css_set_rwsem held.
803 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
804 struct cgroupfs_root *root)
807 * No need to lock the task - since we hold cgroup_mutex the
808 * task can't change groups, so the only thing that can happen
809 * is that it exits and its css is set back to init_css_set.
811 return cset_cgroup_from_root(task_css_set(task), root);
815 * A task must hold cgroup_mutex to modify cgroups.
817 * Any task can increment and decrement the count field without lock.
818 * So in general, code holding cgroup_mutex can't rely on the count
819 * field not changing. However, if the count goes to zero, then only
820 * cgroup_attach_task() can increment it again. Because a count of zero
821 * means that no tasks are currently attached, therefore there is no
822 * way a task attached to that cgroup can fork (the other way to
823 * increment the count). So code holding cgroup_mutex can safely
824 * assume that if the count is zero, it will stay zero. Similarly, if
825 * a task holds cgroup_mutex on a cgroup with zero count, it
826 * knows that the cgroup won't be removed, as cgroup_rmdir()
829 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
830 * (usually) take cgroup_mutex. These are the two most performance
831 * critical pieces of code here. The exception occurs on cgroup_exit(),
832 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
833 * is taken, and if the cgroup count is zero, a usermode call made
834 * to the release agent with the name of the cgroup (path relative to
835 * the root of cgroup file system) as the argument.
837 * A cgroup can only be deleted if both its 'count' of using tasks
838 * is zero, and its list of 'children' cgroups is empty. Since all
839 * tasks in the system use _some_ cgroup, and since there is always at
840 * least one task in the system (init, pid == 1), therefore, top_cgroup
841 * always has either children cgroups and/or using tasks. So we don't
842 * need a special hack to ensure that top_cgroup cannot be deleted.
844 * P.S. One more locking exception. RCU is used to guard the
845 * update of a tasks cgroup pointer by cgroup_attach_task()
848 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
849 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
850 static const struct file_operations proc_cgroupstats_operations;
852 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
855 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
856 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
857 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
858 cft->ss->name, cft->name);
860 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
865 * cgroup_file_mode - deduce file mode of a control file
866 * @cft: the control file in question
868 * returns cft->mode if ->mode is not 0
869 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
870 * returns S_IRUGO if it has only a read handler
871 * returns S_IWUSR if it has only a write hander
873 static umode_t cgroup_file_mode(const struct cftype *cft)
880 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
883 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
890 static void cgroup_free_fn(struct work_struct *work)
892 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
894 atomic_dec(&cgrp->root->nr_cgrps);
895 cgroup_pidlist_destroy_all(cgrp);
899 * We get a ref to the parent, and put the ref when this
900 * cgroup is being freed, so it's guaranteed that the
901 * parent won't be destroyed before its children.
903 cgroup_put(cgrp->parent);
904 kernfs_put(cgrp->kn);
908 * This is top cgroup's refcnt reaching zero, which
909 * indicates that the root should be released.
911 cgroup_destroy_root(cgrp->root);
915 static void cgroup_free_rcu(struct rcu_head *head)
917 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
919 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
920 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
923 static void cgroup_get(struct cgroup *cgrp)
925 WARN_ON_ONCE(cgroup_is_dead(cgrp));
926 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
927 atomic_inc(&cgrp->refcnt);
930 static void cgroup_put(struct cgroup *cgrp)
932 if (!atomic_dec_and_test(&cgrp->refcnt))
934 if (WARN_ON_ONCE(cgrp->parent && !cgroup_is_dead(cgrp)))
938 * XXX: cgrp->id is only used to look up css's. As cgroup and
939 * css's lifetimes will be decoupled, it should be made
940 * per-subsystem and moved to css->id so that lookups are
941 * successful until the target css is released.
943 mutex_lock(&cgroup_mutex);
944 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
945 mutex_unlock(&cgroup_mutex);
948 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
951 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
953 char name[CGROUP_FILE_NAME_MAX];
955 lockdep_assert_held(&cgroup_tree_mutex);
956 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
960 * cgroup_clear_dir - remove subsys files in a cgroup directory
961 * @cgrp: target cgroup
962 * @subsys_mask: mask of the subsystem ids whose files should be removed
964 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
966 struct cgroup_subsys *ss;
969 for_each_subsys(ss, i) {
972 if (!test_bit(i, &subsys_mask))
974 list_for_each_entry(cfts, &ss->cfts, node)
975 cgroup_addrm_files(cgrp, cfts, false);
979 static int rebind_subsystems(struct cgroupfs_root *dst_root,
980 unsigned long ss_mask)
982 struct cgroup *dst_top = &dst_root->top_cgroup;
983 struct cgroup_subsys *ss;
986 lockdep_assert_held(&cgroup_tree_mutex);
987 lockdep_assert_held(&cgroup_mutex);
989 for_each_subsys(ss, ssid) {
990 if (!(ss_mask & (1 << ssid)))
993 /* if @ss is on the dummy_root, we can always move it */
994 if (ss->root == &cgroup_dummy_root)
997 /* if @ss has non-root cgroups attached to it, can't move */
998 if (!list_empty(&ss->root->top_cgroup.children))
1001 /* can't move between two non-dummy roots either */
1002 if (dst_root != &cgroup_dummy_root)
1006 if (dst_root != &cgroup_dummy_root) {
1007 ret = cgroup_populate_dir(dst_top, ss_mask);
1013 * Nothing can fail from this point on. Remove files for the
1014 * removed subsystems and rebind each subsystem.
1016 mutex_unlock(&cgroup_mutex);
1017 for_each_subsys(ss, ssid)
1018 if ((ss_mask & (1 << ssid)) && ss->root != &cgroup_dummy_root)
1019 cgroup_clear_dir(&ss->root->top_cgroup, 1 << ssid);
1020 mutex_lock(&cgroup_mutex);
1022 for_each_subsys(ss, ssid) {
1023 struct cgroupfs_root *src_root;
1024 struct cgroup *src_top;
1025 struct cgroup_subsys_state *css;
1027 if (!(ss_mask & (1 << ssid)))
1030 src_root = ss->root;
1031 src_top = &src_root->top_cgroup;
1032 css = cgroup_css(src_top, ss);
1034 WARN_ON(!css || cgroup_css(dst_top, ss));
1036 RCU_INIT_POINTER(src_top->subsys[ssid], NULL);
1037 rcu_assign_pointer(dst_top->subsys[ssid], css);
1038 ss->root = dst_root;
1039 css->cgroup = dst_top;
1041 src_top->subsys_mask &= ~(1 << ssid);
1042 dst_top->subsys_mask |= 1 << ssid;
1048 if (dst_root != &cgroup_dummy_root)
1049 kernfs_activate(dst_top->kn);
1053 static int cgroup_show_options(struct seq_file *seq,
1054 struct kernfs_root *kf_root)
1056 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1057 struct cgroup_subsys *ss;
1060 for_each_subsys(ss, ssid)
1061 if (root->top_cgroup.subsys_mask & (1 << ssid))
1062 seq_printf(seq, ",%s", ss->name);
1063 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1064 seq_puts(seq, ",sane_behavior");
1065 if (root->flags & CGRP_ROOT_NOPREFIX)
1066 seq_puts(seq, ",noprefix");
1067 if (root->flags & CGRP_ROOT_XATTR)
1068 seq_puts(seq, ",xattr");
1070 spin_lock(&release_agent_path_lock);
1071 if (strlen(root->release_agent_path))
1072 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1073 spin_unlock(&release_agent_path_lock);
1075 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1076 seq_puts(seq, ",clone_children");
1077 if (strlen(root->name))
1078 seq_printf(seq, ",name=%s", root->name);
1082 struct cgroup_sb_opts {
1083 unsigned long subsys_mask;
1084 unsigned long flags;
1085 char *release_agent;
1086 bool cpuset_clone_children;
1088 /* User explicitly requested empty subsystem */
1093 * Convert a hierarchy specifier into a bitmask of subsystems and
1094 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1095 * array. This function takes refcounts on subsystems to be used, unless it
1096 * returns error, in which case no refcounts are taken.
1098 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1100 char *token, *o = data;
1101 bool all_ss = false, one_ss = false;
1102 unsigned long mask = (unsigned long)-1;
1103 struct cgroup_subsys *ss;
1106 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1108 #ifdef CONFIG_CPUSETS
1109 mask = ~(1UL << cpuset_cgrp_id);
1112 memset(opts, 0, sizeof(*opts));
1114 while ((token = strsep(&o, ",")) != NULL) {
1117 if (!strcmp(token, "none")) {
1118 /* Explicitly have no subsystems */
1122 if (!strcmp(token, "all")) {
1123 /* Mutually exclusive option 'all' + subsystem name */
1129 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1130 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1133 if (!strcmp(token, "noprefix")) {
1134 opts->flags |= CGRP_ROOT_NOPREFIX;
1137 if (!strcmp(token, "clone_children")) {
1138 opts->cpuset_clone_children = true;
1141 if (!strcmp(token, "xattr")) {
1142 opts->flags |= CGRP_ROOT_XATTR;
1145 if (!strncmp(token, "release_agent=", 14)) {
1146 /* Specifying two release agents is forbidden */
1147 if (opts->release_agent)
1149 opts->release_agent =
1150 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1151 if (!opts->release_agent)
1155 if (!strncmp(token, "name=", 5)) {
1156 const char *name = token + 5;
1157 /* Can't specify an empty name */
1160 /* Must match [\w.-]+ */
1161 for (i = 0; i < strlen(name); i++) {
1165 if ((c == '.') || (c == '-') || (c == '_'))
1169 /* Specifying two names is forbidden */
1172 opts->name = kstrndup(name,
1173 MAX_CGROUP_ROOT_NAMELEN - 1,
1181 for_each_subsys(ss, i) {
1182 if (strcmp(token, ss->name))
1187 /* Mutually exclusive option 'all' + subsystem name */
1190 set_bit(i, &opts->subsys_mask);
1195 if (i == CGROUP_SUBSYS_COUNT)
1200 * If the 'all' option was specified select all the subsystems,
1201 * otherwise if 'none', 'name=' and a subsystem name options
1202 * were not specified, let's default to 'all'
1204 if (all_ss || (!one_ss && !opts->none && !opts->name))
1205 for_each_subsys(ss, i)
1207 set_bit(i, &opts->subsys_mask);
1209 /* Consistency checks */
1211 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1212 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1214 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1215 opts->cpuset_clone_children || opts->release_agent ||
1217 pr_err("cgroup: sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1223 * Option noprefix was introduced just for backward compatibility
1224 * with the old cpuset, so we allow noprefix only if mounting just
1225 * the cpuset subsystem.
1227 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1231 /* Can't specify "none" and some subsystems */
1232 if (opts->subsys_mask && opts->none)
1236 * We either have to specify by name or by subsystems. (So all
1237 * empty hierarchies must have a name).
1239 if (!opts->subsys_mask && !opts->name)
1245 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1248 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1249 struct cgroup_sb_opts opts;
1250 unsigned long added_mask, removed_mask;
1252 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1253 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1257 mutex_lock(&cgroup_tree_mutex);
1258 mutex_lock(&cgroup_mutex);
1260 /* See what subsystems are wanted */
1261 ret = parse_cgroupfs_options(data, &opts);
1265 if (opts.subsys_mask != root->top_cgroup.subsys_mask || opts.release_agent)
1266 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1267 task_tgid_nr(current), current->comm);
1269 added_mask = opts.subsys_mask & ~root->top_cgroup.subsys_mask;
1270 removed_mask = root->top_cgroup.subsys_mask & ~opts.subsys_mask;
1272 /* Don't allow flags or name to change at remount */
1273 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1274 (opts.name && strcmp(opts.name, root->name))) {
1275 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1276 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1277 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1282 /* remounting is not allowed for populated hierarchies */
1283 if (!list_empty(&root->top_cgroup.children)) {
1288 ret = rebind_subsystems(root, added_mask);
1292 rebind_subsystems(&cgroup_dummy_root, removed_mask);
1294 if (opts.release_agent) {
1295 spin_lock(&release_agent_path_lock);
1296 strcpy(root->release_agent_path, opts.release_agent);
1297 spin_unlock(&release_agent_path_lock);
1300 kfree(opts.release_agent);
1302 mutex_unlock(&cgroup_mutex);
1303 mutex_unlock(&cgroup_tree_mutex);
1308 * To reduce the fork() overhead for systems that are not actually using
1309 * their cgroups capability, we don't maintain the lists running through
1310 * each css_set to its tasks until we see the list actually used - in other
1311 * words after the first mount.
1313 static bool use_task_css_set_links __read_mostly;
1315 static void cgroup_enable_task_cg_lists(void)
1317 struct task_struct *p, *g;
1319 down_write(&css_set_rwsem);
1321 if (use_task_css_set_links)
1324 use_task_css_set_links = true;
1327 * We need tasklist_lock because RCU is not safe against
1328 * while_each_thread(). Besides, a forking task that has passed
1329 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1330 * is not guaranteed to have its child immediately visible in the
1331 * tasklist if we walk through it with RCU.
1333 read_lock(&tasklist_lock);
1334 do_each_thread(g, p) {
1335 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1336 task_css_set(p) != &init_css_set);
1339 * We should check if the process is exiting, otherwise
1340 * it will race with cgroup_exit() in that the list
1341 * entry won't be deleted though the process has exited.
1342 * Do it while holding siglock so that we don't end up
1343 * racing against cgroup_exit().
1345 spin_lock_irq(&p->sighand->siglock);
1346 if (!(p->flags & PF_EXITING)) {
1347 struct css_set *cset = task_css_set(p);
1349 list_add(&p->cg_list, &cset->tasks);
1352 spin_unlock_irq(&p->sighand->siglock);
1353 } while_each_thread(g, p);
1354 read_unlock(&tasklist_lock);
1356 up_write(&css_set_rwsem);
1359 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1361 atomic_set(&cgrp->refcnt, 1);
1362 INIT_LIST_HEAD(&cgrp->sibling);
1363 INIT_LIST_HEAD(&cgrp->children);
1364 INIT_LIST_HEAD(&cgrp->cset_links);
1365 INIT_LIST_HEAD(&cgrp->release_list);
1366 INIT_LIST_HEAD(&cgrp->pidlists);
1367 mutex_init(&cgrp->pidlist_mutex);
1368 cgrp->dummy_css.cgroup = cgrp;
1371 static void init_cgroup_root(struct cgroupfs_root *root,
1372 struct cgroup_sb_opts *opts)
1374 struct cgroup *cgrp = &root->top_cgroup;
1376 INIT_LIST_HEAD(&root->root_list);
1377 atomic_set(&root->nr_cgrps, 1);
1379 init_cgroup_housekeeping(cgrp);
1380 idr_init(&root->cgroup_idr);
1382 root->flags = opts->flags;
1383 if (opts->release_agent)
1384 strcpy(root->release_agent_path, opts->release_agent);
1386 strcpy(root->name, opts->name);
1387 if (opts->cpuset_clone_children)
1388 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1391 static int cgroup_setup_root(struct cgroupfs_root *root, unsigned long ss_mask)
1393 LIST_HEAD(tmp_links);
1394 struct cgroup *root_cgrp = &root->top_cgroup;
1395 struct css_set *cset;
1398 lockdep_assert_held(&cgroup_tree_mutex);
1399 lockdep_assert_held(&cgroup_mutex);
1401 ret = idr_alloc(&root->cgroup_idr, root_cgrp, 0, 1, GFP_KERNEL);
1404 root_cgrp->id = ret;
1407 * We're accessing css_set_count without locking css_set_rwsem here,
1408 * but that's OK - it can only be increased by someone holding
1409 * cgroup_lock, and that's us. The worst that can happen is that we
1410 * have some link structures left over
1412 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1416 ret = cgroup_init_root_id(root);
1420 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1421 KERNFS_ROOT_CREATE_DEACTIVATED,
1423 if (IS_ERR(root->kf_root)) {
1424 ret = PTR_ERR(root->kf_root);
1427 root_cgrp->kn = root->kf_root->kn;
1429 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1433 ret = rebind_subsystems(root, ss_mask);
1438 * There must be no failure case after here, since rebinding takes
1439 * care of subsystems' refcounts, which are explicitly dropped in
1440 * the failure exit path.
1442 list_add(&root->root_list, &cgroup_roots);
1443 cgroup_root_count++;
1446 * Link the top cgroup in this hierarchy into all the css_set
1449 down_write(&css_set_rwsem);
1450 hash_for_each(css_set_table, i, cset, hlist)
1451 link_css_set(&tmp_links, cset, root_cgrp);
1452 up_write(&css_set_rwsem);
1454 BUG_ON(!list_empty(&root_cgrp->children));
1455 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1457 kernfs_activate(root_cgrp->kn);
1462 kernfs_destroy_root(root->kf_root);
1463 root->kf_root = NULL;
1465 cgroup_exit_root_id(root);
1467 free_cgrp_cset_links(&tmp_links);
1471 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1472 int flags, const char *unused_dev_name,
1475 struct cgroupfs_root *root;
1476 struct cgroup_sb_opts opts;
1477 struct dentry *dentry;
1481 * The first time anyone tries to mount a cgroup, enable the list
1482 * linking each css_set to its tasks and fix up all existing tasks.
1484 if (!use_task_css_set_links)
1485 cgroup_enable_task_cg_lists();
1487 mutex_lock(&cgroup_tree_mutex);
1488 mutex_lock(&cgroup_mutex);
1490 /* First find the desired set of subsystems */
1491 ret = parse_cgroupfs_options(data, &opts);
1495 /* look for a matching existing root */
1496 for_each_root(root) {
1497 bool name_match = false;
1499 if (root == &cgroup_dummy_root)
1503 * If we asked for a name then it must match. Also, if
1504 * name matches but sybsys_mask doesn't, we should fail.
1505 * Remember whether name matched.
1508 if (strcmp(opts.name, root->name))
1514 * If we asked for subsystems (or explicitly for no
1515 * subsystems) then they must match.
1517 if ((opts.subsys_mask || opts.none) &&
1518 (opts.subsys_mask != root->top_cgroup.subsys_mask)) {
1525 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1526 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1527 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1531 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1536 * A root's lifetime is governed by its top cgroup. Zero
1537 * ref indicate that the root is being destroyed. Wait for
1538 * destruction to complete so that the subsystems are free.
1539 * We can use wait_queue for the wait but this path is
1540 * super cold. Let's just sleep for a bit and retry.
1542 if (!atomic_inc_not_zero(&root->top_cgroup.refcnt)) {
1543 mutex_unlock(&cgroup_mutex);
1544 mutex_unlock(&cgroup_tree_mutex);
1545 kfree(opts.release_agent);
1556 * No such thing, create a new one. name= matching without subsys
1557 * specification is allowed for already existing hierarchies but we
1558 * can't create new one without subsys specification.
1560 if (!opts.subsys_mask && !opts.none) {
1565 root = kzalloc(sizeof(*root), GFP_KERNEL);
1571 init_cgroup_root(root, &opts);
1573 ret = cgroup_setup_root(root, opts.subsys_mask);
1575 cgroup_free_root(root);
1578 mutex_unlock(&cgroup_mutex);
1579 mutex_unlock(&cgroup_tree_mutex);
1581 kfree(opts.release_agent);
1585 return ERR_PTR(ret);
1587 dentry = kernfs_mount(fs_type, flags, root->kf_root);
1589 cgroup_put(&root->top_cgroup);
1593 static void cgroup_kill_sb(struct super_block *sb)
1595 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1596 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1598 cgroup_put(&root->top_cgroup);
1602 static struct file_system_type cgroup_fs_type = {
1604 .mount = cgroup_mount,
1605 .kill_sb = cgroup_kill_sb,
1608 static struct kobject *cgroup_kobj;
1611 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1612 * @task: target task
1613 * @buf: the buffer to write the path into
1614 * @buflen: the length of the buffer
1616 * Determine @task's cgroup on the first (the one with the lowest non-zero
1617 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1618 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1619 * cgroup controller callbacks.
1621 * Return value is the same as kernfs_path().
1623 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1625 struct cgroupfs_root *root;
1626 struct cgroup *cgrp;
1627 int hierarchy_id = 1;
1630 mutex_lock(&cgroup_mutex);
1631 down_read(&css_set_rwsem);
1633 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1636 cgrp = task_cgroup_from_root(task, root);
1637 path = cgroup_path(cgrp, buf, buflen);
1639 /* if no hierarchy exists, everyone is in "/" */
1640 if (strlcpy(buf, "/", buflen) < buflen)
1644 up_read(&css_set_rwsem);
1645 mutex_unlock(&cgroup_mutex);
1648 EXPORT_SYMBOL_GPL(task_cgroup_path);
1650 /* used to track tasks and other necessary states during migration */
1651 struct cgroup_taskset {
1652 /* the src and dst cset list running through cset->mg_node */
1653 struct list_head src_csets;
1654 struct list_head dst_csets;
1657 * Fields for cgroup_taskset_*() iteration.
1659 * Before migration is committed, the target migration tasks are on
1660 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1661 * the csets on ->dst_csets. ->csets point to either ->src_csets
1662 * or ->dst_csets depending on whether migration is committed.
1664 * ->cur_csets and ->cur_task point to the current task position
1667 struct list_head *csets;
1668 struct css_set *cur_cset;
1669 struct task_struct *cur_task;
1673 * cgroup_taskset_first - reset taskset and return the first task
1674 * @tset: taskset of interest
1676 * @tset iteration is initialized and the first task is returned.
1678 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1680 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1681 tset->cur_task = NULL;
1683 return cgroup_taskset_next(tset);
1687 * cgroup_taskset_next - iterate to the next task in taskset
1688 * @tset: taskset of interest
1690 * Return the next task in @tset. Iteration must have been initialized
1691 * with cgroup_taskset_first().
1693 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1695 struct css_set *cset = tset->cur_cset;
1696 struct task_struct *task = tset->cur_task;
1698 while (&cset->mg_node != tset->csets) {
1700 task = list_first_entry(&cset->mg_tasks,
1701 struct task_struct, cg_list);
1703 task = list_next_entry(task, cg_list);
1705 if (&task->cg_list != &cset->mg_tasks) {
1706 tset->cur_cset = cset;
1707 tset->cur_task = task;
1711 cset = list_next_entry(cset, mg_node);
1719 * cgroup_task_migrate - move a task from one cgroup to another.
1720 * @old_cgrp; the cgroup @tsk is being migrated from
1721 * @tsk: the task being migrated
1722 * @new_cset: the new css_set @tsk is being attached to
1724 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1726 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1727 struct task_struct *tsk,
1728 struct css_set *new_cset)
1730 struct css_set *old_cset;
1732 lockdep_assert_held(&cgroup_mutex);
1733 lockdep_assert_held(&css_set_rwsem);
1736 * We are synchronized through threadgroup_lock() against PF_EXITING
1737 * setting such that we can't race against cgroup_exit() changing the
1738 * css_set to init_css_set and dropping the old one.
1740 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1741 old_cset = task_css_set(tsk);
1743 get_css_set(new_cset);
1744 rcu_assign_pointer(tsk->cgroups, new_cset);
1745 list_move(&tsk->cg_list, &new_cset->mg_tasks);
1748 * We just gained a reference on old_cset by taking it from the
1749 * task. As trading it for new_cset is protected by cgroup_mutex,
1750 * we're safe to drop it here; it will be freed under RCU.
1752 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1753 put_css_set_locked(old_cset, false);
1757 * cgroup_migrate_finish - cleanup after attach
1758 * @preloaded_csets: list of preloaded css_sets
1760 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1761 * those functions for details.
1763 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1765 struct css_set *cset, *tmp_cset;
1767 lockdep_assert_held(&cgroup_mutex);
1769 down_write(&css_set_rwsem);
1770 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1771 cset->mg_src_cgrp = NULL;
1772 cset->mg_dst_cset = NULL;
1773 list_del_init(&cset->mg_preload_node);
1774 put_css_set_locked(cset, false);
1776 up_write(&css_set_rwsem);
1780 * cgroup_migrate_add_src - add a migration source css_set
1781 * @src_cset: the source css_set to add
1782 * @dst_cgrp: the destination cgroup
1783 * @preloaded_csets: list of preloaded css_sets
1785 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1786 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1787 * up by cgroup_migrate_finish().
1789 * This function may be called without holding threadgroup_lock even if the
1790 * target is a process. Threads may be created and destroyed but as long
1791 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1792 * the preloaded css_sets are guaranteed to cover all migrations.
1794 static void cgroup_migrate_add_src(struct css_set *src_cset,
1795 struct cgroup *dst_cgrp,
1796 struct list_head *preloaded_csets)
1798 struct cgroup *src_cgrp;
1800 lockdep_assert_held(&cgroup_mutex);
1801 lockdep_assert_held(&css_set_rwsem);
1803 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
1805 /* nothing to do if this cset already belongs to the cgroup */
1806 if (src_cgrp == dst_cgrp)
1809 if (!list_empty(&src_cset->mg_preload_node))
1812 WARN_ON(src_cset->mg_src_cgrp);
1813 WARN_ON(!list_empty(&src_cset->mg_tasks));
1814 WARN_ON(!list_empty(&src_cset->mg_node));
1816 src_cset->mg_src_cgrp = src_cgrp;
1817 get_css_set(src_cset);
1818 list_add(&src_cset->mg_preload_node, preloaded_csets);
1822 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
1823 * @dst_cgrp: the destination cgroup
1824 * @preloaded_csets: list of preloaded source css_sets
1826 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
1827 * have been preloaded to @preloaded_csets. This function looks up and
1828 * pins all destination css_sets, links each to its source, and put them on
1831 * This function must be called after cgroup_migrate_add_src() has been
1832 * called on each migration source css_set. After migration is performed
1833 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
1836 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
1837 struct list_head *preloaded_csets)
1840 struct css_set *src_cset;
1842 lockdep_assert_held(&cgroup_mutex);
1844 /* look up the dst cset for each src cset and link it to src */
1845 list_for_each_entry(src_cset, preloaded_csets, mg_preload_node) {
1846 struct css_set *dst_cset;
1848 dst_cset = find_css_set(src_cset, dst_cgrp);
1852 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
1853 src_cset->mg_dst_cset = dst_cset;
1855 if (list_empty(&dst_cset->mg_preload_node))
1856 list_add(&dst_cset->mg_preload_node, &csets);
1858 put_css_set(dst_cset, false);
1861 list_splice(&csets, preloaded_csets);
1864 cgroup_migrate_finish(&csets);
1869 * cgroup_migrate - migrate a process or task to a cgroup
1870 * @cgrp: the destination cgroup
1871 * @leader: the leader of the process or the task to migrate
1872 * @threadgroup: whether @leader points to the whole process or a single task
1874 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
1875 * process, the caller must be holding threadgroup_lock of @leader. The
1876 * caller is also responsible for invoking cgroup_migrate_add_src() and
1877 * cgroup_migrate_prepare_dst() on the targets before invoking this
1878 * function and following up with cgroup_migrate_finish().
1880 * As long as a controller's ->can_attach() doesn't fail, this function is
1881 * guaranteed to succeed. This means that, excluding ->can_attach()
1882 * failure, when migrating multiple targets, the success or failure can be
1883 * decided for all targets by invoking group_migrate_prepare_dst() before
1884 * actually starting migrating.
1886 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
1889 struct cgroup_taskset tset = {
1890 .src_csets = LIST_HEAD_INIT(tset.src_csets),
1891 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
1892 .csets = &tset.src_csets,
1894 struct cgroup_subsys_state *css, *failed_css = NULL;
1895 struct css_set *cset, *tmp_cset;
1896 struct task_struct *task, *tmp_task;
1900 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1901 * already PF_EXITING could be freed from underneath us unless we
1902 * take an rcu_read_lock.
1904 down_write(&css_set_rwsem);
1908 /* @task either already exited or can't exit until the end */
1909 if (task->flags & PF_EXITING)
1912 /* leave @task alone if post_fork() hasn't linked it yet */
1913 if (list_empty(&task->cg_list))
1916 cset = task_css_set(task);
1917 if (!cset->mg_src_cgrp)
1920 list_move(&task->cg_list, &cset->mg_tasks);
1921 list_move(&cset->mg_node, &tset.src_csets);
1922 list_move(&cset->mg_dst_cset->mg_node, &tset.dst_csets);
1926 } while_each_thread(leader, task);
1928 up_write(&css_set_rwsem);
1930 /* methods shouldn't be called if no task is actually migrating */
1931 if (list_empty(&tset.src_csets))
1934 /* check that we can legitimately attach to the cgroup */
1935 for_each_css(css, i, cgrp) {
1936 if (css->ss->can_attach) {
1937 ret = css->ss->can_attach(css, &tset);
1940 goto out_cancel_attach;
1946 * Now that we're guaranteed success, proceed to move all tasks to
1947 * the new cgroup. There are no failure cases after here, so this
1948 * is the commit point.
1950 down_write(&css_set_rwsem);
1951 list_for_each_entry(cset, &tset.src_csets, mg_node) {
1952 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
1953 cgroup_task_migrate(cset->mg_src_cgrp, task,
1956 up_write(&css_set_rwsem);
1959 * Migration is committed, all target tasks are now on dst_csets.
1960 * Nothing is sensitive to fork() after this point. Notify
1961 * controllers that migration is complete.
1963 tset.csets = &tset.dst_csets;
1965 for_each_css(css, i, cgrp)
1966 if (css->ss->attach)
1967 css->ss->attach(css, &tset);
1970 goto out_release_tset;
1973 for_each_css(css, i, cgrp) {
1974 if (css == failed_css)
1976 if (css->ss->cancel_attach)
1977 css->ss->cancel_attach(css, &tset);
1980 down_write(&css_set_rwsem);
1981 list_splice_init(&tset.dst_csets, &tset.src_csets);
1982 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
1983 list_splice_init(&cset->mg_tasks, &cset->tasks);
1984 list_del_init(&cset->mg_node);
1986 up_write(&css_set_rwsem);
1991 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1992 * @dst_cgrp: the cgroup to attach to
1993 * @leader: the task or the leader of the threadgroup to be attached
1994 * @threadgroup: attach the whole threadgroup?
1996 * Call holding cgroup_mutex and threadgroup_lock of @leader.
1998 static int cgroup_attach_task(struct cgroup *dst_cgrp,
1999 struct task_struct *leader, bool threadgroup)
2001 LIST_HEAD(preloaded_csets);
2002 struct task_struct *task;
2005 /* look up all src csets */
2006 down_read(&css_set_rwsem);
2010 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2014 } while_each_thread(leader, task);
2016 up_read(&css_set_rwsem);
2018 /* prepare dst csets and commit */
2019 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2021 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2023 cgroup_migrate_finish(&preloaded_csets);
2028 * Find the task_struct of the task to attach by vpid and pass it along to the
2029 * function to attach either it or all tasks in its threadgroup. Will lock
2030 * cgroup_mutex and threadgroup.
2032 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2034 struct task_struct *tsk;
2035 const struct cred *cred = current_cred(), *tcred;
2038 if (!cgroup_lock_live_group(cgrp))
2044 tsk = find_task_by_vpid(pid);
2048 goto out_unlock_cgroup;
2051 * even if we're attaching all tasks in the thread group, we
2052 * only need to check permissions on one of them.
2054 tcred = __task_cred(tsk);
2055 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2056 !uid_eq(cred->euid, tcred->uid) &&
2057 !uid_eq(cred->euid, tcred->suid)) {
2060 goto out_unlock_cgroup;
2066 tsk = tsk->group_leader;
2069 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2070 * trapped in a cpuset, or RT worker may be born in a cgroup
2071 * with no rt_runtime allocated. Just say no.
2073 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2076 goto out_unlock_cgroup;
2079 get_task_struct(tsk);
2082 threadgroup_lock(tsk);
2084 if (!thread_group_leader(tsk)) {
2086 * a race with de_thread from another thread's exec()
2087 * may strip us of our leadership, if this happens,
2088 * there is no choice but to throw this task away and
2089 * try again; this is
2090 * "double-double-toil-and-trouble-check locking".
2092 threadgroup_unlock(tsk);
2093 put_task_struct(tsk);
2094 goto retry_find_task;
2098 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2100 threadgroup_unlock(tsk);
2102 put_task_struct(tsk);
2104 mutex_unlock(&cgroup_mutex);
2109 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2110 * @from: attach to all cgroups of a given task
2111 * @tsk: the task to be attached
2113 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2115 struct cgroupfs_root *root;
2118 mutex_lock(&cgroup_mutex);
2119 for_each_root(root) {
2120 struct cgroup *from_cgrp;
2122 if (root == &cgroup_dummy_root)
2125 down_read(&css_set_rwsem);
2126 from_cgrp = task_cgroup_from_root(from, root);
2127 up_read(&css_set_rwsem);
2129 retval = cgroup_attach_task(from_cgrp, tsk, false);
2133 mutex_unlock(&cgroup_mutex);
2137 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2139 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2140 struct cftype *cft, u64 pid)
2142 return attach_task_by_pid(css->cgroup, pid, false);
2145 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2146 struct cftype *cft, u64 tgid)
2148 return attach_task_by_pid(css->cgroup, tgid, true);
2151 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2152 struct cftype *cft, const char *buffer)
2154 struct cgroupfs_root *root = css->cgroup->root;
2156 BUILD_BUG_ON(sizeof(root->release_agent_path) < PATH_MAX);
2157 if (!cgroup_lock_live_group(css->cgroup))
2159 spin_lock(&release_agent_path_lock);
2160 strlcpy(root->release_agent_path, buffer,
2161 sizeof(root->release_agent_path));
2162 spin_unlock(&release_agent_path_lock);
2163 mutex_unlock(&cgroup_mutex);
2167 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2169 struct cgroup *cgrp = seq_css(seq)->cgroup;
2171 if (!cgroup_lock_live_group(cgrp))
2173 seq_puts(seq, cgrp->root->release_agent_path);
2174 seq_putc(seq, '\n');
2175 mutex_unlock(&cgroup_mutex);
2179 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2181 struct cgroup *cgrp = seq_css(seq)->cgroup;
2183 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2187 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2188 size_t nbytes, loff_t off)
2190 struct cgroup *cgrp = of->kn->parent->priv;
2191 struct cftype *cft = of->kn->priv;
2192 struct cgroup_subsys_state *css;
2196 * kernfs guarantees that a file isn't deleted with operations in
2197 * flight, which means that the matching css is and stays alive and
2198 * doesn't need to be pinned. The RCU locking is not necessary
2199 * either. It's just for the convenience of using cgroup_css().
2202 css = cgroup_css(cgrp, cft->ss);
2205 if (cft->write_string) {
2206 ret = cft->write_string(css, cft, strstrip(buf));
2207 } else if (cft->write_u64) {
2208 unsigned long long v;
2209 ret = kstrtoull(buf, 0, &v);
2211 ret = cft->write_u64(css, cft, v);
2212 } else if (cft->write_s64) {
2214 ret = kstrtoll(buf, 0, &v);
2216 ret = cft->write_s64(css, cft, v);
2217 } else if (cft->trigger) {
2218 ret = cft->trigger(css, (unsigned int)cft->private);
2223 return ret ?: nbytes;
2226 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2228 return seq_cft(seq)->seq_start(seq, ppos);
2231 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2233 return seq_cft(seq)->seq_next(seq, v, ppos);
2236 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2238 seq_cft(seq)->seq_stop(seq, v);
2241 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2243 struct cftype *cft = seq_cft(m);
2244 struct cgroup_subsys_state *css = seq_css(m);
2247 return cft->seq_show(m, arg);
2250 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2251 else if (cft->read_s64)
2252 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2258 static struct kernfs_ops cgroup_kf_single_ops = {
2259 .atomic_write_len = PAGE_SIZE,
2260 .write = cgroup_file_write,
2261 .seq_show = cgroup_seqfile_show,
2264 static struct kernfs_ops cgroup_kf_ops = {
2265 .atomic_write_len = PAGE_SIZE,
2266 .write = cgroup_file_write,
2267 .seq_start = cgroup_seqfile_start,
2268 .seq_next = cgroup_seqfile_next,
2269 .seq_stop = cgroup_seqfile_stop,
2270 .seq_show = cgroup_seqfile_show,
2274 * cgroup_rename - Only allow simple rename of directories in place.
2276 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2277 const char *new_name_str)
2279 struct cgroup *cgrp = kn->priv;
2282 if (kernfs_type(kn) != KERNFS_DIR)
2284 if (kn->parent != new_parent)
2288 * This isn't a proper migration and its usefulness is very
2289 * limited. Disallow if sane_behavior.
2291 if (cgroup_sane_behavior(cgrp))
2294 mutex_lock(&cgroup_tree_mutex);
2295 mutex_lock(&cgroup_mutex);
2297 ret = kernfs_rename(kn, new_parent, new_name_str);
2299 mutex_unlock(&cgroup_mutex);
2300 mutex_unlock(&cgroup_tree_mutex);
2304 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2306 char name[CGROUP_FILE_NAME_MAX];
2307 struct kernfs_node *kn;
2308 struct lock_class_key *key = NULL;
2310 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2311 key = &cft->lockdep_key;
2313 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2314 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2316 return PTR_ERR_OR_ZERO(kn);
2320 * cgroup_addrm_files - add or remove files to a cgroup directory
2321 * @cgrp: the target cgroup
2322 * @cfts: array of cftypes to be added
2323 * @is_add: whether to add or remove
2325 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2326 * For removals, this function never fails. If addition fails, this
2327 * function doesn't remove files already added. The caller is responsible
2330 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2336 lockdep_assert_held(&cgroup_tree_mutex);
2338 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2339 /* does cft->flags tell us to skip this file on @cgrp? */
2340 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2342 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2344 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2348 ret = cgroup_add_file(cgrp, cft);
2350 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2355 cgroup_rm_file(cgrp, cft);
2361 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2364 struct cgroup_subsys *ss = cfts[0].ss;
2365 struct cgroup *root = &ss->root->top_cgroup;
2366 struct cgroup_subsys_state *css;
2369 lockdep_assert_held(&cgroup_tree_mutex);
2371 /* don't bother if @ss isn't attached */
2372 if (ss->root == &cgroup_dummy_root)
2375 /* add/rm files for all cgroups created before */
2376 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2377 struct cgroup *cgrp = css->cgroup;
2379 if (cgroup_is_dead(cgrp))
2382 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2388 kernfs_activate(root->kn);
2392 static void cgroup_exit_cftypes(struct cftype *cfts)
2396 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2397 /* free copy for custom atomic_write_len, see init_cftypes() */
2398 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2405 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2409 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2410 struct kernfs_ops *kf_ops;
2412 WARN_ON(cft->ss || cft->kf_ops);
2415 kf_ops = &cgroup_kf_ops;
2417 kf_ops = &cgroup_kf_single_ops;
2420 * Ugh... if @cft wants a custom max_write_len, we need to
2421 * make a copy of kf_ops to set its atomic_write_len.
2423 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2424 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
2426 cgroup_exit_cftypes(cfts);
2429 kf_ops->atomic_write_len = cft->max_write_len;
2432 cft->kf_ops = kf_ops;
2439 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
2441 lockdep_assert_held(&cgroup_tree_mutex);
2443 if (!cfts || !cfts[0].ss)
2446 list_del(&cfts->node);
2447 cgroup_apply_cftypes(cfts, false);
2448 cgroup_exit_cftypes(cfts);
2453 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2454 * @cfts: zero-length name terminated array of cftypes
2456 * Unregister @cfts. Files described by @cfts are removed from all
2457 * existing cgroups and all future cgroups won't have them either. This
2458 * function can be called anytime whether @cfts' subsys is attached or not.
2460 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2463 int cgroup_rm_cftypes(struct cftype *cfts)
2467 mutex_lock(&cgroup_tree_mutex);
2468 ret = cgroup_rm_cftypes_locked(cfts);
2469 mutex_unlock(&cgroup_tree_mutex);
2474 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2475 * @ss: target cgroup subsystem
2476 * @cfts: zero-length name terminated array of cftypes
2478 * Register @cfts to @ss. Files described by @cfts are created for all
2479 * existing cgroups to which @ss is attached and all future cgroups will
2480 * have them too. This function can be called anytime whether @ss is
2483 * Returns 0 on successful registration, -errno on failure. Note that this
2484 * function currently returns 0 as long as @cfts registration is successful
2485 * even if some file creation attempts on existing cgroups fail.
2487 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2491 if (!cfts || cfts[0].name[0] == '\0')
2494 ret = cgroup_init_cftypes(ss, cfts);
2498 mutex_lock(&cgroup_tree_mutex);
2500 list_add_tail(&cfts->node, &ss->cfts);
2501 ret = cgroup_apply_cftypes(cfts, true);
2503 cgroup_rm_cftypes_locked(cfts);
2505 mutex_unlock(&cgroup_tree_mutex);
2510 * cgroup_task_count - count the number of tasks in a cgroup.
2511 * @cgrp: the cgroup in question
2513 * Return the number of tasks in the cgroup.
2515 static int cgroup_task_count(const struct cgroup *cgrp)
2518 struct cgrp_cset_link *link;
2520 down_read(&css_set_rwsem);
2521 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2522 count += atomic_read(&link->cset->refcount);
2523 up_read(&css_set_rwsem);
2528 * css_next_child - find the next child of a given css
2529 * @pos_css: the current position (%NULL to initiate traversal)
2530 * @parent_css: css whose children to walk
2532 * This function returns the next child of @parent_css and should be called
2533 * under either cgroup_mutex or RCU read lock. The only requirement is
2534 * that @parent_css and @pos_css are accessible. The next sibling is
2535 * guaranteed to be returned regardless of their states.
2537 struct cgroup_subsys_state *
2538 css_next_child(struct cgroup_subsys_state *pos_css,
2539 struct cgroup_subsys_state *parent_css)
2541 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2542 struct cgroup *cgrp = parent_css->cgroup;
2543 struct cgroup *next;
2545 cgroup_assert_mutexes_or_rcu_locked();
2548 * @pos could already have been removed. Once a cgroup is removed,
2549 * its ->sibling.next is no longer updated when its next sibling
2550 * changes. As CGRP_DEAD assertion is serialized and happens
2551 * before the cgroup is taken off the ->sibling list, if we see it
2552 * unasserted, it's guaranteed that the next sibling hasn't
2553 * finished its grace period even if it's already removed, and thus
2554 * safe to dereference from this RCU critical section. If
2555 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2556 * to be visible as %true here.
2558 * If @pos is dead, its next pointer can't be dereferenced;
2559 * however, as each cgroup is given a monotonically increasing
2560 * unique serial number and always appended to the sibling list,
2561 * the next one can be found by walking the parent's children until
2562 * we see a cgroup with higher serial number than @pos's. While
2563 * this path can be slower, it's taken only when either the current
2564 * cgroup is removed or iteration and removal race.
2567 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2568 } else if (likely(!cgroup_is_dead(pos))) {
2569 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2571 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2572 if (next->serial_nr > pos->serial_nr)
2576 if (&next->sibling == &cgrp->children)
2579 return cgroup_css(next, parent_css->ss);
2583 * css_next_descendant_pre - find the next descendant for pre-order walk
2584 * @pos: the current position (%NULL to initiate traversal)
2585 * @root: css whose descendants to walk
2587 * To be used by css_for_each_descendant_pre(). Find the next descendant
2588 * to visit for pre-order traversal of @root's descendants. @root is
2589 * included in the iteration and the first node to be visited.
2591 * While this function requires cgroup_mutex or RCU read locking, it
2592 * doesn't require the whole traversal to be contained in a single critical
2593 * section. This function will return the correct next descendant as long
2594 * as both @pos and @root are accessible and @pos is a descendant of @root.
2596 struct cgroup_subsys_state *
2597 css_next_descendant_pre(struct cgroup_subsys_state *pos,
2598 struct cgroup_subsys_state *root)
2600 struct cgroup_subsys_state *next;
2602 cgroup_assert_mutexes_or_rcu_locked();
2604 /* if first iteration, visit @root */
2608 /* visit the first child if exists */
2609 next = css_next_child(NULL, pos);
2613 /* no child, visit my or the closest ancestor's next sibling */
2614 while (pos != root) {
2615 next = css_next_child(pos, css_parent(pos));
2618 pos = css_parent(pos);
2625 * css_rightmost_descendant - return the rightmost descendant of a css
2626 * @pos: css of interest
2628 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2629 * is returned. This can be used during pre-order traversal to skip
2632 * While this function requires cgroup_mutex or RCU read locking, it
2633 * doesn't require the whole traversal to be contained in a single critical
2634 * section. This function will return the correct rightmost descendant as
2635 * long as @pos is accessible.
2637 struct cgroup_subsys_state *
2638 css_rightmost_descendant(struct cgroup_subsys_state *pos)
2640 struct cgroup_subsys_state *last, *tmp;
2642 cgroup_assert_mutexes_or_rcu_locked();
2646 /* ->prev isn't RCU safe, walk ->next till the end */
2648 css_for_each_child(tmp, last)
2655 static struct cgroup_subsys_state *
2656 css_leftmost_descendant(struct cgroup_subsys_state *pos)
2658 struct cgroup_subsys_state *last;
2662 pos = css_next_child(NULL, pos);
2669 * css_next_descendant_post - find the next descendant for post-order walk
2670 * @pos: the current position (%NULL to initiate traversal)
2671 * @root: css whose descendants to walk
2673 * To be used by css_for_each_descendant_post(). Find the next descendant
2674 * to visit for post-order traversal of @root's descendants. @root is
2675 * included in the iteration and the last node to be visited.
2677 * While this function requires cgroup_mutex or RCU read locking, it
2678 * doesn't require the whole traversal to be contained in a single critical
2679 * section. This function will return the correct next descendant as long
2680 * as both @pos and @cgroup are accessible and @pos is a descendant of
2683 struct cgroup_subsys_state *
2684 css_next_descendant_post(struct cgroup_subsys_state *pos,
2685 struct cgroup_subsys_state *root)
2687 struct cgroup_subsys_state *next;
2689 cgroup_assert_mutexes_or_rcu_locked();
2691 /* if first iteration, visit leftmost descendant which may be @root */
2693 return css_leftmost_descendant(root);
2695 /* if we visited @root, we're done */
2699 /* if there's an unvisited sibling, visit its leftmost descendant */
2700 next = css_next_child(pos, css_parent(pos));
2702 return css_leftmost_descendant(next);
2704 /* no sibling left, visit parent */
2705 return css_parent(pos);
2709 * css_advance_task_iter - advance a task itererator to the next css_set
2710 * @it: the iterator to advance
2712 * Advance @it to the next css_set to walk.
2714 static void css_advance_task_iter(struct css_task_iter *it)
2716 struct list_head *l = it->cset_link;
2717 struct cgrp_cset_link *link;
2718 struct css_set *cset;
2720 /* Advance to the next non-empty css_set */
2723 if (l == &it->origin_css->cgroup->cset_links) {
2724 it->cset_link = NULL;
2727 link = list_entry(l, struct cgrp_cset_link, cset_link);
2729 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
2733 if (!list_empty(&cset->tasks))
2734 it->task = cset->tasks.next;
2736 it->task = cset->mg_tasks.next;
2740 * css_task_iter_start - initiate task iteration
2741 * @css: the css to walk tasks of
2742 * @it: the task iterator to use
2744 * Initiate iteration through the tasks of @css. The caller can call
2745 * css_task_iter_next() to walk through the tasks until the function
2746 * returns NULL. On completion of iteration, css_task_iter_end() must be
2749 * Note that this function acquires a lock which is released when the
2750 * iteration finishes. The caller can't sleep while iteration is in
2753 void css_task_iter_start(struct cgroup_subsys_state *css,
2754 struct css_task_iter *it)
2755 __acquires(css_set_rwsem)
2757 /* no one should try to iterate before mounting cgroups */
2758 WARN_ON_ONCE(!use_task_css_set_links);
2760 down_read(&css_set_rwsem);
2762 it->origin_css = css;
2763 it->cset_link = &css->cgroup->cset_links;
2765 css_advance_task_iter(it);
2769 * css_task_iter_next - return the next task for the iterator
2770 * @it: the task iterator being iterated
2772 * The "next" function for task iteration. @it should have been
2773 * initialized via css_task_iter_start(). Returns NULL when the iteration
2776 struct task_struct *css_task_iter_next(struct css_task_iter *it)
2778 struct task_struct *res;
2779 struct list_head *l = it->task;
2780 struct cgrp_cset_link *link = list_entry(it->cset_link,
2781 struct cgrp_cset_link, cset_link);
2783 /* If the iterator cg is NULL, we have no tasks */
2786 res = list_entry(l, struct task_struct, cg_list);
2789 * Advance iterator to find next entry. cset->tasks is consumed
2790 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
2795 if (l == &link->cset->tasks)
2796 l = link->cset->mg_tasks.next;
2798 if (l == &link->cset->mg_tasks)
2799 css_advance_task_iter(it);
2807 * css_task_iter_end - finish task iteration
2808 * @it: the task iterator to finish
2810 * Finish task iteration started by css_task_iter_start().
2812 void css_task_iter_end(struct css_task_iter *it)
2813 __releases(css_set_rwsem)
2815 up_read(&css_set_rwsem);
2819 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
2820 * @to: cgroup to which the tasks will be moved
2821 * @from: cgroup in which the tasks currently reside
2823 * Locking rules between cgroup_post_fork() and the migration path
2824 * guarantee that, if a task is forking while being migrated, the new child
2825 * is guaranteed to be either visible in the source cgroup after the
2826 * parent's migration is complete or put into the target cgroup. No task
2827 * can slip out of migration through forking.
2829 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
2831 LIST_HEAD(preloaded_csets);
2832 struct cgrp_cset_link *link;
2833 struct css_task_iter it;
2834 struct task_struct *task;
2837 mutex_lock(&cgroup_mutex);
2839 /* all tasks in @from are being moved, all csets are source */
2840 down_read(&css_set_rwsem);
2841 list_for_each_entry(link, &from->cset_links, cset_link)
2842 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
2843 up_read(&css_set_rwsem);
2845 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
2850 * Migrate tasks one-by-one until @form is empty. This fails iff
2851 * ->can_attach() fails.
2854 css_task_iter_start(&from->dummy_css, &it);
2855 task = css_task_iter_next(&it);
2857 get_task_struct(task);
2858 css_task_iter_end(&it);
2861 ret = cgroup_migrate(to, task, false);
2862 put_task_struct(task);
2864 } while (task && !ret);
2866 cgroup_migrate_finish(&preloaded_csets);
2867 mutex_unlock(&cgroup_mutex);
2872 * Stuff for reading the 'tasks'/'procs' files.
2874 * Reading this file can return large amounts of data if a cgroup has
2875 * *lots* of attached tasks. So it may need several calls to read(),
2876 * but we cannot guarantee that the information we produce is correct
2877 * unless we produce it entirely atomically.
2881 /* which pidlist file are we talking about? */
2882 enum cgroup_filetype {
2888 * A pidlist is a list of pids that virtually represents the contents of one
2889 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
2890 * a pair (one each for procs, tasks) for each pid namespace that's relevant
2893 struct cgroup_pidlist {
2895 * used to find which pidlist is wanted. doesn't change as long as
2896 * this particular list stays in the list.
2898 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
2901 /* how many elements the above list has */
2903 /* each of these stored in a list by its cgroup */
2904 struct list_head links;
2905 /* pointer to the cgroup we belong to, for list removal purposes */
2906 struct cgroup *owner;
2907 /* for delayed destruction */
2908 struct delayed_work destroy_dwork;
2912 * The following two functions "fix" the issue where there are more pids
2913 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
2914 * TODO: replace with a kernel-wide solution to this problem
2916 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
2917 static void *pidlist_allocate(int count)
2919 if (PIDLIST_TOO_LARGE(count))
2920 return vmalloc(count * sizeof(pid_t));
2922 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
2925 static void pidlist_free(void *p)
2927 if (is_vmalloc_addr(p))
2934 * Used to destroy all pidlists lingering waiting for destroy timer. None
2935 * should be left afterwards.
2937 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
2939 struct cgroup_pidlist *l, *tmp_l;
2941 mutex_lock(&cgrp->pidlist_mutex);
2942 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
2943 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
2944 mutex_unlock(&cgrp->pidlist_mutex);
2946 flush_workqueue(cgroup_pidlist_destroy_wq);
2947 BUG_ON(!list_empty(&cgrp->pidlists));
2950 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
2952 struct delayed_work *dwork = to_delayed_work(work);
2953 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
2955 struct cgroup_pidlist *tofree = NULL;
2957 mutex_lock(&l->owner->pidlist_mutex);
2960 * Destroy iff we didn't get queued again. The state won't change
2961 * as destroy_dwork can only be queued while locked.
2963 if (!delayed_work_pending(dwork)) {
2964 list_del(&l->links);
2965 pidlist_free(l->list);
2966 put_pid_ns(l->key.ns);
2970 mutex_unlock(&l->owner->pidlist_mutex);
2975 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
2976 * Returns the number of unique elements.
2978 static int pidlist_uniq(pid_t *list, int length)
2983 * we presume the 0th element is unique, so i starts at 1. trivial
2984 * edge cases first; no work needs to be done for either
2986 if (length == 0 || length == 1)
2988 /* src and dest walk down the list; dest counts unique elements */
2989 for (src = 1; src < length; src++) {
2990 /* find next unique element */
2991 while (list[src] == list[src-1]) {
2996 /* dest always points to where the next unique element goes */
2997 list[dest] = list[src];
3005 * The two pid files - task and cgroup.procs - guaranteed that the result
3006 * is sorted, which forced this whole pidlist fiasco. As pid order is
3007 * different per namespace, each namespace needs differently sorted list,
3008 * making it impossible to use, for example, single rbtree of member tasks
3009 * sorted by task pointer. As pidlists can be fairly large, allocating one
3010 * per open file is dangerous, so cgroup had to implement shared pool of
3011 * pidlists keyed by cgroup and namespace.
3013 * All this extra complexity was caused by the original implementation
3014 * committing to an entirely unnecessary property. In the long term, we
3015 * want to do away with it. Explicitly scramble sort order if
3016 * sane_behavior so that no such expectation exists in the new interface.
3018 * Scrambling is done by swapping every two consecutive bits, which is
3019 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3021 static pid_t pid_fry(pid_t pid)
3023 unsigned a = pid & 0x55555555;
3024 unsigned b = pid & 0xAAAAAAAA;
3026 return (a << 1) | (b >> 1);
3029 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3031 if (cgroup_sane_behavior(cgrp))
3032 return pid_fry(pid);
3037 static int cmppid(const void *a, const void *b)
3039 return *(pid_t *)a - *(pid_t *)b;
3042 static int fried_cmppid(const void *a, const void *b)
3044 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3047 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3048 enum cgroup_filetype type)
3050 struct cgroup_pidlist *l;
3051 /* don't need task_nsproxy() if we're looking at ourself */
3052 struct pid_namespace *ns = task_active_pid_ns(current);
3054 lockdep_assert_held(&cgrp->pidlist_mutex);
3056 list_for_each_entry(l, &cgrp->pidlists, links)
3057 if (l->key.type == type && l->key.ns == ns)
3063 * find the appropriate pidlist for our purpose (given procs vs tasks)
3064 * returns with the lock on that pidlist already held, and takes care
3065 * of the use count, or returns NULL with no locks held if we're out of
3068 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3069 enum cgroup_filetype type)
3071 struct cgroup_pidlist *l;
3073 lockdep_assert_held(&cgrp->pidlist_mutex);
3075 l = cgroup_pidlist_find(cgrp, type);
3079 /* entry not found; create a new one */
3080 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3084 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3086 /* don't need task_nsproxy() if we're looking at ourself */
3087 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3089 list_add(&l->links, &cgrp->pidlists);
3094 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3096 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3097 struct cgroup_pidlist **lp)
3101 int pid, n = 0; /* used for populating the array */
3102 struct css_task_iter it;
3103 struct task_struct *tsk;
3104 struct cgroup_pidlist *l;
3106 lockdep_assert_held(&cgrp->pidlist_mutex);
3109 * If cgroup gets more users after we read count, we won't have
3110 * enough space - tough. This race is indistinguishable to the
3111 * caller from the case that the additional cgroup users didn't
3112 * show up until sometime later on.
3114 length = cgroup_task_count(cgrp);
3115 array = pidlist_allocate(length);
3118 /* now, populate the array */
3119 css_task_iter_start(&cgrp->dummy_css, &it);
3120 while ((tsk = css_task_iter_next(&it))) {
3121 if (unlikely(n == length))
3123 /* get tgid or pid for procs or tasks file respectively */
3124 if (type == CGROUP_FILE_PROCS)
3125 pid = task_tgid_vnr(tsk);
3127 pid = task_pid_vnr(tsk);
3128 if (pid > 0) /* make sure to only use valid results */
3131 css_task_iter_end(&it);
3133 /* now sort & (if procs) strip out duplicates */
3134 if (cgroup_sane_behavior(cgrp))
3135 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3137 sort(array, length, sizeof(pid_t), cmppid, NULL);
3138 if (type == CGROUP_FILE_PROCS)
3139 length = pidlist_uniq(array, length);
3141 l = cgroup_pidlist_find_create(cgrp, type);
3143 mutex_unlock(&cgrp->pidlist_mutex);
3144 pidlist_free(array);
3148 /* store array, freeing old if necessary */
3149 pidlist_free(l->list);
3157 * cgroupstats_build - build and fill cgroupstats
3158 * @stats: cgroupstats to fill information into
3159 * @dentry: A dentry entry belonging to the cgroup for which stats have
3162 * Build and fill cgroupstats so that taskstats can export it to user
3165 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3167 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3168 struct cgroup *cgrp;
3169 struct css_task_iter it;
3170 struct task_struct *tsk;
3172 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3173 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3174 kernfs_type(kn) != KERNFS_DIR)
3177 mutex_lock(&cgroup_mutex);
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);
3186 if (!cgrp || cgroup_is_dead(cgrp)) {
3188 mutex_unlock(&cgroup_mutex);
3193 css_task_iter_start(&cgrp->dummy_css, &it);
3194 while ((tsk = css_task_iter_next(&it))) {
3195 switch (tsk->state) {
3197 stats->nr_running++;
3199 case TASK_INTERRUPTIBLE:
3200 stats->nr_sleeping++;
3202 case TASK_UNINTERRUPTIBLE:
3203 stats->nr_uninterruptible++;
3206 stats->nr_stopped++;
3209 if (delayacct_is_task_waiting_on_io(tsk))
3210 stats->nr_io_wait++;
3214 css_task_iter_end(&it);
3216 mutex_unlock(&cgroup_mutex);
3222 * seq_file methods for the tasks/procs files. The seq_file position is the
3223 * next pid to display; the seq_file iterator is a pointer to the pid
3224 * in the cgroup->l->list array.
3227 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3230 * Initially we receive a position value that corresponds to
3231 * one more than the last pid shown (or 0 on the first call or
3232 * after a seek to the start). Use a binary-search to find the
3233 * next pid to display, if any
3235 struct kernfs_open_file *of = s->private;
3236 struct cgroup *cgrp = seq_css(s)->cgroup;
3237 struct cgroup_pidlist *l;
3238 enum cgroup_filetype type = seq_cft(s)->private;
3239 int index = 0, pid = *pos;
3242 mutex_lock(&cgrp->pidlist_mutex);
3245 * !NULL @of->priv indicates that this isn't the first start()
3246 * after open. If the matching pidlist is around, we can use that.
3247 * Look for it. Note that @of->priv can't be used directly. It
3248 * could already have been destroyed.
3251 of->priv = cgroup_pidlist_find(cgrp, type);
3254 * Either this is the first start() after open or the matching
3255 * pidlist has been destroyed inbetween. Create a new one.
3258 ret = pidlist_array_load(cgrp, type,
3259 (struct cgroup_pidlist **)&of->priv);
3261 return ERR_PTR(ret);
3266 int end = l->length;
3268 while (index < end) {
3269 int mid = (index + end) / 2;
3270 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3273 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3279 /* If we're off the end of the array, we're done */
3280 if (index >= l->length)
3282 /* Update the abstract position to be the actual pid that we found */
3283 iter = l->list + index;
3284 *pos = cgroup_pid_fry(cgrp, *iter);
3288 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3290 struct kernfs_open_file *of = s->private;
3291 struct cgroup_pidlist *l = of->priv;
3294 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3295 CGROUP_PIDLIST_DESTROY_DELAY);
3296 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3299 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3301 struct kernfs_open_file *of = s->private;
3302 struct cgroup_pidlist *l = of->priv;
3304 pid_t *end = l->list + l->length;
3306 * Advance to the next pid in the array. If this goes off the
3313 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3318 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3320 return seq_printf(s, "%d\n", *(int *)v);
3324 * seq_operations functions for iterating on pidlists through seq_file -
3325 * independent of whether it's tasks or procs
3327 static const struct seq_operations cgroup_pidlist_seq_operations = {
3328 .start = cgroup_pidlist_start,
3329 .stop = cgroup_pidlist_stop,
3330 .next = cgroup_pidlist_next,
3331 .show = cgroup_pidlist_show,
3334 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3337 return notify_on_release(css->cgroup);
3340 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3341 struct cftype *cft, u64 val)
3343 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3345 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3347 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3351 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3354 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3357 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3358 struct cftype *cft, u64 val)
3361 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3363 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3367 static struct cftype cgroup_base_files[] = {
3369 .name = "cgroup.procs",
3370 .seq_start = cgroup_pidlist_start,
3371 .seq_next = cgroup_pidlist_next,
3372 .seq_stop = cgroup_pidlist_stop,
3373 .seq_show = cgroup_pidlist_show,
3374 .private = CGROUP_FILE_PROCS,
3375 .write_u64 = cgroup_procs_write,
3376 .mode = S_IRUGO | S_IWUSR,
3379 .name = "cgroup.clone_children",
3380 .flags = CFTYPE_INSANE,
3381 .read_u64 = cgroup_clone_children_read,
3382 .write_u64 = cgroup_clone_children_write,
3385 .name = "cgroup.sane_behavior",
3386 .flags = CFTYPE_ONLY_ON_ROOT,
3387 .seq_show = cgroup_sane_behavior_show,
3391 * Historical crazy stuff. These don't have "cgroup." prefix and
3392 * don't exist if sane_behavior. If you're depending on these, be
3393 * prepared to be burned.
3397 .flags = CFTYPE_INSANE, /* use "procs" instead */
3398 .seq_start = cgroup_pidlist_start,
3399 .seq_next = cgroup_pidlist_next,
3400 .seq_stop = cgroup_pidlist_stop,
3401 .seq_show = cgroup_pidlist_show,
3402 .private = CGROUP_FILE_TASKS,
3403 .write_u64 = cgroup_tasks_write,
3404 .mode = S_IRUGO | S_IWUSR,
3407 .name = "notify_on_release",
3408 .flags = CFTYPE_INSANE,
3409 .read_u64 = cgroup_read_notify_on_release,
3410 .write_u64 = cgroup_write_notify_on_release,
3413 .name = "release_agent",
3414 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3415 .seq_show = cgroup_release_agent_show,
3416 .write_string = cgroup_release_agent_write,
3417 .max_write_len = PATH_MAX - 1,
3423 * cgroup_populate_dir - create subsys files in a cgroup directory
3424 * @cgrp: target cgroup
3425 * @subsys_mask: mask of the subsystem ids whose files should be added
3427 * On failure, no file is added.
3429 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3431 struct cgroup_subsys *ss;
3434 /* process cftsets of each subsystem */
3435 for_each_subsys(ss, i) {
3436 struct cftype *cfts;
3438 if (!test_bit(i, &subsys_mask))
3441 list_for_each_entry(cfts, &ss->cfts, node) {
3442 ret = cgroup_addrm_files(cgrp, cfts, true);
3449 cgroup_clear_dir(cgrp, subsys_mask);
3454 * css destruction is four-stage process.
3456 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3457 * Implemented in kill_css().
3459 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3460 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3461 * by invoking offline_css(). After offlining, the base ref is put.
3462 * Implemented in css_killed_work_fn().
3464 * 3. When the percpu_ref reaches zero, the only possible remaining
3465 * accessors are inside RCU read sections. css_release() schedules the
3468 * 4. After the grace period, the css can be freed. Implemented in
3469 * css_free_work_fn().
3471 * It is actually hairier because both step 2 and 4 require process context
3472 * and thus involve punting to css->destroy_work adding two additional
3473 * steps to the already complex sequence.
3475 static void css_free_work_fn(struct work_struct *work)
3477 struct cgroup_subsys_state *css =
3478 container_of(work, struct cgroup_subsys_state, destroy_work);
3479 struct cgroup *cgrp = css->cgroup;
3482 css_put(css->parent);
3484 css->ss->css_free(css);
3488 static void css_free_rcu_fn(struct rcu_head *rcu_head)
3490 struct cgroup_subsys_state *css =
3491 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
3493 INIT_WORK(&css->destroy_work, css_free_work_fn);
3494 queue_work(cgroup_destroy_wq, &css->destroy_work);
3497 static void css_release(struct percpu_ref *ref)
3499 struct cgroup_subsys_state *css =
3500 container_of(ref, struct cgroup_subsys_state, refcnt);
3502 rcu_assign_pointer(css->cgroup->subsys[css->ss->id], NULL);
3503 call_rcu(&css->rcu_head, css_free_rcu_fn);
3506 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3507 struct cgroup *cgrp)
3514 css->parent = cgroup_css(cgrp->parent, ss);
3516 css->flags |= CSS_ROOT;
3518 BUG_ON(cgroup_css(cgrp, ss));
3521 /* invoke ->css_online() on a new CSS and mark it online if successful */
3522 static int online_css(struct cgroup_subsys_state *css)
3524 struct cgroup_subsys *ss = css->ss;
3527 lockdep_assert_held(&cgroup_tree_mutex);
3528 lockdep_assert_held(&cgroup_mutex);
3531 ret = ss->css_online(css);
3533 css->flags |= CSS_ONLINE;
3534 css->cgroup->nr_css++;
3535 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
3540 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
3541 static void offline_css(struct cgroup_subsys_state *css)
3543 struct cgroup_subsys *ss = css->ss;
3545 lockdep_assert_held(&cgroup_tree_mutex);
3546 lockdep_assert_held(&cgroup_mutex);
3548 if (!(css->flags & CSS_ONLINE))
3551 if (ss->css_offline)
3552 ss->css_offline(css);
3554 css->flags &= ~CSS_ONLINE;
3555 css->cgroup->nr_css--;
3556 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
3560 * create_css - create a cgroup_subsys_state
3561 * @cgrp: the cgroup new css will be associated with
3562 * @ss: the subsys of new css
3564 * Create a new css associated with @cgrp - @ss pair. On success, the new
3565 * css is online and installed in @cgrp with all interface files created.
3566 * Returns 0 on success, -errno on failure.
3568 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
3570 struct cgroup *parent = cgrp->parent;
3571 struct cgroup_subsys_state *css;
3574 lockdep_assert_held(&cgroup_mutex);
3576 css = ss->css_alloc(cgroup_css(parent, ss));
3578 return PTR_ERR(css);
3580 err = percpu_ref_init(&css->refcnt, css_release);
3584 init_css(css, ss, cgrp);
3586 err = cgroup_populate_dir(cgrp, 1 << ss->id);
3590 err = online_css(css);
3595 css_get(css->parent);
3597 cgrp->subsys_mask |= 1 << ss->id;
3599 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
3601 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",
3602 current->comm, current->pid, ss->name);
3603 if (!strcmp(ss->name, "memory"))
3604 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
3605 ss->warned_broken_hierarchy = true;
3611 percpu_ref_cancel_init(&css->refcnt);
3617 * cgroup_create - create a cgroup
3618 * @parent: cgroup that will be parent of the new cgroup
3619 * @name: name of the new cgroup
3620 * @mode: mode to set on new cgroup
3622 static long cgroup_create(struct cgroup *parent, const char *name,
3625 struct cgroup *cgrp;
3626 struct cgroupfs_root *root = parent->root;
3628 struct cgroup_subsys *ss;
3629 struct kernfs_node *kn;
3631 /* allocate the cgroup and its ID, 0 is reserved for the root */
3632 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
3636 mutex_lock(&cgroup_tree_mutex);
3639 * Only live parents can have children. Note that the liveliness
3640 * check isn't strictly necessary because cgroup_mkdir() and
3641 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
3642 * anyway so that locking is contained inside cgroup proper and we
3643 * don't get nasty surprises if we ever grow another caller.
3645 if (!cgroup_lock_live_group(parent)) {
3647 goto err_unlock_tree;
3651 * Temporarily set the pointer to NULL, so idr_find() won't return
3652 * a half-baked cgroup.
3654 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
3660 init_cgroup_housekeeping(cgrp);
3662 cgrp->parent = parent;
3663 cgrp->dummy_css.parent = &parent->dummy_css;
3664 cgrp->root = parent->root;
3666 if (notify_on_release(parent))
3667 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3669 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
3670 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3672 /* create the directory */
3673 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
3681 * This extra ref will be put in cgroup_free_fn() and guarantees
3682 * that @cgrp->kn is always accessible.
3686 cgrp->serial_nr = cgroup_serial_nr_next++;
3688 /* allocation complete, commit to creation */
3689 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
3690 atomic_inc(&root->nr_cgrps);
3694 * @cgrp is now fully operational. If something fails after this
3695 * point, it'll be released via the normal destruction path.
3697 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
3699 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
3703 /* let's create and online css's */
3704 for_each_subsys(ss, ssid) {
3705 if (root->top_cgroup.subsys_mask & (1 << ssid)) {
3706 err = create_css(cgrp, ss);
3712 kernfs_activate(kn);
3714 mutex_unlock(&cgroup_mutex);
3715 mutex_unlock(&cgroup_tree_mutex);
3720 idr_remove(&root->cgroup_idr, cgrp->id);
3722 mutex_unlock(&cgroup_mutex);
3724 mutex_unlock(&cgroup_tree_mutex);
3729 cgroup_destroy_locked(cgrp);
3730 mutex_unlock(&cgroup_mutex);
3731 mutex_unlock(&cgroup_tree_mutex);
3735 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
3738 struct cgroup *parent = parent_kn->priv;
3740 return cgroup_create(parent, name, mode);
3744 * This is called when the refcnt of a css is confirmed to be killed.
3745 * css_tryget() is now guaranteed to fail.
3747 static void css_killed_work_fn(struct work_struct *work)
3749 struct cgroup_subsys_state *css =
3750 container_of(work, struct cgroup_subsys_state, destroy_work);
3751 struct cgroup *cgrp = css->cgroup;
3753 mutex_lock(&cgroup_tree_mutex);
3754 mutex_lock(&cgroup_mutex);
3757 * css_tryget() is guaranteed to fail now. Tell subsystems to
3758 * initate destruction.
3763 * If @cgrp is marked dead, it's waiting for refs of all css's to
3764 * be disabled before proceeding to the second phase of cgroup
3765 * destruction. If we are the last one, kick it off.
3767 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
3768 cgroup_destroy_css_killed(cgrp);
3770 mutex_unlock(&cgroup_mutex);
3771 mutex_unlock(&cgroup_tree_mutex);
3774 * Put the css refs from kill_css(). Each css holds an extra
3775 * reference to the cgroup's dentry and cgroup removal proceeds
3776 * regardless of css refs. On the last put of each css, whenever
3777 * that may be, the extra dentry ref is put so that dentry
3778 * destruction happens only after all css's are released.
3783 /* css kill confirmation processing requires process context, bounce */
3784 static void css_killed_ref_fn(struct percpu_ref *ref)
3786 struct cgroup_subsys_state *css =
3787 container_of(ref, struct cgroup_subsys_state, refcnt);
3789 INIT_WORK(&css->destroy_work, css_killed_work_fn);
3790 queue_work(cgroup_destroy_wq, &css->destroy_work);
3793 static void __kill_css(struct cgroup_subsys_state *css)
3795 lockdep_assert_held(&cgroup_tree_mutex);
3798 * This must happen before css is disassociated with its cgroup.
3799 * See seq_css() for details.
3801 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
3804 * Killing would put the base ref, but we need to keep it alive
3805 * until after ->css_offline().
3810 * cgroup core guarantees that, by the time ->css_offline() is
3811 * invoked, no new css reference will be given out via
3812 * css_tryget(). We can't simply call percpu_ref_kill() and
3813 * proceed to offlining css's because percpu_ref_kill() doesn't
3814 * guarantee that the ref is seen as killed on all CPUs on return.
3816 * Use percpu_ref_kill_and_confirm() to get notifications as each
3817 * css is confirmed to be seen as killed on all CPUs.
3819 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
3823 * kill_css - destroy a css
3824 * @css: css to destroy
3826 * This function initiates destruction of @css by removing cgroup interface
3827 * files and putting its base reference. ->css_offline() will be invoked
3828 * asynchronously once css_tryget() is guaranteed to fail and when the
3829 * reference count reaches zero, @css will be released.
3831 static void kill_css(struct cgroup_subsys_state *css)
3833 struct cgroup *cgrp = css->cgroup;
3835 lockdep_assert_held(&cgroup_tree_mutex);
3837 /* if already killed, noop */
3838 if (cgrp->subsys_mask & (1 << css->ss->id)) {
3839 cgrp->subsys_mask &= ~(1 << css->ss->id);
3845 * cgroup_destroy_locked - the first stage of cgroup destruction
3846 * @cgrp: cgroup to be destroyed
3848 * css's make use of percpu refcnts whose killing latency shouldn't be
3849 * exposed to userland and are RCU protected. Also, cgroup core needs to
3850 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
3851 * invoked. To satisfy all the requirements, destruction is implemented in
3852 * the following two steps.
3854 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
3855 * userland visible parts and start killing the percpu refcnts of
3856 * css's. Set up so that the next stage will be kicked off once all
3857 * the percpu refcnts are confirmed to be killed.
3859 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
3860 * rest of destruction. Once all cgroup references are gone, the
3861 * cgroup is RCU-freed.
3863 * This function implements s1. After this step, @cgrp is gone as far as
3864 * the userland is concerned and a new cgroup with the same name may be
3865 * created. As cgroup doesn't care about the names internally, this
3866 * doesn't cause any problem.
3868 static int cgroup_destroy_locked(struct cgroup *cgrp)
3869 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
3871 struct cgroup *child;
3872 struct cgroup_subsys_state *css;
3876 lockdep_assert_held(&cgroup_tree_mutex);
3877 lockdep_assert_held(&cgroup_mutex);
3880 * css_set_rwsem synchronizes access to ->cset_links and prevents
3881 * @cgrp from being removed while put_css_set() is in progress.
3883 down_read(&css_set_rwsem);
3884 empty = list_empty(&cgrp->cset_links);
3885 up_read(&css_set_rwsem);
3890 * Make sure there's no live children. We can't test ->children
3891 * emptiness as dead children linger on it while being destroyed;
3892 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
3896 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
3897 empty = cgroup_is_dead(child);
3906 * Mark @cgrp dead. This prevents further task migration and child
3907 * creation by disabling cgroup_lock_live_group(). Note that
3908 * CGRP_DEAD assertion is depended upon by css_next_child() to
3909 * resume iteration after dropping RCU read lock. See
3910 * css_next_child() for details.
3912 set_bit(CGRP_DEAD, &cgrp->flags);
3915 * Initiate massacre of all css's. cgroup_destroy_css_killed()
3916 * will be invoked to perform the rest of destruction once the
3917 * percpu refs of all css's are confirmed to be killed. This
3918 * involves removing the subsystem's files, drop cgroup_mutex.
3920 mutex_unlock(&cgroup_mutex);
3921 for_each_css(css, ssid, cgrp)
3923 mutex_lock(&cgroup_mutex);
3925 /* CGRP_DEAD is set, remove from ->release_list for the last time */
3926 raw_spin_lock(&release_list_lock);
3927 if (!list_empty(&cgrp->release_list))
3928 list_del_init(&cgrp->release_list);
3929 raw_spin_unlock(&release_list_lock);
3932 * If @cgrp has css's attached, the second stage of cgroup
3933 * destruction is kicked off from css_killed_work_fn() after the
3934 * refs of all attached css's are killed. If @cgrp doesn't have
3935 * any css, we kick it off here.
3938 cgroup_destroy_css_killed(cgrp);
3940 /* remove @cgrp directory along with the base files */
3941 mutex_unlock(&cgroup_mutex);
3944 * There are two control paths which try to determine cgroup from
3945 * dentry without going through kernfs - cgroupstats_build() and
3946 * css_tryget_from_dir(). Those are supported by RCU protecting
3947 * clearing of cgrp->kn->priv backpointer, which should happen
3948 * after all files under it have been removed.
3950 kernfs_remove(cgrp->kn); /* @cgrp has an extra ref on its kn */
3951 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
3953 mutex_lock(&cgroup_mutex);
3959 * cgroup_destroy_css_killed - the second step of cgroup destruction
3960 * @work: cgroup->destroy_free_work
3962 * This function is invoked from a work item for a cgroup which is being
3963 * destroyed after all css's are offlined and performs the rest of
3964 * destruction. This is the second step of destruction described in the
3965 * comment above cgroup_destroy_locked().
3967 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
3969 struct cgroup *parent = cgrp->parent;
3971 lockdep_assert_held(&cgroup_tree_mutex);
3972 lockdep_assert_held(&cgroup_mutex);
3974 /* delete this cgroup from parent->children */
3975 list_del_rcu(&cgrp->sibling);
3979 set_bit(CGRP_RELEASABLE, &parent->flags);
3980 check_for_release(parent);
3983 static int cgroup_rmdir(struct kernfs_node *kn)
3985 struct cgroup *cgrp = kn->priv;
3989 * This is self-destruction but @kn can't be removed while this
3990 * callback is in progress. Let's break active protection. Once
3991 * the protection is broken, @cgrp can be destroyed at any point.
3992 * Pin it so that it stays accessible.
3995 kernfs_break_active_protection(kn);
3997 mutex_lock(&cgroup_tree_mutex);
3998 mutex_lock(&cgroup_mutex);
4001 * @cgrp might already have been destroyed while we're trying to
4004 if (!cgroup_is_dead(cgrp))
4005 ret = cgroup_destroy_locked(cgrp);
4007 mutex_unlock(&cgroup_mutex);
4008 mutex_unlock(&cgroup_tree_mutex);
4010 kernfs_unbreak_active_protection(kn);
4015 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4016 .remount_fs = cgroup_remount,
4017 .show_options = cgroup_show_options,
4018 .mkdir = cgroup_mkdir,
4019 .rmdir = cgroup_rmdir,
4020 .rename = cgroup_rename,
4023 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4025 struct cgroup_subsys_state *css;
4027 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4029 mutex_lock(&cgroup_tree_mutex);
4030 mutex_lock(&cgroup_mutex);
4032 INIT_LIST_HEAD(&ss->cfts);
4034 /* Create the top cgroup state for this subsystem */
4035 ss->root = &cgroup_dummy_root;
4036 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4037 /* We don't handle early failures gracefully */
4038 BUG_ON(IS_ERR(css));
4039 init_css(css, ss, cgroup_dummy_top);
4041 /* Update the init_css_set to contain a subsys
4042 * pointer to this state - since the subsystem is
4043 * newly registered, all tasks and hence the
4044 * init_css_set is in the subsystem's top cgroup. */
4045 init_css_set.subsys[ss->id] = css;
4047 need_forkexit_callback |= ss->fork || ss->exit;
4049 /* At system boot, before all subsystems have been
4050 * registered, no tasks have been forked, so we don't
4051 * need to invoke fork callbacks here. */
4052 BUG_ON(!list_empty(&init_task.tasks));
4054 BUG_ON(online_css(css));
4056 cgroup_dummy_root.top_cgroup.subsys_mask |= 1 << ss->id;
4058 mutex_unlock(&cgroup_mutex);
4059 mutex_unlock(&cgroup_tree_mutex);
4063 * cgroup_init_early - cgroup initialization at system boot
4065 * Initialize cgroups at system boot, and initialize any
4066 * subsystems that request early init.
4068 int __init cgroup_init_early(void)
4070 static struct cgroup_sb_opts __initdata opts = { };
4071 struct cgroup_subsys *ss;
4074 init_cgroup_root(&cgroup_dummy_root, &opts);
4075 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4077 for_each_subsys(ss, i) {
4078 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4079 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4080 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4082 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4083 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4086 ss->name = cgroup_subsys_name[i];
4089 cgroup_init_subsys(ss);
4095 * cgroup_init - cgroup initialization
4097 * Register cgroup filesystem and /proc file, and initialize
4098 * any subsystems that didn't request early init.
4100 int __init cgroup_init(void)
4102 struct cgroup_subsys *ss;
4106 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4108 mutex_lock(&cgroup_tree_mutex);
4109 mutex_lock(&cgroup_mutex);
4111 /* Add init_css_set to the hash table */
4112 key = css_set_hash(init_css_set.subsys);
4113 hash_add(css_set_table, &init_css_set.hlist, key);
4115 BUG_ON(cgroup_setup_root(&cgroup_dummy_root, 0));
4117 mutex_unlock(&cgroup_mutex);
4118 mutex_unlock(&cgroup_tree_mutex);
4120 for_each_subsys(ss, ssid) {
4121 if (!ss->early_init)
4122 cgroup_init_subsys(ss);
4125 * cftype registration needs kmalloc and can't be done
4126 * during early_init. Register base cftypes separately.
4128 if (ss->base_cftypes)
4129 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4132 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4136 err = register_filesystem(&cgroup_fs_type);
4138 kobject_put(cgroup_kobj);
4142 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4146 static int __init cgroup_wq_init(void)
4149 * There isn't much point in executing destruction path in
4150 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4151 * Use 1 for @max_active.
4153 * We would prefer to do this in cgroup_init() above, but that
4154 * is called before init_workqueues(): so leave this until after.
4156 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4157 BUG_ON(!cgroup_destroy_wq);
4160 * Used to destroy pidlists and separate to serve as flush domain.
4161 * Cap @max_active to 1 too.
4163 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4165 BUG_ON(!cgroup_pidlist_destroy_wq);
4169 core_initcall(cgroup_wq_init);
4172 * proc_cgroup_show()
4173 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4174 * - Used for /proc/<pid>/cgroup.
4177 /* TODO: Use a proper seq_file iterator */
4178 int proc_cgroup_show(struct seq_file *m, void *v)
4181 struct task_struct *tsk;
4184 struct cgroupfs_root *root;
4187 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4193 tsk = get_pid_task(pid, PIDTYPE_PID);
4199 mutex_lock(&cgroup_mutex);
4200 down_read(&css_set_rwsem);
4202 for_each_root(root) {
4203 struct cgroup_subsys *ss;
4204 struct cgroup *cgrp;
4205 int ssid, count = 0;
4207 if (root == &cgroup_dummy_root)
4210 seq_printf(m, "%d:", root->hierarchy_id);
4211 for_each_subsys(ss, ssid)
4212 if (root->top_cgroup.subsys_mask & (1 << ssid))
4213 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4214 if (strlen(root->name))
4215 seq_printf(m, "%sname=%s", count ? "," : "",
4218 cgrp = task_cgroup_from_root(tsk, root);
4219 path = cgroup_path(cgrp, buf, PATH_MAX);
4221 retval = -ENAMETOOLONG;
4229 up_read(&css_set_rwsem);
4230 mutex_unlock(&cgroup_mutex);
4231 put_task_struct(tsk);
4238 /* Display information about each subsystem and each hierarchy */
4239 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4241 struct cgroup_subsys *ss;
4244 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4246 * ideally we don't want subsystems moving around while we do this.
4247 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4248 * subsys/hierarchy state.
4250 mutex_lock(&cgroup_mutex);
4252 for_each_subsys(ss, i)
4253 seq_printf(m, "%s\t%d\t%d\t%d\n",
4254 ss->name, ss->root->hierarchy_id,
4255 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4257 mutex_unlock(&cgroup_mutex);
4261 static int cgroupstats_open(struct inode *inode, struct file *file)
4263 return single_open(file, proc_cgroupstats_show, NULL);
4266 static const struct file_operations proc_cgroupstats_operations = {
4267 .open = cgroupstats_open,
4269 .llseek = seq_lseek,
4270 .release = single_release,
4274 * cgroup_fork - initialize cgroup related fields during copy_process()
4275 * @child: pointer to task_struct of forking parent process.
4277 * A task is associated with the init_css_set until cgroup_post_fork()
4278 * attaches it to the parent's css_set. Empty cg_list indicates that
4279 * @child isn't holding reference to its css_set.
4281 void cgroup_fork(struct task_struct *child)
4283 RCU_INIT_POINTER(child->cgroups, &init_css_set);
4284 INIT_LIST_HEAD(&child->cg_list);
4288 * cgroup_post_fork - called on a new task after adding it to the task list
4289 * @child: the task in question
4291 * Adds the task to the list running through its css_set if necessary and
4292 * call the subsystem fork() callbacks. Has to be after the task is
4293 * visible on the task list in case we race with the first call to
4294 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4297 void cgroup_post_fork(struct task_struct *child)
4299 struct cgroup_subsys *ss;
4303 * This may race against cgroup_enable_task_cg_links(). As that
4304 * function sets use_task_css_set_links before grabbing
4305 * tasklist_lock and we just went through tasklist_lock to add
4306 * @child, it's guaranteed that either we see the set
4307 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4308 * @child during its iteration.
4310 * If we won the race, @child is associated with %current's
4311 * css_set. Grabbing css_set_rwsem guarantees both that the
4312 * association is stable, and, on completion of the parent's
4313 * migration, @child is visible in the source of migration or
4314 * already in the destination cgroup. This guarantee is necessary
4315 * when implementing operations which need to migrate all tasks of
4316 * a cgroup to another.
4318 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4319 * will remain in init_css_set. This is safe because all tasks are
4320 * in the init_css_set before cg_links is enabled and there's no
4321 * operation which transfers all tasks out of init_css_set.
4323 if (use_task_css_set_links) {
4324 struct css_set *cset;
4326 down_write(&css_set_rwsem);
4327 cset = task_css_set(current);
4328 if (list_empty(&child->cg_list)) {
4329 rcu_assign_pointer(child->cgroups, cset);
4330 list_add(&child->cg_list, &cset->tasks);
4333 up_write(&css_set_rwsem);
4337 * Call ss->fork(). This must happen after @child is linked on
4338 * css_set; otherwise, @child might change state between ->fork()
4339 * and addition to css_set.
4341 if (need_forkexit_callback) {
4342 for_each_subsys(ss, i)
4349 * cgroup_exit - detach cgroup from exiting task
4350 * @tsk: pointer to task_struct of exiting process
4351 * @run_callback: run exit callbacks?
4353 * Description: Detach cgroup from @tsk and release it.
4355 * Note that cgroups marked notify_on_release force every task in
4356 * them to take the global cgroup_mutex mutex when exiting.
4357 * This could impact scaling on very large systems. Be reluctant to
4358 * use notify_on_release cgroups where very high task exit scaling
4359 * is required on large systems.
4361 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
4362 * call cgroup_exit() while the task is still competent to handle
4363 * notify_on_release(), then leave the task attached to the root cgroup in
4364 * each hierarchy for the remainder of its exit. No need to bother with
4365 * init_css_set refcnting. init_css_set never goes away and we can't race
4366 * with migration path - either PF_EXITING is visible to migration path or
4367 * @tsk never got on the tasklist.
4369 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4371 struct cgroup_subsys *ss;
4372 struct css_set *cset;
4373 bool put_cset = false;
4377 * Unlink from @tsk from its css_set. As migration path can't race
4378 * with us, we can check cg_list without grabbing css_set_rwsem.
4380 if (!list_empty(&tsk->cg_list)) {
4381 down_write(&css_set_rwsem);
4382 list_del_init(&tsk->cg_list);
4383 up_write(&css_set_rwsem);
4387 /* Reassign the task to the init_css_set. */
4388 cset = task_css_set(tsk);
4389 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4391 if (run_callbacks && need_forkexit_callback) {
4392 /* see cgroup_post_fork() for details */
4393 for_each_subsys(ss, i) {
4395 struct cgroup_subsys_state *old_css = cset->subsys[i];
4396 struct cgroup_subsys_state *css = task_css(tsk, i);
4398 ss->exit(css, old_css, tsk);
4404 put_css_set(cset, true);
4407 static void check_for_release(struct cgroup *cgrp)
4409 if (cgroup_is_releasable(cgrp) &&
4410 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
4412 * Control Group is currently removeable. If it's not
4413 * already queued for a userspace notification, queue
4416 int need_schedule_work = 0;
4418 raw_spin_lock(&release_list_lock);
4419 if (!cgroup_is_dead(cgrp) &&
4420 list_empty(&cgrp->release_list)) {
4421 list_add(&cgrp->release_list, &release_list);
4422 need_schedule_work = 1;
4424 raw_spin_unlock(&release_list_lock);
4425 if (need_schedule_work)
4426 schedule_work(&release_agent_work);
4431 * Notify userspace when a cgroup is released, by running the
4432 * configured release agent with the name of the cgroup (path
4433 * relative to the root of cgroup file system) as the argument.
4435 * Most likely, this user command will try to rmdir this cgroup.
4437 * This races with the possibility that some other task will be
4438 * attached to this cgroup before it is removed, or that some other
4439 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4440 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4441 * unused, and this cgroup will be reprieved from its death sentence,
4442 * to continue to serve a useful existence. Next time it's released,
4443 * we will get notified again, if it still has 'notify_on_release' set.
4445 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4446 * means only wait until the task is successfully execve()'d. The
4447 * separate release agent task is forked by call_usermodehelper(),
4448 * then control in this thread returns here, without waiting for the
4449 * release agent task. We don't bother to wait because the caller of
4450 * this routine has no use for the exit status of the release agent
4451 * task, so no sense holding our caller up for that.
4453 static void cgroup_release_agent(struct work_struct *work)
4455 BUG_ON(work != &release_agent_work);
4456 mutex_lock(&cgroup_mutex);
4457 raw_spin_lock(&release_list_lock);
4458 while (!list_empty(&release_list)) {
4459 char *argv[3], *envp[3];
4461 char *pathbuf = NULL, *agentbuf = NULL, *path;
4462 struct cgroup *cgrp = list_entry(release_list.next,
4465 list_del_init(&cgrp->release_list);
4466 raw_spin_unlock(&release_list_lock);
4467 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
4470 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
4473 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4478 argv[i++] = agentbuf;
4483 /* minimal command environment */
4484 envp[i++] = "HOME=/";
4485 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4488 /* Drop the lock while we invoke the usermode helper,
4489 * since the exec could involve hitting disk and hence
4490 * be a slow process */
4491 mutex_unlock(&cgroup_mutex);
4492 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4493 mutex_lock(&cgroup_mutex);
4497 raw_spin_lock(&release_list_lock);
4499 raw_spin_unlock(&release_list_lock);
4500 mutex_unlock(&cgroup_mutex);
4503 static int __init cgroup_disable(char *str)
4505 struct cgroup_subsys *ss;
4509 while ((token = strsep(&str, ",")) != NULL) {
4513 for_each_subsys(ss, i) {
4514 if (!strcmp(token, ss->name)) {
4516 printk(KERN_INFO "Disabling %s control group"
4517 " subsystem\n", ss->name);
4524 __setup("cgroup_disable=", cgroup_disable);
4527 * css_tryget_from_dir - get corresponding css from the dentry of a cgroup dir
4528 * @dentry: directory dentry of interest
4529 * @ss: subsystem of interest
4531 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
4532 * to get the corresponding css and return it. If such css doesn't exist
4533 * or can't be pinned, an ERR_PTR value is returned.
4535 struct cgroup_subsys_state *css_tryget_from_dir(struct dentry *dentry,
4536 struct cgroup_subsys *ss)
4538 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
4539 struct cgroup_subsys_state *css = NULL;
4540 struct cgroup *cgrp;
4542 /* is @dentry a cgroup dir? */
4543 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
4544 kernfs_type(kn) != KERNFS_DIR)
4545 return ERR_PTR(-EBADF);
4550 * This path doesn't originate from kernfs and @kn could already
4551 * have been or be removed at any point. @kn->priv is RCU
4552 * protected for this access. See destroy_locked() for details.
4554 cgrp = rcu_dereference(kn->priv);
4556 css = cgroup_css(cgrp, ss);
4558 if (!css || !css_tryget(css))
4559 css = ERR_PTR(-ENOENT);
4566 * css_from_id - lookup css by id
4567 * @id: the cgroup id
4568 * @ss: cgroup subsys to be looked into
4570 * Returns the css if there's valid one with @id, otherwise returns NULL.
4571 * Should be called under rcu_read_lock().
4573 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
4575 struct cgroup *cgrp;
4577 cgroup_assert_mutexes_or_rcu_locked();
4579 cgrp = idr_find(&ss->root->cgroup_idr, id);
4581 return cgroup_css(cgrp, ss);
4585 #ifdef CONFIG_CGROUP_DEBUG
4586 static struct cgroup_subsys_state *
4587 debug_css_alloc(struct cgroup_subsys_state *parent_css)
4589 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4592 return ERR_PTR(-ENOMEM);
4597 static void debug_css_free(struct cgroup_subsys_state *css)
4602 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
4605 return cgroup_task_count(css->cgroup);
4608 static u64 current_css_set_read(struct cgroup_subsys_state *css,
4611 return (u64)(unsigned long)current->cgroups;
4614 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
4620 count = atomic_read(&task_css_set(current)->refcount);
4625 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
4627 struct cgrp_cset_link *link;
4628 struct css_set *cset;
4631 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
4635 down_read(&css_set_rwsem);
4637 cset = rcu_dereference(current->cgroups);
4638 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
4639 struct cgroup *c = link->cgrp;
4640 const char *name = "?";
4642 if (c != cgroup_dummy_top) {
4643 cgroup_name(c, name_buf, NAME_MAX + 1);
4647 seq_printf(seq, "Root %d group %s\n",
4648 c->root->hierarchy_id, name);
4651 up_read(&css_set_rwsem);
4656 #define MAX_TASKS_SHOWN_PER_CSS 25
4657 static int cgroup_css_links_read(struct seq_file *seq, void *v)
4659 struct cgroup_subsys_state *css = seq_css(seq);
4660 struct cgrp_cset_link *link;
4662 down_read(&css_set_rwsem);
4663 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
4664 struct css_set *cset = link->cset;
4665 struct task_struct *task;
4668 seq_printf(seq, "css_set %p\n", cset);
4670 list_for_each_entry(task, &cset->tasks, cg_list) {
4671 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
4673 seq_printf(seq, " task %d\n", task_pid_vnr(task));
4676 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
4677 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
4679 seq_printf(seq, " task %d\n", task_pid_vnr(task));
4683 seq_puts(seq, " ...\n");
4685 up_read(&css_set_rwsem);
4689 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
4691 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
4694 static struct cftype debug_files[] = {
4696 .name = "taskcount",
4697 .read_u64 = debug_taskcount_read,
4701 .name = "current_css_set",
4702 .read_u64 = current_css_set_read,
4706 .name = "current_css_set_refcount",
4707 .read_u64 = current_css_set_refcount_read,
4711 .name = "current_css_set_cg_links",
4712 .seq_show = current_css_set_cg_links_read,
4716 .name = "cgroup_css_links",
4717 .seq_show = cgroup_css_links_read,
4721 .name = "releasable",
4722 .read_u64 = releasable_read,
4728 struct cgroup_subsys debug_cgrp_subsys = {
4729 .css_alloc = debug_css_alloc,
4730 .css_free = debug_css_free,
4731 .base_cftypes = debug_files,
4733 #endif /* CONFIG_CGROUP_DEBUG */