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 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31 #include <linux/cgroup.h>
32 #include <linux/cred.h>
33 #include <linux/ctype.h>
34 #include <linux/errno.h>
35 #include <linux/init_task.h>
36 #include <linux/kernel.h>
37 #include <linux/list.h>
39 #include <linux/mutex.h>
40 #include <linux/mount.h>
41 #include <linux/pagemap.h>
42 #include <linux/proc_fs.h>
43 #include <linux/rcupdate.h>
44 #include <linux/sched.h>
45 #include <linux/slab.h>
46 #include <linux/spinlock.h>
47 #include <linux/rwsem.h>
48 #include <linux/string.h>
49 #include <linux/sort.h>
50 #include <linux/kmod.h>
51 #include <linux/delayacct.h>
52 #include <linux/cgroupstats.h>
53 #include <linux/hashtable.h>
54 #include <linux/pid_namespace.h>
55 #include <linux/idr.h>
56 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
57 #include <linux/kthread.h>
58 #include <linux/delay.h>
60 #include <linux/atomic.h>
63 * pidlists linger the following amount before being destroyed. The goal
64 * is avoiding frequent destruction in the middle of consecutive read calls
65 * Expiring in the middle is a performance problem not a correctness one.
66 * 1 sec should be enough.
68 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
70 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
74 * cgroup_mutex is the master lock. Any modification to cgroup or its
75 * hierarchy must be performed while holding it.
77 * css_set_rwsem protects task->cgroups pointer, the list of css_set
78 * objects, and the chain of tasks off each css_set.
80 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
81 * cgroup.h can use them for lockdep annotations.
83 #ifdef CONFIG_PROVE_RCU
84 DEFINE_MUTEX(cgroup_mutex);
85 DECLARE_RWSEM(css_set_rwsem);
86 EXPORT_SYMBOL_GPL(cgroup_mutex);
87 EXPORT_SYMBOL_GPL(css_set_rwsem);
89 static DEFINE_MUTEX(cgroup_mutex);
90 static DECLARE_RWSEM(css_set_rwsem);
94 * Protects cgroup_idr and css_idr so that IDs can be released without
95 * grabbing cgroup_mutex.
97 static DEFINE_SPINLOCK(cgroup_idr_lock);
100 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
101 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
103 static DEFINE_SPINLOCK(release_agent_path_lock);
105 #define cgroup_assert_mutex_or_rcu_locked() \
106 rcu_lockdep_assert(rcu_read_lock_held() || \
107 lockdep_is_held(&cgroup_mutex), \
108 "cgroup_mutex or RCU read lock required");
111 * cgroup destruction makes heavy use of work items and there can be a lot
112 * of concurrent destructions. Use a separate workqueue so that cgroup
113 * destruction work items don't end up filling up max_active of system_wq
114 * which may lead to deadlock.
116 static struct workqueue_struct *cgroup_destroy_wq;
119 * pidlist destructions need to be flushed on cgroup destruction. Use a
120 * separate workqueue as flush domain.
122 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
124 /* generate an array of cgroup subsystem pointers */
125 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
126 static struct cgroup_subsys *cgroup_subsys[] = {
127 #include <linux/cgroup_subsys.h>
131 /* array of cgroup subsystem names */
132 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
133 static const char *cgroup_subsys_name[] = {
134 #include <linux/cgroup_subsys.h>
139 * The default hierarchy, reserved for the subsystems that are otherwise
140 * unattached - it never has more than a single cgroup, and all tasks are
141 * part of that cgroup.
143 struct cgroup_root cgrp_dfl_root;
146 * The default hierarchy always exists but is hidden until mounted for the
147 * first time. This is for backward compatibility.
149 static bool cgrp_dfl_root_visible;
151 /* The list of hierarchy roots */
153 static LIST_HEAD(cgroup_roots);
154 static int cgroup_root_count;
156 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
157 static DEFINE_IDR(cgroup_hierarchy_idr);
160 * Assign a monotonically increasing serial number to csses. It guarantees
161 * cgroups with bigger numbers are newer than those with smaller numbers.
162 * Also, as csses are always appended to the parent's ->children list, it
163 * guarantees that sibling csses are always sorted in the ascending serial
164 * number order on the list. Protected by cgroup_mutex.
166 static u64 css_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 bool cgroup_has_live_children(struct cgroup *cgrp);
179 static int rebind_subsystems(struct cgroup_root *dst_root,
180 unsigned int ss_mask);
181 static int cgroup_destroy_locked(struct cgroup *cgrp);
182 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss);
183 static void css_release(struct percpu_ref *ref);
184 static void kill_css(struct cgroup_subsys_state *css);
185 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
187 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
189 /* IDR wrappers which synchronize using cgroup_idr_lock */
190 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
195 idr_preload(gfp_mask);
196 spin_lock_bh(&cgroup_idr_lock);
197 ret = idr_alloc(idr, ptr, start, end, gfp_mask);
198 spin_unlock_bh(&cgroup_idr_lock);
203 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
207 spin_lock_bh(&cgroup_idr_lock);
208 ret = idr_replace(idr, ptr, id);
209 spin_unlock_bh(&cgroup_idr_lock);
213 static void cgroup_idr_remove(struct idr *idr, int id)
215 spin_lock_bh(&cgroup_idr_lock);
217 spin_unlock_bh(&cgroup_idr_lock);
220 static struct cgroup *cgroup_parent(struct cgroup *cgrp)
222 struct cgroup_subsys_state *parent_css = cgrp->self.parent;
225 return container_of(parent_css, struct cgroup, self);
230 * cgroup_css - obtain a cgroup's css for the specified subsystem
231 * @cgrp: the cgroup of interest
232 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
234 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
235 * function must be called either under cgroup_mutex or rcu_read_lock() and
236 * the caller is responsible for pinning the returned css if it wants to
237 * keep accessing it outside the said locks. This function may return
238 * %NULL if @cgrp doesn't have @subsys_id enabled.
240 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
241 struct cgroup_subsys *ss)
244 return rcu_dereference_check(cgrp->subsys[ss->id],
245 lockdep_is_held(&cgroup_mutex));
251 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
252 * @cgrp: the cgroup of interest
253 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
255 * Similar to cgroup_css() but returns the effctive css, which is defined
256 * as the matching css of the nearest ancestor including self which has @ss
257 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
258 * function is guaranteed to return non-NULL css.
260 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
261 struct cgroup_subsys *ss)
263 lockdep_assert_held(&cgroup_mutex);
268 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
271 while (cgroup_parent(cgrp) &&
272 !(cgroup_parent(cgrp)->child_subsys_mask & (1 << ss->id)))
273 cgrp = cgroup_parent(cgrp);
275 return cgroup_css(cgrp, ss);
278 /* convenient tests for these bits */
279 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
281 return test_bit(CGRP_DEAD, &cgrp->flags);
284 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
286 struct cgroup *cgrp = of->kn->parent->priv;
287 struct cftype *cft = of_cft(of);
290 * This is open and unprotected implementation of cgroup_css().
291 * seq_css() is only called from a kernfs file operation which has
292 * an active reference on the file. Because all the subsystem
293 * files are drained before a css is disassociated with a cgroup,
294 * the matching css from the cgroup's subsys table is guaranteed to
295 * be and stay valid until the enclosing operation is complete.
298 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
302 EXPORT_SYMBOL_GPL(of_css);
305 * cgroup_is_descendant - test ancestry
306 * @cgrp: the cgroup to be tested
307 * @ancestor: possible ancestor of @cgrp
309 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
310 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
311 * and @ancestor are accessible.
313 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
316 if (cgrp == ancestor)
318 cgrp = cgroup_parent(cgrp);
323 static int cgroup_is_releasable(const struct cgroup *cgrp)
326 (1 << CGRP_RELEASABLE) |
327 (1 << CGRP_NOTIFY_ON_RELEASE);
328 return (cgrp->flags & bits) == bits;
331 static int notify_on_release(const struct cgroup *cgrp)
333 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
337 * for_each_css - iterate all css's of a cgroup
338 * @css: the iteration cursor
339 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
340 * @cgrp: the target cgroup to iterate css's of
342 * Should be called under cgroup_[tree_]mutex.
344 #define for_each_css(css, ssid, cgrp) \
345 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
346 if (!((css) = rcu_dereference_check( \
347 (cgrp)->subsys[(ssid)], \
348 lockdep_is_held(&cgroup_mutex)))) { } \
352 * for_each_e_css - iterate all effective css's of a cgroup
353 * @css: the iteration cursor
354 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
355 * @cgrp: the target cgroup to iterate css's of
357 * Should be called under cgroup_[tree_]mutex.
359 #define for_each_e_css(css, ssid, cgrp) \
360 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
361 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
366 * for_each_subsys - iterate all enabled cgroup subsystems
367 * @ss: the iteration cursor
368 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
370 #define for_each_subsys(ss, ssid) \
371 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
372 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
374 /* iterate across the hierarchies */
375 #define for_each_root(root) \
376 list_for_each_entry((root), &cgroup_roots, root_list)
378 /* iterate over child cgrps, lock should be held throughout iteration */
379 #define cgroup_for_each_live_child(child, cgrp) \
380 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
381 if (({ lockdep_assert_held(&cgroup_mutex); \
382 cgroup_is_dead(child); })) \
386 /* the list of cgroups eligible for automatic release. Protected by
387 * release_list_lock */
388 static LIST_HEAD(release_list);
389 static DEFINE_RAW_SPINLOCK(release_list_lock);
390 static void cgroup_release_agent(struct work_struct *work);
391 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
392 static void check_for_release(struct cgroup *cgrp);
395 * A cgroup can be associated with multiple css_sets as different tasks may
396 * belong to different cgroups on different hierarchies. In the other
397 * direction, a css_set is naturally associated with multiple cgroups.
398 * This M:N relationship is represented by the following link structure
399 * which exists for each association and allows traversing the associations
402 struct cgrp_cset_link {
403 /* the cgroup and css_set this link associates */
405 struct css_set *cset;
407 /* list of cgrp_cset_links anchored at cgrp->cset_links */
408 struct list_head cset_link;
410 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
411 struct list_head cgrp_link;
415 * The default css_set - used by init and its children prior to any
416 * hierarchies being mounted. It contains a pointer to the root state
417 * for each subsystem. Also used to anchor the list of css_sets. Not
418 * reference-counted, to improve performance when child cgroups
419 * haven't been created.
421 struct css_set init_css_set = {
422 .refcount = ATOMIC_INIT(1),
423 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
424 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
425 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
426 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
427 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
430 static int css_set_count = 1; /* 1 for init_css_set */
433 * cgroup_update_populated - updated populated count of a cgroup
434 * @cgrp: the target cgroup
435 * @populated: inc or dec populated count
437 * @cgrp is either getting the first task (css_set) or losing the last.
438 * Update @cgrp->populated_cnt accordingly. The count is propagated
439 * towards root so that a given cgroup's populated_cnt is zero iff the
440 * cgroup and all its descendants are empty.
442 * @cgrp's interface file "cgroup.populated" is zero if
443 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
444 * changes from or to zero, userland is notified that the content of the
445 * interface file has changed. This can be used to detect when @cgrp and
446 * its descendants become populated or empty.
448 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
450 lockdep_assert_held(&css_set_rwsem);
456 trigger = !cgrp->populated_cnt++;
458 trigger = !--cgrp->populated_cnt;
463 if (cgrp->populated_kn)
464 kernfs_notify(cgrp->populated_kn);
465 cgrp = cgroup_parent(cgrp);
470 * hash table for cgroup groups. This improves the performance to find
471 * an existing css_set. This hash doesn't (currently) take into
472 * account cgroups in empty hierarchies.
474 #define CSS_SET_HASH_BITS 7
475 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
477 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
479 unsigned long key = 0UL;
480 struct cgroup_subsys *ss;
483 for_each_subsys(ss, i)
484 key += (unsigned long)css[i];
485 key = (key >> 16) ^ key;
490 static void put_css_set_locked(struct css_set *cset, bool taskexit)
492 struct cgrp_cset_link *link, *tmp_link;
493 struct cgroup_subsys *ss;
496 lockdep_assert_held(&css_set_rwsem);
498 if (!atomic_dec_and_test(&cset->refcount))
501 /* This css_set is dead. unlink it and release cgroup refcounts */
502 for_each_subsys(ss, ssid)
503 list_del(&cset->e_cset_node[ssid]);
504 hash_del(&cset->hlist);
507 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
508 struct cgroup *cgrp = link->cgrp;
510 list_del(&link->cset_link);
511 list_del(&link->cgrp_link);
513 /* @cgrp can't go away while we're holding css_set_rwsem */
514 if (list_empty(&cgrp->cset_links)) {
515 cgroup_update_populated(cgrp, false);
516 if (notify_on_release(cgrp)) {
518 set_bit(CGRP_RELEASABLE, &cgrp->flags);
519 check_for_release(cgrp);
526 kfree_rcu(cset, rcu_head);
529 static void put_css_set(struct css_set *cset, bool taskexit)
532 * Ensure that the refcount doesn't hit zero while any readers
533 * can see it. Similar to atomic_dec_and_lock(), but for an
536 if (atomic_add_unless(&cset->refcount, -1, 1))
539 down_write(&css_set_rwsem);
540 put_css_set_locked(cset, taskexit);
541 up_write(&css_set_rwsem);
545 * refcounted get/put for css_set objects
547 static inline void get_css_set(struct css_set *cset)
549 atomic_inc(&cset->refcount);
553 * compare_css_sets - helper function for find_existing_css_set().
554 * @cset: candidate css_set being tested
555 * @old_cset: existing css_set for a task
556 * @new_cgrp: cgroup that's being entered by the task
557 * @template: desired set of css pointers in css_set (pre-calculated)
559 * Returns true if "cset" matches "old_cset" except for the hierarchy
560 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
562 static bool compare_css_sets(struct css_set *cset,
563 struct css_set *old_cset,
564 struct cgroup *new_cgrp,
565 struct cgroup_subsys_state *template[])
567 struct list_head *l1, *l2;
570 * On the default hierarchy, there can be csets which are
571 * associated with the same set of cgroups but different csses.
572 * Let's first ensure that csses match.
574 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
578 * Compare cgroup pointers in order to distinguish between
579 * different cgroups in hierarchies. As different cgroups may
580 * share the same effective css, this comparison is always
583 l1 = &cset->cgrp_links;
584 l2 = &old_cset->cgrp_links;
586 struct cgrp_cset_link *link1, *link2;
587 struct cgroup *cgrp1, *cgrp2;
591 /* See if we reached the end - both lists are equal length. */
592 if (l1 == &cset->cgrp_links) {
593 BUG_ON(l2 != &old_cset->cgrp_links);
596 BUG_ON(l2 == &old_cset->cgrp_links);
598 /* Locate the cgroups associated with these links. */
599 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
600 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
603 /* Hierarchies should be linked in the same order. */
604 BUG_ON(cgrp1->root != cgrp2->root);
607 * If this hierarchy is the hierarchy of the cgroup
608 * that's changing, then we need to check that this
609 * css_set points to the new cgroup; if it's any other
610 * hierarchy, then this css_set should point to the
611 * same cgroup as the old css_set.
613 if (cgrp1->root == new_cgrp->root) {
614 if (cgrp1 != new_cgrp)
625 * find_existing_css_set - init css array and find the matching css_set
626 * @old_cset: the css_set that we're using before the cgroup transition
627 * @cgrp: the cgroup that we're moving into
628 * @template: out param for the new set of csses, should be clear on entry
630 static struct css_set *find_existing_css_set(struct css_set *old_cset,
632 struct cgroup_subsys_state *template[])
634 struct cgroup_root *root = cgrp->root;
635 struct cgroup_subsys *ss;
636 struct css_set *cset;
641 * Build the set of subsystem state objects that we want to see in the
642 * new css_set. while subsystems can change globally, the entries here
643 * won't change, so no need for locking.
645 for_each_subsys(ss, i) {
646 if (root->subsys_mask & (1UL << i)) {
648 * @ss is in this hierarchy, so we want the
649 * effective css from @cgrp.
651 template[i] = cgroup_e_css(cgrp, ss);
654 * @ss is not in this hierarchy, so we don't want
657 template[i] = old_cset->subsys[i];
661 key = css_set_hash(template);
662 hash_for_each_possible(css_set_table, cset, hlist, key) {
663 if (!compare_css_sets(cset, old_cset, cgrp, template))
666 /* This css_set matches what we need */
670 /* No existing cgroup group matched */
674 static void free_cgrp_cset_links(struct list_head *links_to_free)
676 struct cgrp_cset_link *link, *tmp_link;
678 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
679 list_del(&link->cset_link);
685 * allocate_cgrp_cset_links - allocate cgrp_cset_links
686 * @count: the number of links to allocate
687 * @tmp_links: list_head the allocated links are put on
689 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
690 * through ->cset_link. Returns 0 on success or -errno.
692 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
694 struct cgrp_cset_link *link;
697 INIT_LIST_HEAD(tmp_links);
699 for (i = 0; i < count; i++) {
700 link = kzalloc(sizeof(*link), GFP_KERNEL);
702 free_cgrp_cset_links(tmp_links);
705 list_add(&link->cset_link, tmp_links);
711 * link_css_set - a helper function to link a css_set to a cgroup
712 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
713 * @cset: the css_set to be linked
714 * @cgrp: the destination cgroup
716 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
719 struct cgrp_cset_link *link;
721 BUG_ON(list_empty(tmp_links));
723 if (cgroup_on_dfl(cgrp))
724 cset->dfl_cgrp = cgrp;
726 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
730 if (list_empty(&cgrp->cset_links))
731 cgroup_update_populated(cgrp, true);
732 list_move(&link->cset_link, &cgrp->cset_links);
735 * Always add links to the tail of the list so that the list
736 * is sorted by order of hierarchy creation
738 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
742 * find_css_set - return a new css_set with one cgroup updated
743 * @old_cset: the baseline css_set
744 * @cgrp: the cgroup to be updated
746 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
747 * substituted into the appropriate hierarchy.
749 static struct css_set *find_css_set(struct css_set *old_cset,
752 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
753 struct css_set *cset;
754 struct list_head tmp_links;
755 struct cgrp_cset_link *link;
756 struct cgroup_subsys *ss;
760 lockdep_assert_held(&cgroup_mutex);
762 /* First see if we already have a cgroup group that matches
764 down_read(&css_set_rwsem);
765 cset = find_existing_css_set(old_cset, cgrp, template);
768 up_read(&css_set_rwsem);
773 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
777 /* Allocate all the cgrp_cset_link objects that we'll need */
778 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
783 atomic_set(&cset->refcount, 1);
784 INIT_LIST_HEAD(&cset->cgrp_links);
785 INIT_LIST_HEAD(&cset->tasks);
786 INIT_LIST_HEAD(&cset->mg_tasks);
787 INIT_LIST_HEAD(&cset->mg_preload_node);
788 INIT_LIST_HEAD(&cset->mg_node);
789 INIT_HLIST_NODE(&cset->hlist);
791 /* Copy the set of subsystem state objects generated in
792 * find_existing_css_set() */
793 memcpy(cset->subsys, template, sizeof(cset->subsys));
795 down_write(&css_set_rwsem);
796 /* Add reference counts and links from the new css_set. */
797 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
798 struct cgroup *c = link->cgrp;
800 if (c->root == cgrp->root)
802 link_css_set(&tmp_links, cset, c);
805 BUG_ON(!list_empty(&tmp_links));
809 /* Add @cset to the hash table */
810 key = css_set_hash(cset->subsys);
811 hash_add(css_set_table, &cset->hlist, key);
813 for_each_subsys(ss, ssid)
814 list_add_tail(&cset->e_cset_node[ssid],
815 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
817 up_write(&css_set_rwsem);
822 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
824 struct cgroup *root_cgrp = kf_root->kn->priv;
826 return root_cgrp->root;
829 static int cgroup_init_root_id(struct cgroup_root *root)
833 lockdep_assert_held(&cgroup_mutex);
835 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
839 root->hierarchy_id = id;
843 static void cgroup_exit_root_id(struct cgroup_root *root)
845 lockdep_assert_held(&cgroup_mutex);
847 if (root->hierarchy_id) {
848 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
849 root->hierarchy_id = 0;
853 static void cgroup_free_root(struct cgroup_root *root)
856 /* hierarhcy ID shoulid already have been released */
857 WARN_ON_ONCE(root->hierarchy_id);
859 idr_destroy(&root->cgroup_idr);
864 static void cgroup_destroy_root(struct cgroup_root *root)
866 struct cgroup *cgrp = &root->cgrp;
867 struct cgrp_cset_link *link, *tmp_link;
869 mutex_lock(&cgroup_mutex);
871 BUG_ON(atomic_read(&root->nr_cgrps));
872 BUG_ON(!list_empty(&cgrp->self.children));
874 /* Rebind all subsystems back to the default hierarchy */
875 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
878 * Release all the links from cset_links to this hierarchy's
881 down_write(&css_set_rwsem);
883 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
884 list_del(&link->cset_link);
885 list_del(&link->cgrp_link);
888 up_write(&css_set_rwsem);
890 if (!list_empty(&root->root_list)) {
891 list_del(&root->root_list);
895 cgroup_exit_root_id(root);
897 mutex_unlock(&cgroup_mutex);
899 kernfs_destroy_root(root->kf_root);
900 cgroup_free_root(root);
903 /* look up cgroup associated with given css_set on the specified hierarchy */
904 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
905 struct cgroup_root *root)
907 struct cgroup *res = NULL;
909 lockdep_assert_held(&cgroup_mutex);
910 lockdep_assert_held(&css_set_rwsem);
912 if (cset == &init_css_set) {
915 struct cgrp_cset_link *link;
917 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
918 struct cgroup *c = link->cgrp;
920 if (c->root == root) {
932 * Return the cgroup for "task" from the given hierarchy. Must be
933 * called with cgroup_mutex and css_set_rwsem held.
935 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
936 struct cgroup_root *root)
939 * No need to lock the task - since we hold cgroup_mutex the
940 * task can't change groups, so the only thing that can happen
941 * is that it exits and its css is set back to init_css_set.
943 return cset_cgroup_from_root(task_css_set(task), root);
947 * A task must hold cgroup_mutex to modify cgroups.
949 * Any task can increment and decrement the count field without lock.
950 * So in general, code holding cgroup_mutex can't rely on the count
951 * field not changing. However, if the count goes to zero, then only
952 * cgroup_attach_task() can increment it again. Because a count of zero
953 * means that no tasks are currently attached, therefore there is no
954 * way a task attached to that cgroup can fork (the other way to
955 * increment the count). So code holding cgroup_mutex can safely
956 * assume that if the count is zero, it will stay zero. Similarly, if
957 * a task holds cgroup_mutex on a cgroup with zero count, it
958 * knows that the cgroup won't be removed, as cgroup_rmdir()
961 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
962 * (usually) take cgroup_mutex. These are the two most performance
963 * critical pieces of code here. The exception occurs on cgroup_exit(),
964 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
965 * is taken, and if the cgroup count is zero, a usermode call made
966 * to the release agent with the name of the cgroup (path relative to
967 * the root of cgroup file system) as the argument.
969 * A cgroup can only be deleted if both its 'count' of using tasks
970 * is zero, and its list of 'children' cgroups is empty. Since all
971 * tasks in the system use _some_ cgroup, and since there is always at
972 * least one task in the system (init, pid == 1), therefore, root cgroup
973 * always has either children cgroups and/or using tasks. So we don't
974 * need a special hack to ensure that root cgroup cannot be deleted.
976 * P.S. One more locking exception. RCU is used to guard the
977 * update of a tasks cgroup pointer by cgroup_attach_task()
980 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask);
981 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
982 static const struct file_operations proc_cgroupstats_operations;
984 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
987 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
988 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
989 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
990 cft->ss->name, cft->name);
992 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
997 * cgroup_file_mode - deduce file mode of a control file
998 * @cft: the control file in question
1000 * returns cft->mode if ->mode is not 0
1001 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1002 * returns S_IRUGO if it has only a read handler
1003 * returns S_IWUSR if it has only a write hander
1005 static umode_t cgroup_file_mode(const struct cftype *cft)
1012 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1015 if (cft->write_u64 || cft->write_s64 || cft->write)
1021 static void cgroup_get(struct cgroup *cgrp)
1023 WARN_ON_ONCE(cgroup_is_dead(cgrp));
1024 css_get(&cgrp->self);
1027 static void cgroup_put(struct cgroup *cgrp)
1029 css_put(&cgrp->self);
1033 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1034 * @kn: the kernfs_node being serviced
1036 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1037 * the method finishes if locking succeeded. Note that once this function
1038 * returns the cgroup returned by cgroup_kn_lock_live() may become
1039 * inaccessible any time. If the caller intends to continue to access the
1040 * cgroup, it should pin it before invoking this function.
1042 static void cgroup_kn_unlock(struct kernfs_node *kn)
1044 struct cgroup *cgrp;
1046 if (kernfs_type(kn) == KERNFS_DIR)
1049 cgrp = kn->parent->priv;
1051 mutex_unlock(&cgroup_mutex);
1053 kernfs_unbreak_active_protection(kn);
1058 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1059 * @kn: the kernfs_node being serviced
1061 * This helper is to be used by a cgroup kernfs method currently servicing
1062 * @kn. It breaks the active protection, performs cgroup locking and
1063 * verifies that the associated cgroup is alive. Returns the cgroup if
1064 * alive; otherwise, %NULL. A successful return should be undone by a
1065 * matching cgroup_kn_unlock() invocation.
1067 * Any cgroup kernfs method implementation which requires locking the
1068 * associated cgroup should use this helper. It avoids nesting cgroup
1069 * locking under kernfs active protection and allows all kernfs operations
1070 * including self-removal.
1072 static struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn)
1074 struct cgroup *cgrp;
1076 if (kernfs_type(kn) == KERNFS_DIR)
1079 cgrp = kn->parent->priv;
1082 * We're gonna grab cgroup_mutex which nests outside kernfs
1083 * active_ref. cgroup liveliness check alone provides enough
1084 * protection against removal. Ensure @cgrp stays accessible and
1085 * break the active_ref protection.
1088 kernfs_break_active_protection(kn);
1090 mutex_lock(&cgroup_mutex);
1092 if (!cgroup_is_dead(cgrp))
1095 cgroup_kn_unlock(kn);
1099 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1101 char name[CGROUP_FILE_NAME_MAX];
1103 lockdep_assert_held(&cgroup_mutex);
1104 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1108 * cgroup_clear_dir - remove subsys files in a cgroup directory
1109 * @cgrp: target cgroup
1110 * @subsys_mask: mask of the subsystem ids whose files should be removed
1112 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned int subsys_mask)
1114 struct cgroup_subsys *ss;
1117 for_each_subsys(ss, i) {
1118 struct cftype *cfts;
1120 if (!(subsys_mask & (1 << i)))
1122 list_for_each_entry(cfts, &ss->cfts, node)
1123 cgroup_addrm_files(cgrp, cfts, false);
1127 static int rebind_subsystems(struct cgroup_root *dst_root, unsigned int ss_mask)
1129 struct cgroup_subsys *ss;
1132 lockdep_assert_held(&cgroup_mutex);
1134 for_each_subsys(ss, ssid) {
1135 if (!(ss_mask & (1 << ssid)))
1138 /* if @ss has non-root csses attached to it, can't move */
1139 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1142 /* can't move between two non-dummy roots either */
1143 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1147 ret = cgroup_populate_dir(&dst_root->cgrp, ss_mask);
1149 if (dst_root != &cgrp_dfl_root)
1153 * Rebinding back to the default root is not allowed to
1154 * fail. Using both default and non-default roots should
1155 * be rare. Moving subsystems back and forth even more so.
1156 * Just warn about it and continue.
1158 if (cgrp_dfl_root_visible) {
1159 pr_warn("failed to create files (%d) while rebinding 0x%x to default root\n",
1161 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1166 * Nothing can fail from this point on. Remove files for the
1167 * removed subsystems and rebind each subsystem.
1169 for_each_subsys(ss, ssid)
1170 if (ss_mask & (1 << ssid))
1171 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1173 for_each_subsys(ss, ssid) {
1174 struct cgroup_root *src_root;
1175 struct cgroup_subsys_state *css;
1176 struct css_set *cset;
1178 if (!(ss_mask & (1 << ssid)))
1181 src_root = ss->root;
1182 css = cgroup_css(&src_root->cgrp, ss);
1184 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1186 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1187 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1188 ss->root = dst_root;
1189 css->cgroup = &dst_root->cgrp;
1191 down_write(&css_set_rwsem);
1192 hash_for_each(css_set_table, i, cset, hlist)
1193 list_move_tail(&cset->e_cset_node[ss->id],
1194 &dst_root->cgrp.e_csets[ss->id]);
1195 up_write(&css_set_rwsem);
1197 src_root->subsys_mask &= ~(1 << ssid);
1198 src_root->cgrp.child_subsys_mask &= ~(1 << ssid);
1200 /* default hierarchy doesn't enable controllers by default */
1201 dst_root->subsys_mask |= 1 << ssid;
1202 if (dst_root != &cgrp_dfl_root)
1203 dst_root->cgrp.child_subsys_mask |= 1 << ssid;
1209 kernfs_activate(dst_root->cgrp.kn);
1213 static int cgroup_show_options(struct seq_file *seq,
1214 struct kernfs_root *kf_root)
1216 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1217 struct cgroup_subsys *ss;
1220 for_each_subsys(ss, ssid)
1221 if (root->subsys_mask & (1 << ssid))
1222 seq_printf(seq, ",%s", ss->name);
1223 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1224 seq_puts(seq, ",sane_behavior");
1225 if (root->flags & CGRP_ROOT_NOPREFIX)
1226 seq_puts(seq, ",noprefix");
1227 if (root->flags & CGRP_ROOT_XATTR)
1228 seq_puts(seq, ",xattr");
1230 spin_lock(&release_agent_path_lock);
1231 if (strlen(root->release_agent_path))
1232 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1233 spin_unlock(&release_agent_path_lock);
1235 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1236 seq_puts(seq, ",clone_children");
1237 if (strlen(root->name))
1238 seq_printf(seq, ",name=%s", root->name);
1242 struct cgroup_sb_opts {
1243 unsigned int subsys_mask;
1245 char *release_agent;
1246 bool cpuset_clone_children;
1248 /* User explicitly requested empty subsystem */
1252 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1254 char *token, *o = data;
1255 bool all_ss = false, one_ss = false;
1256 unsigned int mask = -1U;
1257 struct cgroup_subsys *ss;
1260 #ifdef CONFIG_CPUSETS
1261 mask = ~(1U << cpuset_cgrp_id);
1264 memset(opts, 0, sizeof(*opts));
1266 while ((token = strsep(&o, ",")) != NULL) {
1269 if (!strcmp(token, "none")) {
1270 /* Explicitly have no subsystems */
1274 if (!strcmp(token, "all")) {
1275 /* Mutually exclusive option 'all' + subsystem name */
1281 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1282 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1285 if (!strcmp(token, "noprefix")) {
1286 opts->flags |= CGRP_ROOT_NOPREFIX;
1289 if (!strcmp(token, "clone_children")) {
1290 opts->cpuset_clone_children = true;
1293 if (!strcmp(token, "xattr")) {
1294 opts->flags |= CGRP_ROOT_XATTR;
1297 if (!strncmp(token, "release_agent=", 14)) {
1298 /* Specifying two release agents is forbidden */
1299 if (opts->release_agent)
1301 opts->release_agent =
1302 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1303 if (!opts->release_agent)
1307 if (!strncmp(token, "name=", 5)) {
1308 const char *name = token + 5;
1309 /* Can't specify an empty name */
1312 /* Must match [\w.-]+ */
1313 for (i = 0; i < strlen(name); i++) {
1317 if ((c == '.') || (c == '-') || (c == '_'))
1321 /* Specifying two names is forbidden */
1324 opts->name = kstrndup(name,
1325 MAX_CGROUP_ROOT_NAMELEN - 1,
1333 for_each_subsys(ss, i) {
1334 if (strcmp(token, ss->name))
1339 /* Mutually exclusive option 'all' + subsystem name */
1342 opts->subsys_mask |= (1 << i);
1347 if (i == CGROUP_SUBSYS_COUNT)
1351 /* Consistency checks */
1353 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1354 pr_warn("sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1356 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1357 opts->cpuset_clone_children || opts->release_agent ||
1359 pr_err("sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1364 * If the 'all' option was specified select all the
1365 * subsystems, otherwise if 'none', 'name=' and a subsystem
1366 * name options were not specified, let's default to 'all'
1368 if (all_ss || (!one_ss && !opts->none && !opts->name))
1369 for_each_subsys(ss, i)
1371 opts->subsys_mask |= (1 << i);
1374 * We either have to specify by name or by subsystems. (So
1375 * all empty hierarchies must have a name).
1377 if (!opts->subsys_mask && !opts->name)
1382 * Option noprefix was introduced just for backward compatibility
1383 * with the old cpuset, so we allow noprefix only if mounting just
1384 * the cpuset subsystem.
1386 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1390 /* Can't specify "none" and some subsystems */
1391 if (opts->subsys_mask && opts->none)
1397 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1400 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1401 struct cgroup_sb_opts opts;
1402 unsigned int added_mask, removed_mask;
1404 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1405 pr_err("sane_behavior: remount is not allowed\n");
1409 mutex_lock(&cgroup_mutex);
1411 /* See what subsystems are wanted */
1412 ret = parse_cgroupfs_options(data, &opts);
1416 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1417 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1418 task_tgid_nr(current), current->comm);
1420 added_mask = opts.subsys_mask & ~root->subsys_mask;
1421 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1423 /* Don't allow flags or name to change at remount */
1424 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1425 (opts.name && strcmp(opts.name, root->name))) {
1426 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1427 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1428 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1433 /* remounting is not allowed for populated hierarchies */
1434 if (!list_empty(&root->cgrp.self.children)) {
1439 ret = rebind_subsystems(root, added_mask);
1443 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1445 if (opts.release_agent) {
1446 spin_lock(&release_agent_path_lock);
1447 strcpy(root->release_agent_path, opts.release_agent);
1448 spin_unlock(&release_agent_path_lock);
1451 kfree(opts.release_agent);
1453 mutex_unlock(&cgroup_mutex);
1458 * To reduce the fork() overhead for systems that are not actually using
1459 * their cgroups capability, we don't maintain the lists running through
1460 * each css_set to its tasks until we see the list actually used - in other
1461 * words after the first mount.
1463 static bool use_task_css_set_links __read_mostly;
1465 static void cgroup_enable_task_cg_lists(void)
1467 struct task_struct *p, *g;
1469 down_write(&css_set_rwsem);
1471 if (use_task_css_set_links)
1474 use_task_css_set_links = true;
1477 * We need tasklist_lock because RCU is not safe against
1478 * while_each_thread(). Besides, a forking task that has passed
1479 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1480 * is not guaranteed to have its child immediately visible in the
1481 * tasklist if we walk through it with RCU.
1483 read_lock(&tasklist_lock);
1484 do_each_thread(g, p) {
1485 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1486 task_css_set(p) != &init_css_set);
1489 * We should check if the process is exiting, otherwise
1490 * it will race with cgroup_exit() in that the list
1491 * entry won't be deleted though the process has exited.
1492 * Do it while holding siglock so that we don't end up
1493 * racing against cgroup_exit().
1495 spin_lock_irq(&p->sighand->siglock);
1496 if (!(p->flags & PF_EXITING)) {
1497 struct css_set *cset = task_css_set(p);
1499 list_add(&p->cg_list, &cset->tasks);
1502 spin_unlock_irq(&p->sighand->siglock);
1503 } while_each_thread(g, p);
1504 read_unlock(&tasklist_lock);
1506 up_write(&css_set_rwsem);
1509 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1511 struct cgroup_subsys *ss;
1514 INIT_LIST_HEAD(&cgrp->self.sibling);
1515 INIT_LIST_HEAD(&cgrp->self.children);
1516 INIT_LIST_HEAD(&cgrp->cset_links);
1517 INIT_LIST_HEAD(&cgrp->release_list);
1518 INIT_LIST_HEAD(&cgrp->pidlists);
1519 mutex_init(&cgrp->pidlist_mutex);
1520 cgrp->self.cgroup = cgrp;
1522 for_each_subsys(ss, ssid)
1523 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1525 init_waitqueue_head(&cgrp->offline_waitq);
1528 static void init_cgroup_root(struct cgroup_root *root,
1529 struct cgroup_sb_opts *opts)
1531 struct cgroup *cgrp = &root->cgrp;
1533 INIT_LIST_HEAD(&root->root_list);
1534 atomic_set(&root->nr_cgrps, 1);
1536 init_cgroup_housekeeping(cgrp);
1537 idr_init(&root->cgroup_idr);
1539 root->flags = opts->flags;
1540 if (opts->release_agent)
1541 strcpy(root->release_agent_path, opts->release_agent);
1543 strcpy(root->name, opts->name);
1544 if (opts->cpuset_clone_children)
1545 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1548 static int cgroup_setup_root(struct cgroup_root *root, unsigned int ss_mask)
1550 LIST_HEAD(tmp_links);
1551 struct cgroup *root_cgrp = &root->cgrp;
1552 struct css_set *cset;
1555 lockdep_assert_held(&cgroup_mutex);
1557 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_NOWAIT);
1560 root_cgrp->id = ret;
1562 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release);
1567 * We're accessing css_set_count without locking css_set_rwsem here,
1568 * but that's OK - it can only be increased by someone holding
1569 * cgroup_lock, and that's us. The worst that can happen is that we
1570 * have some link structures left over
1572 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1576 ret = cgroup_init_root_id(root);
1580 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1581 KERNFS_ROOT_CREATE_DEACTIVATED,
1583 if (IS_ERR(root->kf_root)) {
1584 ret = PTR_ERR(root->kf_root);
1587 root_cgrp->kn = root->kf_root->kn;
1589 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1593 ret = rebind_subsystems(root, ss_mask);
1598 * There must be no failure case after here, since rebinding takes
1599 * care of subsystems' refcounts, which are explicitly dropped in
1600 * the failure exit path.
1602 list_add(&root->root_list, &cgroup_roots);
1603 cgroup_root_count++;
1606 * Link the root cgroup in this hierarchy into all the css_set
1609 down_write(&css_set_rwsem);
1610 hash_for_each(css_set_table, i, cset, hlist)
1611 link_css_set(&tmp_links, cset, root_cgrp);
1612 up_write(&css_set_rwsem);
1614 BUG_ON(!list_empty(&root_cgrp->self.children));
1615 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1617 kernfs_activate(root_cgrp->kn);
1622 kernfs_destroy_root(root->kf_root);
1623 root->kf_root = NULL;
1625 cgroup_exit_root_id(root);
1627 percpu_ref_cancel_init(&root_cgrp->self.refcnt);
1629 free_cgrp_cset_links(&tmp_links);
1633 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1634 int flags, const char *unused_dev_name,
1637 struct cgroup_root *root;
1638 struct cgroup_sb_opts opts;
1639 struct dentry *dentry;
1644 * The first time anyone tries to mount a cgroup, enable the list
1645 * linking each css_set to its tasks and fix up all existing tasks.
1647 if (!use_task_css_set_links)
1648 cgroup_enable_task_cg_lists();
1650 mutex_lock(&cgroup_mutex);
1652 /* First find the desired set of subsystems */
1653 ret = parse_cgroupfs_options(data, &opts);
1657 /* look for a matching existing root */
1658 if (!opts.subsys_mask && !opts.none && !opts.name) {
1659 cgrp_dfl_root_visible = true;
1660 root = &cgrp_dfl_root;
1661 cgroup_get(&root->cgrp);
1666 for_each_root(root) {
1667 bool name_match = false;
1669 if (root == &cgrp_dfl_root)
1673 * If we asked for a name then it must match. Also, if
1674 * name matches but sybsys_mask doesn't, we should fail.
1675 * Remember whether name matched.
1678 if (strcmp(opts.name, root->name))
1684 * If we asked for subsystems (or explicitly for no
1685 * subsystems) then they must match.
1687 if ((opts.subsys_mask || opts.none) &&
1688 (opts.subsys_mask != root->subsys_mask)) {
1695 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1696 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1697 pr_err("sane_behavior: new mount options should match the existing superblock\n");
1701 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1706 * A root's lifetime is governed by its root cgroup.
1707 * tryget_live failure indicate that the root is being
1708 * destroyed. Wait for destruction to complete so that the
1709 * subsystems are free. We can use wait_queue for the wait
1710 * but this path is super cold. Let's just sleep for a bit
1713 if (!percpu_ref_tryget_live(&root->cgrp.self.refcnt)) {
1714 mutex_unlock(&cgroup_mutex);
1716 ret = restart_syscall();
1725 * No such thing, create a new one. name= matching without subsys
1726 * specification is allowed for already existing hierarchies but we
1727 * can't create new one without subsys specification.
1729 if (!opts.subsys_mask && !opts.none) {
1734 root = kzalloc(sizeof(*root), GFP_KERNEL);
1740 init_cgroup_root(root, &opts);
1742 ret = cgroup_setup_root(root, opts.subsys_mask);
1744 cgroup_free_root(root);
1747 mutex_unlock(&cgroup_mutex);
1749 kfree(opts.release_agent);
1753 return ERR_PTR(ret);
1755 dentry = kernfs_mount(fs_type, flags, root->kf_root, &new_sb);
1756 if (IS_ERR(dentry) || !new_sb)
1757 cgroup_put(&root->cgrp);
1761 static void cgroup_kill_sb(struct super_block *sb)
1763 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1764 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1767 * If @root doesn't have any mounts or children, start killing it.
1768 * This prevents new mounts by disabling percpu_ref_tryget_live().
1769 * cgroup_mount() may wait for @root's release.
1771 if (cgroup_has_live_children(&root->cgrp))
1772 cgroup_put(&root->cgrp);
1774 percpu_ref_kill(&root->cgrp.self.refcnt);
1779 static struct file_system_type cgroup_fs_type = {
1781 .mount = cgroup_mount,
1782 .kill_sb = cgroup_kill_sb,
1785 static struct kobject *cgroup_kobj;
1788 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1789 * @task: target task
1790 * @buf: the buffer to write the path into
1791 * @buflen: the length of the buffer
1793 * Determine @task's cgroup on the first (the one with the lowest non-zero
1794 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1795 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1796 * cgroup controller callbacks.
1798 * Return value is the same as kernfs_path().
1800 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1802 struct cgroup_root *root;
1803 struct cgroup *cgrp;
1804 int hierarchy_id = 1;
1807 mutex_lock(&cgroup_mutex);
1808 down_read(&css_set_rwsem);
1810 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1813 cgrp = task_cgroup_from_root(task, root);
1814 path = cgroup_path(cgrp, buf, buflen);
1816 /* if no hierarchy exists, everyone is in "/" */
1817 if (strlcpy(buf, "/", buflen) < buflen)
1821 up_read(&css_set_rwsem);
1822 mutex_unlock(&cgroup_mutex);
1825 EXPORT_SYMBOL_GPL(task_cgroup_path);
1827 /* used to track tasks and other necessary states during migration */
1828 struct cgroup_taskset {
1829 /* the src and dst cset list running through cset->mg_node */
1830 struct list_head src_csets;
1831 struct list_head dst_csets;
1834 * Fields for cgroup_taskset_*() iteration.
1836 * Before migration is committed, the target migration tasks are on
1837 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1838 * the csets on ->dst_csets. ->csets point to either ->src_csets
1839 * or ->dst_csets depending on whether migration is committed.
1841 * ->cur_csets and ->cur_task point to the current task position
1844 struct list_head *csets;
1845 struct css_set *cur_cset;
1846 struct task_struct *cur_task;
1850 * cgroup_taskset_first - reset taskset and return the first task
1851 * @tset: taskset of interest
1853 * @tset iteration is initialized and the first task is returned.
1855 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1857 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1858 tset->cur_task = NULL;
1860 return cgroup_taskset_next(tset);
1864 * cgroup_taskset_next - iterate to the next task in taskset
1865 * @tset: taskset of interest
1867 * Return the next task in @tset. Iteration must have been initialized
1868 * with cgroup_taskset_first().
1870 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1872 struct css_set *cset = tset->cur_cset;
1873 struct task_struct *task = tset->cur_task;
1875 while (&cset->mg_node != tset->csets) {
1877 task = list_first_entry(&cset->mg_tasks,
1878 struct task_struct, cg_list);
1880 task = list_next_entry(task, cg_list);
1882 if (&task->cg_list != &cset->mg_tasks) {
1883 tset->cur_cset = cset;
1884 tset->cur_task = task;
1888 cset = list_next_entry(cset, mg_node);
1896 * cgroup_task_migrate - move a task from one cgroup to another.
1897 * @old_cgrp: the cgroup @tsk is being migrated from
1898 * @tsk: the task being migrated
1899 * @new_cset: the new css_set @tsk is being attached to
1901 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1903 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1904 struct task_struct *tsk,
1905 struct css_set *new_cset)
1907 struct css_set *old_cset;
1909 lockdep_assert_held(&cgroup_mutex);
1910 lockdep_assert_held(&css_set_rwsem);
1913 * We are synchronized through threadgroup_lock() against PF_EXITING
1914 * setting such that we can't race against cgroup_exit() changing the
1915 * css_set to init_css_set and dropping the old one.
1917 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1918 old_cset = task_css_set(tsk);
1920 get_css_set(new_cset);
1921 rcu_assign_pointer(tsk->cgroups, new_cset);
1924 * Use move_tail so that cgroup_taskset_first() still returns the
1925 * leader after migration. This works because cgroup_migrate()
1926 * ensures that the dst_cset of the leader is the first on the
1927 * tset's dst_csets list.
1929 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
1932 * We just gained a reference on old_cset by taking it from the
1933 * task. As trading it for new_cset is protected by cgroup_mutex,
1934 * we're safe to drop it here; it will be freed under RCU.
1936 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1937 put_css_set_locked(old_cset, false);
1941 * cgroup_migrate_finish - cleanup after attach
1942 * @preloaded_csets: list of preloaded css_sets
1944 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1945 * those functions for details.
1947 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1949 struct css_set *cset, *tmp_cset;
1951 lockdep_assert_held(&cgroup_mutex);
1953 down_write(&css_set_rwsem);
1954 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1955 cset->mg_src_cgrp = NULL;
1956 cset->mg_dst_cset = NULL;
1957 list_del_init(&cset->mg_preload_node);
1958 put_css_set_locked(cset, false);
1960 up_write(&css_set_rwsem);
1964 * cgroup_migrate_add_src - add a migration source css_set
1965 * @src_cset: the source css_set to add
1966 * @dst_cgrp: the destination cgroup
1967 * @preloaded_csets: list of preloaded css_sets
1969 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1970 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1971 * up by cgroup_migrate_finish().
1973 * This function may be called without holding threadgroup_lock even if the
1974 * target is a process. Threads may be created and destroyed but as long
1975 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1976 * the preloaded css_sets are guaranteed to cover all migrations.
1978 static void cgroup_migrate_add_src(struct css_set *src_cset,
1979 struct cgroup *dst_cgrp,
1980 struct list_head *preloaded_csets)
1982 struct cgroup *src_cgrp;
1984 lockdep_assert_held(&cgroup_mutex);
1985 lockdep_assert_held(&css_set_rwsem);
1987 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
1989 if (!list_empty(&src_cset->mg_preload_node))
1992 WARN_ON(src_cset->mg_src_cgrp);
1993 WARN_ON(!list_empty(&src_cset->mg_tasks));
1994 WARN_ON(!list_empty(&src_cset->mg_node));
1996 src_cset->mg_src_cgrp = src_cgrp;
1997 get_css_set(src_cset);
1998 list_add(&src_cset->mg_preload_node, preloaded_csets);
2002 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2003 * @dst_cgrp: the destination cgroup (may be %NULL)
2004 * @preloaded_csets: list of preloaded source css_sets
2006 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
2007 * have been preloaded to @preloaded_csets. This function looks up and
2008 * pins all destination css_sets, links each to its source, and append them
2009 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
2010 * source css_set is assumed to be its cgroup on the default hierarchy.
2012 * This function must be called after cgroup_migrate_add_src() has been
2013 * called on each migration source css_set. After migration is performed
2014 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2017 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
2018 struct list_head *preloaded_csets)
2021 struct css_set *src_cset, *tmp_cset;
2023 lockdep_assert_held(&cgroup_mutex);
2026 * Except for the root, child_subsys_mask must be zero for a cgroup
2027 * with tasks so that child cgroups don't compete against tasks.
2029 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && cgroup_parent(dst_cgrp) &&
2030 dst_cgrp->child_subsys_mask)
2033 /* look up the dst cset for each src cset and link it to src */
2034 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2035 struct css_set *dst_cset;
2037 dst_cset = find_css_set(src_cset,
2038 dst_cgrp ?: src_cset->dfl_cgrp);
2042 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2045 * If src cset equals dst, it's noop. Drop the src.
2046 * cgroup_migrate() will skip the cset too. Note that we
2047 * can't handle src == dst as some nodes are used by both.
2049 if (src_cset == dst_cset) {
2050 src_cset->mg_src_cgrp = NULL;
2051 list_del_init(&src_cset->mg_preload_node);
2052 put_css_set(src_cset, false);
2053 put_css_set(dst_cset, false);
2057 src_cset->mg_dst_cset = dst_cset;
2059 if (list_empty(&dst_cset->mg_preload_node))
2060 list_add(&dst_cset->mg_preload_node, &csets);
2062 put_css_set(dst_cset, false);
2065 list_splice_tail(&csets, preloaded_csets);
2068 cgroup_migrate_finish(&csets);
2073 * cgroup_migrate - migrate a process or task to a cgroup
2074 * @cgrp: the destination cgroup
2075 * @leader: the leader of the process or the task to migrate
2076 * @threadgroup: whether @leader points to the whole process or a single task
2078 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2079 * process, the caller must be holding threadgroup_lock of @leader. The
2080 * caller is also responsible for invoking cgroup_migrate_add_src() and
2081 * cgroup_migrate_prepare_dst() on the targets before invoking this
2082 * function and following up with cgroup_migrate_finish().
2084 * As long as a controller's ->can_attach() doesn't fail, this function is
2085 * guaranteed to succeed. This means that, excluding ->can_attach()
2086 * failure, when migrating multiple targets, the success or failure can be
2087 * decided for all targets by invoking group_migrate_prepare_dst() before
2088 * actually starting migrating.
2090 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
2093 struct cgroup_taskset tset = {
2094 .src_csets = LIST_HEAD_INIT(tset.src_csets),
2095 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
2096 .csets = &tset.src_csets,
2098 struct cgroup_subsys_state *css, *failed_css = NULL;
2099 struct css_set *cset, *tmp_cset;
2100 struct task_struct *task, *tmp_task;
2104 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2105 * already PF_EXITING could be freed from underneath us unless we
2106 * take an rcu_read_lock.
2108 down_write(&css_set_rwsem);
2112 /* @task either already exited or can't exit until the end */
2113 if (task->flags & PF_EXITING)
2116 /* leave @task alone if post_fork() hasn't linked it yet */
2117 if (list_empty(&task->cg_list))
2120 cset = task_css_set(task);
2121 if (!cset->mg_src_cgrp)
2125 * cgroup_taskset_first() must always return the leader.
2126 * Take care to avoid disturbing the ordering.
2128 list_move_tail(&task->cg_list, &cset->mg_tasks);
2129 if (list_empty(&cset->mg_node))
2130 list_add_tail(&cset->mg_node, &tset.src_csets);
2131 if (list_empty(&cset->mg_dst_cset->mg_node))
2132 list_move_tail(&cset->mg_dst_cset->mg_node,
2137 } while_each_thread(leader, task);
2139 up_write(&css_set_rwsem);
2141 /* methods shouldn't be called if no task is actually migrating */
2142 if (list_empty(&tset.src_csets))
2145 /* check that we can legitimately attach to the cgroup */
2146 for_each_e_css(css, i, cgrp) {
2147 if (css->ss->can_attach) {
2148 ret = css->ss->can_attach(css, &tset);
2151 goto out_cancel_attach;
2157 * Now that we're guaranteed success, proceed to move all tasks to
2158 * the new cgroup. There are no failure cases after here, so this
2159 * is the commit point.
2161 down_write(&css_set_rwsem);
2162 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2163 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2164 cgroup_task_migrate(cset->mg_src_cgrp, task,
2167 up_write(&css_set_rwsem);
2170 * Migration is committed, all target tasks are now on dst_csets.
2171 * Nothing is sensitive to fork() after this point. Notify
2172 * controllers that migration is complete.
2174 tset.csets = &tset.dst_csets;
2176 for_each_e_css(css, i, cgrp)
2177 if (css->ss->attach)
2178 css->ss->attach(css, &tset);
2181 goto out_release_tset;
2184 for_each_e_css(css, i, cgrp) {
2185 if (css == failed_css)
2187 if (css->ss->cancel_attach)
2188 css->ss->cancel_attach(css, &tset);
2191 down_write(&css_set_rwsem);
2192 list_splice_init(&tset.dst_csets, &tset.src_csets);
2193 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2194 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2195 list_del_init(&cset->mg_node);
2197 up_write(&css_set_rwsem);
2202 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2203 * @dst_cgrp: the cgroup to attach to
2204 * @leader: the task or the leader of the threadgroup to be attached
2205 * @threadgroup: attach the whole threadgroup?
2207 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2209 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2210 struct task_struct *leader, bool threadgroup)
2212 LIST_HEAD(preloaded_csets);
2213 struct task_struct *task;
2216 /* look up all src csets */
2217 down_read(&css_set_rwsem);
2221 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2225 } while_each_thread(leader, task);
2227 up_read(&css_set_rwsem);
2229 /* prepare dst csets and commit */
2230 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2232 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2234 cgroup_migrate_finish(&preloaded_csets);
2239 * Find the task_struct of the task to attach by vpid and pass it along to the
2240 * function to attach either it or all tasks in its threadgroup. Will lock
2241 * cgroup_mutex and threadgroup.
2243 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
2244 size_t nbytes, loff_t off, bool threadgroup)
2246 struct task_struct *tsk;
2247 const struct cred *cred = current_cred(), *tcred;
2248 struct cgroup *cgrp;
2252 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2255 cgrp = cgroup_kn_lock_live(of->kn);
2262 tsk = find_task_by_vpid(pid);
2266 goto out_unlock_cgroup;
2269 * even if we're attaching all tasks in the thread group, we
2270 * only need to check permissions on one of them.
2272 tcred = __task_cred(tsk);
2273 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2274 !uid_eq(cred->euid, tcred->uid) &&
2275 !uid_eq(cred->euid, tcred->suid)) {
2278 goto out_unlock_cgroup;
2284 tsk = tsk->group_leader;
2287 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2288 * trapped in a cpuset, or RT worker may be born in a cgroup
2289 * with no rt_runtime allocated. Just say no.
2291 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2294 goto out_unlock_cgroup;
2297 get_task_struct(tsk);
2300 threadgroup_lock(tsk);
2302 if (!thread_group_leader(tsk)) {
2304 * a race with de_thread from another thread's exec()
2305 * may strip us of our leadership, if this happens,
2306 * there is no choice but to throw this task away and
2307 * try again; this is
2308 * "double-double-toil-and-trouble-check locking".
2310 threadgroup_unlock(tsk);
2311 put_task_struct(tsk);
2312 goto retry_find_task;
2316 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2318 threadgroup_unlock(tsk);
2320 put_task_struct(tsk);
2322 cgroup_kn_unlock(of->kn);
2323 return ret ?: nbytes;
2327 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2328 * @from: attach to all cgroups of a given task
2329 * @tsk: the task to be attached
2331 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2333 struct cgroup_root *root;
2336 mutex_lock(&cgroup_mutex);
2337 for_each_root(root) {
2338 struct cgroup *from_cgrp;
2340 if (root == &cgrp_dfl_root)
2343 down_read(&css_set_rwsem);
2344 from_cgrp = task_cgroup_from_root(from, root);
2345 up_read(&css_set_rwsem);
2347 retval = cgroup_attach_task(from_cgrp, tsk, false);
2351 mutex_unlock(&cgroup_mutex);
2355 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2357 static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
2358 char *buf, size_t nbytes, loff_t off)
2360 return __cgroup_procs_write(of, buf, nbytes, off, false);
2363 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
2364 char *buf, size_t nbytes, loff_t off)
2366 return __cgroup_procs_write(of, buf, nbytes, off, true);
2369 static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
2370 char *buf, size_t nbytes, loff_t off)
2372 struct cgroup *cgrp;
2374 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2376 cgrp = cgroup_kn_lock_live(of->kn);
2379 spin_lock(&release_agent_path_lock);
2380 strlcpy(cgrp->root->release_agent_path, strstrip(buf),
2381 sizeof(cgrp->root->release_agent_path));
2382 spin_unlock(&release_agent_path_lock);
2383 cgroup_kn_unlock(of->kn);
2387 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2389 struct cgroup *cgrp = seq_css(seq)->cgroup;
2391 spin_lock(&release_agent_path_lock);
2392 seq_puts(seq, cgrp->root->release_agent_path);
2393 spin_unlock(&release_agent_path_lock);
2394 seq_putc(seq, '\n');
2398 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2400 struct cgroup *cgrp = seq_css(seq)->cgroup;
2402 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2406 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned int ss_mask)
2408 struct cgroup_subsys *ss;
2409 bool printed = false;
2412 for_each_subsys(ss, ssid) {
2413 if (ss_mask & (1 << ssid)) {
2416 seq_printf(seq, "%s", ss->name);
2421 seq_putc(seq, '\n');
2424 /* show controllers which are currently attached to the default hierarchy */
2425 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2427 struct cgroup *cgrp = seq_css(seq)->cgroup;
2429 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask);
2433 /* show controllers which are enabled from the parent */
2434 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2436 struct cgroup *cgrp = seq_css(seq)->cgroup;
2438 cgroup_print_ss_mask(seq, cgroup_parent(cgrp)->child_subsys_mask);
2442 /* show controllers which are enabled for a given cgroup's children */
2443 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2445 struct cgroup *cgrp = seq_css(seq)->cgroup;
2447 cgroup_print_ss_mask(seq, cgrp->child_subsys_mask);
2452 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2453 * @cgrp: root of the subtree to update csses for
2455 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2456 * css associations need to be updated accordingly. This function looks up
2457 * all css_sets which are attached to the subtree, creates the matching
2458 * updated css_sets and migrates the tasks to the new ones.
2460 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2462 LIST_HEAD(preloaded_csets);
2463 struct cgroup_subsys_state *css;
2464 struct css_set *src_cset;
2467 lockdep_assert_held(&cgroup_mutex);
2469 /* look up all csses currently attached to @cgrp's subtree */
2470 down_read(&css_set_rwsem);
2471 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2472 struct cgrp_cset_link *link;
2474 /* self is not affected by child_subsys_mask change */
2475 if (css->cgroup == cgrp)
2478 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2479 cgroup_migrate_add_src(link->cset, cgrp,
2482 up_read(&css_set_rwsem);
2484 /* NULL dst indicates self on default hierarchy */
2485 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2489 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2490 struct task_struct *last_task = NULL, *task;
2492 /* src_csets precede dst_csets, break on the first dst_cset */
2493 if (!src_cset->mg_src_cgrp)
2497 * All tasks in src_cset need to be migrated to the
2498 * matching dst_cset. Empty it process by process. We
2499 * walk tasks but migrate processes. The leader might even
2500 * belong to a different cset but such src_cset would also
2501 * be among the target src_csets because the default
2502 * hierarchy enforces per-process membership.
2505 down_read(&css_set_rwsem);
2506 task = list_first_entry_or_null(&src_cset->tasks,
2507 struct task_struct, cg_list);
2509 task = task->group_leader;
2510 WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
2511 get_task_struct(task);
2513 up_read(&css_set_rwsem);
2518 /* guard against possible infinite loop */
2519 if (WARN(last_task == task,
2520 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2524 threadgroup_lock(task);
2525 /* raced against de_thread() from another thread? */
2526 if (!thread_group_leader(task)) {
2527 threadgroup_unlock(task);
2528 put_task_struct(task);
2532 ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
2534 threadgroup_unlock(task);
2535 put_task_struct(task);
2537 if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
2543 cgroup_migrate_finish(&preloaded_csets);
2547 /* change the enabled child controllers for a cgroup in the default hierarchy */
2548 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
2549 char *buf, size_t nbytes,
2552 unsigned int enable = 0, disable = 0;
2553 struct cgroup *cgrp, *child;
2554 struct cgroup_subsys *ss;
2559 * Parse input - space separated list of subsystem names prefixed
2560 * with either + or -.
2562 buf = strstrip(buf);
2563 while ((tok = strsep(&buf, " "))) {
2566 for_each_subsys(ss, ssid) {
2567 if (ss->disabled || strcmp(tok + 1, ss->name))
2571 enable |= 1 << ssid;
2572 disable &= ~(1 << ssid);
2573 } else if (*tok == '-') {
2574 disable |= 1 << ssid;
2575 enable &= ~(1 << ssid);
2581 if (ssid == CGROUP_SUBSYS_COUNT)
2585 cgrp = cgroup_kn_lock_live(of->kn);
2589 for_each_subsys(ss, ssid) {
2590 if (enable & (1 << ssid)) {
2591 if (cgrp->child_subsys_mask & (1 << ssid)) {
2592 enable &= ~(1 << ssid);
2597 * Because css offlining is asynchronous, userland
2598 * might try to re-enable the same controller while
2599 * the previous instance is still around. In such
2600 * cases, wait till it's gone using offline_waitq.
2602 cgroup_for_each_live_child(child, cgrp) {
2605 if (!cgroup_css(child, ss))
2609 prepare_to_wait(&child->offline_waitq, &wait,
2610 TASK_UNINTERRUPTIBLE);
2611 cgroup_kn_unlock(of->kn);
2613 finish_wait(&child->offline_waitq, &wait);
2616 return restart_syscall();
2619 /* unavailable or not enabled on the parent? */
2620 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2621 (cgroup_parent(cgrp) &&
2622 !(cgroup_parent(cgrp)->child_subsys_mask & (1 << ssid)))) {
2626 } else if (disable & (1 << ssid)) {
2627 if (!(cgrp->child_subsys_mask & (1 << ssid))) {
2628 disable &= ~(1 << ssid);
2632 /* a child has it enabled? */
2633 cgroup_for_each_live_child(child, cgrp) {
2634 if (child->child_subsys_mask & (1 << ssid)) {
2642 if (!enable && !disable) {
2648 * Except for the root, child_subsys_mask must be zero for a cgroup
2649 * with tasks so that child cgroups don't compete against tasks.
2651 if (enable && cgroup_parent(cgrp) && !list_empty(&cgrp->cset_links)) {
2657 * Create csses for enables and update child_subsys_mask. This
2658 * changes cgroup_e_css() results which in turn makes the
2659 * subsequent cgroup_update_dfl_csses() associate all tasks in the
2660 * subtree to the updated csses.
2662 for_each_subsys(ss, ssid) {
2663 if (!(enable & (1 << ssid)))
2666 cgroup_for_each_live_child(child, cgrp) {
2667 ret = create_css(child, ss);
2673 cgrp->child_subsys_mask |= enable;
2674 cgrp->child_subsys_mask &= ~disable;
2676 ret = cgroup_update_dfl_csses(cgrp);
2680 /* all tasks are now migrated away from the old csses, kill them */
2681 for_each_subsys(ss, ssid) {
2682 if (!(disable & (1 << ssid)))
2685 cgroup_for_each_live_child(child, cgrp)
2686 kill_css(cgroup_css(child, ss));
2689 kernfs_activate(cgrp->kn);
2692 cgroup_kn_unlock(of->kn);
2693 return ret ?: nbytes;
2696 cgrp->child_subsys_mask &= ~enable;
2697 cgrp->child_subsys_mask |= disable;
2699 for_each_subsys(ss, ssid) {
2700 if (!(enable & (1 << ssid)))
2703 cgroup_for_each_live_child(child, cgrp) {
2704 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2712 static int cgroup_populated_show(struct seq_file *seq, void *v)
2714 seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
2718 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2719 size_t nbytes, loff_t off)
2721 struct cgroup *cgrp = of->kn->parent->priv;
2722 struct cftype *cft = of->kn->priv;
2723 struct cgroup_subsys_state *css;
2727 return cft->write(of, buf, nbytes, off);
2730 * kernfs guarantees that a file isn't deleted with operations in
2731 * flight, which means that the matching css is and stays alive and
2732 * doesn't need to be pinned. The RCU locking is not necessary
2733 * either. It's just for the convenience of using cgroup_css().
2736 css = cgroup_css(cgrp, cft->ss);
2739 if (cft->write_u64) {
2740 unsigned long long v;
2741 ret = kstrtoull(buf, 0, &v);
2743 ret = cft->write_u64(css, cft, v);
2744 } else if (cft->write_s64) {
2746 ret = kstrtoll(buf, 0, &v);
2748 ret = cft->write_s64(css, cft, v);
2753 return ret ?: nbytes;
2756 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2758 return seq_cft(seq)->seq_start(seq, ppos);
2761 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2763 return seq_cft(seq)->seq_next(seq, v, ppos);
2766 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2768 seq_cft(seq)->seq_stop(seq, v);
2771 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2773 struct cftype *cft = seq_cft(m);
2774 struct cgroup_subsys_state *css = seq_css(m);
2777 return cft->seq_show(m, arg);
2780 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2781 else if (cft->read_s64)
2782 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2788 static struct kernfs_ops cgroup_kf_single_ops = {
2789 .atomic_write_len = PAGE_SIZE,
2790 .write = cgroup_file_write,
2791 .seq_show = cgroup_seqfile_show,
2794 static struct kernfs_ops cgroup_kf_ops = {
2795 .atomic_write_len = PAGE_SIZE,
2796 .write = cgroup_file_write,
2797 .seq_start = cgroup_seqfile_start,
2798 .seq_next = cgroup_seqfile_next,
2799 .seq_stop = cgroup_seqfile_stop,
2800 .seq_show = cgroup_seqfile_show,
2804 * cgroup_rename - Only allow simple rename of directories in place.
2806 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2807 const char *new_name_str)
2809 struct cgroup *cgrp = kn->priv;
2812 if (kernfs_type(kn) != KERNFS_DIR)
2814 if (kn->parent != new_parent)
2818 * This isn't a proper migration and its usefulness is very
2819 * limited. Disallow if sane_behavior.
2821 if (cgroup_sane_behavior(cgrp))
2825 * We're gonna grab cgroup_mutex which nests outside kernfs
2826 * active_ref. kernfs_rename() doesn't require active_ref
2827 * protection. Break them before grabbing cgroup_mutex.
2829 kernfs_break_active_protection(new_parent);
2830 kernfs_break_active_protection(kn);
2832 mutex_lock(&cgroup_mutex);
2834 ret = kernfs_rename(kn, new_parent, new_name_str);
2836 mutex_unlock(&cgroup_mutex);
2838 kernfs_unbreak_active_protection(kn);
2839 kernfs_unbreak_active_protection(new_parent);
2843 /* set uid and gid of cgroup dirs and files to that of the creator */
2844 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
2846 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
2847 .ia_uid = current_fsuid(),
2848 .ia_gid = current_fsgid(), };
2850 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
2851 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
2854 return kernfs_setattr(kn, &iattr);
2857 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2859 char name[CGROUP_FILE_NAME_MAX];
2860 struct kernfs_node *kn;
2861 struct lock_class_key *key = NULL;
2864 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2865 key = &cft->lockdep_key;
2867 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2868 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2873 ret = cgroup_kn_set_ugid(kn);
2879 if (cft->seq_show == cgroup_populated_show)
2880 cgrp->populated_kn = kn;
2885 * cgroup_addrm_files - add or remove files to a cgroup directory
2886 * @cgrp: the target cgroup
2887 * @cfts: array of cftypes to be added
2888 * @is_add: whether to add or remove
2890 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2891 * For removals, this function never fails. If addition fails, this
2892 * function doesn't remove files already added. The caller is responsible
2895 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2901 lockdep_assert_held(&cgroup_mutex);
2903 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2904 /* does cft->flags tell us to skip this file on @cgrp? */
2905 if ((cft->flags & CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
2907 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2909 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
2911 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
2915 ret = cgroup_add_file(cgrp, cft);
2917 pr_warn("%s: failed to add %s, err=%d\n",
2918 __func__, cft->name, ret);
2922 cgroup_rm_file(cgrp, cft);
2928 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2931 struct cgroup_subsys *ss = cfts[0].ss;
2932 struct cgroup *root = &ss->root->cgrp;
2933 struct cgroup_subsys_state *css;
2936 lockdep_assert_held(&cgroup_mutex);
2938 /* add/rm files for all cgroups created before */
2939 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2940 struct cgroup *cgrp = css->cgroup;
2942 if (cgroup_is_dead(cgrp))
2945 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2951 kernfs_activate(root->kn);
2955 static void cgroup_exit_cftypes(struct cftype *cfts)
2959 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2960 /* free copy for custom atomic_write_len, see init_cftypes() */
2961 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2968 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2972 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2973 struct kernfs_ops *kf_ops;
2975 WARN_ON(cft->ss || cft->kf_ops);
2978 kf_ops = &cgroup_kf_ops;
2980 kf_ops = &cgroup_kf_single_ops;
2983 * Ugh... if @cft wants a custom max_write_len, we need to
2984 * make a copy of kf_ops to set its atomic_write_len.
2986 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2987 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
2989 cgroup_exit_cftypes(cfts);
2992 kf_ops->atomic_write_len = cft->max_write_len;
2995 cft->kf_ops = kf_ops;
3002 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3004 lockdep_assert_held(&cgroup_mutex);
3006 if (!cfts || !cfts[0].ss)
3009 list_del(&cfts->node);
3010 cgroup_apply_cftypes(cfts, false);
3011 cgroup_exit_cftypes(cfts);
3016 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3017 * @cfts: zero-length name terminated array of cftypes
3019 * Unregister @cfts. Files described by @cfts are removed from all
3020 * existing cgroups and all future cgroups won't have them either. This
3021 * function can be called anytime whether @cfts' subsys is attached or not.
3023 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3026 int cgroup_rm_cftypes(struct cftype *cfts)
3030 mutex_lock(&cgroup_mutex);
3031 ret = cgroup_rm_cftypes_locked(cfts);
3032 mutex_unlock(&cgroup_mutex);
3037 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3038 * @ss: target cgroup subsystem
3039 * @cfts: zero-length name terminated array of cftypes
3041 * Register @cfts to @ss. Files described by @cfts are created for all
3042 * existing cgroups to which @ss is attached and all future cgroups will
3043 * have them too. This function can be called anytime whether @ss is
3046 * Returns 0 on successful registration, -errno on failure. Note that this
3047 * function currently returns 0 as long as @cfts registration is successful
3048 * even if some file creation attempts on existing cgroups fail.
3050 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3054 if (!cfts || cfts[0].name[0] == '\0')
3057 ret = cgroup_init_cftypes(ss, cfts);
3061 mutex_lock(&cgroup_mutex);
3063 list_add_tail(&cfts->node, &ss->cfts);
3064 ret = cgroup_apply_cftypes(cfts, true);
3066 cgroup_rm_cftypes_locked(cfts);
3068 mutex_unlock(&cgroup_mutex);
3073 * cgroup_task_count - count the number of tasks in a cgroup.
3074 * @cgrp: the cgroup in question
3076 * Return the number of tasks in the cgroup.
3078 static int cgroup_task_count(const struct cgroup *cgrp)
3081 struct cgrp_cset_link *link;
3083 down_read(&css_set_rwsem);
3084 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3085 count += atomic_read(&link->cset->refcount);
3086 up_read(&css_set_rwsem);
3091 * css_next_child - find the next child of a given css
3092 * @pos_css: the current position (%NULL to initiate traversal)
3093 * @parent_css: css whose children to walk
3095 * This function returns the next child of @parent_css and should be called
3096 * under either cgroup_mutex or RCU read lock. The only requirement is
3097 * that @parent_css and @pos_css are accessible. The next sibling is
3098 * guaranteed to be returned regardless of their states.
3100 struct cgroup_subsys_state *
3101 css_next_child(struct cgroup_subsys_state *pos_css,
3102 struct cgroup_subsys_state *parent_css)
3104 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3105 struct cgroup *cgrp = parent_css->cgroup;
3106 struct cgroup *next;
3108 cgroup_assert_mutex_or_rcu_locked();
3111 * @pos could already have been unlinked from the sibling list.
3112 * Once a cgroup is removed, its ->sibling.next is no longer
3113 * updated when its next sibling changes. CSS_RELEASED is set when
3114 * @pos is taken off list, at which time its next pointer is valid,
3115 * and, as releases are serialized, the one pointed to by the next
3116 * pointer is guaranteed to not have started release yet. This
3117 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3118 * critical section, the one pointed to by its next pointer is
3119 * guaranteed to not have finished its RCU grace period even if we
3120 * have dropped rcu_read_lock() inbetween iterations.
3122 * If @pos has CSS_RELEASED set, its next pointer can't be
3123 * dereferenced; however, as each css is given a monotonically
3124 * increasing unique serial number and always appended to the
3125 * sibling list, the next one can be found by walking the parent's
3126 * children until the first css with higher serial number than
3127 * @pos's. While this path can be slower, it happens iff iteration
3128 * races against release and the race window is very small.
3131 next = list_entry_rcu(cgrp->self.children.next, struct cgroup, self.sibling);
3132 } else if (likely(!(pos->self.flags & CSS_RELEASED))) {
3133 next = list_entry_rcu(pos->self.sibling.next, struct cgroup, self.sibling);
3135 list_for_each_entry_rcu(next, &cgrp->self.children, self.sibling)
3136 if (next->self.serial_nr > pos->self.serial_nr)
3141 * @next, if not pointing to the head, can be dereferenced and is
3142 * the next sibling; however, it might have @ss disabled. If so,
3143 * fast-forward to the next enabled one.
3145 while (&next->self.sibling != &cgrp->self.children) {
3146 struct cgroup_subsys_state *next_css = cgroup_css(next, parent_css->ss);
3150 next = list_entry_rcu(next->self.sibling.next, struct cgroup, self.sibling);
3156 * css_next_descendant_pre - find the next descendant for pre-order walk
3157 * @pos: the current position (%NULL to initiate traversal)
3158 * @root: css whose descendants to walk
3160 * To be used by css_for_each_descendant_pre(). Find the next descendant
3161 * to visit for pre-order traversal of @root's descendants. @root is
3162 * included in the iteration and the first node to be visited.
3164 * While this function requires cgroup_mutex or RCU read locking, it
3165 * doesn't require the whole traversal to be contained in a single critical
3166 * section. This function will return the correct next descendant as long
3167 * as both @pos and @root are accessible and @pos is a descendant of @root.
3169 struct cgroup_subsys_state *
3170 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3171 struct cgroup_subsys_state *root)
3173 struct cgroup_subsys_state *next;
3175 cgroup_assert_mutex_or_rcu_locked();
3177 /* if first iteration, visit @root */
3181 /* visit the first child if exists */
3182 next = css_next_child(NULL, pos);
3186 /* no child, visit my or the closest ancestor's next sibling */
3187 while (pos != root) {
3188 next = css_next_child(pos, pos->parent);
3198 * css_rightmost_descendant - return the rightmost descendant of a css
3199 * @pos: css of interest
3201 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3202 * is returned. This can be used during pre-order traversal to skip
3205 * While this function requires cgroup_mutex or RCU read locking, it
3206 * doesn't require the whole traversal to be contained in a single critical
3207 * section. This function will return the correct rightmost descendant as
3208 * long as @pos is accessible.
3210 struct cgroup_subsys_state *
3211 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3213 struct cgroup_subsys_state *last, *tmp;
3215 cgroup_assert_mutex_or_rcu_locked();
3219 /* ->prev isn't RCU safe, walk ->next till the end */
3221 css_for_each_child(tmp, last)
3228 static struct cgroup_subsys_state *
3229 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3231 struct cgroup_subsys_state *last;
3235 pos = css_next_child(NULL, pos);
3242 * css_next_descendant_post - find the next descendant for post-order walk
3243 * @pos: the current position (%NULL to initiate traversal)
3244 * @root: css whose descendants to walk
3246 * To be used by css_for_each_descendant_post(). Find the next descendant
3247 * to visit for post-order traversal of @root's descendants. @root is
3248 * included in the iteration and the last node to be visited.
3250 * While this function requires cgroup_mutex or RCU read locking, it
3251 * doesn't require the whole traversal to be contained in a single critical
3252 * section. This function will return the correct next descendant as long
3253 * as both @pos and @cgroup are accessible and @pos is a descendant of
3256 struct cgroup_subsys_state *
3257 css_next_descendant_post(struct cgroup_subsys_state *pos,
3258 struct cgroup_subsys_state *root)
3260 struct cgroup_subsys_state *next;
3262 cgroup_assert_mutex_or_rcu_locked();
3264 /* if first iteration, visit leftmost descendant which may be @root */
3266 return css_leftmost_descendant(root);
3268 /* if we visited @root, we're done */
3272 /* if there's an unvisited sibling, visit its leftmost descendant */
3273 next = css_next_child(pos, pos->parent);
3275 return css_leftmost_descendant(next);
3277 /* no sibling left, visit parent */
3281 static bool cgroup_has_live_children(struct cgroup *cgrp)
3283 struct cgroup *child;
3286 list_for_each_entry_rcu(child, &cgrp->self.children, self.sibling) {
3287 if (!cgroup_is_dead(child)) {
3297 * css_advance_task_iter - advance a task itererator to the next css_set
3298 * @it: the iterator to advance
3300 * Advance @it to the next css_set to walk.
3302 static void css_advance_task_iter(struct css_task_iter *it)
3304 struct list_head *l = it->cset_pos;
3305 struct cgrp_cset_link *link;
3306 struct css_set *cset;
3308 /* Advance to the next non-empty css_set */
3311 if (l == it->cset_head) {
3312 it->cset_pos = NULL;
3317 cset = container_of(l, struct css_set,
3318 e_cset_node[it->ss->id]);
3320 link = list_entry(l, struct cgrp_cset_link, cset_link);
3323 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
3327 if (!list_empty(&cset->tasks))
3328 it->task_pos = cset->tasks.next;
3330 it->task_pos = cset->mg_tasks.next;
3332 it->tasks_head = &cset->tasks;
3333 it->mg_tasks_head = &cset->mg_tasks;
3337 * css_task_iter_start - initiate task iteration
3338 * @css: the css to walk tasks of
3339 * @it: the task iterator to use
3341 * Initiate iteration through the tasks of @css. The caller can call
3342 * css_task_iter_next() to walk through the tasks until the function
3343 * returns NULL. On completion of iteration, css_task_iter_end() must be
3346 * Note that this function acquires a lock which is released when the
3347 * iteration finishes. The caller can't sleep while iteration is in
3350 void css_task_iter_start(struct cgroup_subsys_state *css,
3351 struct css_task_iter *it)
3352 __acquires(css_set_rwsem)
3354 /* no one should try to iterate before mounting cgroups */
3355 WARN_ON_ONCE(!use_task_css_set_links);
3357 down_read(&css_set_rwsem);
3362 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3364 it->cset_pos = &css->cgroup->cset_links;
3366 it->cset_head = it->cset_pos;
3368 css_advance_task_iter(it);
3372 * css_task_iter_next - return the next task for the iterator
3373 * @it: the task iterator being iterated
3375 * The "next" function for task iteration. @it should have been
3376 * initialized via css_task_iter_start(). Returns NULL when the iteration
3379 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3381 struct task_struct *res;
3382 struct list_head *l = it->task_pos;
3384 /* If the iterator cg is NULL, we have no tasks */
3387 res = list_entry(l, struct task_struct, cg_list);
3390 * Advance iterator to find next entry. cset->tasks is consumed
3391 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3396 if (l == it->tasks_head)
3397 l = it->mg_tasks_head->next;
3399 if (l == it->mg_tasks_head)
3400 css_advance_task_iter(it);
3408 * css_task_iter_end - finish task iteration
3409 * @it: the task iterator to finish
3411 * Finish task iteration started by css_task_iter_start().
3413 void css_task_iter_end(struct css_task_iter *it)
3414 __releases(css_set_rwsem)
3416 up_read(&css_set_rwsem);
3420 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3421 * @to: cgroup to which the tasks will be moved
3422 * @from: cgroup in which the tasks currently reside
3424 * Locking rules between cgroup_post_fork() and the migration path
3425 * guarantee that, if a task is forking while being migrated, the new child
3426 * is guaranteed to be either visible in the source cgroup after the
3427 * parent's migration is complete or put into the target cgroup. No task
3428 * can slip out of migration through forking.
3430 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3432 LIST_HEAD(preloaded_csets);
3433 struct cgrp_cset_link *link;
3434 struct css_task_iter it;
3435 struct task_struct *task;
3438 mutex_lock(&cgroup_mutex);
3440 /* all tasks in @from are being moved, all csets are source */
3441 down_read(&css_set_rwsem);
3442 list_for_each_entry(link, &from->cset_links, cset_link)
3443 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
3444 up_read(&css_set_rwsem);
3446 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
3451 * Migrate tasks one-by-one until @form is empty. This fails iff
3452 * ->can_attach() fails.
3455 css_task_iter_start(&from->self, &it);
3456 task = css_task_iter_next(&it);
3458 get_task_struct(task);
3459 css_task_iter_end(&it);
3462 ret = cgroup_migrate(to, task, false);
3463 put_task_struct(task);
3465 } while (task && !ret);
3467 cgroup_migrate_finish(&preloaded_csets);
3468 mutex_unlock(&cgroup_mutex);
3473 * Stuff for reading the 'tasks'/'procs' files.
3475 * Reading this file can return large amounts of data if a cgroup has
3476 * *lots* of attached tasks. So it may need several calls to read(),
3477 * but we cannot guarantee that the information we produce is correct
3478 * unless we produce it entirely atomically.
3482 /* which pidlist file are we talking about? */
3483 enum cgroup_filetype {
3489 * A pidlist is a list of pids that virtually represents the contents of one
3490 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3491 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3494 struct cgroup_pidlist {
3496 * used to find which pidlist is wanted. doesn't change as long as
3497 * this particular list stays in the list.
3499 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3502 /* how many elements the above list has */
3504 /* each of these stored in a list by its cgroup */
3505 struct list_head links;
3506 /* pointer to the cgroup we belong to, for list removal purposes */
3507 struct cgroup *owner;
3508 /* for delayed destruction */
3509 struct delayed_work destroy_dwork;
3513 * The following two functions "fix" the issue where there are more pids
3514 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3515 * TODO: replace with a kernel-wide solution to this problem
3517 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3518 static void *pidlist_allocate(int count)
3520 if (PIDLIST_TOO_LARGE(count))
3521 return vmalloc(count * sizeof(pid_t));
3523 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3526 static void pidlist_free(void *p)
3528 if (is_vmalloc_addr(p))
3535 * Used to destroy all pidlists lingering waiting for destroy timer. None
3536 * should be left afterwards.
3538 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3540 struct cgroup_pidlist *l, *tmp_l;
3542 mutex_lock(&cgrp->pidlist_mutex);
3543 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3544 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3545 mutex_unlock(&cgrp->pidlist_mutex);
3547 flush_workqueue(cgroup_pidlist_destroy_wq);
3548 BUG_ON(!list_empty(&cgrp->pidlists));
3551 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3553 struct delayed_work *dwork = to_delayed_work(work);
3554 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3556 struct cgroup_pidlist *tofree = NULL;
3558 mutex_lock(&l->owner->pidlist_mutex);
3561 * Destroy iff we didn't get queued again. The state won't change
3562 * as destroy_dwork can only be queued while locked.
3564 if (!delayed_work_pending(dwork)) {
3565 list_del(&l->links);
3566 pidlist_free(l->list);
3567 put_pid_ns(l->key.ns);
3571 mutex_unlock(&l->owner->pidlist_mutex);
3576 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3577 * Returns the number of unique elements.
3579 static int pidlist_uniq(pid_t *list, int length)
3584 * we presume the 0th element is unique, so i starts at 1. trivial
3585 * edge cases first; no work needs to be done for either
3587 if (length == 0 || length == 1)
3589 /* src and dest walk down the list; dest counts unique elements */
3590 for (src = 1; src < length; src++) {
3591 /* find next unique element */
3592 while (list[src] == list[src-1]) {
3597 /* dest always points to where the next unique element goes */
3598 list[dest] = list[src];
3606 * The two pid files - task and cgroup.procs - guaranteed that the result
3607 * is sorted, which forced this whole pidlist fiasco. As pid order is
3608 * different per namespace, each namespace needs differently sorted list,
3609 * making it impossible to use, for example, single rbtree of member tasks
3610 * sorted by task pointer. As pidlists can be fairly large, allocating one
3611 * per open file is dangerous, so cgroup had to implement shared pool of
3612 * pidlists keyed by cgroup and namespace.
3614 * All this extra complexity was caused by the original implementation
3615 * committing to an entirely unnecessary property. In the long term, we
3616 * want to do away with it. Explicitly scramble sort order if
3617 * sane_behavior so that no such expectation exists in the new interface.
3619 * Scrambling is done by swapping every two consecutive bits, which is
3620 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3622 static pid_t pid_fry(pid_t pid)
3624 unsigned a = pid & 0x55555555;
3625 unsigned b = pid & 0xAAAAAAAA;
3627 return (a << 1) | (b >> 1);
3630 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3632 if (cgroup_sane_behavior(cgrp))
3633 return pid_fry(pid);
3638 static int cmppid(const void *a, const void *b)
3640 return *(pid_t *)a - *(pid_t *)b;
3643 static int fried_cmppid(const void *a, const void *b)
3645 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3648 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3649 enum cgroup_filetype type)
3651 struct cgroup_pidlist *l;
3652 /* don't need task_nsproxy() if we're looking at ourself */
3653 struct pid_namespace *ns = task_active_pid_ns(current);
3655 lockdep_assert_held(&cgrp->pidlist_mutex);
3657 list_for_each_entry(l, &cgrp->pidlists, links)
3658 if (l->key.type == type && l->key.ns == ns)
3664 * find the appropriate pidlist for our purpose (given procs vs tasks)
3665 * returns with the lock on that pidlist already held, and takes care
3666 * of the use count, or returns NULL with no locks held if we're out of
3669 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3670 enum cgroup_filetype type)
3672 struct cgroup_pidlist *l;
3674 lockdep_assert_held(&cgrp->pidlist_mutex);
3676 l = cgroup_pidlist_find(cgrp, type);
3680 /* entry not found; create a new one */
3681 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3685 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3687 /* don't need task_nsproxy() if we're looking at ourself */
3688 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3690 list_add(&l->links, &cgrp->pidlists);
3695 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3697 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3698 struct cgroup_pidlist **lp)
3702 int pid, n = 0; /* used for populating the array */
3703 struct css_task_iter it;
3704 struct task_struct *tsk;
3705 struct cgroup_pidlist *l;
3707 lockdep_assert_held(&cgrp->pidlist_mutex);
3710 * If cgroup gets more users after we read count, we won't have
3711 * enough space - tough. This race is indistinguishable to the
3712 * caller from the case that the additional cgroup users didn't
3713 * show up until sometime later on.
3715 length = cgroup_task_count(cgrp);
3716 array = pidlist_allocate(length);
3719 /* now, populate the array */
3720 css_task_iter_start(&cgrp->self, &it);
3721 while ((tsk = css_task_iter_next(&it))) {
3722 if (unlikely(n == length))
3724 /* get tgid or pid for procs or tasks file respectively */
3725 if (type == CGROUP_FILE_PROCS)
3726 pid = task_tgid_vnr(tsk);
3728 pid = task_pid_vnr(tsk);
3729 if (pid > 0) /* make sure to only use valid results */
3732 css_task_iter_end(&it);
3734 /* now sort & (if procs) strip out duplicates */
3735 if (cgroup_sane_behavior(cgrp))
3736 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3738 sort(array, length, sizeof(pid_t), cmppid, NULL);
3739 if (type == CGROUP_FILE_PROCS)
3740 length = pidlist_uniq(array, length);
3742 l = cgroup_pidlist_find_create(cgrp, type);
3744 mutex_unlock(&cgrp->pidlist_mutex);
3745 pidlist_free(array);
3749 /* store array, freeing old if necessary */
3750 pidlist_free(l->list);
3758 * cgroupstats_build - build and fill cgroupstats
3759 * @stats: cgroupstats to fill information into
3760 * @dentry: A dentry entry belonging to the cgroup for which stats have
3763 * Build and fill cgroupstats so that taskstats can export it to user
3766 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3768 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3769 struct cgroup *cgrp;
3770 struct css_task_iter it;
3771 struct task_struct *tsk;
3773 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3774 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3775 kernfs_type(kn) != KERNFS_DIR)
3778 mutex_lock(&cgroup_mutex);
3781 * We aren't being called from kernfs and there's no guarantee on
3782 * @kn->priv's validity. For this and css_tryget_online_from_dir(),
3783 * @kn->priv is RCU safe. Let's do the RCU dancing.
3786 cgrp = rcu_dereference(kn->priv);
3787 if (!cgrp || cgroup_is_dead(cgrp)) {
3789 mutex_unlock(&cgroup_mutex);
3794 css_task_iter_start(&cgrp->self, &it);
3795 while ((tsk = css_task_iter_next(&it))) {
3796 switch (tsk->state) {
3798 stats->nr_running++;
3800 case TASK_INTERRUPTIBLE:
3801 stats->nr_sleeping++;
3803 case TASK_UNINTERRUPTIBLE:
3804 stats->nr_uninterruptible++;
3807 stats->nr_stopped++;
3810 if (delayacct_is_task_waiting_on_io(tsk))
3811 stats->nr_io_wait++;
3815 css_task_iter_end(&it);
3817 mutex_unlock(&cgroup_mutex);
3823 * seq_file methods for the tasks/procs files. The seq_file position is the
3824 * next pid to display; the seq_file iterator is a pointer to the pid
3825 * in the cgroup->l->list array.
3828 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3831 * Initially we receive a position value that corresponds to
3832 * one more than the last pid shown (or 0 on the first call or
3833 * after a seek to the start). Use a binary-search to find the
3834 * next pid to display, if any
3836 struct kernfs_open_file *of = s->private;
3837 struct cgroup *cgrp = seq_css(s)->cgroup;
3838 struct cgroup_pidlist *l;
3839 enum cgroup_filetype type = seq_cft(s)->private;
3840 int index = 0, pid = *pos;
3843 mutex_lock(&cgrp->pidlist_mutex);
3846 * !NULL @of->priv indicates that this isn't the first start()
3847 * after open. If the matching pidlist is around, we can use that.
3848 * Look for it. Note that @of->priv can't be used directly. It
3849 * could already have been destroyed.
3852 of->priv = cgroup_pidlist_find(cgrp, type);
3855 * Either this is the first start() after open or the matching
3856 * pidlist has been destroyed inbetween. Create a new one.
3859 ret = pidlist_array_load(cgrp, type,
3860 (struct cgroup_pidlist **)&of->priv);
3862 return ERR_PTR(ret);
3867 int end = l->length;
3869 while (index < end) {
3870 int mid = (index + end) / 2;
3871 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3874 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3880 /* If we're off the end of the array, we're done */
3881 if (index >= l->length)
3883 /* Update the abstract position to be the actual pid that we found */
3884 iter = l->list + index;
3885 *pos = cgroup_pid_fry(cgrp, *iter);
3889 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3891 struct kernfs_open_file *of = s->private;
3892 struct cgroup_pidlist *l = of->priv;
3895 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3896 CGROUP_PIDLIST_DESTROY_DELAY);
3897 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3900 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3902 struct kernfs_open_file *of = s->private;
3903 struct cgroup_pidlist *l = of->priv;
3905 pid_t *end = l->list + l->length;
3907 * Advance to the next pid in the array. If this goes off the
3914 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3919 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3921 return seq_printf(s, "%d\n", *(int *)v);
3924 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3927 return notify_on_release(css->cgroup);
3930 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3931 struct cftype *cft, u64 val)
3933 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3935 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3937 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3941 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3944 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3947 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3948 struct cftype *cft, u64 val)
3951 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3953 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3957 static struct cftype cgroup_base_files[] = {
3959 .name = "cgroup.procs",
3960 .seq_start = cgroup_pidlist_start,
3961 .seq_next = cgroup_pidlist_next,
3962 .seq_stop = cgroup_pidlist_stop,
3963 .seq_show = cgroup_pidlist_show,
3964 .private = CGROUP_FILE_PROCS,
3965 .write = cgroup_procs_write,
3966 .mode = S_IRUGO | S_IWUSR,
3969 .name = "cgroup.clone_children",
3970 .flags = CFTYPE_INSANE,
3971 .read_u64 = cgroup_clone_children_read,
3972 .write_u64 = cgroup_clone_children_write,
3975 .name = "cgroup.sane_behavior",
3976 .flags = CFTYPE_ONLY_ON_ROOT,
3977 .seq_show = cgroup_sane_behavior_show,
3980 .name = "cgroup.controllers",
3981 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_ONLY_ON_ROOT,
3982 .seq_show = cgroup_root_controllers_show,
3985 .name = "cgroup.controllers",
3986 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
3987 .seq_show = cgroup_controllers_show,
3990 .name = "cgroup.subtree_control",
3991 .flags = CFTYPE_ONLY_ON_DFL,
3992 .seq_show = cgroup_subtree_control_show,
3993 .write = cgroup_subtree_control_write,
3996 .name = "cgroup.populated",
3997 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
3998 .seq_show = cgroup_populated_show,
4002 * Historical crazy stuff. These don't have "cgroup." prefix and
4003 * don't exist if sane_behavior. If you're depending on these, be
4004 * prepared to be burned.
4008 .flags = CFTYPE_INSANE, /* use "procs" instead */
4009 .seq_start = cgroup_pidlist_start,
4010 .seq_next = cgroup_pidlist_next,
4011 .seq_stop = cgroup_pidlist_stop,
4012 .seq_show = cgroup_pidlist_show,
4013 .private = CGROUP_FILE_TASKS,
4014 .write = cgroup_tasks_write,
4015 .mode = S_IRUGO | S_IWUSR,
4018 .name = "notify_on_release",
4019 .flags = CFTYPE_INSANE,
4020 .read_u64 = cgroup_read_notify_on_release,
4021 .write_u64 = cgroup_write_notify_on_release,
4024 .name = "release_agent",
4025 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4026 .seq_show = cgroup_release_agent_show,
4027 .write = cgroup_release_agent_write,
4028 .max_write_len = PATH_MAX - 1,
4034 * cgroup_populate_dir - create subsys files in a cgroup directory
4035 * @cgrp: target cgroup
4036 * @subsys_mask: mask of the subsystem ids whose files should be added
4038 * On failure, no file is added.
4040 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask)
4042 struct cgroup_subsys *ss;
4045 /* process cftsets of each subsystem */
4046 for_each_subsys(ss, i) {
4047 struct cftype *cfts;
4049 if (!(subsys_mask & (1 << i)))
4052 list_for_each_entry(cfts, &ss->cfts, node) {
4053 ret = cgroup_addrm_files(cgrp, cfts, true);
4060 cgroup_clear_dir(cgrp, subsys_mask);
4065 * css destruction is four-stage process.
4067 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4068 * Implemented in kill_css().
4070 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4071 * and thus css_tryget_online() is guaranteed to fail, the css can be
4072 * offlined by invoking offline_css(). After offlining, the base ref is
4073 * put. Implemented in css_killed_work_fn().
4075 * 3. When the percpu_ref reaches zero, the only possible remaining
4076 * accessors are inside RCU read sections. css_release() schedules the
4079 * 4. After the grace period, the css can be freed. Implemented in
4080 * css_free_work_fn().
4082 * It is actually hairier because both step 2 and 4 require process context
4083 * and thus involve punting to css->destroy_work adding two additional
4084 * steps to the already complex sequence.
4086 static void css_free_work_fn(struct work_struct *work)
4088 struct cgroup_subsys_state *css =
4089 container_of(work, struct cgroup_subsys_state, destroy_work);
4090 struct cgroup *cgrp = css->cgroup;
4095 css_put(css->parent);
4097 css->ss->css_free(css);
4100 /* cgroup free path */
4101 atomic_dec(&cgrp->root->nr_cgrps);
4102 cgroup_pidlist_destroy_all(cgrp);
4104 if (cgroup_parent(cgrp)) {
4106 * We get a ref to the parent, and put the ref when
4107 * this cgroup is being freed, so it's guaranteed
4108 * that the parent won't be destroyed before its
4111 cgroup_put(cgroup_parent(cgrp));
4112 kernfs_put(cgrp->kn);
4116 * This is root cgroup's refcnt reaching zero,
4117 * which indicates that the root should be
4120 cgroup_destroy_root(cgrp->root);
4125 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4127 struct cgroup_subsys_state *css =
4128 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4130 INIT_WORK(&css->destroy_work, css_free_work_fn);
4131 queue_work(cgroup_destroy_wq, &css->destroy_work);
4134 static void css_release_work_fn(struct work_struct *work)
4136 struct cgroup_subsys_state *css =
4137 container_of(work, struct cgroup_subsys_state, destroy_work);
4138 struct cgroup_subsys *ss = css->ss;
4139 struct cgroup *cgrp = css->cgroup;
4141 mutex_lock(&cgroup_mutex);
4143 css->flags |= CSS_RELEASED;
4144 list_del_rcu(&css->sibling);
4147 /* css release path */
4148 cgroup_idr_remove(&ss->css_idr, css->id);
4150 /* cgroup release path */
4151 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4155 mutex_unlock(&cgroup_mutex);
4157 call_rcu(&css->rcu_head, css_free_rcu_fn);
4160 static void css_release(struct percpu_ref *ref)
4162 struct cgroup_subsys_state *css =
4163 container_of(ref, struct cgroup_subsys_state, refcnt);
4165 INIT_WORK(&css->destroy_work, css_release_work_fn);
4166 queue_work(cgroup_destroy_wq, &css->destroy_work);
4169 static void init_and_link_css(struct cgroup_subsys_state *css,
4170 struct cgroup_subsys *ss, struct cgroup *cgrp)
4172 lockdep_assert_held(&cgroup_mutex);
4176 memset(css, 0, sizeof(*css));
4179 INIT_LIST_HEAD(&css->sibling);
4180 INIT_LIST_HEAD(&css->children);
4181 css->serial_nr = css_serial_nr_next++;
4183 if (cgroup_parent(cgrp)) {
4184 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4185 css_get(css->parent);
4188 BUG_ON(cgroup_css(cgrp, ss));
4191 /* invoke ->css_online() on a new CSS and mark it online if successful */
4192 static int online_css(struct cgroup_subsys_state *css)
4194 struct cgroup_subsys *ss = css->ss;
4197 lockdep_assert_held(&cgroup_mutex);
4200 ret = ss->css_online(css);
4202 css->flags |= CSS_ONLINE;
4203 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4208 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4209 static void offline_css(struct cgroup_subsys_state *css)
4211 struct cgroup_subsys *ss = css->ss;
4213 lockdep_assert_held(&cgroup_mutex);
4215 if (!(css->flags & CSS_ONLINE))
4218 if (ss->css_offline)
4219 ss->css_offline(css);
4221 css->flags &= ~CSS_ONLINE;
4222 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4224 wake_up_all(&css->cgroup->offline_waitq);
4228 * create_css - create a cgroup_subsys_state
4229 * @cgrp: the cgroup new css will be associated with
4230 * @ss: the subsys of new css
4232 * Create a new css associated with @cgrp - @ss pair. On success, the new
4233 * css is online and installed in @cgrp with all interface files created.
4234 * Returns 0 on success, -errno on failure.
4236 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4238 struct cgroup *parent = cgroup_parent(cgrp);
4239 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4240 struct cgroup_subsys_state *css;
4243 lockdep_assert_held(&cgroup_mutex);
4245 css = ss->css_alloc(parent_css);
4247 return PTR_ERR(css);
4249 init_and_link_css(css, ss, cgrp);
4251 err = percpu_ref_init(&css->refcnt, css_release);
4255 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_NOWAIT);
4257 goto err_free_percpu_ref;
4260 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4264 /* @css is ready to be brought online now, make it visible */
4265 list_add_tail_rcu(&css->sibling, &parent_css->children);
4266 cgroup_idr_replace(&ss->css_idr, css, css->id);
4268 err = online_css(css);
4272 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4273 cgroup_parent(parent)) {
4274 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4275 current->comm, current->pid, ss->name);
4276 if (!strcmp(ss->name, "memory"))
4277 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4278 ss->warned_broken_hierarchy = true;
4284 list_del_rcu(&css->sibling);
4285 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4287 cgroup_idr_remove(&ss->css_idr, css->id);
4288 err_free_percpu_ref:
4289 percpu_ref_cancel_init(&css->refcnt);
4291 call_rcu(&css->rcu_head, css_free_rcu_fn);
4295 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4298 struct cgroup *parent, *cgrp;
4299 struct cgroup_root *root;
4300 struct cgroup_subsys *ss;
4301 struct kernfs_node *kn;
4304 parent = cgroup_kn_lock_live(parent_kn);
4307 root = parent->root;
4309 /* allocate the cgroup and its ID, 0 is reserved for the root */
4310 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4316 ret = percpu_ref_init(&cgrp->self.refcnt, css_release);
4321 * Temporarily set the pointer to NULL, so idr_find() won't return
4322 * a half-baked cgroup.
4324 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_NOWAIT);
4327 goto out_cancel_ref;
4330 init_cgroup_housekeeping(cgrp);
4332 cgrp->self.parent = &parent->self;
4335 if (notify_on_release(parent))
4336 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4338 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4339 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4341 /* create the directory */
4342 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4350 * This extra ref will be put in cgroup_free_fn() and guarantees
4351 * that @cgrp->kn is always accessible.
4355 cgrp->self.serial_nr = css_serial_nr_next++;
4357 /* allocation complete, commit to creation */
4358 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4359 atomic_inc(&root->nr_cgrps);
4363 * @cgrp is now fully operational. If something fails after this
4364 * point, it'll be released via the normal destruction path.
4366 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4368 ret = cgroup_kn_set_ugid(kn);
4372 ret = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4376 /* let's create and online css's */
4377 for_each_subsys(ss, ssid) {
4378 if (parent->child_subsys_mask & (1 << ssid)) {
4379 ret = create_css(cgrp, ss);
4386 * On the default hierarchy, a child doesn't automatically inherit
4387 * child_subsys_mask from the parent. Each is configured manually.
4389 if (!cgroup_on_dfl(cgrp))
4390 cgrp->child_subsys_mask = parent->child_subsys_mask;
4392 kernfs_activate(kn);
4398 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4400 percpu_ref_cancel_init(&cgrp->self.refcnt);
4404 cgroup_kn_unlock(parent_kn);
4408 cgroup_destroy_locked(cgrp);
4413 * This is called when the refcnt of a css is confirmed to be killed.
4414 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
4415 * initate destruction and put the css ref from kill_css().
4417 static void css_killed_work_fn(struct work_struct *work)
4419 struct cgroup_subsys_state *css =
4420 container_of(work, struct cgroup_subsys_state, destroy_work);
4422 mutex_lock(&cgroup_mutex);
4424 mutex_unlock(&cgroup_mutex);
4429 /* css kill confirmation processing requires process context, bounce */
4430 static void css_killed_ref_fn(struct percpu_ref *ref)
4432 struct cgroup_subsys_state *css =
4433 container_of(ref, struct cgroup_subsys_state, refcnt);
4435 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4436 queue_work(cgroup_destroy_wq, &css->destroy_work);
4440 * kill_css - destroy a css
4441 * @css: css to destroy
4443 * This function initiates destruction of @css by removing cgroup interface
4444 * files and putting its base reference. ->css_offline() will be invoked
4445 * asynchronously once css_tryget_online() is guaranteed to fail and when
4446 * the reference count reaches zero, @css will be released.
4448 static void kill_css(struct cgroup_subsys_state *css)
4450 lockdep_assert_held(&cgroup_mutex);
4453 * This must happen before css is disassociated with its cgroup.
4454 * See seq_css() for details.
4456 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4459 * Killing would put the base ref, but we need to keep it alive
4460 * until after ->css_offline().
4465 * cgroup core guarantees that, by the time ->css_offline() is
4466 * invoked, no new css reference will be given out via
4467 * css_tryget_online(). We can't simply call percpu_ref_kill() and
4468 * proceed to offlining css's because percpu_ref_kill() doesn't
4469 * guarantee that the ref is seen as killed on all CPUs on return.
4471 * Use percpu_ref_kill_and_confirm() to get notifications as each
4472 * css is confirmed to be seen as killed on all CPUs.
4474 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4478 * cgroup_destroy_locked - the first stage of cgroup destruction
4479 * @cgrp: cgroup to be destroyed
4481 * css's make use of percpu refcnts whose killing latency shouldn't be
4482 * exposed to userland and are RCU protected. Also, cgroup core needs to
4483 * guarantee that css_tryget_online() won't succeed by the time
4484 * ->css_offline() is invoked. To satisfy all the requirements,
4485 * destruction is implemented in the following two steps.
4487 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4488 * userland visible parts and start killing the percpu refcnts of
4489 * css's. Set up so that the next stage will be kicked off once all
4490 * the percpu refcnts are confirmed to be killed.
4492 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4493 * rest of destruction. Once all cgroup references are gone, the
4494 * cgroup is RCU-freed.
4496 * This function implements s1. After this step, @cgrp is gone as far as
4497 * the userland is concerned and a new cgroup with the same name may be
4498 * created. As cgroup doesn't care about the names internally, this
4499 * doesn't cause any problem.
4501 static int cgroup_destroy_locked(struct cgroup *cgrp)
4502 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4504 struct cgroup_subsys_state *css;
4508 lockdep_assert_held(&cgroup_mutex);
4511 * css_set_rwsem synchronizes access to ->cset_links and prevents
4512 * @cgrp from being removed while put_css_set() is in progress.
4514 down_read(&css_set_rwsem);
4515 empty = list_empty(&cgrp->cset_links);
4516 up_read(&css_set_rwsem);
4521 * Make sure there's no live children. We can't test emptiness of
4522 * ->self.children as dead children linger on it while being
4523 * drained; otherwise, "rmdir parent/child parent" may fail.
4525 if (cgroup_has_live_children(cgrp))
4529 * Mark @cgrp dead. This prevents further task migration and child
4530 * creation by disabling cgroup_lock_live_group().
4532 set_bit(CGRP_DEAD, &cgrp->flags);
4534 /* initiate massacre of all css's */
4535 for_each_css(css, ssid, cgrp)
4538 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4539 raw_spin_lock(&release_list_lock);
4540 if (!list_empty(&cgrp->release_list))
4541 list_del_init(&cgrp->release_list);
4542 raw_spin_unlock(&release_list_lock);
4545 * Remove @cgrp directory along with the base files. @cgrp has an
4546 * extra ref on its kn.
4548 kernfs_remove(cgrp->kn);
4550 set_bit(CGRP_RELEASABLE, &cgroup_parent(cgrp)->flags);
4551 check_for_release(cgroup_parent(cgrp));
4553 /* put the base reference */
4554 percpu_ref_kill(&cgrp->self.refcnt);
4559 static int cgroup_rmdir(struct kernfs_node *kn)
4561 struct cgroup *cgrp;
4564 cgrp = cgroup_kn_lock_live(kn);
4567 cgroup_get(cgrp); /* for @kn->priv clearing */
4569 ret = cgroup_destroy_locked(cgrp);
4571 cgroup_kn_unlock(kn);
4574 * There are two control paths which try to determine cgroup from
4575 * dentry without going through kernfs - cgroupstats_build() and
4576 * css_tryget_online_from_dir(). Those are supported by RCU
4577 * protecting clearing of cgrp->kn->priv backpointer, which should
4578 * happen after all files under it have been removed.
4581 RCU_INIT_POINTER(*(void __rcu __force **)&kn->priv, NULL);
4587 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4588 .remount_fs = cgroup_remount,
4589 .show_options = cgroup_show_options,
4590 .mkdir = cgroup_mkdir,
4591 .rmdir = cgroup_rmdir,
4592 .rename = cgroup_rename,
4595 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
4597 struct cgroup_subsys_state *css;
4599 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4601 mutex_lock(&cgroup_mutex);
4603 idr_init(&ss->css_idr);
4604 INIT_LIST_HEAD(&ss->cfts);
4606 /* Create the root cgroup state for this subsystem */
4607 ss->root = &cgrp_dfl_root;
4608 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
4609 /* We don't handle early failures gracefully */
4610 BUG_ON(IS_ERR(css));
4611 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
4614 * Root csses are never destroyed and we can't initialize
4615 * percpu_ref during early init. Disable refcnting.
4617 css->flags |= CSS_NO_REF;
4620 /* allocation can't be done safely during early init */
4623 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
4624 BUG_ON(css->id < 0);
4627 /* Update the init_css_set to contain a subsys
4628 * pointer to this state - since the subsystem is
4629 * newly registered, all tasks and hence the
4630 * init_css_set is in the subsystem's root cgroup. */
4631 init_css_set.subsys[ss->id] = css;
4633 need_forkexit_callback |= ss->fork || ss->exit;
4635 /* At system boot, before all subsystems have been
4636 * registered, no tasks have been forked, so we don't
4637 * need to invoke fork callbacks here. */
4638 BUG_ON(!list_empty(&init_task.tasks));
4640 BUG_ON(online_css(css));
4642 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
4644 mutex_unlock(&cgroup_mutex);
4648 * cgroup_init_early - cgroup initialization at system boot
4650 * Initialize cgroups at system boot, and initialize any
4651 * subsystems that request early init.
4653 int __init cgroup_init_early(void)
4655 static struct cgroup_sb_opts __initdata opts =
4656 { .flags = CGRP_ROOT_SANE_BEHAVIOR };
4657 struct cgroup_subsys *ss;
4660 init_cgroup_root(&cgrp_dfl_root, &opts);
4661 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
4663 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4665 for_each_subsys(ss, i) {
4666 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4667 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4668 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4670 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4671 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4674 ss->name = cgroup_subsys_name[i];
4677 cgroup_init_subsys(ss, true);
4683 * cgroup_init - cgroup initialization
4685 * Register cgroup filesystem and /proc file, and initialize
4686 * any subsystems that didn't request early init.
4688 int __init cgroup_init(void)
4690 struct cgroup_subsys *ss;
4694 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4696 mutex_lock(&cgroup_mutex);
4698 /* Add init_css_set to the hash table */
4699 key = css_set_hash(init_css_set.subsys);
4700 hash_add(css_set_table, &init_css_set.hlist, key);
4702 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
4704 mutex_unlock(&cgroup_mutex);
4706 for_each_subsys(ss, ssid) {
4707 if (ss->early_init) {
4708 struct cgroup_subsys_state *css =
4709 init_css_set.subsys[ss->id];
4711 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
4713 BUG_ON(css->id < 0);
4715 cgroup_init_subsys(ss, false);
4718 list_add_tail(&init_css_set.e_cset_node[ssid],
4719 &cgrp_dfl_root.cgrp.e_csets[ssid]);
4722 * cftype registration needs kmalloc and can't be done
4723 * during early_init. Register base cftypes separately.
4725 if (ss->base_cftypes)
4726 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4729 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4733 err = register_filesystem(&cgroup_fs_type);
4735 kobject_put(cgroup_kobj);
4739 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4743 static int __init cgroup_wq_init(void)
4746 * There isn't much point in executing destruction path in
4747 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4748 * Use 1 for @max_active.
4750 * We would prefer to do this in cgroup_init() above, but that
4751 * is called before init_workqueues(): so leave this until after.
4753 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4754 BUG_ON(!cgroup_destroy_wq);
4757 * Used to destroy pidlists and separate to serve as flush domain.
4758 * Cap @max_active to 1 too.
4760 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4762 BUG_ON(!cgroup_pidlist_destroy_wq);
4766 core_initcall(cgroup_wq_init);
4769 * proc_cgroup_show()
4770 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4771 * - Used for /proc/<pid>/cgroup.
4774 /* TODO: Use a proper seq_file iterator */
4775 int proc_cgroup_show(struct seq_file *m, void *v)
4778 struct task_struct *tsk;
4781 struct cgroup_root *root;
4784 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4790 tsk = get_pid_task(pid, PIDTYPE_PID);
4796 mutex_lock(&cgroup_mutex);
4797 down_read(&css_set_rwsem);
4799 for_each_root(root) {
4800 struct cgroup_subsys *ss;
4801 struct cgroup *cgrp;
4802 int ssid, count = 0;
4804 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
4807 seq_printf(m, "%d:", root->hierarchy_id);
4808 for_each_subsys(ss, ssid)
4809 if (root->subsys_mask & (1 << ssid))
4810 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4811 if (strlen(root->name))
4812 seq_printf(m, "%sname=%s", count ? "," : "",
4815 cgrp = task_cgroup_from_root(tsk, root);
4816 path = cgroup_path(cgrp, buf, PATH_MAX);
4818 retval = -ENAMETOOLONG;
4826 up_read(&css_set_rwsem);
4827 mutex_unlock(&cgroup_mutex);
4828 put_task_struct(tsk);
4835 /* Display information about each subsystem and each hierarchy */
4836 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4838 struct cgroup_subsys *ss;
4841 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4843 * ideally we don't want subsystems moving around while we do this.
4844 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4845 * subsys/hierarchy state.
4847 mutex_lock(&cgroup_mutex);
4849 for_each_subsys(ss, i)
4850 seq_printf(m, "%s\t%d\t%d\t%d\n",
4851 ss->name, ss->root->hierarchy_id,
4852 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4854 mutex_unlock(&cgroup_mutex);
4858 static int cgroupstats_open(struct inode *inode, struct file *file)
4860 return single_open(file, proc_cgroupstats_show, NULL);
4863 static const struct file_operations proc_cgroupstats_operations = {
4864 .open = cgroupstats_open,
4866 .llseek = seq_lseek,
4867 .release = single_release,
4871 * cgroup_fork - initialize cgroup related fields during copy_process()
4872 * @child: pointer to task_struct of forking parent process.
4874 * A task is associated with the init_css_set until cgroup_post_fork()
4875 * attaches it to the parent's css_set. Empty cg_list indicates that
4876 * @child isn't holding reference to its css_set.
4878 void cgroup_fork(struct task_struct *child)
4880 RCU_INIT_POINTER(child->cgroups, &init_css_set);
4881 INIT_LIST_HEAD(&child->cg_list);
4885 * cgroup_post_fork - called on a new task after adding it to the task list
4886 * @child: the task in question
4888 * Adds the task to the list running through its css_set if necessary and
4889 * call the subsystem fork() callbacks. Has to be after the task is
4890 * visible on the task list in case we race with the first call to
4891 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4894 void cgroup_post_fork(struct task_struct *child)
4896 struct cgroup_subsys *ss;
4900 * This may race against cgroup_enable_task_cg_links(). As that
4901 * function sets use_task_css_set_links before grabbing
4902 * tasklist_lock and we just went through tasklist_lock to add
4903 * @child, it's guaranteed that either we see the set
4904 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4905 * @child during its iteration.
4907 * If we won the race, @child is associated with %current's
4908 * css_set. Grabbing css_set_rwsem guarantees both that the
4909 * association is stable, and, on completion of the parent's
4910 * migration, @child is visible in the source of migration or
4911 * already in the destination cgroup. This guarantee is necessary
4912 * when implementing operations which need to migrate all tasks of
4913 * a cgroup to another.
4915 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4916 * will remain in init_css_set. This is safe because all tasks are
4917 * in the init_css_set before cg_links is enabled and there's no
4918 * operation which transfers all tasks out of init_css_set.
4920 if (use_task_css_set_links) {
4921 struct css_set *cset;
4923 down_write(&css_set_rwsem);
4924 cset = task_css_set(current);
4925 if (list_empty(&child->cg_list)) {
4926 rcu_assign_pointer(child->cgroups, cset);
4927 list_add(&child->cg_list, &cset->tasks);
4930 up_write(&css_set_rwsem);
4934 * Call ss->fork(). This must happen after @child is linked on
4935 * css_set; otherwise, @child might change state between ->fork()
4936 * and addition to css_set.
4938 if (need_forkexit_callback) {
4939 for_each_subsys(ss, i)
4946 * cgroup_exit - detach cgroup from exiting task
4947 * @tsk: pointer to task_struct of exiting process
4949 * Description: Detach cgroup from @tsk and release it.
4951 * Note that cgroups marked notify_on_release force every task in
4952 * them to take the global cgroup_mutex mutex when exiting.
4953 * This could impact scaling on very large systems. Be reluctant to
4954 * use notify_on_release cgroups where very high task exit scaling
4955 * is required on large systems.
4957 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
4958 * call cgroup_exit() while the task is still competent to handle
4959 * notify_on_release(), then leave the task attached to the root cgroup in
4960 * each hierarchy for the remainder of its exit. No need to bother with
4961 * init_css_set refcnting. init_css_set never goes away and we can't race
4962 * with migration path - PF_EXITING is visible to migration path.
4964 void cgroup_exit(struct task_struct *tsk)
4966 struct cgroup_subsys *ss;
4967 struct css_set *cset;
4968 bool put_cset = false;
4972 * Unlink from @tsk from its css_set. As migration path can't race
4973 * with us, we can check cg_list without grabbing css_set_rwsem.
4975 if (!list_empty(&tsk->cg_list)) {
4976 down_write(&css_set_rwsem);
4977 list_del_init(&tsk->cg_list);
4978 up_write(&css_set_rwsem);
4982 /* Reassign the task to the init_css_set. */
4983 cset = task_css_set(tsk);
4984 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4986 if (need_forkexit_callback) {
4987 /* see cgroup_post_fork() for details */
4988 for_each_subsys(ss, i) {
4990 struct cgroup_subsys_state *old_css = cset->subsys[i];
4991 struct cgroup_subsys_state *css = task_css(tsk, i);
4993 ss->exit(css, old_css, tsk);
4999 put_css_set(cset, true);
5002 static void check_for_release(struct cgroup *cgrp)
5004 if (cgroup_is_releasable(cgrp) &&
5005 list_empty(&cgrp->cset_links) && !cgroup_has_live_children(cgrp)) {
5007 * Control Group is currently removeable. If it's not
5008 * already queued for a userspace notification, queue
5011 int need_schedule_work = 0;
5013 raw_spin_lock(&release_list_lock);
5014 if (!cgroup_is_dead(cgrp) &&
5015 list_empty(&cgrp->release_list)) {
5016 list_add(&cgrp->release_list, &release_list);
5017 need_schedule_work = 1;
5019 raw_spin_unlock(&release_list_lock);
5020 if (need_schedule_work)
5021 schedule_work(&release_agent_work);
5026 * Notify userspace when a cgroup is released, by running the
5027 * configured release agent with the name of the cgroup (path
5028 * relative to the root of cgroup file system) as the argument.
5030 * Most likely, this user command will try to rmdir this cgroup.
5032 * This races with the possibility that some other task will be
5033 * attached to this cgroup before it is removed, or that some other
5034 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5035 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5036 * unused, and this cgroup will be reprieved from its death sentence,
5037 * to continue to serve a useful existence. Next time it's released,
5038 * we will get notified again, if it still has 'notify_on_release' set.
5040 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5041 * means only wait until the task is successfully execve()'d. The
5042 * separate release agent task is forked by call_usermodehelper(),
5043 * then control in this thread returns here, without waiting for the
5044 * release agent task. We don't bother to wait because the caller of
5045 * this routine has no use for the exit status of the release agent
5046 * task, so no sense holding our caller up for that.
5048 static void cgroup_release_agent(struct work_struct *work)
5050 BUG_ON(work != &release_agent_work);
5051 mutex_lock(&cgroup_mutex);
5052 raw_spin_lock(&release_list_lock);
5053 while (!list_empty(&release_list)) {
5054 char *argv[3], *envp[3];
5056 char *pathbuf = NULL, *agentbuf = NULL, *path;
5057 struct cgroup *cgrp = list_entry(release_list.next,
5060 list_del_init(&cgrp->release_list);
5061 raw_spin_unlock(&release_list_lock);
5062 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5065 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5068 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5073 argv[i++] = agentbuf;
5078 /* minimal command environment */
5079 envp[i++] = "HOME=/";
5080 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5083 /* Drop the lock while we invoke the usermode helper,
5084 * since the exec could involve hitting disk and hence
5085 * be a slow process */
5086 mutex_unlock(&cgroup_mutex);
5087 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5088 mutex_lock(&cgroup_mutex);
5092 raw_spin_lock(&release_list_lock);
5094 raw_spin_unlock(&release_list_lock);
5095 mutex_unlock(&cgroup_mutex);
5098 static int __init cgroup_disable(char *str)
5100 struct cgroup_subsys *ss;
5104 while ((token = strsep(&str, ",")) != NULL) {
5108 for_each_subsys(ss, i) {
5109 if (!strcmp(token, ss->name)) {
5111 printk(KERN_INFO "Disabling %s control group"
5112 " subsystem\n", ss->name);
5119 __setup("cgroup_disable=", cgroup_disable);
5122 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5123 * @dentry: directory dentry of interest
5124 * @ss: subsystem of interest
5126 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5127 * to get the corresponding css and return it. If such css doesn't exist
5128 * or can't be pinned, an ERR_PTR value is returned.
5130 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5131 struct cgroup_subsys *ss)
5133 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5134 struct cgroup_subsys_state *css = NULL;
5135 struct cgroup *cgrp;
5137 /* is @dentry a cgroup dir? */
5138 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5139 kernfs_type(kn) != KERNFS_DIR)
5140 return ERR_PTR(-EBADF);
5145 * This path doesn't originate from kernfs and @kn could already
5146 * have been or be removed at any point. @kn->priv is RCU
5147 * protected for this access. See cgroup_rmdir() for details.
5149 cgrp = rcu_dereference(kn->priv);
5151 css = cgroup_css(cgrp, ss);
5153 if (!css || !css_tryget_online(css))
5154 css = ERR_PTR(-ENOENT);
5161 * css_from_id - lookup css by id
5162 * @id: the cgroup id
5163 * @ss: cgroup subsys to be looked into
5165 * Returns the css if there's valid one with @id, otherwise returns NULL.
5166 * Should be called under rcu_read_lock().
5168 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5170 WARN_ON_ONCE(!rcu_read_lock_held());
5171 return idr_find(&ss->css_idr, id);
5174 #ifdef CONFIG_CGROUP_DEBUG
5175 static struct cgroup_subsys_state *
5176 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5178 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5181 return ERR_PTR(-ENOMEM);
5186 static void debug_css_free(struct cgroup_subsys_state *css)
5191 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5194 return cgroup_task_count(css->cgroup);
5197 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5200 return (u64)(unsigned long)current->cgroups;
5203 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5209 count = atomic_read(&task_css_set(current)->refcount);
5214 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5216 struct cgrp_cset_link *link;
5217 struct css_set *cset;
5220 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5224 down_read(&css_set_rwsem);
5226 cset = rcu_dereference(current->cgroups);
5227 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5228 struct cgroup *c = link->cgrp;
5230 cgroup_name(c, name_buf, NAME_MAX + 1);
5231 seq_printf(seq, "Root %d group %s\n",
5232 c->root->hierarchy_id, name_buf);
5235 up_read(&css_set_rwsem);
5240 #define MAX_TASKS_SHOWN_PER_CSS 25
5241 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5243 struct cgroup_subsys_state *css = seq_css(seq);
5244 struct cgrp_cset_link *link;
5246 down_read(&css_set_rwsem);
5247 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5248 struct css_set *cset = link->cset;
5249 struct task_struct *task;
5252 seq_printf(seq, "css_set %p\n", cset);
5254 list_for_each_entry(task, &cset->tasks, cg_list) {
5255 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5257 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5260 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5261 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5263 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5267 seq_puts(seq, " ...\n");
5269 up_read(&css_set_rwsem);
5273 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5275 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5278 static struct cftype debug_files[] = {
5280 .name = "taskcount",
5281 .read_u64 = debug_taskcount_read,
5285 .name = "current_css_set",
5286 .read_u64 = current_css_set_read,
5290 .name = "current_css_set_refcount",
5291 .read_u64 = current_css_set_refcount_read,
5295 .name = "current_css_set_cg_links",
5296 .seq_show = current_css_set_cg_links_read,
5300 .name = "cgroup_css_links",
5301 .seq_show = cgroup_css_links_read,
5305 .name = "releasable",
5306 .read_u64 = releasable_read,
5312 struct cgroup_subsys debug_cgrp_subsys = {
5313 .css_alloc = debug_css_alloc,
5314 .css_free = debug_css_free,
5315 .base_cftypes = debug_files,
5317 #endif /* CONFIG_CGROUP_DEBUG */