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/sched/cputime.h>
60 #define CREATE_TRACE_POINTS
61 #include <trace/events/cgroup.h>
63 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
65 /* let's not notify more than 100 times per second */
66 #define CGROUP_FILE_NOTIFY_MIN_INTV DIV_ROUND_UP(HZ, 100)
69 * cgroup_mutex is the master lock. Any modification to cgroup or its
70 * hierarchy must be performed while holding it.
72 * css_set_lock protects task->cgroups pointer, the list of css_set
73 * objects, and the chain of tasks off each css_set.
75 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
76 * cgroup.h can use them for lockdep annotations.
78 DEFINE_MUTEX(cgroup_mutex);
79 DEFINE_SPINLOCK(css_set_lock);
81 #ifdef CONFIG_PROVE_RCU
82 EXPORT_SYMBOL_GPL(cgroup_mutex);
83 EXPORT_SYMBOL_GPL(css_set_lock);
86 DEFINE_SPINLOCK(trace_cgroup_path_lock);
87 char trace_cgroup_path[TRACE_CGROUP_PATH_LEN];
90 * Protects cgroup_idr and css_idr so that IDs can be released without
91 * grabbing cgroup_mutex.
93 static DEFINE_SPINLOCK(cgroup_idr_lock);
96 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
97 * against file removal/re-creation across css hiding.
99 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
101 struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
103 #define cgroup_assert_mutex_or_rcu_locked() \
104 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
105 !lockdep_is_held(&cgroup_mutex), \
106 "cgroup_mutex or RCU read lock required");
109 * cgroup destruction makes heavy use of work items and there can be a lot
110 * of concurrent destructions. Use a separate workqueue so that cgroup
111 * destruction work items don't end up filling up max_active of system_wq
112 * which may lead to deadlock.
114 static struct workqueue_struct *cgroup_destroy_wq;
116 /* generate an array of cgroup subsystem pointers */
117 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
118 struct cgroup_subsys *cgroup_subsys[] = {
119 #include <linux/cgroup_subsys.h>
123 /* array of cgroup subsystem names */
124 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
125 static const char *cgroup_subsys_name[] = {
126 #include <linux/cgroup_subsys.h>
130 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
132 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
133 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
134 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
135 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
136 #include <linux/cgroup_subsys.h>
139 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
140 static struct static_key_true *cgroup_subsys_enabled_key[] = {
141 #include <linux/cgroup_subsys.h>
145 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
146 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
147 #include <linux/cgroup_subsys.h>
151 static DEFINE_PER_CPU(struct cgroup_rstat_cpu, cgrp_dfl_root_rstat_cpu);
154 * The default hierarchy, reserved for the subsystems that are otherwise
155 * unattached - it never has more than a single cgroup, and all tasks are
156 * part of that cgroup.
158 struct cgroup_root cgrp_dfl_root = { .cgrp.rstat_cpu = &cgrp_dfl_root_rstat_cpu };
159 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
162 * The default hierarchy always exists but is hidden until mounted for the
163 * first time. This is for backward compatibility.
165 static bool cgrp_dfl_visible;
167 /* some controllers are not supported in the default hierarchy */
168 static u16 cgrp_dfl_inhibit_ss_mask;
170 /* some controllers are implicitly enabled on the default hierarchy */
171 static u16 cgrp_dfl_implicit_ss_mask;
173 /* some controllers can be threaded on the default hierarchy */
174 static u16 cgrp_dfl_threaded_ss_mask;
176 /* The list of hierarchy roots */
177 LIST_HEAD(cgroup_roots);
178 static int cgroup_root_count;
180 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
181 static DEFINE_IDR(cgroup_hierarchy_idr);
184 * Assign a monotonically increasing serial number to csses. It guarantees
185 * cgroups with bigger numbers are newer than those with smaller numbers.
186 * Also, as csses are always appended to the parent's ->children list, it
187 * guarantees that sibling csses are always sorted in the ascending serial
188 * number order on the list. Protected by cgroup_mutex.
190 static u64 css_serial_nr_next = 1;
193 * These bitmasks identify subsystems with specific features to avoid
194 * having to do iterative checks repeatedly.
196 static u16 have_fork_callback __read_mostly;
197 static u16 have_exit_callback __read_mostly;
198 static u16 have_free_callback __read_mostly;
199 static u16 have_canfork_callback __read_mostly;
201 /* cgroup namespace for init task */
202 struct cgroup_namespace init_cgroup_ns = {
203 .count = REFCOUNT_INIT(2),
204 .user_ns = &init_user_ns,
205 .ns.ops = &cgroupns_operations,
206 .ns.inum = PROC_CGROUP_INIT_INO,
207 .root_cset = &init_css_set,
210 static struct file_system_type cgroup2_fs_type;
211 static struct cftype cgroup_base_files[];
213 static int cgroup_apply_control(struct cgroup *cgrp);
214 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
215 static void css_task_iter_advance(struct css_task_iter *it);
216 static int cgroup_destroy_locked(struct cgroup *cgrp);
217 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
218 struct cgroup_subsys *ss);
219 static void css_release(struct percpu_ref *ref);
220 static void kill_css(struct cgroup_subsys_state *css);
221 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
222 struct cgroup *cgrp, struct cftype cfts[],
226 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
227 * @ssid: subsys ID of interest
229 * cgroup_subsys_enabled() can only be used with literal subsys names which
230 * is fine for individual subsystems but unsuitable for cgroup core. This
231 * is slower static_key_enabled() based test indexed by @ssid.
233 bool cgroup_ssid_enabled(int ssid)
235 if (CGROUP_SUBSYS_COUNT == 0)
238 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
242 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
243 * @cgrp: the cgroup of interest
245 * The default hierarchy is the v2 interface of cgroup and this function
246 * can be used to test whether a cgroup is on the default hierarchy for
247 * cases where a subsystem should behave differnetly depending on the
250 * The set of behaviors which change on the default hierarchy are still
251 * being determined and the mount option is prefixed with __DEVEL__.
253 * List of changed behaviors:
255 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
256 * and "name" are disallowed.
258 * - When mounting an existing superblock, mount options should match.
260 * - Remount is disallowed.
262 * - rename(2) is disallowed.
264 * - "tasks" is removed. Everything should be at process granularity. Use
265 * "cgroup.procs" instead.
267 * - "cgroup.procs" is not sorted. pids will be unique unless they got
268 * recycled inbetween reads.
270 * - "release_agent" and "notify_on_release" are removed. Replacement
271 * notification mechanism will be implemented.
273 * - "cgroup.clone_children" is removed.
275 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
276 * and its descendants contain no task; otherwise, 1. The file also
277 * generates kernfs notification which can be monitored through poll and
278 * [di]notify when the value of the file changes.
280 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
281 * take masks of ancestors with non-empty cpus/mems, instead of being
282 * moved to an ancestor.
284 * - cpuset: a task can be moved into an empty cpuset, and again it takes
285 * masks of ancestors.
287 * - memcg: use_hierarchy is on by default and the cgroup file for the flag
290 * - blkcg: blk-throttle becomes properly hierarchical.
292 * - debug: disallowed on the default hierarchy.
294 bool cgroup_on_dfl(const struct cgroup *cgrp)
296 return cgrp->root == &cgrp_dfl_root;
299 /* IDR wrappers which synchronize using cgroup_idr_lock */
300 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
305 idr_preload(gfp_mask);
306 spin_lock_bh(&cgroup_idr_lock);
307 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
308 spin_unlock_bh(&cgroup_idr_lock);
313 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
317 spin_lock_bh(&cgroup_idr_lock);
318 ret = idr_replace(idr, ptr, id);
319 spin_unlock_bh(&cgroup_idr_lock);
323 static void cgroup_idr_remove(struct idr *idr, int id)
325 spin_lock_bh(&cgroup_idr_lock);
327 spin_unlock_bh(&cgroup_idr_lock);
330 static bool cgroup_has_tasks(struct cgroup *cgrp)
332 return cgrp->nr_populated_csets;
335 bool cgroup_is_threaded(struct cgroup *cgrp)
337 return cgrp->dom_cgrp != cgrp;
340 /* can @cgrp host both domain and threaded children? */
341 static bool cgroup_is_mixable(struct cgroup *cgrp)
344 * Root isn't under domain level resource control exempting it from
345 * the no-internal-process constraint, so it can serve as a thread
346 * root and a parent of resource domains at the same time.
348 return !cgroup_parent(cgrp);
351 /* can @cgrp become a thread root? should always be true for a thread root */
352 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
354 /* mixables don't care */
355 if (cgroup_is_mixable(cgrp))
358 /* domain roots can't be nested under threaded */
359 if (cgroup_is_threaded(cgrp))
362 /* can only have either domain or threaded children */
363 if (cgrp->nr_populated_domain_children)
366 /* and no domain controllers can be enabled */
367 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
373 /* is @cgrp root of a threaded subtree? */
374 bool cgroup_is_thread_root(struct cgroup *cgrp)
376 /* thread root should be a domain */
377 if (cgroup_is_threaded(cgrp))
380 /* a domain w/ threaded children is a thread root */
381 if (cgrp->nr_threaded_children)
385 * A domain which has tasks and explicit threaded controllers
386 * enabled is a thread root.
388 if (cgroup_has_tasks(cgrp) &&
389 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
395 /* a domain which isn't connected to the root w/o brekage can't be used */
396 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
398 /* the cgroup itself can be a thread root */
399 if (cgroup_is_threaded(cgrp))
402 /* but the ancestors can't be unless mixable */
403 while ((cgrp = cgroup_parent(cgrp))) {
404 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
406 if (cgroup_is_threaded(cgrp))
413 /* subsystems visibly enabled on a cgroup */
414 static u16 cgroup_control(struct cgroup *cgrp)
416 struct cgroup *parent = cgroup_parent(cgrp);
417 u16 root_ss_mask = cgrp->root->subsys_mask;
420 u16 ss_mask = parent->subtree_control;
422 /* threaded cgroups can only have threaded controllers */
423 if (cgroup_is_threaded(cgrp))
424 ss_mask &= cgrp_dfl_threaded_ss_mask;
428 if (cgroup_on_dfl(cgrp))
429 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
430 cgrp_dfl_implicit_ss_mask);
434 /* subsystems enabled on a cgroup */
435 static u16 cgroup_ss_mask(struct cgroup *cgrp)
437 struct cgroup *parent = cgroup_parent(cgrp);
440 u16 ss_mask = parent->subtree_ss_mask;
442 /* threaded cgroups can only have threaded controllers */
443 if (cgroup_is_threaded(cgrp))
444 ss_mask &= cgrp_dfl_threaded_ss_mask;
448 return cgrp->root->subsys_mask;
452 * cgroup_css - obtain a cgroup's css for the specified subsystem
453 * @cgrp: the cgroup of interest
454 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
456 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
457 * function must be called either under cgroup_mutex or rcu_read_lock() and
458 * the caller is responsible for pinning the returned css if it wants to
459 * keep accessing it outside the said locks. This function may return
460 * %NULL if @cgrp doesn't have @subsys_id enabled.
462 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
463 struct cgroup_subsys *ss)
466 return rcu_dereference_check(cgrp->subsys[ss->id],
467 lockdep_is_held(&cgroup_mutex));
473 * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
474 * @cgrp: the cgroup of interest
475 * @ss: the subsystem of interest
477 * Find and get @cgrp's css assocaited with @ss. If the css doesn't exist
478 * or is offline, %NULL is returned.
480 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
481 struct cgroup_subsys *ss)
483 struct cgroup_subsys_state *css;
486 css = cgroup_css(cgrp, ss);
487 if (!css || !css_tryget_online(css))
495 * cgroup_e_css_by_mask - obtain a cgroup's effective css for the specified ss
496 * @cgrp: the cgroup of interest
497 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
499 * Similar to cgroup_css() but returns the effective css, which is defined
500 * as the matching css of the nearest ancestor including self which has @ss
501 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
502 * function is guaranteed to return non-NULL css.
504 static struct cgroup_subsys_state *cgroup_e_css_by_mask(struct cgroup *cgrp,
505 struct cgroup_subsys *ss)
507 lockdep_assert_held(&cgroup_mutex);
513 * This function is used while updating css associations and thus
514 * can't test the csses directly. Test ss_mask.
516 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
517 cgrp = cgroup_parent(cgrp);
522 return cgroup_css(cgrp, ss);
526 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
527 * @cgrp: the cgroup of interest
528 * @ss: the subsystem of interest
530 * Find and get the effective css of @cgrp for @ss. The effective css is
531 * defined as the matching css of the nearest ancestor including self which
532 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
533 * the root css is returned, so this function always returns a valid css.
535 * The returned css is not guaranteed to be online, and therefore it is the
536 * callers responsiblity to tryget a reference for it.
538 struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
539 struct cgroup_subsys *ss)
541 struct cgroup_subsys_state *css;
544 css = cgroup_css(cgrp, ss);
548 cgrp = cgroup_parent(cgrp);
551 return init_css_set.subsys[ss->id];
555 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
556 * @cgrp: the cgroup of interest
557 * @ss: the subsystem of interest
559 * Find and get the effective css of @cgrp for @ss. The effective css is
560 * defined as the matching css of the nearest ancestor including self which
561 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
562 * the root css is returned, so this function always returns a valid css.
563 * The returned css must be put using css_put().
565 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
566 struct cgroup_subsys *ss)
568 struct cgroup_subsys_state *css;
573 css = cgroup_css(cgrp, ss);
575 if (css && css_tryget_online(css))
577 cgrp = cgroup_parent(cgrp);
580 css = init_css_set.subsys[ss->id];
587 static void cgroup_get_live(struct cgroup *cgrp)
589 WARN_ON_ONCE(cgroup_is_dead(cgrp));
590 css_get(&cgrp->self);
593 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
595 struct cgroup *cgrp = of->kn->parent->priv;
596 struct cftype *cft = of_cft(of);
599 * This is open and unprotected implementation of cgroup_css().
600 * seq_css() is only called from a kernfs file operation which has
601 * an active reference on the file. Because all the subsystem
602 * files are drained before a css is disassociated with a cgroup,
603 * the matching css from the cgroup's subsys table is guaranteed to
604 * be and stay valid until the enclosing operation is complete.
607 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
611 EXPORT_SYMBOL_GPL(of_css);
614 * for_each_css - iterate all css's of a cgroup
615 * @css: the iteration cursor
616 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
617 * @cgrp: the target cgroup to iterate css's of
619 * Should be called under cgroup_[tree_]mutex.
621 #define for_each_css(css, ssid, cgrp) \
622 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
623 if (!((css) = rcu_dereference_check( \
624 (cgrp)->subsys[(ssid)], \
625 lockdep_is_held(&cgroup_mutex)))) { } \
629 * for_each_e_css - iterate all effective css's of a cgroup
630 * @css: the iteration cursor
631 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
632 * @cgrp: the target cgroup to iterate css's of
634 * Should be called under cgroup_[tree_]mutex.
636 #define for_each_e_css(css, ssid, cgrp) \
637 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
638 if (!((css) = cgroup_e_css_by_mask(cgrp, \
639 cgroup_subsys[(ssid)]))) \
644 * do_each_subsys_mask - filter for_each_subsys with a bitmask
645 * @ss: the iteration cursor
646 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
647 * @ss_mask: the bitmask
649 * The block will only run for cases where the ssid-th bit (1 << ssid) of
652 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
653 unsigned long __ss_mask = (ss_mask); \
654 if (!CGROUP_SUBSYS_COUNT) { /* to avoid spurious gcc warning */ \
658 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
659 (ss) = cgroup_subsys[ssid]; \
662 #define while_each_subsys_mask() \
667 /* iterate over child cgrps, lock should be held throughout iteration */
668 #define cgroup_for_each_live_child(child, cgrp) \
669 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
670 if (({ lockdep_assert_held(&cgroup_mutex); \
671 cgroup_is_dead(child); })) \
675 /* walk live descendants in preorder */
676 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
677 css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
678 if (({ lockdep_assert_held(&cgroup_mutex); \
679 (dsct) = (d_css)->cgroup; \
680 cgroup_is_dead(dsct); })) \
684 /* walk live descendants in postorder */
685 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
686 css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
687 if (({ lockdep_assert_held(&cgroup_mutex); \
688 (dsct) = (d_css)->cgroup; \
689 cgroup_is_dead(dsct); })) \
694 * The default css_set - used by init and its children prior to any
695 * hierarchies being mounted. It contains a pointer to the root state
696 * for each subsystem. Also used to anchor the list of css_sets. Not
697 * reference-counted, to improve performance when child cgroups
698 * haven't been created.
700 struct css_set init_css_set = {
701 .refcount = REFCOUNT_INIT(1),
702 .dom_cset = &init_css_set,
703 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
704 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
705 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
706 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
707 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
708 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
709 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
712 * The following field is re-initialized when this cset gets linked
713 * in cgroup_init(). However, let's initialize the field
714 * statically too so that the default cgroup can be accessed safely
717 .dfl_cgrp = &cgrp_dfl_root.cgrp,
720 static int css_set_count = 1; /* 1 for init_css_set */
722 static bool css_set_threaded(struct css_set *cset)
724 return cset->dom_cset != cset;
728 * css_set_populated - does a css_set contain any tasks?
729 * @cset: target css_set
731 * css_set_populated() should be the same as !!cset->nr_tasks at steady
732 * state. However, css_set_populated() can be called while a task is being
733 * added to or removed from the linked list before the nr_tasks is
734 * properly updated. Hence, we can't just look at ->nr_tasks here.
736 static bool css_set_populated(struct css_set *cset)
738 lockdep_assert_held(&css_set_lock);
740 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
744 * cgroup_update_populated - update the populated count of a cgroup
745 * @cgrp: the target cgroup
746 * @populated: inc or dec populated count
748 * One of the css_sets associated with @cgrp is either getting its first
749 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
750 * count is propagated towards root so that a given cgroup's
751 * nr_populated_children is zero iff none of its descendants contain any
754 * @cgrp's interface file "cgroup.populated" is zero if both
755 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
756 * 1 otherwise. When the sum changes from or to zero, userland is notified
757 * that the content of the interface file has changed. This can be used to
758 * detect when @cgrp and its descendants become populated or empty.
760 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
762 struct cgroup *child = NULL;
763 int adj = populated ? 1 : -1;
765 lockdep_assert_held(&css_set_lock);
768 bool was_populated = cgroup_is_populated(cgrp);
771 cgrp->nr_populated_csets += adj;
773 if (cgroup_is_threaded(child))
774 cgrp->nr_populated_threaded_children += adj;
776 cgrp->nr_populated_domain_children += adj;
779 if (was_populated == cgroup_is_populated(cgrp))
782 cgroup1_check_for_release(cgrp);
783 cgroup_file_notify(&cgrp->events_file);
786 cgrp = cgroup_parent(cgrp);
791 * css_set_update_populated - update populated state of a css_set
792 * @cset: target css_set
793 * @populated: whether @cset is populated or depopulated
795 * @cset is either getting the first task or losing the last. Update the
796 * populated counters of all associated cgroups accordingly.
798 static void css_set_update_populated(struct css_set *cset, bool populated)
800 struct cgrp_cset_link *link;
802 lockdep_assert_held(&css_set_lock);
804 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
805 cgroup_update_populated(link->cgrp, populated);
809 * css_set_move_task - move a task from one css_set to another
810 * @task: task being moved
811 * @from_cset: css_set @task currently belongs to (may be NULL)
812 * @to_cset: new css_set @task is being moved to (may be NULL)
813 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
815 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
816 * css_set, @from_cset can be NULL. If @task is being disassociated
817 * instead of moved, @to_cset can be NULL.
819 * This function automatically handles populated counter updates and
820 * css_task_iter adjustments but the caller is responsible for managing
821 * @from_cset and @to_cset's reference counts.
823 static void css_set_move_task(struct task_struct *task,
824 struct css_set *from_cset, struct css_set *to_cset,
827 lockdep_assert_held(&css_set_lock);
829 if (to_cset && !css_set_populated(to_cset))
830 css_set_update_populated(to_cset, true);
833 struct css_task_iter *it, *pos;
835 WARN_ON_ONCE(list_empty(&task->cg_list));
838 * @task is leaving, advance task iterators which are
839 * pointing to it so that they can resume at the next
840 * position. Advancing an iterator might remove it from
841 * the list, use safe walk. See css_task_iter_advance*()
844 list_for_each_entry_safe(it, pos, &from_cset->task_iters,
846 if (it->task_pos == &task->cg_list)
847 css_task_iter_advance(it);
849 list_del_init(&task->cg_list);
850 if (!css_set_populated(from_cset))
851 css_set_update_populated(from_cset, false);
853 WARN_ON_ONCE(!list_empty(&task->cg_list));
858 * We are synchronized through cgroup_threadgroup_rwsem
859 * against PF_EXITING setting such that we can't race
860 * against cgroup_exit() changing the css_set to
861 * init_css_set and dropping the old one.
863 WARN_ON_ONCE(task->flags & PF_EXITING);
865 rcu_assign_pointer(task->cgroups, to_cset);
866 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
872 * hash table for cgroup groups. This improves the performance to find
873 * an existing css_set. This hash doesn't (currently) take into
874 * account cgroups in empty hierarchies.
876 #define CSS_SET_HASH_BITS 7
877 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
879 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
881 unsigned long key = 0UL;
882 struct cgroup_subsys *ss;
885 for_each_subsys(ss, i)
886 key += (unsigned long)css[i];
887 key = (key >> 16) ^ key;
892 void put_css_set_locked(struct css_set *cset)
894 struct cgrp_cset_link *link, *tmp_link;
895 struct cgroup_subsys *ss;
898 lockdep_assert_held(&css_set_lock);
900 if (!refcount_dec_and_test(&cset->refcount))
903 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
905 /* This css_set is dead. unlink it and release cgroup and css refs */
906 for_each_subsys(ss, ssid) {
907 list_del(&cset->e_cset_node[ssid]);
908 css_put(cset->subsys[ssid]);
910 hash_del(&cset->hlist);
913 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
914 list_del(&link->cset_link);
915 list_del(&link->cgrp_link);
916 if (cgroup_parent(link->cgrp))
917 cgroup_put(link->cgrp);
921 if (css_set_threaded(cset)) {
922 list_del(&cset->threaded_csets_node);
923 put_css_set_locked(cset->dom_cset);
926 kfree_rcu(cset, rcu_head);
930 * compare_css_sets - helper function for find_existing_css_set().
931 * @cset: candidate css_set being tested
932 * @old_cset: existing css_set for a task
933 * @new_cgrp: cgroup that's being entered by the task
934 * @template: desired set of css pointers in css_set (pre-calculated)
936 * Returns true if "cset" matches "old_cset" except for the hierarchy
937 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
939 static bool compare_css_sets(struct css_set *cset,
940 struct css_set *old_cset,
941 struct cgroup *new_cgrp,
942 struct cgroup_subsys_state *template[])
944 struct cgroup *new_dfl_cgrp;
945 struct list_head *l1, *l2;
948 * On the default hierarchy, there can be csets which are
949 * associated with the same set of cgroups but different csses.
950 * Let's first ensure that csses match.
952 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
956 /* @cset's domain should match the default cgroup's */
957 if (cgroup_on_dfl(new_cgrp))
958 new_dfl_cgrp = new_cgrp;
960 new_dfl_cgrp = old_cset->dfl_cgrp;
962 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
966 * Compare cgroup pointers in order to distinguish between
967 * different cgroups in hierarchies. As different cgroups may
968 * share the same effective css, this comparison is always
971 l1 = &cset->cgrp_links;
972 l2 = &old_cset->cgrp_links;
974 struct cgrp_cset_link *link1, *link2;
975 struct cgroup *cgrp1, *cgrp2;
979 /* See if we reached the end - both lists are equal length. */
980 if (l1 == &cset->cgrp_links) {
981 BUG_ON(l2 != &old_cset->cgrp_links);
984 BUG_ON(l2 == &old_cset->cgrp_links);
986 /* Locate the cgroups associated with these links. */
987 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
988 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
991 /* Hierarchies should be linked in the same order. */
992 BUG_ON(cgrp1->root != cgrp2->root);
995 * If this hierarchy is the hierarchy of the cgroup
996 * that's changing, then we need to check that this
997 * css_set points to the new cgroup; if it's any other
998 * hierarchy, then this css_set should point to the
999 * same cgroup as the old css_set.
1001 if (cgrp1->root == new_cgrp->root) {
1002 if (cgrp1 != new_cgrp)
1013 * find_existing_css_set - init css array and find the matching css_set
1014 * @old_cset: the css_set that we're using before the cgroup transition
1015 * @cgrp: the cgroup that we're moving into
1016 * @template: out param for the new set of csses, should be clear on entry
1018 static struct css_set *find_existing_css_set(struct css_set *old_cset,
1019 struct cgroup *cgrp,
1020 struct cgroup_subsys_state *template[])
1022 struct cgroup_root *root = cgrp->root;
1023 struct cgroup_subsys *ss;
1024 struct css_set *cset;
1029 * Build the set of subsystem state objects that we want to see in the
1030 * new css_set. while subsystems can change globally, the entries here
1031 * won't change, so no need for locking.
1033 for_each_subsys(ss, i) {
1034 if (root->subsys_mask & (1UL << i)) {
1036 * @ss is in this hierarchy, so we want the
1037 * effective css from @cgrp.
1039 template[i] = cgroup_e_css_by_mask(cgrp, ss);
1042 * @ss is not in this hierarchy, so we don't want
1043 * to change the css.
1045 template[i] = old_cset->subsys[i];
1049 key = css_set_hash(template);
1050 hash_for_each_possible(css_set_table, cset, hlist, key) {
1051 if (!compare_css_sets(cset, old_cset, cgrp, template))
1054 /* This css_set matches what we need */
1058 /* No existing cgroup group matched */
1062 static void free_cgrp_cset_links(struct list_head *links_to_free)
1064 struct cgrp_cset_link *link, *tmp_link;
1066 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1067 list_del(&link->cset_link);
1073 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1074 * @count: the number of links to allocate
1075 * @tmp_links: list_head the allocated links are put on
1077 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1078 * through ->cset_link. Returns 0 on success or -errno.
1080 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1082 struct cgrp_cset_link *link;
1085 INIT_LIST_HEAD(tmp_links);
1087 for (i = 0; i < count; i++) {
1088 link = kzalloc(sizeof(*link), GFP_KERNEL);
1090 free_cgrp_cset_links(tmp_links);
1093 list_add(&link->cset_link, tmp_links);
1099 * link_css_set - a helper function to link a css_set to a cgroup
1100 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1101 * @cset: the css_set to be linked
1102 * @cgrp: the destination cgroup
1104 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1105 struct cgroup *cgrp)
1107 struct cgrp_cset_link *link;
1109 BUG_ON(list_empty(tmp_links));
1111 if (cgroup_on_dfl(cgrp))
1112 cset->dfl_cgrp = cgrp;
1114 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1119 * Always add links to the tail of the lists so that the lists are
1120 * in choronological order.
1122 list_move_tail(&link->cset_link, &cgrp->cset_links);
1123 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1125 if (cgroup_parent(cgrp))
1126 cgroup_get_live(cgrp);
1130 * find_css_set - return a new css_set with one cgroup updated
1131 * @old_cset: the baseline css_set
1132 * @cgrp: the cgroup to be updated
1134 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1135 * substituted into the appropriate hierarchy.
1137 static struct css_set *find_css_set(struct css_set *old_cset,
1138 struct cgroup *cgrp)
1140 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1141 struct css_set *cset;
1142 struct list_head tmp_links;
1143 struct cgrp_cset_link *link;
1144 struct cgroup_subsys *ss;
1148 lockdep_assert_held(&cgroup_mutex);
1150 /* First see if we already have a cgroup group that matches
1151 * the desired set */
1152 spin_lock_irq(&css_set_lock);
1153 cset = find_existing_css_set(old_cset, cgrp, template);
1156 spin_unlock_irq(&css_set_lock);
1161 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1165 /* Allocate all the cgrp_cset_link objects that we'll need */
1166 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1171 refcount_set(&cset->refcount, 1);
1172 cset->dom_cset = cset;
1173 INIT_LIST_HEAD(&cset->tasks);
1174 INIT_LIST_HEAD(&cset->mg_tasks);
1175 INIT_LIST_HEAD(&cset->task_iters);
1176 INIT_LIST_HEAD(&cset->threaded_csets);
1177 INIT_HLIST_NODE(&cset->hlist);
1178 INIT_LIST_HEAD(&cset->cgrp_links);
1179 INIT_LIST_HEAD(&cset->mg_preload_node);
1180 INIT_LIST_HEAD(&cset->mg_node);
1182 /* Copy the set of subsystem state objects generated in
1183 * find_existing_css_set() */
1184 memcpy(cset->subsys, template, sizeof(cset->subsys));
1186 spin_lock_irq(&css_set_lock);
1187 /* Add reference counts and links from the new css_set. */
1188 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1189 struct cgroup *c = link->cgrp;
1191 if (c->root == cgrp->root)
1193 link_css_set(&tmp_links, cset, c);
1196 BUG_ON(!list_empty(&tmp_links));
1200 /* Add @cset to the hash table */
1201 key = css_set_hash(cset->subsys);
1202 hash_add(css_set_table, &cset->hlist, key);
1204 for_each_subsys(ss, ssid) {
1205 struct cgroup_subsys_state *css = cset->subsys[ssid];
1207 list_add_tail(&cset->e_cset_node[ssid],
1208 &css->cgroup->e_csets[ssid]);
1212 spin_unlock_irq(&css_set_lock);
1215 * If @cset should be threaded, look up the matching dom_cset and
1216 * link them up. We first fully initialize @cset then look for the
1217 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1218 * to stay empty until we return.
1220 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1221 struct css_set *dcset;
1223 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1229 spin_lock_irq(&css_set_lock);
1230 cset->dom_cset = dcset;
1231 list_add_tail(&cset->threaded_csets_node,
1232 &dcset->threaded_csets);
1233 spin_unlock_irq(&css_set_lock);
1239 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1241 struct cgroup *root_cgrp = kf_root->kn->priv;
1243 return root_cgrp->root;
1246 static int cgroup_init_root_id(struct cgroup_root *root)
1250 lockdep_assert_held(&cgroup_mutex);
1252 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1256 root->hierarchy_id = id;
1260 static void cgroup_exit_root_id(struct cgroup_root *root)
1262 lockdep_assert_held(&cgroup_mutex);
1264 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1267 void cgroup_free_root(struct cgroup_root *root)
1270 idr_destroy(&root->cgroup_idr);
1275 static void cgroup_destroy_root(struct cgroup_root *root)
1277 struct cgroup *cgrp = &root->cgrp;
1278 struct cgrp_cset_link *link, *tmp_link;
1280 trace_cgroup_destroy_root(root);
1282 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1284 BUG_ON(atomic_read(&root->nr_cgrps));
1285 BUG_ON(!list_empty(&cgrp->self.children));
1287 /* Rebind all subsystems back to the default hierarchy */
1288 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1291 * Release all the links from cset_links to this hierarchy's
1294 spin_lock_irq(&css_set_lock);
1296 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1297 list_del(&link->cset_link);
1298 list_del(&link->cgrp_link);
1302 spin_unlock_irq(&css_set_lock);
1304 if (!list_empty(&root->root_list)) {
1305 list_del(&root->root_list);
1306 cgroup_root_count--;
1309 cgroup_exit_root_id(root);
1311 mutex_unlock(&cgroup_mutex);
1313 kernfs_destroy_root(root->kf_root);
1314 cgroup_free_root(root);
1318 * look up cgroup associated with current task's cgroup namespace on the
1319 * specified hierarchy
1321 static struct cgroup *
1322 current_cgns_cgroup_from_root(struct cgroup_root *root)
1324 struct cgroup *res = NULL;
1325 struct css_set *cset;
1327 lockdep_assert_held(&css_set_lock);
1331 cset = current->nsproxy->cgroup_ns->root_cset;
1332 if (cset == &init_css_set) {
1335 struct cgrp_cset_link *link;
1337 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1338 struct cgroup *c = link->cgrp;
1340 if (c->root == root) {
1352 /* look up cgroup associated with given css_set on the specified hierarchy */
1353 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1354 struct cgroup_root *root)
1356 struct cgroup *res = NULL;
1358 lockdep_assert_held(&cgroup_mutex);
1359 lockdep_assert_held(&css_set_lock);
1361 if (cset == &init_css_set) {
1363 } else if (root == &cgrp_dfl_root) {
1364 res = cset->dfl_cgrp;
1366 struct cgrp_cset_link *link;
1368 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1369 struct cgroup *c = link->cgrp;
1371 if (c->root == root) {
1383 * Return the cgroup for "task" from the given hierarchy. Must be
1384 * called with cgroup_mutex and css_set_lock held.
1386 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1387 struct cgroup_root *root)
1390 * No need to lock the task - since we hold cgroup_mutex the
1391 * task can't change groups, so the only thing that can happen
1392 * is that it exits and its css is set back to init_css_set.
1394 return cset_cgroup_from_root(task_css_set(task), root);
1398 * A task must hold cgroup_mutex to modify cgroups.
1400 * Any task can increment and decrement the count field without lock.
1401 * So in general, code holding cgroup_mutex can't rely on the count
1402 * field not changing. However, if the count goes to zero, then only
1403 * cgroup_attach_task() can increment it again. Because a count of zero
1404 * means that no tasks are currently attached, therefore there is no
1405 * way a task attached to that cgroup can fork (the other way to
1406 * increment the count). So code holding cgroup_mutex can safely
1407 * assume that if the count is zero, it will stay zero. Similarly, if
1408 * a task holds cgroup_mutex on a cgroup with zero count, it
1409 * knows that the cgroup won't be removed, as cgroup_rmdir()
1412 * A cgroup can only be deleted if both its 'count' of using tasks
1413 * is zero, and its list of 'children' cgroups is empty. Since all
1414 * tasks in the system use _some_ cgroup, and since there is always at
1415 * least one task in the system (init, pid == 1), therefore, root cgroup
1416 * always has either children cgroups and/or using tasks. So we don't
1417 * need a special hack to ensure that root cgroup cannot be deleted.
1419 * P.S. One more locking exception. RCU is used to guard the
1420 * update of a tasks cgroup pointer by cgroup_attach_task()
1423 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1425 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1428 struct cgroup_subsys *ss = cft->ss;
1430 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1431 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1432 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1433 cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1436 strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1441 * cgroup_file_mode - deduce file mode of a control file
1442 * @cft: the control file in question
1444 * S_IRUGO for read, S_IWUSR for write.
1446 static umode_t cgroup_file_mode(const struct cftype *cft)
1450 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1453 if (cft->write_u64 || cft->write_s64 || cft->write) {
1454 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1464 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1465 * @subtree_control: the new subtree_control mask to consider
1466 * @this_ss_mask: available subsystems
1468 * On the default hierarchy, a subsystem may request other subsystems to be
1469 * enabled together through its ->depends_on mask. In such cases, more
1470 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1472 * This function calculates which subsystems need to be enabled if
1473 * @subtree_control is to be applied while restricted to @this_ss_mask.
1475 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1477 u16 cur_ss_mask = subtree_control;
1478 struct cgroup_subsys *ss;
1481 lockdep_assert_held(&cgroup_mutex);
1483 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1486 u16 new_ss_mask = cur_ss_mask;
1488 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1489 new_ss_mask |= ss->depends_on;
1490 } while_each_subsys_mask();
1493 * Mask out subsystems which aren't available. This can
1494 * happen only if some depended-upon subsystems were bound
1495 * to non-default hierarchies.
1497 new_ss_mask &= this_ss_mask;
1499 if (new_ss_mask == cur_ss_mask)
1501 cur_ss_mask = new_ss_mask;
1508 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1509 * @kn: the kernfs_node being serviced
1511 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1512 * the method finishes if locking succeeded. Note that once this function
1513 * returns the cgroup returned by cgroup_kn_lock_live() may become
1514 * inaccessible any time. If the caller intends to continue to access the
1515 * cgroup, it should pin it before invoking this function.
1517 void cgroup_kn_unlock(struct kernfs_node *kn)
1519 struct cgroup *cgrp;
1521 if (kernfs_type(kn) == KERNFS_DIR)
1524 cgrp = kn->parent->priv;
1526 mutex_unlock(&cgroup_mutex);
1528 kernfs_unbreak_active_protection(kn);
1533 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1534 * @kn: the kernfs_node being serviced
1535 * @drain_offline: perform offline draining on the cgroup
1537 * This helper is to be used by a cgroup kernfs method currently servicing
1538 * @kn. It breaks the active protection, performs cgroup locking and
1539 * verifies that the associated cgroup is alive. Returns the cgroup if
1540 * alive; otherwise, %NULL. A successful return should be undone by a
1541 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1542 * cgroup is drained of offlining csses before return.
1544 * Any cgroup kernfs method implementation which requires locking the
1545 * associated cgroup should use this helper. It avoids nesting cgroup
1546 * locking under kernfs active protection and allows all kernfs operations
1547 * including self-removal.
1549 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1551 struct cgroup *cgrp;
1553 if (kernfs_type(kn) == KERNFS_DIR)
1556 cgrp = kn->parent->priv;
1559 * We're gonna grab cgroup_mutex which nests outside kernfs
1560 * active_ref. cgroup liveliness check alone provides enough
1561 * protection against removal. Ensure @cgrp stays accessible and
1562 * break the active_ref protection.
1564 if (!cgroup_tryget(cgrp))
1566 kernfs_break_active_protection(kn);
1569 cgroup_lock_and_drain_offline(cgrp);
1571 mutex_lock(&cgroup_mutex);
1573 if (!cgroup_is_dead(cgrp))
1576 cgroup_kn_unlock(kn);
1580 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1582 char name[CGROUP_FILE_NAME_MAX];
1584 lockdep_assert_held(&cgroup_mutex);
1586 if (cft->file_offset) {
1587 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1588 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1590 spin_lock_irq(&cgroup_file_kn_lock);
1592 spin_unlock_irq(&cgroup_file_kn_lock);
1594 del_timer_sync(&cfile->notify_timer);
1597 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1601 * css_clear_dir - remove subsys files in a cgroup directory
1604 static void css_clear_dir(struct cgroup_subsys_state *css)
1606 struct cgroup *cgrp = css->cgroup;
1607 struct cftype *cfts;
1609 if (!(css->flags & CSS_VISIBLE))
1612 css->flags &= ~CSS_VISIBLE;
1615 if (cgroup_on_dfl(cgrp))
1616 cfts = cgroup_base_files;
1618 cfts = cgroup1_base_files;
1620 cgroup_addrm_files(css, cgrp, cfts, false);
1622 list_for_each_entry(cfts, &css->ss->cfts, node)
1623 cgroup_addrm_files(css, cgrp, cfts, false);
1628 * css_populate_dir - create subsys files in a cgroup directory
1631 * On failure, no file is added.
1633 static int css_populate_dir(struct cgroup_subsys_state *css)
1635 struct cgroup *cgrp = css->cgroup;
1636 struct cftype *cfts, *failed_cfts;
1639 if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
1643 if (cgroup_on_dfl(cgrp))
1644 cfts = cgroup_base_files;
1646 cfts = cgroup1_base_files;
1648 ret = cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1652 list_for_each_entry(cfts, &css->ss->cfts, node) {
1653 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1661 css->flags |= CSS_VISIBLE;
1665 list_for_each_entry(cfts, &css->ss->cfts, node) {
1666 if (cfts == failed_cfts)
1668 cgroup_addrm_files(css, cgrp, cfts, false);
1673 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1675 struct cgroup *dcgrp = &dst_root->cgrp;
1676 struct cgroup_subsys *ss;
1679 lockdep_assert_held(&cgroup_mutex);
1681 do_each_subsys_mask(ss, ssid, ss_mask) {
1683 * If @ss has non-root csses attached to it, can't move.
1684 * If @ss is an implicit controller, it is exempt from this
1685 * rule and can be stolen.
1687 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1688 !ss->implicit_on_dfl)
1691 /* can't move between two non-dummy roots either */
1692 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1694 } while_each_subsys_mask();
1696 do_each_subsys_mask(ss, ssid, ss_mask) {
1697 struct cgroup_root *src_root = ss->root;
1698 struct cgroup *scgrp = &src_root->cgrp;
1699 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1700 struct css_set *cset;
1702 WARN_ON(!css || cgroup_css(dcgrp, ss));
1704 /* disable from the source */
1705 src_root->subsys_mask &= ~(1 << ssid);
1706 WARN_ON(cgroup_apply_control(scgrp));
1707 cgroup_finalize_control(scgrp, 0);
1710 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1711 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1712 ss->root = dst_root;
1713 css->cgroup = dcgrp;
1715 spin_lock_irq(&css_set_lock);
1716 hash_for_each(css_set_table, i, cset, hlist)
1717 list_move_tail(&cset->e_cset_node[ss->id],
1718 &dcgrp->e_csets[ss->id]);
1719 spin_unlock_irq(&css_set_lock);
1721 /* default hierarchy doesn't enable controllers by default */
1722 dst_root->subsys_mask |= 1 << ssid;
1723 if (dst_root == &cgrp_dfl_root) {
1724 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1726 dcgrp->subtree_control |= 1 << ssid;
1727 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1730 ret = cgroup_apply_control(dcgrp);
1732 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1737 } while_each_subsys_mask();
1739 kernfs_activate(dcgrp->kn);
1743 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1744 struct kernfs_root *kf_root)
1748 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1749 struct cgroup *ns_cgroup;
1751 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1755 spin_lock_irq(&css_set_lock);
1756 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1757 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1758 spin_unlock_irq(&css_set_lock);
1760 if (len >= PATH_MAX)
1763 seq_escape(sf, buf, " \t\n\\");
1770 static int parse_cgroup_root_flags(char *data, unsigned int *root_flags)
1779 while ((token = strsep(&data, ",")) != NULL) {
1780 if (!strcmp(token, "nsdelegate")) {
1781 *root_flags |= CGRP_ROOT_NS_DELEGATE;
1785 pr_err("cgroup2: unknown option \"%s\"\n", token);
1792 static void apply_cgroup_root_flags(unsigned int root_flags)
1794 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1795 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1796 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1798 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1802 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1804 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1805 seq_puts(seq, ",nsdelegate");
1809 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1811 unsigned int root_flags;
1814 ret = parse_cgroup_root_flags(data, &root_flags);
1818 apply_cgroup_root_flags(root_flags);
1823 * To reduce the fork() overhead for systems that are not actually using
1824 * their cgroups capability, we don't maintain the lists running through
1825 * each css_set to its tasks until we see the list actually used - in other
1826 * words after the first mount.
1828 static bool use_task_css_set_links __read_mostly;
1830 static void cgroup_enable_task_cg_lists(void)
1832 struct task_struct *p, *g;
1835 * We need tasklist_lock because RCU is not safe against
1836 * while_each_thread(). Besides, a forking task that has passed
1837 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1838 * is not guaranteed to have its child immediately visible in the
1839 * tasklist if we walk through it with RCU.
1841 read_lock(&tasklist_lock);
1842 spin_lock_irq(&css_set_lock);
1844 if (use_task_css_set_links)
1847 use_task_css_set_links = true;
1849 do_each_thread(g, p) {
1850 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1851 task_css_set(p) != &init_css_set);
1854 * We should check if the process is exiting, otherwise
1855 * it will race with cgroup_exit() in that the list
1856 * entry won't be deleted though the process has exited.
1857 * Do it while holding siglock so that we don't end up
1858 * racing against cgroup_exit().
1860 * Interrupts were already disabled while acquiring
1861 * the css_set_lock, so we do not need to disable it
1862 * again when acquiring the sighand->siglock here.
1864 spin_lock(&p->sighand->siglock);
1865 if (!(p->flags & PF_EXITING)) {
1866 struct css_set *cset = task_css_set(p);
1868 if (!css_set_populated(cset))
1869 css_set_update_populated(cset, true);
1870 list_add_tail(&p->cg_list, &cset->tasks);
1874 spin_unlock(&p->sighand->siglock);
1875 } while_each_thread(g, p);
1877 spin_unlock_irq(&css_set_lock);
1878 read_unlock(&tasklist_lock);
1881 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1883 struct cgroup_subsys *ss;
1886 INIT_LIST_HEAD(&cgrp->self.sibling);
1887 INIT_LIST_HEAD(&cgrp->self.children);
1888 INIT_LIST_HEAD(&cgrp->cset_links);
1889 INIT_LIST_HEAD(&cgrp->pidlists);
1890 mutex_init(&cgrp->pidlist_mutex);
1891 cgrp->self.cgroup = cgrp;
1892 cgrp->self.flags |= CSS_ONLINE;
1893 cgrp->dom_cgrp = cgrp;
1894 cgrp->max_descendants = INT_MAX;
1895 cgrp->max_depth = INT_MAX;
1896 INIT_LIST_HEAD(&cgrp->rstat_css_list);
1897 prev_cputime_init(&cgrp->prev_cputime);
1899 for_each_subsys(ss, ssid)
1900 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1902 init_waitqueue_head(&cgrp->offline_waitq);
1903 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
1906 void init_cgroup_root(struct cgroup_root *root, struct cgroup_sb_opts *opts)
1908 struct cgroup *cgrp = &root->cgrp;
1910 INIT_LIST_HEAD(&root->root_list);
1911 atomic_set(&root->nr_cgrps, 1);
1913 init_cgroup_housekeeping(cgrp);
1914 idr_init(&root->cgroup_idr);
1916 root->flags = opts->flags;
1917 if (opts->release_agent)
1918 strscpy(root->release_agent_path, opts->release_agent, PATH_MAX);
1920 strscpy(root->name, opts->name, MAX_CGROUP_ROOT_NAMELEN);
1921 if (opts->cpuset_clone_children)
1922 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1925 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask, int ref_flags)
1927 LIST_HEAD(tmp_links);
1928 struct cgroup *root_cgrp = &root->cgrp;
1929 struct kernfs_syscall_ops *kf_sops;
1930 struct css_set *cset;
1933 lockdep_assert_held(&cgroup_mutex);
1935 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1938 root_cgrp->id = ret;
1939 root_cgrp->ancestor_ids[0] = ret;
1941 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
1942 ref_flags, GFP_KERNEL);
1947 * We're accessing css_set_count without locking css_set_lock here,
1948 * but that's OK - it can only be increased by someone holding
1949 * cgroup_lock, and that's us. Later rebinding may disable
1950 * controllers on the default hierarchy and thus create new csets,
1951 * which can't be more than the existing ones. Allocate 2x.
1953 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
1957 ret = cgroup_init_root_id(root);
1961 kf_sops = root == &cgrp_dfl_root ?
1962 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
1964 root->kf_root = kernfs_create_root(kf_sops,
1965 KERNFS_ROOT_CREATE_DEACTIVATED |
1966 KERNFS_ROOT_SUPPORT_EXPORTOP,
1968 if (IS_ERR(root->kf_root)) {
1969 ret = PTR_ERR(root->kf_root);
1972 root_cgrp->kn = root->kf_root->kn;
1974 ret = css_populate_dir(&root_cgrp->self);
1978 ret = rebind_subsystems(root, ss_mask);
1982 ret = cgroup_bpf_inherit(root_cgrp);
1985 trace_cgroup_setup_root(root);
1988 * There must be no failure case after here, since rebinding takes
1989 * care of subsystems' refcounts, which are explicitly dropped in
1990 * the failure exit path.
1992 list_add(&root->root_list, &cgroup_roots);
1993 cgroup_root_count++;
1996 * Link the root cgroup in this hierarchy into all the css_set
1999 spin_lock_irq(&css_set_lock);
2000 hash_for_each(css_set_table, i, cset, hlist) {
2001 link_css_set(&tmp_links, cset, root_cgrp);
2002 if (css_set_populated(cset))
2003 cgroup_update_populated(root_cgrp, true);
2005 spin_unlock_irq(&css_set_lock);
2007 BUG_ON(!list_empty(&root_cgrp->self.children));
2008 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
2010 kernfs_activate(root_cgrp->kn);
2015 kernfs_destroy_root(root->kf_root);
2016 root->kf_root = NULL;
2018 cgroup_exit_root_id(root);
2020 percpu_ref_exit(&root_cgrp->self.refcnt);
2022 free_cgrp_cset_links(&tmp_links);
2026 struct dentry *cgroup_do_mount(struct file_system_type *fs_type, int flags,
2027 struct cgroup_root *root, unsigned long magic,
2028 struct cgroup_namespace *ns)
2030 struct dentry *dentry;
2033 dentry = kernfs_mount(fs_type, flags, root->kf_root, magic, &new_sb);
2036 * In non-init cgroup namespace, instead of root cgroup's dentry,
2037 * we return the dentry corresponding to the cgroupns->root_cgrp.
2039 if (!IS_ERR(dentry) && ns != &init_cgroup_ns) {
2040 struct dentry *nsdentry;
2041 struct cgroup *cgrp;
2043 mutex_lock(&cgroup_mutex);
2044 spin_lock_irq(&css_set_lock);
2046 cgrp = cset_cgroup_from_root(ns->root_cset, root);
2048 spin_unlock_irq(&css_set_lock);
2049 mutex_unlock(&cgroup_mutex);
2051 nsdentry = kernfs_node_dentry(cgrp->kn, dentry->d_sb);
2056 if (IS_ERR(dentry) || !new_sb)
2057 cgroup_put(&root->cgrp);
2062 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
2063 int flags, const char *unused_dev_name,
2066 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
2067 struct dentry *dentry;
2072 /* Check if the caller has permission to mount. */
2073 if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) {
2075 return ERR_PTR(-EPERM);
2079 * The first time anyone tries to mount a cgroup, enable the list
2080 * linking each css_set to its tasks and fix up all existing tasks.
2082 if (!use_task_css_set_links)
2083 cgroup_enable_task_cg_lists();
2085 if (fs_type == &cgroup2_fs_type) {
2086 unsigned int root_flags;
2088 ret = parse_cgroup_root_flags(data, &root_flags);
2091 return ERR_PTR(ret);
2094 cgrp_dfl_visible = true;
2095 cgroup_get_live(&cgrp_dfl_root.cgrp);
2097 dentry = cgroup_do_mount(&cgroup2_fs_type, flags, &cgrp_dfl_root,
2098 CGROUP2_SUPER_MAGIC, ns);
2099 if (!IS_ERR(dentry))
2100 apply_cgroup_root_flags(root_flags);
2102 dentry = cgroup1_mount(&cgroup_fs_type, flags, data,
2103 CGROUP_SUPER_MAGIC, ns);
2110 static void cgroup_kill_sb(struct super_block *sb)
2112 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2113 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2116 * If @root doesn't have any mounts or children, start killing it.
2117 * This prevents new mounts by disabling percpu_ref_tryget_live().
2118 * cgroup_mount() may wait for @root's release.
2120 * And don't kill the default root.
2122 if (!list_empty(&root->cgrp.self.children) ||
2123 root == &cgrp_dfl_root)
2124 cgroup_put(&root->cgrp);
2126 percpu_ref_kill(&root->cgrp.self.refcnt);
2131 struct file_system_type cgroup_fs_type = {
2133 .mount = cgroup_mount,
2134 .kill_sb = cgroup_kill_sb,
2135 .fs_flags = FS_USERNS_MOUNT,
2138 static struct file_system_type cgroup2_fs_type = {
2140 .mount = cgroup_mount,
2141 .kill_sb = cgroup_kill_sb,
2142 .fs_flags = FS_USERNS_MOUNT,
2145 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2146 struct cgroup_namespace *ns)
2148 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2150 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2153 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2154 struct cgroup_namespace *ns)
2158 mutex_lock(&cgroup_mutex);
2159 spin_lock_irq(&css_set_lock);
2161 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2163 spin_unlock_irq(&css_set_lock);
2164 mutex_unlock(&cgroup_mutex);
2168 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2171 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2172 * @task: target task
2173 * @buf: the buffer to write the path into
2174 * @buflen: the length of the buffer
2176 * Determine @task's cgroup on the first (the one with the lowest non-zero
2177 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2178 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2179 * cgroup controller callbacks.
2181 * Return value is the same as kernfs_path().
2183 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2185 struct cgroup_root *root;
2186 struct cgroup *cgrp;
2187 int hierarchy_id = 1;
2190 mutex_lock(&cgroup_mutex);
2191 spin_lock_irq(&css_set_lock);
2193 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2196 cgrp = task_cgroup_from_root(task, root);
2197 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2199 /* if no hierarchy exists, everyone is in "/" */
2200 ret = strlcpy(buf, "/", buflen);
2203 spin_unlock_irq(&css_set_lock);
2204 mutex_unlock(&cgroup_mutex);
2207 EXPORT_SYMBOL_GPL(task_cgroup_path);
2210 * cgroup_migrate_add_task - add a migration target task to a migration context
2211 * @task: target task
2212 * @mgctx: target migration context
2214 * Add @task, which is a migration target, to @mgctx->tset. This function
2215 * becomes noop if @task doesn't need to be migrated. @task's css_set
2216 * should have been added as a migration source and @task->cg_list will be
2217 * moved from the css_set's tasks list to mg_tasks one.
2219 static void cgroup_migrate_add_task(struct task_struct *task,
2220 struct cgroup_mgctx *mgctx)
2222 struct css_set *cset;
2224 lockdep_assert_held(&css_set_lock);
2226 /* @task either already exited or can't exit until the end */
2227 if (task->flags & PF_EXITING)
2230 /* leave @task alone if post_fork() hasn't linked it yet */
2231 if (list_empty(&task->cg_list))
2234 cset = task_css_set(task);
2235 if (!cset->mg_src_cgrp)
2238 mgctx->tset.nr_tasks++;
2240 list_move_tail(&task->cg_list, &cset->mg_tasks);
2241 if (list_empty(&cset->mg_node))
2242 list_add_tail(&cset->mg_node,
2243 &mgctx->tset.src_csets);
2244 if (list_empty(&cset->mg_dst_cset->mg_node))
2245 list_add_tail(&cset->mg_dst_cset->mg_node,
2246 &mgctx->tset.dst_csets);
2250 * cgroup_taskset_first - reset taskset and return the first task
2251 * @tset: taskset of interest
2252 * @dst_cssp: output variable for the destination css
2254 * @tset iteration is initialized and the first task is returned.
2256 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2257 struct cgroup_subsys_state **dst_cssp)
2259 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2260 tset->cur_task = NULL;
2262 return cgroup_taskset_next(tset, dst_cssp);
2266 * cgroup_taskset_next - iterate to the next task in taskset
2267 * @tset: taskset of interest
2268 * @dst_cssp: output variable for the destination css
2270 * Return the next task in @tset. Iteration must have been initialized
2271 * with cgroup_taskset_first().
2273 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2274 struct cgroup_subsys_state **dst_cssp)
2276 struct css_set *cset = tset->cur_cset;
2277 struct task_struct *task = tset->cur_task;
2279 while (&cset->mg_node != tset->csets) {
2281 task = list_first_entry(&cset->mg_tasks,
2282 struct task_struct, cg_list);
2284 task = list_next_entry(task, cg_list);
2286 if (&task->cg_list != &cset->mg_tasks) {
2287 tset->cur_cset = cset;
2288 tset->cur_task = task;
2291 * This function may be called both before and
2292 * after cgroup_taskset_migrate(). The two cases
2293 * can be distinguished by looking at whether @cset
2294 * has its ->mg_dst_cset set.
2296 if (cset->mg_dst_cset)
2297 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2299 *dst_cssp = cset->subsys[tset->ssid];
2304 cset = list_next_entry(cset, mg_node);
2312 * cgroup_taskset_migrate - migrate a taskset
2313 * @mgctx: migration context
2315 * Migrate tasks in @mgctx as setup by migration preparation functions.
2316 * This function fails iff one of the ->can_attach callbacks fails and
2317 * guarantees that either all or none of the tasks in @mgctx are migrated.
2318 * @mgctx is consumed regardless of success.
2320 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2322 struct cgroup_taskset *tset = &mgctx->tset;
2323 struct cgroup_subsys *ss;
2324 struct task_struct *task, *tmp_task;
2325 struct css_set *cset, *tmp_cset;
2326 int ssid, failed_ssid, ret;
2328 /* check that we can legitimately attach to the cgroup */
2329 if (tset->nr_tasks) {
2330 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2331 if (ss->can_attach) {
2333 ret = ss->can_attach(tset);
2336 goto out_cancel_attach;
2339 } while_each_subsys_mask();
2343 * Now that we're guaranteed success, proceed to move all tasks to
2344 * the new cgroup. There are no failure cases after here, so this
2345 * is the commit point.
2347 spin_lock_irq(&css_set_lock);
2348 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2349 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2350 struct css_set *from_cset = task_css_set(task);
2351 struct css_set *to_cset = cset->mg_dst_cset;
2353 get_css_set(to_cset);
2354 to_cset->nr_tasks++;
2355 css_set_move_task(task, from_cset, to_cset, true);
2356 put_css_set_locked(from_cset);
2357 from_cset->nr_tasks--;
2360 spin_unlock_irq(&css_set_lock);
2363 * Migration is committed, all target tasks are now on dst_csets.
2364 * Nothing is sensitive to fork() after this point. Notify
2365 * controllers that migration is complete.
2367 tset->csets = &tset->dst_csets;
2369 if (tset->nr_tasks) {
2370 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2375 } while_each_subsys_mask();
2379 goto out_release_tset;
2382 if (tset->nr_tasks) {
2383 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2384 if (ssid == failed_ssid)
2386 if (ss->cancel_attach) {
2388 ss->cancel_attach(tset);
2390 } while_each_subsys_mask();
2393 spin_lock_irq(&css_set_lock);
2394 list_splice_init(&tset->dst_csets, &tset->src_csets);
2395 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2396 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2397 list_del_init(&cset->mg_node);
2399 spin_unlock_irq(&css_set_lock);
2402 * Re-initialize the cgroup_taskset structure in case it is reused
2403 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2407 tset->csets = &tset->src_csets;
2412 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2413 * @dst_cgrp: destination cgroup to test
2415 * On the default hierarchy, except for the mixable, (possible) thread root
2416 * and threaded cgroups, subtree_control must be zero for migration
2417 * destination cgroups with tasks so that child cgroups don't compete
2420 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2422 /* v1 doesn't have any restriction */
2423 if (!cgroup_on_dfl(dst_cgrp))
2426 /* verify @dst_cgrp can host resources */
2427 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2430 /* mixables don't care */
2431 if (cgroup_is_mixable(dst_cgrp))
2435 * If @dst_cgrp is already or can become a thread root or is
2436 * threaded, it doesn't matter.
2438 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2441 /* apply no-internal-process constraint */
2442 if (dst_cgrp->subtree_control)
2449 * cgroup_migrate_finish - cleanup after attach
2450 * @mgctx: migration context
2452 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2453 * those functions for details.
2455 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2457 LIST_HEAD(preloaded);
2458 struct css_set *cset, *tmp_cset;
2460 lockdep_assert_held(&cgroup_mutex);
2462 spin_lock_irq(&css_set_lock);
2464 list_splice_tail_init(&mgctx->preloaded_src_csets, &preloaded);
2465 list_splice_tail_init(&mgctx->preloaded_dst_csets, &preloaded);
2467 list_for_each_entry_safe(cset, tmp_cset, &preloaded, mg_preload_node) {
2468 cset->mg_src_cgrp = NULL;
2469 cset->mg_dst_cgrp = NULL;
2470 cset->mg_dst_cset = NULL;
2471 list_del_init(&cset->mg_preload_node);
2472 put_css_set_locked(cset);
2475 spin_unlock_irq(&css_set_lock);
2479 * cgroup_migrate_add_src - add a migration source css_set
2480 * @src_cset: the source css_set to add
2481 * @dst_cgrp: the destination cgroup
2482 * @mgctx: migration context
2484 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2485 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2486 * up by cgroup_migrate_finish().
2488 * This function may be called without holding cgroup_threadgroup_rwsem
2489 * even if the target is a process. Threads may be created and destroyed
2490 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2491 * into play and the preloaded css_sets are guaranteed to cover all
2494 void cgroup_migrate_add_src(struct css_set *src_cset,
2495 struct cgroup *dst_cgrp,
2496 struct cgroup_mgctx *mgctx)
2498 struct cgroup *src_cgrp;
2500 lockdep_assert_held(&cgroup_mutex);
2501 lockdep_assert_held(&css_set_lock);
2504 * If ->dead, @src_set is associated with one or more dead cgroups
2505 * and doesn't contain any migratable tasks. Ignore it early so
2506 * that the rest of migration path doesn't get confused by it.
2511 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2513 if (!list_empty(&src_cset->mg_preload_node))
2516 WARN_ON(src_cset->mg_src_cgrp);
2517 WARN_ON(src_cset->mg_dst_cgrp);
2518 WARN_ON(!list_empty(&src_cset->mg_tasks));
2519 WARN_ON(!list_empty(&src_cset->mg_node));
2521 src_cset->mg_src_cgrp = src_cgrp;
2522 src_cset->mg_dst_cgrp = dst_cgrp;
2523 get_css_set(src_cset);
2524 list_add_tail(&src_cset->mg_preload_node, &mgctx->preloaded_src_csets);
2528 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2529 * @mgctx: migration context
2531 * Tasks are about to be moved and all the source css_sets have been
2532 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2533 * pins all destination css_sets, links each to its source, and append them
2534 * to @mgctx->preloaded_dst_csets.
2536 * This function must be called after cgroup_migrate_add_src() has been
2537 * called on each migration source css_set. After migration is performed
2538 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2541 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2543 struct css_set *src_cset, *tmp_cset;
2545 lockdep_assert_held(&cgroup_mutex);
2547 /* look up the dst cset for each src cset and link it to src */
2548 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2550 struct css_set *dst_cset;
2551 struct cgroup_subsys *ss;
2554 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2558 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2561 * If src cset equals dst, it's noop. Drop the src.
2562 * cgroup_migrate() will skip the cset too. Note that we
2563 * can't handle src == dst as some nodes are used by both.
2565 if (src_cset == dst_cset) {
2566 src_cset->mg_src_cgrp = NULL;
2567 src_cset->mg_dst_cgrp = NULL;
2568 list_del_init(&src_cset->mg_preload_node);
2569 put_css_set(src_cset);
2570 put_css_set(dst_cset);
2574 src_cset->mg_dst_cset = dst_cset;
2576 if (list_empty(&dst_cset->mg_preload_node))
2577 list_add_tail(&dst_cset->mg_preload_node,
2578 &mgctx->preloaded_dst_csets);
2580 put_css_set(dst_cset);
2582 for_each_subsys(ss, ssid)
2583 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2584 mgctx->ss_mask |= 1 << ssid;
2589 cgroup_migrate_finish(mgctx);
2594 * cgroup_migrate - migrate a process or task to a cgroup
2595 * @leader: the leader of the process or the task to migrate
2596 * @threadgroup: whether @leader points to the whole process or a single task
2597 * @mgctx: migration context
2599 * Migrate a process or task denoted by @leader. If migrating a process,
2600 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2601 * responsible for invoking cgroup_migrate_add_src() and
2602 * cgroup_migrate_prepare_dst() on the targets before invoking this
2603 * function and following up with cgroup_migrate_finish().
2605 * As long as a controller's ->can_attach() doesn't fail, this function is
2606 * guaranteed to succeed. This means that, excluding ->can_attach()
2607 * failure, when migrating multiple targets, the success or failure can be
2608 * decided for all targets by invoking group_migrate_prepare_dst() before
2609 * actually starting migrating.
2611 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2612 struct cgroup_mgctx *mgctx)
2614 struct task_struct *task;
2617 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2618 * already PF_EXITING could be freed from underneath us unless we
2619 * take an rcu_read_lock.
2621 spin_lock_irq(&css_set_lock);
2625 cgroup_migrate_add_task(task, mgctx);
2628 } while_each_thread(leader, task);
2630 spin_unlock_irq(&css_set_lock);
2632 return cgroup_migrate_execute(mgctx);
2636 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2637 * @dst_cgrp: the cgroup to attach to
2638 * @leader: the task or the leader of the threadgroup to be attached
2639 * @threadgroup: attach the whole threadgroup?
2641 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2643 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2646 DEFINE_CGROUP_MGCTX(mgctx);
2647 struct task_struct *task;
2650 ret = cgroup_migrate_vet_dst(dst_cgrp);
2654 /* look up all src csets */
2655 spin_lock_irq(&css_set_lock);
2659 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2662 } while_each_thread(leader, task);
2664 spin_unlock_irq(&css_set_lock);
2666 /* prepare dst csets and commit */
2667 ret = cgroup_migrate_prepare_dst(&mgctx);
2669 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2671 cgroup_migrate_finish(&mgctx);
2674 TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
2679 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup)
2680 __acquires(&cgroup_threadgroup_rwsem)
2682 struct task_struct *tsk;
2685 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2686 return ERR_PTR(-EINVAL);
2688 percpu_down_write(&cgroup_threadgroup_rwsem);
2692 tsk = find_task_by_vpid(pid);
2694 tsk = ERR_PTR(-ESRCH);
2695 goto out_unlock_threadgroup;
2702 tsk = tsk->group_leader;
2705 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2706 * If userland migrates such a kthread to a non-root cgroup, it can
2707 * become trapped in a cpuset, or RT kthread may be born in a
2708 * cgroup with no rt_runtime allocated. Just say no.
2710 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2711 tsk = ERR_PTR(-EINVAL);
2712 goto out_unlock_threadgroup;
2715 get_task_struct(tsk);
2716 goto out_unlock_rcu;
2718 out_unlock_threadgroup:
2719 percpu_up_write(&cgroup_threadgroup_rwsem);
2725 void cgroup_procs_write_finish(struct task_struct *task)
2726 __releases(&cgroup_threadgroup_rwsem)
2728 struct cgroup_subsys *ss;
2731 /* release reference from cgroup_procs_write_start() */
2732 put_task_struct(task);
2734 percpu_up_write(&cgroup_threadgroup_rwsem);
2735 for_each_subsys(ss, ssid)
2736 if (ss->post_attach)
2740 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2742 struct cgroup_subsys *ss;
2743 bool printed = false;
2746 do_each_subsys_mask(ss, ssid, ss_mask) {
2749 seq_printf(seq, "%s", ss->name);
2751 } while_each_subsys_mask();
2753 seq_putc(seq, '\n');
2756 /* show controllers which are enabled from the parent */
2757 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2759 struct cgroup *cgrp = seq_css(seq)->cgroup;
2761 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2765 /* show controllers which are enabled for a given cgroup's children */
2766 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2768 struct cgroup *cgrp = seq_css(seq)->cgroup;
2770 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2775 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2776 * @cgrp: root of the subtree to update csses for
2778 * @cgrp's control masks have changed and its subtree's css associations
2779 * need to be updated accordingly. This function looks up all css_sets
2780 * which are attached to the subtree, creates the matching updated css_sets
2781 * and migrates the tasks to the new ones.
2783 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2785 DEFINE_CGROUP_MGCTX(mgctx);
2786 struct cgroup_subsys_state *d_css;
2787 struct cgroup *dsct;
2788 struct css_set *src_cset;
2791 lockdep_assert_held(&cgroup_mutex);
2793 percpu_down_write(&cgroup_threadgroup_rwsem);
2795 /* look up all csses currently attached to @cgrp's subtree */
2796 spin_lock_irq(&css_set_lock);
2797 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2798 struct cgrp_cset_link *link;
2800 list_for_each_entry(link, &dsct->cset_links, cset_link)
2801 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2803 spin_unlock_irq(&css_set_lock);
2805 /* NULL dst indicates self on default hierarchy */
2806 ret = cgroup_migrate_prepare_dst(&mgctx);
2810 spin_lock_irq(&css_set_lock);
2811 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets, mg_preload_node) {
2812 struct task_struct *task, *ntask;
2814 /* all tasks in src_csets need to be migrated */
2815 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2816 cgroup_migrate_add_task(task, &mgctx);
2818 spin_unlock_irq(&css_set_lock);
2820 ret = cgroup_migrate_execute(&mgctx);
2822 cgroup_migrate_finish(&mgctx);
2823 percpu_up_write(&cgroup_threadgroup_rwsem);
2828 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2829 * @cgrp: root of the target subtree
2831 * Because css offlining is asynchronous, userland may try to re-enable a
2832 * controller while the previous css is still around. This function grabs
2833 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2835 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2836 __acquires(&cgroup_mutex)
2838 struct cgroup *dsct;
2839 struct cgroup_subsys_state *d_css;
2840 struct cgroup_subsys *ss;
2844 mutex_lock(&cgroup_mutex);
2846 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2847 for_each_subsys(ss, ssid) {
2848 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2851 if (!css || !percpu_ref_is_dying(&css->refcnt))
2854 cgroup_get_live(dsct);
2855 prepare_to_wait(&dsct->offline_waitq, &wait,
2856 TASK_UNINTERRUPTIBLE);
2858 mutex_unlock(&cgroup_mutex);
2860 finish_wait(&dsct->offline_waitq, &wait);
2869 * cgroup_save_control - save control masks and dom_cgrp of a subtree
2870 * @cgrp: root of the target subtree
2872 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
2873 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2876 static void cgroup_save_control(struct cgroup *cgrp)
2878 struct cgroup *dsct;
2879 struct cgroup_subsys_state *d_css;
2881 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2882 dsct->old_subtree_control = dsct->subtree_control;
2883 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
2884 dsct->old_dom_cgrp = dsct->dom_cgrp;
2889 * cgroup_propagate_control - refresh control masks of a subtree
2890 * @cgrp: root of the target subtree
2892 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
2893 * ->subtree_control and propagate controller availability through the
2894 * subtree so that descendants don't have unavailable controllers enabled.
2896 static void cgroup_propagate_control(struct cgroup *cgrp)
2898 struct cgroup *dsct;
2899 struct cgroup_subsys_state *d_css;
2901 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2902 dsct->subtree_control &= cgroup_control(dsct);
2903 dsct->subtree_ss_mask =
2904 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
2905 cgroup_ss_mask(dsct));
2910 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
2911 * @cgrp: root of the target subtree
2913 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
2914 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2917 static void cgroup_restore_control(struct cgroup *cgrp)
2919 struct cgroup *dsct;
2920 struct cgroup_subsys_state *d_css;
2922 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2923 dsct->subtree_control = dsct->old_subtree_control;
2924 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
2925 dsct->dom_cgrp = dsct->old_dom_cgrp;
2929 static bool css_visible(struct cgroup_subsys_state *css)
2931 struct cgroup_subsys *ss = css->ss;
2932 struct cgroup *cgrp = css->cgroup;
2934 if (cgroup_control(cgrp) & (1 << ss->id))
2936 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
2938 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
2942 * cgroup_apply_control_enable - enable or show csses according to control
2943 * @cgrp: root of the target subtree
2945 * Walk @cgrp's subtree and create new csses or make the existing ones
2946 * visible. A css is created invisible if it's being implicitly enabled
2947 * through dependency. An invisible css is made visible when the userland
2948 * explicitly enables it.
2950 * Returns 0 on success, -errno on failure. On failure, csses which have
2951 * been processed already aren't cleaned up. The caller is responsible for
2952 * cleaning up with cgroup_apply_control_disable().
2954 static int cgroup_apply_control_enable(struct cgroup *cgrp)
2956 struct cgroup *dsct;
2957 struct cgroup_subsys_state *d_css;
2958 struct cgroup_subsys *ss;
2961 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2962 for_each_subsys(ss, ssid) {
2963 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2965 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
2967 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
2971 css = css_create(dsct, ss);
2973 return PTR_ERR(css);
2976 if (css_visible(css)) {
2977 ret = css_populate_dir(css);
2988 * cgroup_apply_control_disable - kill or hide csses according to control
2989 * @cgrp: root of the target subtree
2991 * Walk @cgrp's subtree and kill and hide csses so that they match
2992 * cgroup_ss_mask() and cgroup_visible_mask().
2994 * A css is hidden when the userland requests it to be disabled while other
2995 * subsystems are still depending on it. The css must not actively control
2996 * resources and be in the vanilla state if it's made visible again later.
2997 * Controllers which may be depended upon should provide ->css_reset() for
3000 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3002 struct cgroup *dsct;
3003 struct cgroup_subsys_state *d_css;
3004 struct cgroup_subsys *ss;
3007 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3008 for_each_subsys(ss, ssid) {
3009 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3011 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
3017 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3019 } else if (!css_visible(css)) {
3029 * cgroup_apply_control - apply control mask updates to the subtree
3030 * @cgrp: root of the target subtree
3032 * subsystems can be enabled and disabled in a subtree using the following
3035 * 1. Call cgroup_save_control() to stash the current state.
3036 * 2. Update ->subtree_control masks in the subtree as desired.
3037 * 3. Call cgroup_apply_control() to apply the changes.
3038 * 4. Optionally perform other related operations.
3039 * 5. Call cgroup_finalize_control() to finish up.
3041 * This function implements step 3 and propagates the mask changes
3042 * throughout @cgrp's subtree, updates csses accordingly and perform
3043 * process migrations.
3045 static int cgroup_apply_control(struct cgroup *cgrp)
3049 cgroup_propagate_control(cgrp);
3051 ret = cgroup_apply_control_enable(cgrp);
3056 * At this point, cgroup_e_css_by_mask() results reflect the new csses
3057 * making the following cgroup_update_dfl_csses() properly update
3058 * css associations of all tasks in the subtree.
3060 ret = cgroup_update_dfl_csses(cgrp);
3068 * cgroup_finalize_control - finalize control mask update
3069 * @cgrp: root of the target subtree
3070 * @ret: the result of the update
3072 * Finalize control mask update. See cgroup_apply_control() for more info.
3074 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3077 cgroup_restore_control(cgrp);
3078 cgroup_propagate_control(cgrp);
3081 cgroup_apply_control_disable(cgrp);
3084 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3086 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3088 /* if nothing is getting enabled, nothing to worry about */
3092 /* can @cgrp host any resources? */
3093 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3096 /* mixables don't care */
3097 if (cgroup_is_mixable(cgrp))
3100 if (domain_enable) {
3101 /* can't enable domain controllers inside a thread subtree */
3102 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3106 * Threaded controllers can handle internal competitions
3107 * and are always allowed inside a (prospective) thread
3110 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3115 * Controllers can't be enabled for a cgroup with tasks to avoid
3116 * child cgroups competing against tasks.
3118 if (cgroup_has_tasks(cgrp))
3124 /* change the enabled child controllers for a cgroup in the default hierarchy */
3125 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3126 char *buf, size_t nbytes,
3129 u16 enable = 0, disable = 0;
3130 struct cgroup *cgrp, *child;
3131 struct cgroup_subsys *ss;
3136 * Parse input - space separated list of subsystem names prefixed
3137 * with either + or -.
3139 buf = strstrip(buf);
3140 while ((tok = strsep(&buf, " "))) {
3143 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3144 if (!cgroup_ssid_enabled(ssid) ||
3145 strcmp(tok + 1, ss->name))
3149 enable |= 1 << ssid;
3150 disable &= ~(1 << ssid);
3151 } else if (*tok == '-') {
3152 disable |= 1 << ssid;
3153 enable &= ~(1 << ssid);
3158 } while_each_subsys_mask();
3159 if (ssid == CGROUP_SUBSYS_COUNT)
3163 cgrp = cgroup_kn_lock_live(of->kn, true);
3167 for_each_subsys(ss, ssid) {
3168 if (enable & (1 << ssid)) {
3169 if (cgrp->subtree_control & (1 << ssid)) {
3170 enable &= ~(1 << ssid);
3174 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3178 } else if (disable & (1 << ssid)) {
3179 if (!(cgrp->subtree_control & (1 << ssid))) {
3180 disable &= ~(1 << ssid);
3184 /* a child has it enabled? */
3185 cgroup_for_each_live_child(child, cgrp) {
3186 if (child->subtree_control & (1 << ssid)) {
3194 if (!enable && !disable) {
3199 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3203 /* save and update control masks and prepare csses */
3204 cgroup_save_control(cgrp);
3206 cgrp->subtree_control |= enable;
3207 cgrp->subtree_control &= ~disable;
3209 ret = cgroup_apply_control(cgrp);
3210 cgroup_finalize_control(cgrp, ret);
3214 kernfs_activate(cgrp->kn);
3216 cgroup_kn_unlock(of->kn);
3217 return ret ?: nbytes;
3221 * cgroup_enable_threaded - make @cgrp threaded
3222 * @cgrp: the target cgroup
3224 * Called when "threaded" is written to the cgroup.type interface file and
3225 * tries to make @cgrp threaded and join the parent's resource domain.
3226 * This function is never called on the root cgroup as cgroup.type doesn't
3229 static int cgroup_enable_threaded(struct cgroup *cgrp)
3231 struct cgroup *parent = cgroup_parent(cgrp);
3232 struct cgroup *dom_cgrp = parent->dom_cgrp;
3233 struct cgroup *dsct;
3234 struct cgroup_subsys_state *d_css;
3237 lockdep_assert_held(&cgroup_mutex);
3239 /* noop if already threaded */
3240 if (cgroup_is_threaded(cgrp))
3244 * If @cgroup is populated or has domain controllers enabled, it
3245 * can't be switched. While the below cgroup_can_be_thread_root()
3246 * test can catch the same conditions, that's only when @parent is
3247 * not mixable, so let's check it explicitly.
3249 if (cgroup_is_populated(cgrp) ||
3250 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3253 /* we're joining the parent's domain, ensure its validity */
3254 if (!cgroup_is_valid_domain(dom_cgrp) ||
3255 !cgroup_can_be_thread_root(dom_cgrp))
3259 * The following shouldn't cause actual migrations and should
3262 cgroup_save_control(cgrp);
3264 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3265 if (dsct == cgrp || cgroup_is_threaded(dsct))
3266 dsct->dom_cgrp = dom_cgrp;
3268 ret = cgroup_apply_control(cgrp);
3270 parent->nr_threaded_children++;
3272 cgroup_finalize_control(cgrp, ret);
3276 static int cgroup_type_show(struct seq_file *seq, void *v)
3278 struct cgroup *cgrp = seq_css(seq)->cgroup;
3280 if (cgroup_is_threaded(cgrp))
3281 seq_puts(seq, "threaded\n");
3282 else if (!cgroup_is_valid_domain(cgrp))
3283 seq_puts(seq, "domain invalid\n");
3284 else if (cgroup_is_thread_root(cgrp))
3285 seq_puts(seq, "domain threaded\n");
3287 seq_puts(seq, "domain\n");
3292 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3293 size_t nbytes, loff_t off)
3295 struct cgroup *cgrp;
3298 /* only switching to threaded mode is supported */
3299 if (strcmp(strstrip(buf), "threaded"))
3302 cgrp = cgroup_kn_lock_live(of->kn, false);
3306 /* threaded can only be enabled */
3307 ret = cgroup_enable_threaded(cgrp);
3309 cgroup_kn_unlock(of->kn);
3310 return ret ?: nbytes;
3313 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3315 struct cgroup *cgrp = seq_css(seq)->cgroup;
3316 int descendants = READ_ONCE(cgrp->max_descendants);
3318 if (descendants == INT_MAX)
3319 seq_puts(seq, "max\n");
3321 seq_printf(seq, "%d\n", descendants);
3326 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3327 char *buf, size_t nbytes, loff_t off)
3329 struct cgroup *cgrp;
3333 buf = strstrip(buf);
3334 if (!strcmp(buf, "max")) {
3335 descendants = INT_MAX;
3337 ret = kstrtoint(buf, 0, &descendants);
3342 if (descendants < 0)
3345 cgrp = cgroup_kn_lock_live(of->kn, false);
3349 cgrp->max_descendants = descendants;
3351 cgroup_kn_unlock(of->kn);
3356 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3358 struct cgroup *cgrp = seq_css(seq)->cgroup;
3359 int depth = READ_ONCE(cgrp->max_depth);
3361 if (depth == INT_MAX)
3362 seq_puts(seq, "max\n");
3364 seq_printf(seq, "%d\n", depth);
3369 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3370 char *buf, size_t nbytes, loff_t off)
3372 struct cgroup *cgrp;
3376 buf = strstrip(buf);
3377 if (!strcmp(buf, "max")) {
3380 ret = kstrtoint(buf, 0, &depth);
3388 cgrp = cgroup_kn_lock_live(of->kn, false);
3392 cgrp->max_depth = depth;
3394 cgroup_kn_unlock(of->kn);
3399 static int cgroup_events_show(struct seq_file *seq, void *v)
3401 seq_printf(seq, "populated %d\n",
3402 cgroup_is_populated(seq_css(seq)->cgroup));
3406 static int cgroup_stat_show(struct seq_file *seq, void *v)
3408 struct cgroup *cgroup = seq_css(seq)->cgroup;
3410 seq_printf(seq, "nr_descendants %d\n",
3411 cgroup->nr_descendants);
3412 seq_printf(seq, "nr_dying_descendants %d\n",
3413 cgroup->nr_dying_descendants);
3418 static int __maybe_unused cgroup_extra_stat_show(struct seq_file *seq,
3419 struct cgroup *cgrp, int ssid)
3421 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3422 struct cgroup_subsys_state *css;
3425 if (!ss->css_extra_stat_show)
3428 css = cgroup_tryget_css(cgrp, ss);
3432 ret = ss->css_extra_stat_show(seq, css);
3437 static int cpu_stat_show(struct seq_file *seq, void *v)
3439 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3442 cgroup_base_stat_cputime_show(seq);
3443 #ifdef CONFIG_CGROUP_SCHED
3444 ret = cgroup_extra_stat_show(seq, cgrp, cpu_cgrp_id);
3449 static int cgroup_file_open(struct kernfs_open_file *of)
3451 struct cftype *cft = of->kn->priv;
3454 return cft->open(of);
3458 static void cgroup_file_release(struct kernfs_open_file *of)
3460 struct cftype *cft = of->kn->priv;
3466 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3467 size_t nbytes, loff_t off)
3469 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
3470 struct cgroup *cgrp = of->kn->parent->priv;
3471 struct cftype *cft = of->kn->priv;
3472 struct cgroup_subsys_state *css;
3476 * If namespaces are delegation boundaries, disallow writes to
3477 * files in an non-init namespace root from inside the namespace
3478 * except for the files explicitly marked delegatable -
3479 * cgroup.procs and cgroup.subtree_control.
3481 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3482 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3483 ns != &init_cgroup_ns && ns->root_cset->dfl_cgrp == cgrp)
3487 return cft->write(of, buf, nbytes, off);
3490 * kernfs guarantees that a file isn't deleted with operations in
3491 * flight, which means that the matching css is and stays alive and
3492 * doesn't need to be pinned. The RCU locking is not necessary
3493 * either. It's just for the convenience of using cgroup_css().
3496 css = cgroup_css(cgrp, cft->ss);
3499 if (cft->write_u64) {
3500 unsigned long long v;
3501 ret = kstrtoull(buf, 0, &v);
3503 ret = cft->write_u64(css, cft, v);
3504 } else if (cft->write_s64) {
3506 ret = kstrtoll(buf, 0, &v);
3508 ret = cft->write_s64(css, cft, v);