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>
38 #include <linux/magic.h>
40 #include <linux/mutex.h>
41 #include <linux/mount.h>
42 #include <linux/pagemap.h>
43 #include <linux/proc_fs.h>
44 #include <linux/rcupdate.h>
45 #include <linux/sched.h>
46 #include <linux/slab.h>
47 #include <linux/spinlock.h>
48 #include <linux/rwsem.h>
49 #include <linux/string.h>
50 #include <linux/sort.h>
51 #include <linux/kmod.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hashtable.h>
55 #include <linux/pid_namespace.h>
56 #include <linux/idr.h>
57 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
58 #include <linux/kthread.h>
59 #include <linux/delay.h>
61 #include <linux/atomic.h>
64 * pidlists linger the following amount before being destroyed. The goal
65 * is avoiding frequent destruction in the middle of consecutive read calls
66 * Expiring in the middle is a performance problem not a correctness one.
67 * 1 sec should be enough.
69 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
71 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
75 * cgroup_mutex is the master lock. Any modification to cgroup or its
76 * hierarchy must be performed while holding it.
78 * css_set_rwsem protects task->cgroups pointer, the list of css_set
79 * objects, and the chain of tasks off each css_set.
81 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
82 * cgroup.h can use them for lockdep annotations.
84 #ifdef CONFIG_PROVE_RCU
85 DEFINE_MUTEX(cgroup_mutex);
86 DECLARE_RWSEM(css_set_rwsem);
87 EXPORT_SYMBOL_GPL(cgroup_mutex);
88 EXPORT_SYMBOL_GPL(css_set_rwsem);
90 static DEFINE_MUTEX(cgroup_mutex);
91 static DECLARE_RWSEM(css_set_rwsem);
95 * Protects cgroup_idr and css_idr so that IDs can be released without
96 * grabbing cgroup_mutex.
98 static DEFINE_SPINLOCK(cgroup_idr_lock);
101 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
102 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
104 static DEFINE_SPINLOCK(release_agent_path_lock);
106 #define cgroup_assert_mutex_or_rcu_locked() \
107 rcu_lockdep_assert(rcu_read_lock_held() || \
108 lockdep_is_held(&cgroup_mutex), \
109 "cgroup_mutex or RCU read lock required");
112 * cgroup destruction makes heavy use of work items and there can be a lot
113 * of concurrent destructions. Use a separate workqueue so that cgroup
114 * destruction work items don't end up filling up max_active of system_wq
115 * which may lead to deadlock.
117 static struct workqueue_struct *cgroup_destroy_wq;
120 * pidlist destructions need to be flushed on cgroup destruction. Use a
121 * separate workqueue as flush domain.
123 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
125 /* generate an array of cgroup subsystem pointers */
126 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
127 static struct cgroup_subsys *cgroup_subsys[] = {
128 #include <linux/cgroup_subsys.h>
132 /* array of cgroup subsystem names */
133 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
134 static const char *cgroup_subsys_name[] = {
135 #include <linux/cgroup_subsys.h>
140 * The default hierarchy, reserved for the subsystems that are otherwise
141 * unattached - it never has more than a single cgroup, and all tasks are
142 * part of that cgroup.
144 struct cgroup_root cgrp_dfl_root;
147 * The default hierarchy always exists but is hidden until mounted for the
148 * first time. This is for backward compatibility.
150 static bool cgrp_dfl_root_visible;
153 * Set by the boot param of the same name and makes subsystems with NULL
154 * ->dfl_files to use ->legacy_files on the default hierarchy.
156 static bool cgroup_legacy_files_on_dfl;
158 /* some controllers are not supported in the default hierarchy */
159 static unsigned int cgrp_dfl_root_inhibit_ss_mask;
161 /* The list of hierarchy roots */
163 static LIST_HEAD(cgroup_roots);
164 static int cgroup_root_count;
166 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
167 static DEFINE_IDR(cgroup_hierarchy_idr);
170 * Assign a monotonically increasing serial number to csses. It guarantees
171 * cgroups with bigger numbers are newer than those with smaller numbers.
172 * Also, as csses are always appended to the parent's ->children list, it
173 * guarantees that sibling csses are always sorted in the ascending serial
174 * number order on the list. Protected by cgroup_mutex.
176 static u64 css_serial_nr_next = 1;
178 /* This flag indicates whether tasks in the fork and exit paths should
179 * check for fork/exit handlers to call. This avoids us having to do
180 * extra work in the fork/exit path if none of the subsystems need to
183 static int need_forkexit_callback __read_mostly;
185 static struct cftype cgroup_dfl_base_files[];
186 static struct cftype cgroup_legacy_base_files[];
188 static void cgroup_put(struct cgroup *cgrp);
189 static int rebind_subsystems(struct cgroup_root *dst_root,
190 unsigned int ss_mask);
191 static int cgroup_destroy_locked(struct cgroup *cgrp);
192 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss,
194 static void css_release(struct percpu_ref *ref);
195 static void kill_css(struct cgroup_subsys_state *css);
196 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
198 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
200 /* IDR wrappers which synchronize using cgroup_idr_lock */
201 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
206 idr_preload(gfp_mask);
207 spin_lock_bh(&cgroup_idr_lock);
208 ret = idr_alloc(idr, ptr, start, end, gfp_mask);
209 spin_unlock_bh(&cgroup_idr_lock);
214 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
218 spin_lock_bh(&cgroup_idr_lock);
219 ret = idr_replace(idr, ptr, id);
220 spin_unlock_bh(&cgroup_idr_lock);
224 static void cgroup_idr_remove(struct idr *idr, int id)
226 spin_lock_bh(&cgroup_idr_lock);
228 spin_unlock_bh(&cgroup_idr_lock);
231 static struct cgroup *cgroup_parent(struct cgroup *cgrp)
233 struct cgroup_subsys_state *parent_css = cgrp->self.parent;
236 return container_of(parent_css, struct cgroup, self);
241 * cgroup_css - obtain a cgroup's css for the specified subsystem
242 * @cgrp: the cgroup of interest
243 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
245 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
246 * function must be called either under cgroup_mutex or rcu_read_lock() and
247 * the caller is responsible for pinning the returned css if it wants to
248 * keep accessing it outside the said locks. This function may return
249 * %NULL if @cgrp doesn't have @subsys_id enabled.
251 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
252 struct cgroup_subsys *ss)
255 return rcu_dereference_check(cgrp->subsys[ss->id],
256 lockdep_is_held(&cgroup_mutex));
262 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
263 * @cgrp: the cgroup of interest
264 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
266 * Similar to cgroup_css() but returns the effctive css, which is defined
267 * as the matching css of the nearest ancestor including self which has @ss
268 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
269 * function is guaranteed to return non-NULL css.
271 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
272 struct cgroup_subsys *ss)
274 lockdep_assert_held(&cgroup_mutex);
279 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
282 while (cgroup_parent(cgrp) &&
283 !(cgroup_parent(cgrp)->child_subsys_mask & (1 << ss->id)))
284 cgrp = cgroup_parent(cgrp);
286 return cgroup_css(cgrp, ss);
289 /* convenient tests for these bits */
290 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
292 return !(cgrp->self.flags & CSS_ONLINE);
295 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
297 struct cgroup *cgrp = of->kn->parent->priv;
298 struct cftype *cft = of_cft(of);
301 * This is open and unprotected implementation of cgroup_css().
302 * seq_css() is only called from a kernfs file operation which has
303 * an active reference on the file. Because all the subsystem
304 * files are drained before a css is disassociated with a cgroup,
305 * the matching css from the cgroup's subsys table is guaranteed to
306 * be and stay valid until the enclosing operation is complete.
309 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
313 EXPORT_SYMBOL_GPL(of_css);
316 * cgroup_is_descendant - test ancestry
317 * @cgrp: the cgroup to be tested
318 * @ancestor: possible ancestor of @cgrp
320 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
321 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
322 * and @ancestor are accessible.
324 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
327 if (cgrp == ancestor)
329 cgrp = cgroup_parent(cgrp);
334 static int cgroup_is_releasable(const struct cgroup *cgrp)
337 (1 << CGRP_RELEASABLE) |
338 (1 << CGRP_NOTIFY_ON_RELEASE);
339 return (cgrp->flags & bits) == bits;
342 static int notify_on_release(const struct cgroup *cgrp)
344 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
348 * for_each_css - iterate all css's of a cgroup
349 * @css: the iteration cursor
350 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
351 * @cgrp: the target cgroup to iterate css's of
353 * Should be called under cgroup_[tree_]mutex.
355 #define for_each_css(css, ssid, cgrp) \
356 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
357 if (!((css) = rcu_dereference_check( \
358 (cgrp)->subsys[(ssid)], \
359 lockdep_is_held(&cgroup_mutex)))) { } \
363 * for_each_e_css - iterate all effective css's of a cgroup
364 * @css: the iteration cursor
365 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
366 * @cgrp: the target cgroup to iterate css's of
368 * Should be called under cgroup_[tree_]mutex.
370 #define for_each_e_css(css, ssid, cgrp) \
371 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
372 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
377 * for_each_subsys - iterate all enabled cgroup subsystems
378 * @ss: the iteration cursor
379 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
381 #define for_each_subsys(ss, ssid) \
382 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
383 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
385 /* iterate across the hierarchies */
386 #define for_each_root(root) \
387 list_for_each_entry((root), &cgroup_roots, root_list)
389 /* iterate over child cgrps, lock should be held throughout iteration */
390 #define cgroup_for_each_live_child(child, cgrp) \
391 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
392 if (({ lockdep_assert_held(&cgroup_mutex); \
393 cgroup_is_dead(child); })) \
397 /* the list of cgroups eligible for automatic release. Protected by
398 * release_list_lock */
399 static LIST_HEAD(release_list);
400 static DEFINE_RAW_SPINLOCK(release_list_lock);
401 static void cgroup_release_agent(struct work_struct *work);
402 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
403 static void check_for_release(struct cgroup *cgrp);
406 * A cgroup can be associated with multiple css_sets as different tasks may
407 * belong to different cgroups on different hierarchies. In the other
408 * direction, a css_set is naturally associated with multiple cgroups.
409 * This M:N relationship is represented by the following link structure
410 * which exists for each association and allows traversing the associations
413 struct cgrp_cset_link {
414 /* the cgroup and css_set this link associates */
416 struct css_set *cset;
418 /* list of cgrp_cset_links anchored at cgrp->cset_links */
419 struct list_head cset_link;
421 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
422 struct list_head cgrp_link;
426 * The default css_set - used by init and its children prior to any
427 * hierarchies being mounted. It contains a pointer to the root state
428 * for each subsystem. Also used to anchor the list of css_sets. Not
429 * reference-counted, to improve performance when child cgroups
430 * haven't been created.
432 struct css_set init_css_set = {
433 .refcount = ATOMIC_INIT(1),
434 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
435 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
436 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
437 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
438 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
441 static int css_set_count = 1; /* 1 for init_css_set */
444 * cgroup_update_populated - updated populated count of a cgroup
445 * @cgrp: the target cgroup
446 * @populated: inc or dec populated count
448 * @cgrp is either getting the first task (css_set) or losing the last.
449 * Update @cgrp->populated_cnt accordingly. The count is propagated
450 * towards root so that a given cgroup's populated_cnt is zero iff the
451 * cgroup and all its descendants are empty.
453 * @cgrp's interface file "cgroup.populated" is zero if
454 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
455 * changes from or to zero, userland is notified that the content of the
456 * interface file has changed. This can be used to detect when @cgrp and
457 * its descendants become populated or empty.
459 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
461 lockdep_assert_held(&css_set_rwsem);
467 trigger = !cgrp->populated_cnt++;
469 trigger = !--cgrp->populated_cnt;
474 if (cgrp->populated_kn)
475 kernfs_notify(cgrp->populated_kn);
476 cgrp = cgroup_parent(cgrp);
481 * hash table for cgroup groups. This improves the performance to find
482 * an existing css_set. This hash doesn't (currently) take into
483 * account cgroups in empty hierarchies.
485 #define CSS_SET_HASH_BITS 7
486 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
488 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
490 unsigned long key = 0UL;
491 struct cgroup_subsys *ss;
494 for_each_subsys(ss, i)
495 key += (unsigned long)css[i];
496 key = (key >> 16) ^ key;
501 static void put_css_set_locked(struct css_set *cset, bool taskexit)
503 struct cgrp_cset_link *link, *tmp_link;
504 struct cgroup_subsys *ss;
507 lockdep_assert_held(&css_set_rwsem);
509 if (!atomic_dec_and_test(&cset->refcount))
512 /* This css_set is dead. unlink it and release cgroup refcounts */
513 for_each_subsys(ss, ssid)
514 list_del(&cset->e_cset_node[ssid]);
515 hash_del(&cset->hlist);
518 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
519 struct cgroup *cgrp = link->cgrp;
521 list_del(&link->cset_link);
522 list_del(&link->cgrp_link);
524 /* @cgrp can't go away while we're holding css_set_rwsem */
525 if (list_empty(&cgrp->cset_links)) {
526 cgroup_update_populated(cgrp, false);
527 if (notify_on_release(cgrp)) {
529 set_bit(CGRP_RELEASABLE, &cgrp->flags);
530 check_for_release(cgrp);
537 kfree_rcu(cset, rcu_head);
540 static void put_css_set(struct css_set *cset, bool taskexit)
543 * Ensure that the refcount doesn't hit zero while any readers
544 * can see it. Similar to atomic_dec_and_lock(), but for an
547 if (atomic_add_unless(&cset->refcount, -1, 1))
550 down_write(&css_set_rwsem);
551 put_css_set_locked(cset, taskexit);
552 up_write(&css_set_rwsem);
556 * refcounted get/put for css_set objects
558 static inline void get_css_set(struct css_set *cset)
560 atomic_inc(&cset->refcount);
564 * compare_css_sets - helper function for find_existing_css_set().
565 * @cset: candidate css_set being tested
566 * @old_cset: existing css_set for a task
567 * @new_cgrp: cgroup that's being entered by the task
568 * @template: desired set of css pointers in css_set (pre-calculated)
570 * Returns true if "cset" matches "old_cset" except for the hierarchy
571 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
573 static bool compare_css_sets(struct css_set *cset,
574 struct css_set *old_cset,
575 struct cgroup *new_cgrp,
576 struct cgroup_subsys_state *template[])
578 struct list_head *l1, *l2;
581 * On the default hierarchy, there can be csets which are
582 * associated with the same set of cgroups but different csses.
583 * Let's first ensure that csses match.
585 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
589 * Compare cgroup pointers in order to distinguish between
590 * different cgroups in hierarchies. As different cgroups may
591 * share the same effective css, this comparison is always
594 l1 = &cset->cgrp_links;
595 l2 = &old_cset->cgrp_links;
597 struct cgrp_cset_link *link1, *link2;
598 struct cgroup *cgrp1, *cgrp2;
602 /* See if we reached the end - both lists are equal length. */
603 if (l1 == &cset->cgrp_links) {
604 BUG_ON(l2 != &old_cset->cgrp_links);
607 BUG_ON(l2 == &old_cset->cgrp_links);
609 /* Locate the cgroups associated with these links. */
610 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
611 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
614 /* Hierarchies should be linked in the same order. */
615 BUG_ON(cgrp1->root != cgrp2->root);
618 * If this hierarchy is the hierarchy of the cgroup
619 * that's changing, then we need to check that this
620 * css_set points to the new cgroup; if it's any other
621 * hierarchy, then this css_set should point to the
622 * same cgroup as the old css_set.
624 if (cgrp1->root == new_cgrp->root) {
625 if (cgrp1 != new_cgrp)
636 * find_existing_css_set - init css array and find the matching css_set
637 * @old_cset: the css_set that we're using before the cgroup transition
638 * @cgrp: the cgroup that we're moving into
639 * @template: out param for the new set of csses, should be clear on entry
641 static struct css_set *find_existing_css_set(struct css_set *old_cset,
643 struct cgroup_subsys_state *template[])
645 struct cgroup_root *root = cgrp->root;
646 struct cgroup_subsys *ss;
647 struct css_set *cset;
652 * Build the set of subsystem state objects that we want to see in the
653 * new css_set. while subsystems can change globally, the entries here
654 * won't change, so no need for locking.
656 for_each_subsys(ss, i) {
657 if (root->subsys_mask & (1UL << i)) {
659 * @ss is in this hierarchy, so we want the
660 * effective css from @cgrp.
662 template[i] = cgroup_e_css(cgrp, ss);
665 * @ss is not in this hierarchy, so we don't want
668 template[i] = old_cset->subsys[i];
672 key = css_set_hash(template);
673 hash_for_each_possible(css_set_table, cset, hlist, key) {
674 if (!compare_css_sets(cset, old_cset, cgrp, template))
677 /* This css_set matches what we need */
681 /* No existing cgroup group matched */
685 static void free_cgrp_cset_links(struct list_head *links_to_free)
687 struct cgrp_cset_link *link, *tmp_link;
689 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
690 list_del(&link->cset_link);
696 * allocate_cgrp_cset_links - allocate cgrp_cset_links
697 * @count: the number of links to allocate
698 * @tmp_links: list_head the allocated links are put on
700 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
701 * through ->cset_link. Returns 0 on success or -errno.
703 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
705 struct cgrp_cset_link *link;
708 INIT_LIST_HEAD(tmp_links);
710 for (i = 0; i < count; i++) {
711 link = kzalloc(sizeof(*link), GFP_KERNEL);
713 free_cgrp_cset_links(tmp_links);
716 list_add(&link->cset_link, tmp_links);
722 * link_css_set - a helper function to link a css_set to a cgroup
723 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
724 * @cset: the css_set to be linked
725 * @cgrp: the destination cgroup
727 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
730 struct cgrp_cset_link *link;
732 BUG_ON(list_empty(tmp_links));
734 if (cgroup_on_dfl(cgrp))
735 cset->dfl_cgrp = cgrp;
737 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
741 if (list_empty(&cgrp->cset_links))
742 cgroup_update_populated(cgrp, true);
743 list_move(&link->cset_link, &cgrp->cset_links);
746 * Always add links to the tail of the list so that the list
747 * is sorted by order of hierarchy creation
749 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
753 * find_css_set - return a new css_set with one cgroup updated
754 * @old_cset: the baseline css_set
755 * @cgrp: the cgroup to be updated
757 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
758 * substituted into the appropriate hierarchy.
760 static struct css_set *find_css_set(struct css_set *old_cset,
763 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
764 struct css_set *cset;
765 struct list_head tmp_links;
766 struct cgrp_cset_link *link;
767 struct cgroup_subsys *ss;
771 lockdep_assert_held(&cgroup_mutex);
773 /* First see if we already have a cgroup group that matches
775 down_read(&css_set_rwsem);
776 cset = find_existing_css_set(old_cset, cgrp, template);
779 up_read(&css_set_rwsem);
784 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
788 /* Allocate all the cgrp_cset_link objects that we'll need */
789 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
794 atomic_set(&cset->refcount, 1);
795 INIT_LIST_HEAD(&cset->cgrp_links);
796 INIT_LIST_HEAD(&cset->tasks);
797 INIT_LIST_HEAD(&cset->mg_tasks);
798 INIT_LIST_HEAD(&cset->mg_preload_node);
799 INIT_LIST_HEAD(&cset->mg_node);
800 INIT_HLIST_NODE(&cset->hlist);
802 /* Copy the set of subsystem state objects generated in
803 * find_existing_css_set() */
804 memcpy(cset->subsys, template, sizeof(cset->subsys));
806 down_write(&css_set_rwsem);
807 /* Add reference counts and links from the new css_set. */
808 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
809 struct cgroup *c = link->cgrp;
811 if (c->root == cgrp->root)
813 link_css_set(&tmp_links, cset, c);
816 BUG_ON(!list_empty(&tmp_links));
820 /* Add @cset to the hash table */
821 key = css_set_hash(cset->subsys);
822 hash_add(css_set_table, &cset->hlist, key);
824 for_each_subsys(ss, ssid)
825 list_add_tail(&cset->e_cset_node[ssid],
826 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
828 up_write(&css_set_rwsem);
833 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
835 struct cgroup *root_cgrp = kf_root->kn->priv;
837 return root_cgrp->root;
840 static int cgroup_init_root_id(struct cgroup_root *root)
844 lockdep_assert_held(&cgroup_mutex);
846 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
850 root->hierarchy_id = id;
854 static void cgroup_exit_root_id(struct cgroup_root *root)
856 lockdep_assert_held(&cgroup_mutex);
858 if (root->hierarchy_id) {
859 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
860 root->hierarchy_id = 0;
864 static void cgroup_free_root(struct cgroup_root *root)
867 /* hierarhcy ID shoulid already have been released */
868 WARN_ON_ONCE(root->hierarchy_id);
870 idr_destroy(&root->cgroup_idr);
875 static void cgroup_destroy_root(struct cgroup_root *root)
877 struct cgroup *cgrp = &root->cgrp;
878 struct cgrp_cset_link *link, *tmp_link;
880 mutex_lock(&cgroup_mutex);
882 BUG_ON(atomic_read(&root->nr_cgrps));
883 BUG_ON(!list_empty(&cgrp->self.children));
885 /* Rebind all subsystems back to the default hierarchy */
886 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
889 * Release all the links from cset_links to this hierarchy's
892 down_write(&css_set_rwsem);
894 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
895 list_del(&link->cset_link);
896 list_del(&link->cgrp_link);
899 up_write(&css_set_rwsem);
901 if (!list_empty(&root->root_list)) {
902 list_del(&root->root_list);
906 cgroup_exit_root_id(root);
908 mutex_unlock(&cgroup_mutex);
910 kernfs_destroy_root(root->kf_root);
911 cgroup_free_root(root);
914 /* look up cgroup associated with given css_set on the specified hierarchy */
915 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
916 struct cgroup_root *root)
918 struct cgroup *res = NULL;
920 lockdep_assert_held(&cgroup_mutex);
921 lockdep_assert_held(&css_set_rwsem);
923 if (cset == &init_css_set) {
926 struct cgrp_cset_link *link;
928 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
929 struct cgroup *c = link->cgrp;
931 if (c->root == root) {
943 * Return the cgroup for "task" from the given hierarchy. Must be
944 * called with cgroup_mutex and css_set_rwsem held.
946 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
947 struct cgroup_root *root)
950 * No need to lock the task - since we hold cgroup_mutex the
951 * task can't change groups, so the only thing that can happen
952 * is that it exits and its css is set back to init_css_set.
954 return cset_cgroup_from_root(task_css_set(task), root);
958 * A task must hold cgroup_mutex to modify cgroups.
960 * Any task can increment and decrement the count field without lock.
961 * So in general, code holding cgroup_mutex can't rely on the count
962 * field not changing. However, if the count goes to zero, then only
963 * cgroup_attach_task() can increment it again. Because a count of zero
964 * means that no tasks are currently attached, therefore there is no
965 * way a task attached to that cgroup can fork (the other way to
966 * increment the count). So code holding cgroup_mutex can safely
967 * assume that if the count is zero, it will stay zero. Similarly, if
968 * a task holds cgroup_mutex on a cgroup with zero count, it
969 * knows that the cgroup won't be removed, as cgroup_rmdir()
972 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
973 * (usually) take cgroup_mutex. These are the two most performance
974 * critical pieces of code here. The exception occurs on cgroup_exit(),
975 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
976 * is taken, and if the cgroup count is zero, a usermode call made
977 * to the release agent with the name of the cgroup (path relative to
978 * the root of cgroup file system) as the argument.
980 * A cgroup can only be deleted if both its 'count' of using tasks
981 * is zero, and its list of 'children' cgroups is empty. Since all
982 * tasks in the system use _some_ cgroup, and since there is always at
983 * least one task in the system (init, pid == 1), therefore, root cgroup
984 * always has either children cgroups and/or using tasks. So we don't
985 * need a special hack to ensure that root cgroup cannot be deleted.
987 * P.S. One more locking exception. RCU is used to guard the
988 * update of a tasks cgroup pointer by cgroup_attach_task()
991 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask);
992 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
993 static const struct file_operations proc_cgroupstats_operations;
995 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
998 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
999 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1000 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1001 cft->ss->name, cft->name);
1003 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1008 * cgroup_file_mode - deduce file mode of a control file
1009 * @cft: the control file in question
1011 * returns cft->mode if ->mode is not 0
1012 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1013 * returns S_IRUGO if it has only a read handler
1014 * returns S_IWUSR if it has only a write hander
1016 static umode_t cgroup_file_mode(const struct cftype *cft)
1023 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1026 if (cft->write_u64 || cft->write_s64 || cft->write)
1032 static void cgroup_get(struct cgroup *cgrp)
1034 WARN_ON_ONCE(cgroup_is_dead(cgrp));
1035 css_get(&cgrp->self);
1038 static void cgroup_put(struct cgroup *cgrp)
1040 css_put(&cgrp->self);
1044 * cgroup_refresh_child_subsys_mask - update child_subsys_mask
1045 * @cgrp: the target cgroup
1047 * On the default hierarchy, a subsystem may request other subsystems to be
1048 * enabled together through its ->depends_on mask. In such cases, more
1049 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1051 * This function determines which subsystems need to be enabled given the
1052 * current @cgrp->subtree_control and records it in
1053 * @cgrp->child_subsys_mask. The resulting mask is always a superset of
1054 * @cgrp->subtree_control and follows the usual hierarchy rules.
1056 static void cgroup_refresh_child_subsys_mask(struct cgroup *cgrp)
1058 struct cgroup *parent = cgroup_parent(cgrp);
1059 unsigned int cur_ss_mask = cgrp->subtree_control;
1060 struct cgroup_subsys *ss;
1063 lockdep_assert_held(&cgroup_mutex);
1065 if (!cgroup_on_dfl(cgrp)) {
1066 cgrp->child_subsys_mask = cur_ss_mask;
1071 unsigned int new_ss_mask = cur_ss_mask;
1073 for_each_subsys(ss, ssid)
1074 if (cur_ss_mask & (1 << ssid))
1075 new_ss_mask |= ss->depends_on;
1078 * Mask out subsystems which aren't available. This can
1079 * happen only if some depended-upon subsystems were bound
1080 * to non-default hierarchies.
1083 new_ss_mask &= parent->child_subsys_mask;
1085 new_ss_mask &= cgrp->root->subsys_mask;
1087 if (new_ss_mask == cur_ss_mask)
1089 cur_ss_mask = new_ss_mask;
1092 cgrp->child_subsys_mask = cur_ss_mask;
1096 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1097 * @kn: the kernfs_node being serviced
1099 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1100 * the method finishes if locking succeeded. Note that once this function
1101 * returns the cgroup returned by cgroup_kn_lock_live() may become
1102 * inaccessible any time. If the caller intends to continue to access the
1103 * cgroup, it should pin it before invoking this function.
1105 static void cgroup_kn_unlock(struct kernfs_node *kn)
1107 struct cgroup *cgrp;
1109 if (kernfs_type(kn) == KERNFS_DIR)
1112 cgrp = kn->parent->priv;
1114 mutex_unlock(&cgroup_mutex);
1116 kernfs_unbreak_active_protection(kn);
1121 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1122 * @kn: the kernfs_node being serviced
1124 * This helper is to be used by a cgroup kernfs method currently servicing
1125 * @kn. It breaks the active protection, performs cgroup locking and
1126 * verifies that the associated cgroup is alive. Returns the cgroup if
1127 * alive; otherwise, %NULL. A successful return should be undone by a
1128 * matching cgroup_kn_unlock() invocation.
1130 * Any cgroup kernfs method implementation which requires locking the
1131 * associated cgroup should use this helper. It avoids nesting cgroup
1132 * locking under kernfs active protection and allows all kernfs operations
1133 * including self-removal.
1135 static struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn)
1137 struct cgroup *cgrp;
1139 if (kernfs_type(kn) == KERNFS_DIR)
1142 cgrp = kn->parent->priv;
1145 * We're gonna grab cgroup_mutex which nests outside kernfs
1146 * active_ref. cgroup liveliness check alone provides enough
1147 * protection against removal. Ensure @cgrp stays accessible and
1148 * break the active_ref protection.
1151 kernfs_break_active_protection(kn);
1153 mutex_lock(&cgroup_mutex);
1155 if (!cgroup_is_dead(cgrp))
1158 cgroup_kn_unlock(kn);
1162 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1164 char name[CGROUP_FILE_NAME_MAX];
1166 lockdep_assert_held(&cgroup_mutex);
1167 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1171 * cgroup_clear_dir - remove subsys files in a cgroup directory
1172 * @cgrp: target cgroup
1173 * @subsys_mask: mask of the subsystem ids whose files should be removed
1175 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned int subsys_mask)
1177 struct cgroup_subsys *ss;
1180 for_each_subsys(ss, i) {
1181 struct cftype *cfts;
1183 if (!(subsys_mask & (1 << i)))
1185 list_for_each_entry(cfts, &ss->cfts, node)
1186 cgroup_addrm_files(cgrp, cfts, false);
1190 static int rebind_subsystems(struct cgroup_root *dst_root, unsigned int ss_mask)
1192 struct cgroup_subsys *ss;
1193 unsigned int tmp_ss_mask;
1196 lockdep_assert_held(&cgroup_mutex);
1198 for_each_subsys(ss, ssid) {
1199 if (!(ss_mask & (1 << ssid)))
1202 /* if @ss has non-root csses attached to it, can't move */
1203 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1206 /* can't move between two non-dummy roots either */
1207 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1211 /* skip creating root files on dfl_root for inhibited subsystems */
1212 tmp_ss_mask = ss_mask;
1213 if (dst_root == &cgrp_dfl_root)
1214 tmp_ss_mask &= ~cgrp_dfl_root_inhibit_ss_mask;
1216 ret = cgroup_populate_dir(&dst_root->cgrp, tmp_ss_mask);
1218 if (dst_root != &cgrp_dfl_root)
1222 * Rebinding back to the default root is not allowed to
1223 * fail. Using both default and non-default roots should
1224 * be rare. Moving subsystems back and forth even more so.
1225 * Just warn about it and continue.
1227 if (cgrp_dfl_root_visible) {
1228 pr_warn("failed to create files (%d) while rebinding 0x%x to default root\n",
1230 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1235 * Nothing can fail from this point on. Remove files for the
1236 * removed subsystems and rebind each subsystem.
1238 for_each_subsys(ss, ssid)
1239 if (ss_mask & (1 << ssid))
1240 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1242 for_each_subsys(ss, ssid) {
1243 struct cgroup_root *src_root;
1244 struct cgroup_subsys_state *css;
1245 struct css_set *cset;
1247 if (!(ss_mask & (1 << ssid)))
1250 src_root = ss->root;
1251 css = cgroup_css(&src_root->cgrp, ss);
1253 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1255 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1256 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1257 ss->root = dst_root;
1258 css->cgroup = &dst_root->cgrp;
1260 down_write(&css_set_rwsem);
1261 hash_for_each(css_set_table, i, cset, hlist)
1262 list_move_tail(&cset->e_cset_node[ss->id],
1263 &dst_root->cgrp.e_csets[ss->id]);
1264 up_write(&css_set_rwsem);
1266 src_root->subsys_mask &= ~(1 << ssid);
1267 src_root->cgrp.subtree_control &= ~(1 << ssid);
1268 cgroup_refresh_child_subsys_mask(&src_root->cgrp);
1270 /* default hierarchy doesn't enable controllers by default */
1271 dst_root->subsys_mask |= 1 << ssid;
1272 if (dst_root != &cgrp_dfl_root) {
1273 dst_root->cgrp.subtree_control |= 1 << ssid;
1274 cgroup_refresh_child_subsys_mask(&dst_root->cgrp);
1281 kernfs_activate(dst_root->cgrp.kn);
1285 static int cgroup_show_options(struct seq_file *seq,
1286 struct kernfs_root *kf_root)
1288 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1289 struct cgroup_subsys *ss;
1292 for_each_subsys(ss, ssid)
1293 if (root->subsys_mask & (1 << ssid))
1294 seq_printf(seq, ",%s", ss->name);
1295 if (root->flags & CGRP_ROOT_NOPREFIX)
1296 seq_puts(seq, ",noprefix");
1297 if (root->flags & CGRP_ROOT_XATTR)
1298 seq_puts(seq, ",xattr");
1300 spin_lock(&release_agent_path_lock);
1301 if (strlen(root->release_agent_path))
1302 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1303 spin_unlock(&release_agent_path_lock);
1305 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1306 seq_puts(seq, ",clone_children");
1307 if (strlen(root->name))
1308 seq_printf(seq, ",name=%s", root->name);
1312 struct cgroup_sb_opts {
1313 unsigned int subsys_mask;
1315 char *release_agent;
1316 bool cpuset_clone_children;
1318 /* User explicitly requested empty subsystem */
1322 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1324 char *token, *o = data;
1325 bool all_ss = false, one_ss = false;
1326 unsigned int mask = -1U;
1327 struct cgroup_subsys *ss;
1331 #ifdef CONFIG_CPUSETS
1332 mask = ~(1U << cpuset_cgrp_id);
1335 memset(opts, 0, sizeof(*opts));
1337 while ((token = strsep(&o, ",")) != NULL) {
1342 if (!strcmp(token, "none")) {
1343 /* Explicitly have no subsystems */
1347 if (!strcmp(token, "all")) {
1348 /* Mutually exclusive option 'all' + subsystem name */
1354 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1355 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1358 if (!strcmp(token, "noprefix")) {
1359 opts->flags |= CGRP_ROOT_NOPREFIX;
1362 if (!strcmp(token, "clone_children")) {
1363 opts->cpuset_clone_children = true;
1366 if (!strcmp(token, "xattr")) {
1367 opts->flags |= CGRP_ROOT_XATTR;
1370 if (!strncmp(token, "release_agent=", 14)) {
1371 /* Specifying two release agents is forbidden */
1372 if (opts->release_agent)
1374 opts->release_agent =
1375 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1376 if (!opts->release_agent)
1380 if (!strncmp(token, "name=", 5)) {
1381 const char *name = token + 5;
1382 /* Can't specify an empty name */
1385 /* Must match [\w.-]+ */
1386 for (i = 0; i < strlen(name); i++) {
1390 if ((c == '.') || (c == '-') || (c == '_'))
1394 /* Specifying two names is forbidden */
1397 opts->name = kstrndup(name,
1398 MAX_CGROUP_ROOT_NAMELEN - 1,
1406 for_each_subsys(ss, i) {
1407 if (strcmp(token, ss->name))
1412 /* Mutually exclusive option 'all' + subsystem name */
1415 opts->subsys_mask |= (1 << i);
1420 if (i == CGROUP_SUBSYS_COUNT)
1424 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1425 pr_warn("sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1427 pr_err("sane_behavior: no other mount options allowed\n");
1434 * If the 'all' option was specified select all the subsystems,
1435 * otherwise if 'none', 'name=' and a subsystem name options were
1436 * not specified, let's default to 'all'
1438 if (all_ss || (!one_ss && !opts->none && !opts->name))
1439 for_each_subsys(ss, i)
1441 opts->subsys_mask |= (1 << i);
1444 * We either have to specify by name or by subsystems. (So all
1445 * empty hierarchies must have a name).
1447 if (!opts->subsys_mask && !opts->name)
1451 * Option noprefix was introduced just for backward compatibility
1452 * with the old cpuset, so we allow noprefix only if mounting just
1453 * the cpuset subsystem.
1455 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1458 /* Can't specify "none" and some subsystems */
1459 if (opts->subsys_mask && opts->none)
1465 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1468 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1469 struct cgroup_sb_opts opts;
1470 unsigned int added_mask, removed_mask;
1472 if (root == &cgrp_dfl_root) {
1473 pr_err("remount is not allowed\n");
1477 mutex_lock(&cgroup_mutex);
1479 /* See what subsystems are wanted */
1480 ret = parse_cgroupfs_options(data, &opts);
1484 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1485 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1486 task_tgid_nr(current), current->comm);
1488 added_mask = opts.subsys_mask & ~root->subsys_mask;
1489 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1491 /* Don't allow flags or name to change at remount */
1492 if ((opts.flags ^ root->flags) ||
1493 (opts.name && strcmp(opts.name, root->name))) {
1494 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1495 opts.flags, opts.name ?: "", root->flags, root->name);
1500 /* remounting is not allowed for populated hierarchies */
1501 if (!list_empty(&root->cgrp.self.children)) {
1506 ret = rebind_subsystems(root, added_mask);
1510 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1512 if (opts.release_agent) {
1513 spin_lock(&release_agent_path_lock);
1514 strcpy(root->release_agent_path, opts.release_agent);
1515 spin_unlock(&release_agent_path_lock);
1518 kfree(opts.release_agent);
1520 mutex_unlock(&cgroup_mutex);
1525 * To reduce the fork() overhead for systems that are not actually using
1526 * their cgroups capability, we don't maintain the lists running through
1527 * each css_set to its tasks until we see the list actually used - in other
1528 * words after the first mount.
1530 static bool use_task_css_set_links __read_mostly;
1532 static void cgroup_enable_task_cg_lists(void)
1534 struct task_struct *p, *g;
1536 down_write(&css_set_rwsem);
1538 if (use_task_css_set_links)
1541 use_task_css_set_links = true;
1544 * We need tasklist_lock because RCU is not safe against
1545 * while_each_thread(). Besides, a forking task that has passed
1546 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1547 * is not guaranteed to have its child immediately visible in the
1548 * tasklist if we walk through it with RCU.
1550 read_lock(&tasklist_lock);
1551 do_each_thread(g, p) {
1552 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1553 task_css_set(p) != &init_css_set);
1556 * We should check if the process is exiting, otherwise
1557 * it will race with cgroup_exit() in that the list
1558 * entry won't be deleted though the process has exited.
1559 * Do it while holding siglock so that we don't end up
1560 * racing against cgroup_exit().
1562 spin_lock_irq(&p->sighand->siglock);
1563 if (!(p->flags & PF_EXITING)) {
1564 struct css_set *cset = task_css_set(p);
1566 list_add(&p->cg_list, &cset->tasks);
1569 spin_unlock_irq(&p->sighand->siglock);
1570 } while_each_thread(g, p);
1571 read_unlock(&tasklist_lock);
1573 up_write(&css_set_rwsem);
1576 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1578 struct cgroup_subsys *ss;
1581 INIT_LIST_HEAD(&cgrp->self.sibling);
1582 INIT_LIST_HEAD(&cgrp->self.children);
1583 INIT_LIST_HEAD(&cgrp->cset_links);
1584 INIT_LIST_HEAD(&cgrp->release_list);
1585 INIT_LIST_HEAD(&cgrp->pidlists);
1586 mutex_init(&cgrp->pidlist_mutex);
1587 cgrp->self.cgroup = cgrp;
1588 cgrp->self.flags |= CSS_ONLINE;
1590 for_each_subsys(ss, ssid)
1591 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1593 init_waitqueue_head(&cgrp->offline_waitq);
1596 static void init_cgroup_root(struct cgroup_root *root,
1597 struct cgroup_sb_opts *opts)
1599 struct cgroup *cgrp = &root->cgrp;
1601 INIT_LIST_HEAD(&root->root_list);
1602 atomic_set(&root->nr_cgrps, 1);
1604 init_cgroup_housekeeping(cgrp);
1605 idr_init(&root->cgroup_idr);
1607 root->flags = opts->flags;
1608 if (opts->release_agent)
1609 strcpy(root->release_agent_path, opts->release_agent);
1611 strcpy(root->name, opts->name);
1612 if (opts->cpuset_clone_children)
1613 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1616 static int cgroup_setup_root(struct cgroup_root *root, unsigned int ss_mask)
1618 LIST_HEAD(tmp_links);
1619 struct cgroup *root_cgrp = &root->cgrp;
1620 struct cftype *base_files;
1621 struct css_set *cset;
1624 lockdep_assert_held(&cgroup_mutex);
1626 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_NOWAIT);
1629 root_cgrp->id = ret;
1631 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release);
1636 * We're accessing css_set_count without locking css_set_rwsem here,
1637 * but that's OK - it can only be increased by someone holding
1638 * cgroup_lock, and that's us. The worst that can happen is that we
1639 * have some link structures left over
1641 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1645 ret = cgroup_init_root_id(root);
1649 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1650 KERNFS_ROOT_CREATE_DEACTIVATED,
1652 if (IS_ERR(root->kf_root)) {
1653 ret = PTR_ERR(root->kf_root);
1656 root_cgrp->kn = root->kf_root->kn;
1658 if (root == &cgrp_dfl_root)
1659 base_files = cgroup_dfl_base_files;
1661 base_files = cgroup_legacy_base_files;
1663 ret = cgroup_addrm_files(root_cgrp, base_files, true);
1667 ret = rebind_subsystems(root, ss_mask);
1672 * There must be no failure case after here, since rebinding takes
1673 * care of subsystems' refcounts, which are explicitly dropped in
1674 * the failure exit path.
1676 list_add(&root->root_list, &cgroup_roots);
1677 cgroup_root_count++;
1680 * Link the root cgroup in this hierarchy into all the css_set
1683 down_write(&css_set_rwsem);
1684 hash_for_each(css_set_table, i, cset, hlist)
1685 link_css_set(&tmp_links, cset, root_cgrp);
1686 up_write(&css_set_rwsem);
1688 BUG_ON(!list_empty(&root_cgrp->self.children));
1689 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1691 kernfs_activate(root_cgrp->kn);
1696 kernfs_destroy_root(root->kf_root);
1697 root->kf_root = NULL;
1699 cgroup_exit_root_id(root);
1701 percpu_ref_cancel_init(&root_cgrp->self.refcnt);
1703 free_cgrp_cset_links(&tmp_links);
1707 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1708 int flags, const char *unused_dev_name,
1711 struct cgroup_root *root;
1712 struct cgroup_sb_opts opts;
1713 struct dentry *dentry;
1718 * The first time anyone tries to mount a cgroup, enable the list
1719 * linking each css_set to its tasks and fix up all existing tasks.
1721 if (!use_task_css_set_links)
1722 cgroup_enable_task_cg_lists();
1724 mutex_lock(&cgroup_mutex);
1726 /* First find the desired set of subsystems */
1727 ret = parse_cgroupfs_options(data, &opts);
1731 /* look for a matching existing root */
1732 if (opts.flags & CGRP_ROOT_SANE_BEHAVIOR) {
1733 cgrp_dfl_root_visible = true;
1734 root = &cgrp_dfl_root;
1735 cgroup_get(&root->cgrp);
1740 for_each_root(root) {
1741 bool name_match = false;
1743 if (root == &cgrp_dfl_root)
1747 * If we asked for a name then it must match. Also, if
1748 * name matches but sybsys_mask doesn't, we should fail.
1749 * Remember whether name matched.
1752 if (strcmp(opts.name, root->name))
1758 * If we asked for subsystems (or explicitly for no
1759 * subsystems) then they must match.
1761 if ((opts.subsys_mask || opts.none) &&
1762 (opts.subsys_mask != root->subsys_mask)) {
1769 if (root->flags ^ opts.flags)
1770 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1773 * A root's lifetime is governed by its root cgroup.
1774 * tryget_live failure indicate that the root is being
1775 * destroyed. Wait for destruction to complete so that the
1776 * subsystems are free. We can use wait_queue for the wait
1777 * but this path is super cold. Let's just sleep for a bit
1780 if (!percpu_ref_tryget_live(&root->cgrp.self.refcnt)) {
1781 mutex_unlock(&cgroup_mutex);
1783 ret = restart_syscall();
1792 * No such thing, create a new one. name= matching without subsys
1793 * specification is allowed for already existing hierarchies but we
1794 * can't create new one without subsys specification.
1796 if (!opts.subsys_mask && !opts.none) {
1801 root = kzalloc(sizeof(*root), GFP_KERNEL);
1807 init_cgroup_root(root, &opts);
1809 ret = cgroup_setup_root(root, opts.subsys_mask);
1811 cgroup_free_root(root);
1814 mutex_unlock(&cgroup_mutex);
1816 kfree(opts.release_agent);
1820 return ERR_PTR(ret);
1822 dentry = kernfs_mount(fs_type, flags, root->kf_root,
1823 CGROUP_SUPER_MAGIC, &new_sb);
1824 if (IS_ERR(dentry) || !new_sb)
1825 cgroup_put(&root->cgrp);
1829 static void cgroup_kill_sb(struct super_block *sb)
1831 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1832 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1835 * If @root doesn't have any mounts or children, start killing it.
1836 * This prevents new mounts by disabling percpu_ref_tryget_live().
1837 * cgroup_mount() may wait for @root's release.
1839 * And don't kill the default root.
1841 if (css_has_online_children(&root->cgrp.self) ||
1842 root == &cgrp_dfl_root)
1843 cgroup_put(&root->cgrp);
1845 percpu_ref_kill(&root->cgrp.self.refcnt);
1850 static struct file_system_type cgroup_fs_type = {
1852 .mount = cgroup_mount,
1853 .kill_sb = cgroup_kill_sb,
1856 static struct kobject *cgroup_kobj;
1859 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1860 * @task: target task
1861 * @buf: the buffer to write the path into
1862 * @buflen: the length of the buffer
1864 * Determine @task's cgroup on the first (the one with the lowest non-zero
1865 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1866 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1867 * cgroup controller callbacks.
1869 * Return value is the same as kernfs_path().
1871 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1873 struct cgroup_root *root;
1874 struct cgroup *cgrp;
1875 int hierarchy_id = 1;
1878 mutex_lock(&cgroup_mutex);
1879 down_read(&css_set_rwsem);
1881 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1884 cgrp = task_cgroup_from_root(task, root);
1885 path = cgroup_path(cgrp, buf, buflen);
1887 /* if no hierarchy exists, everyone is in "/" */
1888 if (strlcpy(buf, "/", buflen) < buflen)
1892 up_read(&css_set_rwsem);
1893 mutex_unlock(&cgroup_mutex);
1896 EXPORT_SYMBOL_GPL(task_cgroup_path);
1898 /* used to track tasks and other necessary states during migration */
1899 struct cgroup_taskset {
1900 /* the src and dst cset list running through cset->mg_node */
1901 struct list_head src_csets;
1902 struct list_head dst_csets;
1905 * Fields for cgroup_taskset_*() iteration.
1907 * Before migration is committed, the target migration tasks are on
1908 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1909 * the csets on ->dst_csets. ->csets point to either ->src_csets
1910 * or ->dst_csets depending on whether migration is committed.
1912 * ->cur_csets and ->cur_task point to the current task position
1915 struct list_head *csets;
1916 struct css_set *cur_cset;
1917 struct task_struct *cur_task;
1921 * cgroup_taskset_first - reset taskset and return the first task
1922 * @tset: taskset of interest
1924 * @tset iteration is initialized and the first task is returned.
1926 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1928 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1929 tset->cur_task = NULL;
1931 return cgroup_taskset_next(tset);
1935 * cgroup_taskset_next - iterate to the next task in taskset
1936 * @tset: taskset of interest
1938 * Return the next task in @tset. Iteration must have been initialized
1939 * with cgroup_taskset_first().
1941 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1943 struct css_set *cset = tset->cur_cset;
1944 struct task_struct *task = tset->cur_task;
1946 while (&cset->mg_node != tset->csets) {
1948 task = list_first_entry(&cset->mg_tasks,
1949 struct task_struct, cg_list);
1951 task = list_next_entry(task, cg_list);
1953 if (&task->cg_list != &cset->mg_tasks) {
1954 tset->cur_cset = cset;
1955 tset->cur_task = task;
1959 cset = list_next_entry(cset, mg_node);
1967 * cgroup_task_migrate - move a task from one cgroup to another.
1968 * @old_cgrp: the cgroup @tsk is being migrated from
1969 * @tsk: the task being migrated
1970 * @new_cset: the new css_set @tsk is being attached to
1972 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1974 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1975 struct task_struct *tsk,
1976 struct css_set *new_cset)
1978 struct css_set *old_cset;
1980 lockdep_assert_held(&cgroup_mutex);
1981 lockdep_assert_held(&css_set_rwsem);
1984 * We are synchronized through threadgroup_lock() against PF_EXITING
1985 * setting such that we can't race against cgroup_exit() changing the
1986 * css_set to init_css_set and dropping the old one.
1988 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1989 old_cset = task_css_set(tsk);
1991 get_css_set(new_cset);
1992 rcu_assign_pointer(tsk->cgroups, new_cset);
1995 * Use move_tail so that cgroup_taskset_first() still returns the
1996 * leader after migration. This works because cgroup_migrate()
1997 * ensures that the dst_cset of the leader is the first on the
1998 * tset's dst_csets list.
2000 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
2003 * We just gained a reference on old_cset by taking it from the
2004 * task. As trading it for new_cset is protected by cgroup_mutex,
2005 * we're safe to drop it here; it will be freed under RCU.
2007 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
2008 put_css_set_locked(old_cset, false);
2012 * cgroup_migrate_finish - cleanup after attach
2013 * @preloaded_csets: list of preloaded css_sets
2015 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2016 * those functions for details.
2018 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
2020 struct css_set *cset, *tmp_cset;
2022 lockdep_assert_held(&cgroup_mutex);
2024 down_write(&css_set_rwsem);
2025 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
2026 cset->mg_src_cgrp = NULL;
2027 cset->mg_dst_cset = NULL;
2028 list_del_init(&cset->mg_preload_node);
2029 put_css_set_locked(cset, false);
2031 up_write(&css_set_rwsem);
2035 * cgroup_migrate_add_src - add a migration source css_set
2036 * @src_cset: the source css_set to add
2037 * @dst_cgrp: the destination cgroup
2038 * @preloaded_csets: list of preloaded css_sets
2040 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2041 * @src_cset and add it to @preloaded_csets, which should later be cleaned
2042 * up by cgroup_migrate_finish().
2044 * This function may be called without holding threadgroup_lock even if the
2045 * target is a process. Threads may be created and destroyed but as long
2046 * as cgroup_mutex is not dropped, no new css_set can be put into play and
2047 * the preloaded css_sets are guaranteed to cover all migrations.
2049 static void cgroup_migrate_add_src(struct css_set *src_cset,
2050 struct cgroup *dst_cgrp,
2051 struct list_head *preloaded_csets)
2053 struct cgroup *src_cgrp;
2055 lockdep_assert_held(&cgroup_mutex);
2056 lockdep_assert_held(&css_set_rwsem);
2058 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2060 if (!list_empty(&src_cset->mg_preload_node))
2063 WARN_ON(src_cset->mg_src_cgrp);
2064 WARN_ON(!list_empty(&src_cset->mg_tasks));
2065 WARN_ON(!list_empty(&src_cset->mg_node));
2067 src_cset->mg_src_cgrp = src_cgrp;
2068 get_css_set(src_cset);
2069 list_add(&src_cset->mg_preload_node, preloaded_csets);
2073 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2074 * @dst_cgrp: the destination cgroup (may be %NULL)
2075 * @preloaded_csets: list of preloaded source css_sets
2077 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
2078 * have been preloaded to @preloaded_csets. This function looks up and
2079 * pins all destination css_sets, links each to its source, and append them
2080 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
2081 * source css_set is assumed to be its cgroup on the default hierarchy.
2083 * This function must be called after cgroup_migrate_add_src() has been
2084 * called on each migration source css_set. After migration is performed
2085 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2088 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
2089 struct list_head *preloaded_csets)
2092 struct css_set *src_cset, *tmp_cset;
2094 lockdep_assert_held(&cgroup_mutex);
2097 * Except for the root, child_subsys_mask must be zero for a cgroup
2098 * with tasks so that child cgroups don't compete against tasks.
2100 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && cgroup_parent(dst_cgrp) &&
2101 dst_cgrp->child_subsys_mask)
2104 /* look up the dst cset for each src cset and link it to src */
2105 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2106 struct css_set *dst_cset;
2108 dst_cset = find_css_set(src_cset,
2109 dst_cgrp ?: src_cset->dfl_cgrp);
2113 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2116 * If src cset equals dst, it's noop. Drop the src.
2117 * cgroup_migrate() will skip the cset too. Note that we
2118 * can't handle src == dst as some nodes are used by both.
2120 if (src_cset == dst_cset) {
2121 src_cset->mg_src_cgrp = NULL;
2122 list_del_init(&src_cset->mg_preload_node);
2123 put_css_set(src_cset, false);
2124 put_css_set(dst_cset, false);
2128 src_cset->mg_dst_cset = dst_cset;
2130 if (list_empty(&dst_cset->mg_preload_node))
2131 list_add(&dst_cset->mg_preload_node, &csets);
2133 put_css_set(dst_cset, false);
2136 list_splice_tail(&csets, preloaded_csets);
2139 cgroup_migrate_finish(&csets);
2144 * cgroup_migrate - migrate a process or task to a cgroup
2145 * @cgrp: the destination cgroup
2146 * @leader: the leader of the process or the task to migrate
2147 * @threadgroup: whether @leader points to the whole process or a single task
2149 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2150 * process, the caller must be holding threadgroup_lock of @leader. The
2151 * caller is also responsible for invoking cgroup_migrate_add_src() and
2152 * cgroup_migrate_prepare_dst() on the targets before invoking this
2153 * function and following up with cgroup_migrate_finish().
2155 * As long as a controller's ->can_attach() doesn't fail, this function is
2156 * guaranteed to succeed. This means that, excluding ->can_attach()
2157 * failure, when migrating multiple targets, the success or failure can be
2158 * decided for all targets by invoking group_migrate_prepare_dst() before
2159 * actually starting migrating.
2161 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
2164 struct cgroup_taskset tset = {
2165 .src_csets = LIST_HEAD_INIT(tset.src_csets),
2166 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
2167 .csets = &tset.src_csets,
2169 struct cgroup_subsys_state *css, *failed_css = NULL;
2170 struct css_set *cset, *tmp_cset;
2171 struct task_struct *task, *tmp_task;
2175 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2176 * already PF_EXITING could be freed from underneath us unless we
2177 * take an rcu_read_lock.
2179 down_write(&css_set_rwsem);
2183 /* @task either already exited or can't exit until the end */
2184 if (task->flags & PF_EXITING)
2187 /* leave @task alone if post_fork() hasn't linked it yet */
2188 if (list_empty(&task->cg_list))
2191 cset = task_css_set(task);
2192 if (!cset->mg_src_cgrp)
2196 * cgroup_taskset_first() must always return the leader.
2197 * Take care to avoid disturbing the ordering.
2199 list_move_tail(&task->cg_list, &cset->mg_tasks);
2200 if (list_empty(&cset->mg_node))
2201 list_add_tail(&cset->mg_node, &tset.src_csets);
2202 if (list_empty(&cset->mg_dst_cset->mg_node))
2203 list_move_tail(&cset->mg_dst_cset->mg_node,
2208 } while_each_thread(leader, task);
2210 up_write(&css_set_rwsem);
2212 /* methods shouldn't be called if no task is actually migrating */
2213 if (list_empty(&tset.src_csets))
2216 /* check that we can legitimately attach to the cgroup */
2217 for_each_e_css(css, i, cgrp) {
2218 if (css->ss->can_attach) {
2219 ret = css->ss->can_attach(css, &tset);
2222 goto out_cancel_attach;
2228 * Now that we're guaranteed success, proceed to move all tasks to
2229 * the new cgroup. There are no failure cases after here, so this
2230 * is the commit point.
2232 down_write(&css_set_rwsem);
2233 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2234 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2235 cgroup_task_migrate(cset->mg_src_cgrp, task,
2238 up_write(&css_set_rwsem);
2241 * Migration is committed, all target tasks are now on dst_csets.
2242 * Nothing is sensitive to fork() after this point. Notify
2243 * controllers that migration is complete.
2245 tset.csets = &tset.dst_csets;
2247 for_each_e_css(css, i, cgrp)
2248 if (css->ss->attach)
2249 css->ss->attach(css, &tset);
2252 goto out_release_tset;
2255 for_each_e_css(css, i, cgrp) {
2256 if (css == failed_css)
2258 if (css->ss->cancel_attach)
2259 css->ss->cancel_attach(css, &tset);
2262 down_write(&css_set_rwsem);
2263 list_splice_init(&tset.dst_csets, &tset.src_csets);
2264 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2265 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2266 list_del_init(&cset->mg_node);
2268 up_write(&css_set_rwsem);
2273 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2274 * @dst_cgrp: the cgroup to attach to
2275 * @leader: the task or the leader of the threadgroup to be attached
2276 * @threadgroup: attach the whole threadgroup?
2278 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2280 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2281 struct task_struct *leader, bool threadgroup)
2283 LIST_HEAD(preloaded_csets);
2284 struct task_struct *task;
2287 /* look up all src csets */
2288 down_read(&css_set_rwsem);
2292 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2296 } while_each_thread(leader, task);
2298 up_read(&css_set_rwsem);
2300 /* prepare dst csets and commit */
2301 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2303 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2305 cgroup_migrate_finish(&preloaded_csets);
2310 * Find the task_struct of the task to attach by vpid and pass it along to the
2311 * function to attach either it or all tasks in its threadgroup. Will lock
2312 * cgroup_mutex and threadgroup.
2314 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
2315 size_t nbytes, loff_t off, bool threadgroup)
2317 struct task_struct *tsk;
2318 const struct cred *cred = current_cred(), *tcred;
2319 struct cgroup *cgrp;
2323 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2326 cgrp = cgroup_kn_lock_live(of->kn);
2333 tsk = find_task_by_vpid(pid);
2337 goto out_unlock_cgroup;
2340 * even if we're attaching all tasks in the thread group, we
2341 * only need to check permissions on one of them.
2343 tcred = __task_cred(tsk);
2344 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2345 !uid_eq(cred->euid, tcred->uid) &&
2346 !uid_eq(cred->euid, tcred->suid)) {
2349 goto out_unlock_cgroup;
2355 tsk = tsk->group_leader;
2358 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2359 * trapped in a cpuset, or RT worker may be born in a cgroup
2360 * with no rt_runtime allocated. Just say no.
2362 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2365 goto out_unlock_cgroup;
2368 get_task_struct(tsk);
2371 threadgroup_lock(tsk);
2373 if (!thread_group_leader(tsk)) {
2375 * a race with de_thread from another thread's exec()
2376 * may strip us of our leadership, if this happens,
2377 * there is no choice but to throw this task away and
2378 * try again; this is
2379 * "double-double-toil-and-trouble-check locking".
2381 threadgroup_unlock(tsk);
2382 put_task_struct(tsk);
2383 goto retry_find_task;
2387 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2389 threadgroup_unlock(tsk);
2391 put_task_struct(tsk);
2393 cgroup_kn_unlock(of->kn);
2394 return ret ?: nbytes;
2398 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2399 * @from: attach to all cgroups of a given task
2400 * @tsk: the task to be attached
2402 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2404 struct cgroup_root *root;
2407 mutex_lock(&cgroup_mutex);
2408 for_each_root(root) {
2409 struct cgroup *from_cgrp;
2411 if (root == &cgrp_dfl_root)
2414 down_read(&css_set_rwsem);
2415 from_cgrp = task_cgroup_from_root(from, root);
2416 up_read(&css_set_rwsem);
2418 retval = cgroup_attach_task(from_cgrp, tsk, false);
2422 mutex_unlock(&cgroup_mutex);
2426 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2428 static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
2429 char *buf, size_t nbytes, loff_t off)
2431 return __cgroup_procs_write(of, buf, nbytes, off, false);
2434 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
2435 char *buf, size_t nbytes, loff_t off)
2437 return __cgroup_procs_write(of, buf, nbytes, off, true);
2440 static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
2441 char *buf, size_t nbytes, loff_t off)
2443 struct cgroup *cgrp;
2445 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2447 cgrp = cgroup_kn_lock_live(of->kn);
2450 spin_lock(&release_agent_path_lock);
2451 strlcpy(cgrp->root->release_agent_path, strstrip(buf),
2452 sizeof(cgrp->root->release_agent_path));
2453 spin_unlock(&release_agent_path_lock);
2454 cgroup_kn_unlock(of->kn);
2458 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2460 struct cgroup *cgrp = seq_css(seq)->cgroup;
2462 spin_lock(&release_agent_path_lock);
2463 seq_puts(seq, cgrp->root->release_agent_path);
2464 spin_unlock(&release_agent_path_lock);
2465 seq_putc(seq, '\n');
2469 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2471 seq_puts(seq, "0\n");
2475 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned int ss_mask)
2477 struct cgroup_subsys *ss;
2478 bool printed = false;
2481 for_each_subsys(ss, ssid) {
2482 if (ss_mask & (1 << ssid)) {
2485 seq_printf(seq, "%s", ss->name);
2490 seq_putc(seq, '\n');
2493 /* show controllers which are currently attached to the default hierarchy */
2494 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2496 struct cgroup *cgrp = seq_css(seq)->cgroup;
2498 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask &
2499 ~cgrp_dfl_root_inhibit_ss_mask);
2503 /* show controllers which are enabled from the parent */
2504 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2506 struct cgroup *cgrp = seq_css(seq)->cgroup;
2508 cgroup_print_ss_mask(seq, cgroup_parent(cgrp)->subtree_control);
2512 /* show controllers which are enabled for a given cgroup's children */
2513 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2515 struct cgroup *cgrp = seq_css(seq)->cgroup;
2517 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2522 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2523 * @cgrp: root of the subtree to update csses for
2525 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2526 * css associations need to be updated accordingly. This function looks up
2527 * all css_sets which are attached to the subtree, creates the matching
2528 * updated css_sets and migrates the tasks to the new ones.
2530 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2532 LIST_HEAD(preloaded_csets);
2533 struct cgroup_subsys_state *css;
2534 struct css_set *src_cset;
2537 lockdep_assert_held(&cgroup_mutex);
2539 /* look up all csses currently attached to @cgrp's subtree */
2540 down_read(&css_set_rwsem);
2541 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2542 struct cgrp_cset_link *link;
2544 /* self is not affected by child_subsys_mask change */
2545 if (css->cgroup == cgrp)
2548 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2549 cgroup_migrate_add_src(link->cset, cgrp,
2552 up_read(&css_set_rwsem);
2554 /* NULL dst indicates self on default hierarchy */
2555 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2559 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2560 struct task_struct *last_task = NULL, *task;
2562 /* src_csets precede dst_csets, break on the first dst_cset */
2563 if (!src_cset->mg_src_cgrp)
2567 * All tasks in src_cset need to be migrated to the
2568 * matching dst_cset. Empty it process by process. We
2569 * walk tasks but migrate processes. The leader might even
2570 * belong to a different cset but such src_cset would also
2571 * be among the target src_csets because the default
2572 * hierarchy enforces per-process membership.
2575 down_read(&css_set_rwsem);
2576 task = list_first_entry_or_null(&src_cset->tasks,
2577 struct task_struct, cg_list);
2579 task = task->group_leader;
2580 WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
2581 get_task_struct(task);
2583 up_read(&css_set_rwsem);
2588 /* guard against possible infinite loop */
2589 if (WARN(last_task == task,
2590 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2594 threadgroup_lock(task);
2595 /* raced against de_thread() from another thread? */
2596 if (!thread_group_leader(task)) {
2597 threadgroup_unlock(task);
2598 put_task_struct(task);
2602 ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
2604 threadgroup_unlock(task);
2605 put_task_struct(task);
2607 if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
2613 cgroup_migrate_finish(&preloaded_csets);
2617 /* change the enabled child controllers for a cgroup in the default hierarchy */
2618 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
2619 char *buf, size_t nbytes,
2622 unsigned int enable = 0, disable = 0;
2623 unsigned int css_enable, css_disable, old_ctrl, new_ctrl;
2624 struct cgroup *cgrp, *child;
2625 struct cgroup_subsys *ss;
2630 * Parse input - space separated list of subsystem names prefixed
2631 * with either + or -.
2633 buf = strstrip(buf);
2634 while ((tok = strsep(&buf, " "))) {
2637 for_each_subsys(ss, ssid) {
2638 if (ss->disabled || strcmp(tok + 1, ss->name) ||
2639 ((1 << ss->id) & cgrp_dfl_root_inhibit_ss_mask))
2643 enable |= 1 << ssid;
2644 disable &= ~(1 << ssid);
2645 } else if (*tok == '-') {
2646 disable |= 1 << ssid;
2647 enable &= ~(1 << ssid);
2653 if (ssid == CGROUP_SUBSYS_COUNT)
2657 cgrp = cgroup_kn_lock_live(of->kn);
2661 for_each_subsys(ss, ssid) {
2662 if (enable & (1 << ssid)) {
2663 if (cgrp->subtree_control & (1 << ssid)) {
2664 enable &= ~(1 << ssid);
2668 /* unavailable or not enabled on the parent? */
2669 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2670 (cgroup_parent(cgrp) &&
2671 !(cgroup_parent(cgrp)->subtree_control & (1 << ssid)))) {
2677 * @ss is already enabled through dependency and
2678 * we'll just make it visible. Skip draining.
2680 if (cgrp->child_subsys_mask & (1 << ssid))
2684 * Because css offlining is asynchronous, userland
2685 * might try to re-enable the same controller while
2686 * the previous instance is still around. In such
2687 * cases, wait till it's gone using offline_waitq.
2689 cgroup_for_each_live_child(child, cgrp) {
2692 if (!cgroup_css(child, ss))
2696 prepare_to_wait(&child->offline_waitq, &wait,
2697 TASK_UNINTERRUPTIBLE);
2698 cgroup_kn_unlock(of->kn);
2700 finish_wait(&child->offline_waitq, &wait);
2703 return restart_syscall();
2705 } else if (disable & (1 << ssid)) {
2706 if (!(cgrp->subtree_control & (1 << ssid))) {
2707 disable &= ~(1 << ssid);
2711 /* a child has it enabled? */
2712 cgroup_for_each_live_child(child, cgrp) {
2713 if (child->subtree_control & (1 << ssid)) {
2721 if (!enable && !disable) {
2727 * Except for the root, subtree_control must be zero for a cgroup
2728 * with tasks so that child cgroups don't compete against tasks.
2730 if (enable && cgroup_parent(cgrp) && !list_empty(&cgrp->cset_links)) {
2736 * Update subsys masks and calculate what needs to be done. More
2737 * subsystems than specified may need to be enabled or disabled
2738 * depending on subsystem dependencies.
2740 cgrp->subtree_control |= enable;
2741 cgrp->subtree_control &= ~disable;
2743 old_ctrl = cgrp->child_subsys_mask;
2744 cgroup_refresh_child_subsys_mask(cgrp);
2745 new_ctrl = cgrp->child_subsys_mask;
2747 css_enable = ~old_ctrl & new_ctrl;
2748 css_disable = old_ctrl & ~new_ctrl;
2749 enable |= css_enable;
2750 disable |= css_disable;
2753 * Create new csses or make the existing ones visible. A css is
2754 * created invisible if it's being implicitly enabled through
2755 * dependency. An invisible css is made visible when the userland
2756 * explicitly enables it.
2758 for_each_subsys(ss, ssid) {
2759 if (!(enable & (1 << ssid)))
2762 cgroup_for_each_live_child(child, cgrp) {
2763 if (css_enable & (1 << ssid))
2764 ret = create_css(child, ss,
2765 cgrp->subtree_control & (1 << ssid));
2767 ret = cgroup_populate_dir(child, 1 << ssid);
2774 * At this point, cgroup_e_css() results reflect the new csses
2775 * making the following cgroup_update_dfl_csses() properly update
2776 * css associations of all tasks in the subtree.
2778 ret = cgroup_update_dfl_csses(cgrp);
2783 * All tasks are migrated out of disabled csses. Kill or hide
2784 * them. A css is hidden when the userland requests it to be
2785 * disabled while other subsystems are still depending on it. The
2786 * css must not actively control resources and be in the vanilla
2787 * state if it's made visible again later. Controllers which may
2788 * be depended upon should provide ->css_reset() for this purpose.
2790 for_each_subsys(ss, ssid) {
2791 if (!(disable & (1 << ssid)))
2794 cgroup_for_each_live_child(child, cgrp) {
2795 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2797 if (css_disable & (1 << ssid)) {
2800 cgroup_clear_dir(child, 1 << ssid);
2807 kernfs_activate(cgrp->kn);
2810 cgroup_kn_unlock(of->kn);
2811 return ret ?: nbytes;
2814 cgrp->subtree_control &= ~enable;
2815 cgrp->subtree_control |= disable;
2816 cgroup_refresh_child_subsys_mask(cgrp);
2818 for_each_subsys(ss, ssid) {
2819 if (!(enable & (1 << ssid)))
2822 cgroup_for_each_live_child(child, cgrp) {
2823 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2828 if (css_enable & (1 << ssid))
2831 cgroup_clear_dir(child, 1 << ssid);
2837 static int cgroup_populated_show(struct seq_file *seq, void *v)
2839 seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
2843 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2844 size_t nbytes, loff_t off)
2846 struct cgroup *cgrp = of->kn->parent->priv;
2847 struct cftype *cft = of->kn->priv;
2848 struct cgroup_subsys_state *css;
2852 return cft->write(of, buf, nbytes, off);
2855 * kernfs guarantees that a file isn't deleted with operations in
2856 * flight, which means that the matching css is and stays alive and
2857 * doesn't need to be pinned. The RCU locking is not necessary
2858 * either. It's just for the convenience of using cgroup_css().
2861 css = cgroup_css(cgrp, cft->ss);
2864 if (cft->write_u64) {
2865 unsigned long long v;
2866 ret = kstrtoull(buf, 0, &v);
2868 ret = cft->write_u64(css, cft, v);
2869 } else if (cft->write_s64) {
2871 ret = kstrtoll(buf, 0, &v);
2873 ret = cft->write_s64(css, cft, v);
2878 return ret ?: nbytes;
2881 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2883 return seq_cft(seq)->seq_start(seq, ppos);
2886 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2888 return seq_cft(seq)->seq_next(seq, v, ppos);
2891 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2893 seq_cft(seq)->seq_stop(seq, v);
2896 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2898 struct cftype *cft = seq_cft(m);
2899 struct cgroup_subsys_state *css = seq_css(m);
2902 return cft->seq_show(m, arg);
2905 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2906 else if (cft->read_s64)
2907 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2913 static struct kernfs_ops cgroup_kf_single_ops = {
2914 .atomic_write_len = PAGE_SIZE,
2915 .write = cgroup_file_write,
2916 .seq_show = cgroup_seqfile_show,
2919 static struct kernfs_ops cgroup_kf_ops = {
2920 .atomic_write_len = PAGE_SIZE,
2921 .write = cgroup_file_write,
2922 .seq_start = cgroup_seqfile_start,
2923 .seq_next = cgroup_seqfile_next,
2924 .seq_stop = cgroup_seqfile_stop,
2925 .seq_show = cgroup_seqfile_show,
2929 * cgroup_rename - Only allow simple rename of directories in place.
2931 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2932 const char *new_name_str)
2934 struct cgroup *cgrp = kn->priv;
2937 if (kernfs_type(kn) != KERNFS_DIR)
2939 if (kn->parent != new_parent)
2943 * This isn't a proper migration and its usefulness is very
2944 * limited. Disallow on the default hierarchy.
2946 if (cgroup_on_dfl(cgrp))
2950 * We're gonna grab cgroup_mutex which nests outside kernfs
2951 * active_ref. kernfs_rename() doesn't require active_ref
2952 * protection. Break them before grabbing cgroup_mutex.
2954 kernfs_break_active_protection(new_parent);
2955 kernfs_break_active_protection(kn);
2957 mutex_lock(&cgroup_mutex);
2959 ret = kernfs_rename(kn, new_parent, new_name_str);
2961 mutex_unlock(&cgroup_mutex);
2963 kernfs_unbreak_active_protection(kn);
2964 kernfs_unbreak_active_protection(new_parent);
2968 /* set uid and gid of cgroup dirs and files to that of the creator */
2969 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
2971 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
2972 .ia_uid = current_fsuid(),
2973 .ia_gid = current_fsgid(), };
2975 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
2976 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
2979 return kernfs_setattr(kn, &iattr);
2982 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2984 char name[CGROUP_FILE_NAME_MAX];
2985 struct kernfs_node *kn;
2986 struct lock_class_key *key = NULL;
2989 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2990 key = &cft->lockdep_key;
2992 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2993 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2998 ret = cgroup_kn_set_ugid(kn);
3004 if (cft->seq_show == cgroup_populated_show)
3005 cgrp->populated_kn = kn;
3010 * cgroup_addrm_files - add or remove files to a cgroup directory
3011 * @cgrp: the target cgroup
3012 * @cfts: array of cftypes to be added
3013 * @is_add: whether to add or remove
3015 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3016 * For removals, this function never fails. If addition fails, this
3017 * function doesn't remove files already added. The caller is responsible
3020 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
3026 lockdep_assert_held(&cgroup_mutex);
3028 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3029 /* does cft->flags tell us to skip this file on @cgrp? */
3030 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3032 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3034 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3036 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3040 ret = cgroup_add_file(cgrp, cft);
3042 pr_warn("%s: failed to add %s, err=%d\n",
3043 __func__, cft->name, ret);
3047 cgroup_rm_file(cgrp, cft);
3053 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3056 struct cgroup_subsys *ss = cfts[0].ss;
3057 struct cgroup *root = &ss->root->cgrp;
3058 struct cgroup_subsys_state *css;
3061 lockdep_assert_held(&cgroup_mutex);
3063 /* add/rm files for all cgroups created before */
3064 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3065 struct cgroup *cgrp = css->cgroup;
3067 if (cgroup_is_dead(cgrp))
3070 ret = cgroup_addrm_files(cgrp, cfts, is_add);
3076 kernfs_activate(root->kn);
3080 static void cgroup_exit_cftypes(struct cftype *cfts)
3084 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3085 /* free copy for custom atomic_write_len, see init_cftypes() */
3086 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3091 /* revert flags set by cgroup core while adding @cfts */
3092 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3096 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3100 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3101 struct kernfs_ops *kf_ops;
3103 WARN_ON(cft->ss || cft->kf_ops);
3106 kf_ops = &cgroup_kf_ops;
3108 kf_ops = &cgroup_kf_single_ops;
3111 * Ugh... if @cft wants a custom max_write_len, we need to
3112 * make a copy of kf_ops to set its atomic_write_len.
3114 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3115 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3117 cgroup_exit_cftypes(cfts);
3120 kf_ops->atomic_write_len = cft->max_write_len;
3123 cft->kf_ops = kf_ops;
3130 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3132 lockdep_assert_held(&cgroup_mutex);
3134 if (!cfts || !cfts[0].ss)
3137 list_del(&cfts->node);
3138 cgroup_apply_cftypes(cfts, false);
3139 cgroup_exit_cftypes(cfts);
3144 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3145 * @cfts: zero-length name terminated array of cftypes
3147 * Unregister @cfts. Files described by @cfts are removed from all
3148 * existing cgroups and all future cgroups won't have them either. This
3149 * function can be called anytime whether @cfts' subsys is attached or not.
3151 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3154 int cgroup_rm_cftypes(struct cftype *cfts)
3158 mutex_lock(&cgroup_mutex);
3159 ret = cgroup_rm_cftypes_locked(cfts);
3160 mutex_unlock(&cgroup_mutex);
3165 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3166 * @ss: target cgroup subsystem
3167 * @cfts: zero-length name terminated array of cftypes
3169 * Register @cfts to @ss. Files described by @cfts are created for all
3170 * existing cgroups to which @ss is attached and all future cgroups will
3171 * have them too. This function can be called anytime whether @ss is
3174 * Returns 0 on successful registration, -errno on failure. Note that this
3175 * function currently returns 0 as long as @cfts registration is successful
3176 * even if some file creation attempts on existing cgroups fail.
3178 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3185 if (!cfts || cfts[0].name[0] == '\0')
3188 ret = cgroup_init_cftypes(ss, cfts);
3192 mutex_lock(&cgroup_mutex);
3194 list_add_tail(&cfts->node, &ss->cfts);
3195 ret = cgroup_apply_cftypes(cfts, true);
3197 cgroup_rm_cftypes_locked(cfts);
3199 mutex_unlock(&cgroup_mutex);
3204 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3205 * @ss: target cgroup subsystem
3206 * @cfts: zero-length name terminated array of cftypes
3208 * Similar to cgroup_add_cftypes() but the added files are only used for
3209 * the default hierarchy.
3211 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3215 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3216 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3217 return cgroup_add_cftypes(ss, cfts);
3221 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3222 * @ss: target cgroup subsystem
3223 * @cfts: zero-length name terminated array of cftypes
3225 * Similar to cgroup_add_cftypes() but the added files are only used for
3226 * the legacy hierarchies.
3228 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3232 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3233 cft->flags |= __CFTYPE_NOT_ON_DFL;
3234 return cgroup_add_cftypes(ss, cfts);
3238 * cgroup_task_count - count the number of tasks in a cgroup.
3239 * @cgrp: the cgroup in question
3241 * Return the number of tasks in the cgroup.
3243 static int cgroup_task_count(const struct cgroup *cgrp)
3246 struct cgrp_cset_link *link;
3248 down_read(&css_set_rwsem);
3249 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3250 count += atomic_read(&link->cset->refcount);
3251 up_read(&css_set_rwsem);
3256 * css_next_child - find the next child of a given css
3257 * @pos: the current position (%NULL to initiate traversal)
3258 * @parent: css whose children to walk
3260 * This function returns the next child of @parent and should be called
3261 * under either cgroup_mutex or RCU read lock. The only requirement is
3262 * that @parent and @pos are accessible. The next sibling is guaranteed to
3263 * be returned regardless of their states.
3265 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3266 * css which finished ->css_online() is guaranteed to be visible in the
3267 * future iterations and will stay visible until the last reference is put.
3268 * A css which hasn't finished ->css_online() or already finished
3269 * ->css_offline() may show up during traversal. It's each subsystem's
3270 * responsibility to synchronize against on/offlining.
3272 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3273 struct cgroup_subsys_state *parent)
3275 struct cgroup_subsys_state *next;
3277 cgroup_assert_mutex_or_rcu_locked();
3280 * @pos could already have been unlinked from the sibling list.
3281 * Once a cgroup is removed, its ->sibling.next is no longer
3282 * updated when its next sibling changes. CSS_RELEASED is set when
3283 * @pos is taken off list, at which time its next pointer is valid,
3284 * and, as releases are serialized, the one pointed to by the next
3285 * pointer is guaranteed to not have started release yet. This
3286 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3287 * critical section, the one pointed to by its next pointer is
3288 * guaranteed to not have finished its RCU grace period even if we
3289 * have dropped rcu_read_lock() inbetween iterations.
3291 * If @pos has CSS_RELEASED set, its next pointer can't be
3292 * dereferenced; however, as each css is given a monotonically
3293 * increasing unique serial number and always appended to the
3294 * sibling list, the next one can be found by walking the parent's
3295 * children until the first css with higher serial number than
3296 * @pos's. While this path can be slower, it happens iff iteration
3297 * races against release and the race window is very small.
3300 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3301 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3302 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3304 list_for_each_entry_rcu(next, &parent->children, sibling)
3305 if (next->serial_nr > pos->serial_nr)
3310 * @next, if not pointing to the head, can be dereferenced and is
3313 if (&next->sibling != &parent->children)
3319 * css_next_descendant_pre - find the next descendant for pre-order walk
3320 * @pos: the current position (%NULL to initiate traversal)
3321 * @root: css whose descendants to walk
3323 * To be used by css_for_each_descendant_pre(). Find the next descendant
3324 * to visit for pre-order traversal of @root's descendants. @root is
3325 * included in the iteration and the first node to be visited.
3327 * While this function requires cgroup_mutex or RCU read locking, it
3328 * doesn't require the whole traversal to be contained in a single critical
3329 * section. This function will return the correct next descendant as long
3330 * as both @pos and @root are accessible and @pos is a descendant of @root.
3332 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3333 * css which finished ->css_online() is guaranteed to be visible in the
3334 * future iterations and will stay visible until the last reference is put.
3335 * A css which hasn't finished ->css_online() or already finished
3336 * ->css_offline() may show up during traversal. It's each subsystem's
3337 * responsibility to synchronize against on/offlining.
3339 struct cgroup_subsys_state *
3340 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3341 struct cgroup_subsys_state *root)
3343 struct cgroup_subsys_state *next;
3345 cgroup_assert_mutex_or_rcu_locked();
3347 /* if first iteration, visit @root */
3351 /* visit the first child if exists */
3352 next = css_next_child(NULL, pos);
3356 /* no child, visit my or the closest ancestor's next sibling */
3357 while (pos != root) {
3358 next = css_next_child(pos, pos->parent);
3368 * css_rightmost_descendant - return the rightmost descendant of a css
3369 * @pos: css of interest
3371 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3372 * is returned. This can be used during pre-order traversal to skip
3375 * While this function requires cgroup_mutex or RCU read locking, it
3376 * doesn't require the whole traversal to be contained in a single critical
3377 * section. This function will return the correct rightmost descendant as
3378 * long as @pos is accessible.
3380 struct cgroup_subsys_state *
3381 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3383 struct cgroup_subsys_state *last, *tmp;
3385 cgroup_assert_mutex_or_rcu_locked();
3389 /* ->prev isn't RCU safe, walk ->next till the end */
3391 css_for_each_child(tmp, last)
3398 static struct cgroup_subsys_state *
3399 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3401 struct cgroup_subsys_state *last;
3405 pos = css_next_child(NULL, pos);
3412 * css_next_descendant_post - find the next descendant for post-order walk
3413 * @pos: the current position (%NULL to initiate traversal)
3414 * @root: css whose descendants to walk
3416 * To be used by css_for_each_descendant_post(). Find the next descendant
3417 * to visit for post-order traversal of @root's descendants. @root is
3418 * included in the iteration and the last node to be visited.
3420 * While this function requires cgroup_mutex or RCU read locking, it
3421 * doesn't require the whole traversal to be contained in a single critical
3422 * section. This function will return the correct next descendant as long
3423 * as both @pos and @cgroup are accessible and @pos is a descendant of
3426 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3427 * css which finished ->css_online() is guaranteed to be visible in the
3428 * future iterations and will stay visible until the last reference is put.
3429 * A css which hasn't finished ->css_online() or already finished
3430 * ->css_offline() may show up during traversal. It's each subsystem's
3431 * responsibility to synchronize against on/offlining.
3433 struct cgroup_subsys_state *
3434 css_next_descendant_post(struct cgroup_subsys_state *pos,
3435 struct cgroup_subsys_state *root)
3437 struct cgroup_subsys_state *next;
3439 cgroup_assert_mutex_or_rcu_locked();
3441 /* if first iteration, visit leftmost descendant which may be @root */
3443 return css_leftmost_descendant(root);
3445 /* if we visited @root, we're done */
3449 /* if there's an unvisited sibling, visit its leftmost descendant */
3450 next = css_next_child(pos, pos->parent);
3452 return css_leftmost_descendant(next);
3454 /* no sibling left, visit parent */
3459 * css_has_online_children - does a css have online children
3460 * @css: the target css
3462 * Returns %true if @css has any online children; otherwise, %false. This
3463 * function can be called from any context but the caller is responsible
3464 * for synchronizing against on/offlining as necessary.
3466 bool css_has_online_children(struct cgroup_subsys_state *css)
3468 struct cgroup_subsys_state *child;
3472 css_for_each_child(child, css) {
3473 if (css->flags & CSS_ONLINE) {
3483 * css_advance_task_iter - advance a task itererator to the next css_set
3484 * @it: the iterator to advance
3486 * Advance @it to the next css_set to walk.
3488 static void css_advance_task_iter(struct css_task_iter *it)
3490 struct list_head *l = it->cset_pos;
3491 struct cgrp_cset_link *link;
3492 struct css_set *cset;
3494 /* Advance to the next non-empty css_set */
3497 if (l == it->cset_head) {
3498 it->cset_pos = NULL;
3503 cset = container_of(l, struct css_set,
3504 e_cset_node[it->ss->id]);
3506 link = list_entry(l, struct cgrp_cset_link, cset_link);
3509 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
3513 if (!list_empty(&cset->tasks))
3514 it->task_pos = cset->tasks.next;
3516 it->task_pos = cset->mg_tasks.next;
3518 it->tasks_head = &cset->tasks;
3519 it->mg_tasks_head = &cset->mg_tasks;
3523 * css_task_iter_start - initiate task iteration
3524 * @css: the css to walk tasks of
3525 * @it: the task iterator to use
3527 * Initiate iteration through the tasks of @css. The caller can call
3528 * css_task_iter_next() to walk through the tasks until the function
3529 * returns NULL. On completion of iteration, css_task_iter_end() must be
3532 * Note that this function acquires a lock which is released when the
3533 * iteration finishes. The caller can't sleep while iteration is in
3536 void css_task_iter_start(struct cgroup_subsys_state *css,
3537 struct css_task_iter *it)
3538 __acquires(css_set_rwsem)
3540 /* no one should try to iterate before mounting cgroups */
3541 WARN_ON_ONCE(!use_task_css_set_links);
3543 down_read(&css_set_rwsem);
3548 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3550 it->cset_pos = &css->cgroup->cset_links;
3552 it->cset_head = it->cset_pos;
3554 css_advance_task_iter(it);
3558 * css_task_iter_next - return the next task for the iterator
3559 * @it: the task iterator being iterated
3561 * The "next" function for task iteration. @it should have been
3562 * initialized via css_task_iter_start(). Returns NULL when the iteration
3565 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3567 struct task_struct *res;
3568 struct list_head *l = it->task_pos;
3570 /* If the iterator cg is NULL, we have no tasks */
3573 res = list_entry(l, struct task_struct, cg_list);
3576 * Advance iterator to find next entry. cset->tasks is consumed
3577 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3582 if (l == it->tasks_head)
3583 l = it->mg_tasks_head->next;
3585 if (l == it->mg_tasks_head)
3586 css_advance_task_iter(it);
3594 * css_task_iter_end - finish task iteration
3595 * @it: the task iterator to finish
3597 * Finish task iteration started by css_task_iter_start().
3599 void css_task_iter_end(struct css_task_iter *it)
3600 __releases(css_set_rwsem)
3602 up_read(&css_set_rwsem);
3606 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3607 * @to: cgroup to which the tasks will be moved
3608 * @from: cgroup in which the tasks currently reside
3610 * Locking rules between cgroup_post_fork() and the migration path
3611 * guarantee that, if a task is forking while being migrated, the new child
3612 * is guaranteed to be either visible in the source cgroup after the
3613 * parent's migration is complete or put into the target cgroup. No task
3614 * can slip out of migration through forking.
3616 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3618 LIST_HEAD(preloaded_csets);
3619 struct cgrp_cset_link *link;
3620 struct css_task_iter it;
3621 struct task_struct *task;
3624 mutex_lock(&cgroup_mutex);
3626 /* all tasks in @from are being moved, all csets are source */
3627 down_read(&css_set_rwsem);
3628 list_for_each_entry(link, &from->cset_links, cset_link)
3629 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
3630 up_read(&css_set_rwsem);
3632 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
3637 * Migrate tasks one-by-one until @form is empty. This fails iff
3638 * ->can_attach() fails.
3641 css_task_iter_start(&from->self, &it);
3642 task = css_task_iter_next(&it);
3644 get_task_struct(task);
3645 css_task_iter_end(&it);
3648 ret = cgroup_migrate(to, task, false);
3649 put_task_struct(task);
3651 } while (task && !ret);
3653 cgroup_migrate_finish(&preloaded_csets);
3654 mutex_unlock(&cgroup_mutex);
3659 * Stuff for reading the 'tasks'/'procs' files.
3661 * Reading this file can return large amounts of data if a cgroup has
3662 * *lots* of attached tasks. So it may need several calls to read(),
3663 * but we cannot guarantee that the information we produce is correct
3664 * unless we produce it entirely atomically.
3668 /* which pidlist file are we talking about? */
3669 enum cgroup_filetype {
3675 * A pidlist is a list of pids that virtually represents the contents of one
3676 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3677 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3680 struct cgroup_pidlist {
3682 * used to find which pidlist is wanted. doesn't change as long as
3683 * this particular list stays in the list.
3685 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3688 /* how many elements the above list has */
3690 /* each of these stored in a list by its cgroup */
3691 struct list_head links;
3692 /* pointer to the cgroup we belong to, for list removal purposes */
3693 struct cgroup *owner;
3694 /* for delayed destruction */
3695 struct delayed_work destroy_dwork;
3699 * The following two functions "fix" the issue where there are more pids
3700 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3701 * TODO: replace with a kernel-wide solution to this problem
3703 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3704 static void *pidlist_allocate(int count)
3706 if (PIDLIST_TOO_LARGE(count))
3707 return vmalloc(count * sizeof(pid_t));
3709 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3712 static void pidlist_free(void *p)
3714 if (is_vmalloc_addr(p))
3721 * Used to destroy all pidlists lingering waiting for destroy timer. None
3722 * should be left afterwards.
3724 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3726 struct cgroup_pidlist *l, *tmp_l;
3728 mutex_lock(&cgrp->pidlist_mutex);
3729 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3730 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3731 mutex_unlock(&cgrp->pidlist_mutex);
3733 flush_workqueue(cgroup_pidlist_destroy_wq);
3734 BUG_ON(!list_empty(&cgrp->pidlists));
3737 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3739 struct delayed_work *dwork = to_delayed_work(work);
3740 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3742 struct cgroup_pidlist *tofree = NULL;
3744 mutex_lock(&l->owner->pidlist_mutex);
3747 * Destroy iff we didn't get queued again. The state won't change
3748 * as destroy_dwork can only be queued while locked.
3750 if (!delayed_work_pending(dwork)) {
3751 list_del(&l->links);
3752 pidlist_free(l->list);
3753 put_pid_ns(l->key.ns);
3757 mutex_unlock(&l->owner->pidlist_mutex);
3762 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3763 * Returns the number of unique elements.
3765 static int pidlist_uniq(pid_t *list, int length)
3770 * we presume the 0th element is unique, so i starts at 1. trivial
3771 * edge cases first; no work needs to be done for either
3773 if (length == 0 || length == 1)
3775 /* src and dest walk down the list; dest counts unique elements */
3776 for (src = 1; src < length; src++) {
3777 /* find next unique element */
3778 while (list[src] == list[src-1]) {
3783 /* dest always points to where the next unique element goes */
3784 list[dest] = list[src];
3792 * The two pid files - task and cgroup.procs - guaranteed that the result
3793 * is sorted, which forced this whole pidlist fiasco. As pid order is
3794 * different per namespace, each namespace needs differently sorted list,
3795 * making it impossible to use, for example, single rbtree of member tasks
3796 * sorted by task pointer. As pidlists can be fairly large, allocating one
3797 * per open file is dangerous, so cgroup had to implement shared pool of
3798 * pidlists keyed by cgroup and namespace.
3800 * All this extra complexity was caused by the original implementation
3801 * committing to an entirely unnecessary property. In the long term, we
3802 * want to do away with it. Explicitly scramble sort order if on the
3803 * default hierarchy so that no such expectation exists in the new
3806 * Scrambling is done by swapping every two consecutive bits, which is
3807 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3809 static pid_t pid_fry(pid_t pid)
3811 unsigned a = pid & 0x55555555;
3812 unsigned b = pid & 0xAAAAAAAA;
3814 return (a << 1) | (b >> 1);
3817 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3819 if (cgroup_on_dfl(cgrp))
3820 return pid_fry(pid);
3825 static int cmppid(const void *a, const void *b)
3827 return *(pid_t *)a - *(pid_t *)b;
3830 static int fried_cmppid(const void *a, const void *b)
3832 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3835 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3836 enum cgroup_filetype type)
3838 struct cgroup_pidlist *l;
3839 /* don't need task_nsproxy() if we're looking at ourself */
3840 struct pid_namespace *ns = task_active_pid_ns(current);
3842 lockdep_assert_held(&cgrp->pidlist_mutex);
3844 list_for_each_entry(l, &cgrp->pidlists, links)
3845 if (l->key.type == type && l->key.ns == ns)
3851 * find the appropriate pidlist for our purpose (given procs vs tasks)
3852 * returns with the lock on that pidlist already held, and takes care
3853 * of the use count, or returns NULL with no locks held if we're out of
3856 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3857 enum cgroup_filetype type)
3859 struct cgroup_pidlist *l;
3861 lockdep_assert_held(&cgrp->pidlist_mutex);
3863 l = cgroup_pidlist_find(cgrp, type);
3867 /* entry not found; create a new one */
3868 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3872 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3874 /* don't need task_nsproxy() if we're looking at ourself */
3875 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3877 list_add(&l->links, &cgrp->pidlists);
3882 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3884 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3885 struct cgroup_pidlist **lp)
3889 int pid, n = 0; /* used for populating the array */
3890 struct css_task_iter it;
3891 struct task_struct *tsk;
3892 struct cgroup_pidlist *l;
3894 lockdep_assert_held(&cgrp->pidlist_mutex);
3897 * If cgroup gets more users after we read count, we won't have
3898 * enough space - tough. This race is indistinguishable to the
3899 * caller from the case that the additional cgroup users didn't
3900 * show up until sometime later on.
3902 length = cgroup_task_count(cgrp);
3903 array = pidlist_allocate(length);
3906 /* now, populate the array */
3907 css_task_iter_start(&cgrp->self, &it);
3908 while ((tsk = css_task_iter_next(&it))) {
3909 if (unlikely(n == length))
3911 /* get tgid or pid for procs or tasks file respectively */
3912 if (type == CGROUP_FILE_PROCS)
3913 pid = task_tgid_vnr(tsk);
3915 pid = task_pid_vnr(tsk);
3916 if (pid > 0) /* make sure to only use valid results */
3919 css_task_iter_end(&it);
3921 /* now sort & (if procs) strip out duplicates */
3922 if (cgroup_on_dfl(cgrp))
3923 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3925 sort(array, length, sizeof(pid_t), cmppid, NULL);
3926 if (type == CGROUP_FILE_PROCS)
3927 length = pidlist_uniq(array, length);
3929 l = cgroup_pidlist_find_create(cgrp, type);
3931 mutex_unlock(&cgrp->pidlist_mutex);
3932 pidlist_free(array);
3936 /* store array, freeing old if necessary */
3937 pidlist_free(l->list);
3945 * cgroupstats_build - build and fill cgroupstats
3946 * @stats: cgroupstats to fill information into
3947 * @dentry: A dentry entry belonging to the cgroup for which stats have
3950 * Build and fill cgroupstats so that taskstats can export it to user
3953 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3955 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3956 struct cgroup *cgrp;
3957 struct css_task_iter it;
3958 struct task_struct *tsk;
3960 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3961 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3962 kernfs_type(kn) != KERNFS_DIR)
3965 mutex_lock(&cgroup_mutex);
3968 * We aren't being called from kernfs and there's no guarantee on
3969 * @kn->priv's validity. For this and css_tryget_online_from_dir(),
3970 * @kn->priv is RCU safe. Let's do the RCU dancing.
3973 cgrp = rcu_dereference(kn->priv);
3974 if (!cgrp || cgroup_is_dead(cgrp)) {
3976 mutex_unlock(&cgroup_mutex);
3981 css_task_iter_start(&cgrp->self, &it);
3982 while ((tsk = css_task_iter_next(&it))) {
3983 switch (tsk->state) {
3985 stats->nr_running++;
3987 case TASK_INTERRUPTIBLE:
3988 stats->nr_sleeping++;
3990 case TASK_UNINTERRUPTIBLE:
3991 stats->nr_uninterruptible++;
3994 stats->nr_stopped++;
3997 if (delayacct_is_task_waiting_on_io(tsk))
3998 stats->nr_io_wait++;
4002 css_task_iter_end(&it);
4004 mutex_unlock(&cgroup_mutex);
4010 * seq_file methods for the tasks/procs files. The seq_file position is the
4011 * next pid to display; the seq_file iterator is a pointer to the pid
4012 * in the cgroup->l->list array.
4015 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
4018 * Initially we receive a position value that corresponds to
4019 * one more than the last pid shown (or 0 on the first call or
4020 * after a seek to the start). Use a binary-search to find the
4021 * next pid to display, if any
4023 struct kernfs_open_file *of = s->private;
4024 struct cgroup *cgrp = seq_css(s)->cgroup;
4025 struct cgroup_pidlist *l;
4026 enum cgroup_filetype type = seq_cft(s)->private;
4027 int index = 0, pid = *pos;
4030 mutex_lock(&cgrp->pidlist_mutex);
4033 * !NULL @of->priv indicates that this isn't the first start()
4034 * after open. If the matching pidlist is around, we can use that.
4035 * Look for it. Note that @of->priv can't be used directly. It
4036 * could already have been destroyed.
4039 of->priv = cgroup_pidlist_find(cgrp, type);
4042 * Either this is the first start() after open or the matching
4043 * pidlist has been destroyed inbetween. Create a new one.
4046 ret = pidlist_array_load(cgrp, type,
4047 (struct cgroup_pidlist **)&of->priv);
4049 return ERR_PTR(ret);
4054 int end = l->length;
4056 while (index < end) {
4057 int mid = (index + end) / 2;
4058 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
4061 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
4067 /* If we're off the end of the array, we're done */
4068 if (index >= l->length)
4070 /* Update the abstract position to be the actual pid that we found */
4071 iter = l->list + index;
4072 *pos = cgroup_pid_fry(cgrp, *iter);
4076 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
4078 struct kernfs_open_file *of = s->private;
4079 struct cgroup_pidlist *l = of->priv;
4082 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
4083 CGROUP_PIDLIST_DESTROY_DELAY);
4084 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
4087 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
4089 struct kernfs_open_file *of = s->private;
4090 struct cgroup_pidlist *l = of->priv;
4092 pid_t *end = l->list + l->length;
4094 * Advance to the next pid in the array. If this goes off the
4101 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
4106 static int cgroup_pidlist_show(struct seq_file *s, void *v)
4108 return seq_printf(s, "%d\n", *(int *)v);
4111 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
4114 return notify_on_release(css->cgroup);
4117 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
4118 struct cftype *cft, u64 val)
4120 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
4122 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
4124 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
4128 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
4131 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4134 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
4135 struct cftype *cft, u64 val)
4138 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4140 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4144 /* cgroup core interface files for the default hierarchy */
4145 static struct cftype cgroup_dfl_base_files[] = {
4147 .name = "cgroup.procs",
4148 .seq_start = cgroup_pidlist_start,
4149 .seq_next = cgroup_pidlist_next,
4150 .seq_stop = cgroup_pidlist_stop,
4151 .seq_show = cgroup_pidlist_show,
4152 .private = CGROUP_FILE_PROCS,
4153 .write = cgroup_procs_write,
4154 .mode = S_IRUGO | S_IWUSR,
4157 .name = "cgroup.controllers",
4158 .flags = CFTYPE_ONLY_ON_ROOT,
4159 .seq_show = cgroup_root_controllers_show,
4162 .name = "cgroup.controllers",
4163 .flags = CFTYPE_NOT_ON_ROOT,
4164 .seq_show = cgroup_controllers_show,
4167 .name = "cgroup.subtree_control",
4168 .seq_show = cgroup_subtree_control_show,
4169 .write = cgroup_subtree_control_write,
4172 .name = "cgroup.populated",
4173 .flags = CFTYPE_NOT_ON_ROOT,
4174 .seq_show = cgroup_populated_show,
4179 /* cgroup core interface files for the legacy hierarchies */
4180 static struct cftype cgroup_legacy_base_files[] = {
4182 .name = "cgroup.procs",
4183 .seq_start = cgroup_pidlist_start,
4184 .seq_next = cgroup_pidlist_next,
4185 .seq_stop = cgroup_pidlist_stop,
4186 .seq_show = cgroup_pidlist_show,
4187 .private = CGROUP_FILE_PROCS,
4188 .write = cgroup_procs_write,
4189 .mode = S_IRUGO | S_IWUSR,
4192 .name = "cgroup.clone_children",
4193 .read_u64 = cgroup_clone_children_read,
4194 .write_u64 = cgroup_clone_children_write,
4197 .name = "cgroup.sane_behavior",
4198 .flags = CFTYPE_ONLY_ON_ROOT,
4199 .seq_show = cgroup_sane_behavior_show,
4203 .seq_start = cgroup_pidlist_start,
4204 .seq_next = cgroup_pidlist_next,
4205 .seq_stop = cgroup_pidlist_stop,
4206 .seq_show = cgroup_pidlist_show,
4207 .private = CGROUP_FILE_TASKS,
4208 .write = cgroup_tasks_write,
4209 .mode = S_IRUGO | S_IWUSR,
4212 .name = "notify_on_release",
4213 .read_u64 = cgroup_read_notify_on_release,
4214 .write_u64 = cgroup_write_notify_on_release,
4217 .name = "release_agent",
4218 .flags = CFTYPE_ONLY_ON_ROOT,
4219 .seq_show = cgroup_release_agent_show,
4220 .write = cgroup_release_agent_write,
4221 .max_write_len = PATH_MAX - 1,
4227 * cgroup_populate_dir - create subsys files in a cgroup directory
4228 * @cgrp: target cgroup
4229 * @subsys_mask: mask of the subsystem ids whose files should be added
4231 * On failure, no file is added.
4233 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask)
4235 struct cgroup_subsys *ss;
4238 /* process cftsets of each subsystem */
4239 for_each_subsys(ss, i) {
4240 struct cftype *cfts;
4242 if (!(subsys_mask & (1 << i)))
4245 list_for_each_entry(cfts, &ss->cfts, node) {
4246 ret = cgroup_addrm_files(cgrp, cfts, true);
4253 cgroup_clear_dir(cgrp, subsys_mask);
4258 * css destruction is four-stage process.
4260 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4261 * Implemented in kill_css().
4263 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4264 * and thus css_tryget_online() is guaranteed to fail, the css can be
4265 * offlined by invoking offline_css(). After offlining, the base ref is
4266 * put. Implemented in css_killed_work_fn().
4268 * 3. When the percpu_ref reaches zero, the only possible remaining
4269 * accessors are inside RCU read sections. css_release() schedules the
4272 * 4. After the grace period, the css can be freed. Implemented in
4273 * css_free_work_fn().
4275 * It is actually hairier because both step 2 and 4 require process context
4276 * and thus involve punting to css->destroy_work adding two additional
4277 * steps to the already complex sequence.
4279 static void css_free_work_fn(struct work_struct *work)
4281 struct cgroup_subsys_state *css =
4282 container_of(work, struct cgroup_subsys_state, destroy_work);
4283 struct cgroup *cgrp = css->cgroup;
4288 css_put(css->parent);
4290 css->ss->css_free(css);
4293 /* cgroup free path */
4294 atomic_dec(&cgrp->root->nr_cgrps);
4295 cgroup_pidlist_destroy_all(cgrp);
4297 if (cgroup_parent(cgrp)) {
4299 * We get a ref to the parent, and put the ref when
4300 * this cgroup is being freed, so it's guaranteed
4301 * that the parent won't be destroyed before its
4304 cgroup_put(cgroup_parent(cgrp));
4305 kernfs_put(cgrp->kn);
4309 * This is root cgroup's refcnt reaching zero,
4310 * which indicates that the root should be
4313 cgroup_destroy_root(cgrp->root);
4318 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4320 struct cgroup_subsys_state *css =
4321 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4323 INIT_WORK(&css->destroy_work, css_free_work_fn);
4324 queue_work(cgroup_destroy_wq, &css->destroy_work);
4327 static void css_release_work_fn(struct work_struct *work)
4329 struct cgroup_subsys_state *css =
4330 container_of(work, struct cgroup_subsys_state, destroy_work);
4331 struct cgroup_subsys *ss = css->ss;
4332 struct cgroup *cgrp = css->cgroup;
4334 mutex_lock(&cgroup_mutex);
4336 css->flags |= CSS_RELEASED;
4337 list_del_rcu(&css->sibling);
4340 /* css release path */
4341 cgroup_idr_remove(&ss->css_idr, css->id);
4343 /* cgroup release path */
4344 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4348 mutex_unlock(&cgroup_mutex);
4350 call_rcu(&css->rcu_head, css_free_rcu_fn);
4353 static void css_release(struct percpu_ref *ref)
4355 struct cgroup_subsys_state *css =
4356 container_of(ref, struct cgroup_subsys_state, refcnt);
4358 INIT_WORK(&css->destroy_work, css_release_work_fn);
4359 queue_work(cgroup_destroy_wq, &css->destroy_work);
4362 static void init_and_link_css(struct cgroup_subsys_state *css,
4363 struct cgroup_subsys *ss, struct cgroup *cgrp)
4365 lockdep_assert_held(&cgroup_mutex);
4369 memset(css, 0, sizeof(*css));
4372 INIT_LIST_HEAD(&css->sibling);
4373 INIT_LIST_HEAD(&css->children);
4374 css->serial_nr = css_serial_nr_next++;
4376 if (cgroup_parent(cgrp)) {
4377 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4378 css_get(css->parent);
4381 BUG_ON(cgroup_css(cgrp, ss));
4384 /* invoke ->css_online() on a new CSS and mark it online if successful */
4385 static int online_css(struct cgroup_subsys_state *css)
4387 struct cgroup_subsys *ss = css->ss;
4390 lockdep_assert_held(&cgroup_mutex);
4393 ret = ss->css_online(css);
4395 css->flags |= CSS_ONLINE;
4396 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4401 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4402 static void offline_css(struct cgroup_subsys_state *css)
4404 struct cgroup_subsys *ss = css->ss;
4406 lockdep_assert_held(&cgroup_mutex);
4408 if (!(css->flags & CSS_ONLINE))
4411 if (ss->css_offline)
4412 ss->css_offline(css);
4414 css->flags &= ~CSS_ONLINE;
4415 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4417 wake_up_all(&css->cgroup->offline_waitq);
4421 * create_css - create a cgroup_subsys_state
4422 * @cgrp: the cgroup new css will be associated with
4423 * @ss: the subsys of new css
4424 * @visible: whether to create control knobs for the new css or not
4426 * Create a new css associated with @cgrp - @ss pair. On success, the new
4427 * css is online and installed in @cgrp with all interface files created if
4428 * @visible. Returns 0 on success, -errno on failure.
4430 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss,
4433 struct cgroup *parent = cgroup_parent(cgrp);
4434 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4435 struct cgroup_subsys_state *css;
4438 lockdep_assert_held(&cgroup_mutex);
4440 css = ss->css_alloc(parent_css);
4442 return PTR_ERR(css);
4444 init_and_link_css(css, ss, cgrp);
4446 err = percpu_ref_init(&css->refcnt, css_release);
4450 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_NOWAIT);
4452 goto err_free_percpu_ref;
4456 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4461 /* @css is ready to be brought online now, make it visible */
4462 list_add_tail_rcu(&css->sibling, &parent_css->children);
4463 cgroup_idr_replace(&ss->css_idr, css, css->id);
4465 err = online_css(css);
4469 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4470 cgroup_parent(parent)) {
4471 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4472 current->comm, current->pid, ss->name);
4473 if (!strcmp(ss->name, "memory"))
4474 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4475 ss->warned_broken_hierarchy = true;
4481 list_del_rcu(&css->sibling);
4482 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4484 cgroup_idr_remove(&ss->css_idr, css->id);
4485 err_free_percpu_ref:
4486 percpu_ref_cancel_init(&css->refcnt);
4488 call_rcu(&css->rcu_head, css_free_rcu_fn);
4492 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4495 struct cgroup *parent, *cgrp;
4496 struct cgroup_root *root;
4497 struct cgroup_subsys *ss;
4498 struct kernfs_node *kn;
4499 struct cftype *base_files;
4502 parent = cgroup_kn_lock_live(parent_kn);
4505 root = parent->root;
4507 /* allocate the cgroup and its ID, 0 is reserved for the root */
4508 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4514 ret = percpu_ref_init(&cgrp->self.refcnt, css_release);
4519 * Temporarily set the pointer to NULL, so idr_find() won't return
4520 * a half-baked cgroup.
4522 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_NOWAIT);
4525 goto out_cancel_ref;
4528 init_cgroup_housekeeping(cgrp);
4530 cgrp->self.parent = &parent->self;
4533 if (notify_on_release(parent))
4534 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4536 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4537 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4539 /* create the directory */
4540 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4548 * This extra ref will be put in cgroup_free_fn() and guarantees
4549 * that @cgrp->kn is always accessible.
4553 cgrp->self.serial_nr = css_serial_nr_next++;
4555 /* allocation complete, commit to creation */
4556 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4557 atomic_inc(&root->nr_cgrps);
4561 * @cgrp is now fully operational. If something fails after this
4562 * point, it'll be released via the normal destruction path.
4564 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4566 ret = cgroup_kn_set_ugid(kn);
4570 if (cgroup_on_dfl(cgrp))
4571 base_files = cgroup_dfl_base_files;
4573 base_files = cgroup_legacy_base_files;
4575 ret = cgroup_addrm_files(cgrp, base_files, true);
4579 /* let's create and online css's */
4580 for_each_subsys(ss, ssid) {
4581 if (parent->child_subsys_mask & (1 << ssid)) {
4582 ret = create_css(cgrp, ss,
4583 parent->subtree_control & (1 << ssid));
4590 * On the default hierarchy, a child doesn't automatically inherit
4591 * subtree_control from the parent. Each is configured manually.
4593 if (!cgroup_on_dfl(cgrp)) {
4594 cgrp->subtree_control = parent->subtree_control;
4595 cgroup_refresh_child_subsys_mask(cgrp);
4598 kernfs_activate(kn);
4604 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4606 percpu_ref_cancel_init(&cgrp->self.refcnt);
4610 cgroup_kn_unlock(parent_kn);
4614 cgroup_destroy_locked(cgrp);
4619 * This is called when the refcnt of a css is confirmed to be killed.
4620 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
4621 * initate destruction and put the css ref from kill_css().
4623 static void css_killed_work_fn(struct work_struct *work)
4625 struct cgroup_subsys_state *css =
4626 container_of(work, struct cgroup_subsys_state, destroy_work);
4628 mutex_lock(&cgroup_mutex);
4630 mutex_unlock(&cgroup_mutex);
4635 /* css kill confirmation processing requires process context, bounce */
4636 static void css_killed_ref_fn(struct percpu_ref *ref)
4638 struct cgroup_subsys_state *css =
4639 container_of(ref, struct cgroup_subsys_state, refcnt);
4641 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4642 queue_work(cgroup_destroy_wq, &css->destroy_work);
4646 * kill_css - destroy a css
4647 * @css: css to destroy
4649 * This function initiates destruction of @css by removing cgroup interface
4650 * files and putting its base reference. ->css_offline() will be invoked
4651 * asynchronously once css_tryget_online() is guaranteed to fail and when
4652 * the reference count reaches zero, @css will be released.
4654 static void kill_css(struct cgroup_subsys_state *css)
4656 lockdep_assert_held(&cgroup_mutex);
4659 * This must happen before css is disassociated with its cgroup.
4660 * See seq_css() for details.
4662 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4665 * Killing would put the base ref, but we need to keep it alive
4666 * until after ->css_offline().
4671 * cgroup core guarantees that, by the time ->css_offline() is
4672 * invoked, no new css reference will be given out via
4673 * css_tryget_online(). We can't simply call percpu_ref_kill() and
4674 * proceed to offlining css's because percpu_ref_kill() doesn't
4675 * guarantee that the ref is seen as killed on all CPUs on return.
4677 * Use percpu_ref_kill_and_confirm() to get notifications as each
4678 * css is confirmed to be seen as killed on all CPUs.
4680 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4684 * cgroup_destroy_locked - the first stage of cgroup destruction
4685 * @cgrp: cgroup to be destroyed
4687 * css's make use of percpu refcnts whose killing latency shouldn't be
4688 * exposed to userland and are RCU protected. Also, cgroup core needs to
4689 * guarantee that css_tryget_online() won't succeed by the time
4690 * ->css_offline() is invoked. To satisfy all the requirements,
4691 * destruction is implemented in the following two steps.
4693 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4694 * userland visible parts and start killing the percpu refcnts of
4695 * css's. Set up so that the next stage will be kicked off once all
4696 * the percpu refcnts are confirmed to be killed.
4698 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4699 * rest of destruction. Once all cgroup references are gone, the
4700 * cgroup is RCU-freed.
4702 * This function implements s1. After this step, @cgrp is gone as far as
4703 * the userland is concerned and a new cgroup with the same name may be
4704 * created. As cgroup doesn't care about the names internally, this
4705 * doesn't cause any problem.
4707 static int cgroup_destroy_locked(struct cgroup *cgrp)
4708 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4710 struct cgroup_subsys_state *css;
4714 lockdep_assert_held(&cgroup_mutex);
4717 * css_set_rwsem synchronizes access to ->cset_links and prevents
4718 * @cgrp from being removed while put_css_set() is in progress.
4720 down_read(&css_set_rwsem);
4721 empty = list_empty(&cgrp->cset_links);
4722 up_read(&css_set_rwsem);
4727 * Make sure there's no live children. We can't test emptiness of
4728 * ->self.children as dead children linger on it while being
4729 * drained; otherwise, "rmdir parent/child parent" may fail.
4731 if (css_has_online_children(&cgrp->self))
4735 * Mark @cgrp dead. This prevents further task migration and child
4736 * creation by disabling cgroup_lock_live_group().
4738 cgrp->self.flags &= ~CSS_ONLINE;
4740 /* initiate massacre of all css's */
4741 for_each_css(css, ssid, cgrp)
4744 /* CSS_ONLINE is clear, remove from ->release_list for the last time */
4745 raw_spin_lock(&release_list_lock);
4746 if (!list_empty(&cgrp->release_list))
4747 list_del_init(&cgrp->release_list);
4748 raw_spin_unlock(&release_list_lock);
4751 * Remove @cgrp directory along with the base files. @cgrp has an
4752 * extra ref on its kn.
4754 kernfs_remove(cgrp->kn);
4756 set_bit(CGRP_RELEASABLE, &cgroup_parent(cgrp)->flags);
4757 check_for_release(cgroup_parent(cgrp));
4759 /* put the base reference */
4760 percpu_ref_kill(&cgrp->self.refcnt);
4765 static int cgroup_rmdir(struct kernfs_node *kn)
4767 struct cgroup *cgrp;
4770 cgrp = cgroup_kn_lock_live(kn);
4773 cgroup_get(cgrp); /* for @kn->priv clearing */
4775 ret = cgroup_destroy_locked(cgrp);
4777 cgroup_kn_unlock(kn);
4780 * There are two control paths which try to determine cgroup from
4781 * dentry without going through kernfs - cgroupstats_build() and
4782 * css_tryget_online_from_dir(). Those are supported by RCU
4783 * protecting clearing of cgrp->kn->priv backpointer, which should
4784 * happen after all files under it have been removed.
4787 RCU_INIT_POINTER(*(void __rcu __force **)&kn->priv, NULL);
4793 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4794 .remount_fs = cgroup_remount,
4795 .show_options = cgroup_show_options,
4796 .mkdir = cgroup_mkdir,
4797 .rmdir = cgroup_rmdir,
4798 .rename = cgroup_rename,
4801 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
4803 struct cgroup_subsys_state *css;
4805 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4807 mutex_lock(&cgroup_mutex);
4809 idr_init(&ss->css_idr);
4810 INIT_LIST_HEAD(&ss->cfts);
4812 /* Create the root cgroup state for this subsystem */
4813 ss->root = &cgrp_dfl_root;
4814 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
4815 /* We don't handle early failures gracefully */
4816 BUG_ON(IS_ERR(css));
4817 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
4820 * Root csses are never destroyed and we can't initialize
4821 * percpu_ref during early init. Disable refcnting.
4823 css->flags |= CSS_NO_REF;
4826 /* allocation can't be done safely during early init */
4829 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
4830 BUG_ON(css->id < 0);
4833 /* Update the init_css_set to contain a subsys
4834 * pointer to this state - since the subsystem is
4835 * newly registered, all tasks and hence the
4836 * init_css_set is in the subsystem's root cgroup. */
4837 init_css_set.subsys[ss->id] = css;
4839 need_forkexit_callback |= ss->fork || ss->exit;
4841 /* At system boot, before all subsystems have been
4842 * registered, no tasks have been forked, so we don't
4843 * need to invoke fork callbacks here. */
4844 BUG_ON(!list_empty(&init_task.tasks));
4846 BUG_ON(online_css(css));
4848 mutex_unlock(&cgroup_mutex);
4852 * cgroup_init_early - cgroup initialization at system boot
4854 * Initialize cgroups at system boot, and initialize any
4855 * subsystems that request early init.
4857 int __init cgroup_init_early(void)
4859 static struct cgroup_sb_opts __initdata opts;
4860 struct cgroup_subsys *ss;
4863 init_cgroup_root(&cgrp_dfl_root, &opts);
4864 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
4866 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4868 for_each_subsys(ss, i) {
4869 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4870 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4871 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4873 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4874 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4877 ss->name = cgroup_subsys_name[i];
4880 cgroup_init_subsys(ss, true);
4886 * cgroup_init - cgroup initialization
4888 * Register cgroup filesystem and /proc file, and initialize
4889 * any subsystems that didn't request early init.
4891 int __init cgroup_init(void)
4893 struct cgroup_subsys *ss;
4897 BUG_ON(cgroup_init_cftypes(NULL, cgroup_dfl_base_files));
4898 BUG_ON(cgroup_init_cftypes(NULL, cgroup_legacy_base_files));
4900 mutex_lock(&cgroup_mutex);
4902 /* Add init_css_set to the hash table */
4903 key = css_set_hash(init_css_set.subsys);
4904 hash_add(css_set_table, &init_css_set.hlist, key);
4906 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
4908 mutex_unlock(&cgroup_mutex);
4910 for_each_subsys(ss, ssid) {
4911 if (ss->early_init) {
4912 struct cgroup_subsys_state *css =
4913 init_css_set.subsys[ss->id];
4915 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
4917 BUG_ON(css->id < 0);
4919 cgroup_init_subsys(ss, false);
4922 list_add_tail(&init_css_set.e_cset_node[ssid],
4923 &cgrp_dfl_root.cgrp.e_csets[ssid]);
4926 * Setting dfl_root subsys_mask needs to consider the
4927 * disabled flag and cftype registration needs kmalloc,
4928 * both of which aren't available during early_init.
4933 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
4935 if (cgroup_legacy_files_on_dfl && !ss->dfl_cftypes)
4936 ss->dfl_cftypes = ss->legacy_cftypes;
4938 if (!ss->dfl_cftypes)
4939 cgrp_dfl_root_inhibit_ss_mask |= 1 << ss->id;
4941 if (ss->dfl_cftypes == ss->legacy_cftypes) {
4942 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
4944 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
4945 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
4949 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4953 err = register_filesystem(&cgroup_fs_type);
4955 kobject_put(cgroup_kobj);
4959 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4963 static int __init cgroup_wq_init(void)
4966 * There isn't much point in executing destruction path in
4967 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4968 * Use 1 for @max_active.
4970 * We would prefer to do this in cgroup_init() above, but that
4971 * is called before init_workqueues(): so leave this until after.
4973 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4974 BUG_ON(!cgroup_destroy_wq);
4977 * Used to destroy pidlists and separate to serve as flush domain.
4978 * Cap @max_active to 1 too.
4980 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4982 BUG_ON(!cgroup_pidlist_destroy_wq);
4986 core_initcall(cgroup_wq_init);
4989 * proc_cgroup_show()
4990 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4991 * - Used for /proc/<pid>/cgroup.
4994 /* TODO: Use a proper seq_file iterator */
4995 int proc_cgroup_show(struct seq_file *m, void *v)
4998 struct task_struct *tsk;
5001 struct cgroup_root *root;
5004 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5010 tsk = get_pid_task(pid, PIDTYPE_PID);
5016 mutex_lock(&cgroup_mutex);
5017 down_read(&css_set_rwsem);
5019 for_each_root(root) {
5020 struct cgroup_subsys *ss;
5021 struct cgroup *cgrp;
5022 int ssid, count = 0;
5024 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
5027 seq_printf(m, "%d:", root->hierarchy_id);
5028 for_each_subsys(ss, ssid)
5029 if (root->subsys_mask & (1 << ssid))
5030 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
5031 if (strlen(root->name))
5032 seq_printf(m, "%sname=%s", count ? "," : "",
5035 cgrp = task_cgroup_from_root(tsk, root);
5036 path = cgroup_path(cgrp, buf, PATH_MAX);
5038 retval = -ENAMETOOLONG;
5046 up_read(&css_set_rwsem);
5047 mutex_unlock(&cgroup_mutex);
5048 put_task_struct(tsk);
5055 /* Display information about each subsystem and each hierarchy */
5056 static int proc_cgroupstats_show(struct seq_file *m, void *v)
5058 struct cgroup_subsys *ss;
5061 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
5063 * ideally we don't want subsystems moving around while we do this.
5064 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
5065 * subsys/hierarchy state.
5067 mutex_lock(&cgroup_mutex);
5069 for_each_subsys(ss, i)
5070 seq_printf(m, "%s\t%d\t%d\t%d\n",
5071 ss->name, ss->root->hierarchy_id,
5072 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
5074 mutex_unlock(&cgroup_mutex);
5078 static int cgroupstats_open(struct inode *inode, struct file *file)
5080 return single_open(file, proc_cgroupstats_show, NULL);
5083 static const struct file_operations proc_cgroupstats_operations = {
5084 .open = cgroupstats_open,
5086 .llseek = seq_lseek,
5087 .release = single_release,
5091 * cgroup_fork - initialize cgroup related fields during copy_process()
5092 * @child: pointer to task_struct of forking parent process.
5094 * A task is associated with the init_css_set until cgroup_post_fork()
5095 * attaches it to the parent's css_set. Empty cg_list indicates that
5096 * @child isn't holding reference to its css_set.
5098 void cgroup_fork(struct task_struct *child)
5100 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5101 INIT_LIST_HEAD(&child->cg_list);
5105 * cgroup_post_fork - called on a new task after adding it to the task list
5106 * @child: the task in question
5108 * Adds the task to the list running through its css_set if necessary and
5109 * call the subsystem fork() callbacks. Has to be after the task is
5110 * visible on the task list in case we race with the first call to
5111 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5114 void cgroup_post_fork(struct task_struct *child)
5116 struct cgroup_subsys *ss;
5120 * This may race against cgroup_enable_task_cg_links(). As that
5121 * function sets use_task_css_set_links before grabbing
5122 * tasklist_lock and we just went through tasklist_lock to add
5123 * @child, it's guaranteed that either we see the set
5124 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5125 * @child during its iteration.
5127 * If we won the race, @child is associated with %current's
5128 * css_set. Grabbing css_set_rwsem guarantees both that the
5129 * association is stable, and, on completion of the parent's
5130 * migration, @child is visible in the source of migration or
5131 * already in the destination cgroup. This guarantee is necessary
5132 * when implementing operations which need to migrate all tasks of
5133 * a cgroup to another.
5135 * Note that if we lose to cgroup_enable_task_cg_links(), @child
5136 * will remain in init_css_set. This is safe because all tasks are
5137 * in the init_css_set before cg_links is enabled and there's no
5138 * operation which transfers all tasks out of init_css_set.
5140 if (use_task_css_set_links) {
5141 struct css_set *cset;
5143 down_write(&css_set_rwsem);
5144 cset = task_css_set(current);
5145 if (list_empty(&child->cg_list)) {
5146 rcu_assign_pointer(child->cgroups, cset);
5147 list_add(&child->cg_list, &cset->tasks);
5150 up_write(&css_set_rwsem);
5154 * Call ss->fork(). This must happen after @child is linked on
5155 * css_set; otherwise, @child might change state between ->fork()
5156 * and addition to css_set.
5158 if (need_forkexit_callback) {
5159 for_each_subsys(ss, i)
5166 * cgroup_exit - detach cgroup from exiting task
5167 * @tsk: pointer to task_struct of exiting process
5169 * Description: Detach cgroup from @tsk and release it.
5171 * Note that cgroups marked notify_on_release force every task in
5172 * them to take the global cgroup_mutex mutex when exiting.
5173 * This could impact scaling on very large systems. Be reluctant to
5174 * use notify_on_release cgroups where very high task exit scaling
5175 * is required on large systems.
5177 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5178 * call cgroup_exit() while the task is still competent to handle
5179 * notify_on_release(), then leave the task attached to the root cgroup in
5180 * each hierarchy for the remainder of its exit. No need to bother with
5181 * init_css_set refcnting. init_css_set never goes away and we can't race
5182 * with migration path - PF_EXITING is visible to migration path.
5184 void cgroup_exit(struct task_struct *tsk)
5186 struct cgroup_subsys *ss;
5187 struct css_set *cset;
5188 bool put_cset = false;
5192 * Unlink from @tsk from its css_set. As migration path can't race
5193 * with us, we can check cg_list without grabbing css_set_rwsem.
5195 if (!list_empty(&tsk->cg_list)) {
5196 down_write(&css_set_rwsem);
5197 list_del_init(&tsk->cg_list);
5198 up_write(&css_set_rwsem);
5202 /* Reassign the task to the init_css_set. */
5203 cset = task_css_set(tsk);
5204 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5206 if (need_forkexit_callback) {
5207 /* see cgroup_post_fork() for details */
5208 for_each_subsys(ss, i) {
5210 struct cgroup_subsys_state *old_css = cset->subsys[i];
5211 struct cgroup_subsys_state *css = task_css(tsk, i);
5213 ss->exit(css, old_css, tsk);
5219 put_css_set(cset, true);
5222 static void check_for_release(struct cgroup *cgrp)
5224 if (cgroup_is_releasable(cgrp) && list_empty(&cgrp->cset_links) &&
5225 !css_has_online_children(&cgrp->self)) {
5227 * Control Group is currently removeable. If it's not
5228 * already queued for a userspace notification, queue
5231 int need_schedule_work = 0;
5233 raw_spin_lock(&release_list_lock);
5234 if (!cgroup_is_dead(cgrp) &&
5235 list_empty(&cgrp->release_list)) {
5236 list_add(&cgrp->release_list, &release_list);
5237 need_schedule_work = 1;
5239 raw_spin_unlock(&release_list_lock);
5240 if (need_schedule_work)
5241 schedule_work(&release_agent_work);
5246 * Notify userspace when a cgroup is released, by running the
5247 * configured release agent with the name of the cgroup (path
5248 * relative to the root of cgroup file system) as the argument.
5250 * Most likely, this user command will try to rmdir this cgroup.
5252 * This races with the possibility that some other task will be
5253 * attached to this cgroup before it is removed, or that some other
5254 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5255 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5256 * unused, and this cgroup will be reprieved from its death sentence,
5257 * to continue to serve a useful existence. Next time it's released,
5258 * we will get notified again, if it still has 'notify_on_release' set.
5260 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5261 * means only wait until the task is successfully execve()'d. The
5262 * separate release agent task is forked by call_usermodehelper(),
5263 * then control in this thread returns here, without waiting for the
5264 * release agent task. We don't bother to wait because the caller of
5265 * this routine has no use for the exit status of the release agent
5266 * task, so no sense holding our caller up for that.
5268 static void cgroup_release_agent(struct work_struct *work)
5270 BUG_ON(work != &release_agent_work);
5271 mutex_lock(&cgroup_mutex);
5272 raw_spin_lock(&release_list_lock);
5273 while (!list_empty(&release_list)) {
5274 char *argv[3], *envp[3];
5276 char *pathbuf = NULL, *agentbuf = NULL, *path;
5277 struct cgroup *cgrp = list_entry(release_list.next,
5280 list_del_init(&cgrp->release_list);
5281 raw_spin_unlock(&release_list_lock);
5282 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5285 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5288 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5293 argv[i++] = agentbuf;
5298 /* minimal command environment */
5299 envp[i++] = "HOME=/";
5300 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5303 /* Drop the lock while we invoke the usermode helper,
5304 * since the exec could involve hitting disk and hence
5305 * be a slow process */
5306 mutex_unlock(&cgroup_mutex);
5307 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5308 mutex_lock(&cgroup_mutex);
5312 raw_spin_lock(&release_list_lock);
5314 raw_spin_unlock(&release_list_lock);
5315 mutex_unlock(&cgroup_mutex);
5318 static int __init cgroup_disable(char *str)
5320 struct cgroup_subsys *ss;
5324 while ((token = strsep(&str, ",")) != NULL) {
5328 for_each_subsys(ss, i) {
5329 if (!strcmp(token, ss->name)) {
5331 printk(KERN_INFO "Disabling %s control group"
5332 " subsystem\n", ss->name);
5339 __setup("cgroup_disable=", cgroup_disable);
5341 static int __init cgroup_set_legacy_files_on_dfl(char *str)
5343 printk("cgroup: using legacy files on the default hierarchy\n");
5344 cgroup_legacy_files_on_dfl = true;
5347 __setup("cgroup__DEVEL__legacy_files_on_dfl", cgroup_set_legacy_files_on_dfl);
5350 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5351 * @dentry: directory dentry of interest
5352 * @ss: subsystem of interest
5354 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5355 * to get the corresponding css and return it. If such css doesn't exist
5356 * or can't be pinned, an ERR_PTR value is returned.
5358 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5359 struct cgroup_subsys *ss)
5361 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5362 struct cgroup_subsys_state *css = NULL;
5363 struct cgroup *cgrp;
5365 /* is @dentry a cgroup dir? */
5366 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5367 kernfs_type(kn) != KERNFS_DIR)
5368 return ERR_PTR(-EBADF);
5373 * This path doesn't originate from kernfs and @kn could already
5374 * have been or be removed at any point. @kn->priv is RCU
5375 * protected for this access. See cgroup_rmdir() for details.
5377 cgrp = rcu_dereference(kn->priv);
5379 css = cgroup_css(cgrp, ss);
5381 if (!css || !css_tryget_online(css))
5382 css = ERR_PTR(-ENOENT);
5389 * css_from_id - lookup css by id
5390 * @id: the cgroup id
5391 * @ss: cgroup subsys to be looked into
5393 * Returns the css if there's valid one with @id, otherwise returns NULL.
5394 * Should be called under rcu_read_lock().
5396 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5398 WARN_ON_ONCE(!rcu_read_lock_held());
5399 return idr_find(&ss->css_idr, id);
5402 #ifdef CONFIG_CGROUP_DEBUG
5403 static struct cgroup_subsys_state *
5404 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5406 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5409 return ERR_PTR(-ENOMEM);
5414 static void debug_css_free(struct cgroup_subsys_state *css)
5419 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5422 return cgroup_task_count(css->cgroup);
5425 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5428 return (u64)(unsigned long)current->cgroups;
5431 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5437 count = atomic_read(&task_css_set(current)->refcount);
5442 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5444 struct cgrp_cset_link *link;
5445 struct css_set *cset;
5448 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5452 down_read(&css_set_rwsem);
5454 cset = rcu_dereference(current->cgroups);
5455 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5456 struct cgroup *c = link->cgrp;
5458 cgroup_name(c, name_buf, NAME_MAX + 1);
5459 seq_printf(seq, "Root %d group %s\n",
5460 c->root->hierarchy_id, name_buf);
5463 up_read(&css_set_rwsem);
5468 #define MAX_TASKS_SHOWN_PER_CSS 25
5469 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5471 struct cgroup_subsys_state *css = seq_css(seq);
5472 struct cgrp_cset_link *link;
5474 down_read(&css_set_rwsem);
5475 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5476 struct css_set *cset = link->cset;
5477 struct task_struct *task;
5480 seq_printf(seq, "css_set %p\n", cset);
5482 list_for_each_entry(task, &cset->tasks, cg_list) {
5483 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5485 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5488 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5489 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5491 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5495 seq_puts(seq, " ...\n");
5497 up_read(&css_set_rwsem);
5501 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5503 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5506 static struct cftype debug_files[] = {
5508 .name = "taskcount",
5509 .read_u64 = debug_taskcount_read,
5513 .name = "current_css_set",
5514 .read_u64 = current_css_set_read,
5518 .name = "current_css_set_refcount",
5519 .read_u64 = current_css_set_refcount_read,
5523 .name = "current_css_set_cg_links",
5524 .seq_show = current_css_set_cg_links_read,
5528 .name = "cgroup_css_links",
5529 .seq_show = cgroup_css_links_read,
5533 .name = "releasable",
5534 .read_u64 = releasable_read,
5540 struct cgroup_subsys debug_cgrp_subsys = {
5541 .css_alloc = debug_css_alloc,
5542 .css_free = debug_css_free,
5543 .legacy_cftypes = debug_files,
5545 #endif /* CONFIG_CGROUP_DEBUG */