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 "cgroup-internal.h"
33 #include <linux/cred.h>
34 #include <linux/errno.h>
35 #include <linux/init_task.h>
36 #include <linux/kernel.h>
37 #include <linux/magic.h>
38 #include <linux/mutex.h>
39 #include <linux/mount.h>
40 #include <linux/pagemap.h>
41 #include <linux/proc_fs.h>
42 #include <linux/rcupdate.h>
43 #include <linux/sched.h>
44 #include <linux/sched/task.h>
45 #include <linux/slab.h>
46 #include <linux/spinlock.h>
47 #include <linux/percpu-rwsem.h>
48 #include <linux/string.h>
49 #include <linux/hashtable.h>
50 #include <linux/idr.h>
51 #include <linux/kthread.h>
52 #include <linux/atomic.h>
53 #include <linux/cpuset.h>
54 #include <linux/proc_ns.h>
55 #include <linux/nsproxy.h>
56 #include <linux/file.h>
57 #include <linux/fs_parser.h>
58 #include <linux/sched/cputime.h>
59 #include <linux/psi.h>
62 #define CREATE_TRACE_POINTS
63 #include <trace/events/cgroup.h>
65 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
67 /* let's not notify more than 100 times per second */
68 #define CGROUP_FILE_NOTIFY_MIN_INTV DIV_ROUND_UP(HZ, 100)
71 * cgroup_mutex is the master lock. Any modification to cgroup or its
72 * hierarchy must be performed while holding it.
74 * css_set_lock protects task->cgroups pointer, the list of css_set
75 * objects, and the chain of tasks off each css_set.
77 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
78 * cgroup.h can use them for lockdep annotations.
80 DEFINE_MUTEX(cgroup_mutex);
81 DEFINE_SPINLOCK(css_set_lock);
83 #ifdef CONFIG_PROVE_RCU
84 EXPORT_SYMBOL_GPL(cgroup_mutex);
85 EXPORT_SYMBOL_GPL(css_set_lock);
88 DEFINE_SPINLOCK(trace_cgroup_path_lock);
89 char trace_cgroup_path[TRACE_CGROUP_PATH_LEN];
90 bool cgroup_debug __read_mostly;
93 * Protects cgroup_idr and css_idr so that IDs can be released without
94 * grabbing cgroup_mutex.
96 static DEFINE_SPINLOCK(cgroup_idr_lock);
99 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
100 * against file removal/re-creation across css hiding.
102 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
104 struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
106 #define cgroup_assert_mutex_or_rcu_locked() \
107 RCU_LOCKDEP_WARN(!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;
119 /* generate an array of cgroup subsystem pointers */
120 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
121 struct cgroup_subsys *cgroup_subsys[] = {
122 #include <linux/cgroup_subsys.h>
126 /* array of cgroup subsystem names */
127 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
128 static const char *cgroup_subsys_name[] = {
129 #include <linux/cgroup_subsys.h>
133 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
135 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
136 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
137 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
138 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
139 #include <linux/cgroup_subsys.h>
142 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
143 static struct static_key_true *cgroup_subsys_enabled_key[] = {
144 #include <linux/cgroup_subsys.h>
148 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
149 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
150 #include <linux/cgroup_subsys.h>
154 static DEFINE_PER_CPU(struct cgroup_rstat_cpu, cgrp_dfl_root_rstat_cpu);
157 * The default hierarchy, reserved for the subsystems that are otherwise
158 * unattached - it never has more than a single cgroup, and all tasks are
159 * part of that cgroup.
161 struct cgroup_root cgrp_dfl_root = { .cgrp.rstat_cpu = &cgrp_dfl_root_rstat_cpu };
162 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
165 * The default hierarchy always exists but is hidden until mounted for the
166 * first time. This is for backward compatibility.
168 static bool cgrp_dfl_visible;
170 /* some controllers are not supported in the default hierarchy */
171 static u16 cgrp_dfl_inhibit_ss_mask;
173 /* some controllers are implicitly enabled on the default hierarchy */
174 static u16 cgrp_dfl_implicit_ss_mask;
176 /* some controllers can be threaded on the default hierarchy */
177 static u16 cgrp_dfl_threaded_ss_mask;
179 /* The list of hierarchy roots */
180 LIST_HEAD(cgroup_roots);
181 static int cgroup_root_count;
183 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
184 static DEFINE_IDR(cgroup_hierarchy_idr);
187 * Assign a monotonically increasing serial number to csses. It guarantees
188 * cgroups with bigger numbers are newer than those with smaller numbers.
189 * Also, as csses are always appended to the parent's ->children list, it
190 * guarantees that sibling csses are always sorted in the ascending serial
191 * number order on the list. Protected by cgroup_mutex.
193 static u64 css_serial_nr_next = 1;
196 * These bitmasks identify subsystems with specific features to avoid
197 * having to do iterative checks repeatedly.
199 static u16 have_fork_callback __read_mostly;
200 static u16 have_exit_callback __read_mostly;
201 static u16 have_free_callback __read_mostly;
202 static u16 have_canfork_callback __read_mostly;
204 /* cgroup namespace for init task */
205 struct cgroup_namespace init_cgroup_ns = {
206 .count = REFCOUNT_INIT(2),
207 .user_ns = &init_user_ns,
208 .ns.ops = &cgroupns_operations,
209 .ns.inum = PROC_CGROUP_INIT_INO,
210 .root_cset = &init_css_set,
213 static struct file_system_type cgroup2_fs_type;
214 static struct cftype cgroup_base_files[];
216 static int cgroup_apply_control(struct cgroup *cgrp);
217 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
218 static void css_task_iter_advance(struct css_task_iter *it);
219 static int cgroup_destroy_locked(struct cgroup *cgrp);
220 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
221 struct cgroup_subsys *ss);
222 static void css_release(struct percpu_ref *ref);
223 static void kill_css(struct cgroup_subsys_state *css);
224 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
225 struct cgroup *cgrp, struct cftype cfts[],
229 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
230 * @ssid: subsys ID of interest
232 * cgroup_subsys_enabled() can only be used with literal subsys names which
233 * is fine for individual subsystems but unsuitable for cgroup core. This
234 * is slower static_key_enabled() based test indexed by @ssid.
236 bool cgroup_ssid_enabled(int ssid)
238 if (CGROUP_SUBSYS_COUNT == 0)
241 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
245 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
246 * @cgrp: the cgroup of interest
248 * The default hierarchy is the v2 interface of cgroup and this function
249 * can be used to test whether a cgroup is on the default hierarchy for
250 * cases where a subsystem should behave differnetly depending on the
253 * The set of behaviors which change on the default hierarchy are still
254 * being determined and the mount option is prefixed with __DEVEL__.
256 * List of changed behaviors:
258 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
259 * and "name" are disallowed.
261 * - When mounting an existing superblock, mount options should match.
263 * - Remount is disallowed.
265 * - rename(2) is disallowed.
267 * - "tasks" is removed. Everything should be at process granularity. Use
268 * "cgroup.procs" instead.
270 * - "cgroup.procs" is not sorted. pids will be unique unless they got
271 * recycled inbetween reads.
273 * - "release_agent" and "notify_on_release" are removed. Replacement
274 * notification mechanism will be implemented.
276 * - "cgroup.clone_children" is removed.
278 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
279 * and its descendants contain no task; otherwise, 1. The file also
280 * generates kernfs notification which can be monitored through poll and
281 * [di]notify when the value of the file changes.
283 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
284 * take masks of ancestors with non-empty cpus/mems, instead of being
285 * moved to an ancestor.
287 * - cpuset: a task can be moved into an empty cpuset, and again it takes
288 * masks of ancestors.
290 * - memcg: use_hierarchy is on by default and the cgroup file for the flag
293 * - blkcg: blk-throttle becomes properly hierarchical.
295 * - debug: disallowed on the default hierarchy.
297 bool cgroup_on_dfl(const struct cgroup *cgrp)
299 return cgrp->root == &cgrp_dfl_root;
302 /* IDR wrappers which synchronize using cgroup_idr_lock */
303 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
308 idr_preload(gfp_mask);
309 spin_lock_bh(&cgroup_idr_lock);
310 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
311 spin_unlock_bh(&cgroup_idr_lock);
316 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
320 spin_lock_bh(&cgroup_idr_lock);
321 ret = idr_replace(idr, ptr, id);
322 spin_unlock_bh(&cgroup_idr_lock);
326 static void cgroup_idr_remove(struct idr *idr, int id)
328 spin_lock_bh(&cgroup_idr_lock);
330 spin_unlock_bh(&cgroup_idr_lock);
333 static bool cgroup_has_tasks(struct cgroup *cgrp)
335 return cgrp->nr_populated_csets;
338 bool cgroup_is_threaded(struct cgroup *cgrp)
340 return cgrp->dom_cgrp != cgrp;
343 /* can @cgrp host both domain and threaded children? */
344 static bool cgroup_is_mixable(struct cgroup *cgrp)
347 * Root isn't under domain level resource control exempting it from
348 * the no-internal-process constraint, so it can serve as a thread
349 * root and a parent of resource domains at the same time.
351 return !cgroup_parent(cgrp);
354 /* can @cgrp become a thread root? should always be true for a thread root */
355 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
357 /* mixables don't care */
358 if (cgroup_is_mixable(cgrp))
361 /* domain roots can't be nested under threaded */
362 if (cgroup_is_threaded(cgrp))
365 /* can only have either domain or threaded children */
366 if (cgrp->nr_populated_domain_children)
369 /* and no domain controllers can be enabled */
370 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
376 /* is @cgrp root of a threaded subtree? */
377 bool cgroup_is_thread_root(struct cgroup *cgrp)
379 /* thread root should be a domain */
380 if (cgroup_is_threaded(cgrp))
383 /* a domain w/ threaded children is a thread root */
384 if (cgrp->nr_threaded_children)
388 * A domain which has tasks and explicit threaded controllers
389 * enabled is a thread root.
391 if (cgroup_has_tasks(cgrp) &&
392 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
398 /* a domain which isn't connected to the root w/o brekage can't be used */
399 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
401 /* the cgroup itself can be a thread root */
402 if (cgroup_is_threaded(cgrp))
405 /* but the ancestors can't be unless mixable */
406 while ((cgrp = cgroup_parent(cgrp))) {
407 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
409 if (cgroup_is_threaded(cgrp))
416 /* subsystems visibly enabled on a cgroup */
417 static u16 cgroup_control(struct cgroup *cgrp)
419 struct cgroup *parent = cgroup_parent(cgrp);
420 u16 root_ss_mask = cgrp->root->subsys_mask;
423 u16 ss_mask = parent->subtree_control;
425 /* threaded cgroups can only have threaded controllers */
426 if (cgroup_is_threaded(cgrp))
427 ss_mask &= cgrp_dfl_threaded_ss_mask;
431 if (cgroup_on_dfl(cgrp))
432 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
433 cgrp_dfl_implicit_ss_mask);
437 /* subsystems enabled on a cgroup */
438 static u16 cgroup_ss_mask(struct cgroup *cgrp)
440 struct cgroup *parent = cgroup_parent(cgrp);
443 u16 ss_mask = parent->subtree_ss_mask;
445 /* threaded cgroups can only have threaded controllers */
446 if (cgroup_is_threaded(cgrp))
447 ss_mask &= cgrp_dfl_threaded_ss_mask;
451 return cgrp->root->subsys_mask;
455 * cgroup_css - obtain a cgroup's css for the specified subsystem
456 * @cgrp: the cgroup of interest
457 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
459 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
460 * function must be called either under cgroup_mutex or rcu_read_lock() and
461 * the caller is responsible for pinning the returned css if it wants to
462 * keep accessing it outside the said locks. This function may return
463 * %NULL if @cgrp doesn't have @subsys_id enabled.
465 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
466 struct cgroup_subsys *ss)
469 return rcu_dereference_check(cgrp->subsys[ss->id],
470 lockdep_is_held(&cgroup_mutex));
476 * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
477 * @cgrp: the cgroup of interest
478 * @ss: the subsystem of interest
480 * Find and get @cgrp's css assocaited with @ss. If the css doesn't exist
481 * or is offline, %NULL is returned.
483 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
484 struct cgroup_subsys *ss)
486 struct cgroup_subsys_state *css;
489 css = cgroup_css(cgrp, ss);
490 if (!css || !css_tryget_online(css))
498 * cgroup_e_css_by_mask - obtain a cgroup's effective css for the specified ss
499 * @cgrp: the cgroup of interest
500 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
502 * Similar to cgroup_css() but returns the effective css, which is defined
503 * as the matching css of the nearest ancestor including self which has @ss
504 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
505 * function is guaranteed to return non-NULL css.
507 static struct cgroup_subsys_state *cgroup_e_css_by_mask(struct cgroup *cgrp,
508 struct cgroup_subsys *ss)
510 lockdep_assert_held(&cgroup_mutex);
516 * This function is used while updating css associations and thus
517 * can't test the csses directly. Test ss_mask.
519 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
520 cgrp = cgroup_parent(cgrp);
525 return cgroup_css(cgrp, ss);
529 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
530 * @cgrp: the cgroup of interest
531 * @ss: the subsystem of interest
533 * Find and get the effective css of @cgrp for @ss. The effective css is
534 * defined as the matching css of the nearest ancestor including self which
535 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
536 * the root css is returned, so this function always returns a valid css.
538 * The returned css is not guaranteed to be online, and therefore it is the
539 * callers responsiblity to tryget a reference for it.
541 struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
542 struct cgroup_subsys *ss)
544 struct cgroup_subsys_state *css;
547 css = cgroup_css(cgrp, ss);
551 cgrp = cgroup_parent(cgrp);
554 return init_css_set.subsys[ss->id];
558 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
559 * @cgrp: the cgroup of interest
560 * @ss: the subsystem of interest
562 * Find and get the effective css of @cgrp for @ss. The effective css is
563 * defined as the matching css of the nearest ancestor including self which
564 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
565 * the root css is returned, so this function always returns a valid css.
566 * The returned css must be put using css_put().
568 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
569 struct cgroup_subsys *ss)
571 struct cgroup_subsys_state *css;
576 css = cgroup_css(cgrp, ss);
578 if (css && css_tryget_online(css))
580 cgrp = cgroup_parent(cgrp);
583 css = init_css_set.subsys[ss->id];
590 static void cgroup_get_live(struct cgroup *cgrp)
592 WARN_ON_ONCE(cgroup_is_dead(cgrp));
593 css_get(&cgrp->self);
596 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
598 struct cgroup *cgrp = of->kn->parent->priv;
599 struct cftype *cft = of_cft(of);
602 * This is open and unprotected implementation of cgroup_css().
603 * seq_css() is only called from a kernfs file operation which has
604 * an active reference on the file. Because all the subsystem
605 * files are drained before a css is disassociated with a cgroup,
606 * the matching css from the cgroup's subsys table is guaranteed to
607 * be and stay valid until the enclosing operation is complete.
610 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
614 EXPORT_SYMBOL_GPL(of_css);
617 * for_each_css - iterate all css's of a cgroup
618 * @css: the iteration cursor
619 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
620 * @cgrp: the target cgroup to iterate css's of
622 * Should be called under cgroup_[tree_]mutex.
624 #define for_each_css(css, ssid, cgrp) \
625 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
626 if (!((css) = rcu_dereference_check( \
627 (cgrp)->subsys[(ssid)], \
628 lockdep_is_held(&cgroup_mutex)))) { } \
632 * for_each_e_css - iterate all effective css's of a cgroup
633 * @css: the iteration cursor
634 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
635 * @cgrp: the target cgroup to iterate css's of
637 * Should be called under cgroup_[tree_]mutex.
639 #define for_each_e_css(css, ssid, cgrp) \
640 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
641 if (!((css) = cgroup_e_css_by_mask(cgrp, \
642 cgroup_subsys[(ssid)]))) \
647 * do_each_subsys_mask - filter for_each_subsys with a bitmask
648 * @ss: the iteration cursor
649 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
650 * @ss_mask: the bitmask
652 * The block will only run for cases where the ssid-th bit (1 << ssid) of
655 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
656 unsigned long __ss_mask = (ss_mask); \
657 if (!CGROUP_SUBSYS_COUNT) { /* to avoid spurious gcc warning */ \
661 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
662 (ss) = cgroup_subsys[ssid]; \
665 #define while_each_subsys_mask() \
670 /* iterate over child cgrps, lock should be held throughout iteration */
671 #define cgroup_for_each_live_child(child, cgrp) \
672 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
673 if (({ lockdep_assert_held(&cgroup_mutex); \
674 cgroup_is_dead(child); })) \
678 /* walk live descendants in preorder */
679 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
680 css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
681 if (({ lockdep_assert_held(&cgroup_mutex); \
682 (dsct) = (d_css)->cgroup; \
683 cgroup_is_dead(dsct); })) \
687 /* walk live descendants in postorder */
688 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
689 css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
690 if (({ lockdep_assert_held(&cgroup_mutex); \
691 (dsct) = (d_css)->cgroup; \
692 cgroup_is_dead(dsct); })) \
697 * The default css_set - used by init and its children prior to any
698 * hierarchies being mounted. It contains a pointer to the root state
699 * for each subsystem. Also used to anchor the list of css_sets. Not
700 * reference-counted, to improve performance when child cgroups
701 * haven't been created.
703 struct css_set init_css_set = {
704 .refcount = REFCOUNT_INIT(1),
705 .dom_cset = &init_css_set,
706 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
707 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
708 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
709 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
710 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
711 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
712 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
715 * The following field is re-initialized when this cset gets linked
716 * in cgroup_init(). However, let's initialize the field
717 * statically too so that the default cgroup can be accessed safely
720 .dfl_cgrp = &cgrp_dfl_root.cgrp,
723 static int css_set_count = 1; /* 1 for init_css_set */
725 static bool css_set_threaded(struct css_set *cset)
727 return cset->dom_cset != cset;
731 * css_set_populated - does a css_set contain any tasks?
732 * @cset: target css_set
734 * css_set_populated() should be the same as !!cset->nr_tasks at steady
735 * state. However, css_set_populated() can be called while a task is being
736 * added to or removed from the linked list before the nr_tasks is
737 * properly updated. Hence, we can't just look at ->nr_tasks here.
739 static bool css_set_populated(struct css_set *cset)
741 lockdep_assert_held(&css_set_lock);
743 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
747 * cgroup_update_populated - update the populated count of a cgroup
748 * @cgrp: the target cgroup
749 * @populated: inc or dec populated count
751 * One of the css_sets associated with @cgrp is either getting its first
752 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
753 * count is propagated towards root so that a given cgroup's
754 * nr_populated_children is zero iff none of its descendants contain any
757 * @cgrp's interface file "cgroup.populated" is zero if both
758 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
759 * 1 otherwise. When the sum changes from or to zero, userland is notified
760 * that the content of the interface file has changed. This can be used to
761 * detect when @cgrp and its descendants become populated or empty.
763 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
765 struct cgroup *child = NULL;
766 int adj = populated ? 1 : -1;
768 lockdep_assert_held(&css_set_lock);
771 bool was_populated = cgroup_is_populated(cgrp);
774 cgrp->nr_populated_csets += adj;
776 if (cgroup_is_threaded(child))
777 cgrp->nr_populated_threaded_children += adj;
779 cgrp->nr_populated_domain_children += adj;
782 if (was_populated == cgroup_is_populated(cgrp))
785 cgroup1_check_for_release(cgrp);
786 cgroup_file_notify(&cgrp->events_file);
789 cgrp = cgroup_parent(cgrp);
794 * css_set_update_populated - update populated state of a css_set
795 * @cset: target css_set
796 * @populated: whether @cset is populated or depopulated
798 * @cset is either getting the first task or losing the last. Update the
799 * populated counters of all associated cgroups accordingly.
801 static void css_set_update_populated(struct css_set *cset, bool populated)
803 struct cgrp_cset_link *link;
805 lockdep_assert_held(&css_set_lock);
807 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
808 cgroup_update_populated(link->cgrp, populated);
812 * css_set_move_task - move a task from one css_set to another
813 * @task: task being moved
814 * @from_cset: css_set @task currently belongs to (may be NULL)
815 * @to_cset: new css_set @task is being moved to (may be NULL)
816 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
818 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
819 * css_set, @from_cset can be NULL. If @task is being disassociated
820 * instead of moved, @to_cset can be NULL.
822 * This function automatically handles populated counter updates and
823 * css_task_iter adjustments but the caller is responsible for managing
824 * @from_cset and @to_cset's reference counts.
826 static void css_set_move_task(struct task_struct *task,
827 struct css_set *from_cset, struct css_set *to_cset,
830 lockdep_assert_held(&css_set_lock);
832 if (to_cset && !css_set_populated(to_cset))
833 css_set_update_populated(to_cset, true);
836 struct css_task_iter *it, *pos;
838 WARN_ON_ONCE(list_empty(&task->cg_list));
841 * @task is leaving, advance task iterators which are
842 * pointing to it so that they can resume at the next
843 * position. Advancing an iterator might remove it from
844 * the list, use safe walk. See css_task_iter_advance*()
847 list_for_each_entry_safe(it, pos, &from_cset->task_iters,
849 if (it->task_pos == &task->cg_list)
850 css_task_iter_advance(it);
852 list_del_init(&task->cg_list);
853 if (!css_set_populated(from_cset))
854 css_set_update_populated(from_cset, false);
856 WARN_ON_ONCE(!list_empty(&task->cg_list));
861 * We are synchronized through cgroup_threadgroup_rwsem
862 * against PF_EXITING setting such that we can't race
863 * against cgroup_exit() changing the css_set to
864 * init_css_set and dropping the old one.
866 WARN_ON_ONCE(task->flags & PF_EXITING);
868 cgroup_move_task(task, to_cset);
869 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
875 * hash table for cgroup groups. This improves the performance to find
876 * an existing css_set. This hash doesn't (currently) take into
877 * account cgroups in empty hierarchies.
879 #define CSS_SET_HASH_BITS 7
880 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
882 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
884 unsigned long key = 0UL;
885 struct cgroup_subsys *ss;
888 for_each_subsys(ss, i)
889 key += (unsigned long)css[i];
890 key = (key >> 16) ^ key;
895 void put_css_set_locked(struct css_set *cset)
897 struct cgrp_cset_link *link, *tmp_link;
898 struct cgroup_subsys *ss;
901 lockdep_assert_held(&css_set_lock);
903 if (!refcount_dec_and_test(&cset->refcount))
906 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
908 /* This css_set is dead. unlink it and release cgroup and css refs */
909 for_each_subsys(ss, ssid) {
910 list_del(&cset->e_cset_node[ssid]);
911 css_put(cset->subsys[ssid]);
913 hash_del(&cset->hlist);
916 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
917 list_del(&link->cset_link);
918 list_del(&link->cgrp_link);
919 if (cgroup_parent(link->cgrp))
920 cgroup_put(link->cgrp);
924 if (css_set_threaded(cset)) {
925 list_del(&cset->threaded_csets_node);
926 put_css_set_locked(cset->dom_cset);
929 kfree_rcu(cset, rcu_head);
933 * compare_css_sets - helper function for find_existing_css_set().
934 * @cset: candidate css_set being tested
935 * @old_cset: existing css_set for a task
936 * @new_cgrp: cgroup that's being entered by the task
937 * @template: desired set of css pointers in css_set (pre-calculated)
939 * Returns true if "cset" matches "old_cset" except for the hierarchy
940 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
942 static bool compare_css_sets(struct css_set *cset,
943 struct css_set *old_cset,
944 struct cgroup *new_cgrp,
945 struct cgroup_subsys_state *template[])
947 struct cgroup *new_dfl_cgrp;
948 struct list_head *l1, *l2;
951 * On the default hierarchy, there can be csets which are
952 * associated with the same set of cgroups but different csses.
953 * Let's first ensure that csses match.
955 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
959 /* @cset's domain should match the default cgroup's */
960 if (cgroup_on_dfl(new_cgrp))
961 new_dfl_cgrp = new_cgrp;
963 new_dfl_cgrp = old_cset->dfl_cgrp;
965 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
969 * Compare cgroup pointers in order to distinguish between
970 * different cgroups in hierarchies. As different cgroups may
971 * share the same effective css, this comparison is always
974 l1 = &cset->cgrp_links;
975 l2 = &old_cset->cgrp_links;
977 struct cgrp_cset_link *link1, *link2;
978 struct cgroup *cgrp1, *cgrp2;
982 /* See if we reached the end - both lists are equal length. */
983 if (l1 == &cset->cgrp_links) {
984 BUG_ON(l2 != &old_cset->cgrp_links);
987 BUG_ON(l2 == &old_cset->cgrp_links);
989 /* Locate the cgroups associated with these links. */
990 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
991 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
994 /* Hierarchies should be linked in the same order. */
995 BUG_ON(cgrp1->root != cgrp2->root);
998 * If this hierarchy is the hierarchy of the cgroup
999 * that's changing, then we need to check that this
1000 * css_set points to the new cgroup; if it's any other
1001 * hierarchy, then this css_set should point to the
1002 * same cgroup as the old css_set.
1004 if (cgrp1->root == new_cgrp->root) {
1005 if (cgrp1 != new_cgrp)
1016 * find_existing_css_set - init css array and find the matching css_set
1017 * @old_cset: the css_set that we're using before the cgroup transition
1018 * @cgrp: the cgroup that we're moving into
1019 * @template: out param for the new set of csses, should be clear on entry
1021 static struct css_set *find_existing_css_set(struct css_set *old_cset,
1022 struct cgroup *cgrp,
1023 struct cgroup_subsys_state *template[])
1025 struct cgroup_root *root = cgrp->root;
1026 struct cgroup_subsys *ss;
1027 struct css_set *cset;
1032 * Build the set of subsystem state objects that we want to see in the
1033 * new css_set. while subsystems can change globally, the entries here
1034 * won't change, so no need for locking.
1036 for_each_subsys(ss, i) {
1037 if (root->subsys_mask & (1UL << i)) {
1039 * @ss is in this hierarchy, so we want the
1040 * effective css from @cgrp.
1042 template[i] = cgroup_e_css_by_mask(cgrp, ss);
1045 * @ss is not in this hierarchy, so we don't want
1046 * to change the css.
1048 template[i] = old_cset->subsys[i];
1052 key = css_set_hash(template);
1053 hash_for_each_possible(css_set_table, cset, hlist, key) {
1054 if (!compare_css_sets(cset, old_cset, cgrp, template))
1057 /* This css_set matches what we need */
1061 /* No existing cgroup group matched */
1065 static void free_cgrp_cset_links(struct list_head *links_to_free)
1067 struct cgrp_cset_link *link, *tmp_link;
1069 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1070 list_del(&link->cset_link);
1076 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1077 * @count: the number of links to allocate
1078 * @tmp_links: list_head the allocated links are put on
1080 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1081 * through ->cset_link. Returns 0 on success or -errno.
1083 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1085 struct cgrp_cset_link *link;
1088 INIT_LIST_HEAD(tmp_links);
1090 for (i = 0; i < count; i++) {
1091 link = kzalloc(sizeof(*link), GFP_KERNEL);
1093 free_cgrp_cset_links(tmp_links);
1096 list_add(&link->cset_link, tmp_links);
1102 * link_css_set - a helper function to link a css_set to a cgroup
1103 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1104 * @cset: the css_set to be linked
1105 * @cgrp: the destination cgroup
1107 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1108 struct cgroup *cgrp)
1110 struct cgrp_cset_link *link;
1112 BUG_ON(list_empty(tmp_links));
1114 if (cgroup_on_dfl(cgrp))
1115 cset->dfl_cgrp = cgrp;
1117 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1122 * Always add links to the tail of the lists so that the lists are
1123 * in choronological order.
1125 list_move_tail(&link->cset_link, &cgrp->cset_links);
1126 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1128 if (cgroup_parent(cgrp))
1129 cgroup_get_live(cgrp);
1133 * find_css_set - return a new css_set with one cgroup updated
1134 * @old_cset: the baseline css_set
1135 * @cgrp: the cgroup to be updated
1137 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1138 * substituted into the appropriate hierarchy.
1140 static struct css_set *find_css_set(struct css_set *old_cset,
1141 struct cgroup *cgrp)
1143 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1144 struct css_set *cset;
1145 struct list_head tmp_links;
1146 struct cgrp_cset_link *link;
1147 struct cgroup_subsys *ss;
1151 lockdep_assert_held(&cgroup_mutex);
1153 /* First see if we already have a cgroup group that matches
1154 * the desired set */
1155 spin_lock_irq(&css_set_lock);
1156 cset = find_existing_css_set(old_cset, cgrp, template);
1159 spin_unlock_irq(&css_set_lock);
1164 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1168 /* Allocate all the cgrp_cset_link objects that we'll need */
1169 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1174 refcount_set(&cset->refcount, 1);
1175 cset->dom_cset = cset;
1176 INIT_LIST_HEAD(&cset->tasks);
1177 INIT_LIST_HEAD(&cset->mg_tasks);
1178 INIT_LIST_HEAD(&cset->task_iters);
1179 INIT_LIST_HEAD(&cset->threaded_csets);
1180 INIT_HLIST_NODE(&cset->hlist);
1181 INIT_LIST_HEAD(&cset->cgrp_links);
1182 INIT_LIST_HEAD(&cset->mg_preload_node);
1183 INIT_LIST_HEAD(&cset->mg_node);
1185 /* Copy the set of subsystem state objects generated in
1186 * find_existing_css_set() */
1187 memcpy(cset->subsys, template, sizeof(cset->subsys));
1189 spin_lock_irq(&css_set_lock);
1190 /* Add reference counts and links from the new css_set. */
1191 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1192 struct cgroup *c = link->cgrp;
1194 if (c->root == cgrp->root)
1196 link_css_set(&tmp_links, cset, c);
1199 BUG_ON(!list_empty(&tmp_links));
1203 /* Add @cset to the hash table */
1204 key = css_set_hash(cset->subsys);
1205 hash_add(css_set_table, &cset->hlist, key);
1207 for_each_subsys(ss, ssid) {
1208 struct cgroup_subsys_state *css = cset->subsys[ssid];
1210 list_add_tail(&cset->e_cset_node[ssid],
1211 &css->cgroup->e_csets[ssid]);
1215 spin_unlock_irq(&css_set_lock);
1218 * If @cset should be threaded, look up the matching dom_cset and
1219 * link them up. We first fully initialize @cset then look for the
1220 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1221 * to stay empty until we return.
1223 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1224 struct css_set *dcset;
1226 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1232 spin_lock_irq(&css_set_lock);
1233 cset->dom_cset = dcset;
1234 list_add_tail(&cset->threaded_csets_node,
1235 &dcset->threaded_csets);
1236 spin_unlock_irq(&css_set_lock);
1242 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1244 struct cgroup *root_cgrp = kf_root->kn->priv;
1246 return root_cgrp->root;
1249 static int cgroup_init_root_id(struct cgroup_root *root)
1253 lockdep_assert_held(&cgroup_mutex);
1255 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1259 root->hierarchy_id = id;
1263 static void cgroup_exit_root_id(struct cgroup_root *root)
1265 lockdep_assert_held(&cgroup_mutex);
1267 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1270 void cgroup_free_root(struct cgroup_root *root)
1273 idr_destroy(&root->cgroup_idr);
1278 static void cgroup_destroy_root(struct cgroup_root *root)
1280 struct cgroup *cgrp = &root->cgrp;
1281 struct cgrp_cset_link *link, *tmp_link;
1283 trace_cgroup_destroy_root(root);
1285 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1287 BUG_ON(atomic_read(&root->nr_cgrps));
1288 BUG_ON(!list_empty(&cgrp->self.children));
1290 /* Rebind all subsystems back to the default hierarchy */
1291 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1294 * Release all the links from cset_links to this hierarchy's
1297 spin_lock_irq(&css_set_lock);
1299 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1300 list_del(&link->cset_link);
1301 list_del(&link->cgrp_link);
1305 spin_unlock_irq(&css_set_lock);
1307 if (!list_empty(&root->root_list)) {
1308 list_del(&root->root_list);
1309 cgroup_root_count--;
1312 cgroup_exit_root_id(root);
1314 mutex_unlock(&cgroup_mutex);
1316 kernfs_destroy_root(root->kf_root);
1317 cgroup_free_root(root);
1321 * look up cgroup associated with current task's cgroup namespace on the
1322 * specified hierarchy
1324 static struct cgroup *
1325 current_cgns_cgroup_from_root(struct cgroup_root *root)
1327 struct cgroup *res = NULL;
1328 struct css_set *cset;
1330 lockdep_assert_held(&css_set_lock);
1334 cset = current->nsproxy->cgroup_ns->root_cset;
1335 if (cset == &init_css_set) {
1338 struct cgrp_cset_link *link;
1340 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1341 struct cgroup *c = link->cgrp;
1343 if (c->root == root) {
1355 /* look up cgroup associated with given css_set on the specified hierarchy */
1356 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1357 struct cgroup_root *root)
1359 struct cgroup *res = NULL;
1361 lockdep_assert_held(&cgroup_mutex);
1362 lockdep_assert_held(&css_set_lock);
1364 if (cset == &init_css_set) {
1366 } else if (root == &cgrp_dfl_root) {
1367 res = cset->dfl_cgrp;
1369 struct cgrp_cset_link *link;
1371 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1372 struct cgroup *c = link->cgrp;
1374 if (c->root == root) {
1386 * Return the cgroup for "task" from the given hierarchy. Must be
1387 * called with cgroup_mutex and css_set_lock held.
1389 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1390 struct cgroup_root *root)
1393 * No need to lock the task - since we hold cgroup_mutex the
1394 * task can't change groups, so the only thing that can happen
1395 * is that it exits and its css is set back to init_css_set.
1397 return cset_cgroup_from_root(task_css_set(task), root);
1401 * A task must hold cgroup_mutex to modify cgroups.
1403 * Any task can increment and decrement the count field without lock.
1404 * So in general, code holding cgroup_mutex can't rely on the count
1405 * field not changing. However, if the count goes to zero, then only
1406 * cgroup_attach_task() can increment it again. Because a count of zero
1407 * means that no tasks are currently attached, therefore there is no
1408 * way a task attached to that cgroup can fork (the other way to
1409 * increment the count). So code holding cgroup_mutex can safely
1410 * assume that if the count is zero, it will stay zero. Similarly, if
1411 * a task holds cgroup_mutex on a cgroup with zero count, it
1412 * knows that the cgroup won't be removed, as cgroup_rmdir()
1415 * A cgroup can only be deleted if both its 'count' of using tasks
1416 * is zero, and its list of 'children' cgroups is empty. Since all
1417 * tasks in the system use _some_ cgroup, and since there is always at
1418 * least one task in the system (init, pid == 1), therefore, root cgroup
1419 * always has either children cgroups and/or using tasks. So we don't
1420 * need a special hack to ensure that root cgroup cannot be deleted.
1422 * P.S. One more locking exception. RCU is used to guard the
1423 * update of a tasks cgroup pointer by cgroup_attach_task()
1426 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1428 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1431 struct cgroup_subsys *ss = cft->ss;
1433 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1434 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
1435 const char *dbg = (cft->flags & CFTYPE_DEBUG) ? ".__DEBUG__." : "";
1437 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s%s.%s",
1438 dbg, cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1441 strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1447 * cgroup_file_mode - deduce file mode of a control file
1448 * @cft: the control file in question
1450 * S_IRUGO for read, S_IWUSR for write.
1452 static umode_t cgroup_file_mode(const struct cftype *cft)
1456 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1459 if (cft->write_u64 || cft->write_s64 || cft->write) {
1460 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1470 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1471 * @subtree_control: the new subtree_control mask to consider
1472 * @this_ss_mask: available subsystems
1474 * On the default hierarchy, a subsystem may request other subsystems to be
1475 * enabled together through its ->depends_on mask. In such cases, more
1476 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1478 * This function calculates which subsystems need to be enabled if
1479 * @subtree_control is to be applied while restricted to @this_ss_mask.
1481 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1483 u16 cur_ss_mask = subtree_control;
1484 struct cgroup_subsys *ss;
1487 lockdep_assert_held(&cgroup_mutex);
1489 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1492 u16 new_ss_mask = cur_ss_mask;
1494 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1495 new_ss_mask |= ss->depends_on;
1496 } while_each_subsys_mask();
1499 * Mask out subsystems which aren't available. This can
1500 * happen only if some depended-upon subsystems were bound
1501 * to non-default hierarchies.
1503 new_ss_mask &= this_ss_mask;
1505 if (new_ss_mask == cur_ss_mask)
1507 cur_ss_mask = new_ss_mask;
1514 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1515 * @kn: the kernfs_node being serviced
1517 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1518 * the method finishes if locking succeeded. Note that once this function
1519 * returns the cgroup returned by cgroup_kn_lock_live() may become
1520 * inaccessible any time. If the caller intends to continue to access the
1521 * cgroup, it should pin it before invoking this function.
1523 void cgroup_kn_unlock(struct kernfs_node *kn)
1525 struct cgroup *cgrp;
1527 if (kernfs_type(kn) == KERNFS_DIR)
1530 cgrp = kn->parent->priv;
1532 mutex_unlock(&cgroup_mutex);
1534 kernfs_unbreak_active_protection(kn);
1539 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1540 * @kn: the kernfs_node being serviced
1541 * @drain_offline: perform offline draining on the cgroup
1543 * This helper is to be used by a cgroup kernfs method currently servicing
1544 * @kn. It breaks the active protection, performs cgroup locking and
1545 * verifies that the associated cgroup is alive. Returns the cgroup if
1546 * alive; otherwise, %NULL. A successful return should be undone by a
1547 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1548 * cgroup is drained of offlining csses before return.
1550 * Any cgroup kernfs method implementation which requires locking the
1551 * associated cgroup should use this helper. It avoids nesting cgroup
1552 * locking under kernfs active protection and allows all kernfs operations
1553 * including self-removal.
1555 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1557 struct cgroup *cgrp;
1559 if (kernfs_type(kn) == KERNFS_DIR)
1562 cgrp = kn->parent->priv;
1565 * We're gonna grab cgroup_mutex which nests outside kernfs
1566 * active_ref. cgroup liveliness check alone provides enough
1567 * protection against removal. Ensure @cgrp stays accessible and
1568 * break the active_ref protection.
1570 if (!cgroup_tryget(cgrp))
1572 kernfs_break_active_protection(kn);
1575 cgroup_lock_and_drain_offline(cgrp);
1577 mutex_lock(&cgroup_mutex);
1579 if (!cgroup_is_dead(cgrp))
1582 cgroup_kn_unlock(kn);
1586 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1588 char name[CGROUP_FILE_NAME_MAX];
1590 lockdep_assert_held(&cgroup_mutex);
1592 if (cft->file_offset) {
1593 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1594 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1596 spin_lock_irq(&cgroup_file_kn_lock);
1598 spin_unlock_irq(&cgroup_file_kn_lock);
1600 del_timer_sync(&cfile->notify_timer);
1603 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1607 * css_clear_dir - remove subsys files in a cgroup directory
1610 static void css_clear_dir(struct cgroup_subsys_state *css)
1612 struct cgroup *cgrp = css->cgroup;
1613 struct cftype *cfts;
1615 if (!(css->flags & CSS_VISIBLE))
1618 css->flags &= ~CSS_VISIBLE;
1621 if (cgroup_on_dfl(cgrp))
1622 cfts = cgroup_base_files;
1624 cfts = cgroup1_base_files;
1626 cgroup_addrm_files(css, cgrp, cfts, false);
1628 list_for_each_entry(cfts, &css->ss->cfts, node)
1629 cgroup_addrm_files(css, cgrp, cfts, false);
1634 * css_populate_dir - create subsys files in a cgroup directory
1637 * On failure, no file is added.
1639 static int css_populate_dir(struct cgroup_subsys_state *css)
1641 struct cgroup *cgrp = css->cgroup;
1642 struct cftype *cfts, *failed_cfts;
1645 if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
1649 if (cgroup_on_dfl(cgrp))
1650 cfts = cgroup_base_files;
1652 cfts = cgroup1_base_files;
1654 ret = cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1658 list_for_each_entry(cfts, &css->ss->cfts, node) {
1659 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1667 css->flags |= CSS_VISIBLE;
1671 list_for_each_entry(cfts, &css->ss->cfts, node) {
1672 if (cfts == failed_cfts)
1674 cgroup_addrm_files(css, cgrp, cfts, false);
1679 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1681 struct cgroup *dcgrp = &dst_root->cgrp;
1682 struct cgroup_subsys *ss;
1685 lockdep_assert_held(&cgroup_mutex);
1687 do_each_subsys_mask(ss, ssid, ss_mask) {
1689 * If @ss has non-root csses attached to it, can't move.
1690 * If @ss is an implicit controller, it is exempt from this
1691 * rule and can be stolen.
1693 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1694 !ss->implicit_on_dfl)
1697 /* can't move between two non-dummy roots either */
1698 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1700 } while_each_subsys_mask();
1702 do_each_subsys_mask(ss, ssid, ss_mask) {
1703 struct cgroup_root *src_root = ss->root;
1704 struct cgroup *scgrp = &src_root->cgrp;
1705 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1706 struct css_set *cset;
1708 WARN_ON(!css || cgroup_css(dcgrp, ss));
1710 /* disable from the source */
1711 src_root->subsys_mask &= ~(1 << ssid);
1712 WARN_ON(cgroup_apply_control(scgrp));
1713 cgroup_finalize_control(scgrp, 0);
1716 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1717 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1718 ss->root = dst_root;
1719 css->cgroup = dcgrp;
1721 spin_lock_irq(&css_set_lock);
1722 hash_for_each(css_set_table, i, cset, hlist)
1723 list_move_tail(&cset->e_cset_node[ss->id],
1724 &dcgrp->e_csets[ss->id]);
1725 spin_unlock_irq(&css_set_lock);
1727 /* default hierarchy doesn't enable controllers by default */
1728 dst_root->subsys_mask |= 1 << ssid;
1729 if (dst_root == &cgrp_dfl_root) {
1730 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1732 dcgrp->subtree_control |= 1 << ssid;
1733 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1736 ret = cgroup_apply_control(dcgrp);
1738 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1743 } while_each_subsys_mask();
1745 kernfs_activate(dcgrp->kn);
1749 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1750 struct kernfs_root *kf_root)
1754 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1755 struct cgroup *ns_cgroup;
1757 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1761 spin_lock_irq(&css_set_lock);
1762 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1763 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1764 spin_unlock_irq(&css_set_lock);
1766 if (len >= PATH_MAX)
1769 seq_escape(sf, buf, " \t\n\\");
1776 enum cgroup2_param {
1781 static const struct fs_parameter_spec cgroup2_param_specs[] = {
1782 fsparam_flag ("nsdelegate", Opt_nsdelegate),
1786 static const struct fs_parameter_description cgroup2_fs_parameters = {
1788 .specs = cgroup2_param_specs,
1791 static int cgroup2_parse_param(struct fs_context *fc, struct fs_parameter *param)
1793 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1794 struct fs_parse_result result;
1797 opt = fs_parse(fc, &cgroup2_fs_parameters, param, &result);
1802 case Opt_nsdelegate:
1803 ctx->flags |= CGRP_ROOT_NS_DELEGATE;
1809 static void apply_cgroup_root_flags(unsigned int root_flags)
1811 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1812 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1813 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1815 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1819 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1821 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1822 seq_puts(seq, ",nsdelegate");
1826 static int cgroup_reconfigure(struct fs_context *fc)
1828 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1830 apply_cgroup_root_flags(ctx->flags);
1835 * To reduce the fork() overhead for systems that are not actually using
1836 * their cgroups capability, we don't maintain the lists running through
1837 * each css_set to its tasks until we see the list actually used - in other
1838 * words after the first mount.
1840 static bool use_task_css_set_links __read_mostly;
1842 static void cgroup_enable_task_cg_lists(void)
1844 struct task_struct *p, *g;
1847 * We need tasklist_lock because RCU is not safe against
1848 * while_each_thread(). Besides, a forking task that has passed
1849 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1850 * is not guaranteed to have its child immediately visible in the
1851 * tasklist if we walk through it with RCU.
1853 read_lock(&tasklist_lock);
1854 spin_lock_irq(&css_set_lock);
1856 if (use_task_css_set_links)
1859 use_task_css_set_links = true;
1861 do_each_thread(g, p) {
1862 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1863 task_css_set(p) != &init_css_set);
1866 * We should check if the process is exiting, otherwise
1867 * it will race with cgroup_exit() in that the list
1868 * entry won't be deleted though the process has exited.
1869 * Do it while holding siglock so that we don't end up
1870 * racing against cgroup_exit().
1872 * Interrupts were already disabled while acquiring
1873 * the css_set_lock, so we do not need to disable it
1874 * again when acquiring the sighand->siglock here.
1876 spin_lock(&p->sighand->siglock);
1877 if (!(p->flags & PF_EXITING)) {
1878 struct css_set *cset = task_css_set(p);
1880 if (!css_set_populated(cset))
1881 css_set_update_populated(cset, true);
1882 list_add_tail(&p->cg_list, &cset->tasks);
1886 spin_unlock(&p->sighand->siglock);
1887 } while_each_thread(g, p);
1889 spin_unlock_irq(&css_set_lock);
1890 read_unlock(&tasklist_lock);
1893 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1895 struct cgroup_subsys *ss;
1898 INIT_LIST_HEAD(&cgrp->self.sibling);
1899 INIT_LIST_HEAD(&cgrp->self.children);
1900 INIT_LIST_HEAD(&cgrp->cset_links);
1901 INIT_LIST_HEAD(&cgrp->pidlists);
1902 mutex_init(&cgrp->pidlist_mutex);
1903 cgrp->self.cgroup = cgrp;
1904 cgrp->self.flags |= CSS_ONLINE;
1905 cgrp->dom_cgrp = cgrp;
1906 cgrp->max_descendants = INT_MAX;
1907 cgrp->max_depth = INT_MAX;
1908 INIT_LIST_HEAD(&cgrp->rstat_css_list);
1909 prev_cputime_init(&cgrp->prev_cputime);
1911 for_each_subsys(ss, ssid)
1912 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1914 init_waitqueue_head(&cgrp->offline_waitq);
1915 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
1918 void init_cgroup_root(struct cgroup_fs_context *ctx)
1920 struct cgroup_root *root = ctx->root;
1921 struct cgroup *cgrp = &root->cgrp;
1923 INIT_LIST_HEAD(&root->root_list);
1924 atomic_set(&root->nr_cgrps, 1);
1926 init_cgroup_housekeeping(cgrp);
1927 idr_init(&root->cgroup_idr);
1929 root->flags = ctx->flags;
1930 if (ctx->release_agent)
1931 strscpy(root->release_agent_path, ctx->release_agent, PATH_MAX);
1933 strscpy(root->name, ctx->name, MAX_CGROUP_ROOT_NAMELEN);
1934 if (ctx->cpuset_clone_children)
1935 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1938 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask)
1940 LIST_HEAD(tmp_links);
1941 struct cgroup *root_cgrp = &root->cgrp;
1942 struct kernfs_syscall_ops *kf_sops;
1943 struct css_set *cset;
1946 lockdep_assert_held(&cgroup_mutex);
1948 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1951 root_cgrp->id = ret;
1952 root_cgrp->ancestor_ids[0] = ret;
1954 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
1960 * We're accessing css_set_count without locking css_set_lock here,
1961 * but that's OK - it can only be increased by someone holding
1962 * cgroup_lock, and that's us. Later rebinding may disable
1963 * controllers on the default hierarchy and thus create new csets,
1964 * which can't be more than the existing ones. Allocate 2x.
1966 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
1970 ret = cgroup_init_root_id(root);
1974 kf_sops = root == &cgrp_dfl_root ?
1975 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
1977 root->kf_root = kernfs_create_root(kf_sops,
1978 KERNFS_ROOT_CREATE_DEACTIVATED |
1979 KERNFS_ROOT_SUPPORT_EXPORTOP,
1981 if (IS_ERR(root->kf_root)) {
1982 ret = PTR_ERR(root->kf_root);
1985 root_cgrp->kn = root->kf_root->kn;
1987 ret = css_populate_dir(&root_cgrp->self);
1991 ret = rebind_subsystems(root, ss_mask);
1995 ret = cgroup_bpf_inherit(root_cgrp);
1998 trace_cgroup_setup_root(root);
2001 * There must be no failure case after here, since rebinding takes
2002 * care of subsystems' refcounts, which are explicitly dropped in
2003 * the failure exit path.
2005 list_add(&root->root_list, &cgroup_roots);
2006 cgroup_root_count++;
2009 * Link the root cgroup in this hierarchy into all the css_set
2012 spin_lock_irq(&css_set_lock);
2013 hash_for_each(css_set_table, i, cset, hlist) {
2014 link_css_set(&tmp_links, cset, root_cgrp);
2015 if (css_set_populated(cset))
2016 cgroup_update_populated(root_cgrp, true);
2018 spin_unlock_irq(&css_set_lock);
2020 BUG_ON(!list_empty(&root_cgrp->self.children));
2021 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
2023 kernfs_activate(root_cgrp->kn);
2028 kernfs_destroy_root(root->kf_root);
2029 root->kf_root = NULL;
2031 cgroup_exit_root_id(root);
2033 percpu_ref_exit(&root_cgrp->self.refcnt);
2035 free_cgrp_cset_links(&tmp_links);
2039 struct dentry *cgroup_do_mount(struct file_system_type *fs_type, int flags,
2040 struct cgroup_root *root, unsigned long magic,
2041 struct cgroup_namespace *ns)
2043 struct dentry *dentry;
2044 bool new_sb = false;
2046 dentry = kernfs_mount(fs_type, flags, root->kf_root, magic, &new_sb);
2049 * In non-init cgroup namespace, instead of root cgroup's dentry,
2050 * we return the dentry corresponding to the cgroupns->root_cgrp.
2052 if (!IS_ERR(dentry) && ns != &init_cgroup_ns) {
2053 struct dentry *nsdentry;
2054 struct super_block *sb = dentry->d_sb;
2055 struct cgroup *cgrp;
2057 mutex_lock(&cgroup_mutex);
2058 spin_lock_irq(&css_set_lock);
2060 cgrp = cset_cgroup_from_root(ns->root_cset, root);
2062 spin_unlock_irq(&css_set_lock);
2063 mutex_unlock(&cgroup_mutex);
2065 nsdentry = kernfs_node_dentry(cgrp->kn, sb);
2067 if (IS_ERR(nsdentry))
2068 deactivate_locked_super(sb);
2073 cgroup_put(&root->cgrp);
2079 * Destroy a cgroup filesystem context.
2081 static void cgroup_fs_context_free(struct fs_context *fc)
2083 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2086 kfree(ctx->release_agent);
2090 static int cgroup_get_tree(struct fs_context *fc)
2092 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
2093 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2094 struct dentry *root;
2096 /* Check if the caller has permission to mount. */
2097 if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN))
2100 cgrp_dfl_visible = true;
2101 cgroup_get_live(&cgrp_dfl_root.cgrp);
2102 ctx->root = &cgrp_dfl_root;
2104 root = cgroup_do_mount(&cgroup2_fs_type, fc->sb_flags, &cgrp_dfl_root,
2105 CGROUP2_SUPER_MAGIC, ns);
2107 return PTR_ERR(root);
2109 apply_cgroup_root_flags(ctx->flags);
2114 static const struct fs_context_operations cgroup_fs_context_ops = {
2115 .free = cgroup_fs_context_free,
2116 .parse_param = cgroup2_parse_param,
2117 .get_tree = cgroup_get_tree,
2118 .reconfigure = cgroup_reconfigure,
2121 static const struct fs_context_operations cgroup1_fs_context_ops = {
2122 .free = cgroup_fs_context_free,
2123 .parse_param = cgroup1_parse_param,
2124 .get_tree = cgroup1_get_tree,
2125 .reconfigure = cgroup1_reconfigure,
2129 * Initialise the cgroup filesystem creation/reconfiguration context.
2131 static int cgroup_init_fs_context(struct fs_context *fc)
2133 struct cgroup_fs_context *ctx;
2135 ctx = kzalloc(sizeof(struct cgroup_fs_context), GFP_KERNEL);
2140 * The first time anyone tries to mount a cgroup, enable the list
2141 * linking each css_set to its tasks and fix up all existing tasks.
2143 if (!use_task_css_set_links)
2144 cgroup_enable_task_cg_lists();
2146 fc->fs_private = ctx;
2147 if (fc->fs_type == &cgroup2_fs_type)
2148 fc->ops = &cgroup_fs_context_ops;
2150 fc->ops = &cgroup1_fs_context_ops;
2154 static void cgroup_kill_sb(struct super_block *sb)
2156 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2157 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2160 * If @root doesn't have any children, start killing it.
2161 * This prevents new mounts by disabling percpu_ref_tryget_live().
2162 * cgroup_mount() may wait for @root's release.
2164 * And don't kill the default root.
2166 if (list_empty(&root->cgrp.self.children) && root != &cgrp_dfl_root &&
2167 !percpu_ref_is_dying(&root->cgrp.self.refcnt))
2168 percpu_ref_kill(&root->cgrp.self.refcnt);
2169 cgroup_put(&root->cgrp);
2173 struct file_system_type cgroup_fs_type = {
2175 .init_fs_context = cgroup_init_fs_context,
2176 .parameters = &cgroup1_fs_parameters,
2177 .kill_sb = cgroup_kill_sb,
2178 .fs_flags = FS_USERNS_MOUNT,
2181 static struct file_system_type cgroup2_fs_type = {
2183 .init_fs_context = cgroup_init_fs_context,
2184 .parameters = &cgroup2_fs_parameters,
2185 .kill_sb = cgroup_kill_sb,
2186 .fs_flags = FS_USERNS_MOUNT,
2189 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2190 struct cgroup_namespace *ns)
2192 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2194 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2197 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2198 struct cgroup_namespace *ns)
2202 mutex_lock(&cgroup_mutex);
2203 spin_lock_irq(&css_set_lock);
2205 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2207 spin_unlock_irq(&css_set_lock);
2208 mutex_unlock(&cgroup_mutex);
2212 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2215 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2216 * @task: target task
2217 * @buf: the buffer to write the path into
2218 * @buflen: the length of the buffer
2220 * Determine @task's cgroup on the first (the one with the lowest non-zero
2221 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2222 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2223 * cgroup controller callbacks.
2225 * Return value is the same as kernfs_path().
2227 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2229 struct cgroup_root *root;
2230 struct cgroup *cgrp;
2231 int hierarchy_id = 1;
2234 mutex_lock(&cgroup_mutex);
2235 spin_lock_irq(&css_set_lock);
2237 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2240 cgrp = task_cgroup_from_root(task, root);
2241 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2243 /* if no hierarchy exists, everyone is in "/" */
2244 ret = strlcpy(buf, "/", buflen);
2247 spin_unlock_irq(&css_set_lock);
2248 mutex_unlock(&cgroup_mutex);
2251 EXPORT_SYMBOL_GPL(task_cgroup_path);
2254 * cgroup_migrate_add_task - add a migration target task to a migration context
2255 * @task: target task
2256 * @mgctx: target migration context
2258 * Add @task, which is a migration target, to @mgctx->tset. This function
2259 * becomes noop if @task doesn't need to be migrated. @task's css_set
2260 * should have been added as a migration source and @task->cg_list will be
2261 * moved from the css_set's tasks list to mg_tasks one.
2263 static void cgroup_migrate_add_task(struct task_struct *task,
2264 struct cgroup_mgctx *mgctx)
2266 struct css_set *cset;
2268 lockdep_assert_held(&css_set_lock);
2270 /* @task either already exited or can't exit until the end */
2271 if (task->flags & PF_EXITING)
2274 /* leave @task alone if post_fork() hasn't linked it yet */
2275 if (list_empty(&task->cg_list))
2278 cset = task_css_set(task);
2279 if (!cset->mg_src_cgrp)
2282 mgctx->tset.nr_tasks++;
2284 list_move_tail(&task->cg_list, &cset->mg_tasks);
2285 if (list_empty(&cset->mg_node))
2286 list_add_tail(&cset->mg_node,
2287 &mgctx->tset.src_csets);
2288 if (list_empty(&cset->mg_dst_cset->mg_node))
2289 list_add_tail(&cset->mg_dst_cset->mg_node,
2290 &mgctx->tset.dst_csets);
2294 * cgroup_taskset_first - reset taskset and return the first task
2295 * @tset: taskset of interest
2296 * @dst_cssp: output variable for the destination css
2298 * @tset iteration is initialized and the first task is returned.
2300 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2301 struct cgroup_subsys_state **dst_cssp)
2303 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2304 tset->cur_task = NULL;
2306 return cgroup_taskset_next(tset, dst_cssp);
2310 * cgroup_taskset_next - iterate to the next task in taskset
2311 * @tset: taskset of interest
2312 * @dst_cssp: output variable for the destination css
2314 * Return the next task in @tset. Iteration must have been initialized
2315 * with cgroup_taskset_first().
2317 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2318 struct cgroup_subsys_state **dst_cssp)
2320 struct css_set *cset = tset->cur_cset;
2321 struct task_struct *task = tset->cur_task;
2323 while (&cset->mg_node != tset->csets) {
2325 task = list_first_entry(&cset->mg_tasks,
2326 struct task_struct, cg_list);
2328 task = list_next_entry(task, cg_list);
2330 if (&task->cg_list != &cset->mg_tasks) {
2331 tset->cur_cset = cset;
2332 tset->cur_task = task;
2335 * This function may be called both before and
2336 * after cgroup_taskset_migrate(). The two cases
2337 * can be distinguished by looking at whether @cset
2338 * has its ->mg_dst_cset set.
2340 if (cset->mg_dst_cset)
2341 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2343 *dst_cssp = cset->subsys[tset->ssid];
2348 cset = list_next_entry(cset, mg_node);
2356 * cgroup_taskset_migrate - migrate a taskset
2357 * @mgctx: migration context
2359 * Migrate tasks in @mgctx as setup by migration preparation functions.
2360 * This function fails iff one of the ->can_attach callbacks fails and
2361 * guarantees that either all or none of the tasks in @mgctx are migrated.
2362 * @mgctx is consumed regardless of success.
2364 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2366 struct cgroup_taskset *tset = &mgctx->tset;
2367 struct cgroup_subsys *ss;
2368 struct task_struct *task, *tmp_task;
2369 struct css_set *cset, *tmp_cset;
2370 int ssid, failed_ssid, ret;
2372 /* check that we can legitimately attach to the cgroup */
2373 if (tset->nr_tasks) {
2374 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2375 if (ss->can_attach) {
2377 ret = ss->can_attach(tset);
2380 goto out_cancel_attach;
2383 } while_each_subsys_mask();
2387 * Now that we're guaranteed success, proceed to move all tasks to
2388 * the new cgroup. There are no failure cases after here, so this
2389 * is the commit point.
2391 spin_lock_irq(&css_set_lock);
2392 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2393 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2394 struct css_set *from_cset = task_css_set(task);
2395 struct css_set *to_cset = cset->mg_dst_cset;
2397 get_css_set(to_cset);
2398 to_cset->nr_tasks++;
2399 css_set_move_task(task, from_cset, to_cset, true);
2400 put_css_set_locked(from_cset);
2401 from_cset->nr_tasks--;
2404 spin_unlock_irq(&css_set_lock);
2407 * Migration is committed, all target tasks are now on dst_csets.
2408 * Nothing is sensitive to fork() after this point. Notify
2409 * controllers that migration is complete.
2411 tset->csets = &tset->dst_csets;
2413 if (tset->nr_tasks) {
2414 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2419 } while_each_subsys_mask();
2423 goto out_release_tset;
2426 if (tset->nr_tasks) {
2427 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2428 if (ssid == failed_ssid)
2430 if (ss->cancel_attach) {
2432 ss->cancel_attach(tset);
2434 } while_each_subsys_mask();
2437 spin_lock_irq(&css_set_lock);
2438 list_splice_init(&tset->dst_csets, &tset->src_csets);
2439 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2440 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2441 list_del_init(&cset->mg_node);
2443 spin_unlock_irq(&css_set_lock);
2446 * Re-initialize the cgroup_taskset structure in case it is reused
2447 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2451 tset->csets = &tset->src_csets;
2456 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2457 * @dst_cgrp: destination cgroup to test
2459 * On the default hierarchy, except for the mixable, (possible) thread root
2460 * and threaded cgroups, subtree_control must be zero for migration
2461 * destination cgroups with tasks so that child cgroups don't compete
2464 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2466 /* v1 doesn't have any restriction */
2467 if (!cgroup_on_dfl(dst_cgrp))
2470 /* verify @dst_cgrp can host resources */
2471 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2474 /* mixables don't care */
2475 if (cgroup_is_mixable(dst_cgrp))
2479 * If @dst_cgrp is already or can become a thread root or is
2480 * threaded, it doesn't matter.
2482 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2485 /* apply no-internal-process constraint */
2486 if (dst_cgrp->subtree_control)
2493 * cgroup_migrate_finish - cleanup after attach
2494 * @mgctx: migration context
2496 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2497 * those functions for details.
2499 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2501 LIST_HEAD(preloaded);
2502 struct css_set *cset, *tmp_cset;
2504 lockdep_assert_held(&cgroup_mutex);
2506 spin_lock_irq(&css_set_lock);
2508 list_splice_tail_init(&mgctx->preloaded_src_csets, &preloaded);
2509 list_splice_tail_init(&mgctx->preloaded_dst_csets, &preloaded);
2511 list_for_each_entry_safe(cset, tmp_cset, &preloaded, mg_preload_node) {
2512 cset->mg_src_cgrp = NULL;
2513 cset->mg_dst_cgrp = NULL;
2514 cset->mg_dst_cset = NULL;
2515 list_del_init(&cset->mg_preload_node);
2516 put_css_set_locked(cset);
2519 spin_unlock_irq(&css_set_lock);
2523 * cgroup_migrate_add_src - add a migration source css_set
2524 * @src_cset: the source css_set to add
2525 * @dst_cgrp: the destination cgroup
2526 * @mgctx: migration context
2528 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2529 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2530 * up by cgroup_migrate_finish().
2532 * This function may be called without holding cgroup_threadgroup_rwsem
2533 * even if the target is a process. Threads may be created and destroyed
2534 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2535 * into play and the preloaded css_sets are guaranteed to cover all
2538 void cgroup_migrate_add_src(struct css_set *src_cset,
2539 struct cgroup *dst_cgrp,
2540 struct cgroup_mgctx *mgctx)
2542 struct cgroup *src_cgrp;
2544 lockdep_assert_held(&cgroup_mutex);
2545 lockdep_assert_held(&css_set_lock);
2548 * If ->dead, @src_set is associated with one or more dead cgroups
2549 * and doesn't contain any migratable tasks. Ignore it early so
2550 * that the rest of migration path doesn't get confused by it.
2555 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2557 if (!list_empty(&src_cset->mg_preload_node))
2560 WARN_ON(src_cset->mg_src_cgrp);
2561 WARN_ON(src_cset->mg_dst_cgrp);
2562 WARN_ON(!list_empty(&src_cset->mg_tasks));
2563 WARN_ON(!list_empty(&src_cset->mg_node));
2565 src_cset->mg_src_cgrp = src_cgrp;
2566 src_cset->mg_dst_cgrp = dst_cgrp;
2567 get_css_set(src_cset);
2568 list_add_tail(&src_cset->mg_preload_node, &mgctx->preloaded_src_csets);
2572 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2573 * @mgctx: migration context
2575 * Tasks are about to be moved and all the source css_sets have been
2576 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2577 * pins all destination css_sets, links each to its source, and append them
2578 * to @mgctx->preloaded_dst_csets.
2580 * This function must be called after cgroup_migrate_add_src() has been
2581 * called on each migration source css_set. After migration is performed
2582 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2585 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2587 struct css_set *src_cset, *tmp_cset;
2589 lockdep_assert_held(&cgroup_mutex);
2591 /* look up the dst cset for each src cset and link it to src */
2592 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2594 struct css_set *dst_cset;
2595 struct cgroup_subsys *ss;
2598 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2602 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2605 * If src cset equals dst, it's noop. Drop the src.
2606 * cgroup_migrate() will skip the cset too. Note that we
2607 * can't handle src == dst as some nodes are used by both.
2609 if (src_cset == dst_cset) {
2610 src_cset->mg_src_cgrp = NULL;
2611 src_cset->mg_dst_cgrp = NULL;
2612 list_del_init(&src_cset->mg_preload_node);
2613 put_css_set(src_cset);
2614 put_css_set(dst_cset);
2618 src_cset->mg_dst_cset = dst_cset;
2620 if (list_empty(&dst_cset->mg_preload_node))
2621 list_add_tail(&dst_cset->mg_preload_node,
2622 &mgctx->preloaded_dst_csets);
2624 put_css_set(dst_cset);
2626 for_each_subsys(ss, ssid)
2627 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2628 mgctx->ss_mask |= 1 << ssid;
2633 cgroup_migrate_finish(mgctx);
2638 * cgroup_migrate - migrate a process or task to a cgroup
2639 * @leader: the leader of the process or the task to migrate
2640 * @threadgroup: whether @leader points to the whole process or a single task
2641 * @mgctx: migration context
2643 * Migrate a process or task denoted by @leader. If migrating a process,
2644 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2645 * responsible for invoking cgroup_migrate_add_src() and
2646 * cgroup_migrate_prepare_dst() on the targets before invoking this
2647 * function and following up with cgroup_migrate_finish().
2649 * As long as a controller's ->can_attach() doesn't fail, this function is
2650 * guaranteed to succeed. This means that, excluding ->can_attach()
2651 * failure, when migrating multiple targets, the success or failure can be
2652 * decided for all targets by invoking group_migrate_prepare_dst() before
2653 * actually starting migrating.
2655 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2656 struct cgroup_mgctx *mgctx)
2658 struct task_struct *task;
2661 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2662 * already PF_EXITING could be freed from underneath us unless we
2663 * take an rcu_read_lock.
2665 spin_lock_irq(&css_set_lock);
2669 cgroup_migrate_add_task(task, mgctx);
2672 } while_each_thread(leader, task);
2674 spin_unlock_irq(&css_set_lock);
2676 return cgroup_migrate_execute(mgctx);
2680 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2681 * @dst_cgrp: the cgroup to attach to
2682 * @leader: the task or the leader of the threadgroup to be attached
2683 * @threadgroup: attach the whole threadgroup?
2685 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2687 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2690 DEFINE_CGROUP_MGCTX(mgctx);
2691 struct task_struct *task;
2694 ret = cgroup_migrate_vet_dst(dst_cgrp);
2698 /* look up all src csets */
2699 spin_lock_irq(&css_set_lock);
2703 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2706 } while_each_thread(leader, task);
2708 spin_unlock_irq(&css_set_lock);
2710 /* prepare dst csets and commit */
2711 ret = cgroup_migrate_prepare_dst(&mgctx);
2713 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2715 cgroup_migrate_finish(&mgctx);
2718 TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
2723 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup)
2724 __acquires(&cgroup_threadgroup_rwsem)
2726 struct task_struct *tsk;
2729 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2730 return ERR_PTR(-EINVAL);
2732 percpu_down_write(&cgroup_threadgroup_rwsem);
2736 tsk = find_task_by_vpid(pid);
2738 tsk = ERR_PTR(-ESRCH);
2739 goto out_unlock_threadgroup;
2746 tsk = tsk->group_leader;
2749 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2750 * If userland migrates such a kthread to a non-root cgroup, it can
2751 * become trapped in a cpuset, or RT kthread may be born in a
2752 * cgroup with no rt_runtime allocated. Just say no.
2754 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2755 tsk = ERR_PTR(-EINVAL);
2756 goto out_unlock_threadgroup;
2759 get_task_struct(tsk);
2760 goto out_unlock_rcu;
2762 out_unlock_threadgroup:
2763 percpu_up_write(&cgroup_threadgroup_rwsem);
2769 void cgroup_procs_write_finish(struct task_struct *task)
2770 __releases(&cgroup_threadgroup_rwsem)
2772 struct cgroup_subsys *ss;
2775 /* release reference from cgroup_procs_write_start() */
2776 put_task_struct(task);
2778 percpu_up_write(&cgroup_threadgroup_rwsem);
2779 for_each_subsys(ss, ssid)
2780 if (ss->post_attach)
2784 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2786 struct cgroup_subsys *ss;
2787 bool printed = false;
2790 do_each_subsys_mask(ss, ssid, ss_mask) {
2793 seq_printf(seq, "%s", ss->name);
2795 } while_each_subsys_mask();
2797 seq_putc(seq, '\n');
2800 /* show controllers which are enabled from the parent */
2801 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2803 struct cgroup *cgrp = seq_css(seq)->cgroup;
2805 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2809 /* show controllers which are enabled for a given cgroup's children */
2810 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2812 struct cgroup *cgrp = seq_css(seq)->cgroup;
2814 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2819 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2820 * @cgrp: root of the subtree to update csses for
2822 * @cgrp's control masks have changed and its subtree's css associations
2823 * need to be updated accordingly. This function looks up all css_sets
2824 * which are attached to the subtree, creates the matching updated css_sets
2825 * and migrates the tasks to the new ones.
2827 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2829 DEFINE_CGROUP_MGCTX(mgctx);
2830 struct cgroup_subsys_state *d_css;
2831 struct cgroup *dsct;
2832 struct css_set *src_cset;
2835 lockdep_assert_held(&cgroup_mutex);
2837 percpu_down_write(&cgroup_threadgroup_rwsem);
2839 /* look up all csses currently attached to @cgrp's subtree */
2840 spin_lock_irq(&css_set_lock);
2841 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2842 struct cgrp_cset_link *link;
2844 list_for_each_entry(link, &dsct->cset_links, cset_link)
2845 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2847 spin_unlock_irq(&css_set_lock);
2849 /* NULL dst indicates self on default hierarchy */
2850 ret = cgroup_migrate_prepare_dst(&mgctx);
2854 spin_lock_irq(&css_set_lock);
2855 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets, mg_preload_node) {
2856 struct task_struct *task, *ntask;
2858 /* all tasks in src_csets need to be migrated */
2859 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2860 cgroup_migrate_add_task(task, &mgctx);
2862 spin_unlock_irq(&css_set_lock);
2864 ret = cgroup_migrate_execute(&mgctx);
2866 cgroup_migrate_finish(&mgctx);
2867 percpu_up_write(&cgroup_threadgroup_rwsem);
2872 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2873 * @cgrp: root of the target subtree
2875 * Because css offlining is asynchronous, userland may try to re-enable a
2876 * controller while the previous css is still around. This function grabs
2877 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2879 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2880 __acquires(&cgroup_mutex)
2882 struct cgroup *dsct;
2883 struct cgroup_subsys_state *d_css;
2884 struct cgroup_subsys *ss;
2888 mutex_lock(&cgroup_mutex);
2890 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2891 for_each_subsys(ss, ssid) {
2892 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2895 if (!css || !percpu_ref_is_dying(&css->refcnt))
2898 cgroup_get_live(dsct);
2899 prepare_to_wait(&dsct->offline_waitq, &wait,
2900 TASK_UNINTERRUPTIBLE);
2902 mutex_unlock(&cgroup_mutex);
2904 finish_wait(&dsct->offline_waitq, &wait);
2913 * cgroup_save_control - save control masks and dom_cgrp of a subtree
2914 * @cgrp: root of the target subtree
2916 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
2917 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2920 static void cgroup_save_control(struct cgroup *cgrp)
2922 struct cgroup *dsct;
2923 struct cgroup_subsys_state *d_css;
2925 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2926 dsct->old_subtree_control = dsct->subtree_control;
2927 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
2928 dsct->old_dom_cgrp = dsct->dom_cgrp;
2933 * cgroup_propagate_control - refresh control masks of a subtree
2934 * @cgrp: root of the target subtree
2936 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
2937 * ->subtree_control and propagate controller availability through the
2938 * subtree so that descendants don't have unavailable controllers enabled.
2940 static void cgroup_propagate_control(struct cgroup *cgrp)
2942 struct cgroup *dsct;
2943 struct cgroup_subsys_state *d_css;
2945 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2946 dsct->subtree_control &= cgroup_control(dsct);
2947 dsct->subtree_ss_mask =
2948 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
2949 cgroup_ss_mask(dsct));
2954 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
2955 * @cgrp: root of the target subtree
2957 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
2958 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2961 static void cgroup_restore_control(struct cgroup *cgrp)
2963 struct cgroup *dsct;
2964 struct cgroup_subsys_state *d_css;
2966 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2967 dsct->subtree_control = dsct->old_subtree_control;
2968 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
2969 dsct->dom_cgrp = dsct->old_dom_cgrp;
2973 static bool css_visible(struct cgroup_subsys_state *css)
2975 struct cgroup_subsys *ss = css->ss;
2976 struct cgroup *cgrp = css->cgroup;
2978 if (cgroup_control(cgrp) & (1 << ss->id))
2980 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
2982 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
2986 * cgroup_apply_control_enable - enable or show csses according to control
2987 * @cgrp: root of the target subtree
2989 * Walk @cgrp's subtree and create new csses or make the existing ones
2990 * visible. A css is created invisible if it's being implicitly enabled
2991 * through dependency. An invisible css is made visible when the userland
2992 * explicitly enables it.
2994 * Returns 0 on success, -errno on failure. On failure, csses which have
2995 * been processed already aren't cleaned up. The caller is responsible for
2996 * cleaning up with cgroup_apply_control_disable().
2998 static int cgroup_apply_control_enable(struct cgroup *cgrp)
3000 struct cgroup *dsct;
3001 struct cgroup_subsys_state *d_css;
3002 struct cgroup_subsys *ss;
3005 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3006 for_each_subsys(ss, ssid) {
3007 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3009 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
3011 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
3015 css = css_create(dsct, ss);
3017 return PTR_ERR(css);
3020 if (css_visible(css)) {
3021 ret = css_populate_dir(css);
3032 * cgroup_apply_control_disable - kill or hide csses according to control
3033 * @cgrp: root of the target subtree
3035 * Walk @cgrp's subtree and kill and hide csses so that they match
3036 * cgroup_ss_mask() and cgroup_visible_mask().
3038 * A css is hidden when the userland requests it to be disabled while other
3039 * subsystems are still depending on it. The css must not actively control
3040 * resources and be in the vanilla state if it's made visible again later.
3041 * Controllers which may be depended upon should provide ->css_reset() for
3044 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3046 struct cgroup *dsct;
3047 struct cgroup_subsys_state *d_css;
3048 struct cgroup_subsys *ss;
3051 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3052 for_each_subsys(ss, ssid) {
3053 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3055 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
3061 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3063 } else if (!css_visible(css)) {
3073 * cgroup_apply_control - apply control mask updates to the subtree
3074 * @cgrp: root of the target subtree
3076 * subsystems can be enabled and disabled in a subtree using the following
3079 * 1. Call cgroup_save_control() to stash the current state.
3080 * 2. Update ->subtree_control masks in the subtree as desired.
3081 * 3. Call cgroup_apply_control() to apply the changes.
3082 * 4. Optionally perform other related operations.
3083 * 5. Call cgroup_finalize_control() to finish up.
3085 * This function implements step 3 and propagates the mask changes
3086 * throughout @cgrp's subtree, updates csses accordingly and perform
3087 * process migrations.
3089 static int cgroup_apply_control(struct cgroup *cgrp)
3093 cgroup_propagate_control(cgrp);
3095 ret = cgroup_apply_control_enable(cgrp);
3100 * At this point, cgroup_e_css_by_mask() results reflect the new csses
3101 * making the following cgroup_update_dfl_csses() properly update
3102 * css associations of all tasks in the subtree.
3104 ret = cgroup_update_dfl_csses(cgrp);
3112 * cgroup_finalize_control - finalize control mask update
3113 * @cgrp: root of the target subtree
3114 * @ret: the result of the update
3116 * Finalize control mask update. See cgroup_apply_control() for more info.
3118 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3121 cgroup_restore_control(cgrp);
3122 cgroup_propagate_control(cgrp);
3125 cgroup_apply_control_disable(cgrp);
3128 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3130 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3132 /* if nothing is getting enabled, nothing to worry about */
3136 /* can @cgrp host any resources? */
3137 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3140 /* mixables don't care */
3141 if (cgroup_is_mixable(cgrp))
3144 if (domain_enable) {
3145 /* can't enable domain controllers inside a thread subtree */
3146 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3150 * Threaded controllers can handle internal competitions
3151 * and are always allowed inside a (prospective) thread
3154 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3159 * Controllers can't be enabled for a cgroup with tasks to avoid
3160 * child cgroups competing against tasks.
3162 if (cgroup_has_tasks(cgrp))
3168 /* change the enabled child controllers for a cgroup in the default hierarchy */
3169 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3170 char *buf, size_t nbytes,
3173 u16 enable = 0, disable = 0;
3174 struct cgroup *cgrp, *child;
3175 struct cgroup_subsys *ss;
3180 * Parse input - space separated list of subsystem names prefixed
3181 * with either + or -.
3183 buf = strstrip(buf);
3184 while ((tok = strsep(&buf, " "))) {
3187 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3188 if (!cgroup_ssid_enabled(ssid) ||
3189 strcmp(tok + 1, ss->name))
3193 enable |= 1 << ssid;
3194 disable &= ~(1 << ssid);
3195 } else if (*tok == '-') {
3196 disable |= 1 << ssid;
3197 enable &= ~(1 << ssid);
3202 } while_each_subsys_mask();
3203 if (ssid == CGROUP_SUBSYS_COUNT)
3207 cgrp = cgroup_kn_lock_live(of->kn, true);
3211 for_each_subsys(ss, ssid) {
3212 if (enable & (1 << ssid)) {
3213 if (cgrp->subtree_control & (1 << ssid)) {
3214 enable &= ~(1 << ssid);
3218 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3222 } else if (disable & (1 << ssid)) {
3223 if (!(cgrp->subtree_control & (1 << ssid))) {
3224 disable &= ~(1 << ssid);
3228 /* a child has it enabled? */
3229 cgroup_for_each_live_child(child, cgrp) {
3230 if (child->subtree_control & (1 << ssid)) {
3238 if (!enable && !disable) {
3243 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3247 /* save and update control masks and prepare csses */
3248 cgroup_save_control(cgrp);
3250 cgrp->subtree_control |= enable;
3251 cgrp->subtree_control &= ~disable;
3253 ret = cgroup_apply_control(cgrp);
3254 cgroup_finalize_control(cgrp, ret);
3258 kernfs_activate(cgrp->kn);
3260 cgroup_kn_unlock(of->kn);
3261 return ret ?: nbytes;
3265 * cgroup_enable_threaded - make @cgrp threaded
3266 * @cgrp: the target cgroup
3268 * Called when "threaded" is written to the cgroup.type interface file and
3269 * tries to make @cgrp threaded and join the parent's resource domain.
3270 * This function is never called on the root cgroup as cgroup.type doesn't
3273 static int cgroup_enable_threaded(struct cgroup *cgrp)
3275 struct cgroup *parent = cgroup_parent(cgrp);
3276 struct cgroup *dom_cgrp = parent->dom_cgrp;
3277 struct cgroup *dsct;
3278 struct cgroup_subsys_state *d_css;
3281 lockdep_assert_held(&cgroup_mutex);
3283 /* noop if already threaded */
3284 if (cgroup_is_threaded(cgrp))
3288 * If @cgroup is populated or has domain controllers enabled, it
3289 * can't be switched. While the below cgroup_can_be_thread_root()
3290 * test can catch the same conditions, that's only when @parent is
3291 * not mixable, so let's check it explicitly.
3293 if (cgroup_is_populated(cgrp) ||
3294 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3297 /* we're joining the parent's domain, ensure its validity */
3298 if (!cgroup_is_valid_domain(dom_cgrp) ||
3299 !cgroup_can_be_thread_root(dom_cgrp))
3303 * The following shouldn't cause actual migrations and should
3306 cgroup_save_control(cgrp);
3308 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3309 if (dsct == cgrp || cgroup_is_threaded(dsct))
3310 dsct->dom_cgrp = dom_cgrp;
3312 ret = cgroup_apply_control(cgrp);
3314 parent->nr_threaded_children++;
3316 cgroup_finalize_control(cgrp, ret);
3320 static int cgroup_type_show(struct seq_file *seq, void *v)
3322 struct cgroup *cgrp = seq_css(seq)->cgroup;
3324 if (cgroup_is_threaded(cgrp))
3325 seq_puts(seq, "threaded\n");
3326 else if (!cgroup_is_valid_domain(cgrp))
3327 seq_puts(seq, "domain invalid\n");
3328 else if (cgroup_is_thread_root(cgrp))
3329 seq_puts(seq, "domain threaded\n");
3331 seq_puts(seq, "domain\n");
3336 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3337 size_t nbytes, loff_t off)
3339 struct cgroup *cgrp;
3342 /* only switching to threaded mode is supported */
3343 if (strcmp(strstrip(buf), "threaded"))
3346 cgrp = cgroup_kn_lock_live(of->kn, false);
3350 /* threaded can only be enabled */
3351 ret = cgroup_enable_threaded(cgrp);
3353 cgroup_kn_unlock(of->kn);
3354 return ret ?: nbytes;
3357 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3359 struct cgroup *cgrp = seq_css(seq)->cgroup;
3360 int descendants = READ_ONCE(cgrp->max_descendants);
3362 if (descendants == INT_MAX)
3363 seq_puts(seq, "max\n");
3365 seq_printf(seq, "%d\n", descendants);
3370 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3371 char *buf, size_t nbytes, loff_t off)
3373 struct cgroup *cgrp;
3377 buf = strstrip(buf);
3378 if (!strcmp(buf, "max")) {
3379 descendants = INT_MAX;
3381 ret = kstrtoint(buf, 0, &descendants);
3386 if (descendants < 0)
3389 cgrp = cgroup_kn_lock_live(of->kn, false);
3393 cgrp->max_descendants = descendants;
3395 cgroup_kn_unlock(of->kn);
3400 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3402 struct cgroup *cgrp = seq_css(seq)->cgroup;
3403 int depth = READ_ONCE(cgrp->max_depth);
3405 if (depth == INT_MAX)
3406 seq_puts(seq, "max\n");
3408 seq_printf(seq, "%d\n", depth);
3413 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3414 char *buf, size_t nbytes, loff_t off)
3416 struct cgroup *cgrp;
3420 buf = strstrip(buf);
3421 if (!strcmp(buf, "max")) {
3424 ret = kstrtoint(buf, 0, &depth);
3432 cgrp = cgroup_kn_lock_live(of->kn, false);
3436 cgrp->max_depth = depth;
3438 cgroup_kn_unlock(of->kn);
3443 static int cgroup_events_show(struct seq_file *seq, void *v)
3445 seq_printf(seq, "populated %d\n",
3446 cgroup_is_populated(seq_css(seq)->cgroup));
3450 static int cgroup_stat_show(struct seq_file *seq, void *v)
3452 struct cgroup *cgroup = seq_css(seq)->cgroup;
3454 seq_printf(seq, "nr_descendants %d\n",
3455 cgroup->nr_descendants);
3456 seq_printf(seq, "nr_dying_descendants %d\n",
3457 cgroup->nr_dying_descendants);
3462 static int __maybe_unused cgroup_extra_stat_show(struct seq_file *seq,
3463 struct cgroup *cgrp, int ssid)
3465 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3466 struct cgroup_subsys_state *css;
3469 if (!ss->css_extra_stat_show)
3472 css = cgroup_tryget_css(cgrp, ss);
3476 ret = ss->css_extra_stat_show(seq, css);
3481 static int cpu_stat_show(struct seq_file *seq, void *v)
3483 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3486 cgroup_base_stat_cputime_show(seq);
3487 #ifdef CONFIG_CGROUP_SCHED
3488 ret = cgroup_extra_stat_show(seq, cgrp, cpu_cgrp_id);
3494 static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
3496 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_IO);
3498 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
3500 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_MEM);
3502 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
3504 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_CPU);
3508 static int cgroup_file_open(struct kernfs_open_file *of)
3510 struct cftype *cft = of->kn->priv;
3513 return cft->open(of);
3517 static void cgroup_file_release(struct kernfs_open_file *of)
3519 struct cftype *cft = of->kn->priv;
3525 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3526 size_t nbytes, loff_t off)
3528 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
3529 struct cgroup *cgrp = of->kn->parent->priv;
3530 struct cftype *cft = of->kn->priv;
3531 struct cgroup_subsys_state *css;
3535 * If namespaces are delegation boundaries, disallow writes to
3536 * files in an non-init namespace root from inside the namespace
3537 * except for the files explicitly marked delegatable -
3538 * cgroup.procs and cgroup.subtree_control.
3540 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3541 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3542 ns != &init_cgroup_ns && ns->root_cset->dfl_cgrp == cgrp)
3546 return cft->write(of, buf, nbytes, off);
3549 * kernfs guarantees that a file isn't deleted with operations in
3550 * flight, which means that the matching css is and stays alive and
3551 * doesn't need to be pinned. The RCU locking is not necessary
3552 * either. It's just for the convenience of using cgroup_css().
3555 css = cgroup_css(cgrp, cft->ss);
3558 if (cft->write_u64) {
3559 unsigned long long v;
3560 ret = kstrtoull(buf, 0, &v);
3562 ret = cft->write_u64(css, cft, v);
3563 } else if (cft->write_s64) {
3565 ret = kstrtoll(buf, 0, &v);
3567 ret = cft->write_s64(css, cft, v);
3572 return ret ?: nbytes;
3575 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3577 return seq_cft(seq)->seq_start(seq, ppos);
3580 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3582 return seq_cft(seq)->seq_next(seq, v, ppos);
3585 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3587 if (seq_cft(seq)->seq_stop)
3588 seq_cft(seq)->seq_stop(seq, v);
3591 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3593 struct cftype *cft = seq_cft(m);
3594 struct cgroup_subsys_state *css = seq_css(m);
3597 return cft->seq_show(m, arg);
3600 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3601 else if (cft->read_s64)
3602 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3608 static struct kernfs_ops cgroup_kf_single_ops = {
3609 .atomic_write_len = PAGE_SIZE,
3610 .open = cgroup_file_open,
3611 .release = cgroup_file_release,
3612 .write = cgroup_file_write,
3613 .seq_show = cgroup_seqfile_show,
3616 static struct kernfs_ops cgroup_kf_ops = {
3617 .atomic_write_len = PAGE_SIZE,
3618 .open = cgroup_file_open,
3619 .release = cgroup_file_release,
3620 .write = cgroup_file_write,
3621 .seq_start = cgroup_seqfile_start,
3622 .seq_next = cgroup_seqfile_next,
3623 .seq_stop = cgroup_seqfile_stop,
3624 .seq_show = cgroup_seqfile_show,
3627 /* set uid and gid of cgroup dirs and files to that of the creator */
3628 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3630 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3631 .ia_uid = current_fsuid(),
3632 .ia_gid = current_fsgid(), };
3634 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3635 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3638 return kernfs_setattr(kn, &iattr);
3641 static void cgroup_file_notify_timer(struct timer_list *timer)
3643 cgroup_file_notify(container_of(timer, struct cgroup_file,
3647 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
3650 char name[CGROUP_FILE_NAME_MAX];
3651 struct kernfs_node *kn;
3652 struct lock_class_key *key = NULL;
3655 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3656 key = &cft->lockdep_key;
3658 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3659 cgroup_file_mode(cft),
3660 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
3661 0, cft->kf_ops, cft,
3666 ret = cgroup_kn_set_ugid(kn);
3672 if (cft->file_offset) {
3673 struct cgroup_file *cfile = (void *)css + cft->file_offset;
3675 timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
3677 spin_lock_irq(&cgroup_file_kn_lock);
3679 spin_unlock_irq(&cgroup_file_kn_lock);
3686 * cgroup_addrm_files - add or remove files to a cgroup directory
3687 * @css: the target css
3688 * @cgrp: the target cgroup (usually css->cgroup)
3689 * @cfts: array of cftypes to be added
3690 * @is_add: whether to add or remove
3692 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3693 * For removals, this function never fails.
3695 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
3696 struct cgroup *cgrp, struct cftype cfts[],
3699 struct cftype *cft, *cft_end = NULL;
3702 lockdep_assert_held(&cgroup_mutex);
3705 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
3706 /* does cft->flags tell us to skip this file on @cgrp? */
3707 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3709 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3711 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3713 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3715 if ((cft->flags & CFTYPE_DEBUG) && !cgroup_debug)
3718 ret = cgroup_add_file(css, cgrp, cft);
3720 pr_warn("%s: failed to add %s, err=%d\n",
3721 __func__, cft->name, ret);
3727 cgroup_rm_file(cgrp, cft);
3733 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3735 struct cgroup_subsys *ss = cfts[0].ss;
3736 struct cgroup *root = &ss->root->cgrp;
3737 struct cgroup_subsys_state *css;
3740 lockdep_assert_held(&cgroup_mutex);
3742 /* add/rm files for all cgroups created before */
3743 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3744 struct cgroup *cgrp = css->cgroup;
3746 if (!(css->flags & CSS_VISIBLE))
3749 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
3755 kernfs_activate(root->kn);
3759 static void cgroup_exit_cftypes(struct cftype *cfts)
3763 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3764 /* free copy for custom atomic_write_len, see init_cftypes() */
3765 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3770 /* revert flags set by cgroup core while adding @cfts */
3771 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3775 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3779 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3780 struct kernfs_ops *kf_ops;
3782 WARN_ON(cft->ss || cft->kf_ops);
3785 kf_ops = &cgroup_kf_ops;
3787 kf_ops = &cgroup_kf_single_ops;
3790 * Ugh... if @cft wants a custom max_write_len, we need to
3791 * make a copy of kf_ops to set its atomic_write_len.
3793 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3794 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3796 cgroup_exit_cftypes(cfts);
3799 kf_ops->atomic_write_len = cft->max_write_len;
3802 cft->kf_ops = kf_ops;
3809 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3811 lockdep_assert_held(&cgroup_mutex);
3813 if (!cfts || !cfts[0].ss)
3816 list_del(&cfts->node);
3817 cgroup_apply_cftypes(cfts, false);
3818 cgroup_exit_cftypes(cfts);
3823 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3824 * @cfts: zero-length name terminated array of cftypes
3826 * Unregister @cfts. Files described by @cfts are removed from all
3827 * existing cgroups and all future cgroups won't have them either. This
3828 * function can be called anytime whether @cfts' subsys is attached or not.
3830 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3833 int cgroup_rm_cftypes(struct cftype *cfts)
3837 mutex_lock(&cgroup_mutex);
3838 ret = cgroup_rm_cftypes_locked(cfts);
3839 mutex_unlock(&cgroup_mutex);
3844 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3845 * @ss: target cgroup subsystem
3846 * @cfts: zero-length name terminated array of cftypes
3848 * Register @cfts to @ss. Files described by @cfts are created for all
3849 * existing cgroups to which @ss is attached and all future cgroups will
3850 * have them too. This function can be called anytime whether @ss is
3853 * Returns 0 on successful registration, -errno on failure. Note that this
3854 * function currently returns 0 as long as @cfts registration is successful
3855 * even if some file creation attempts on existing cgroups fail.
3857 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3861 if (!cgroup_ssid_enabled(ss->id))
3864 if (!cfts || cfts[0].name[0] == '\0')
3867 ret = cgroup_init_cftypes(ss, cfts);
3871 mutex_lock(&cgroup_mutex);
3873 list_add_tail(&cfts->node, &ss->cfts);
3874 ret = cgroup_apply_cftypes(cfts, true);
3876 cgroup_rm_cftypes_locked(cfts);
3878 mutex_unlock(&cgroup_mutex);
3883 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3884 * @ss: target cgroup subsystem
3885 * @cfts: zero-length name terminated array of cftypes
3887 * Similar to cgroup_add_cftypes() but the added files are only used for
3888 * the default hierarchy.
3890 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3894 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3895 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3896 return cgroup_add_cftypes(ss, cfts);
3900 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3901 * @ss: target cgroup subsystem
3902 * @cfts: zero-length name terminated array of cftypes
3904 * Similar to cgroup_add_cftypes() but the added files are only used for
3905 * the legacy hierarchies.
3907 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3911 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3912 cft->flags |= __CFTYPE_NOT_ON_DFL;
3913 return cgroup_add_cftypes(ss, cfts);
3917 * cgroup_file_notify - generate a file modified event for a cgroup_file
3918 * @cfile: target cgroup_file
3920 * @cfile must have been obtained by setting cftype->file_offset.
3922 void cgroup_file_notify(struct cgroup_file *cfile)
3924 unsigned long flags;
3926 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
3928 unsigned long last = cfile->notified_at;
3929 unsigned long next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
3931 if (time_in_range(jiffies, last, next)) {
3932 timer_reduce(&cfile->notify_timer, next);
3934 kernfs_notify(cfile->kn);
3935 cfile->notified_at = jiffies;
3938 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
3942 * css_next_child - find the next child of a given css
3943 * @pos: the current position (%NULL to initiate traversal)
3944 * @parent: css whose children to walk
3946 * This function returns the next child of @parent and should be called
3947 * under either cgroup_mutex or RCU read lock. The only requirement is
3948 * that @parent and @pos are accessible. The next sibling is guaranteed to
3949 * be returned regardless of their states.
3951 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3952 * css which finished ->css_online() is guaranteed to be visible in the
3953 * future iterations and will stay visible until the last reference is put.
3954 * A css which hasn't finished ->css_online() or already finished
3955 * ->css_offline() may show up during traversal. It's each subsystem's
3956 * responsibility to synchronize against on/offlining.
3958 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3959 struct cgroup_subsys_state *parent)
3961 struct cgroup_subsys_state *next;
3963 cgroup_assert_mutex_or_rcu_locked();
3966 * @pos could already have been unlinked from the sibling list.
3967 * Once a cgroup is removed, its ->sibling.next is no longer
3968 * updated when its next sibling changes. CSS_RELEASED is set when
3969 * @pos is taken off list, at which time its next pointer is valid,
3970 * and, as releases are serialized, the one pointed to by the next
3971 * pointer is guaranteed to not have started release yet. This
3972 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3973 * critical section, the one pointed to by its next pointer is
3974 * guaranteed to not have finished its RCU grace period even if we
3975 * have dropped rcu_read_lock() inbetween iterations.
3977 * If @pos has CSS_RELEASED set, its next pointer can't be
3978 * dereferenced; however, as each css is given a monotonically
3979 * increasing unique serial number and always appended to the
3980 * sibling list, the next one can be found by walking the parent's
3981 * children until the first css with higher serial number than
3982 * @pos's. While this path can be slower, it happens iff iteration
3983 * races against release and the race window is very small.
3986 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3987 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3988 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3990 list_for_each_entry_rcu(next, &parent->children, sibling)
3991 if (next->serial_nr > pos->serial_nr)
3996 * @next, if not pointing to the head, can be dereferenced and is
3999 if (&next->sibling != &parent->children)
4005 * css_next_descendant_pre - find the next descendant for pre-order walk
4006 * @pos: the current position (%NULL to initiate traversal)
4007 * @root: css whose descendants to walk
4009 * To be used by css_for_each_descendant_pre(). Find the next descendant
4010 * to visit for pre-order traversal of @root's descendants. @root is
4011 * included in the iteration and the first node to be visited.
4013 * While this function requires cgroup_mutex or RCU read locking, it
4014 * doesn't require the whole traversal to be contained in a single critical
4015 * section. This function will return the correct next descendant as long
4016 * as both @pos and @root are accessible and @pos is a descendant of @root.
4018 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4019 * css which finished ->css_online() is guaranteed to be visible in the
4020 * future iterations and will stay visible until the last reference is put.
4021 * A css which hasn't finished ->css_online() or already finished
4022 * ->css_offline() may show up during traversal. It's each subsystem's
4023 * responsibility to synchronize against on/offlining.
4025 struct cgroup_subsys_state *
4026 css_next_descendant_pre(struct cgroup_subsys_state *pos,
4027 struct cgroup_subsys_state *root)
4029 struct cgroup_subsys_state *next;
4031 cgroup_assert_mutex_or_rcu_locked();
4033 /* if first iteration, visit @root */
4037 /* visit the first child if exists */
4038 next = css_next_child(NULL, pos);
4042 /* no child, visit my or the closest ancestor's next sibling */
4043 while (pos != root) {
4044 next = css_next_child(pos, pos->parent);
4054 * css_rightmost_descendant - return the rightmost descendant of a css
4055 * @pos: css of interest
4057 * Return the rightmost descendant of @pos. If there's no descendant, @pos
4058 * is returned. This can be used during pre-order traversal to skip
4061 * While this function requires cgroup_mutex or RCU read locking, it
4062 * doesn't require the whole traversal to be contained in a single critical
4063 * section. This function will return the correct rightmost descendant as
4064 * long as @pos is accessible.
4066 struct cgroup_subsys_state *
4067 css_rightmost_descendant(struct cgroup_subsys_state *pos)
4069 struct cgroup_subsys_state *last, *tmp;
4071 cgroup_assert_mutex_or_rcu_locked();
4075 /* ->prev isn't RCU safe, walk ->next till the end */
4077 css_for_each_child(tmp, last)
4084 static struct cgroup_subsys_state *
4085 css_leftmost_descendant(struct cgroup_subsys_state *pos)
4087 struct cgroup_subsys_state *last;
4091 pos = css_next_child(NULL, pos);
4098 * css_next_descendant_post - find the next descendant for post-order walk
4099 * @pos: the current position (%NULL to initiate traversal)
4100 * @root: css whose descendants to walk
4102 * To be used by css_for_each_descendant_post(). Find the next descendant
4103 * to visit for post-order traversal of @root's descendants. @root is
4104 * included in the iteration and the last node to be visited.
4106 * While this function requires cgroup_mutex or RCU read locking, it
4107 * doesn't require the whole traversal to be contained in a single critical
4108 * section. This function will return the correct next descendant as long
4109 * as both @pos and @cgroup are accessible and @pos is a descendant of
4112 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4113 * css which finished ->css_online() is guaranteed to be visible in the
4114 * future iterations and will stay visible until the last reference is put.
4115 * A css which hasn't finished ->css_online() or already finished
4116 * ->css_offline() may show up during traversal. It's each subsystem's
4117 * responsibility to synchronize against on/offlining.
4119 struct cgroup_subsys_state *
4120 css_next_descendant_post(struct cgroup_subsys_state *pos,
4121 struct cgroup_subsys_state *root)
4123 struct cgroup_subsys_state *next;
4125 cgroup_assert_mutex_or_rcu_locked();