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 bool cgroup_has_live_children(struct cgroup *cgrp);
180 static int rebind_subsystems(struct cgroup_root *dst_root,
181 unsigned int ss_mask);
182 static int cgroup_destroy_locked(struct cgroup *cgrp);
183 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss);
184 static void css_release(struct percpu_ref *ref);
185 static void kill_css(struct cgroup_subsys_state *css);
186 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
188 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
190 /* IDR wrappers which synchronize using cgroup_idr_lock */
191 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
196 idr_preload(gfp_mask);
197 spin_lock_bh(&cgroup_idr_lock);
198 ret = idr_alloc(idr, ptr, start, end, gfp_mask);
199 spin_unlock_bh(&cgroup_idr_lock);
204 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
208 spin_lock_bh(&cgroup_idr_lock);
209 ret = idr_replace(idr, ptr, id);
210 spin_unlock_bh(&cgroup_idr_lock);
214 static void cgroup_idr_remove(struct idr *idr, int id)
216 spin_lock_bh(&cgroup_idr_lock);
218 spin_unlock_bh(&cgroup_idr_lock);
222 * cgroup_css - obtain a cgroup's css for the specified subsystem
223 * @cgrp: the cgroup of interest
224 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
226 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
227 * function must be called either under cgroup_mutex or rcu_read_lock() and
228 * the caller is responsible for pinning the returned css if it wants to
229 * keep accessing it outside the said locks. This function may return
230 * %NULL if @cgrp doesn't have @subsys_id enabled.
232 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
233 struct cgroup_subsys *ss)
236 return rcu_dereference_check(cgrp->subsys[ss->id],
237 lockdep_is_held(&cgroup_mutex));
243 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
244 * @cgrp: the cgroup of interest
245 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
247 * Similar to cgroup_css() but returns the effctive css, which is defined
248 * as the matching css of the nearest ancestor including self which has @ss
249 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
250 * function is guaranteed to return non-NULL css.
252 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
253 struct cgroup_subsys *ss)
255 lockdep_assert_held(&cgroup_mutex);
260 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
263 while (cgrp->parent &&
264 !(cgrp->parent->child_subsys_mask & (1 << ss->id)))
267 return cgroup_css(cgrp, ss);
270 /* convenient tests for these bits */
271 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
273 return test_bit(CGRP_DEAD, &cgrp->flags);
276 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
278 struct cgroup *cgrp = of->kn->parent->priv;
279 struct cftype *cft = of_cft(of);
282 * This is open and unprotected implementation of cgroup_css().
283 * seq_css() is only called from a kernfs file operation which has
284 * an active reference on the file. Because all the subsystem
285 * files are drained before a css is disassociated with a cgroup,
286 * the matching css from the cgroup's subsys table is guaranteed to
287 * be and stay valid until the enclosing operation is complete.
290 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
294 EXPORT_SYMBOL_GPL(of_css);
297 * cgroup_is_descendant - test ancestry
298 * @cgrp: the cgroup to be tested
299 * @ancestor: possible ancestor of @cgrp
301 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
302 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
303 * and @ancestor are accessible.
305 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
308 if (cgrp == ancestor)
315 static int cgroup_is_releasable(const struct cgroup *cgrp)
318 (1 << CGRP_RELEASABLE) |
319 (1 << CGRP_NOTIFY_ON_RELEASE);
320 return (cgrp->flags & bits) == bits;
323 static int notify_on_release(const struct cgroup *cgrp)
325 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
329 * for_each_css - iterate all css's of a cgroup
330 * @css: the iteration cursor
331 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
332 * @cgrp: the target cgroup to iterate css's of
334 * Should be called under cgroup_[tree_]mutex.
336 #define for_each_css(css, ssid, cgrp) \
337 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
338 if (!((css) = rcu_dereference_check( \
339 (cgrp)->subsys[(ssid)], \
340 lockdep_is_held(&cgroup_mutex)))) { } \
344 * for_each_e_css - iterate all effective css's of a cgroup
345 * @css: the iteration cursor
346 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
347 * @cgrp: the target cgroup to iterate css's of
349 * Should be called under cgroup_[tree_]mutex.
351 #define for_each_e_css(css, ssid, cgrp) \
352 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
353 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
358 * for_each_subsys - iterate all enabled cgroup subsystems
359 * @ss: the iteration cursor
360 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
362 #define for_each_subsys(ss, ssid) \
363 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
364 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
366 /* iterate across the hierarchies */
367 #define for_each_root(root) \
368 list_for_each_entry((root), &cgroup_roots, root_list)
370 /* iterate over child cgrps, lock should be held throughout iteration */
371 #define cgroup_for_each_live_child(child, cgrp) \
372 list_for_each_entry((child), &(cgrp)->children, sibling) \
373 if (({ lockdep_assert_held(&cgroup_mutex); \
374 cgroup_is_dead(child); })) \
378 /* the list of cgroups eligible for automatic release. Protected by
379 * release_list_lock */
380 static LIST_HEAD(release_list);
381 static DEFINE_RAW_SPINLOCK(release_list_lock);
382 static void cgroup_release_agent(struct work_struct *work);
383 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
384 static void check_for_release(struct cgroup *cgrp);
387 * A cgroup can be associated with multiple css_sets as different tasks may
388 * belong to different cgroups on different hierarchies. In the other
389 * direction, a css_set is naturally associated with multiple cgroups.
390 * This M:N relationship is represented by the following link structure
391 * which exists for each association and allows traversing the associations
394 struct cgrp_cset_link {
395 /* the cgroup and css_set this link associates */
397 struct css_set *cset;
399 /* list of cgrp_cset_links anchored at cgrp->cset_links */
400 struct list_head cset_link;
402 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
403 struct list_head cgrp_link;
407 * The default css_set - used by init and its children prior to any
408 * hierarchies being mounted. It contains a pointer to the root state
409 * for each subsystem. Also used to anchor the list of css_sets. Not
410 * reference-counted, to improve performance when child cgroups
411 * haven't been created.
413 struct css_set init_css_set = {
414 .refcount = ATOMIC_INIT(1),
415 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
416 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
417 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
418 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
419 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
422 static int css_set_count = 1; /* 1 for init_css_set */
425 * cgroup_update_populated - updated populated count of a cgroup
426 * @cgrp: the target cgroup
427 * @populated: inc or dec populated count
429 * @cgrp is either getting the first task (css_set) or losing the last.
430 * Update @cgrp->populated_cnt accordingly. The count is propagated
431 * towards root so that a given cgroup's populated_cnt is zero iff the
432 * cgroup and all its descendants are empty.
434 * @cgrp's interface file "cgroup.populated" is zero if
435 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
436 * changes from or to zero, userland is notified that the content of the
437 * interface file has changed. This can be used to detect when @cgrp and
438 * its descendants become populated or empty.
440 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
442 lockdep_assert_held(&css_set_rwsem);
448 trigger = !cgrp->populated_cnt++;
450 trigger = !--cgrp->populated_cnt;
455 if (cgrp->populated_kn)
456 kernfs_notify(cgrp->populated_kn);
462 * hash table for cgroup groups. This improves the performance to find
463 * an existing css_set. This hash doesn't (currently) take into
464 * account cgroups in empty hierarchies.
466 #define CSS_SET_HASH_BITS 7
467 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
469 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
471 unsigned long key = 0UL;
472 struct cgroup_subsys *ss;
475 for_each_subsys(ss, i)
476 key += (unsigned long)css[i];
477 key = (key >> 16) ^ key;
482 static void put_css_set_locked(struct css_set *cset, bool taskexit)
484 struct cgrp_cset_link *link, *tmp_link;
485 struct cgroup_subsys *ss;
488 lockdep_assert_held(&css_set_rwsem);
490 if (!atomic_dec_and_test(&cset->refcount))
493 /* This css_set is dead. unlink it and release cgroup refcounts */
494 for_each_subsys(ss, ssid)
495 list_del(&cset->e_cset_node[ssid]);
496 hash_del(&cset->hlist);
499 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
500 struct cgroup *cgrp = link->cgrp;
502 list_del(&link->cset_link);
503 list_del(&link->cgrp_link);
505 /* @cgrp can't go away while we're holding css_set_rwsem */
506 if (list_empty(&cgrp->cset_links)) {
507 cgroup_update_populated(cgrp, false);
508 if (notify_on_release(cgrp)) {
510 set_bit(CGRP_RELEASABLE, &cgrp->flags);
511 check_for_release(cgrp);
518 kfree_rcu(cset, rcu_head);
521 static void put_css_set(struct css_set *cset, bool taskexit)
524 * Ensure that the refcount doesn't hit zero while any readers
525 * can see it. Similar to atomic_dec_and_lock(), but for an
528 if (atomic_add_unless(&cset->refcount, -1, 1))
531 down_write(&css_set_rwsem);
532 put_css_set_locked(cset, taskexit);
533 up_write(&css_set_rwsem);
537 * refcounted get/put for css_set objects
539 static inline void get_css_set(struct css_set *cset)
541 atomic_inc(&cset->refcount);
545 * compare_css_sets - helper function for find_existing_css_set().
546 * @cset: candidate css_set being tested
547 * @old_cset: existing css_set for a task
548 * @new_cgrp: cgroup that's being entered by the task
549 * @template: desired set of css pointers in css_set (pre-calculated)
551 * Returns true if "cset" matches "old_cset" except for the hierarchy
552 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
554 static bool compare_css_sets(struct css_set *cset,
555 struct css_set *old_cset,
556 struct cgroup *new_cgrp,
557 struct cgroup_subsys_state *template[])
559 struct list_head *l1, *l2;
562 * On the default hierarchy, there can be csets which are
563 * associated with the same set of cgroups but different csses.
564 * Let's first ensure that csses match.
566 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
570 * Compare cgroup pointers in order to distinguish between
571 * different cgroups in hierarchies. As different cgroups may
572 * share the same effective css, this comparison is always
575 l1 = &cset->cgrp_links;
576 l2 = &old_cset->cgrp_links;
578 struct cgrp_cset_link *link1, *link2;
579 struct cgroup *cgrp1, *cgrp2;
583 /* See if we reached the end - both lists are equal length. */
584 if (l1 == &cset->cgrp_links) {
585 BUG_ON(l2 != &old_cset->cgrp_links);
588 BUG_ON(l2 == &old_cset->cgrp_links);
590 /* Locate the cgroups associated with these links. */
591 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
592 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
595 /* Hierarchies should be linked in the same order. */
596 BUG_ON(cgrp1->root != cgrp2->root);
599 * If this hierarchy is the hierarchy of the cgroup
600 * that's changing, then we need to check that this
601 * css_set points to the new cgroup; if it's any other
602 * hierarchy, then this css_set should point to the
603 * same cgroup as the old css_set.
605 if (cgrp1->root == new_cgrp->root) {
606 if (cgrp1 != new_cgrp)
617 * find_existing_css_set - init css array and find the matching css_set
618 * @old_cset: the css_set that we're using before the cgroup transition
619 * @cgrp: the cgroup that we're moving into
620 * @template: out param for the new set of csses, should be clear on entry
622 static struct css_set *find_existing_css_set(struct css_set *old_cset,
624 struct cgroup_subsys_state *template[])
626 struct cgroup_root *root = cgrp->root;
627 struct cgroup_subsys *ss;
628 struct css_set *cset;
633 * Build the set of subsystem state objects that we want to see in the
634 * new css_set. while subsystems can change globally, the entries here
635 * won't change, so no need for locking.
637 for_each_subsys(ss, i) {
638 if (root->subsys_mask & (1UL << i)) {
640 * @ss is in this hierarchy, so we want the
641 * effective css from @cgrp.
643 template[i] = cgroup_e_css(cgrp, ss);
646 * @ss is not in this hierarchy, so we don't want
649 template[i] = old_cset->subsys[i];
653 key = css_set_hash(template);
654 hash_for_each_possible(css_set_table, cset, hlist, key) {
655 if (!compare_css_sets(cset, old_cset, cgrp, template))
658 /* This css_set matches what we need */
662 /* No existing cgroup group matched */
666 static void free_cgrp_cset_links(struct list_head *links_to_free)
668 struct cgrp_cset_link *link, *tmp_link;
670 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
671 list_del(&link->cset_link);
677 * allocate_cgrp_cset_links - allocate cgrp_cset_links
678 * @count: the number of links to allocate
679 * @tmp_links: list_head the allocated links are put on
681 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
682 * through ->cset_link. Returns 0 on success or -errno.
684 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
686 struct cgrp_cset_link *link;
689 INIT_LIST_HEAD(tmp_links);
691 for (i = 0; i < count; i++) {
692 link = kzalloc(sizeof(*link), GFP_KERNEL);
694 free_cgrp_cset_links(tmp_links);
697 list_add(&link->cset_link, tmp_links);
703 * link_css_set - a helper function to link a css_set to a cgroup
704 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
705 * @cset: the css_set to be linked
706 * @cgrp: the destination cgroup
708 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
711 struct cgrp_cset_link *link;
713 BUG_ON(list_empty(tmp_links));
715 if (cgroup_on_dfl(cgrp))
716 cset->dfl_cgrp = cgrp;
718 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
722 if (list_empty(&cgrp->cset_links))
723 cgroup_update_populated(cgrp, true);
724 list_move(&link->cset_link, &cgrp->cset_links);
727 * Always add links to the tail of the list so that the list
728 * is sorted by order of hierarchy creation
730 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
734 * find_css_set - return a new css_set with one cgroup updated
735 * @old_cset: the baseline css_set
736 * @cgrp: the cgroup to be updated
738 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
739 * substituted into the appropriate hierarchy.
741 static struct css_set *find_css_set(struct css_set *old_cset,
744 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
745 struct css_set *cset;
746 struct list_head tmp_links;
747 struct cgrp_cset_link *link;
748 struct cgroup_subsys *ss;
752 lockdep_assert_held(&cgroup_mutex);
754 /* First see if we already have a cgroup group that matches
756 down_read(&css_set_rwsem);
757 cset = find_existing_css_set(old_cset, cgrp, template);
760 up_read(&css_set_rwsem);
765 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
769 /* Allocate all the cgrp_cset_link objects that we'll need */
770 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
775 atomic_set(&cset->refcount, 1);
776 INIT_LIST_HEAD(&cset->cgrp_links);
777 INIT_LIST_HEAD(&cset->tasks);
778 INIT_LIST_HEAD(&cset->mg_tasks);
779 INIT_LIST_HEAD(&cset->mg_preload_node);
780 INIT_LIST_HEAD(&cset->mg_node);
781 INIT_HLIST_NODE(&cset->hlist);
783 /* Copy the set of subsystem state objects generated in
784 * find_existing_css_set() */
785 memcpy(cset->subsys, template, sizeof(cset->subsys));
787 down_write(&css_set_rwsem);
788 /* Add reference counts and links from the new css_set. */
789 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
790 struct cgroup *c = link->cgrp;
792 if (c->root == cgrp->root)
794 link_css_set(&tmp_links, cset, c);
797 BUG_ON(!list_empty(&tmp_links));
801 /* Add @cset to the hash table */
802 key = css_set_hash(cset->subsys);
803 hash_add(css_set_table, &cset->hlist, key);
805 for_each_subsys(ss, ssid)
806 list_add_tail(&cset->e_cset_node[ssid],
807 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
809 up_write(&css_set_rwsem);
814 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
816 struct cgroup *root_cgrp = kf_root->kn->priv;
818 return root_cgrp->root;
821 static int cgroup_init_root_id(struct cgroup_root *root)
825 lockdep_assert_held(&cgroup_mutex);
827 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
831 root->hierarchy_id = id;
835 static void cgroup_exit_root_id(struct cgroup_root *root)
837 lockdep_assert_held(&cgroup_mutex);
839 if (root->hierarchy_id) {
840 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
841 root->hierarchy_id = 0;
845 static void cgroup_free_root(struct cgroup_root *root)
848 /* hierarhcy ID shoulid already have been released */
849 WARN_ON_ONCE(root->hierarchy_id);
851 idr_destroy(&root->cgroup_idr);
856 static void cgroup_destroy_root(struct cgroup_root *root)
858 struct cgroup *cgrp = &root->cgrp;
859 struct cgrp_cset_link *link, *tmp_link;
861 mutex_lock(&cgroup_mutex);
863 BUG_ON(atomic_read(&root->nr_cgrps));
864 BUG_ON(!list_empty(&cgrp->children));
866 /* Rebind all subsystems back to the default hierarchy */
867 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
870 * Release all the links from cset_links to this hierarchy's
873 down_write(&css_set_rwsem);
875 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
876 list_del(&link->cset_link);
877 list_del(&link->cgrp_link);
880 up_write(&css_set_rwsem);
882 if (!list_empty(&root->root_list)) {
883 list_del(&root->root_list);
887 cgroup_exit_root_id(root);
889 mutex_unlock(&cgroup_mutex);
891 kernfs_destroy_root(root->kf_root);
892 cgroup_free_root(root);
895 /* look up cgroup associated with given css_set on the specified hierarchy */
896 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
897 struct cgroup_root *root)
899 struct cgroup *res = NULL;
901 lockdep_assert_held(&cgroup_mutex);
902 lockdep_assert_held(&css_set_rwsem);
904 if (cset == &init_css_set) {
907 struct cgrp_cset_link *link;
909 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
910 struct cgroup *c = link->cgrp;
912 if (c->root == root) {
924 * Return the cgroup for "task" from the given hierarchy. Must be
925 * called with cgroup_mutex and css_set_rwsem held.
927 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
928 struct cgroup_root *root)
931 * No need to lock the task - since we hold cgroup_mutex the
932 * task can't change groups, so the only thing that can happen
933 * is that it exits and its css is set back to init_css_set.
935 return cset_cgroup_from_root(task_css_set(task), root);
939 * A task must hold cgroup_mutex to modify cgroups.
941 * Any task can increment and decrement the count field without lock.
942 * So in general, code holding cgroup_mutex can't rely on the count
943 * field not changing. However, if the count goes to zero, then only
944 * cgroup_attach_task() can increment it again. Because a count of zero
945 * means that no tasks are currently attached, therefore there is no
946 * way a task attached to that cgroup can fork (the other way to
947 * increment the count). So code holding cgroup_mutex can safely
948 * assume that if the count is zero, it will stay zero. Similarly, if
949 * a task holds cgroup_mutex on a cgroup with zero count, it
950 * knows that the cgroup won't be removed, as cgroup_rmdir()
953 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
954 * (usually) take cgroup_mutex. These are the two most performance
955 * critical pieces of code here. The exception occurs on cgroup_exit(),
956 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
957 * is taken, and if the cgroup count is zero, a usermode call made
958 * to the release agent with the name of the cgroup (path relative to
959 * the root of cgroup file system) as the argument.
961 * A cgroup can only be deleted if both its 'count' of using tasks
962 * is zero, and its list of 'children' cgroups is empty. Since all
963 * tasks in the system use _some_ cgroup, and since there is always at
964 * least one task in the system (init, pid == 1), therefore, root cgroup
965 * always has either children cgroups and/or using tasks. So we don't
966 * need a special hack to ensure that root cgroup cannot be deleted.
968 * P.S. One more locking exception. RCU is used to guard the
969 * update of a tasks cgroup pointer by cgroup_attach_task()
972 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask);
973 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
974 static const struct file_operations proc_cgroupstats_operations;
976 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
979 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
980 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
981 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
982 cft->ss->name, cft->name);
984 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
989 * cgroup_file_mode - deduce file mode of a control file
990 * @cft: the control file in question
992 * returns cft->mode if ->mode is not 0
993 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
994 * returns S_IRUGO if it has only a read handler
995 * returns S_IWUSR if it has only a write hander
997 static umode_t cgroup_file_mode(const struct cftype *cft)
1004 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1007 if (cft->write_u64 || cft->write_s64 || cft->write)
1013 static void cgroup_get(struct cgroup *cgrp)
1015 WARN_ON_ONCE(cgroup_is_dead(cgrp));
1016 css_get(&cgrp->self);
1019 static void cgroup_put(struct cgroup *cgrp)
1021 css_put(&cgrp->self);
1025 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1026 * @kn: the kernfs_node being serviced
1028 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1029 * the method finishes if locking succeeded. Note that once this function
1030 * returns the cgroup returned by cgroup_kn_lock_live() may become
1031 * inaccessible any time. If the caller intends to continue to access the
1032 * cgroup, it should pin it before invoking this function.
1034 static void cgroup_kn_unlock(struct kernfs_node *kn)
1036 struct cgroup *cgrp;
1038 if (kernfs_type(kn) == KERNFS_DIR)
1041 cgrp = kn->parent->priv;
1043 mutex_unlock(&cgroup_mutex);
1045 kernfs_unbreak_active_protection(kn);
1050 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1051 * @kn: the kernfs_node being serviced
1053 * This helper is to be used by a cgroup kernfs method currently servicing
1054 * @kn. It breaks the active protection, performs cgroup locking and
1055 * verifies that the associated cgroup is alive. Returns the cgroup if
1056 * alive; otherwise, %NULL. A successful return should be undone by a
1057 * matching cgroup_kn_unlock() invocation.
1059 * Any cgroup kernfs method implementation which requires locking the
1060 * associated cgroup should use this helper. It avoids nesting cgroup
1061 * locking under kernfs active protection and allows all kernfs operations
1062 * including self-removal.
1064 static struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn)
1066 struct cgroup *cgrp;
1068 if (kernfs_type(kn) == KERNFS_DIR)
1071 cgrp = kn->parent->priv;
1074 * We're gonna grab cgroup_mutex which nests outside kernfs
1075 * active_ref. cgroup liveliness check alone provides enough
1076 * protection against removal. Ensure @cgrp stays accessible and
1077 * break the active_ref protection.
1080 kernfs_break_active_protection(kn);
1082 mutex_lock(&cgroup_mutex);
1084 if (!cgroup_is_dead(cgrp))
1087 cgroup_kn_unlock(kn);
1091 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1093 char name[CGROUP_FILE_NAME_MAX];
1095 lockdep_assert_held(&cgroup_mutex);
1096 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1100 * cgroup_clear_dir - remove subsys files in a cgroup directory
1101 * @cgrp: target cgroup
1102 * @subsys_mask: mask of the subsystem ids whose files should be removed
1104 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned int subsys_mask)
1106 struct cgroup_subsys *ss;
1109 for_each_subsys(ss, i) {
1110 struct cftype *cfts;
1112 if (!(subsys_mask & (1 << i)))
1114 list_for_each_entry(cfts, &ss->cfts, node)
1115 cgroup_addrm_files(cgrp, cfts, false);
1119 static int rebind_subsystems(struct cgroup_root *dst_root, unsigned int ss_mask)
1121 struct cgroup_subsys *ss;
1124 lockdep_assert_held(&cgroup_mutex);
1126 for_each_subsys(ss, ssid) {
1127 if (!(ss_mask & (1 << ssid)))
1130 /* if @ss has non-root csses attached to it, can't move */
1131 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1134 /* can't move between two non-dummy roots either */
1135 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1139 ret = cgroup_populate_dir(&dst_root->cgrp, ss_mask);
1141 if (dst_root != &cgrp_dfl_root)
1145 * Rebinding back to the default root is not allowed to
1146 * fail. Using both default and non-default roots should
1147 * be rare. Moving subsystems back and forth even more so.
1148 * Just warn about it and continue.
1150 if (cgrp_dfl_root_visible) {
1151 pr_warn("failed to create files (%d) while rebinding 0x%x to default root\n",
1153 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1158 * Nothing can fail from this point on. Remove files for the
1159 * removed subsystems and rebind each subsystem.
1161 for_each_subsys(ss, ssid)
1162 if (ss_mask & (1 << ssid))
1163 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1165 for_each_subsys(ss, ssid) {
1166 struct cgroup_root *src_root;
1167 struct cgroup_subsys_state *css;
1168 struct css_set *cset;
1170 if (!(ss_mask & (1 << ssid)))
1173 src_root = ss->root;
1174 css = cgroup_css(&src_root->cgrp, ss);
1176 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1178 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1179 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1180 ss->root = dst_root;
1181 css->cgroup = &dst_root->cgrp;
1183 down_write(&css_set_rwsem);
1184 hash_for_each(css_set_table, i, cset, hlist)
1185 list_move_tail(&cset->e_cset_node[ss->id],
1186 &dst_root->cgrp.e_csets[ss->id]);
1187 up_write(&css_set_rwsem);
1189 src_root->subsys_mask &= ~(1 << ssid);
1190 src_root->cgrp.child_subsys_mask &= ~(1 << ssid);
1192 /* default hierarchy doesn't enable controllers by default */
1193 dst_root->subsys_mask |= 1 << ssid;
1194 if (dst_root != &cgrp_dfl_root)
1195 dst_root->cgrp.child_subsys_mask |= 1 << ssid;
1201 kernfs_activate(dst_root->cgrp.kn);
1205 static int cgroup_show_options(struct seq_file *seq,
1206 struct kernfs_root *kf_root)
1208 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1209 struct cgroup_subsys *ss;
1212 for_each_subsys(ss, ssid)
1213 if (root->subsys_mask & (1 << ssid))
1214 seq_printf(seq, ",%s", ss->name);
1215 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1216 seq_puts(seq, ",sane_behavior");
1217 if (root->flags & CGRP_ROOT_NOPREFIX)
1218 seq_puts(seq, ",noprefix");
1219 if (root->flags & CGRP_ROOT_XATTR)
1220 seq_puts(seq, ",xattr");
1222 spin_lock(&release_agent_path_lock);
1223 if (strlen(root->release_agent_path))
1224 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1225 spin_unlock(&release_agent_path_lock);
1227 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1228 seq_puts(seq, ",clone_children");
1229 if (strlen(root->name))
1230 seq_printf(seq, ",name=%s", root->name);
1234 struct cgroup_sb_opts {
1235 unsigned int subsys_mask;
1237 char *release_agent;
1238 bool cpuset_clone_children;
1240 /* User explicitly requested empty subsystem */
1244 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1246 char *token, *o = data;
1247 bool all_ss = false, one_ss = false;
1248 unsigned int mask = -1U;
1249 struct cgroup_subsys *ss;
1252 #ifdef CONFIG_CPUSETS
1253 mask = ~(1U << cpuset_cgrp_id);
1256 memset(opts, 0, sizeof(*opts));
1258 while ((token = strsep(&o, ",")) != NULL) {
1261 if (!strcmp(token, "none")) {
1262 /* Explicitly have no subsystems */
1266 if (!strcmp(token, "all")) {
1267 /* Mutually exclusive option 'all' + subsystem name */
1273 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1274 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1277 if (!strcmp(token, "noprefix")) {
1278 opts->flags |= CGRP_ROOT_NOPREFIX;
1281 if (!strcmp(token, "clone_children")) {
1282 opts->cpuset_clone_children = true;
1285 if (!strcmp(token, "xattr")) {
1286 opts->flags |= CGRP_ROOT_XATTR;
1289 if (!strncmp(token, "release_agent=", 14)) {
1290 /* Specifying two release agents is forbidden */
1291 if (opts->release_agent)
1293 opts->release_agent =
1294 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1295 if (!opts->release_agent)
1299 if (!strncmp(token, "name=", 5)) {
1300 const char *name = token + 5;
1301 /* Can't specify an empty name */
1304 /* Must match [\w.-]+ */
1305 for (i = 0; i < strlen(name); i++) {
1309 if ((c == '.') || (c == '-') || (c == '_'))
1313 /* Specifying two names is forbidden */
1316 opts->name = kstrndup(name,
1317 MAX_CGROUP_ROOT_NAMELEN - 1,
1325 for_each_subsys(ss, i) {
1326 if (strcmp(token, ss->name))
1331 /* Mutually exclusive option 'all' + subsystem name */
1334 opts->subsys_mask |= (1 << i);
1339 if (i == CGROUP_SUBSYS_COUNT)
1343 /* Consistency checks */
1345 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1346 pr_warn("sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1348 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1349 opts->cpuset_clone_children || opts->release_agent ||
1351 pr_err("sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1356 * If the 'all' option was specified select all the
1357 * subsystems, otherwise if 'none', 'name=' and a subsystem
1358 * name options were not specified, let's default to 'all'
1360 if (all_ss || (!one_ss && !opts->none && !opts->name))
1361 for_each_subsys(ss, i)
1363 opts->subsys_mask |= (1 << i);
1366 * We either have to specify by name or by subsystems. (So
1367 * all empty hierarchies must have a name).
1369 if (!opts->subsys_mask && !opts->name)
1374 * Option noprefix was introduced just for backward compatibility
1375 * with the old cpuset, so we allow noprefix only if mounting just
1376 * the cpuset subsystem.
1378 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1382 /* Can't specify "none" and some subsystems */
1383 if (opts->subsys_mask && opts->none)
1389 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1392 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1393 struct cgroup_sb_opts opts;
1394 unsigned int added_mask, removed_mask;
1396 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1397 pr_err("sane_behavior: remount is not allowed\n");
1401 mutex_lock(&cgroup_mutex);
1403 /* See what subsystems are wanted */
1404 ret = parse_cgroupfs_options(data, &opts);
1408 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1409 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1410 task_tgid_nr(current), current->comm);
1412 added_mask = opts.subsys_mask & ~root->subsys_mask;
1413 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1415 /* Don't allow flags or name to change at remount */
1416 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1417 (opts.name && strcmp(opts.name, root->name))) {
1418 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1419 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1420 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1425 /* remounting is not allowed for populated hierarchies */
1426 if (!list_empty(&root->cgrp.children)) {
1431 ret = rebind_subsystems(root, added_mask);
1435 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1437 if (opts.release_agent) {
1438 spin_lock(&release_agent_path_lock);
1439 strcpy(root->release_agent_path, opts.release_agent);
1440 spin_unlock(&release_agent_path_lock);
1443 kfree(opts.release_agent);
1445 mutex_unlock(&cgroup_mutex);
1450 * To reduce the fork() overhead for systems that are not actually using
1451 * their cgroups capability, we don't maintain the lists running through
1452 * each css_set to its tasks until we see the list actually used - in other
1453 * words after the first mount.
1455 static bool use_task_css_set_links __read_mostly;
1457 static void cgroup_enable_task_cg_lists(void)
1459 struct task_struct *p, *g;
1461 down_write(&css_set_rwsem);
1463 if (use_task_css_set_links)
1466 use_task_css_set_links = true;
1469 * We need tasklist_lock because RCU is not safe against
1470 * while_each_thread(). Besides, a forking task that has passed
1471 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1472 * is not guaranteed to have its child immediately visible in the
1473 * tasklist if we walk through it with RCU.
1475 read_lock(&tasklist_lock);
1476 do_each_thread(g, p) {
1477 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1478 task_css_set(p) != &init_css_set);
1481 * We should check if the process is exiting, otherwise
1482 * it will race with cgroup_exit() in that the list
1483 * entry won't be deleted though the process has exited.
1484 * Do it while holding siglock so that we don't end up
1485 * racing against cgroup_exit().
1487 spin_lock_irq(&p->sighand->siglock);
1488 if (!(p->flags & PF_EXITING)) {
1489 struct css_set *cset = task_css_set(p);
1491 list_add(&p->cg_list, &cset->tasks);
1494 spin_unlock_irq(&p->sighand->siglock);
1495 } while_each_thread(g, p);
1496 read_unlock(&tasklist_lock);
1498 up_write(&css_set_rwsem);
1501 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1503 struct cgroup_subsys *ss;
1506 INIT_LIST_HEAD(&cgrp->sibling);
1507 INIT_LIST_HEAD(&cgrp->children);
1508 INIT_LIST_HEAD(&cgrp->cset_links);
1509 INIT_LIST_HEAD(&cgrp->release_list);
1510 INIT_LIST_HEAD(&cgrp->pidlists);
1511 mutex_init(&cgrp->pidlist_mutex);
1512 cgrp->self.cgroup = cgrp;
1514 for_each_subsys(ss, ssid)
1515 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1517 init_waitqueue_head(&cgrp->offline_waitq);
1520 static void init_cgroup_root(struct cgroup_root *root,
1521 struct cgroup_sb_opts *opts)
1523 struct cgroup *cgrp = &root->cgrp;
1525 INIT_LIST_HEAD(&root->root_list);
1526 atomic_set(&root->nr_cgrps, 1);
1528 init_cgroup_housekeeping(cgrp);
1529 idr_init(&root->cgroup_idr);
1531 root->flags = opts->flags;
1532 if (opts->release_agent)
1533 strcpy(root->release_agent_path, opts->release_agent);
1535 strcpy(root->name, opts->name);
1536 if (opts->cpuset_clone_children)
1537 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1540 static int cgroup_setup_root(struct cgroup_root *root, unsigned int ss_mask)
1542 LIST_HEAD(tmp_links);
1543 struct cgroup *root_cgrp = &root->cgrp;
1544 struct css_set *cset;
1547 lockdep_assert_held(&cgroup_mutex);
1549 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_NOWAIT);
1552 root_cgrp->id = ret;
1554 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release);
1559 * We're accessing css_set_count without locking css_set_rwsem here,
1560 * but that's OK - it can only be increased by someone holding
1561 * cgroup_lock, and that's us. The worst that can happen is that we
1562 * have some link structures left over
1564 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1568 ret = cgroup_init_root_id(root);
1572 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1573 KERNFS_ROOT_CREATE_DEACTIVATED,
1575 if (IS_ERR(root->kf_root)) {
1576 ret = PTR_ERR(root->kf_root);
1579 root_cgrp->kn = root->kf_root->kn;
1581 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1585 ret = rebind_subsystems(root, ss_mask);
1590 * There must be no failure case after here, since rebinding takes
1591 * care of subsystems' refcounts, which are explicitly dropped in
1592 * the failure exit path.
1594 list_add(&root->root_list, &cgroup_roots);
1595 cgroup_root_count++;
1598 * Link the root cgroup in this hierarchy into all the css_set
1601 down_write(&css_set_rwsem);
1602 hash_for_each(css_set_table, i, cset, hlist)
1603 link_css_set(&tmp_links, cset, root_cgrp);
1604 up_write(&css_set_rwsem);
1606 BUG_ON(!list_empty(&root_cgrp->children));
1607 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1609 kernfs_activate(root_cgrp->kn);
1614 kernfs_destroy_root(root->kf_root);
1615 root->kf_root = NULL;
1617 cgroup_exit_root_id(root);
1619 percpu_ref_cancel_init(&root_cgrp->self.refcnt);
1621 free_cgrp_cset_links(&tmp_links);
1625 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1626 int flags, const char *unused_dev_name,
1629 struct cgroup_root *root;
1630 struct cgroup_sb_opts opts;
1631 struct dentry *dentry;
1636 * The first time anyone tries to mount a cgroup, enable the list
1637 * linking each css_set to its tasks and fix up all existing tasks.
1639 if (!use_task_css_set_links)
1640 cgroup_enable_task_cg_lists();
1642 mutex_lock(&cgroup_mutex);
1644 /* First find the desired set of subsystems */
1645 ret = parse_cgroupfs_options(data, &opts);
1649 /* look for a matching existing root */
1650 if (!opts.subsys_mask && !opts.none && !opts.name) {
1651 cgrp_dfl_root_visible = true;
1652 root = &cgrp_dfl_root;
1653 cgroup_get(&root->cgrp);
1658 for_each_root(root) {
1659 bool name_match = false;
1661 if (root == &cgrp_dfl_root)
1665 * If we asked for a name then it must match. Also, if
1666 * name matches but sybsys_mask doesn't, we should fail.
1667 * Remember whether name matched.
1670 if (strcmp(opts.name, root->name))
1676 * If we asked for subsystems (or explicitly for no
1677 * subsystems) then they must match.
1679 if ((opts.subsys_mask || opts.none) &&
1680 (opts.subsys_mask != root->subsys_mask)) {
1687 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1688 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1689 pr_err("sane_behavior: new mount options should match the existing superblock\n");
1693 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1698 * A root's lifetime is governed by its root cgroup.
1699 * tryget_live failure indicate that the root is being
1700 * destroyed. Wait for destruction to complete so that the
1701 * subsystems are free. We can use wait_queue for the wait
1702 * but this path is super cold. Let's just sleep for a bit
1705 if (!percpu_ref_tryget_live(&root->cgrp.self.refcnt)) {
1706 mutex_unlock(&cgroup_mutex);
1708 ret = restart_syscall();
1717 * No such thing, create a new one. name= matching without subsys
1718 * specification is allowed for already existing hierarchies but we
1719 * can't create new one without subsys specification.
1721 if (!opts.subsys_mask && !opts.none) {
1726 root = kzalloc(sizeof(*root), GFP_KERNEL);
1732 init_cgroup_root(root, &opts);
1734 ret = cgroup_setup_root(root, opts.subsys_mask);
1736 cgroup_free_root(root);
1739 mutex_unlock(&cgroup_mutex);
1741 kfree(opts.release_agent);
1745 return ERR_PTR(ret);
1747 dentry = kernfs_mount(fs_type, flags, root->kf_root, &new_sb);
1748 if (IS_ERR(dentry) || !new_sb)
1749 cgroup_put(&root->cgrp);
1753 static void cgroup_kill_sb(struct super_block *sb)
1755 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1756 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1759 * If @root doesn't have any mounts or children, start killing it.
1760 * This prevents new mounts by disabling percpu_ref_tryget_live().
1761 * cgroup_mount() may wait for @root's release.
1763 if (cgroup_has_live_children(&root->cgrp))
1764 cgroup_put(&root->cgrp);
1766 percpu_ref_kill(&root->cgrp.self.refcnt);
1771 static struct file_system_type cgroup_fs_type = {
1773 .mount = cgroup_mount,
1774 .kill_sb = cgroup_kill_sb,
1777 static struct kobject *cgroup_kobj;
1780 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1781 * @task: target task
1782 * @buf: the buffer to write the path into
1783 * @buflen: the length of the buffer
1785 * Determine @task's cgroup on the first (the one with the lowest non-zero
1786 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1787 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1788 * cgroup controller callbacks.
1790 * Return value is the same as kernfs_path().
1792 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1794 struct cgroup_root *root;
1795 struct cgroup *cgrp;
1796 int hierarchy_id = 1;
1799 mutex_lock(&cgroup_mutex);
1800 down_read(&css_set_rwsem);
1802 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1805 cgrp = task_cgroup_from_root(task, root);
1806 path = cgroup_path(cgrp, buf, buflen);
1808 /* if no hierarchy exists, everyone is in "/" */
1809 if (strlcpy(buf, "/", buflen) < buflen)
1813 up_read(&css_set_rwsem);
1814 mutex_unlock(&cgroup_mutex);
1817 EXPORT_SYMBOL_GPL(task_cgroup_path);
1819 /* used to track tasks and other necessary states during migration */
1820 struct cgroup_taskset {
1821 /* the src and dst cset list running through cset->mg_node */
1822 struct list_head src_csets;
1823 struct list_head dst_csets;
1826 * Fields for cgroup_taskset_*() iteration.
1828 * Before migration is committed, the target migration tasks are on
1829 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1830 * the csets on ->dst_csets. ->csets point to either ->src_csets
1831 * or ->dst_csets depending on whether migration is committed.
1833 * ->cur_csets and ->cur_task point to the current task position
1836 struct list_head *csets;
1837 struct css_set *cur_cset;
1838 struct task_struct *cur_task;
1842 * cgroup_taskset_first - reset taskset and return the first task
1843 * @tset: taskset of interest
1845 * @tset iteration is initialized and the first task is returned.
1847 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1849 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1850 tset->cur_task = NULL;
1852 return cgroup_taskset_next(tset);
1856 * cgroup_taskset_next - iterate to the next task in taskset
1857 * @tset: taskset of interest
1859 * Return the next task in @tset. Iteration must have been initialized
1860 * with cgroup_taskset_first().
1862 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1864 struct css_set *cset = tset->cur_cset;
1865 struct task_struct *task = tset->cur_task;
1867 while (&cset->mg_node != tset->csets) {
1869 task = list_first_entry(&cset->mg_tasks,
1870 struct task_struct, cg_list);
1872 task = list_next_entry(task, cg_list);
1874 if (&task->cg_list != &cset->mg_tasks) {
1875 tset->cur_cset = cset;
1876 tset->cur_task = task;
1880 cset = list_next_entry(cset, mg_node);
1888 * cgroup_task_migrate - move a task from one cgroup to another.
1889 * @old_cgrp: the cgroup @tsk is being migrated from
1890 * @tsk: the task being migrated
1891 * @new_cset: the new css_set @tsk is being attached to
1893 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1895 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1896 struct task_struct *tsk,
1897 struct css_set *new_cset)
1899 struct css_set *old_cset;
1901 lockdep_assert_held(&cgroup_mutex);
1902 lockdep_assert_held(&css_set_rwsem);
1905 * We are synchronized through threadgroup_lock() against PF_EXITING
1906 * setting such that we can't race against cgroup_exit() changing the
1907 * css_set to init_css_set and dropping the old one.
1909 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1910 old_cset = task_css_set(tsk);
1912 get_css_set(new_cset);
1913 rcu_assign_pointer(tsk->cgroups, new_cset);
1916 * Use move_tail so that cgroup_taskset_first() still returns the
1917 * leader after migration. This works because cgroup_migrate()
1918 * ensures that the dst_cset of the leader is the first on the
1919 * tset's dst_csets list.
1921 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
1924 * We just gained a reference on old_cset by taking it from the
1925 * task. As trading it for new_cset is protected by cgroup_mutex,
1926 * we're safe to drop it here; it will be freed under RCU.
1928 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1929 put_css_set_locked(old_cset, false);
1933 * cgroup_migrate_finish - cleanup after attach
1934 * @preloaded_csets: list of preloaded css_sets
1936 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1937 * those functions for details.
1939 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1941 struct css_set *cset, *tmp_cset;
1943 lockdep_assert_held(&cgroup_mutex);
1945 down_write(&css_set_rwsem);
1946 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1947 cset->mg_src_cgrp = NULL;
1948 cset->mg_dst_cset = NULL;
1949 list_del_init(&cset->mg_preload_node);
1950 put_css_set_locked(cset, false);
1952 up_write(&css_set_rwsem);
1956 * cgroup_migrate_add_src - add a migration source css_set
1957 * @src_cset: the source css_set to add
1958 * @dst_cgrp: the destination cgroup
1959 * @preloaded_csets: list of preloaded css_sets
1961 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1962 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1963 * up by cgroup_migrate_finish().
1965 * This function may be called without holding threadgroup_lock even if the
1966 * target is a process. Threads may be created and destroyed but as long
1967 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1968 * the preloaded css_sets are guaranteed to cover all migrations.
1970 static void cgroup_migrate_add_src(struct css_set *src_cset,
1971 struct cgroup *dst_cgrp,
1972 struct list_head *preloaded_csets)
1974 struct cgroup *src_cgrp;
1976 lockdep_assert_held(&cgroup_mutex);
1977 lockdep_assert_held(&css_set_rwsem);
1979 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
1981 if (!list_empty(&src_cset->mg_preload_node))
1984 WARN_ON(src_cset->mg_src_cgrp);
1985 WARN_ON(!list_empty(&src_cset->mg_tasks));
1986 WARN_ON(!list_empty(&src_cset->mg_node));
1988 src_cset->mg_src_cgrp = src_cgrp;
1989 get_css_set(src_cset);
1990 list_add(&src_cset->mg_preload_node, preloaded_csets);
1994 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
1995 * @dst_cgrp: the destination cgroup (may be %NULL)
1996 * @preloaded_csets: list of preloaded source css_sets
1998 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
1999 * have been preloaded to @preloaded_csets. This function looks up and
2000 * pins all destination css_sets, links each to its source, and append them
2001 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
2002 * source css_set is assumed to be its cgroup on the default hierarchy.
2004 * This function must be called after cgroup_migrate_add_src() has been
2005 * called on each migration source css_set. After migration is performed
2006 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2009 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
2010 struct list_head *preloaded_csets)
2013 struct css_set *src_cset, *tmp_cset;
2015 lockdep_assert_held(&cgroup_mutex);
2018 * Except for the root, child_subsys_mask must be zero for a cgroup
2019 * with tasks so that child cgroups don't compete against tasks.
2021 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && dst_cgrp->parent &&
2022 dst_cgrp->child_subsys_mask)
2025 /* look up the dst cset for each src cset and link it to src */
2026 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2027 struct css_set *dst_cset;
2029 dst_cset = find_css_set(src_cset,
2030 dst_cgrp ?: src_cset->dfl_cgrp);
2034 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2037 * If src cset equals dst, it's noop. Drop the src.
2038 * cgroup_migrate() will skip the cset too. Note that we
2039 * can't handle src == dst as some nodes are used by both.
2041 if (src_cset == dst_cset) {
2042 src_cset->mg_src_cgrp = NULL;
2043 list_del_init(&src_cset->mg_preload_node);
2044 put_css_set(src_cset, false);
2045 put_css_set(dst_cset, false);
2049 src_cset->mg_dst_cset = dst_cset;
2051 if (list_empty(&dst_cset->mg_preload_node))
2052 list_add(&dst_cset->mg_preload_node, &csets);
2054 put_css_set(dst_cset, false);
2057 list_splice_tail(&csets, preloaded_csets);
2060 cgroup_migrate_finish(&csets);
2065 * cgroup_migrate - migrate a process or task to a cgroup
2066 * @cgrp: the destination cgroup
2067 * @leader: the leader of the process or the task to migrate
2068 * @threadgroup: whether @leader points to the whole process or a single task
2070 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2071 * process, the caller must be holding threadgroup_lock of @leader. The
2072 * caller is also responsible for invoking cgroup_migrate_add_src() and
2073 * cgroup_migrate_prepare_dst() on the targets before invoking this
2074 * function and following up with cgroup_migrate_finish().
2076 * As long as a controller's ->can_attach() doesn't fail, this function is
2077 * guaranteed to succeed. This means that, excluding ->can_attach()
2078 * failure, when migrating multiple targets, the success or failure can be
2079 * decided for all targets by invoking group_migrate_prepare_dst() before
2080 * actually starting migrating.
2082 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
2085 struct cgroup_taskset tset = {
2086 .src_csets = LIST_HEAD_INIT(tset.src_csets),
2087 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
2088 .csets = &tset.src_csets,
2090 struct cgroup_subsys_state *css, *failed_css = NULL;
2091 struct css_set *cset, *tmp_cset;
2092 struct task_struct *task, *tmp_task;
2096 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2097 * already PF_EXITING could be freed from underneath us unless we
2098 * take an rcu_read_lock.
2100 down_write(&css_set_rwsem);
2104 /* @task either already exited or can't exit until the end */
2105 if (task->flags & PF_EXITING)
2108 /* leave @task alone if post_fork() hasn't linked it yet */
2109 if (list_empty(&task->cg_list))
2112 cset = task_css_set(task);
2113 if (!cset->mg_src_cgrp)
2117 * cgroup_taskset_first() must always return the leader.
2118 * Take care to avoid disturbing the ordering.
2120 list_move_tail(&task->cg_list, &cset->mg_tasks);
2121 if (list_empty(&cset->mg_node))
2122 list_add_tail(&cset->mg_node, &tset.src_csets);
2123 if (list_empty(&cset->mg_dst_cset->mg_node))
2124 list_move_tail(&cset->mg_dst_cset->mg_node,
2129 } while_each_thread(leader, task);
2131 up_write(&css_set_rwsem);
2133 /* methods shouldn't be called if no task is actually migrating */
2134 if (list_empty(&tset.src_csets))
2137 /* check that we can legitimately attach to the cgroup */
2138 for_each_e_css(css, i, cgrp) {
2139 if (css->ss->can_attach) {
2140 ret = css->ss->can_attach(css, &tset);
2143 goto out_cancel_attach;
2149 * Now that we're guaranteed success, proceed to move all tasks to
2150 * the new cgroup. There are no failure cases after here, so this
2151 * is the commit point.
2153 down_write(&css_set_rwsem);
2154 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2155 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2156 cgroup_task_migrate(cset->mg_src_cgrp, task,
2159 up_write(&css_set_rwsem);
2162 * Migration is committed, all target tasks are now on dst_csets.
2163 * Nothing is sensitive to fork() after this point. Notify
2164 * controllers that migration is complete.
2166 tset.csets = &tset.dst_csets;
2168 for_each_e_css(css, i, cgrp)
2169 if (css->ss->attach)
2170 css->ss->attach(css, &tset);
2173 goto out_release_tset;
2176 for_each_e_css(css, i, cgrp) {
2177 if (css == failed_css)
2179 if (css->ss->cancel_attach)
2180 css->ss->cancel_attach(css, &tset);
2183 down_write(&css_set_rwsem);
2184 list_splice_init(&tset.dst_csets, &tset.src_csets);
2185 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2186 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2187 list_del_init(&cset->mg_node);
2189 up_write(&css_set_rwsem);
2194 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2195 * @dst_cgrp: the cgroup to attach to
2196 * @leader: the task or the leader of the threadgroup to be attached
2197 * @threadgroup: attach the whole threadgroup?
2199 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2201 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2202 struct task_struct *leader, bool threadgroup)
2204 LIST_HEAD(preloaded_csets);
2205 struct task_struct *task;
2208 /* look up all src csets */
2209 down_read(&css_set_rwsem);
2213 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2217 } while_each_thread(leader, task);
2219 up_read(&css_set_rwsem);
2221 /* prepare dst csets and commit */
2222 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2224 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2226 cgroup_migrate_finish(&preloaded_csets);
2231 * Find the task_struct of the task to attach by vpid and pass it along to the
2232 * function to attach either it or all tasks in its threadgroup. Will lock
2233 * cgroup_mutex and threadgroup.
2235 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
2236 size_t nbytes, loff_t off, bool threadgroup)
2238 struct task_struct *tsk;
2239 const struct cred *cred = current_cred(), *tcred;
2240 struct cgroup *cgrp;
2244 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2247 cgrp = cgroup_kn_lock_live(of->kn);
2254 tsk = find_task_by_vpid(pid);
2258 goto out_unlock_cgroup;
2261 * even if we're attaching all tasks in the thread group, we
2262 * only need to check permissions on one of them.
2264 tcred = __task_cred(tsk);
2265 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2266 !uid_eq(cred->euid, tcred->uid) &&
2267 !uid_eq(cred->euid, tcred->suid)) {
2270 goto out_unlock_cgroup;
2276 tsk = tsk->group_leader;
2279 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2280 * trapped in a cpuset, or RT worker may be born in a cgroup
2281 * with no rt_runtime allocated. Just say no.
2283 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2286 goto out_unlock_cgroup;
2289 get_task_struct(tsk);
2292 threadgroup_lock(tsk);
2294 if (!thread_group_leader(tsk)) {
2296 * a race with de_thread from another thread's exec()
2297 * may strip us of our leadership, if this happens,
2298 * there is no choice but to throw this task away and
2299 * try again; this is
2300 * "double-double-toil-and-trouble-check locking".
2302 threadgroup_unlock(tsk);
2303 put_task_struct(tsk);
2304 goto retry_find_task;
2308 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2310 threadgroup_unlock(tsk);
2312 put_task_struct(tsk);
2314 cgroup_kn_unlock(of->kn);
2315 return ret ?: nbytes;
2319 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2320 * @from: attach to all cgroups of a given task
2321 * @tsk: the task to be attached
2323 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2325 struct cgroup_root *root;
2328 mutex_lock(&cgroup_mutex);
2329 for_each_root(root) {
2330 struct cgroup *from_cgrp;
2332 if (root == &cgrp_dfl_root)
2335 down_read(&css_set_rwsem);
2336 from_cgrp = task_cgroup_from_root(from, root);
2337 up_read(&css_set_rwsem);
2339 retval = cgroup_attach_task(from_cgrp, tsk, false);
2343 mutex_unlock(&cgroup_mutex);
2347 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2349 static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
2350 char *buf, size_t nbytes, loff_t off)
2352 return __cgroup_procs_write(of, buf, nbytes, off, false);
2355 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
2356 char *buf, size_t nbytes, loff_t off)
2358 return __cgroup_procs_write(of, buf, nbytes, off, true);
2361 static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
2362 char *buf, size_t nbytes, loff_t off)
2364 struct cgroup *cgrp;
2366 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2368 cgrp = cgroup_kn_lock_live(of->kn);
2371 spin_lock(&release_agent_path_lock);
2372 strlcpy(cgrp->root->release_agent_path, strstrip(buf),
2373 sizeof(cgrp->root->release_agent_path));
2374 spin_unlock(&release_agent_path_lock);
2375 cgroup_kn_unlock(of->kn);
2379 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2381 struct cgroup *cgrp = seq_css(seq)->cgroup;
2383 spin_lock(&release_agent_path_lock);
2384 seq_puts(seq, cgrp->root->release_agent_path);
2385 spin_unlock(&release_agent_path_lock);
2386 seq_putc(seq, '\n');
2390 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2392 struct cgroup *cgrp = seq_css(seq)->cgroup;
2394 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2398 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned int ss_mask)
2400 struct cgroup_subsys *ss;
2401 bool printed = false;
2404 for_each_subsys(ss, ssid) {
2405 if (ss_mask & (1 << ssid)) {
2408 seq_printf(seq, "%s", ss->name);
2413 seq_putc(seq, '\n');
2416 /* show controllers which are currently attached to the default hierarchy */
2417 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2419 struct cgroup *cgrp = seq_css(seq)->cgroup;
2421 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask);
2425 /* show controllers which are enabled from the parent */
2426 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2428 struct cgroup *cgrp = seq_css(seq)->cgroup;
2430 cgroup_print_ss_mask(seq, cgrp->parent->child_subsys_mask);
2434 /* show controllers which are enabled for a given cgroup's children */
2435 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2437 struct cgroup *cgrp = seq_css(seq)->cgroup;
2439 cgroup_print_ss_mask(seq, cgrp->child_subsys_mask);
2444 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2445 * @cgrp: root of the subtree to update csses for
2447 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2448 * css associations need to be updated accordingly. This function looks up
2449 * all css_sets which are attached to the subtree, creates the matching
2450 * updated css_sets and migrates the tasks to the new ones.
2452 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2454 LIST_HEAD(preloaded_csets);
2455 struct cgroup_subsys_state *css;
2456 struct css_set *src_cset;
2459 lockdep_assert_held(&cgroup_mutex);
2461 /* look up all csses currently attached to @cgrp's subtree */
2462 down_read(&css_set_rwsem);
2463 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2464 struct cgrp_cset_link *link;
2466 /* self is not affected by child_subsys_mask change */
2467 if (css->cgroup == cgrp)
2470 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2471 cgroup_migrate_add_src(link->cset, cgrp,
2474 up_read(&css_set_rwsem);
2476 /* NULL dst indicates self on default hierarchy */
2477 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2481 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2482 struct task_struct *last_task = NULL, *task;
2484 /* src_csets precede dst_csets, break on the first dst_cset */
2485 if (!src_cset->mg_src_cgrp)
2489 * All tasks in src_cset need to be migrated to the
2490 * matching dst_cset. Empty it process by process. We
2491 * walk tasks but migrate processes. The leader might even
2492 * belong to a different cset but such src_cset would also
2493 * be among the target src_csets because the default
2494 * hierarchy enforces per-process membership.
2497 down_read(&css_set_rwsem);
2498 task = list_first_entry_or_null(&src_cset->tasks,
2499 struct task_struct, cg_list);
2501 task = task->group_leader;
2502 WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
2503 get_task_struct(task);
2505 up_read(&css_set_rwsem);
2510 /* guard against possible infinite loop */
2511 if (WARN(last_task == task,
2512 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2516 threadgroup_lock(task);
2517 /* raced against de_thread() from another thread? */
2518 if (!thread_group_leader(task)) {
2519 threadgroup_unlock(task);
2520 put_task_struct(task);
2524 ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
2526 threadgroup_unlock(task);
2527 put_task_struct(task);
2529 if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
2535 cgroup_migrate_finish(&preloaded_csets);
2539 /* change the enabled child controllers for a cgroup in the default hierarchy */
2540 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
2541 char *buf, size_t nbytes,
2544 unsigned int enable = 0, disable = 0;
2545 struct cgroup *cgrp, *child;
2546 struct cgroup_subsys *ss;
2551 * Parse input - space separated list of subsystem names prefixed
2552 * with either + or -.
2554 buf = strstrip(buf);
2555 while ((tok = strsep(&buf, " "))) {
2558 for_each_subsys(ss, ssid) {
2559 if (ss->disabled || strcmp(tok + 1, ss->name))
2563 enable |= 1 << ssid;
2564 disable &= ~(1 << ssid);
2565 } else if (*tok == '-') {
2566 disable |= 1 << ssid;
2567 enable &= ~(1 << ssid);
2573 if (ssid == CGROUP_SUBSYS_COUNT)
2577 cgrp = cgroup_kn_lock_live(of->kn);
2581 for_each_subsys(ss, ssid) {
2582 if (enable & (1 << ssid)) {
2583 if (cgrp->child_subsys_mask & (1 << ssid)) {
2584 enable &= ~(1 << ssid);
2589 * Because css offlining is asynchronous, userland
2590 * might try to re-enable the same controller while
2591 * the previous instance is still around. In such
2592 * cases, wait till it's gone using offline_waitq.
2594 cgroup_for_each_live_child(child, cgrp) {
2597 if (!cgroup_css(child, ss))
2601 prepare_to_wait(&child->offline_waitq, &wait,
2602 TASK_UNINTERRUPTIBLE);
2603 cgroup_kn_unlock(of->kn);
2605 finish_wait(&child->offline_waitq, &wait);
2608 return restart_syscall();
2611 /* unavailable or not enabled on the parent? */
2612 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2614 !(cgrp->parent->child_subsys_mask & (1 << ssid)))) {
2618 } else if (disable & (1 << ssid)) {
2619 if (!(cgrp->child_subsys_mask & (1 << ssid))) {
2620 disable &= ~(1 << ssid);
2624 /* a child has it enabled? */
2625 cgroup_for_each_live_child(child, cgrp) {
2626 if (child->child_subsys_mask & (1 << ssid)) {
2634 if (!enable && !disable) {
2640 * Except for the root, child_subsys_mask must be zero for a cgroup
2641 * with tasks so that child cgroups don't compete against tasks.
2643 if (enable && cgrp->parent && !list_empty(&cgrp->cset_links)) {
2649 * Create csses for enables and update child_subsys_mask. This
2650 * changes cgroup_e_css() results which in turn makes the
2651 * subsequent cgroup_update_dfl_csses() associate all tasks in the
2652 * subtree to the updated csses.
2654 for_each_subsys(ss, ssid) {
2655 if (!(enable & (1 << ssid)))
2658 cgroup_for_each_live_child(child, cgrp) {
2659 ret = create_css(child, ss);
2665 cgrp->child_subsys_mask |= enable;
2666 cgrp->child_subsys_mask &= ~disable;
2668 ret = cgroup_update_dfl_csses(cgrp);
2672 /* all tasks are now migrated away from the old csses, kill them */
2673 for_each_subsys(ss, ssid) {
2674 if (!(disable & (1 << ssid)))
2677 cgroup_for_each_live_child(child, cgrp)
2678 kill_css(cgroup_css(child, ss));
2681 kernfs_activate(cgrp->kn);
2684 cgroup_kn_unlock(of->kn);
2685 return ret ?: nbytes;
2688 cgrp->child_subsys_mask &= ~enable;
2689 cgrp->child_subsys_mask |= disable;
2691 for_each_subsys(ss, ssid) {
2692 if (!(enable & (1 << ssid)))
2695 cgroup_for_each_live_child(child, cgrp) {
2696 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2704 static int cgroup_populated_show(struct seq_file *seq, void *v)
2706 seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
2710 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2711 size_t nbytes, loff_t off)
2713 struct cgroup *cgrp = of->kn->parent->priv;
2714 struct cftype *cft = of->kn->priv;
2715 struct cgroup_subsys_state *css;
2719 return cft->write(of, buf, nbytes, off);
2722 * kernfs guarantees that a file isn't deleted with operations in
2723 * flight, which means that the matching css is and stays alive and
2724 * doesn't need to be pinned. The RCU locking is not necessary
2725 * either. It's just for the convenience of using cgroup_css().
2728 css = cgroup_css(cgrp, cft->ss);
2731 if (cft->write_u64) {
2732 unsigned long long v;
2733 ret = kstrtoull(buf, 0, &v);
2735 ret = cft->write_u64(css, cft, v);
2736 } else if (cft->write_s64) {
2738 ret = kstrtoll(buf, 0, &v);
2740 ret = cft->write_s64(css, cft, v);
2745 return ret ?: nbytes;
2748 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2750 return seq_cft(seq)->seq_start(seq, ppos);
2753 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2755 return seq_cft(seq)->seq_next(seq, v, ppos);
2758 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2760 seq_cft(seq)->seq_stop(seq, v);
2763 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2765 struct cftype *cft = seq_cft(m);
2766 struct cgroup_subsys_state *css = seq_css(m);
2769 return cft->seq_show(m, arg);
2772 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2773 else if (cft->read_s64)
2774 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2780 static struct kernfs_ops cgroup_kf_single_ops = {
2781 .atomic_write_len = PAGE_SIZE,
2782 .write = cgroup_file_write,
2783 .seq_show = cgroup_seqfile_show,
2786 static struct kernfs_ops cgroup_kf_ops = {
2787 .atomic_write_len = PAGE_SIZE,
2788 .write = cgroup_file_write,
2789 .seq_start = cgroup_seqfile_start,
2790 .seq_next = cgroup_seqfile_next,
2791 .seq_stop = cgroup_seqfile_stop,
2792 .seq_show = cgroup_seqfile_show,
2796 * cgroup_rename - Only allow simple rename of directories in place.
2798 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2799 const char *new_name_str)
2801 struct cgroup *cgrp = kn->priv;
2804 if (kernfs_type(kn) != KERNFS_DIR)
2806 if (kn->parent != new_parent)
2810 * This isn't a proper migration and its usefulness is very
2811 * limited. Disallow if sane_behavior.
2813 if (cgroup_sane_behavior(cgrp))
2817 * We're gonna grab cgroup_mutex which nests outside kernfs
2818 * active_ref. kernfs_rename() doesn't require active_ref
2819 * protection. Break them before grabbing cgroup_mutex.
2821 kernfs_break_active_protection(new_parent);
2822 kernfs_break_active_protection(kn);
2824 mutex_lock(&cgroup_mutex);
2826 ret = kernfs_rename(kn, new_parent, new_name_str);
2828 mutex_unlock(&cgroup_mutex);
2830 kernfs_unbreak_active_protection(kn);
2831 kernfs_unbreak_active_protection(new_parent);
2835 /* set uid and gid of cgroup dirs and files to that of the creator */
2836 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
2838 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
2839 .ia_uid = current_fsuid(),
2840 .ia_gid = current_fsgid(), };
2842 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
2843 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
2846 return kernfs_setattr(kn, &iattr);
2849 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2851 char name[CGROUP_FILE_NAME_MAX];
2852 struct kernfs_node *kn;
2853 struct lock_class_key *key = NULL;
2856 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2857 key = &cft->lockdep_key;
2859 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2860 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2865 ret = cgroup_kn_set_ugid(kn);
2871 if (cft->seq_show == cgroup_populated_show)
2872 cgrp->populated_kn = kn;
2877 * cgroup_addrm_files - add or remove files to a cgroup directory
2878 * @cgrp: the target cgroup
2879 * @cfts: array of cftypes to be added
2880 * @is_add: whether to add or remove
2882 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2883 * For removals, this function never fails. If addition fails, this
2884 * function doesn't remove files already added. The caller is responsible
2887 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2893 lockdep_assert_held(&cgroup_mutex);
2895 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2896 /* does cft->flags tell us to skip this file on @cgrp? */
2897 if ((cft->flags & CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
2899 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2901 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2903 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2907 ret = cgroup_add_file(cgrp, cft);
2909 pr_warn("%s: failed to add %s, err=%d\n",
2910 __func__, cft->name, ret);
2914 cgroup_rm_file(cgrp, cft);
2920 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2923 struct cgroup_subsys *ss = cfts[0].ss;
2924 struct cgroup *root = &ss->root->cgrp;
2925 struct cgroup_subsys_state *css;
2928 lockdep_assert_held(&cgroup_mutex);
2930 /* add/rm files for all cgroups created before */
2931 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2932 struct cgroup *cgrp = css->cgroup;
2934 if (cgroup_is_dead(cgrp))
2937 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2943 kernfs_activate(root->kn);
2947 static void cgroup_exit_cftypes(struct cftype *cfts)
2951 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2952 /* free copy for custom atomic_write_len, see init_cftypes() */
2953 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2960 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2964 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2965 struct kernfs_ops *kf_ops;
2967 WARN_ON(cft->ss || cft->kf_ops);
2970 kf_ops = &cgroup_kf_ops;
2972 kf_ops = &cgroup_kf_single_ops;
2975 * Ugh... if @cft wants a custom max_write_len, we need to
2976 * make a copy of kf_ops to set its atomic_write_len.
2978 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2979 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
2981 cgroup_exit_cftypes(cfts);
2984 kf_ops->atomic_write_len = cft->max_write_len;
2987 cft->kf_ops = kf_ops;
2994 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
2996 lockdep_assert_held(&cgroup_mutex);
2998 if (!cfts || !cfts[0].ss)
3001 list_del(&cfts->node);
3002 cgroup_apply_cftypes(cfts, false);
3003 cgroup_exit_cftypes(cfts);
3008 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3009 * @cfts: zero-length name terminated array of cftypes
3011 * Unregister @cfts. Files described by @cfts are removed from all
3012 * existing cgroups and all future cgroups won't have them either. This
3013 * function can be called anytime whether @cfts' subsys is attached or not.
3015 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3018 int cgroup_rm_cftypes(struct cftype *cfts)
3022 mutex_lock(&cgroup_mutex);
3023 ret = cgroup_rm_cftypes_locked(cfts);
3024 mutex_unlock(&cgroup_mutex);
3029 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3030 * @ss: target cgroup subsystem
3031 * @cfts: zero-length name terminated array of cftypes
3033 * Register @cfts to @ss. Files described by @cfts are created for all
3034 * existing cgroups to which @ss is attached and all future cgroups will
3035 * have them too. This function can be called anytime whether @ss is
3038 * Returns 0 on successful registration, -errno on failure. Note that this
3039 * function currently returns 0 as long as @cfts registration is successful
3040 * even if some file creation attempts on existing cgroups fail.
3042 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3046 if (!cfts || cfts[0].name[0] == '\0')
3049 ret = cgroup_init_cftypes(ss, cfts);
3053 mutex_lock(&cgroup_mutex);
3055 list_add_tail(&cfts->node, &ss->cfts);
3056 ret = cgroup_apply_cftypes(cfts, true);
3058 cgroup_rm_cftypes_locked(cfts);
3060 mutex_unlock(&cgroup_mutex);
3065 * cgroup_task_count - count the number of tasks in a cgroup.
3066 * @cgrp: the cgroup in question
3068 * Return the number of tasks in the cgroup.
3070 static int cgroup_task_count(const struct cgroup *cgrp)
3073 struct cgrp_cset_link *link;
3075 down_read(&css_set_rwsem);
3076 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3077 count += atomic_read(&link->cset->refcount);
3078 up_read(&css_set_rwsem);
3083 * css_next_child - find the next child of a given css
3084 * @pos_css: the current position (%NULL to initiate traversal)
3085 * @parent_css: css whose children to walk
3087 * This function returns the next child of @parent_css and should be called
3088 * under either cgroup_mutex or RCU read lock. The only requirement is
3089 * that @parent_css and @pos_css are accessible. The next sibling is
3090 * guaranteed to be returned regardless of their states.
3092 struct cgroup_subsys_state *
3093 css_next_child(struct cgroup_subsys_state *pos_css,
3094 struct cgroup_subsys_state *parent_css)
3096 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3097 struct cgroup *cgrp = parent_css->cgroup;
3098 struct cgroup *next;
3100 cgroup_assert_mutex_or_rcu_locked();
3103 * @pos could already have been removed. Once a cgroup is removed,
3104 * its ->sibling.next is no longer updated when its next sibling
3105 * changes. As CGRP_DEAD assertion is serialized and happens
3106 * before the cgroup is taken off the ->sibling list, if we see it
3107 * unasserted, it's guaranteed that the next sibling hasn't
3108 * finished its grace period even if it's already removed, and thus
3109 * safe to dereference from this RCU critical section. If
3110 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3111 * to be visible as %true here.
3113 * If @pos is dead, its next pointer can't be dereferenced;
3114 * however, as each cgroup is given a monotonically increasing
3115 * unique serial number and always appended to the sibling list,
3116 * the next one can be found by walking the parent's children until
3117 * we see a cgroup with higher serial number than @pos's. While
3118 * this path can be slower, it's taken only when either the current
3119 * cgroup is removed or iteration and removal race.
3122 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3123 } else if (likely(!cgroup_is_dead(pos))) {
3124 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3126 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3127 if (next->serial_nr > pos->serial_nr)
3132 * @next, if not pointing to the head, can be dereferenced and is
3133 * the next sibling; however, it might have @ss disabled. If so,
3134 * fast-forward to the next enabled one.
3136 while (&next->sibling != &cgrp->children) {
3137 struct cgroup_subsys_state *next_css = cgroup_css(next, parent_css->ss);
3141 next = list_entry_rcu(next->sibling.next, struct cgroup, sibling);
3147 * css_next_descendant_pre - find the next descendant for pre-order walk
3148 * @pos: the current position (%NULL to initiate traversal)
3149 * @root: css whose descendants to walk
3151 * To be used by css_for_each_descendant_pre(). Find the next descendant
3152 * to visit for pre-order traversal of @root's descendants. @root is
3153 * included in the iteration and the first node to be visited.
3155 * While this function requires cgroup_mutex or RCU read locking, it
3156 * doesn't require the whole traversal to be contained in a single critical
3157 * section. This function will return the correct next descendant as long
3158 * as both @pos and @root are accessible and @pos is a descendant of @root.
3160 struct cgroup_subsys_state *
3161 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3162 struct cgroup_subsys_state *root)
3164 struct cgroup_subsys_state *next;
3166 cgroup_assert_mutex_or_rcu_locked();
3168 /* if first iteration, visit @root */
3172 /* visit the first child if exists */
3173 next = css_next_child(NULL, pos);
3177 /* no child, visit my or the closest ancestor's next sibling */
3178 while (pos != root) {
3179 next = css_next_child(pos, css_parent(pos));
3182 pos = css_parent(pos);
3189 * css_rightmost_descendant - return the rightmost descendant of a css
3190 * @pos: css of interest
3192 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3193 * is returned. This can be used during pre-order traversal to skip
3196 * While this function requires cgroup_mutex or RCU read locking, it
3197 * doesn't require the whole traversal to be contained in a single critical
3198 * section. This function will return the correct rightmost descendant as
3199 * long as @pos is accessible.
3201 struct cgroup_subsys_state *
3202 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3204 struct cgroup_subsys_state *last, *tmp;
3206 cgroup_assert_mutex_or_rcu_locked();
3210 /* ->prev isn't RCU safe, walk ->next till the end */
3212 css_for_each_child(tmp, last)
3219 static struct cgroup_subsys_state *
3220 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3222 struct cgroup_subsys_state *last;
3226 pos = css_next_child(NULL, pos);
3233 * css_next_descendant_post - find the next descendant for post-order walk
3234 * @pos: the current position (%NULL to initiate traversal)
3235 * @root: css whose descendants to walk
3237 * To be used by css_for_each_descendant_post(). Find the next descendant
3238 * to visit for post-order traversal of @root's descendants. @root is
3239 * included in the iteration and the last node to be visited.
3241 * While this function requires cgroup_mutex or RCU read locking, it
3242 * doesn't require the whole traversal to be contained in a single critical
3243 * section. This function will return the correct next descendant as long
3244 * as both @pos and @cgroup are accessible and @pos is a descendant of
3247 struct cgroup_subsys_state *
3248 css_next_descendant_post(struct cgroup_subsys_state *pos,
3249 struct cgroup_subsys_state *root)
3251 struct cgroup_subsys_state *next;
3253 cgroup_assert_mutex_or_rcu_locked();
3255 /* if first iteration, visit leftmost descendant which may be @root */
3257 return css_leftmost_descendant(root);
3259 /* if we visited @root, we're done */
3263 /* if there's an unvisited sibling, visit its leftmost descendant */
3264 next = css_next_child(pos, css_parent(pos));
3266 return css_leftmost_descendant(next);
3268 /* no sibling left, visit parent */
3269 return css_parent(pos);
3272 static bool cgroup_has_live_children(struct cgroup *cgrp)
3274 struct cgroup *child;
3277 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
3278 if (!cgroup_is_dead(child)) {
3288 * css_advance_task_iter - advance a task itererator to the next css_set
3289 * @it: the iterator to advance
3291 * Advance @it to the next css_set to walk.
3293 static void css_advance_task_iter(struct css_task_iter *it)
3295 struct list_head *l = it->cset_pos;
3296 struct cgrp_cset_link *link;
3297 struct css_set *cset;
3299 /* Advance to the next non-empty css_set */
3302 if (l == it->cset_head) {
3303 it->cset_pos = NULL;
3308 cset = container_of(l, struct css_set,
3309 e_cset_node[it->ss->id]);
3311 link = list_entry(l, struct cgrp_cset_link, cset_link);
3314 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
3318 if (!list_empty(&cset->tasks))
3319 it->task_pos = cset->tasks.next;
3321 it->task_pos = cset->mg_tasks.next;
3323 it->tasks_head = &cset->tasks;
3324 it->mg_tasks_head = &cset->mg_tasks;
3328 * css_task_iter_start - initiate task iteration
3329 * @css: the css to walk tasks of
3330 * @it: the task iterator to use
3332 * Initiate iteration through the tasks of @css. The caller can call
3333 * css_task_iter_next() to walk through the tasks until the function
3334 * returns NULL. On completion of iteration, css_task_iter_end() must be
3337 * Note that this function acquires a lock which is released when the
3338 * iteration finishes. The caller can't sleep while iteration is in
3341 void css_task_iter_start(struct cgroup_subsys_state *css,
3342 struct css_task_iter *it)
3343 __acquires(css_set_rwsem)
3345 /* no one should try to iterate before mounting cgroups */
3346 WARN_ON_ONCE(!use_task_css_set_links);
3348 down_read(&css_set_rwsem);
3353 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3355 it->cset_pos = &css->cgroup->cset_links;
3357 it->cset_head = it->cset_pos;
3359 css_advance_task_iter(it);
3363 * css_task_iter_next - return the next task for the iterator
3364 * @it: the task iterator being iterated
3366 * The "next" function for task iteration. @it should have been
3367 * initialized via css_task_iter_start(). Returns NULL when the iteration
3370 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3372 struct task_struct *res;
3373 struct list_head *l = it->task_pos;
3375 /* If the iterator cg is NULL, we have no tasks */
3378 res = list_entry(l, struct task_struct, cg_list);
3381 * Advance iterator to find next entry. cset->tasks is consumed
3382 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3387 if (l == it->tasks_head)
3388 l = it->mg_tasks_head->next;
3390 if (l == it->mg_tasks_head)
3391 css_advance_task_iter(it);
3399 * css_task_iter_end - finish task iteration
3400 * @it: the task iterator to finish
3402 * Finish task iteration started by css_task_iter_start().
3404 void css_task_iter_end(struct css_task_iter *it)
3405 __releases(css_set_rwsem)
3407 up_read(&css_set_rwsem);
3411 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3412 * @to: cgroup to which the tasks will be moved
3413 * @from: cgroup in which the tasks currently reside
3415 * Locking rules between cgroup_post_fork() and the migration path
3416 * guarantee that, if a task is forking while being migrated, the new child
3417 * is guaranteed to be either visible in the source cgroup after the
3418 * parent's migration is complete or put into the target cgroup. No task
3419 * can slip out of migration through forking.
3421 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3423 LIST_HEAD(preloaded_csets);
3424 struct cgrp_cset_link *link;
3425 struct css_task_iter it;
3426 struct task_struct *task;
3429 mutex_lock(&cgroup_mutex);
3431 /* all tasks in @from are being moved, all csets are source */
3432 down_read(&css_set_rwsem);
3433 list_for_each_entry(link, &from->cset_links, cset_link)
3434 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
3435 up_read(&css_set_rwsem);
3437 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
3442 * Migrate tasks one-by-one until @form is empty. This fails iff
3443 * ->can_attach() fails.
3446 css_task_iter_start(&from->self, &it);
3447 task = css_task_iter_next(&it);
3449 get_task_struct(task);
3450 css_task_iter_end(&it);
3453 ret = cgroup_migrate(to, task, false);
3454 put_task_struct(task);
3456 } while (task && !ret);
3458 cgroup_migrate_finish(&preloaded_csets);
3459 mutex_unlock(&cgroup_mutex);
3464 * Stuff for reading the 'tasks'/'procs' files.
3466 * Reading this file can return large amounts of data if a cgroup has
3467 * *lots* of attached tasks. So it may need several calls to read(),
3468 * but we cannot guarantee that the information we produce is correct
3469 * unless we produce it entirely atomically.
3473 /* which pidlist file are we talking about? */
3474 enum cgroup_filetype {
3480 * A pidlist is a list of pids that virtually represents the contents of one
3481 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3482 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3485 struct cgroup_pidlist {
3487 * used to find which pidlist is wanted. doesn't change as long as
3488 * this particular list stays in the list.
3490 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3493 /* how many elements the above list has */
3495 /* each of these stored in a list by its cgroup */
3496 struct list_head links;
3497 /* pointer to the cgroup we belong to, for list removal purposes */
3498 struct cgroup *owner;
3499 /* for delayed destruction */
3500 struct delayed_work destroy_dwork;
3504 * The following two functions "fix" the issue where there are more pids
3505 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3506 * TODO: replace with a kernel-wide solution to this problem
3508 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3509 static void *pidlist_allocate(int count)
3511 if (PIDLIST_TOO_LARGE(count))
3512 return vmalloc(count * sizeof(pid_t));
3514 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3517 static void pidlist_free(void *p)
3519 if (is_vmalloc_addr(p))
3526 * Used to destroy all pidlists lingering waiting for destroy timer. None
3527 * should be left afterwards.
3529 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3531 struct cgroup_pidlist *l, *tmp_l;
3533 mutex_lock(&cgrp->pidlist_mutex);
3534 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3535 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3536 mutex_unlock(&cgrp->pidlist_mutex);
3538 flush_workqueue(cgroup_pidlist_destroy_wq);
3539 BUG_ON(!list_empty(&cgrp->pidlists));
3542 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3544 struct delayed_work *dwork = to_delayed_work(work);
3545 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3547 struct cgroup_pidlist *tofree = NULL;
3549 mutex_lock(&l->owner->pidlist_mutex);
3552 * Destroy iff we didn't get queued again. The state won't change
3553 * as destroy_dwork can only be queued while locked.
3555 if (!delayed_work_pending(dwork)) {
3556 list_del(&l->links);
3557 pidlist_free(l->list);
3558 put_pid_ns(l->key.ns);
3562 mutex_unlock(&l->owner->pidlist_mutex);
3567 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3568 * Returns the number of unique elements.
3570 static int pidlist_uniq(pid_t *list, int length)
3575 * we presume the 0th element is unique, so i starts at 1. trivial
3576 * edge cases first; no work needs to be done for either
3578 if (length == 0 || length == 1)
3580 /* src and dest walk down the list; dest counts unique elements */
3581 for (src = 1; src < length; src++) {
3582 /* find next unique element */
3583 while (list[src] == list[src-1]) {
3588 /* dest always points to where the next unique element goes */
3589 list[dest] = list[src];
3597 * The two pid files - task and cgroup.procs - guaranteed that the result
3598 * is sorted, which forced this whole pidlist fiasco. As pid order is
3599 * different per namespace, each namespace needs differently sorted list,
3600 * making it impossible to use, for example, single rbtree of member tasks
3601 * sorted by task pointer. As pidlists can be fairly large, allocating one
3602 * per open file is dangerous, so cgroup had to implement shared pool of
3603 * pidlists keyed by cgroup and namespace.
3605 * All this extra complexity was caused by the original implementation
3606 * committing to an entirely unnecessary property. In the long term, we
3607 * want to do away with it. Explicitly scramble sort order if
3608 * sane_behavior so that no such expectation exists in the new interface.
3610 * Scrambling is done by swapping every two consecutive bits, which is
3611 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3613 static pid_t pid_fry(pid_t pid)
3615 unsigned a = pid & 0x55555555;
3616 unsigned b = pid & 0xAAAAAAAA;
3618 return (a << 1) | (b >> 1);
3621 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3623 if (cgroup_sane_behavior(cgrp))
3624 return pid_fry(pid);
3629 static int cmppid(const void *a, const void *b)
3631 return *(pid_t *)a - *(pid_t *)b;
3634 static int fried_cmppid(const void *a, const void *b)
3636 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3639 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3640 enum cgroup_filetype type)
3642 struct cgroup_pidlist *l;
3643 /* don't need task_nsproxy() if we're looking at ourself */
3644 struct pid_namespace *ns = task_active_pid_ns(current);
3646 lockdep_assert_held(&cgrp->pidlist_mutex);
3648 list_for_each_entry(l, &cgrp->pidlists, links)
3649 if (l->key.type == type && l->key.ns == ns)
3655 * find the appropriate pidlist for our purpose (given procs vs tasks)
3656 * returns with the lock on that pidlist already held, and takes care
3657 * of the use count, or returns NULL with no locks held if we're out of
3660 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3661 enum cgroup_filetype type)
3663 struct cgroup_pidlist *l;
3665 lockdep_assert_held(&cgrp->pidlist_mutex);
3667 l = cgroup_pidlist_find(cgrp, type);
3671 /* entry not found; create a new one */
3672 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3676 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3678 /* don't need task_nsproxy() if we're looking at ourself */
3679 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3681 list_add(&l->links, &cgrp->pidlists);
3686 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3688 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3689 struct cgroup_pidlist **lp)
3693 int pid, n = 0; /* used for populating the array */
3694 struct css_task_iter it;
3695 struct task_struct *tsk;
3696 struct cgroup_pidlist *l;
3698 lockdep_assert_held(&cgrp->pidlist_mutex);
3701 * If cgroup gets more users after we read count, we won't have
3702 * enough space - tough. This race is indistinguishable to the
3703 * caller from the case that the additional cgroup users didn't
3704 * show up until sometime later on.
3706 length = cgroup_task_count(cgrp);
3707 array = pidlist_allocate(length);
3710 /* now, populate the array */
3711 css_task_iter_start(&cgrp->self, &it);
3712 while ((tsk = css_task_iter_next(&it))) {
3713 if (unlikely(n == length))
3715 /* get tgid or pid for procs or tasks file respectively */
3716 if (type == CGROUP_FILE_PROCS)
3717 pid = task_tgid_vnr(tsk);
3719 pid = task_pid_vnr(tsk);
3720 if (pid > 0) /* make sure to only use valid results */
3723 css_task_iter_end(&it);
3725 /* now sort & (if procs) strip out duplicates */
3726 if (cgroup_sane_behavior(cgrp))
3727 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3729 sort(array, length, sizeof(pid_t), cmppid, NULL);
3730 if (type == CGROUP_FILE_PROCS)
3731 length = pidlist_uniq(array, length);
3733 l = cgroup_pidlist_find_create(cgrp, type);
3735 mutex_unlock(&cgrp->pidlist_mutex);
3736 pidlist_free(array);
3740 /* store array, freeing old if necessary */
3741 pidlist_free(l->list);
3749 * cgroupstats_build - build and fill cgroupstats
3750 * @stats: cgroupstats to fill information into
3751 * @dentry: A dentry entry belonging to the cgroup for which stats have
3754 * Build and fill cgroupstats so that taskstats can export it to user
3757 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3759 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3760 struct cgroup *cgrp;
3761 struct css_task_iter it;
3762 struct task_struct *tsk;
3764 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3765 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3766 kernfs_type(kn) != KERNFS_DIR)
3769 mutex_lock(&cgroup_mutex);
3772 * We aren't being called from kernfs and there's no guarantee on
3773 * @kn->priv's validity. For this and css_tryget_online_from_dir(),
3774 * @kn->priv is RCU safe. Let's do the RCU dancing.
3777 cgrp = rcu_dereference(kn->priv);
3778 if (!cgrp || cgroup_is_dead(cgrp)) {
3780 mutex_unlock(&cgroup_mutex);
3785 css_task_iter_start(&cgrp->self, &it);
3786 while ((tsk = css_task_iter_next(&it))) {
3787 switch (tsk->state) {
3789 stats->nr_running++;
3791 case TASK_INTERRUPTIBLE:
3792 stats->nr_sleeping++;
3794 case TASK_UNINTERRUPTIBLE:
3795 stats->nr_uninterruptible++;
3798 stats->nr_stopped++;
3801 if (delayacct_is_task_waiting_on_io(tsk))
3802 stats->nr_io_wait++;
3806 css_task_iter_end(&it);
3808 mutex_unlock(&cgroup_mutex);
3814 * seq_file methods for the tasks/procs files. The seq_file position is the
3815 * next pid to display; the seq_file iterator is a pointer to the pid
3816 * in the cgroup->l->list array.
3819 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3822 * Initially we receive a position value that corresponds to
3823 * one more than the last pid shown (or 0 on the first call or
3824 * after a seek to the start). Use a binary-search to find the
3825 * next pid to display, if any
3827 struct kernfs_open_file *of = s->private;
3828 struct cgroup *cgrp = seq_css(s)->cgroup;
3829 struct cgroup_pidlist *l;
3830 enum cgroup_filetype type = seq_cft(s)->private;
3831 int index = 0, pid = *pos;
3834 mutex_lock(&cgrp->pidlist_mutex);
3837 * !NULL @of->priv indicates that this isn't the first start()
3838 * after open. If the matching pidlist is around, we can use that.
3839 * Look for it. Note that @of->priv can't be used directly. It
3840 * could already have been destroyed.
3843 of->priv = cgroup_pidlist_find(cgrp, type);
3846 * Either this is the first start() after open or the matching
3847 * pidlist has been destroyed inbetween. Create a new one.
3850 ret = pidlist_array_load(cgrp, type,
3851 (struct cgroup_pidlist **)&of->priv);
3853 return ERR_PTR(ret);
3858 int end = l->length;
3860 while (index < end) {
3861 int mid = (index + end) / 2;
3862 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3865 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3871 /* If we're off the end of the array, we're done */
3872 if (index >= l->length)
3874 /* Update the abstract position to be the actual pid that we found */
3875 iter = l->list + index;
3876 *pos = cgroup_pid_fry(cgrp, *iter);
3880 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3882 struct kernfs_open_file *of = s->private;
3883 struct cgroup_pidlist *l = of->priv;
3886 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3887 CGROUP_PIDLIST_DESTROY_DELAY);
3888 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3891 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3893 struct kernfs_open_file *of = s->private;
3894 struct cgroup_pidlist *l = of->priv;
3896 pid_t *end = l->list + l->length;
3898 * Advance to the next pid in the array. If this goes off the
3905 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3910 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3912 return seq_printf(s, "%d\n", *(int *)v);
3915 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3918 return notify_on_release(css->cgroup);
3921 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3922 struct cftype *cft, u64 val)
3924 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3926 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3928 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3932 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3935 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3938 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3939 struct cftype *cft, u64 val)
3942 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3944 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3948 static struct cftype cgroup_base_files[] = {
3950 .name = "cgroup.procs",
3951 .seq_start = cgroup_pidlist_start,
3952 .seq_next = cgroup_pidlist_next,
3953 .seq_stop = cgroup_pidlist_stop,
3954 .seq_show = cgroup_pidlist_show,
3955 .private = CGROUP_FILE_PROCS,
3956 .write = cgroup_procs_write,
3957 .mode = S_IRUGO | S_IWUSR,
3960 .name = "cgroup.clone_children",
3961 .flags = CFTYPE_INSANE,
3962 .read_u64 = cgroup_clone_children_read,
3963 .write_u64 = cgroup_clone_children_write,
3966 .name = "cgroup.sane_behavior",
3967 .flags = CFTYPE_ONLY_ON_ROOT,
3968 .seq_show = cgroup_sane_behavior_show,
3971 .name = "cgroup.controllers",
3972 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_ONLY_ON_ROOT,
3973 .seq_show = cgroup_root_controllers_show,
3976 .name = "cgroup.controllers",
3977 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
3978 .seq_show = cgroup_controllers_show,
3981 .name = "cgroup.subtree_control",
3982 .flags = CFTYPE_ONLY_ON_DFL,
3983 .seq_show = cgroup_subtree_control_show,
3984 .write = cgroup_subtree_control_write,
3987 .name = "cgroup.populated",
3988 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
3989 .seq_show = cgroup_populated_show,
3993 * Historical crazy stuff. These don't have "cgroup." prefix and
3994 * don't exist if sane_behavior. If you're depending on these, be
3995 * prepared to be burned.
3999 .flags = CFTYPE_INSANE, /* use "procs" instead */
4000 .seq_start = cgroup_pidlist_start,
4001 .seq_next = cgroup_pidlist_next,
4002 .seq_stop = cgroup_pidlist_stop,
4003 .seq_show = cgroup_pidlist_show,
4004 .private = CGROUP_FILE_TASKS,
4005 .write = cgroup_tasks_write,
4006 .mode = S_IRUGO | S_IWUSR,
4009 .name = "notify_on_release",
4010 .flags = CFTYPE_INSANE,
4011 .read_u64 = cgroup_read_notify_on_release,
4012 .write_u64 = cgroup_write_notify_on_release,
4015 .name = "release_agent",
4016 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4017 .seq_show = cgroup_release_agent_show,
4018 .write = cgroup_release_agent_write,
4019 .max_write_len = PATH_MAX - 1,
4025 * cgroup_populate_dir - create subsys files in a cgroup directory
4026 * @cgrp: target cgroup
4027 * @subsys_mask: mask of the subsystem ids whose files should be added
4029 * On failure, no file is added.
4031 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask)
4033 struct cgroup_subsys *ss;
4036 /* process cftsets of each subsystem */
4037 for_each_subsys(ss, i) {
4038 struct cftype *cfts;
4040 if (!(subsys_mask & (1 << i)))
4043 list_for_each_entry(cfts, &ss->cfts, node) {
4044 ret = cgroup_addrm_files(cgrp, cfts, true);
4051 cgroup_clear_dir(cgrp, subsys_mask);
4056 * css destruction is four-stage process.
4058 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4059 * Implemented in kill_css().
4061 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4062 * and thus css_tryget_online() is guaranteed to fail, the css can be
4063 * offlined by invoking offline_css(). After offlining, the base ref is
4064 * put. Implemented in css_killed_work_fn().
4066 * 3. When the percpu_ref reaches zero, the only possible remaining
4067 * accessors are inside RCU read sections. css_release() schedules the
4070 * 4. After the grace period, the css can be freed. Implemented in
4071 * css_free_work_fn().
4073 * It is actually hairier because both step 2 and 4 require process context
4074 * and thus involve punting to css->destroy_work adding two additional
4075 * steps to the already complex sequence.
4077 static void css_free_work_fn(struct work_struct *work)
4079 struct cgroup_subsys_state *css =
4080 container_of(work, struct cgroup_subsys_state, destroy_work);
4081 struct cgroup *cgrp = css->cgroup;
4086 css_put(css->parent);
4088 css->ss->css_free(css);
4091 /* cgroup free path */
4092 atomic_dec(&cgrp->root->nr_cgrps);
4093 cgroup_pidlist_destroy_all(cgrp);
4097 * We get a ref to the parent, and put the ref when
4098 * this cgroup is being freed, so it's guaranteed
4099 * that the parent won't be destroyed before its
4102 cgroup_put(cgrp->parent);
4103 kernfs_put(cgrp->kn);
4107 * This is root cgroup's refcnt reaching zero,
4108 * which indicates that the root should be
4111 cgroup_destroy_root(cgrp->root);
4116 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4118 struct cgroup_subsys_state *css =
4119 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4121 INIT_WORK(&css->destroy_work, css_free_work_fn);
4122 queue_work(cgroup_destroy_wq, &css->destroy_work);
4125 static void css_release_work_fn(struct work_struct *work)
4127 struct cgroup_subsys_state *css =
4128 container_of(work, struct cgroup_subsys_state, destroy_work);
4129 struct cgroup_subsys *ss = css->ss;
4130 struct cgroup *cgrp = css->cgroup;
4133 /* css release path */
4134 cgroup_idr_remove(&ss->css_idr, css->id);
4136 /* cgroup release path */
4137 mutex_lock(&cgroup_mutex);
4138 list_del_rcu(&cgrp->sibling);
4139 mutex_unlock(&cgroup_mutex);
4141 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4145 call_rcu(&css->rcu_head, css_free_rcu_fn);
4148 static void css_release(struct percpu_ref *ref)
4150 struct cgroup_subsys_state *css =
4151 container_of(ref, struct cgroup_subsys_state, refcnt);
4153 INIT_WORK(&css->destroy_work, css_release_work_fn);
4154 queue_work(cgroup_destroy_wq, &css->destroy_work);
4157 static void init_and_link_css(struct cgroup_subsys_state *css,
4158 struct cgroup_subsys *ss, struct cgroup *cgrp)
4167 css->parent = cgroup_css(cgrp->parent, ss);
4168 css_get(css->parent);
4171 BUG_ON(cgroup_css(cgrp, ss));
4174 /* invoke ->css_online() on a new CSS and mark it online if successful */
4175 static int online_css(struct cgroup_subsys_state *css)
4177 struct cgroup_subsys *ss = css->ss;
4180 lockdep_assert_held(&cgroup_mutex);
4183 ret = ss->css_online(css);
4185 css->flags |= CSS_ONLINE;
4186 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4191 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4192 static void offline_css(struct cgroup_subsys_state *css)
4194 struct cgroup_subsys *ss = css->ss;
4196 lockdep_assert_held(&cgroup_mutex);
4198 if (!(css->flags & CSS_ONLINE))
4201 if (ss->css_offline)
4202 ss->css_offline(css);
4204 css->flags &= ~CSS_ONLINE;
4205 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4207 wake_up_all(&css->cgroup->offline_waitq);
4211 * create_css - create a cgroup_subsys_state
4212 * @cgrp: the cgroup new css will be associated with
4213 * @ss: the subsys of new css
4215 * Create a new css associated with @cgrp - @ss pair. On success, the new
4216 * css is online and installed in @cgrp with all interface files created.
4217 * Returns 0 on success, -errno on failure.
4219 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4221 struct cgroup *parent = cgrp->parent;
4222 struct cgroup_subsys_state *css;
4225 lockdep_assert_held(&cgroup_mutex);
4227 css = ss->css_alloc(cgroup_css(parent, ss));
4229 return PTR_ERR(css);
4231 init_and_link_css(css, ss, cgrp);
4233 err = percpu_ref_init(&css->refcnt, css_release);
4237 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_NOWAIT);
4239 goto err_free_percpu_ref;
4242 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4246 /* @css is ready to be brought online now, make it visible */
4247 cgroup_idr_replace(&ss->css_idr, css, css->id);
4249 err = online_css(css);
4253 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4255 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4256 current->comm, current->pid, ss->name);
4257 if (!strcmp(ss->name, "memory"))
4258 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4259 ss->warned_broken_hierarchy = true;
4265 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4267 cgroup_idr_remove(&ss->css_idr, css->id);
4268 err_free_percpu_ref:
4269 percpu_ref_cancel_init(&css->refcnt);
4271 call_rcu(&css->rcu_head, css_free_rcu_fn);
4275 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4278 struct cgroup *parent, *cgrp;
4279 struct cgroup_root *root;
4280 struct cgroup_subsys *ss;
4281 struct kernfs_node *kn;
4284 parent = cgroup_kn_lock_live(parent_kn);
4287 root = parent->root;
4289 /* allocate the cgroup and its ID, 0 is reserved for the root */
4290 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4296 ret = percpu_ref_init(&cgrp->self.refcnt, css_release);
4301 * Temporarily set the pointer to NULL, so idr_find() won't return
4302 * a half-baked cgroup.
4304 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_NOWAIT);
4307 goto out_cancel_ref;
4310 init_cgroup_housekeeping(cgrp);
4312 cgrp->parent = parent;
4313 cgrp->self.parent = &parent->self;
4316 if (notify_on_release(parent))
4317 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4319 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4320 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4322 /* create the directory */
4323 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4331 * This extra ref will be put in cgroup_free_fn() and guarantees
4332 * that @cgrp->kn is always accessible.
4336 cgrp->serial_nr = cgroup_serial_nr_next++;
4338 /* allocation complete, commit to creation */
4339 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4340 atomic_inc(&root->nr_cgrps);
4344 * @cgrp is now fully operational. If something fails after this
4345 * point, it'll be released via the normal destruction path.
4347 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4349 ret = cgroup_kn_set_ugid(kn);
4353 ret = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4357 /* let's create and online css's */
4358 for_each_subsys(ss, ssid) {
4359 if (parent->child_subsys_mask & (1 << ssid)) {
4360 ret = create_css(cgrp, ss);
4367 * On the default hierarchy, a child doesn't automatically inherit
4368 * child_subsys_mask from the parent. Each is configured manually.
4370 if (!cgroup_on_dfl(cgrp))
4371 cgrp->child_subsys_mask = parent->child_subsys_mask;
4373 kernfs_activate(kn);
4379 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4381 percpu_ref_cancel_init(&cgrp->self.refcnt);
4385 cgroup_kn_unlock(parent_kn);
4389 cgroup_destroy_locked(cgrp);
4394 * This is called when the refcnt of a css is confirmed to be killed.
4395 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
4396 * initate destruction and put the css ref from kill_css().
4398 static void css_killed_work_fn(struct work_struct *work)
4400 struct cgroup_subsys_state *css =
4401 container_of(work, struct cgroup_subsys_state, destroy_work);
4403 mutex_lock(&cgroup_mutex);
4405 mutex_unlock(&cgroup_mutex);
4410 /* css kill confirmation processing requires process context, bounce */
4411 static void css_killed_ref_fn(struct percpu_ref *ref)
4413 struct cgroup_subsys_state *css =
4414 container_of(ref, struct cgroup_subsys_state, refcnt);
4416 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4417 queue_work(cgroup_destroy_wq, &css->destroy_work);
4421 * kill_css - destroy a css
4422 * @css: css to destroy
4424 * This function initiates destruction of @css by removing cgroup interface
4425 * files and putting its base reference. ->css_offline() will be invoked
4426 * asynchronously once css_tryget_online() is guaranteed to fail and when
4427 * the reference count reaches zero, @css will be released.
4429 static void kill_css(struct cgroup_subsys_state *css)
4431 lockdep_assert_held(&cgroup_mutex);
4434 * This must happen before css is disassociated with its cgroup.
4435 * See seq_css() for details.
4437 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4440 * Killing would put the base ref, but we need to keep it alive
4441 * until after ->css_offline().
4446 * cgroup core guarantees that, by the time ->css_offline() is
4447 * invoked, no new css reference will be given out via
4448 * css_tryget_online(). We can't simply call percpu_ref_kill() and
4449 * proceed to offlining css's because percpu_ref_kill() doesn't
4450 * guarantee that the ref is seen as killed on all CPUs on return.
4452 * Use percpu_ref_kill_and_confirm() to get notifications as each
4453 * css is confirmed to be seen as killed on all CPUs.
4455 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4459 * cgroup_destroy_locked - the first stage of cgroup destruction
4460 * @cgrp: cgroup to be destroyed
4462 * css's make use of percpu refcnts whose killing latency shouldn't be
4463 * exposed to userland and are RCU protected. Also, cgroup core needs to
4464 * guarantee that css_tryget_online() won't succeed by the time
4465 * ->css_offline() is invoked. To satisfy all the requirements,
4466 * destruction is implemented in the following two steps.
4468 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4469 * userland visible parts and start killing the percpu refcnts of
4470 * css's. Set up so that the next stage will be kicked off once all
4471 * the percpu refcnts are confirmed to be killed.
4473 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4474 * rest of destruction. Once all cgroup references are gone, the
4475 * cgroup is RCU-freed.
4477 * This function implements s1. After this step, @cgrp is gone as far as
4478 * the userland is concerned and a new cgroup with the same name may be
4479 * created. As cgroup doesn't care about the names internally, this
4480 * doesn't cause any problem.
4482 static int cgroup_destroy_locked(struct cgroup *cgrp)
4483 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4485 struct cgroup_subsys_state *css;
4489 lockdep_assert_held(&cgroup_mutex);
4492 * css_set_rwsem synchronizes access to ->cset_links and prevents
4493 * @cgrp from being removed while put_css_set() is in progress.
4495 down_read(&css_set_rwsem);
4496 empty = list_empty(&cgrp->cset_links);
4497 up_read(&css_set_rwsem);
4502 * Make sure there's no live children. We can't test ->children
4503 * emptiness as dead children linger on it while being destroyed;
4504 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4506 if (cgroup_has_live_children(cgrp))
4510 * Mark @cgrp dead. This prevents further task migration and child
4511 * creation by disabling cgroup_lock_live_group(). Note that
4512 * CGRP_DEAD assertion is depended upon by css_next_child() to
4513 * resume iteration after dropping RCU read lock. See
4514 * css_next_child() for details.
4516 set_bit(CGRP_DEAD, &cgrp->flags);
4518 /* initiate massacre of all css's */
4519 for_each_css(css, ssid, cgrp)
4522 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4523 raw_spin_lock(&release_list_lock);
4524 if (!list_empty(&cgrp->release_list))
4525 list_del_init(&cgrp->release_list);
4526 raw_spin_unlock(&release_list_lock);
4529 * Remove @cgrp directory along with the base files. @cgrp has an
4530 * extra ref on its kn.
4532 kernfs_remove(cgrp->kn);
4534 set_bit(CGRP_RELEASABLE, &cgrp->parent->flags);
4535 check_for_release(cgrp->parent);
4537 /* put the base reference */
4538 percpu_ref_kill(&cgrp->self.refcnt);
4543 static int cgroup_rmdir(struct kernfs_node *kn)
4545 struct cgroup *cgrp;
4548 cgrp = cgroup_kn_lock_live(kn);
4551 cgroup_get(cgrp); /* for @kn->priv clearing */
4553 ret = cgroup_destroy_locked(cgrp);
4555 cgroup_kn_unlock(kn);
4558 * There are two control paths which try to determine cgroup from
4559 * dentry without going through kernfs - cgroupstats_build() and
4560 * css_tryget_online_from_dir(). Those are supported by RCU
4561 * protecting clearing of cgrp->kn->priv backpointer, which should
4562 * happen after all files under it have been removed.
4565 RCU_INIT_POINTER(*(void __rcu __force **)&kn->priv, NULL);
4571 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4572 .remount_fs = cgroup_remount,
4573 .show_options = cgroup_show_options,
4574 .mkdir = cgroup_mkdir,
4575 .rmdir = cgroup_rmdir,
4576 .rename = cgroup_rename,
4579 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
4581 struct cgroup_subsys_state *css;
4583 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4585 mutex_lock(&cgroup_mutex);
4587 idr_init(&ss->css_idr);
4588 INIT_LIST_HEAD(&ss->cfts);
4590 /* Create the root cgroup state for this subsystem */
4591 ss->root = &cgrp_dfl_root;
4592 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
4593 /* We don't handle early failures gracefully */
4594 BUG_ON(IS_ERR(css));
4595 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
4597 /* allocation can't be done safely during early init */
4600 BUG_ON(percpu_ref_init(&css->refcnt, css_release));
4601 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
4602 BUG_ON(css->id < 0);
4605 /* Update the init_css_set to contain a subsys
4606 * pointer to this state - since the subsystem is
4607 * newly registered, all tasks and hence the
4608 * init_css_set is in the subsystem's root cgroup. */
4609 init_css_set.subsys[ss->id] = css;
4611 need_forkexit_callback |= ss->fork || ss->exit;
4613 /* At system boot, before all subsystems have been
4614 * registered, no tasks have been forked, so we don't
4615 * need to invoke fork callbacks here. */
4616 BUG_ON(!list_empty(&init_task.tasks));
4618 BUG_ON(online_css(css));
4620 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
4622 mutex_unlock(&cgroup_mutex);
4626 * cgroup_init_early - cgroup initialization at system boot
4628 * Initialize cgroups at system boot, and initialize any
4629 * subsystems that request early init.
4631 int __init cgroup_init_early(void)
4633 static struct cgroup_sb_opts __initdata opts =
4634 { .flags = CGRP_ROOT_SANE_BEHAVIOR };
4635 struct cgroup_subsys *ss;
4638 init_cgroup_root(&cgrp_dfl_root, &opts);
4639 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4641 for_each_subsys(ss, i) {
4642 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4643 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4644 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4646 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4647 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4650 ss->name = cgroup_subsys_name[i];
4653 cgroup_init_subsys(ss, true);
4659 * cgroup_init - cgroup initialization
4661 * Register cgroup filesystem and /proc file, and initialize
4662 * any subsystems that didn't request early init.
4664 int __init cgroup_init(void)
4666 struct cgroup_subsys *ss;
4670 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4672 mutex_lock(&cgroup_mutex);
4674 /* Add init_css_set to the hash table */
4675 key = css_set_hash(init_css_set.subsys);
4676 hash_add(css_set_table, &init_css_set.hlist, key);
4678 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
4680 mutex_unlock(&cgroup_mutex);
4682 for_each_subsys(ss, ssid) {
4683 if (ss->early_init) {
4684 struct cgroup_subsys_state *css =
4685 init_css_set.subsys[ss->id];
4687 BUG_ON(percpu_ref_init(&css->refcnt, css_release));
4688 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
4690 BUG_ON(css->id < 0);
4692 cgroup_init_subsys(ss, false);
4695 list_add_tail(&init_css_set.e_cset_node[ssid],
4696 &cgrp_dfl_root.cgrp.e_csets[ssid]);
4699 * cftype registration needs kmalloc and can't be done
4700 * during early_init. Register base cftypes separately.
4702 if (ss->base_cftypes)
4703 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4706 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4710 err = register_filesystem(&cgroup_fs_type);
4712 kobject_put(cgroup_kobj);
4716 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4720 static int __init cgroup_wq_init(void)
4723 * There isn't much point in executing destruction path in
4724 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4725 * Use 1 for @max_active.
4727 * We would prefer to do this in cgroup_init() above, but that
4728 * is called before init_workqueues(): so leave this until after.
4730 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4731 BUG_ON(!cgroup_destroy_wq);
4734 * Used to destroy pidlists and separate to serve as flush domain.
4735 * Cap @max_active to 1 too.
4737 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4739 BUG_ON(!cgroup_pidlist_destroy_wq);
4743 core_initcall(cgroup_wq_init);
4746 * proc_cgroup_show()
4747 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4748 * - Used for /proc/<pid>/cgroup.
4751 /* TODO: Use a proper seq_file iterator */
4752 int proc_cgroup_show(struct seq_file *m, void *v)
4755 struct task_struct *tsk;
4758 struct cgroup_root *root;
4761 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4767 tsk = get_pid_task(pid, PIDTYPE_PID);
4773 mutex_lock(&cgroup_mutex);
4774 down_read(&css_set_rwsem);
4776 for_each_root(root) {
4777 struct cgroup_subsys *ss;
4778 struct cgroup *cgrp;
4779 int ssid, count = 0;
4781 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
4784 seq_printf(m, "%d:", root->hierarchy_id);
4785 for_each_subsys(ss, ssid)
4786 if (root->subsys_mask & (1 << ssid))
4787 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4788 if (strlen(root->name))
4789 seq_printf(m, "%sname=%s", count ? "," : "",
4792 cgrp = task_cgroup_from_root(tsk, root);
4793 path = cgroup_path(cgrp, buf, PATH_MAX);
4795 retval = -ENAMETOOLONG;
4803 up_read(&css_set_rwsem);
4804 mutex_unlock(&cgroup_mutex);
4805 put_task_struct(tsk);
4812 /* Display information about each subsystem and each hierarchy */
4813 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4815 struct cgroup_subsys *ss;
4818 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4820 * ideally we don't want subsystems moving around while we do this.
4821 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4822 * subsys/hierarchy state.
4824 mutex_lock(&cgroup_mutex);
4826 for_each_subsys(ss, i)
4827 seq_printf(m, "%s\t%d\t%d\t%d\n",
4828 ss->name, ss->root->hierarchy_id,
4829 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4831 mutex_unlock(&cgroup_mutex);
4835 static int cgroupstats_open(struct inode *inode, struct file *file)
4837 return single_open(file, proc_cgroupstats_show, NULL);
4840 static const struct file_operations proc_cgroupstats_operations = {
4841 .open = cgroupstats_open,
4843 .llseek = seq_lseek,
4844 .release = single_release,
4848 * cgroup_fork - initialize cgroup related fields during copy_process()
4849 * @child: pointer to task_struct of forking parent process.
4851 * A task is associated with the init_css_set until cgroup_post_fork()
4852 * attaches it to the parent's css_set. Empty cg_list indicates that
4853 * @child isn't holding reference to its css_set.
4855 void cgroup_fork(struct task_struct *child)
4857 RCU_INIT_POINTER(child->cgroups, &init_css_set);
4858 INIT_LIST_HEAD(&child->cg_list);
4862 * cgroup_post_fork - called on a new task after adding it to the task list
4863 * @child: the task in question
4865 * Adds the task to the list running through its css_set if necessary and
4866 * call the subsystem fork() callbacks. Has to be after the task is
4867 * visible on the task list in case we race with the first call to
4868 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4871 void cgroup_post_fork(struct task_struct *child)
4873 struct cgroup_subsys *ss;
4877 * This may race against cgroup_enable_task_cg_links(). As that
4878 * function sets use_task_css_set_links before grabbing
4879 * tasklist_lock and we just went through tasklist_lock to add
4880 * @child, it's guaranteed that either we see the set
4881 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4882 * @child during its iteration.
4884 * If we won the race, @child is associated with %current's
4885 * css_set. Grabbing css_set_rwsem guarantees both that the
4886 * association is stable, and, on completion of the parent's
4887 * migration, @child is visible in the source of migration or
4888 * already in the destination cgroup. This guarantee is necessary
4889 * when implementing operations which need to migrate all tasks of
4890 * a cgroup to another.
4892 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4893 * will remain in init_css_set. This is safe because all tasks are
4894 * in the init_css_set before cg_links is enabled and there's no
4895 * operation which transfers all tasks out of init_css_set.
4897 if (use_task_css_set_links) {
4898 struct css_set *cset;
4900 down_write(&css_set_rwsem);
4901 cset = task_css_set(current);
4902 if (list_empty(&child->cg_list)) {
4903 rcu_assign_pointer(child->cgroups, cset);
4904 list_add(&child->cg_list, &cset->tasks);
4907 up_write(&css_set_rwsem);
4911 * Call ss->fork(). This must happen after @child is linked on
4912 * css_set; otherwise, @child might change state between ->fork()
4913 * and addition to css_set.
4915 if (need_forkexit_callback) {
4916 for_each_subsys(ss, i)
4923 * cgroup_exit - detach cgroup from exiting task
4924 * @tsk: pointer to task_struct of exiting process
4926 * Description: Detach cgroup from @tsk and release it.
4928 * Note that cgroups marked notify_on_release force every task in
4929 * them to take the global cgroup_mutex mutex when exiting.
4930 * This could impact scaling on very large systems. Be reluctant to
4931 * use notify_on_release cgroups where very high task exit scaling
4932 * is required on large systems.
4934 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
4935 * call cgroup_exit() while the task is still competent to handle
4936 * notify_on_release(), then leave the task attached to the root cgroup in
4937 * each hierarchy for the remainder of its exit. No need to bother with
4938 * init_css_set refcnting. init_css_set never goes away and we can't race
4939 * with migration path - PF_EXITING is visible to migration path.
4941 void cgroup_exit(struct task_struct *tsk)
4943 struct cgroup_subsys *ss;
4944 struct css_set *cset;
4945 bool put_cset = false;
4949 * Unlink from @tsk from its css_set. As migration path can't race
4950 * with us, we can check cg_list without grabbing css_set_rwsem.
4952 if (!list_empty(&tsk->cg_list)) {
4953 down_write(&css_set_rwsem);
4954 list_del_init(&tsk->cg_list);
4955 up_write(&css_set_rwsem);
4959 /* Reassign the task to the init_css_set. */
4960 cset = task_css_set(tsk);
4961 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4963 if (need_forkexit_callback) {
4964 /* see cgroup_post_fork() for details */
4965 for_each_subsys(ss, i) {
4967 struct cgroup_subsys_state *old_css = cset->subsys[i];
4968 struct cgroup_subsys_state *css = task_css(tsk, i);
4970 ss->exit(css, old_css, tsk);
4976 put_css_set(cset, true);
4979 static void check_for_release(struct cgroup *cgrp)
4981 if (cgroup_is_releasable(cgrp) &&
4982 list_empty(&cgrp->cset_links) && !cgroup_has_live_children(cgrp)) {
4984 * Control Group is currently removeable. If it's not
4985 * already queued for a userspace notification, queue
4988 int need_schedule_work = 0;
4990 raw_spin_lock(&release_list_lock);
4991 if (!cgroup_is_dead(cgrp) &&
4992 list_empty(&cgrp->release_list)) {
4993 list_add(&cgrp->release_list, &release_list);
4994 need_schedule_work = 1;
4996 raw_spin_unlock(&release_list_lock);
4997 if (need_schedule_work)
4998 schedule_work(&release_agent_work);
5003 * Notify userspace when a cgroup is released, by running the
5004 * configured release agent with the name of the cgroup (path
5005 * relative to the root of cgroup file system) as the argument.
5007 * Most likely, this user command will try to rmdir this cgroup.
5009 * This races with the possibility that some other task will be
5010 * attached to this cgroup before it is removed, or that some other
5011 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5012 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5013 * unused, and this cgroup will be reprieved from its death sentence,
5014 * to continue to serve a useful existence. Next time it's released,
5015 * we will get notified again, if it still has 'notify_on_release' set.
5017 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5018 * means only wait until the task is successfully execve()'d. The
5019 * separate release agent task is forked by call_usermodehelper(),
5020 * then control in this thread returns here, without waiting for the
5021 * release agent task. We don't bother to wait because the caller of
5022 * this routine has no use for the exit status of the release agent
5023 * task, so no sense holding our caller up for that.
5025 static void cgroup_release_agent(struct work_struct *work)
5027 BUG_ON(work != &release_agent_work);
5028 mutex_lock(&cgroup_mutex);
5029 raw_spin_lock(&release_list_lock);
5030 while (!list_empty(&release_list)) {
5031 char *argv[3], *envp[3];
5033 char *pathbuf = NULL, *agentbuf = NULL, *path;
5034 struct cgroup *cgrp = list_entry(release_list.next,
5037 list_del_init(&cgrp->release_list);
5038 raw_spin_unlock(&release_list_lock);
5039 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5042 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5045 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5050 argv[i++] = agentbuf;
5055 /* minimal command environment */
5056 envp[i++] = "HOME=/";
5057 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5060 /* Drop the lock while we invoke the usermode helper,
5061 * since the exec could involve hitting disk and hence
5062 * be a slow process */
5063 mutex_unlock(&cgroup_mutex);
5064 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5065 mutex_lock(&cgroup_mutex);
5069 raw_spin_lock(&release_list_lock);
5071 raw_spin_unlock(&release_list_lock);
5072 mutex_unlock(&cgroup_mutex);
5075 static int __init cgroup_disable(char *str)
5077 struct cgroup_subsys *ss;
5081 while ((token = strsep(&str, ",")) != NULL) {
5085 for_each_subsys(ss, i) {
5086 if (!strcmp(token, ss->name)) {
5088 printk(KERN_INFO "Disabling %s control group"
5089 " subsystem\n", ss->name);
5096 __setup("cgroup_disable=", cgroup_disable);
5099 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5100 * @dentry: directory dentry of interest
5101 * @ss: subsystem of interest
5103 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5104 * to get the corresponding css and return it. If such css doesn't exist
5105 * or can't be pinned, an ERR_PTR value is returned.
5107 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5108 struct cgroup_subsys *ss)
5110 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5111 struct cgroup_subsys_state *css = NULL;
5112 struct cgroup *cgrp;
5114 /* is @dentry a cgroup dir? */
5115 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5116 kernfs_type(kn) != KERNFS_DIR)
5117 return ERR_PTR(-EBADF);
5122 * This path doesn't originate from kernfs and @kn could already
5123 * have been or be removed at any point. @kn->priv is RCU
5124 * protected for this access. See cgroup_rmdir() for details.
5126 cgrp = rcu_dereference(kn->priv);
5128 css = cgroup_css(cgrp, ss);
5130 if (!css || !css_tryget_online(css))
5131 css = ERR_PTR(-ENOENT);
5138 * css_from_id - lookup css by id
5139 * @id: the cgroup id
5140 * @ss: cgroup subsys to be looked into
5142 * Returns the css if there's valid one with @id, otherwise returns NULL.
5143 * Should be called under rcu_read_lock().
5145 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5147 WARN_ON_ONCE(!rcu_read_lock_held());
5148 return idr_find(&ss->css_idr, id);
5151 #ifdef CONFIG_CGROUP_DEBUG
5152 static struct cgroup_subsys_state *
5153 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5155 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5158 return ERR_PTR(-ENOMEM);
5163 static void debug_css_free(struct cgroup_subsys_state *css)
5168 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5171 return cgroup_task_count(css->cgroup);
5174 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5177 return (u64)(unsigned long)current->cgroups;
5180 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5186 count = atomic_read(&task_css_set(current)->refcount);
5191 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5193 struct cgrp_cset_link *link;
5194 struct css_set *cset;
5197 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5201 down_read(&css_set_rwsem);
5203 cset = rcu_dereference(current->cgroups);
5204 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5205 struct cgroup *c = link->cgrp;
5207 cgroup_name(c, name_buf, NAME_MAX + 1);
5208 seq_printf(seq, "Root %d group %s\n",
5209 c->root->hierarchy_id, name_buf);
5212 up_read(&css_set_rwsem);
5217 #define MAX_TASKS_SHOWN_PER_CSS 25
5218 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5220 struct cgroup_subsys_state *css = seq_css(seq);
5221 struct cgrp_cset_link *link;
5223 down_read(&css_set_rwsem);
5224 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5225 struct css_set *cset = link->cset;
5226 struct task_struct *task;
5229 seq_printf(seq, "css_set %p\n", cset);
5231 list_for_each_entry(task, &cset->tasks, cg_list) {
5232 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5234 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5237 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5238 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5240 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5244 seq_puts(seq, " ...\n");
5246 up_read(&css_set_rwsem);
5250 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5252 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5255 static struct cftype debug_files[] = {
5257 .name = "taskcount",
5258 .read_u64 = debug_taskcount_read,
5262 .name = "current_css_set",
5263 .read_u64 = current_css_set_read,
5267 .name = "current_css_set_refcount",
5268 .read_u64 = current_css_set_refcount_read,
5272 .name = "current_css_set_cg_links",
5273 .seq_show = current_css_set_cg_links_read,
5277 .name = "cgroup_css_links",
5278 .seq_show = cgroup_css_links_read,
5282 .name = "releasable",
5283 .read_u64 = releasable_read,
5289 struct cgroup_subsys debug_cgrp_subsys = {
5290 .css_alloc = debug_css_alloc,
5291 .css_free = debug_css_free,
5292 .base_cftypes = debug_files,
5294 #endif /* CONFIG_CGROUP_DEBUG */