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 cgroups. It
161 * guarantees cgroups with bigger numbers are newer than those with smaller
162 * numbers. Also, as cgroups are always appended to the parent's
163 * ->children list, it guarantees that sibling cgroups are always sorted in
164 * the ascending serial number order on the list. Protected by
167 static u64 cgroup_serial_nr_next = 1;
169 /* This flag indicates whether tasks in the fork and exit paths should
170 * check for fork/exit handlers to call. This avoids us having to do
171 * extra work in the fork/exit path if none of the subsystems need to
174 static int need_forkexit_callback __read_mostly;
176 static struct cftype cgroup_base_files[];
178 static void cgroup_put(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 kill_css(struct cgroup_subsys_state *css);
184 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
186 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
188 /* IDR wrappers which synchronize using cgroup_idr_lock */
189 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
194 idr_preload(gfp_mask);
195 spin_lock_bh(&cgroup_idr_lock);
196 ret = idr_alloc(idr, ptr, start, end, gfp_mask);
197 spin_unlock_bh(&cgroup_idr_lock);
202 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
206 spin_lock_bh(&cgroup_idr_lock);
207 ret = idr_replace(idr, ptr, id);
208 spin_unlock_bh(&cgroup_idr_lock);
212 static void cgroup_idr_remove(struct idr *idr, int id)
214 spin_lock_bh(&cgroup_idr_lock);
216 spin_unlock_bh(&cgroup_idr_lock);
220 * cgroup_css - obtain a cgroup's css for the specified subsystem
221 * @cgrp: the cgroup of interest
222 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
224 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
225 * function must be called either under cgroup_mutex or rcu_read_lock() and
226 * the caller is responsible for pinning the returned css if it wants to
227 * keep accessing it outside the said locks. This function may return
228 * %NULL if @cgrp doesn't have @subsys_id enabled.
230 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
231 struct cgroup_subsys *ss)
234 return rcu_dereference_check(cgrp->subsys[ss->id],
235 lockdep_is_held(&cgroup_mutex));
241 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
242 * @cgrp: the cgroup of interest
243 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
245 * Similar to cgroup_css() but returns the effctive css, which is defined
246 * as the matching css of the nearest ancestor including self which has @ss
247 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
248 * function is guaranteed to return non-NULL css.
250 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
251 struct cgroup_subsys *ss)
253 lockdep_assert_held(&cgroup_mutex);
258 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
261 while (cgrp->parent &&
262 !(cgrp->parent->child_subsys_mask & (1 << ss->id)))
265 return cgroup_css(cgrp, ss);
268 /* convenient tests for these bits */
269 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
271 return test_bit(CGRP_DEAD, &cgrp->flags);
274 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
276 struct cgroup *cgrp = of->kn->parent->priv;
277 struct cftype *cft = of_cft(of);
280 * This is open and unprotected implementation of cgroup_css().
281 * seq_css() is only called from a kernfs file operation which has
282 * an active reference on the file. Because all the subsystem
283 * files are drained before a css is disassociated with a cgroup,
284 * the matching css from the cgroup's subsys table is guaranteed to
285 * be and stay valid until the enclosing operation is complete.
288 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
292 EXPORT_SYMBOL_GPL(of_css);
295 * cgroup_is_descendant - test ancestry
296 * @cgrp: the cgroup to be tested
297 * @ancestor: possible ancestor of @cgrp
299 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
300 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
301 * and @ancestor are accessible.
303 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
306 if (cgrp == ancestor)
313 static int cgroup_is_releasable(const struct cgroup *cgrp)
316 (1 << CGRP_RELEASABLE) |
317 (1 << CGRP_NOTIFY_ON_RELEASE);
318 return (cgrp->flags & bits) == bits;
321 static int notify_on_release(const struct cgroup *cgrp)
323 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
327 * for_each_css - iterate all css's of a cgroup
328 * @css: the iteration cursor
329 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
330 * @cgrp: the target cgroup to iterate css's of
332 * Should be called under cgroup_[tree_]mutex.
334 #define for_each_css(css, ssid, cgrp) \
335 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
336 if (!((css) = rcu_dereference_check( \
337 (cgrp)->subsys[(ssid)], \
338 lockdep_is_held(&cgroup_mutex)))) { } \
342 * for_each_e_css - iterate all effective css's of a cgroup
343 * @css: the iteration cursor
344 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
345 * @cgrp: the target cgroup to iterate css's of
347 * Should be called under cgroup_[tree_]mutex.
349 #define for_each_e_css(css, ssid, cgrp) \
350 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
351 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
356 * for_each_subsys - iterate all enabled cgroup subsystems
357 * @ss: the iteration cursor
358 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
360 #define for_each_subsys(ss, ssid) \
361 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
362 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
364 /* iterate across the hierarchies */
365 #define for_each_root(root) \
366 list_for_each_entry((root), &cgroup_roots, root_list)
368 /* iterate over child cgrps, lock should be held throughout iteration */
369 #define cgroup_for_each_live_child(child, cgrp) \
370 list_for_each_entry((child), &(cgrp)->children, sibling) \
371 if (({ lockdep_assert_held(&cgroup_mutex); \
372 cgroup_is_dead(child); })) \
376 /* the list of cgroups eligible for automatic release. Protected by
377 * release_list_lock */
378 static LIST_HEAD(release_list);
379 static DEFINE_RAW_SPINLOCK(release_list_lock);
380 static void cgroup_release_agent(struct work_struct *work);
381 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
382 static void check_for_release(struct cgroup *cgrp);
385 * A cgroup can be associated with multiple css_sets as different tasks may
386 * belong to different cgroups on different hierarchies. In the other
387 * direction, a css_set is naturally associated with multiple cgroups.
388 * This M:N relationship is represented by the following link structure
389 * which exists for each association and allows traversing the associations
392 struct cgrp_cset_link {
393 /* the cgroup and css_set this link associates */
395 struct css_set *cset;
397 /* list of cgrp_cset_links anchored at cgrp->cset_links */
398 struct list_head cset_link;
400 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
401 struct list_head cgrp_link;
405 * The default css_set - used by init and its children prior to any
406 * hierarchies being mounted. It contains a pointer to the root state
407 * for each subsystem. Also used to anchor the list of css_sets. Not
408 * reference-counted, to improve performance when child cgroups
409 * haven't been created.
411 struct css_set init_css_set = {
412 .refcount = ATOMIC_INIT(1),
413 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
414 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
415 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
416 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
417 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
420 static int css_set_count = 1; /* 1 for init_css_set */
423 * cgroup_update_populated - updated populated count of a cgroup
424 * @cgrp: the target cgroup
425 * @populated: inc or dec populated count
427 * @cgrp is either getting the first task (css_set) or losing the last.
428 * Update @cgrp->populated_cnt accordingly. The count is propagated
429 * towards root so that a given cgroup's populated_cnt is zero iff the
430 * cgroup and all its descendants are empty.
432 * @cgrp's interface file "cgroup.populated" is zero if
433 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
434 * changes from or to zero, userland is notified that the content of the
435 * interface file has changed. This can be used to detect when @cgrp and
436 * its descendants become populated or empty.
438 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
440 lockdep_assert_held(&css_set_rwsem);
446 trigger = !cgrp->populated_cnt++;
448 trigger = !--cgrp->populated_cnt;
453 if (cgrp->populated_kn)
454 kernfs_notify(cgrp->populated_kn);
460 * hash table for cgroup groups. This improves the performance to find
461 * an existing css_set. This hash doesn't (currently) take into
462 * account cgroups in empty hierarchies.
464 #define CSS_SET_HASH_BITS 7
465 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
467 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
469 unsigned long key = 0UL;
470 struct cgroup_subsys *ss;
473 for_each_subsys(ss, i)
474 key += (unsigned long)css[i];
475 key = (key >> 16) ^ key;
480 static void put_css_set_locked(struct css_set *cset, bool taskexit)
482 struct cgrp_cset_link *link, *tmp_link;
483 struct cgroup_subsys *ss;
486 lockdep_assert_held(&css_set_rwsem);
488 if (!atomic_dec_and_test(&cset->refcount))
491 /* This css_set is dead. unlink it and release cgroup refcounts */
492 for_each_subsys(ss, ssid)
493 list_del(&cset->e_cset_node[ssid]);
494 hash_del(&cset->hlist);
497 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
498 struct cgroup *cgrp = link->cgrp;
500 list_del(&link->cset_link);
501 list_del(&link->cgrp_link);
503 /* @cgrp can't go away while we're holding css_set_rwsem */
504 if (list_empty(&cgrp->cset_links)) {
505 cgroup_update_populated(cgrp, false);
506 if (notify_on_release(cgrp)) {
508 set_bit(CGRP_RELEASABLE, &cgrp->flags);
509 check_for_release(cgrp);
516 kfree_rcu(cset, rcu_head);
519 static void put_css_set(struct css_set *cset, bool taskexit)
522 * Ensure that the refcount doesn't hit zero while any readers
523 * can see it. Similar to atomic_dec_and_lock(), but for an
526 if (atomic_add_unless(&cset->refcount, -1, 1))
529 down_write(&css_set_rwsem);
530 put_css_set_locked(cset, taskexit);
531 up_write(&css_set_rwsem);
535 * refcounted get/put for css_set objects
537 static inline void get_css_set(struct css_set *cset)
539 atomic_inc(&cset->refcount);
543 * compare_css_sets - helper function for find_existing_css_set().
544 * @cset: candidate css_set being tested
545 * @old_cset: existing css_set for a task
546 * @new_cgrp: cgroup that's being entered by the task
547 * @template: desired set of css pointers in css_set (pre-calculated)
549 * Returns true if "cset" matches "old_cset" except for the hierarchy
550 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
552 static bool compare_css_sets(struct css_set *cset,
553 struct css_set *old_cset,
554 struct cgroup *new_cgrp,
555 struct cgroup_subsys_state *template[])
557 struct list_head *l1, *l2;
560 * On the default hierarchy, there can be csets which are
561 * associated with the same set of cgroups but different csses.
562 * Let's first ensure that csses match.
564 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
568 * Compare cgroup pointers in order to distinguish between
569 * different cgroups in hierarchies. As different cgroups may
570 * share the same effective css, this comparison is always
573 l1 = &cset->cgrp_links;
574 l2 = &old_cset->cgrp_links;
576 struct cgrp_cset_link *link1, *link2;
577 struct cgroup *cgrp1, *cgrp2;
581 /* See if we reached the end - both lists are equal length. */
582 if (l1 == &cset->cgrp_links) {
583 BUG_ON(l2 != &old_cset->cgrp_links);
586 BUG_ON(l2 == &old_cset->cgrp_links);
588 /* Locate the cgroups associated with these links. */
589 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
590 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
593 /* Hierarchies should be linked in the same order. */
594 BUG_ON(cgrp1->root != cgrp2->root);
597 * If this hierarchy is the hierarchy of the cgroup
598 * that's changing, then we need to check that this
599 * css_set points to the new cgroup; if it's any other
600 * hierarchy, then this css_set should point to the
601 * same cgroup as the old css_set.
603 if (cgrp1->root == new_cgrp->root) {
604 if (cgrp1 != new_cgrp)
615 * find_existing_css_set - init css array and find the matching css_set
616 * @old_cset: the css_set that we're using before the cgroup transition
617 * @cgrp: the cgroup that we're moving into
618 * @template: out param for the new set of csses, should be clear on entry
620 static struct css_set *find_existing_css_set(struct css_set *old_cset,
622 struct cgroup_subsys_state *template[])
624 struct cgroup_root *root = cgrp->root;
625 struct cgroup_subsys *ss;
626 struct css_set *cset;
631 * Build the set of subsystem state objects that we want to see in the
632 * new css_set. while subsystems can change globally, the entries here
633 * won't change, so no need for locking.
635 for_each_subsys(ss, i) {
636 if (root->subsys_mask & (1UL << i)) {
638 * @ss is in this hierarchy, so we want the
639 * effective css from @cgrp.
641 template[i] = cgroup_e_css(cgrp, ss);
644 * @ss is not in this hierarchy, so we don't want
647 template[i] = old_cset->subsys[i];
651 key = css_set_hash(template);
652 hash_for_each_possible(css_set_table, cset, hlist, key) {
653 if (!compare_css_sets(cset, old_cset, cgrp, template))
656 /* This css_set matches what we need */
660 /* No existing cgroup group matched */
664 static void free_cgrp_cset_links(struct list_head *links_to_free)
666 struct cgrp_cset_link *link, *tmp_link;
668 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
669 list_del(&link->cset_link);
675 * allocate_cgrp_cset_links - allocate cgrp_cset_links
676 * @count: the number of links to allocate
677 * @tmp_links: list_head the allocated links are put on
679 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
680 * through ->cset_link. Returns 0 on success or -errno.
682 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
684 struct cgrp_cset_link *link;
687 INIT_LIST_HEAD(tmp_links);
689 for (i = 0; i < count; i++) {
690 link = kzalloc(sizeof(*link), GFP_KERNEL);
692 free_cgrp_cset_links(tmp_links);
695 list_add(&link->cset_link, tmp_links);
701 * link_css_set - a helper function to link a css_set to a cgroup
702 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
703 * @cset: the css_set to be linked
704 * @cgrp: the destination cgroup
706 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
709 struct cgrp_cset_link *link;
711 BUG_ON(list_empty(tmp_links));
713 if (cgroup_on_dfl(cgrp))
714 cset->dfl_cgrp = cgrp;
716 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
720 if (list_empty(&cgrp->cset_links))
721 cgroup_update_populated(cgrp, true);
722 list_move(&link->cset_link, &cgrp->cset_links);
725 * Always add links to the tail of the list so that the list
726 * is sorted by order of hierarchy creation
728 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
732 * find_css_set - return a new css_set with one cgroup updated
733 * @old_cset: the baseline css_set
734 * @cgrp: the cgroup to be updated
736 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
737 * substituted into the appropriate hierarchy.
739 static struct css_set *find_css_set(struct css_set *old_cset,
742 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
743 struct css_set *cset;
744 struct list_head tmp_links;
745 struct cgrp_cset_link *link;
746 struct cgroup_subsys *ss;
750 lockdep_assert_held(&cgroup_mutex);
752 /* First see if we already have a cgroup group that matches
754 down_read(&css_set_rwsem);
755 cset = find_existing_css_set(old_cset, cgrp, template);
758 up_read(&css_set_rwsem);
763 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
767 /* Allocate all the cgrp_cset_link objects that we'll need */
768 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
773 atomic_set(&cset->refcount, 1);
774 INIT_LIST_HEAD(&cset->cgrp_links);
775 INIT_LIST_HEAD(&cset->tasks);
776 INIT_LIST_HEAD(&cset->mg_tasks);
777 INIT_LIST_HEAD(&cset->mg_preload_node);
778 INIT_LIST_HEAD(&cset->mg_node);
779 INIT_HLIST_NODE(&cset->hlist);
781 /* Copy the set of subsystem state objects generated in
782 * find_existing_css_set() */
783 memcpy(cset->subsys, template, sizeof(cset->subsys));
785 down_write(&css_set_rwsem);
786 /* Add reference counts and links from the new css_set. */
787 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
788 struct cgroup *c = link->cgrp;
790 if (c->root == cgrp->root)
792 link_css_set(&tmp_links, cset, c);
795 BUG_ON(!list_empty(&tmp_links));
799 /* Add @cset to the hash table */
800 key = css_set_hash(cset->subsys);
801 hash_add(css_set_table, &cset->hlist, key);
803 for_each_subsys(ss, ssid)
804 list_add_tail(&cset->e_cset_node[ssid],
805 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
807 up_write(&css_set_rwsem);
812 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
814 struct cgroup *root_cgrp = kf_root->kn->priv;
816 return root_cgrp->root;
819 static int cgroup_init_root_id(struct cgroup_root *root)
823 lockdep_assert_held(&cgroup_mutex);
825 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
829 root->hierarchy_id = id;
833 static void cgroup_exit_root_id(struct cgroup_root *root)
835 lockdep_assert_held(&cgroup_mutex);
837 if (root->hierarchy_id) {
838 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
839 root->hierarchy_id = 0;
843 static void cgroup_free_root(struct cgroup_root *root)
846 /* hierarhcy ID shoulid already have been released */
847 WARN_ON_ONCE(root->hierarchy_id);
849 idr_destroy(&root->cgroup_idr);
854 static void cgroup_destroy_root(struct cgroup_root *root)
856 struct cgroup *cgrp = &root->cgrp;
857 struct cgrp_cset_link *link, *tmp_link;
859 mutex_lock(&cgroup_mutex);
861 BUG_ON(atomic_read(&root->nr_cgrps));
862 BUG_ON(!list_empty(&cgrp->children));
864 /* Rebind all subsystems back to the default hierarchy */
865 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
868 * Release all the links from cset_links to this hierarchy's
871 down_write(&css_set_rwsem);
873 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
874 list_del(&link->cset_link);
875 list_del(&link->cgrp_link);
878 up_write(&css_set_rwsem);
880 if (!list_empty(&root->root_list)) {
881 list_del(&root->root_list);
885 cgroup_exit_root_id(root);
887 mutex_unlock(&cgroup_mutex);
889 kernfs_destroy_root(root->kf_root);
890 cgroup_free_root(root);
893 /* look up cgroup associated with given css_set on the specified hierarchy */
894 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
895 struct cgroup_root *root)
897 struct cgroup *res = NULL;
899 lockdep_assert_held(&cgroup_mutex);
900 lockdep_assert_held(&css_set_rwsem);
902 if (cset == &init_css_set) {
905 struct cgrp_cset_link *link;
907 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
908 struct cgroup *c = link->cgrp;
910 if (c->root == root) {
922 * Return the cgroup for "task" from the given hierarchy. Must be
923 * called with cgroup_mutex and css_set_rwsem held.
925 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
926 struct cgroup_root *root)
929 * No need to lock the task - since we hold cgroup_mutex the
930 * task can't change groups, so the only thing that can happen
931 * is that it exits and its css is set back to init_css_set.
933 return cset_cgroup_from_root(task_css_set(task), root);
937 * A task must hold cgroup_mutex to modify cgroups.
939 * Any task can increment and decrement the count field without lock.
940 * So in general, code holding cgroup_mutex can't rely on the count
941 * field not changing. However, if the count goes to zero, then only
942 * cgroup_attach_task() can increment it again. Because a count of zero
943 * means that no tasks are currently attached, therefore there is no
944 * way a task attached to that cgroup can fork (the other way to
945 * increment the count). So code holding cgroup_mutex can safely
946 * assume that if the count is zero, it will stay zero. Similarly, if
947 * a task holds cgroup_mutex on a cgroup with zero count, it
948 * knows that the cgroup won't be removed, as cgroup_rmdir()
951 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
952 * (usually) take cgroup_mutex. These are the two most performance
953 * critical pieces of code here. The exception occurs on cgroup_exit(),
954 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
955 * is taken, and if the cgroup count is zero, a usermode call made
956 * to the release agent with the name of the cgroup (path relative to
957 * the root of cgroup file system) as the argument.
959 * A cgroup can only be deleted if both its 'count' of using tasks
960 * is zero, and its list of 'children' cgroups is empty. Since all
961 * tasks in the system use _some_ cgroup, and since there is always at
962 * least one task in the system (init, pid == 1), therefore, root cgroup
963 * always has either children cgroups and/or using tasks. So we don't
964 * need a special hack to ensure that root cgroup cannot be deleted.
966 * P.S. One more locking exception. RCU is used to guard the
967 * update of a tasks cgroup pointer by cgroup_attach_task()
970 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask);
971 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
972 static const struct file_operations proc_cgroupstats_operations;
974 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
977 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
978 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
979 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
980 cft->ss->name, cft->name);
982 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
987 * cgroup_file_mode - deduce file mode of a control file
988 * @cft: the control file in question
990 * returns cft->mode if ->mode is not 0
991 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
992 * returns S_IRUGO if it has only a read handler
993 * returns S_IWUSR if it has only a write hander
995 static umode_t cgroup_file_mode(const struct cftype *cft)
1002 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1005 if (cft->write_u64 || cft->write_s64 || cft->write)
1011 static void cgroup_free_fn(struct work_struct *work)
1013 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
1015 atomic_dec(&cgrp->root->nr_cgrps);
1016 cgroup_pidlist_destroy_all(cgrp);
1020 * We get a ref to the parent, and put the ref when this
1021 * cgroup is being freed, so it's guaranteed that the
1022 * parent won't be destroyed before its children.
1024 cgroup_put(cgrp->parent);
1025 kernfs_put(cgrp->kn);
1029 * This is root cgroup's refcnt reaching zero, which
1030 * indicates that the root should be released.
1032 cgroup_destroy_root(cgrp->root);
1036 static void cgroup_free_rcu(struct rcu_head *head)
1038 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
1040 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
1041 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
1044 static void cgroup_get(struct cgroup *cgrp)
1046 WARN_ON_ONCE(cgroup_is_dead(cgrp));
1047 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
1048 atomic_inc(&cgrp->refcnt);
1051 static void cgroup_put(struct cgroup *cgrp)
1053 if (!atomic_dec_and_test(&cgrp->refcnt))
1055 if (WARN_ON_ONCE(cgrp->parent && !cgroup_is_dead(cgrp)))
1058 /* delete this cgroup from parent->children */
1059 mutex_lock(&cgroup_mutex);
1060 list_del_rcu(&cgrp->sibling);
1061 mutex_unlock(&cgroup_mutex);
1063 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
1066 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
1070 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1071 * @kn: the kernfs_node being serviced
1073 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1074 * the method finishes if locking succeeded. Note that once this function
1075 * returns the cgroup returned by cgroup_kn_lock_live() may become
1076 * inaccessible any time. If the caller intends to continue to access the
1077 * cgroup, it should pin it before invoking this function.
1079 static void cgroup_kn_unlock(struct kernfs_node *kn)
1081 struct cgroup *cgrp;
1083 if (kernfs_type(kn) == KERNFS_DIR)
1086 cgrp = kn->parent->priv;
1088 mutex_unlock(&cgroup_mutex);
1090 kernfs_unbreak_active_protection(kn);
1095 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1096 * @kn: the kernfs_node being serviced
1098 * This helper is to be used by a cgroup kernfs method currently servicing
1099 * @kn. It breaks the active protection, performs cgroup locking and
1100 * verifies that the associated cgroup is alive. Returns the cgroup if
1101 * alive; otherwise, %NULL. A successful return should be undone by a
1102 * matching cgroup_kn_unlock() invocation.
1104 * Any cgroup kernfs method implementation which requires locking the
1105 * associated cgroup should use this helper. It avoids nesting cgroup
1106 * locking under kernfs active protection and allows all kernfs operations
1107 * including self-removal.
1109 static struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn)
1111 struct cgroup *cgrp;
1113 if (kernfs_type(kn) == KERNFS_DIR)
1116 cgrp = kn->parent->priv;
1119 * We're gonna grab cgroup_mutex which nests outside kernfs
1120 * active_ref. cgroup liveliness check alone provides enough
1121 * protection against removal. Ensure @cgrp stays accessible and
1122 * break the active_ref protection.
1125 kernfs_break_active_protection(kn);
1127 mutex_lock(&cgroup_mutex);
1129 if (!cgroup_is_dead(cgrp))
1132 cgroup_kn_unlock(kn);
1136 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1138 char name[CGROUP_FILE_NAME_MAX];
1140 lockdep_assert_held(&cgroup_mutex);
1141 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1145 * cgroup_clear_dir - remove subsys files in a cgroup directory
1146 * @cgrp: target cgroup
1147 * @subsys_mask: mask of the subsystem ids whose files should be removed
1149 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned int subsys_mask)
1151 struct cgroup_subsys *ss;
1154 for_each_subsys(ss, i) {
1155 struct cftype *cfts;
1157 if (!(subsys_mask & (1 << i)))
1159 list_for_each_entry(cfts, &ss->cfts, node)
1160 cgroup_addrm_files(cgrp, cfts, false);
1164 static int rebind_subsystems(struct cgroup_root *dst_root, unsigned int ss_mask)
1166 struct cgroup_subsys *ss;
1169 lockdep_assert_held(&cgroup_mutex);
1171 for_each_subsys(ss, ssid) {
1172 if (!(ss_mask & (1 << ssid)))
1175 /* if @ss has non-root csses attached to it, can't move */
1176 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1179 /* can't move between two non-dummy roots either */
1180 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1184 ret = cgroup_populate_dir(&dst_root->cgrp, ss_mask);
1186 if (dst_root != &cgrp_dfl_root)
1190 * Rebinding back to the default root is not allowed to
1191 * fail. Using both default and non-default roots should
1192 * be rare. Moving subsystems back and forth even more so.
1193 * Just warn about it and continue.
1195 if (cgrp_dfl_root_visible) {
1196 pr_warn("failed to create files (%d) while rebinding 0x%x to default root\n",
1198 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1203 * Nothing can fail from this point on. Remove files for the
1204 * removed subsystems and rebind each subsystem.
1206 for_each_subsys(ss, ssid)
1207 if (ss_mask & (1 << ssid))
1208 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1210 for_each_subsys(ss, ssid) {
1211 struct cgroup_root *src_root;
1212 struct cgroup_subsys_state *css;
1213 struct css_set *cset;
1215 if (!(ss_mask & (1 << ssid)))
1218 src_root = ss->root;
1219 css = cgroup_css(&src_root->cgrp, ss);
1221 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1223 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1224 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1225 ss->root = dst_root;
1226 css->cgroup = &dst_root->cgrp;
1228 down_write(&css_set_rwsem);
1229 hash_for_each(css_set_table, i, cset, hlist)
1230 list_move_tail(&cset->e_cset_node[ss->id],
1231 &dst_root->cgrp.e_csets[ss->id]);
1232 up_write(&css_set_rwsem);
1234 src_root->subsys_mask &= ~(1 << ssid);
1235 src_root->cgrp.child_subsys_mask &= ~(1 << ssid);
1237 /* default hierarchy doesn't enable controllers by default */
1238 dst_root->subsys_mask |= 1 << ssid;
1239 if (dst_root != &cgrp_dfl_root)
1240 dst_root->cgrp.child_subsys_mask |= 1 << ssid;
1246 kernfs_activate(dst_root->cgrp.kn);
1250 static int cgroup_show_options(struct seq_file *seq,
1251 struct kernfs_root *kf_root)
1253 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1254 struct cgroup_subsys *ss;
1257 for_each_subsys(ss, ssid)
1258 if (root->subsys_mask & (1 << ssid))
1259 seq_printf(seq, ",%s", ss->name);
1260 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1261 seq_puts(seq, ",sane_behavior");
1262 if (root->flags & CGRP_ROOT_NOPREFIX)
1263 seq_puts(seq, ",noprefix");
1264 if (root->flags & CGRP_ROOT_XATTR)
1265 seq_puts(seq, ",xattr");
1267 spin_lock(&release_agent_path_lock);
1268 if (strlen(root->release_agent_path))
1269 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1270 spin_unlock(&release_agent_path_lock);
1272 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1273 seq_puts(seq, ",clone_children");
1274 if (strlen(root->name))
1275 seq_printf(seq, ",name=%s", root->name);
1279 struct cgroup_sb_opts {
1280 unsigned int subsys_mask;
1282 char *release_agent;
1283 bool cpuset_clone_children;
1285 /* User explicitly requested empty subsystem */
1289 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1291 char *token, *o = data;
1292 bool all_ss = false, one_ss = false;
1293 unsigned int mask = -1U;
1294 struct cgroup_subsys *ss;
1297 #ifdef CONFIG_CPUSETS
1298 mask = ~(1U << cpuset_cgrp_id);
1301 memset(opts, 0, sizeof(*opts));
1303 while ((token = strsep(&o, ",")) != NULL) {
1306 if (!strcmp(token, "none")) {
1307 /* Explicitly have no subsystems */
1311 if (!strcmp(token, "all")) {
1312 /* Mutually exclusive option 'all' + subsystem name */
1318 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1319 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1322 if (!strcmp(token, "noprefix")) {
1323 opts->flags |= CGRP_ROOT_NOPREFIX;
1326 if (!strcmp(token, "clone_children")) {
1327 opts->cpuset_clone_children = true;
1330 if (!strcmp(token, "xattr")) {
1331 opts->flags |= CGRP_ROOT_XATTR;
1334 if (!strncmp(token, "release_agent=", 14)) {
1335 /* Specifying two release agents is forbidden */
1336 if (opts->release_agent)
1338 opts->release_agent =
1339 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1340 if (!opts->release_agent)
1344 if (!strncmp(token, "name=", 5)) {
1345 const char *name = token + 5;
1346 /* Can't specify an empty name */
1349 /* Must match [\w.-]+ */
1350 for (i = 0; i < strlen(name); i++) {
1354 if ((c == '.') || (c == '-') || (c == '_'))
1358 /* Specifying two names is forbidden */
1361 opts->name = kstrndup(name,
1362 MAX_CGROUP_ROOT_NAMELEN - 1,
1370 for_each_subsys(ss, i) {
1371 if (strcmp(token, ss->name))
1376 /* Mutually exclusive option 'all' + subsystem name */
1379 opts->subsys_mask |= (1 << i);
1384 if (i == CGROUP_SUBSYS_COUNT)
1388 /* Consistency checks */
1390 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1391 pr_warn("sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1393 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1394 opts->cpuset_clone_children || opts->release_agent ||
1396 pr_err("sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1401 * If the 'all' option was specified select all the
1402 * subsystems, otherwise if 'none', 'name=' and a subsystem
1403 * name options were not specified, let's default to 'all'
1405 if (all_ss || (!one_ss && !opts->none && !opts->name))
1406 for_each_subsys(ss, i)
1408 opts->subsys_mask |= (1 << i);
1411 * We either have to specify by name or by subsystems. (So
1412 * all empty hierarchies must have a name).
1414 if (!opts->subsys_mask && !opts->name)
1419 * Option noprefix was introduced just for backward compatibility
1420 * with the old cpuset, so we allow noprefix only if mounting just
1421 * the cpuset subsystem.
1423 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1427 /* Can't specify "none" and some subsystems */
1428 if (opts->subsys_mask && opts->none)
1434 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1437 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1438 struct cgroup_sb_opts opts;
1439 unsigned int added_mask, removed_mask;
1441 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1442 pr_err("sane_behavior: remount is not allowed\n");
1446 mutex_lock(&cgroup_mutex);
1448 /* See what subsystems are wanted */
1449 ret = parse_cgroupfs_options(data, &opts);
1453 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1454 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1455 task_tgid_nr(current), current->comm);
1457 added_mask = opts.subsys_mask & ~root->subsys_mask;
1458 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1460 /* Don't allow flags or name to change at remount */
1461 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1462 (opts.name && strcmp(opts.name, root->name))) {
1463 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1464 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1465 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1470 /* remounting is not allowed for populated hierarchies */
1471 if (!list_empty(&root->cgrp.children)) {
1476 ret = rebind_subsystems(root, added_mask);
1480 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1482 if (opts.release_agent) {
1483 spin_lock(&release_agent_path_lock);
1484 strcpy(root->release_agent_path, opts.release_agent);
1485 spin_unlock(&release_agent_path_lock);
1488 kfree(opts.release_agent);
1490 mutex_unlock(&cgroup_mutex);
1495 * To reduce the fork() overhead for systems that are not actually using
1496 * their cgroups capability, we don't maintain the lists running through
1497 * each css_set to its tasks until we see the list actually used - in other
1498 * words after the first mount.
1500 static bool use_task_css_set_links __read_mostly;
1502 static void cgroup_enable_task_cg_lists(void)
1504 struct task_struct *p, *g;
1506 down_write(&css_set_rwsem);
1508 if (use_task_css_set_links)
1511 use_task_css_set_links = true;
1514 * We need tasklist_lock because RCU is not safe against
1515 * while_each_thread(). Besides, a forking task that has passed
1516 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1517 * is not guaranteed to have its child immediately visible in the
1518 * tasklist if we walk through it with RCU.
1520 read_lock(&tasklist_lock);
1521 do_each_thread(g, p) {
1522 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1523 task_css_set(p) != &init_css_set);
1526 * We should check if the process is exiting, otherwise
1527 * it will race with cgroup_exit() in that the list
1528 * entry won't be deleted though the process has exited.
1529 * Do it while holding siglock so that we don't end up
1530 * racing against cgroup_exit().
1532 spin_lock_irq(&p->sighand->siglock);
1533 if (!(p->flags & PF_EXITING)) {
1534 struct css_set *cset = task_css_set(p);
1536 list_add(&p->cg_list, &cset->tasks);
1539 spin_unlock_irq(&p->sighand->siglock);
1540 } while_each_thread(g, p);
1541 read_unlock(&tasklist_lock);
1543 up_write(&css_set_rwsem);
1546 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1548 struct cgroup_subsys *ss;
1551 atomic_set(&cgrp->refcnt, 1);
1552 INIT_LIST_HEAD(&cgrp->sibling);
1553 INIT_LIST_HEAD(&cgrp->children);
1554 INIT_LIST_HEAD(&cgrp->cset_links);
1555 INIT_LIST_HEAD(&cgrp->release_list);
1556 INIT_LIST_HEAD(&cgrp->pidlists);
1557 mutex_init(&cgrp->pidlist_mutex);
1558 cgrp->self.cgroup = cgrp;
1560 for_each_subsys(ss, ssid)
1561 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1563 init_waitqueue_head(&cgrp->offline_waitq);
1566 static void init_cgroup_root(struct cgroup_root *root,
1567 struct cgroup_sb_opts *opts)
1569 struct cgroup *cgrp = &root->cgrp;
1571 INIT_LIST_HEAD(&root->root_list);
1572 atomic_set(&root->nr_cgrps, 1);
1574 init_cgroup_housekeeping(cgrp);
1575 idr_init(&root->cgroup_idr);
1577 root->flags = opts->flags;
1578 if (opts->release_agent)
1579 strcpy(root->release_agent_path, opts->release_agent);
1581 strcpy(root->name, opts->name);
1582 if (opts->cpuset_clone_children)
1583 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1586 static int cgroup_setup_root(struct cgroup_root *root, unsigned int ss_mask)
1588 LIST_HEAD(tmp_links);
1589 struct cgroup *root_cgrp = &root->cgrp;
1590 struct css_set *cset;
1593 lockdep_assert_held(&cgroup_mutex);
1595 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_NOWAIT);
1598 root_cgrp->id = ret;
1601 * We're accessing css_set_count without locking css_set_rwsem here,
1602 * but that's OK - it can only be increased by someone holding
1603 * cgroup_lock, and that's us. The worst that can happen is that we
1604 * have some link structures left over
1606 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1610 ret = cgroup_init_root_id(root);
1614 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1615 KERNFS_ROOT_CREATE_DEACTIVATED,
1617 if (IS_ERR(root->kf_root)) {
1618 ret = PTR_ERR(root->kf_root);
1621 root_cgrp->kn = root->kf_root->kn;
1623 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1627 ret = rebind_subsystems(root, ss_mask);
1632 * There must be no failure case after here, since rebinding takes
1633 * care of subsystems' refcounts, which are explicitly dropped in
1634 * the failure exit path.
1636 list_add(&root->root_list, &cgroup_roots);
1637 cgroup_root_count++;
1640 * Link the root cgroup in this hierarchy into all the css_set
1643 down_write(&css_set_rwsem);
1644 hash_for_each(css_set_table, i, cset, hlist)
1645 link_css_set(&tmp_links, cset, root_cgrp);
1646 up_write(&css_set_rwsem);
1648 BUG_ON(!list_empty(&root_cgrp->children));
1649 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1651 kernfs_activate(root_cgrp->kn);
1656 kernfs_destroy_root(root->kf_root);
1657 root->kf_root = NULL;
1659 cgroup_exit_root_id(root);
1661 free_cgrp_cset_links(&tmp_links);
1665 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1666 int flags, const char *unused_dev_name,
1669 struct cgroup_root *root;
1670 struct cgroup_sb_opts opts;
1671 struct dentry *dentry;
1676 * The first time anyone tries to mount a cgroup, enable the list
1677 * linking each css_set to its tasks and fix up all existing tasks.
1679 if (!use_task_css_set_links)
1680 cgroup_enable_task_cg_lists();
1682 mutex_lock(&cgroup_mutex);
1684 /* First find the desired set of subsystems */
1685 ret = parse_cgroupfs_options(data, &opts);
1689 /* look for a matching existing root */
1690 if (!opts.subsys_mask && !opts.none && !opts.name) {
1691 cgrp_dfl_root_visible = true;
1692 root = &cgrp_dfl_root;
1693 cgroup_get(&root->cgrp);
1698 for_each_root(root) {
1699 bool name_match = false;
1701 if (root == &cgrp_dfl_root)
1705 * If we asked for a name then it must match. Also, if
1706 * name matches but sybsys_mask doesn't, we should fail.
1707 * Remember whether name matched.
1710 if (strcmp(opts.name, root->name))
1716 * If we asked for subsystems (or explicitly for no
1717 * subsystems) then they must match.
1719 if ((opts.subsys_mask || opts.none) &&
1720 (opts.subsys_mask != root->subsys_mask)) {
1727 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1728 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1729 pr_err("sane_behavior: new mount options should match the existing superblock\n");
1733 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1738 * A root's lifetime is governed by its root cgroup. Zero
1739 * ref indicate that the root is being destroyed. Wait for
1740 * destruction to complete so that the subsystems are free.
1741 * We can use wait_queue for the wait but this path is
1742 * super cold. Let's just sleep for a bit and retry.
1744 if (!atomic_inc_not_zero(&root->cgrp.refcnt)) {
1745 mutex_unlock(&cgroup_mutex);
1747 ret = restart_syscall();
1756 * No such thing, create a new one. name= matching without subsys
1757 * specification is allowed for already existing hierarchies but we
1758 * can't create new one without subsys specification.
1760 if (!opts.subsys_mask && !opts.none) {
1765 root = kzalloc(sizeof(*root), GFP_KERNEL);
1771 init_cgroup_root(root, &opts);
1773 ret = cgroup_setup_root(root, opts.subsys_mask);
1775 cgroup_free_root(root);
1778 mutex_unlock(&cgroup_mutex);
1780 kfree(opts.release_agent);
1784 return ERR_PTR(ret);
1786 dentry = kernfs_mount(fs_type, flags, root->kf_root, &new_sb);
1787 if (IS_ERR(dentry) || !new_sb)
1788 cgroup_put(&root->cgrp);
1792 static void cgroup_kill_sb(struct super_block *sb)
1794 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1795 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1797 cgroup_put(&root->cgrp);
1801 static struct file_system_type cgroup_fs_type = {
1803 .mount = cgroup_mount,
1804 .kill_sb = cgroup_kill_sb,
1807 static struct kobject *cgroup_kobj;
1810 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1811 * @task: target task
1812 * @buf: the buffer to write the path into
1813 * @buflen: the length of the buffer
1815 * Determine @task's cgroup on the first (the one with the lowest non-zero
1816 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1817 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1818 * cgroup controller callbacks.
1820 * Return value is the same as kernfs_path().
1822 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1824 struct cgroup_root *root;
1825 struct cgroup *cgrp;
1826 int hierarchy_id = 1;
1829 mutex_lock(&cgroup_mutex);
1830 down_read(&css_set_rwsem);
1832 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1835 cgrp = task_cgroup_from_root(task, root);
1836 path = cgroup_path(cgrp, buf, buflen);
1838 /* if no hierarchy exists, everyone is in "/" */
1839 if (strlcpy(buf, "/", buflen) < buflen)
1843 up_read(&css_set_rwsem);
1844 mutex_unlock(&cgroup_mutex);
1847 EXPORT_SYMBOL_GPL(task_cgroup_path);
1849 /* used to track tasks and other necessary states during migration */
1850 struct cgroup_taskset {
1851 /* the src and dst cset list running through cset->mg_node */
1852 struct list_head src_csets;
1853 struct list_head dst_csets;
1856 * Fields for cgroup_taskset_*() iteration.
1858 * Before migration is committed, the target migration tasks are on
1859 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1860 * the csets on ->dst_csets. ->csets point to either ->src_csets
1861 * or ->dst_csets depending on whether migration is committed.
1863 * ->cur_csets and ->cur_task point to the current task position
1866 struct list_head *csets;
1867 struct css_set *cur_cset;
1868 struct task_struct *cur_task;
1872 * cgroup_taskset_first - reset taskset and return the first task
1873 * @tset: taskset of interest
1875 * @tset iteration is initialized and the first task is returned.
1877 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1879 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1880 tset->cur_task = NULL;
1882 return cgroup_taskset_next(tset);
1886 * cgroup_taskset_next - iterate to the next task in taskset
1887 * @tset: taskset of interest
1889 * Return the next task in @tset. Iteration must have been initialized
1890 * with cgroup_taskset_first().
1892 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1894 struct css_set *cset = tset->cur_cset;
1895 struct task_struct *task = tset->cur_task;
1897 while (&cset->mg_node != tset->csets) {
1899 task = list_first_entry(&cset->mg_tasks,
1900 struct task_struct, cg_list);
1902 task = list_next_entry(task, cg_list);
1904 if (&task->cg_list != &cset->mg_tasks) {
1905 tset->cur_cset = cset;
1906 tset->cur_task = task;
1910 cset = list_next_entry(cset, mg_node);
1918 * cgroup_task_migrate - move a task from one cgroup to another.
1919 * @old_cgrp: the cgroup @tsk is being migrated from
1920 * @tsk: the task being migrated
1921 * @new_cset: the new css_set @tsk is being attached to
1923 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1925 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1926 struct task_struct *tsk,
1927 struct css_set *new_cset)
1929 struct css_set *old_cset;
1931 lockdep_assert_held(&cgroup_mutex);
1932 lockdep_assert_held(&css_set_rwsem);
1935 * We are synchronized through threadgroup_lock() against PF_EXITING
1936 * setting such that we can't race against cgroup_exit() changing the
1937 * css_set to init_css_set and dropping the old one.
1939 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1940 old_cset = task_css_set(tsk);
1942 get_css_set(new_cset);
1943 rcu_assign_pointer(tsk->cgroups, new_cset);
1946 * Use move_tail so that cgroup_taskset_first() still returns the
1947 * leader after migration. This works because cgroup_migrate()
1948 * ensures that the dst_cset of the leader is the first on the
1949 * tset's dst_csets list.
1951 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
1954 * We just gained a reference on old_cset by taking it from the
1955 * task. As trading it for new_cset is protected by cgroup_mutex,
1956 * we're safe to drop it here; it will be freed under RCU.
1958 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1959 put_css_set_locked(old_cset, false);
1963 * cgroup_migrate_finish - cleanup after attach
1964 * @preloaded_csets: list of preloaded css_sets
1966 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1967 * those functions for details.
1969 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1971 struct css_set *cset, *tmp_cset;
1973 lockdep_assert_held(&cgroup_mutex);
1975 down_write(&css_set_rwsem);
1976 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1977 cset->mg_src_cgrp = NULL;
1978 cset->mg_dst_cset = NULL;
1979 list_del_init(&cset->mg_preload_node);
1980 put_css_set_locked(cset, false);
1982 up_write(&css_set_rwsem);
1986 * cgroup_migrate_add_src - add a migration source css_set
1987 * @src_cset: the source css_set to add
1988 * @dst_cgrp: the destination cgroup
1989 * @preloaded_csets: list of preloaded css_sets
1991 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1992 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1993 * up by cgroup_migrate_finish().
1995 * This function may be called without holding threadgroup_lock even if the
1996 * target is a process. Threads may be created and destroyed but as long
1997 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1998 * the preloaded css_sets are guaranteed to cover all migrations.
2000 static void cgroup_migrate_add_src(struct css_set *src_cset,
2001 struct cgroup *dst_cgrp,
2002 struct list_head *preloaded_csets)
2004 struct cgroup *src_cgrp;
2006 lockdep_assert_held(&cgroup_mutex);
2007 lockdep_assert_held(&css_set_rwsem);
2009 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2011 if (!list_empty(&src_cset->mg_preload_node))
2014 WARN_ON(src_cset->mg_src_cgrp);
2015 WARN_ON(!list_empty(&src_cset->mg_tasks));
2016 WARN_ON(!list_empty(&src_cset->mg_node));
2018 src_cset->mg_src_cgrp = src_cgrp;
2019 get_css_set(src_cset);
2020 list_add(&src_cset->mg_preload_node, preloaded_csets);
2024 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2025 * @dst_cgrp: the destination cgroup (may be %NULL)
2026 * @preloaded_csets: list of preloaded source css_sets
2028 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
2029 * have been preloaded to @preloaded_csets. This function looks up and
2030 * pins all destination css_sets, links each to its source, and append them
2031 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
2032 * source css_set is assumed to be its cgroup on the default hierarchy.
2034 * This function must be called after cgroup_migrate_add_src() has been
2035 * called on each migration source css_set. After migration is performed
2036 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2039 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
2040 struct list_head *preloaded_csets)
2043 struct css_set *src_cset, *tmp_cset;
2045 lockdep_assert_held(&cgroup_mutex);
2048 * Except for the root, child_subsys_mask must be zero for a cgroup
2049 * with tasks so that child cgroups don't compete against tasks.
2051 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && dst_cgrp->parent &&
2052 dst_cgrp->child_subsys_mask)
2055 /* look up the dst cset for each src cset and link it to src */
2056 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2057 struct css_set *dst_cset;
2059 dst_cset = find_css_set(src_cset,
2060 dst_cgrp ?: src_cset->dfl_cgrp);
2064 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2067 * If src cset equals dst, it's noop. Drop the src.
2068 * cgroup_migrate() will skip the cset too. Note that we
2069 * can't handle src == dst as some nodes are used by both.
2071 if (src_cset == dst_cset) {
2072 src_cset->mg_src_cgrp = NULL;
2073 list_del_init(&src_cset->mg_preload_node);
2074 put_css_set(src_cset, false);
2075 put_css_set(dst_cset, false);
2079 src_cset->mg_dst_cset = dst_cset;
2081 if (list_empty(&dst_cset->mg_preload_node))
2082 list_add(&dst_cset->mg_preload_node, &csets);
2084 put_css_set(dst_cset, false);
2087 list_splice_tail(&csets, preloaded_csets);
2090 cgroup_migrate_finish(&csets);
2095 * cgroup_migrate - migrate a process or task to a cgroup
2096 * @cgrp: the destination cgroup
2097 * @leader: the leader of the process or the task to migrate
2098 * @threadgroup: whether @leader points to the whole process or a single task
2100 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2101 * process, the caller must be holding threadgroup_lock of @leader. The
2102 * caller is also responsible for invoking cgroup_migrate_add_src() and
2103 * cgroup_migrate_prepare_dst() on the targets before invoking this
2104 * function and following up with cgroup_migrate_finish().
2106 * As long as a controller's ->can_attach() doesn't fail, this function is
2107 * guaranteed to succeed. This means that, excluding ->can_attach()
2108 * failure, when migrating multiple targets, the success or failure can be
2109 * decided for all targets by invoking group_migrate_prepare_dst() before
2110 * actually starting migrating.
2112 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
2115 struct cgroup_taskset tset = {
2116 .src_csets = LIST_HEAD_INIT(tset.src_csets),
2117 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
2118 .csets = &tset.src_csets,
2120 struct cgroup_subsys_state *css, *failed_css = NULL;
2121 struct css_set *cset, *tmp_cset;
2122 struct task_struct *task, *tmp_task;
2126 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2127 * already PF_EXITING could be freed from underneath us unless we
2128 * take an rcu_read_lock.
2130 down_write(&css_set_rwsem);
2134 /* @task either already exited or can't exit until the end */
2135 if (task->flags & PF_EXITING)
2138 /* leave @task alone if post_fork() hasn't linked it yet */
2139 if (list_empty(&task->cg_list))
2142 cset = task_css_set(task);
2143 if (!cset->mg_src_cgrp)
2147 * cgroup_taskset_first() must always return the leader.
2148 * Take care to avoid disturbing the ordering.
2150 list_move_tail(&task->cg_list, &cset->mg_tasks);
2151 if (list_empty(&cset->mg_node))
2152 list_add_tail(&cset->mg_node, &tset.src_csets);
2153 if (list_empty(&cset->mg_dst_cset->mg_node))
2154 list_move_tail(&cset->mg_dst_cset->mg_node,
2159 } while_each_thread(leader, task);
2161 up_write(&css_set_rwsem);
2163 /* methods shouldn't be called if no task is actually migrating */
2164 if (list_empty(&tset.src_csets))
2167 /* check that we can legitimately attach to the cgroup */
2168 for_each_e_css(css, i, cgrp) {
2169 if (css->ss->can_attach) {
2170 ret = css->ss->can_attach(css, &tset);
2173 goto out_cancel_attach;
2179 * Now that we're guaranteed success, proceed to move all tasks to
2180 * the new cgroup. There are no failure cases after here, so this
2181 * is the commit point.
2183 down_write(&css_set_rwsem);
2184 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2185 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2186 cgroup_task_migrate(cset->mg_src_cgrp, task,
2189 up_write(&css_set_rwsem);
2192 * Migration is committed, all target tasks are now on dst_csets.
2193 * Nothing is sensitive to fork() after this point. Notify
2194 * controllers that migration is complete.
2196 tset.csets = &tset.dst_csets;
2198 for_each_e_css(css, i, cgrp)
2199 if (css->ss->attach)
2200 css->ss->attach(css, &tset);
2203 goto out_release_tset;
2206 for_each_e_css(css, i, cgrp) {
2207 if (css == failed_css)
2209 if (css->ss->cancel_attach)
2210 css->ss->cancel_attach(css, &tset);
2213 down_write(&css_set_rwsem);
2214 list_splice_init(&tset.dst_csets, &tset.src_csets);
2215 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2216 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2217 list_del_init(&cset->mg_node);
2219 up_write(&css_set_rwsem);
2224 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2225 * @dst_cgrp: the cgroup to attach to
2226 * @leader: the task or the leader of the threadgroup to be attached
2227 * @threadgroup: attach the whole threadgroup?
2229 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2231 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2232 struct task_struct *leader, bool threadgroup)
2234 LIST_HEAD(preloaded_csets);
2235 struct task_struct *task;
2238 /* look up all src csets */
2239 down_read(&css_set_rwsem);
2243 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2247 } while_each_thread(leader, task);
2249 up_read(&css_set_rwsem);
2251 /* prepare dst csets and commit */
2252 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2254 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2256 cgroup_migrate_finish(&preloaded_csets);
2261 * Find the task_struct of the task to attach by vpid and pass it along to the
2262 * function to attach either it or all tasks in its threadgroup. Will lock
2263 * cgroup_mutex and threadgroup.
2265 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
2266 size_t nbytes, loff_t off, bool threadgroup)
2268 struct task_struct *tsk;
2269 const struct cred *cred = current_cred(), *tcred;
2270 struct cgroup *cgrp;
2274 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2277 cgrp = cgroup_kn_lock_live(of->kn);
2284 tsk = find_task_by_vpid(pid);
2288 goto out_unlock_cgroup;
2291 * even if we're attaching all tasks in the thread group, we
2292 * only need to check permissions on one of them.
2294 tcred = __task_cred(tsk);
2295 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2296 !uid_eq(cred->euid, tcred->uid) &&
2297 !uid_eq(cred->euid, tcred->suid)) {
2300 goto out_unlock_cgroup;
2306 tsk = tsk->group_leader;
2309 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2310 * trapped in a cpuset, or RT worker may be born in a cgroup
2311 * with no rt_runtime allocated. Just say no.
2313 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2316 goto out_unlock_cgroup;
2319 get_task_struct(tsk);
2322 threadgroup_lock(tsk);
2324 if (!thread_group_leader(tsk)) {
2326 * a race with de_thread from another thread's exec()
2327 * may strip us of our leadership, if this happens,
2328 * there is no choice but to throw this task away and
2329 * try again; this is
2330 * "double-double-toil-and-trouble-check locking".
2332 threadgroup_unlock(tsk);
2333 put_task_struct(tsk);
2334 goto retry_find_task;
2338 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2340 threadgroup_unlock(tsk);
2342 put_task_struct(tsk);
2344 cgroup_kn_unlock(of->kn);
2345 return ret ?: nbytes;
2349 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2350 * @from: attach to all cgroups of a given task
2351 * @tsk: the task to be attached
2353 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2355 struct cgroup_root *root;
2358 mutex_lock(&cgroup_mutex);
2359 for_each_root(root) {
2360 struct cgroup *from_cgrp;
2362 if (root == &cgrp_dfl_root)
2365 down_read(&css_set_rwsem);
2366 from_cgrp = task_cgroup_from_root(from, root);
2367 up_read(&css_set_rwsem);
2369 retval = cgroup_attach_task(from_cgrp, tsk, false);
2373 mutex_unlock(&cgroup_mutex);
2377 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2379 static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
2380 char *buf, size_t nbytes, loff_t off)
2382 return __cgroup_procs_write(of, buf, nbytes, off, false);
2385 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
2386 char *buf, size_t nbytes, loff_t off)
2388 return __cgroup_procs_write(of, buf, nbytes, off, true);
2391 static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
2392 char *buf, size_t nbytes, loff_t off)
2394 struct cgroup *cgrp;
2396 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2398 cgrp = cgroup_kn_lock_live(of->kn);
2401 spin_lock(&release_agent_path_lock);
2402 strlcpy(cgrp->root->release_agent_path, strstrip(buf),
2403 sizeof(cgrp->root->release_agent_path));
2404 spin_unlock(&release_agent_path_lock);
2405 cgroup_kn_unlock(of->kn);
2409 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2411 struct cgroup *cgrp = seq_css(seq)->cgroup;
2413 spin_lock(&release_agent_path_lock);
2414 seq_puts(seq, cgrp->root->release_agent_path);
2415 spin_unlock(&release_agent_path_lock);
2416 seq_putc(seq, '\n');
2420 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2422 struct cgroup *cgrp = seq_css(seq)->cgroup;
2424 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2428 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned int ss_mask)
2430 struct cgroup_subsys *ss;
2431 bool printed = false;
2434 for_each_subsys(ss, ssid) {
2435 if (ss_mask & (1 << ssid)) {
2438 seq_printf(seq, "%s", ss->name);
2443 seq_putc(seq, '\n');
2446 /* show controllers which are currently attached to the default hierarchy */
2447 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2449 struct cgroup *cgrp = seq_css(seq)->cgroup;
2451 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask);
2455 /* show controllers which are enabled from the parent */
2456 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2458 struct cgroup *cgrp = seq_css(seq)->cgroup;
2460 cgroup_print_ss_mask(seq, cgrp->parent->child_subsys_mask);
2464 /* show controllers which are enabled for a given cgroup's children */
2465 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2467 struct cgroup *cgrp = seq_css(seq)->cgroup;
2469 cgroup_print_ss_mask(seq, cgrp->child_subsys_mask);
2474 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2475 * @cgrp: root of the subtree to update csses for
2477 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2478 * css associations need to be updated accordingly. This function looks up
2479 * all css_sets which are attached to the subtree, creates the matching
2480 * updated css_sets and migrates the tasks to the new ones.
2482 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2484 LIST_HEAD(preloaded_csets);
2485 struct cgroup_subsys_state *css;
2486 struct css_set *src_cset;
2489 lockdep_assert_held(&cgroup_mutex);
2491 /* look up all csses currently attached to @cgrp's subtree */
2492 down_read(&css_set_rwsem);
2493 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2494 struct cgrp_cset_link *link;
2496 /* self is not affected by child_subsys_mask change */
2497 if (css->cgroup == cgrp)
2500 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2501 cgroup_migrate_add_src(link->cset, cgrp,
2504 up_read(&css_set_rwsem);
2506 /* NULL dst indicates self on default hierarchy */
2507 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2511 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2512 struct task_struct *last_task = NULL, *task;
2514 /* src_csets precede dst_csets, break on the first dst_cset */
2515 if (!src_cset->mg_src_cgrp)
2519 * All tasks in src_cset need to be migrated to the
2520 * matching dst_cset. Empty it process by process. We
2521 * walk tasks but migrate processes. The leader might even
2522 * belong to a different cset but such src_cset would also
2523 * be among the target src_csets because the default
2524 * hierarchy enforces per-process membership.
2527 down_read(&css_set_rwsem);
2528 task = list_first_entry_or_null(&src_cset->tasks,
2529 struct task_struct, cg_list);
2531 task = task->group_leader;
2532 WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
2533 get_task_struct(task);
2535 up_read(&css_set_rwsem);
2540 /* guard against possible infinite loop */
2541 if (WARN(last_task == task,
2542 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2546 threadgroup_lock(task);
2547 /* raced against de_thread() from another thread? */
2548 if (!thread_group_leader(task)) {
2549 threadgroup_unlock(task);
2550 put_task_struct(task);
2554 ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
2556 threadgroup_unlock(task);
2557 put_task_struct(task);
2559 if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
2565 cgroup_migrate_finish(&preloaded_csets);
2569 /* change the enabled child controllers for a cgroup in the default hierarchy */
2570 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
2571 char *buf, size_t nbytes,
2574 unsigned int enable = 0, disable = 0;
2575 struct cgroup *cgrp, *child;
2576 struct cgroup_subsys *ss;
2581 * Parse input - space separated list of subsystem names prefixed
2582 * with either + or -.
2584 buf = strstrip(buf);
2585 while ((tok = strsep(&buf, " "))) {
2588 for_each_subsys(ss, ssid) {
2589 if (ss->disabled || strcmp(tok + 1, ss->name))
2593 enable |= 1 << ssid;
2594 disable &= ~(1 << ssid);
2595 } else if (*tok == '-') {
2596 disable |= 1 << ssid;
2597 enable &= ~(1 << ssid);
2603 if (ssid == CGROUP_SUBSYS_COUNT)
2607 cgrp = cgroup_kn_lock_live(of->kn);
2611 for_each_subsys(ss, ssid) {
2612 if (enable & (1 << ssid)) {
2613 if (cgrp->child_subsys_mask & (1 << ssid)) {
2614 enable &= ~(1 << ssid);
2619 * Because css offlining is asynchronous, userland
2620 * might try to re-enable the same controller while
2621 * the previous instance is still around. In such
2622 * cases, wait till it's gone using offline_waitq.
2624 cgroup_for_each_live_child(child, cgrp) {
2627 if (!cgroup_css(child, ss))
2631 prepare_to_wait(&child->offline_waitq, &wait,
2632 TASK_UNINTERRUPTIBLE);
2633 cgroup_kn_unlock(of->kn);
2635 finish_wait(&child->offline_waitq, &wait);
2638 return restart_syscall();
2641 /* unavailable or not enabled on the parent? */
2642 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2644 !(cgrp->parent->child_subsys_mask & (1 << ssid)))) {
2648 } else if (disable & (1 << ssid)) {
2649 if (!(cgrp->child_subsys_mask & (1 << ssid))) {
2650 disable &= ~(1 << ssid);
2654 /* a child has it enabled? */
2655 cgroup_for_each_live_child(child, cgrp) {
2656 if (child->child_subsys_mask & (1 << ssid)) {
2664 if (!enable && !disable) {
2670 * Except for the root, child_subsys_mask must be zero for a cgroup
2671 * with tasks so that child cgroups don't compete against tasks.
2673 if (enable && cgrp->parent && !list_empty(&cgrp->cset_links)) {
2679 * Create csses for enables and update child_subsys_mask. This
2680 * changes cgroup_e_css() results which in turn makes the
2681 * subsequent cgroup_update_dfl_csses() associate all tasks in the
2682 * subtree to the updated csses.
2684 for_each_subsys(ss, ssid) {
2685 if (!(enable & (1 << ssid)))
2688 cgroup_for_each_live_child(child, cgrp) {
2689 ret = create_css(child, ss);
2695 cgrp->child_subsys_mask |= enable;
2696 cgrp->child_subsys_mask &= ~disable;
2698 ret = cgroup_update_dfl_csses(cgrp);
2702 /* all tasks are now migrated away from the old csses, kill them */
2703 for_each_subsys(ss, ssid) {
2704 if (!(disable & (1 << ssid)))
2707 cgroup_for_each_live_child(child, cgrp)
2708 kill_css(cgroup_css(child, ss));
2711 kernfs_activate(cgrp->kn);
2714 cgroup_kn_unlock(of->kn);
2715 return ret ?: nbytes;
2718 cgrp->child_subsys_mask &= ~enable;
2719 cgrp->child_subsys_mask |= disable;
2721 for_each_subsys(ss, ssid) {
2722 if (!(enable & (1 << ssid)))
2725 cgroup_for_each_live_child(child, cgrp) {
2726 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2734 static int cgroup_populated_show(struct seq_file *seq, void *v)
2736 seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
2740 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2741 size_t nbytes, loff_t off)
2743 struct cgroup *cgrp = of->kn->parent->priv;
2744 struct cftype *cft = of->kn->priv;
2745 struct cgroup_subsys_state *css;
2749 return cft->write(of, buf, nbytes, off);
2752 * kernfs guarantees that a file isn't deleted with operations in
2753 * flight, which means that the matching css is and stays alive and
2754 * doesn't need to be pinned. The RCU locking is not necessary
2755 * either. It's just for the convenience of using cgroup_css().
2758 css = cgroup_css(cgrp, cft->ss);
2761 if (cft->write_u64) {
2762 unsigned long long v;
2763 ret = kstrtoull(buf, 0, &v);
2765 ret = cft->write_u64(css, cft, v);
2766 } else if (cft->write_s64) {
2768 ret = kstrtoll(buf, 0, &v);
2770 ret = cft->write_s64(css, cft, v);
2775 return ret ?: nbytes;
2778 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2780 return seq_cft(seq)->seq_start(seq, ppos);
2783 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2785 return seq_cft(seq)->seq_next(seq, v, ppos);
2788 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2790 seq_cft(seq)->seq_stop(seq, v);
2793 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2795 struct cftype *cft = seq_cft(m);
2796 struct cgroup_subsys_state *css = seq_css(m);
2799 return cft->seq_show(m, arg);
2802 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2803 else if (cft->read_s64)
2804 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2810 static struct kernfs_ops cgroup_kf_single_ops = {
2811 .atomic_write_len = PAGE_SIZE,
2812 .write = cgroup_file_write,
2813 .seq_show = cgroup_seqfile_show,
2816 static struct kernfs_ops cgroup_kf_ops = {
2817 .atomic_write_len = PAGE_SIZE,
2818 .write = cgroup_file_write,
2819 .seq_start = cgroup_seqfile_start,
2820 .seq_next = cgroup_seqfile_next,
2821 .seq_stop = cgroup_seqfile_stop,
2822 .seq_show = cgroup_seqfile_show,
2826 * cgroup_rename - Only allow simple rename of directories in place.
2828 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2829 const char *new_name_str)
2831 struct cgroup *cgrp = kn->priv;
2834 if (kernfs_type(kn) != KERNFS_DIR)
2836 if (kn->parent != new_parent)
2840 * This isn't a proper migration and its usefulness is very
2841 * limited. Disallow if sane_behavior.
2843 if (cgroup_sane_behavior(cgrp))
2847 * We're gonna grab cgroup_mutex which nests outside kernfs
2848 * active_ref. kernfs_rename() doesn't require active_ref
2849 * protection. Break them before grabbing cgroup_mutex.
2851 kernfs_break_active_protection(new_parent);
2852 kernfs_break_active_protection(kn);
2854 mutex_lock(&cgroup_mutex);
2856 ret = kernfs_rename(kn, new_parent, new_name_str);
2858 mutex_unlock(&cgroup_mutex);
2860 kernfs_unbreak_active_protection(kn);
2861 kernfs_unbreak_active_protection(new_parent);
2865 /* set uid and gid of cgroup dirs and files to that of the creator */
2866 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
2868 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
2869 .ia_uid = current_fsuid(),
2870 .ia_gid = current_fsgid(), };
2872 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
2873 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
2876 return kernfs_setattr(kn, &iattr);
2879 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2881 char name[CGROUP_FILE_NAME_MAX];
2882 struct kernfs_node *kn;
2883 struct lock_class_key *key = NULL;
2886 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2887 key = &cft->lockdep_key;
2889 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2890 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2895 ret = cgroup_kn_set_ugid(kn);
2901 if (cft->seq_show == cgroup_populated_show)
2902 cgrp->populated_kn = kn;
2907 * cgroup_addrm_files - add or remove files to a cgroup directory
2908 * @cgrp: the target cgroup
2909 * @cfts: array of cftypes to be added
2910 * @is_add: whether to add or remove
2912 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2913 * For removals, this function never fails. If addition fails, this
2914 * function doesn't remove files already added. The caller is responsible
2917 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2923 lockdep_assert_held(&cgroup_mutex);
2925 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2926 /* does cft->flags tell us to skip this file on @cgrp? */
2927 if ((cft->flags & CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
2929 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2931 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2933 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2937 ret = cgroup_add_file(cgrp, cft);
2939 pr_warn("%s: failed to add %s, err=%d\n",
2940 __func__, cft->name, ret);
2944 cgroup_rm_file(cgrp, cft);
2950 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2953 struct cgroup_subsys *ss = cfts[0].ss;
2954 struct cgroup *root = &ss->root->cgrp;
2955 struct cgroup_subsys_state *css;
2958 lockdep_assert_held(&cgroup_mutex);
2960 /* add/rm files for all cgroups created before */
2961 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2962 struct cgroup *cgrp = css->cgroup;
2964 if (cgroup_is_dead(cgrp))
2967 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2973 kernfs_activate(root->kn);
2977 static void cgroup_exit_cftypes(struct cftype *cfts)
2981 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2982 /* free copy for custom atomic_write_len, see init_cftypes() */
2983 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2990 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2994 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2995 struct kernfs_ops *kf_ops;
2997 WARN_ON(cft->ss || cft->kf_ops);
3000 kf_ops = &cgroup_kf_ops;
3002 kf_ops = &cgroup_kf_single_ops;
3005 * Ugh... if @cft wants a custom max_write_len, we need to
3006 * make a copy of kf_ops to set its atomic_write_len.
3008 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3009 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3011 cgroup_exit_cftypes(cfts);
3014 kf_ops->atomic_write_len = cft->max_write_len;
3017 cft->kf_ops = kf_ops;
3024 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3026 lockdep_assert_held(&cgroup_mutex);
3028 if (!cfts || !cfts[0].ss)
3031 list_del(&cfts->node);
3032 cgroup_apply_cftypes(cfts, false);
3033 cgroup_exit_cftypes(cfts);
3038 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3039 * @cfts: zero-length name terminated array of cftypes
3041 * Unregister @cfts. Files described by @cfts are removed from all
3042 * existing cgroups and all future cgroups won't have them either. This
3043 * function can be called anytime whether @cfts' subsys is attached or not.
3045 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3048 int cgroup_rm_cftypes(struct cftype *cfts)
3052 mutex_lock(&cgroup_mutex);
3053 ret = cgroup_rm_cftypes_locked(cfts);
3054 mutex_unlock(&cgroup_mutex);
3059 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3060 * @ss: target cgroup subsystem
3061 * @cfts: zero-length name terminated array of cftypes
3063 * Register @cfts to @ss. Files described by @cfts are created for all
3064 * existing cgroups to which @ss is attached and all future cgroups will
3065 * have them too. This function can be called anytime whether @ss is
3068 * Returns 0 on successful registration, -errno on failure. Note that this
3069 * function currently returns 0 as long as @cfts registration is successful
3070 * even if some file creation attempts on existing cgroups fail.
3072 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3076 if (!cfts || cfts[0].name[0] == '\0')
3079 ret = cgroup_init_cftypes(ss, cfts);
3083 mutex_lock(&cgroup_mutex);
3085 list_add_tail(&cfts->node, &ss->cfts);
3086 ret = cgroup_apply_cftypes(cfts, true);
3088 cgroup_rm_cftypes_locked(cfts);
3090 mutex_unlock(&cgroup_mutex);
3095 * cgroup_task_count - count the number of tasks in a cgroup.
3096 * @cgrp: the cgroup in question
3098 * Return the number of tasks in the cgroup.
3100 static int cgroup_task_count(const struct cgroup *cgrp)
3103 struct cgrp_cset_link *link;
3105 down_read(&css_set_rwsem);
3106 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3107 count += atomic_read(&link->cset->refcount);
3108 up_read(&css_set_rwsem);
3113 * css_next_child - find the next child of a given css
3114 * @pos_css: the current position (%NULL to initiate traversal)
3115 * @parent_css: css whose children to walk
3117 * This function returns the next child of @parent_css and should be called
3118 * under either cgroup_mutex or RCU read lock. The only requirement is
3119 * that @parent_css and @pos_css are accessible. The next sibling is
3120 * guaranteed to be returned regardless of their states.
3122 struct cgroup_subsys_state *
3123 css_next_child(struct cgroup_subsys_state *pos_css,
3124 struct cgroup_subsys_state *parent_css)
3126 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3127 struct cgroup *cgrp = parent_css->cgroup;
3128 struct cgroup *next;
3130 cgroup_assert_mutex_or_rcu_locked();
3133 * @pos could already have been removed. Once a cgroup is removed,
3134 * its ->sibling.next is no longer updated when its next sibling
3135 * changes. As CGRP_DEAD assertion is serialized and happens
3136 * before the cgroup is taken off the ->sibling list, if we see it
3137 * unasserted, it's guaranteed that the next sibling hasn't
3138 * finished its grace period even if it's already removed, and thus
3139 * safe to dereference from this RCU critical section. If
3140 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3141 * to be visible as %true here.
3143 * If @pos is dead, its next pointer can't be dereferenced;
3144 * however, as each cgroup is given a monotonically increasing
3145 * unique serial number and always appended to the sibling list,
3146 * the next one can be found by walking the parent's children until
3147 * we see a cgroup with higher serial number than @pos's. While
3148 * this path can be slower, it's taken only when either the current
3149 * cgroup is removed or iteration and removal race.
3152 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3153 } else if (likely(!cgroup_is_dead(pos))) {
3154 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3156 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3157 if (next->serial_nr > pos->serial_nr)
3162 * @next, if not pointing to the head, can be dereferenced and is
3163 * the next sibling; however, it might have @ss disabled. If so,
3164 * fast-forward to the next enabled one.
3166 while (&next->sibling != &cgrp->children) {
3167 struct cgroup_subsys_state *next_css = cgroup_css(next, parent_css->ss);
3171 next = list_entry_rcu(next->sibling.next, struct cgroup, sibling);
3177 * css_next_descendant_pre - find the next descendant for pre-order walk
3178 * @pos: the current position (%NULL to initiate traversal)
3179 * @root: css whose descendants to walk
3181 * To be used by css_for_each_descendant_pre(). Find the next descendant
3182 * to visit for pre-order traversal of @root's descendants. @root is
3183 * included in the iteration and the first node to be visited.
3185 * While this function requires cgroup_mutex or RCU read locking, it
3186 * doesn't require the whole traversal to be contained in a single critical
3187 * section. This function will return the correct next descendant as long
3188 * as both @pos and @root are accessible and @pos is a descendant of @root.
3190 struct cgroup_subsys_state *
3191 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3192 struct cgroup_subsys_state *root)
3194 struct cgroup_subsys_state *next;
3196 cgroup_assert_mutex_or_rcu_locked();
3198 /* if first iteration, visit @root */
3202 /* visit the first child if exists */
3203 next = css_next_child(NULL, pos);
3207 /* no child, visit my or the closest ancestor's next sibling */
3208 while (pos != root) {
3209 next = css_next_child(pos, css_parent(pos));
3212 pos = css_parent(pos);
3219 * css_rightmost_descendant - return the rightmost descendant of a css
3220 * @pos: css of interest
3222 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3223 * is returned. This can be used during pre-order traversal to skip
3226 * While this function requires cgroup_mutex or RCU read locking, it
3227 * doesn't require the whole traversal to be contained in a single critical
3228 * section. This function will return the correct rightmost descendant as
3229 * long as @pos is accessible.
3231 struct cgroup_subsys_state *
3232 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3234 struct cgroup_subsys_state *last, *tmp;
3236 cgroup_assert_mutex_or_rcu_locked();
3240 /* ->prev isn't RCU safe, walk ->next till the end */
3242 css_for_each_child(tmp, last)
3249 static struct cgroup_subsys_state *
3250 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3252 struct cgroup_subsys_state *last;
3256 pos = css_next_child(NULL, pos);
3263 * css_next_descendant_post - find the next descendant for post-order walk
3264 * @pos: the current position (%NULL to initiate traversal)
3265 * @root: css whose descendants to walk
3267 * To be used by css_for_each_descendant_post(). Find the next descendant
3268 * to visit for post-order traversal of @root's descendants. @root is
3269 * included in the iteration and the last node to be visited.
3271 * While this function requires cgroup_mutex or RCU read locking, it
3272 * doesn't require the whole traversal to be contained in a single critical
3273 * section. This function will return the correct next descendant as long
3274 * as both @pos and @cgroup are accessible and @pos is a descendant of
3277 struct cgroup_subsys_state *
3278 css_next_descendant_post(struct cgroup_subsys_state *pos,
3279 struct cgroup_subsys_state *root)
3281 struct cgroup_subsys_state *next;
3283 cgroup_assert_mutex_or_rcu_locked();
3285 /* if first iteration, visit leftmost descendant which may be @root */
3287 return css_leftmost_descendant(root);
3289 /* if we visited @root, we're done */
3293 /* if there's an unvisited sibling, visit its leftmost descendant */
3294 next = css_next_child(pos, css_parent(pos));
3296 return css_leftmost_descendant(next);
3298 /* no sibling left, visit parent */
3299 return css_parent(pos);
3302 static bool cgroup_has_live_children(struct cgroup *cgrp)
3304 struct cgroup *child;
3307 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
3308 if (!cgroup_is_dead(child)) {
3318 * css_advance_task_iter - advance a task itererator to the next css_set
3319 * @it: the iterator to advance
3321 * Advance @it to the next css_set to walk.
3323 static void css_advance_task_iter(struct css_task_iter *it)
3325 struct list_head *l = it->cset_pos;
3326 struct cgrp_cset_link *link;
3327 struct css_set *cset;
3329 /* Advance to the next non-empty css_set */
3332 if (l == it->cset_head) {
3333 it->cset_pos = NULL;
3338 cset = container_of(l, struct css_set,
3339 e_cset_node[it->ss->id]);
3341 link = list_entry(l, struct cgrp_cset_link, cset_link);
3344 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
3348 if (!list_empty(&cset->tasks))
3349 it->task_pos = cset->tasks.next;
3351 it->task_pos = cset->mg_tasks.next;
3353 it->tasks_head = &cset->tasks;
3354 it->mg_tasks_head = &cset->mg_tasks;
3358 * css_task_iter_start - initiate task iteration
3359 * @css: the css to walk tasks of
3360 * @it: the task iterator to use
3362 * Initiate iteration through the tasks of @css. The caller can call
3363 * css_task_iter_next() to walk through the tasks until the function
3364 * returns NULL. On completion of iteration, css_task_iter_end() must be
3367 * Note that this function acquires a lock which is released when the
3368 * iteration finishes. The caller can't sleep while iteration is in
3371 void css_task_iter_start(struct cgroup_subsys_state *css,
3372 struct css_task_iter *it)
3373 __acquires(css_set_rwsem)
3375 /* no one should try to iterate before mounting cgroups */
3376 WARN_ON_ONCE(!use_task_css_set_links);
3378 down_read(&css_set_rwsem);
3383 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3385 it->cset_pos = &css->cgroup->cset_links;
3387 it->cset_head = it->cset_pos;
3389 css_advance_task_iter(it);
3393 * css_task_iter_next - return the next task for the iterator
3394 * @it: the task iterator being iterated
3396 * The "next" function for task iteration. @it should have been
3397 * initialized via css_task_iter_start(). Returns NULL when the iteration
3400 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3402 struct task_struct *res;
3403 struct list_head *l = it->task_pos;
3405 /* If the iterator cg is NULL, we have no tasks */
3408 res = list_entry(l, struct task_struct, cg_list);
3411 * Advance iterator to find next entry. cset->tasks is consumed
3412 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3417 if (l == it->tasks_head)
3418 l = it->mg_tasks_head->next;
3420 if (l == it->mg_tasks_head)
3421 css_advance_task_iter(it);
3429 * css_task_iter_end - finish task iteration
3430 * @it: the task iterator to finish
3432 * Finish task iteration started by css_task_iter_start().
3434 void css_task_iter_end(struct css_task_iter *it)
3435 __releases(css_set_rwsem)
3437 up_read(&css_set_rwsem);
3441 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3442 * @to: cgroup to which the tasks will be moved
3443 * @from: cgroup in which the tasks currently reside
3445 * Locking rules between cgroup_post_fork() and the migration path
3446 * guarantee that, if a task is forking while being migrated, the new child
3447 * is guaranteed to be either visible in the source cgroup after the
3448 * parent's migration is complete or put into the target cgroup. No task
3449 * can slip out of migration through forking.
3451 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3453 LIST_HEAD(preloaded_csets);
3454 struct cgrp_cset_link *link;
3455 struct css_task_iter it;
3456 struct task_struct *task;
3459 mutex_lock(&cgroup_mutex);
3461 /* all tasks in @from are being moved, all csets are source */
3462 down_read(&css_set_rwsem);
3463 list_for_each_entry(link, &from->cset_links, cset_link)
3464 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
3465 up_read(&css_set_rwsem);
3467 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
3472 * Migrate tasks one-by-one until @form is empty. This fails iff
3473 * ->can_attach() fails.
3476 css_task_iter_start(&from->self, &it);
3477 task = css_task_iter_next(&it);
3479 get_task_struct(task);
3480 css_task_iter_end(&it);
3483 ret = cgroup_migrate(to, task, false);
3484 put_task_struct(task);
3486 } while (task && !ret);
3488 cgroup_migrate_finish(&preloaded_csets);
3489 mutex_unlock(&cgroup_mutex);
3494 * Stuff for reading the 'tasks'/'procs' files.
3496 * Reading this file can return large amounts of data if a cgroup has
3497 * *lots* of attached tasks. So it may need several calls to read(),
3498 * but we cannot guarantee that the information we produce is correct
3499 * unless we produce it entirely atomically.
3503 /* which pidlist file are we talking about? */
3504 enum cgroup_filetype {
3510 * A pidlist is a list of pids that virtually represents the contents of one
3511 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3512 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3515 struct cgroup_pidlist {
3517 * used to find which pidlist is wanted. doesn't change as long as
3518 * this particular list stays in the list.
3520 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3523 /* how many elements the above list has */
3525 /* each of these stored in a list by its cgroup */
3526 struct list_head links;
3527 /* pointer to the cgroup we belong to, for list removal purposes */
3528 struct cgroup *owner;
3529 /* for delayed destruction */
3530 struct delayed_work destroy_dwork;
3534 * The following two functions "fix" the issue where there are more pids
3535 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3536 * TODO: replace with a kernel-wide solution to this problem
3538 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3539 static void *pidlist_allocate(int count)
3541 if (PIDLIST_TOO_LARGE(count))
3542 return vmalloc(count * sizeof(pid_t));
3544 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3547 static void pidlist_free(void *p)
3549 if (is_vmalloc_addr(p))
3556 * Used to destroy all pidlists lingering waiting for destroy timer. None
3557 * should be left afterwards.
3559 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3561 struct cgroup_pidlist *l, *tmp_l;
3563 mutex_lock(&cgrp->pidlist_mutex);
3564 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3565 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3566 mutex_unlock(&cgrp->pidlist_mutex);
3568 flush_workqueue(cgroup_pidlist_destroy_wq);
3569 BUG_ON(!list_empty(&cgrp->pidlists));
3572 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3574 struct delayed_work *dwork = to_delayed_work(work);
3575 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3577 struct cgroup_pidlist *tofree = NULL;
3579 mutex_lock(&l->owner->pidlist_mutex);
3582 * Destroy iff we didn't get queued again. The state won't change
3583 * as destroy_dwork can only be queued while locked.
3585 if (!delayed_work_pending(dwork)) {
3586 list_del(&l->links);
3587 pidlist_free(l->list);
3588 put_pid_ns(l->key.ns);
3592 mutex_unlock(&l->owner->pidlist_mutex);
3597 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3598 * Returns the number of unique elements.
3600 static int pidlist_uniq(pid_t *list, int length)
3605 * we presume the 0th element is unique, so i starts at 1. trivial
3606 * edge cases first; no work needs to be done for either
3608 if (length == 0 || length == 1)
3610 /* src and dest walk down the list; dest counts unique elements */
3611 for (src = 1; src < length; src++) {
3612 /* find next unique element */
3613 while (list[src] == list[src-1]) {
3618 /* dest always points to where the next unique element goes */
3619 list[dest] = list[src];
3627 * The two pid files - task and cgroup.procs - guaranteed that the result
3628 * is sorted, which forced this whole pidlist fiasco. As pid order is
3629 * different per namespace, each namespace needs differently sorted list,
3630 * making it impossible to use, for example, single rbtree of member tasks
3631 * sorted by task pointer. As pidlists can be fairly large, allocating one
3632 * per open file is dangerous, so cgroup had to implement shared pool of
3633 * pidlists keyed by cgroup and namespace.
3635 * All this extra complexity was caused by the original implementation
3636 * committing to an entirely unnecessary property. In the long term, we
3637 * want to do away with it. Explicitly scramble sort order if
3638 * sane_behavior so that no such expectation exists in the new interface.
3640 * Scrambling is done by swapping every two consecutive bits, which is
3641 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3643 static pid_t pid_fry(pid_t pid)
3645 unsigned a = pid & 0x55555555;
3646 unsigned b = pid & 0xAAAAAAAA;
3648 return (a << 1) | (b >> 1);
3651 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3653 if (cgroup_sane_behavior(cgrp))
3654 return pid_fry(pid);
3659 static int cmppid(const void *a, const void *b)
3661 return *(pid_t *)a - *(pid_t *)b;
3664 static int fried_cmppid(const void *a, const void *b)
3666 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3669 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3670 enum cgroup_filetype type)
3672 struct cgroup_pidlist *l;
3673 /* don't need task_nsproxy() if we're looking at ourself */
3674 struct pid_namespace *ns = task_active_pid_ns(current);
3676 lockdep_assert_held(&cgrp->pidlist_mutex);
3678 list_for_each_entry(l, &cgrp->pidlists, links)
3679 if (l->key.type == type && l->key.ns == ns)
3685 * find the appropriate pidlist for our purpose (given procs vs tasks)
3686 * returns with the lock on that pidlist already held, and takes care
3687 * of the use count, or returns NULL with no locks held if we're out of
3690 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3691 enum cgroup_filetype type)
3693 struct cgroup_pidlist *l;
3695 lockdep_assert_held(&cgrp->pidlist_mutex);
3697 l = cgroup_pidlist_find(cgrp, type);
3701 /* entry not found; create a new one */
3702 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3706 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3708 /* don't need task_nsproxy() if we're looking at ourself */
3709 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3711 list_add(&l->links, &cgrp->pidlists);
3716 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3718 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3719 struct cgroup_pidlist **lp)
3723 int pid, n = 0; /* used for populating the array */
3724 struct css_task_iter it;
3725 struct task_struct *tsk;
3726 struct cgroup_pidlist *l;
3728 lockdep_assert_held(&cgrp->pidlist_mutex);
3731 * If cgroup gets more users after we read count, we won't have
3732 * enough space - tough. This race is indistinguishable to the
3733 * caller from the case that the additional cgroup users didn't
3734 * show up until sometime later on.
3736 length = cgroup_task_count(cgrp);
3737 array = pidlist_allocate(length);
3740 /* now, populate the array */
3741 css_task_iter_start(&cgrp->self, &it);
3742 while ((tsk = css_task_iter_next(&it))) {
3743 if (unlikely(n == length))
3745 /* get tgid or pid for procs or tasks file respectively */
3746 if (type == CGROUP_FILE_PROCS)
3747 pid = task_tgid_vnr(tsk);
3749 pid = task_pid_vnr(tsk);
3750 if (pid > 0) /* make sure to only use valid results */
3753 css_task_iter_end(&it);
3755 /* now sort & (if procs) strip out duplicates */
3756 if (cgroup_sane_behavior(cgrp))
3757 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3759 sort(array, length, sizeof(pid_t), cmppid, NULL);
3760 if (type == CGROUP_FILE_PROCS)
3761 length = pidlist_uniq(array, length);
3763 l = cgroup_pidlist_find_create(cgrp, type);
3765 mutex_unlock(&cgrp->pidlist_mutex);
3766 pidlist_free(array);
3770 /* store array, freeing old if necessary */
3771 pidlist_free(l->list);
3779 * cgroupstats_build - build and fill cgroupstats
3780 * @stats: cgroupstats to fill information into
3781 * @dentry: A dentry entry belonging to the cgroup for which stats have
3784 * Build and fill cgroupstats so that taskstats can export it to user
3787 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3789 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3790 struct cgroup *cgrp;
3791 struct css_task_iter it;
3792 struct task_struct *tsk;
3794 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3795 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3796 kernfs_type(kn) != KERNFS_DIR)
3799 mutex_lock(&cgroup_mutex);
3802 * We aren't being called from kernfs and there's no guarantee on
3803 * @kn->priv's validity. For this and css_tryget_online_from_dir(),
3804 * @kn->priv is RCU safe. Let's do the RCU dancing.
3807 cgrp = rcu_dereference(kn->priv);
3808 if (!cgrp || cgroup_is_dead(cgrp)) {
3810 mutex_unlock(&cgroup_mutex);
3815 css_task_iter_start(&cgrp->self, &it);
3816 while ((tsk = css_task_iter_next(&it))) {
3817 switch (tsk->state) {
3819 stats->nr_running++;
3821 case TASK_INTERRUPTIBLE:
3822 stats->nr_sleeping++;
3824 case TASK_UNINTERRUPTIBLE:
3825 stats->nr_uninterruptible++;
3828 stats->nr_stopped++;
3831 if (delayacct_is_task_waiting_on_io(tsk))
3832 stats->nr_io_wait++;
3836 css_task_iter_end(&it);
3838 mutex_unlock(&cgroup_mutex);
3844 * seq_file methods for the tasks/procs files. The seq_file position is the
3845 * next pid to display; the seq_file iterator is a pointer to the pid
3846 * in the cgroup->l->list array.
3849 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3852 * Initially we receive a position value that corresponds to
3853 * one more than the last pid shown (or 0 on the first call or
3854 * after a seek to the start). Use a binary-search to find the
3855 * next pid to display, if any
3857 struct kernfs_open_file *of = s->private;
3858 struct cgroup *cgrp = seq_css(s)->cgroup;
3859 struct cgroup_pidlist *l;
3860 enum cgroup_filetype type = seq_cft(s)->private;
3861 int index = 0, pid = *pos;
3864 mutex_lock(&cgrp->pidlist_mutex);
3867 * !NULL @of->priv indicates that this isn't the first start()
3868 * after open. If the matching pidlist is around, we can use that.
3869 * Look for it. Note that @of->priv can't be used directly. It
3870 * could already have been destroyed.
3873 of->priv = cgroup_pidlist_find(cgrp, type);
3876 * Either this is the first start() after open or the matching
3877 * pidlist has been destroyed inbetween. Create a new one.
3880 ret = pidlist_array_load(cgrp, type,
3881 (struct cgroup_pidlist **)&of->priv);
3883 return ERR_PTR(ret);
3888 int end = l->length;
3890 while (index < end) {
3891 int mid = (index + end) / 2;
3892 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3895 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3901 /* If we're off the end of the array, we're done */
3902 if (index >= l->length)
3904 /* Update the abstract position to be the actual pid that we found */
3905 iter = l->list + index;
3906 *pos = cgroup_pid_fry(cgrp, *iter);
3910 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3912 struct kernfs_open_file *of = s->private;
3913 struct cgroup_pidlist *l = of->priv;
3916 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3917 CGROUP_PIDLIST_DESTROY_DELAY);
3918 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3921 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3923 struct kernfs_open_file *of = s->private;
3924 struct cgroup_pidlist *l = of->priv;
3926 pid_t *end = l->list + l->length;
3928 * Advance to the next pid in the array. If this goes off the
3935 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3940 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3942 return seq_printf(s, "%d\n", *(int *)v);
3945 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3948 return notify_on_release(css->cgroup);
3951 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3952 struct cftype *cft, u64 val)
3954 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3956 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3958 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3962 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3965 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3968 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3969 struct cftype *cft, u64 val)
3972 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3974 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3978 static struct cftype cgroup_base_files[] = {
3980 .name = "cgroup.procs",
3981 .seq_start = cgroup_pidlist_start,
3982 .seq_next = cgroup_pidlist_next,
3983 .seq_stop = cgroup_pidlist_stop,
3984 .seq_show = cgroup_pidlist_show,
3985 .private = CGROUP_FILE_PROCS,
3986 .write = cgroup_procs_write,
3987 .mode = S_IRUGO | S_IWUSR,
3990 .name = "cgroup.clone_children",
3991 .flags = CFTYPE_INSANE,
3992 .read_u64 = cgroup_clone_children_read,
3993 .write_u64 = cgroup_clone_children_write,
3996 .name = "cgroup.sane_behavior",
3997 .flags = CFTYPE_ONLY_ON_ROOT,
3998 .seq_show = cgroup_sane_behavior_show,
4001 .name = "cgroup.controllers",
4002 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_ONLY_ON_ROOT,
4003 .seq_show = cgroup_root_controllers_show,
4006 .name = "cgroup.controllers",
4007 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
4008 .seq_show = cgroup_controllers_show,
4011 .name = "cgroup.subtree_control",
4012 .flags = CFTYPE_ONLY_ON_DFL,
4013 .seq_show = cgroup_subtree_control_show,
4014 .write = cgroup_subtree_control_write,
4017 .name = "cgroup.populated",
4018 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
4019 .seq_show = cgroup_populated_show,
4023 * Historical crazy stuff. These don't have "cgroup." prefix and
4024 * don't exist if sane_behavior. If you're depending on these, be
4025 * prepared to be burned.
4029 .flags = CFTYPE_INSANE, /* use "procs" instead */
4030 .seq_start = cgroup_pidlist_start,
4031 .seq_next = cgroup_pidlist_next,
4032 .seq_stop = cgroup_pidlist_stop,
4033 .seq_show = cgroup_pidlist_show,
4034 .private = CGROUP_FILE_TASKS,
4035 .write = cgroup_tasks_write,
4036 .mode = S_IRUGO | S_IWUSR,
4039 .name = "notify_on_release",
4040 .flags = CFTYPE_INSANE,
4041 .read_u64 = cgroup_read_notify_on_release,
4042 .write_u64 = cgroup_write_notify_on_release,
4045 .name = "release_agent",
4046 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4047 .seq_show = cgroup_release_agent_show,
4048 .write = cgroup_release_agent_write,
4049 .max_write_len = PATH_MAX - 1,
4055 * cgroup_populate_dir - create subsys files in a cgroup directory
4056 * @cgrp: target cgroup
4057 * @subsys_mask: mask of the subsystem ids whose files should be added
4059 * On failure, no file is added.
4061 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask)
4063 struct cgroup_subsys *ss;
4066 /* process cftsets of each subsystem */
4067 for_each_subsys(ss, i) {
4068 struct cftype *cfts;
4070 if (!(subsys_mask & (1 << i)))
4073 list_for_each_entry(cfts, &ss->cfts, node) {
4074 ret = cgroup_addrm_files(cgrp, cfts, true);
4081 cgroup_clear_dir(cgrp, subsys_mask);
4086 * css destruction is four-stage process.
4088 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4089 * Implemented in kill_css().
4091 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4092 * and thus css_tryget_online() is guaranteed to fail, the css can be
4093 * offlined by invoking offline_css(). After offlining, the base ref is
4094 * put. Implemented in css_killed_work_fn().
4096 * 3. When the percpu_ref reaches zero, the only possible remaining
4097 * accessors are inside RCU read sections. css_release() schedules the
4100 * 4. After the grace period, the css can be freed. Implemented in
4101 * css_free_work_fn().
4103 * It is actually hairier because both step 2 and 4 require process context
4104 * and thus involve punting to css->destroy_work adding two additional
4105 * steps to the already complex sequence.
4107 static void css_free_work_fn(struct work_struct *work)
4109 struct cgroup_subsys_state *css =
4110 container_of(work, struct cgroup_subsys_state, destroy_work);
4111 struct cgroup *cgrp = css->cgroup;
4114 css_put(css->parent);
4116 css->ss->css_free(css);
4120 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4122 struct cgroup_subsys_state *css =
4123 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4125 INIT_WORK(&css->destroy_work, css_free_work_fn);
4126 queue_work(cgroup_destroy_wq, &css->destroy_work);
4129 static void css_release(struct percpu_ref *ref)
4131 struct cgroup_subsys_state *css =
4132 container_of(ref, struct cgroup_subsys_state, refcnt);
4133 struct cgroup_subsys *ss = css->ss;
4135 cgroup_idr_remove(&ss->css_idr, css->id);
4137 call_rcu(&css->rcu_head, css_free_rcu_fn);
4140 static void init_and_link_css(struct cgroup_subsys_state *css,
4141 struct cgroup_subsys *ss, struct cgroup *cgrp)
4150 css->parent = cgroup_css(cgrp->parent, ss);
4151 css_get(css->parent);
4153 css->flags |= CSS_ROOT;
4156 BUG_ON(cgroup_css(cgrp, ss));
4159 /* invoke ->css_online() on a new CSS and mark it online if successful */
4160 static int online_css(struct cgroup_subsys_state *css)
4162 struct cgroup_subsys *ss = css->ss;
4165 lockdep_assert_held(&cgroup_mutex);
4168 ret = ss->css_online(css);
4170 css->flags |= CSS_ONLINE;
4171 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4176 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4177 static void offline_css(struct cgroup_subsys_state *css)
4179 struct cgroup_subsys *ss = css->ss;
4181 lockdep_assert_held(&cgroup_mutex);
4183 if (!(css->flags & CSS_ONLINE))
4186 if (ss->css_offline)
4187 ss->css_offline(css);
4189 css->flags &= ~CSS_ONLINE;
4190 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4192 wake_up_all(&css->cgroup->offline_waitq);
4196 * create_css - create a cgroup_subsys_state
4197 * @cgrp: the cgroup new css will be associated with
4198 * @ss: the subsys of new css
4200 * Create a new css associated with @cgrp - @ss pair. On success, the new
4201 * css is online and installed in @cgrp with all interface files created.
4202 * Returns 0 on success, -errno on failure.
4204 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4206 struct cgroup *parent = cgrp->parent;
4207 struct cgroup_subsys_state *css;
4210 lockdep_assert_held(&cgroup_mutex);
4212 css = ss->css_alloc(cgroup_css(parent, ss));
4214 return PTR_ERR(css);
4216 init_and_link_css(css, ss, cgrp);
4218 err = percpu_ref_init(&css->refcnt, css_release);
4222 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_NOWAIT);
4224 goto err_free_percpu_ref;
4227 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4231 /* @css is ready to be brought online now, make it visible */
4232 cgroup_idr_replace(&ss->css_idr, css, css->id);
4234 err = online_css(css);
4238 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4240 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4241 current->comm, current->pid, ss->name);
4242 if (!strcmp(ss->name, "memory"))
4243 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4244 ss->warned_broken_hierarchy = true;
4250 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4252 cgroup_idr_remove(&ss->css_idr, css->id);
4253 err_free_percpu_ref:
4254 percpu_ref_cancel_init(&css->refcnt);
4256 call_rcu(&css->rcu_head, css_free_rcu_fn);
4260 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4263 struct cgroup *parent, *cgrp;
4264 struct cgroup_root *root;
4265 struct cgroup_subsys *ss;
4266 struct kernfs_node *kn;
4269 parent = cgroup_kn_lock_live(parent_kn);
4272 root = parent->root;
4274 /* allocate the cgroup and its ID, 0 is reserved for the root */
4275 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4282 * Temporarily set the pointer to NULL, so idr_find() won't return
4283 * a half-baked cgroup.
4285 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_NOWAIT);
4291 init_cgroup_housekeeping(cgrp);
4293 cgrp->parent = parent;
4294 cgrp->self.parent = &parent->self;
4297 if (notify_on_release(parent))
4298 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4300 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4301 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4303 /* create the directory */
4304 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4312 * This extra ref will be put in cgroup_free_fn() and guarantees
4313 * that @cgrp->kn is always accessible.
4317 cgrp->serial_nr = cgroup_serial_nr_next++;
4319 /* allocation complete, commit to creation */
4320 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4321 atomic_inc(&root->nr_cgrps);
4325 * @cgrp is now fully operational. If something fails after this
4326 * point, it'll be released via the normal destruction path.
4328 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4330 ret = cgroup_kn_set_ugid(kn);
4334 ret = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4338 /* let's create and online css's */
4339 for_each_subsys(ss, ssid) {
4340 if (parent->child_subsys_mask & (1 << ssid)) {
4341 ret = create_css(cgrp, ss);
4348 * On the default hierarchy, a child doesn't automatically inherit
4349 * child_subsys_mask from the parent. Each is configured manually.
4351 if (!cgroup_on_dfl(cgrp))
4352 cgrp->child_subsys_mask = parent->child_subsys_mask;
4354 kernfs_activate(kn);
4360 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4364 cgroup_kn_unlock(parent_kn);
4368 cgroup_destroy_locked(cgrp);
4373 * This is called when the refcnt of a css is confirmed to be killed.
4374 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
4375 * initate destruction and put the css ref from kill_css().
4377 static void css_killed_work_fn(struct work_struct *work)
4379 struct cgroup_subsys_state *css =
4380 container_of(work, struct cgroup_subsys_state, destroy_work);
4382 mutex_lock(&cgroup_mutex);
4384 mutex_unlock(&cgroup_mutex);
4389 /* css kill confirmation processing requires process context, bounce */
4390 static void css_killed_ref_fn(struct percpu_ref *ref)
4392 struct cgroup_subsys_state *css =
4393 container_of(ref, struct cgroup_subsys_state, refcnt);
4395 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4396 queue_work(cgroup_destroy_wq, &css->destroy_work);
4400 * kill_css - destroy a css
4401 * @css: css to destroy
4403 * This function initiates destruction of @css by removing cgroup interface
4404 * files and putting its base reference. ->css_offline() will be invoked
4405 * asynchronously once css_tryget_online() is guaranteed to fail and when
4406 * the reference count reaches zero, @css will be released.
4408 static void kill_css(struct cgroup_subsys_state *css)
4410 lockdep_assert_held(&cgroup_mutex);
4413 * This must happen before css is disassociated with its cgroup.
4414 * See seq_css() for details.
4416 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4419 * Killing would put the base ref, but we need to keep it alive
4420 * until after ->css_offline().
4425 * cgroup core guarantees that, by the time ->css_offline() is
4426 * invoked, no new css reference will be given out via
4427 * css_tryget_online(). We can't simply call percpu_ref_kill() and
4428 * proceed to offlining css's because percpu_ref_kill() doesn't
4429 * guarantee that the ref is seen as killed on all CPUs on return.
4431 * Use percpu_ref_kill_and_confirm() to get notifications as each
4432 * css is confirmed to be seen as killed on all CPUs.
4434 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4438 * cgroup_destroy_locked - the first stage of cgroup destruction
4439 * @cgrp: cgroup to be destroyed
4441 * css's make use of percpu refcnts whose killing latency shouldn't be
4442 * exposed to userland and are RCU protected. Also, cgroup core needs to
4443 * guarantee that css_tryget_online() won't succeed by the time
4444 * ->css_offline() is invoked. To satisfy all the requirements,
4445 * destruction is implemented in the following two steps.
4447 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4448 * userland visible parts and start killing the percpu refcnts of
4449 * css's. Set up so that the next stage will be kicked off once all
4450 * the percpu refcnts are confirmed to be killed.
4452 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4453 * rest of destruction. Once all cgroup references are gone, the
4454 * cgroup is RCU-freed.
4456 * This function implements s1. After this step, @cgrp is gone as far as
4457 * the userland is concerned and a new cgroup with the same name may be
4458 * created. As cgroup doesn't care about the names internally, this
4459 * doesn't cause any problem.
4461 static int cgroup_destroy_locked(struct cgroup *cgrp)
4462 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4464 struct cgroup_subsys_state *css;
4468 lockdep_assert_held(&cgroup_mutex);
4471 * css_set_rwsem synchronizes access to ->cset_links and prevents
4472 * @cgrp from being removed while put_css_set() is in progress.
4474 down_read(&css_set_rwsem);
4475 empty = list_empty(&cgrp->cset_links);
4476 up_read(&css_set_rwsem);
4481 * Make sure there's no live children. We can't test ->children
4482 * emptiness as dead children linger on it while being destroyed;
4483 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4485 if (cgroup_has_live_children(cgrp))
4489 * Mark @cgrp dead. This prevents further task migration and child
4490 * creation by disabling cgroup_lock_live_group(). Note that
4491 * CGRP_DEAD assertion is depended upon by css_next_child() to
4492 * resume iteration after dropping RCU read lock. See
4493 * css_next_child() for details.
4495 set_bit(CGRP_DEAD, &cgrp->flags);
4497 /* initiate massacre of all css's */
4498 for_each_css(css, ssid, cgrp)
4501 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4502 raw_spin_lock(&release_list_lock);
4503 if (!list_empty(&cgrp->release_list))
4504 list_del_init(&cgrp->release_list);
4505 raw_spin_unlock(&release_list_lock);
4508 * Remove @cgrp directory along with the base files. @cgrp has an
4509 * extra ref on its kn.
4511 kernfs_remove(cgrp->kn);
4513 set_bit(CGRP_RELEASABLE, &cgrp->parent->flags);
4514 check_for_release(cgrp->parent);
4516 /* put the base reference */
4522 static int cgroup_rmdir(struct kernfs_node *kn)
4524 struct cgroup *cgrp;
4527 cgrp = cgroup_kn_lock_live(kn);
4530 cgroup_get(cgrp); /* for @kn->priv clearing */
4532 ret = cgroup_destroy_locked(cgrp);
4534 cgroup_kn_unlock(kn);
4537 * There are two control paths which try to determine cgroup from
4538 * dentry without going through kernfs - cgroupstats_build() and
4539 * css_tryget_online_from_dir(). Those are supported by RCU
4540 * protecting clearing of cgrp->kn->priv backpointer, which should
4541 * happen after all files under it have been removed.
4544 RCU_INIT_POINTER(*(void __rcu __force **)&kn->priv, NULL);
4550 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4551 .remount_fs = cgroup_remount,
4552 .show_options = cgroup_show_options,
4553 .mkdir = cgroup_mkdir,
4554 .rmdir = cgroup_rmdir,
4555 .rename = cgroup_rename,
4558 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
4560 struct cgroup_subsys_state *css;
4562 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4564 mutex_lock(&cgroup_mutex);
4566 idr_init(&ss->css_idr);
4567 INIT_LIST_HEAD(&ss->cfts);
4569 /* Create the root cgroup state for this subsystem */
4570 ss->root = &cgrp_dfl_root;
4571 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
4572 /* We don't handle early failures gracefully */
4573 BUG_ON(IS_ERR(css));
4574 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
4576 /* idr_alloc() can't be called safely during early init */
4579 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
4580 BUG_ON(css->id < 0);
4583 /* Update the init_css_set to contain a subsys
4584 * pointer to this state - since the subsystem is
4585 * newly registered, all tasks and hence the
4586 * init_css_set is in the subsystem's root cgroup. */
4587 init_css_set.subsys[ss->id] = css;
4589 need_forkexit_callback |= ss->fork || ss->exit;
4591 /* At system boot, before all subsystems have been
4592 * registered, no tasks have been forked, so we don't
4593 * need to invoke fork callbacks here. */
4594 BUG_ON(!list_empty(&init_task.tasks));
4596 BUG_ON(online_css(css));
4598 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
4600 mutex_unlock(&cgroup_mutex);
4604 * cgroup_init_early - cgroup initialization at system boot
4606 * Initialize cgroups at system boot, and initialize any
4607 * subsystems that request early init.
4609 int __init cgroup_init_early(void)
4611 static struct cgroup_sb_opts __initdata opts =
4612 { .flags = CGRP_ROOT_SANE_BEHAVIOR };
4613 struct cgroup_subsys *ss;
4616 init_cgroup_root(&cgrp_dfl_root, &opts);
4617 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4619 for_each_subsys(ss, i) {
4620 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4621 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4622 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4624 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4625 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4628 ss->name = cgroup_subsys_name[i];
4631 cgroup_init_subsys(ss, true);
4637 * cgroup_init - cgroup initialization
4639 * Register cgroup filesystem and /proc file, and initialize
4640 * any subsystems that didn't request early init.
4642 int __init cgroup_init(void)
4644 struct cgroup_subsys *ss;
4648 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4650 mutex_lock(&cgroup_mutex);
4652 /* Add init_css_set to the hash table */
4653 key = css_set_hash(init_css_set.subsys);
4654 hash_add(css_set_table, &init_css_set.hlist, key);
4656 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
4658 mutex_unlock(&cgroup_mutex);
4660 for_each_subsys(ss, ssid) {
4661 if (ss->early_init) {
4662 struct cgroup_subsys_state *css =
4663 init_css_set.subsys[ss->id];
4665 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
4667 BUG_ON(css->id < 0);
4669 cgroup_init_subsys(ss, false);
4672 list_add_tail(&init_css_set.e_cset_node[ssid],
4673 &cgrp_dfl_root.cgrp.e_csets[ssid]);
4676 * cftype registration needs kmalloc and can't be done
4677 * during early_init. Register base cftypes separately.
4679 if (ss->base_cftypes)
4680 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4683 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4687 err = register_filesystem(&cgroup_fs_type);
4689 kobject_put(cgroup_kobj);
4693 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4697 static int __init cgroup_wq_init(void)
4700 * There isn't much point in executing destruction path in
4701 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4702 * Use 1 for @max_active.
4704 * We would prefer to do this in cgroup_init() above, but that
4705 * is called before init_workqueues(): so leave this until after.
4707 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4708 BUG_ON(!cgroup_destroy_wq);
4711 * Used to destroy pidlists and separate to serve as flush domain.
4712 * Cap @max_active to 1 too.
4714 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4716 BUG_ON(!cgroup_pidlist_destroy_wq);
4720 core_initcall(cgroup_wq_init);
4723 * proc_cgroup_show()
4724 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4725 * - Used for /proc/<pid>/cgroup.
4728 /* TODO: Use a proper seq_file iterator */
4729 int proc_cgroup_show(struct seq_file *m, void *v)
4732 struct task_struct *tsk;
4735 struct cgroup_root *root;
4738 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4744 tsk = get_pid_task(pid, PIDTYPE_PID);
4750 mutex_lock(&cgroup_mutex);
4751 down_read(&css_set_rwsem);
4753 for_each_root(root) {
4754 struct cgroup_subsys *ss;
4755 struct cgroup *cgrp;
4756 int ssid, count = 0;
4758 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
4761 seq_printf(m, "%d:", root->hierarchy_id);
4762 for_each_subsys(ss, ssid)
4763 if (root->subsys_mask & (1 << ssid))
4764 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4765 if (strlen(root->name))
4766 seq_printf(m, "%sname=%s", count ? "," : "",
4769 cgrp = task_cgroup_from_root(tsk, root);
4770 path = cgroup_path(cgrp, buf, PATH_MAX);
4772 retval = -ENAMETOOLONG;
4780 up_read(&css_set_rwsem);
4781 mutex_unlock(&cgroup_mutex);
4782 put_task_struct(tsk);
4789 /* Display information about each subsystem and each hierarchy */
4790 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4792 struct cgroup_subsys *ss;
4795 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4797 * ideally we don't want subsystems moving around while we do this.
4798 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4799 * subsys/hierarchy state.
4801 mutex_lock(&cgroup_mutex);
4803 for_each_subsys(ss, i)
4804 seq_printf(m, "%s\t%d\t%d\t%d\n",
4805 ss->name, ss->root->hierarchy_id,
4806 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4808 mutex_unlock(&cgroup_mutex);
4812 static int cgroupstats_open(struct inode *inode, struct file *file)
4814 return single_open(file, proc_cgroupstats_show, NULL);
4817 static const struct file_operations proc_cgroupstats_operations = {
4818 .open = cgroupstats_open,
4820 .llseek = seq_lseek,
4821 .release = single_release,
4825 * cgroup_fork - initialize cgroup related fields during copy_process()
4826 * @child: pointer to task_struct of forking parent process.
4828 * A task is associated with the init_css_set until cgroup_post_fork()
4829 * attaches it to the parent's css_set. Empty cg_list indicates that
4830 * @child isn't holding reference to its css_set.
4832 void cgroup_fork(struct task_struct *child)
4834 RCU_INIT_POINTER(child->cgroups, &init_css_set);
4835 INIT_LIST_HEAD(&child->cg_list);
4839 * cgroup_post_fork - called on a new task after adding it to the task list
4840 * @child: the task in question
4842 * Adds the task to the list running through its css_set if necessary and
4843 * call the subsystem fork() callbacks. Has to be after the task is
4844 * visible on the task list in case we race with the first call to
4845 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4848 void cgroup_post_fork(struct task_struct *child)
4850 struct cgroup_subsys *ss;
4854 * This may race against cgroup_enable_task_cg_links(). As that
4855 * function sets use_task_css_set_links before grabbing
4856 * tasklist_lock and we just went through tasklist_lock to add
4857 * @child, it's guaranteed that either we see the set
4858 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4859 * @child during its iteration.
4861 * If we won the race, @child is associated with %current's
4862 * css_set. Grabbing css_set_rwsem guarantees both that the
4863 * association is stable, and, on completion of the parent's
4864 * migration, @child is visible in the source of migration or
4865 * already in the destination cgroup. This guarantee is necessary
4866 * when implementing operations which need to migrate all tasks of
4867 * a cgroup to another.
4869 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4870 * will remain in init_css_set. This is safe because all tasks are
4871 * in the init_css_set before cg_links is enabled and there's no
4872 * operation which transfers all tasks out of init_css_set.
4874 if (use_task_css_set_links) {
4875 struct css_set *cset;
4877 down_write(&css_set_rwsem);
4878 cset = task_css_set(current);
4879 if (list_empty(&child->cg_list)) {
4880 rcu_assign_pointer(child->cgroups, cset);
4881 list_add(&child->cg_list, &cset->tasks);
4884 up_write(&css_set_rwsem);
4888 * Call ss->fork(). This must happen after @child is linked on
4889 * css_set; otherwise, @child might change state between ->fork()
4890 * and addition to css_set.
4892 if (need_forkexit_callback) {
4893 for_each_subsys(ss, i)
4900 * cgroup_exit - detach cgroup from exiting task
4901 * @tsk: pointer to task_struct of exiting process
4903 * Description: Detach cgroup from @tsk and release it.
4905 * Note that cgroups marked notify_on_release force every task in
4906 * them to take the global cgroup_mutex mutex when exiting.
4907 * This could impact scaling on very large systems. Be reluctant to
4908 * use notify_on_release cgroups where very high task exit scaling
4909 * is required on large systems.
4911 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
4912 * call cgroup_exit() while the task is still competent to handle
4913 * notify_on_release(), then leave the task attached to the root cgroup in
4914 * each hierarchy for the remainder of its exit. No need to bother with
4915 * init_css_set refcnting. init_css_set never goes away and we can't race
4916 * with migration path - PF_EXITING is visible to migration path.
4918 void cgroup_exit(struct task_struct *tsk)
4920 struct cgroup_subsys *ss;
4921 struct css_set *cset;
4922 bool put_cset = false;
4926 * Unlink from @tsk from its css_set. As migration path can't race
4927 * with us, we can check cg_list without grabbing css_set_rwsem.
4929 if (!list_empty(&tsk->cg_list)) {
4930 down_write(&css_set_rwsem);
4931 list_del_init(&tsk->cg_list);
4932 up_write(&css_set_rwsem);
4936 /* Reassign the task to the init_css_set. */
4937 cset = task_css_set(tsk);
4938 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4940 if (need_forkexit_callback) {
4941 /* see cgroup_post_fork() for details */
4942 for_each_subsys(ss, i) {
4944 struct cgroup_subsys_state *old_css = cset->subsys[i];
4945 struct cgroup_subsys_state *css = task_css(tsk, i);
4947 ss->exit(css, old_css, tsk);
4953 put_css_set(cset, true);
4956 static void check_for_release(struct cgroup *cgrp)
4958 if (cgroup_is_releasable(cgrp) &&
4959 list_empty(&cgrp->cset_links) && !cgroup_has_live_children(cgrp)) {
4961 * Control Group is currently removeable. If it's not
4962 * already queued for a userspace notification, queue
4965 int need_schedule_work = 0;
4967 raw_spin_lock(&release_list_lock);
4968 if (!cgroup_is_dead(cgrp) &&
4969 list_empty(&cgrp->release_list)) {
4970 list_add(&cgrp->release_list, &release_list);
4971 need_schedule_work = 1;
4973 raw_spin_unlock(&release_list_lock);
4974 if (need_schedule_work)
4975 schedule_work(&release_agent_work);
4980 * Notify userspace when a cgroup is released, by running the
4981 * configured release agent with the name of the cgroup (path
4982 * relative to the root of cgroup file system) as the argument.
4984 * Most likely, this user command will try to rmdir this cgroup.
4986 * This races with the possibility that some other task will be
4987 * attached to this cgroup before it is removed, or that some other
4988 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4989 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4990 * unused, and this cgroup will be reprieved from its death sentence,
4991 * to continue to serve a useful existence. Next time it's released,
4992 * we will get notified again, if it still has 'notify_on_release' set.
4994 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4995 * means only wait until the task is successfully execve()'d. The
4996 * separate release agent task is forked by call_usermodehelper(),
4997 * then control in this thread returns here, without waiting for the
4998 * release agent task. We don't bother to wait because the caller of
4999 * this routine has no use for the exit status of the release agent
5000 * task, so no sense holding our caller up for that.
5002 static void cgroup_release_agent(struct work_struct *work)
5004 BUG_ON(work != &release_agent_work);
5005 mutex_lock(&cgroup_mutex);
5006 raw_spin_lock(&release_list_lock);
5007 while (!list_empty(&release_list)) {
5008 char *argv[3], *envp[3];
5010 char *pathbuf = NULL, *agentbuf = NULL, *path;
5011 struct cgroup *cgrp = list_entry(release_list.next,
5014 list_del_init(&cgrp->release_list);
5015 raw_spin_unlock(&release_list_lock);
5016 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5019 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5022 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5027 argv[i++] = agentbuf;
5032 /* minimal command environment */
5033 envp[i++] = "HOME=/";
5034 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5037 /* Drop the lock while we invoke the usermode helper,
5038 * since the exec could involve hitting disk and hence
5039 * be a slow process */
5040 mutex_unlock(&cgroup_mutex);
5041 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5042 mutex_lock(&cgroup_mutex);
5046 raw_spin_lock(&release_list_lock);
5048 raw_spin_unlock(&release_list_lock);
5049 mutex_unlock(&cgroup_mutex);
5052 static int __init cgroup_disable(char *str)
5054 struct cgroup_subsys *ss;
5058 while ((token = strsep(&str, ",")) != NULL) {
5062 for_each_subsys(ss, i) {
5063 if (!strcmp(token, ss->name)) {
5065 printk(KERN_INFO "Disabling %s control group"
5066 " subsystem\n", ss->name);
5073 __setup("cgroup_disable=", cgroup_disable);
5076 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5077 * @dentry: directory dentry of interest
5078 * @ss: subsystem of interest
5080 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5081 * to get the corresponding css and return it. If such css doesn't exist
5082 * or can't be pinned, an ERR_PTR value is returned.
5084 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5085 struct cgroup_subsys *ss)
5087 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5088 struct cgroup_subsys_state *css = NULL;
5089 struct cgroup *cgrp;
5091 /* is @dentry a cgroup dir? */
5092 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5093 kernfs_type(kn) != KERNFS_DIR)
5094 return ERR_PTR(-EBADF);
5099 * This path doesn't originate from kernfs and @kn could already
5100 * have been or be removed at any point. @kn->priv is RCU
5101 * protected for this access. See cgroup_rmdir() for details.
5103 cgrp = rcu_dereference(kn->priv);
5105 css = cgroup_css(cgrp, ss);
5107 if (!css || !css_tryget_online(css))
5108 css = ERR_PTR(-ENOENT);
5115 * css_from_id - lookup css by id
5116 * @id: the cgroup id
5117 * @ss: cgroup subsys to be looked into
5119 * Returns the css if there's valid one with @id, otherwise returns NULL.
5120 * Should be called under rcu_read_lock().
5122 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5124 WARN_ON_ONCE(!rcu_read_lock_held());
5125 return idr_find(&ss->css_idr, id);
5128 #ifdef CONFIG_CGROUP_DEBUG
5129 static struct cgroup_subsys_state *
5130 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5132 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5135 return ERR_PTR(-ENOMEM);
5140 static void debug_css_free(struct cgroup_subsys_state *css)
5145 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5148 return cgroup_task_count(css->cgroup);
5151 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5154 return (u64)(unsigned long)current->cgroups;
5157 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5163 count = atomic_read(&task_css_set(current)->refcount);
5168 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5170 struct cgrp_cset_link *link;
5171 struct css_set *cset;
5174 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5178 down_read(&css_set_rwsem);
5180 cset = rcu_dereference(current->cgroups);
5181 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5182 struct cgroup *c = link->cgrp;
5184 cgroup_name(c, name_buf, NAME_MAX + 1);
5185 seq_printf(seq, "Root %d group %s\n",
5186 c->root->hierarchy_id, name_buf);
5189 up_read(&css_set_rwsem);
5194 #define MAX_TASKS_SHOWN_PER_CSS 25
5195 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5197 struct cgroup_subsys_state *css = seq_css(seq);
5198 struct cgrp_cset_link *link;
5200 down_read(&css_set_rwsem);
5201 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5202 struct css_set *cset = link->cset;
5203 struct task_struct *task;
5206 seq_printf(seq, "css_set %p\n", cset);
5208 list_for_each_entry(task, &cset->tasks, cg_list) {
5209 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5211 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5214 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5215 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5217 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5221 seq_puts(seq, " ...\n");
5223 up_read(&css_set_rwsem);
5227 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5229 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5232 static struct cftype debug_files[] = {
5234 .name = "taskcount",
5235 .read_u64 = debug_taskcount_read,
5239 .name = "current_css_set",
5240 .read_u64 = current_css_set_read,
5244 .name = "current_css_set_refcount",
5245 .read_u64 = current_css_set_refcount_read,
5249 .name = "current_css_set_cg_links",
5250 .seq_show = current_css_set_cg_links_read,
5254 .name = "cgroup_css_links",
5255 .seq_show = cgroup_css_links_read,
5259 .name = "releasable",
5260 .read_u64 = releasable_read,
5266 struct cgroup_subsys debug_cgrp_subsys = {
5267 .css_alloc = debug_css_alloc,
5268 .css_free = debug_css_free,
5269 .base_cftypes = debug_files,
5271 #endif /* CONFIG_CGROUP_DEBUG */