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 int cgroup_do_mount(struct fs_context *fc, unsigned long magic,
2040 struct cgroup_namespace *ns)
2042 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2043 bool new_sb = false;
2046 fc->root = kernfs_mount(fc->fs_type, fc->sb_flags, ctx->root->kf_root,
2048 if (IS_ERR(fc->root))
2049 ret = PTR_ERR(fc->root);
2052 * In non-init cgroup namespace, instead of root cgroup's dentry,
2053 * we return the dentry corresponding to the cgroupns->root_cgrp.
2055 if (!ret && ns != &init_cgroup_ns) {
2056 struct dentry *nsdentry;
2057 struct super_block *sb = fc->root->d_sb;
2058 struct cgroup *cgrp;
2060 mutex_lock(&cgroup_mutex);
2061 spin_lock_irq(&css_set_lock);
2063 cgrp = cset_cgroup_from_root(ns->root_cset, ctx->root);
2065 spin_unlock_irq(&css_set_lock);
2066 mutex_unlock(&cgroup_mutex);
2068 nsdentry = kernfs_node_dentry(cgrp->kn, sb);
2070 fc->root = nsdentry;
2071 if (IS_ERR(nsdentry)) {
2072 ret = PTR_ERR(nsdentry);
2073 deactivate_locked_super(sb);
2078 cgroup_put(&ctx->root->cgrp);
2084 * Destroy a cgroup filesystem context.
2086 static void cgroup_fs_context_free(struct fs_context *fc)
2088 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2091 kfree(ctx->release_agent);
2095 static int cgroup_get_tree(struct fs_context *fc)
2097 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
2098 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2101 /* Check if the caller has permission to mount. */
2102 if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN))
2105 cgrp_dfl_visible = true;
2106 cgroup_get_live(&cgrp_dfl_root.cgrp);
2107 ctx->root = &cgrp_dfl_root;
2109 ret = cgroup_do_mount(fc, CGROUP2_SUPER_MAGIC, ns);
2111 apply_cgroup_root_flags(ctx->flags);
2115 static const struct fs_context_operations cgroup_fs_context_ops = {
2116 .free = cgroup_fs_context_free,
2117 .parse_param = cgroup2_parse_param,
2118 .get_tree = cgroup_get_tree,
2119 .reconfigure = cgroup_reconfigure,
2122 static const struct fs_context_operations cgroup1_fs_context_ops = {
2123 .free = cgroup_fs_context_free,
2124 .parse_param = cgroup1_parse_param,
2125 .get_tree = cgroup1_get_tree,
2126 .reconfigure = cgroup1_reconfigure,
2130 * Initialise the cgroup filesystem creation/reconfiguration context.
2132 static int cgroup_init_fs_context(struct fs_context *fc)
2134 struct cgroup_fs_context *ctx;
2136 ctx = kzalloc(sizeof(struct cgroup_fs_context), GFP_KERNEL);
2141 * The first time anyone tries to mount a cgroup, enable the list
2142 * linking each css_set to its tasks and fix up all existing tasks.
2144 if (!use_task_css_set_links)
2145 cgroup_enable_task_cg_lists();
2147 fc->fs_private = ctx;
2148 if (fc->fs_type == &cgroup2_fs_type)
2149 fc->ops = &cgroup_fs_context_ops;
2151 fc->ops = &cgroup1_fs_context_ops;
2155 static void cgroup_kill_sb(struct super_block *sb)
2157 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2158 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2161 * If @root doesn't have any children, start killing it.
2162 * This prevents new mounts by disabling percpu_ref_tryget_live().
2163 * cgroup_mount() may wait for @root's release.
2165 * And don't kill the default root.
2167 if (list_empty(&root->cgrp.self.children) && root != &cgrp_dfl_root &&
2168 !percpu_ref_is_dying(&root->cgrp.self.refcnt))
2169 percpu_ref_kill(&root->cgrp.self.refcnt);
2170 cgroup_put(&root->cgrp);
2174 struct file_system_type cgroup_fs_type = {
2176 .init_fs_context = cgroup_init_fs_context,
2177 .parameters = &cgroup1_fs_parameters,
2178 .kill_sb = cgroup_kill_sb,
2179 .fs_flags = FS_USERNS_MOUNT,
2182 static struct file_system_type cgroup2_fs_type = {
2184 .init_fs_context = cgroup_init_fs_context,
2185 .parameters = &cgroup2_fs_parameters,
2186 .kill_sb = cgroup_kill_sb,
2187 .fs_flags = FS_USERNS_MOUNT,
2190 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2191 struct cgroup_namespace *ns)
2193 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2195 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2198 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2199 struct cgroup_namespace *ns)
2203 mutex_lock(&cgroup_mutex);
2204 spin_lock_irq(&css_set_lock);
2206 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2208 spin_unlock_irq(&css_set_lock);
2209 mutex_unlock(&cgroup_mutex);
2213 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2216 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2217 * @task: target task
2218 * @buf: the buffer to write the path into
2219 * @buflen: the length of the buffer
2221 * Determine @task's cgroup on the first (the one with the lowest non-zero
2222 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2223 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2224 * cgroup controller callbacks.
2226 * Return value is the same as kernfs_path().
2228 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2230 struct cgroup_root *root;
2231 struct cgroup *cgrp;
2232 int hierarchy_id = 1;
2235 mutex_lock(&cgroup_mutex);
2236 spin_lock_irq(&css_set_lock);
2238 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2241 cgrp = task_cgroup_from_root(task, root);
2242 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2244 /* if no hierarchy exists, everyone is in "/" */
2245 ret = strlcpy(buf, "/", buflen);
2248 spin_unlock_irq(&css_set_lock);
2249 mutex_unlock(&cgroup_mutex);
2252 EXPORT_SYMBOL_GPL(task_cgroup_path);
2255 * cgroup_migrate_add_task - add a migration target task to a migration context
2256 * @task: target task
2257 * @mgctx: target migration context
2259 * Add @task, which is a migration target, to @mgctx->tset. This function
2260 * becomes noop if @task doesn't need to be migrated. @task's css_set
2261 * should have been added as a migration source and @task->cg_list will be
2262 * moved from the css_set's tasks list to mg_tasks one.
2264 static void cgroup_migrate_add_task(struct task_struct *task,
2265 struct cgroup_mgctx *mgctx)
2267 struct css_set *cset;
2269 lockdep_assert_held(&css_set_lock);
2271 /* @task either already exited or can't exit until the end */
2272 if (task->flags & PF_EXITING)
2275 /* leave @task alone if post_fork() hasn't linked it yet */
2276 if (list_empty(&task->cg_list))
2279 cset = task_css_set(task);
2280 if (!cset->mg_src_cgrp)
2283 mgctx->tset.nr_tasks++;
2285 list_move_tail(&task->cg_list, &cset->mg_tasks);
2286 if (list_empty(&cset->mg_node))
2287 list_add_tail(&cset->mg_node,
2288 &mgctx->tset.src_csets);
2289 if (list_empty(&cset->mg_dst_cset->mg_node))
2290 list_add_tail(&cset->mg_dst_cset->mg_node,
2291 &mgctx->tset.dst_csets);
2295 * cgroup_taskset_first - reset taskset and return the first task
2296 * @tset: taskset of interest
2297 * @dst_cssp: output variable for the destination css
2299 * @tset iteration is initialized and the first task is returned.
2301 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2302 struct cgroup_subsys_state **dst_cssp)
2304 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2305 tset->cur_task = NULL;
2307 return cgroup_taskset_next(tset, dst_cssp);
2311 * cgroup_taskset_next - iterate to the next task in taskset
2312 * @tset: taskset of interest
2313 * @dst_cssp: output variable for the destination css
2315 * Return the next task in @tset. Iteration must have been initialized
2316 * with cgroup_taskset_first().
2318 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2319 struct cgroup_subsys_state **dst_cssp)
2321 struct css_set *cset = tset->cur_cset;
2322 struct task_struct *task = tset->cur_task;
2324 while (&cset->mg_node != tset->csets) {
2326 task = list_first_entry(&cset->mg_tasks,
2327 struct task_struct, cg_list);
2329 task = list_next_entry(task, cg_list);
2331 if (&task->cg_list != &cset->mg_tasks) {
2332 tset->cur_cset = cset;
2333 tset->cur_task = task;
2336 * This function may be called both before and
2337 * after cgroup_taskset_migrate(). The two cases
2338 * can be distinguished by looking at whether @cset
2339 * has its ->mg_dst_cset set.
2341 if (cset->mg_dst_cset)
2342 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2344 *dst_cssp = cset->subsys[tset->ssid];
2349 cset = list_next_entry(cset, mg_node);
2357 * cgroup_taskset_migrate - migrate a taskset
2358 * @mgctx: migration context
2360 * Migrate tasks in @mgctx as setup by migration preparation functions.
2361 * This function fails iff one of the ->can_attach callbacks fails and
2362 * guarantees that either all or none of the tasks in @mgctx are migrated.
2363 * @mgctx is consumed regardless of success.
2365 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2367 struct cgroup_taskset *tset = &mgctx->tset;
2368 struct cgroup_subsys *ss;
2369 struct task_struct *task, *tmp_task;
2370 struct css_set *cset, *tmp_cset;
2371 int ssid, failed_ssid, ret;
2373 /* check that we can legitimately attach to the cgroup */
2374 if (tset->nr_tasks) {
2375 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2376 if (ss->can_attach) {
2378 ret = ss->can_attach(tset);
2381 goto out_cancel_attach;
2384 } while_each_subsys_mask();
2388 * Now that we're guaranteed success, proceed to move all tasks to
2389 * the new cgroup. There are no failure cases after here, so this
2390 * is the commit point.
2392 spin_lock_irq(&css_set_lock);
2393 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2394 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2395 struct css_set *from_cset = task_css_set(task);
2396 struct css_set *to_cset = cset->mg_dst_cset;
2398 get_css_set(to_cset);
2399 to_cset->nr_tasks++;
2400 css_set_move_task(task, from_cset, to_cset, true);
2401 put_css_set_locked(from_cset);
2402 from_cset->nr_tasks--;
2405 spin_unlock_irq(&css_set_lock);
2408 * Migration is committed, all target tasks are now on dst_csets.
2409 * Nothing is sensitive to fork() after this point. Notify
2410 * controllers that migration is complete.
2412 tset->csets = &tset->dst_csets;
2414 if (tset->nr_tasks) {
2415 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2420 } while_each_subsys_mask();
2424 goto out_release_tset;
2427 if (tset->nr_tasks) {
2428 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2429 if (ssid == failed_ssid)
2431 if (ss->cancel_attach) {
2433 ss->cancel_attach(tset);
2435 } while_each_subsys_mask();
2438 spin_lock_irq(&css_set_lock);
2439 list_splice_init(&tset->dst_csets, &tset->src_csets);
2440 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2441 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2442 list_del_init(&cset->mg_node);
2444 spin_unlock_irq(&css_set_lock);
2447 * Re-initialize the cgroup_taskset structure in case it is reused
2448 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2452 tset->csets = &tset->src_csets;
2457 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2458 * @dst_cgrp: destination cgroup to test
2460 * On the default hierarchy, except for the mixable, (possible) thread root
2461 * and threaded cgroups, subtree_control must be zero for migration
2462 * destination cgroups with tasks so that child cgroups don't compete
2465 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2467 /* v1 doesn't have any restriction */
2468 if (!cgroup_on_dfl(dst_cgrp))
2471 /* verify @dst_cgrp can host resources */
2472 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2475 /* mixables don't care */
2476 if (cgroup_is_mixable(dst_cgrp))
2480 * If @dst_cgrp is already or can become a thread root or is
2481 * threaded, it doesn't matter.
2483 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2486 /* apply no-internal-process constraint */
2487 if (dst_cgrp->subtree_control)
2494 * cgroup_migrate_finish - cleanup after attach
2495 * @mgctx: migration context
2497 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2498 * those functions for details.
2500 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2502 LIST_HEAD(preloaded);
2503 struct css_set *cset, *tmp_cset;
2505 lockdep_assert_held(&cgroup_mutex);
2507 spin_lock_irq(&css_set_lock);
2509 list_splice_tail_init(&mgctx->preloaded_src_csets, &preloaded);
2510 list_splice_tail_init(&mgctx->preloaded_dst_csets, &preloaded);
2512 list_for_each_entry_safe(cset, tmp_cset, &preloaded, mg_preload_node) {
2513 cset->mg_src_cgrp = NULL;
2514 cset->mg_dst_cgrp = NULL;
2515 cset->mg_dst_cset = NULL;
2516 list_del_init(&cset->mg_preload_node);
2517 put_css_set_locked(cset);
2520 spin_unlock_irq(&css_set_lock);
2524 * cgroup_migrate_add_src - add a migration source css_set
2525 * @src_cset: the source css_set to add
2526 * @dst_cgrp: the destination cgroup
2527 * @mgctx: migration context
2529 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2530 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2531 * up by cgroup_migrate_finish().
2533 * This function may be called without holding cgroup_threadgroup_rwsem
2534 * even if the target is a process. Threads may be created and destroyed
2535 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2536 * into play and the preloaded css_sets are guaranteed to cover all
2539 void cgroup_migrate_add_src(struct css_set *src_cset,
2540 struct cgroup *dst_cgrp,
2541 struct cgroup_mgctx *mgctx)
2543 struct cgroup *src_cgrp;
2545 lockdep_assert_held(&cgroup_mutex);
2546 lockdep_assert_held(&css_set_lock);
2549 * If ->dead, @src_set is associated with one or more dead cgroups
2550 * and doesn't contain any migratable tasks. Ignore it early so
2551 * that the rest of migration path doesn't get confused by it.
2556 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2558 if (!list_empty(&src_cset->mg_preload_node))
2561 WARN_ON(src_cset->mg_src_cgrp);
2562 WARN_ON(src_cset->mg_dst_cgrp);
2563 WARN_ON(!list_empty(&src_cset->mg_tasks));
2564 WARN_ON(!list_empty(&src_cset->mg_node));
2566 src_cset->mg_src_cgrp = src_cgrp;
2567 src_cset->mg_dst_cgrp = dst_cgrp;
2568 get_css_set(src_cset);
2569 list_add_tail(&src_cset->mg_preload_node, &mgctx->preloaded_src_csets);
2573 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2574 * @mgctx: migration context
2576 * Tasks are about to be moved and all the source css_sets have been
2577 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2578 * pins all destination css_sets, links each to its source, and append them
2579 * to @mgctx->preloaded_dst_csets.
2581 * This function must be called after cgroup_migrate_add_src() has been
2582 * called on each migration source css_set. After migration is performed
2583 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2586 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2588 struct css_set *src_cset, *tmp_cset;
2590 lockdep_assert_held(&cgroup_mutex);
2592 /* look up the dst cset for each src cset and link it to src */
2593 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2595 struct css_set *dst_cset;
2596 struct cgroup_subsys *ss;
2599 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2603 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2606 * If src cset equals dst, it's noop. Drop the src.
2607 * cgroup_migrate() will skip the cset too. Note that we
2608 * can't handle src == dst as some nodes are used by both.
2610 if (src_cset == dst_cset) {
2611 src_cset->mg_src_cgrp = NULL;
2612 src_cset->mg_dst_cgrp = NULL;
2613 list_del_init(&src_cset->mg_preload_node);
2614 put_css_set(src_cset);
2615 put_css_set(dst_cset);
2619 src_cset->mg_dst_cset = dst_cset;
2621 if (list_empty(&dst_cset->mg_preload_node))
2622 list_add_tail(&dst_cset->mg_preload_node,
2623 &mgctx->preloaded_dst_csets);
2625 put_css_set(dst_cset);
2627 for_each_subsys(ss, ssid)
2628 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2629 mgctx->ss_mask |= 1 << ssid;
2634 cgroup_migrate_finish(mgctx);
2639 * cgroup_migrate - migrate a process or task to a cgroup
2640 * @leader: the leader of the process or the task to migrate
2641 * @threadgroup: whether @leader points to the whole process or a single task
2642 * @mgctx: migration context
2644 * Migrate a process or task denoted by @leader. If migrating a process,
2645 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2646 * responsible for invoking cgroup_migrate_add_src() and
2647 * cgroup_migrate_prepare_dst() on the targets before invoking this
2648 * function and following up with cgroup_migrate_finish().
2650 * As long as a controller's ->can_attach() doesn't fail, this function is
2651 * guaranteed to succeed. This means that, excluding ->can_attach()
2652 * failure, when migrating multiple targets, the success or failure can be
2653 * decided for all targets by invoking group_migrate_prepare_dst() before
2654 * actually starting migrating.
2656 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2657 struct cgroup_mgctx *mgctx)
2659 struct task_struct *task;
2662 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2663 * already PF_EXITING could be freed from underneath us unless we
2664 * take an rcu_read_lock.
2666 spin_lock_irq(&css_set_lock);
2670 cgroup_migrate_add_task(task, mgctx);
2673 } while_each_thread(leader, task);
2675 spin_unlock_irq(&css_set_lock);
2677 return cgroup_migrate_execute(mgctx);
2681 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2682 * @dst_cgrp: the cgroup to attach to
2683 * @leader: the task or the leader of the threadgroup to be attached
2684 * @threadgroup: attach the whole threadgroup?
2686 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2688 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2691 DEFINE_CGROUP_MGCTX(mgctx);
2692 struct task_struct *task;
2695 ret = cgroup_migrate_vet_dst(dst_cgrp);
2699 /* look up all src csets */
2700 spin_lock_irq(&css_set_lock);
2704 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2707 } while_each_thread(leader, task);
2709 spin_unlock_irq(&css_set_lock);
2711 /* prepare dst csets and commit */
2712 ret = cgroup_migrate_prepare_dst(&mgctx);
2714 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2716 cgroup_migrate_finish(&mgctx);
2719 TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
2724 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup)
2725 __acquires(&cgroup_threadgroup_rwsem)
2727 struct task_struct *tsk;
2730 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2731 return ERR_PTR(-EINVAL);
2733 percpu_down_write(&cgroup_threadgroup_rwsem);
2737 tsk = find_task_by_vpid(pid);
2739 tsk = ERR_PTR(-ESRCH);
2740 goto out_unlock_threadgroup;
2747 tsk = tsk->group_leader;
2750 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2751 * If userland migrates such a kthread to a non-root cgroup, it can
2752 * become trapped in a cpuset, or RT kthread may be born in a
2753 * cgroup with no rt_runtime allocated. Just say no.
2755 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2756 tsk = ERR_PTR(-EINVAL);
2757 goto out_unlock_threadgroup;
2760 get_task_struct(tsk);
2761 goto out_unlock_rcu;
2763 out_unlock_threadgroup:
2764 percpu_up_write(&cgroup_threadgroup_rwsem);
2770 void cgroup_procs_write_finish(struct task_struct *task)
2771 __releases(&cgroup_threadgroup_rwsem)
2773 struct cgroup_subsys *ss;
2776 /* release reference from cgroup_procs_write_start() */
2777 put_task_struct(task);
2779 percpu_up_write(&cgroup_threadgroup_rwsem);
2780 for_each_subsys(ss, ssid)
2781 if (ss->post_attach)
2785 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2787 struct cgroup_subsys *ss;
2788 bool printed = false;
2791 do_each_subsys_mask(ss, ssid, ss_mask) {
2794 seq_printf(seq, "%s", ss->name);
2796 } while_each_subsys_mask();
2798 seq_putc(seq, '\n');
2801 /* show controllers which are enabled from the parent */
2802 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2804 struct cgroup *cgrp = seq_css(seq)->cgroup;
2806 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2810 /* show controllers which are enabled for a given cgroup's children */
2811 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2813 struct cgroup *cgrp = seq_css(seq)->cgroup;
2815 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2820 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2821 * @cgrp: root of the subtree to update csses for
2823 * @cgrp's control masks have changed and its subtree's css associations
2824 * need to be updated accordingly. This function looks up all css_sets
2825 * which are attached to the subtree, creates the matching updated css_sets
2826 * and migrates the tasks to the new ones.
2828 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2830 DEFINE_CGROUP_MGCTX(mgctx);
2831 struct cgroup_subsys_state *d_css;
2832 struct cgroup *dsct;
2833 struct css_set *src_cset;
2836 lockdep_assert_held(&cgroup_mutex);
2838 percpu_down_write(&cgroup_threadgroup_rwsem);
2840 /* look up all csses currently attached to @cgrp's subtree */
2841 spin_lock_irq(&css_set_lock);
2842 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2843 struct cgrp_cset_link *link;
2845 list_for_each_entry(link, &dsct->cset_links, cset_link)
2846 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2848 spin_unlock_irq(&css_set_lock);
2850 /* NULL dst indicates self on default hierarchy */
2851 ret = cgroup_migrate_prepare_dst(&mgctx);
2855 spin_lock_irq(&css_set_lock);
2856 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets, mg_preload_node) {
2857 struct task_struct *task, *ntask;
2859 /* all tasks in src_csets need to be migrated */
2860 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2861 cgroup_migrate_add_task(task, &mgctx);
2863 spin_unlock_irq(&css_set_lock);
2865 ret = cgroup_migrate_execute(&mgctx);
2867 cgroup_migrate_finish(&mgctx);
2868 percpu_up_write(&cgroup_threadgroup_rwsem);
2873 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2874 * @cgrp: root of the target subtree
2876 * Because css offlining is asynchronous, userland may try to re-enable a
2877 * controller while the previous css is still around. This function grabs
2878 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2880 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2881 __acquires(&cgroup_mutex)
2883 struct cgroup *dsct;
2884 struct cgroup_subsys_state *d_css;
2885 struct cgroup_subsys *ss;
2889 mutex_lock(&cgroup_mutex);
2891 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2892 for_each_subsys(ss, ssid) {
2893 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2896 if (!css || !percpu_ref_is_dying(&css->refcnt))
2899 cgroup_get_live(dsct);
2900 prepare_to_wait(&dsct->offline_waitq, &wait,
2901 TASK_UNINTERRUPTIBLE);
2903 mutex_unlock(&cgroup_mutex);
2905 finish_wait(&dsct->offline_waitq, &wait);
2914 * cgroup_save_control - save control masks and dom_cgrp of a subtree
2915 * @cgrp: root of the target subtree
2917 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
2918 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2921 static void cgroup_save_control(struct cgroup *cgrp)
2923 struct cgroup *dsct;
2924 struct cgroup_subsys_state *d_css;
2926 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2927 dsct->old_subtree_control = dsct->subtree_control;
2928 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
2929 dsct->old_dom_cgrp = dsct->dom_cgrp;
2934 * cgroup_propagate_control - refresh control masks of a subtree
2935 * @cgrp: root of the target subtree
2937 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
2938 * ->subtree_control and propagate controller availability through the
2939 * subtree so that descendants don't have unavailable controllers enabled.
2941 static void cgroup_propagate_control(struct cgroup *cgrp)
2943 struct cgroup *dsct;
2944 struct cgroup_subsys_state *d_css;
2946 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2947 dsct->subtree_control &= cgroup_control(dsct);
2948 dsct->subtree_ss_mask =
2949 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
2950 cgroup_ss_mask(dsct));
2955 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
2956 * @cgrp: root of the target subtree
2958 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
2959 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2962 static void cgroup_restore_control(struct cgroup *cgrp)
2964 struct cgroup *dsct;
2965 struct cgroup_subsys_state *d_css;
2967 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2968 dsct->subtree_control = dsct->old_subtree_control;
2969 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
2970 dsct->dom_cgrp = dsct->old_dom_cgrp;
2974 static bool css_visible(struct cgroup_subsys_state *css)
2976 struct cgroup_subsys *ss = css->ss;
2977 struct cgroup *cgrp = css->cgroup;
2979 if (cgroup_control(cgrp) & (1 << ss->id))
2981 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
2983 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
2987 * cgroup_apply_control_enable - enable or show csses according to control
2988 * @cgrp: root of the target subtree
2990 * Walk @cgrp's subtree and create new csses or make the existing ones
2991 * visible. A css is created invisible if it's being implicitly enabled
2992 * through dependency. An invisible css is made visible when the userland
2993 * explicitly enables it.
2995 * Returns 0 on success, -errno on failure. On failure, csses which have
2996 * been processed already aren't cleaned up. The caller is responsible for
2997 * cleaning up with cgroup_apply_control_disable().
2999 static int cgroup_apply_control_enable(struct cgroup *cgrp)
3001 struct cgroup *dsct;
3002 struct cgroup_subsys_state *d_css;
3003 struct cgroup_subsys *ss;
3006 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3007 for_each_subsys(ss, ssid) {
3008 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3010 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
3012 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
3016 css = css_create(dsct, ss);
3018 return PTR_ERR(css);
3021 if (css_visible(css)) {
3022 ret = css_populate_dir(css);
3033 * cgroup_apply_control_disable - kill or hide csses according to control
3034 * @cgrp: root of the target subtree
3036 * Walk @cgrp's subtree and kill and hide csses so that they match
3037 * cgroup_ss_mask() and cgroup_visible_mask().
3039 * A css is hidden when the userland requests it to be disabled while other
3040 * subsystems are still depending on it. The css must not actively control
3041 * resources and be in the vanilla state if it's made visible again later.
3042 * Controllers which may be depended upon should provide ->css_reset() for
3045 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3047 struct cgroup *dsct;
3048 struct cgroup_subsys_state *d_css;
3049 struct cgroup_subsys *ss;
3052 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3053 for_each_subsys(ss, ssid) {
3054 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3056 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
3062 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3064 } else if (!css_visible(css)) {
3074 * cgroup_apply_control - apply control mask updates to the subtree
3075 * @cgrp: root of the target subtree
3077 * subsystems can be enabled and disabled in a subtree using the following
3080 * 1. Call cgroup_save_control() to stash the current state.
3081 * 2. Update ->subtree_control masks in the subtree as desired.
3082 * 3. Call cgroup_apply_control() to apply the changes.
3083 * 4. Optionally perform other related operations.
3084 * 5. Call cgroup_finalize_control() to finish up.
3086 * This function implements step 3 and propagates the mask changes
3087 * throughout @cgrp's subtree, updates csses accordingly and perform
3088 * process migrations.
3090 static int cgroup_apply_control(struct cgroup *cgrp)
3094 cgroup_propagate_control(cgrp);
3096 ret = cgroup_apply_control_enable(cgrp);
3101 * At this point, cgroup_e_css_by_mask() results reflect the new csses
3102 * making the following cgroup_update_dfl_csses() properly update
3103 * css associations of all tasks in the subtree.
3105 ret = cgroup_update_dfl_csses(cgrp);
3113 * cgroup_finalize_control - finalize control mask update
3114 * @cgrp: root of the target subtree
3115 * @ret: the result of the update
3117 * Finalize control mask update. See cgroup_apply_control() for more info.
3119 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3122 cgroup_restore_control(cgrp);
3123 cgroup_propagate_control(cgrp);
3126 cgroup_apply_control_disable(cgrp);
3129 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3131 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3133 /* if nothing is getting enabled, nothing to worry about */
3137 /* can @cgrp host any resources? */
3138 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3141 /* mixables don't care */
3142 if (cgroup_is_mixable(cgrp))
3145 if (domain_enable) {
3146 /* can't enable domain controllers inside a thread subtree */
3147 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3151 * Threaded controllers can handle internal competitions
3152 * and are always allowed inside a (prospective) thread
3155 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3160 * Controllers can't be enabled for a cgroup with tasks to avoid
3161 * child cgroups competing against tasks.
3163 if (cgroup_has_tasks(cgrp))
3169 /* change the enabled child controllers for a cgroup in the default hierarchy */
3170 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3171 char *buf, size_t nbytes,
3174 u16 enable = 0, disable = 0;
3175 struct cgroup *cgrp, *child;
3176 struct cgroup_subsys *ss;
3181 * Parse input - space separated list of subsystem names prefixed
3182 * with either + or -.
3184 buf = strstrip(buf);
3185 while ((tok = strsep(&buf, " "))) {
3188 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3189 if (!cgroup_ssid_enabled(ssid) ||
3190 strcmp(tok + 1, ss->name))
3194 enable |= 1 << ssid;
3195 disable &= ~(1 << ssid);
3196 } else if (*tok == '-') {
3197 disable |= 1 << ssid;
3198 enable &= ~(1 << ssid);
3203 } while_each_subsys_mask();
3204 if (ssid == CGROUP_SUBSYS_COUNT)
3208 cgrp = cgroup_kn_lock_live(of->kn, true);
3212 for_each_subsys(ss, ssid) {
3213 if (enable & (1 << ssid)) {
3214 if (cgrp->subtree_control & (1 << ssid)) {
3215 enable &= ~(1 << ssid);
3219 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3223 } else if (disable & (1 << ssid)) {
3224 if (!(cgrp->subtree_control & (1 << ssid))) {
3225 disable &= ~(1 << ssid);
3229 /* a child has it enabled? */
3230 cgroup_for_each_live_child(child, cgrp) {
3231 if (child->subtree_control & (1 << ssid)) {
3239 if (!enable && !disable) {
3244 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3248 /* save and update control masks and prepare csses */
3249 cgroup_save_control(cgrp);
3251 cgrp->subtree_control |= enable;
3252 cgrp->subtree_control &= ~disable;
3254 ret = cgroup_apply_control(cgrp);
3255 cgroup_finalize_control(cgrp, ret);
3259 kernfs_activate(cgrp->kn);
3261 cgroup_kn_unlock(of->kn);
3262 return ret ?: nbytes;
3266 * cgroup_enable_threaded - make @cgrp threaded
3267 * @cgrp: the target cgroup
3269 * Called when "threaded" is written to the cgroup.type interface file and
3270 * tries to make @cgrp threaded and join the parent's resource domain.
3271 * This function is never called on the root cgroup as cgroup.type doesn't
3274 static int cgroup_enable_threaded(struct cgroup *cgrp)
3276 struct cgroup *parent = cgroup_parent(cgrp);
3277 struct cgroup *dom_cgrp = parent->dom_cgrp;
3278 struct cgroup *dsct;
3279 struct cgroup_subsys_state *d_css;
3282 lockdep_assert_held(&cgroup_mutex);
3284 /* noop if already threaded */
3285 if (cgroup_is_threaded(cgrp))
3289 * If @cgroup is populated or has domain controllers enabled, it
3290 * can't be switched. While the below cgroup_can_be_thread_root()
3291 * test can catch the same conditions, that's only when @parent is
3292 * not mixable, so let's check it explicitly.
3294 if (cgroup_is_populated(cgrp) ||
3295 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3298 /* we're joining the parent's domain, ensure its validity */
3299 if (!cgroup_is_valid_domain(dom_cgrp) ||
3300 !cgroup_can_be_thread_root(dom_cgrp))
3304 * The following shouldn't cause actual migrations and should
3307 cgroup_save_control(cgrp);
3309 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3310 if (dsct == cgrp || cgroup_is_threaded(dsct))
3311 dsct->dom_cgrp = dom_cgrp;
3313 ret = cgroup_apply_control(cgrp);
3315 parent->nr_threaded_children++;
3317 cgroup_finalize_control(cgrp, ret);
3321 static int cgroup_type_show(struct seq_file *seq, void *v)
3323 struct cgroup *cgrp = seq_css(seq)->cgroup;
3325 if (cgroup_is_threaded(cgrp))
3326 seq_puts(seq, "threaded\n");
3327 else if (!cgroup_is_valid_domain(cgrp))
3328 seq_puts(seq, "domain invalid\n");
3329 else if (cgroup_is_thread_root(cgrp))
3330 seq_puts(seq, "domain threaded\n");
3332 seq_puts(seq, "domain\n");
3337 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3338 size_t nbytes, loff_t off)
3340 struct cgroup *cgrp;
3343 /* only switching to threaded mode is supported */
3344 if (strcmp(strstrip(buf), "threaded"))
3347 cgrp = cgroup_kn_lock_live(of->kn, false);
3351 /* threaded can only be enabled */
3352 ret = cgroup_enable_threaded(cgrp);
3354 cgroup_kn_unlock(of->kn);
3355 return ret ?: nbytes;
3358 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3360 struct cgroup *cgrp = seq_css(seq)->cgroup;
3361 int descendants = READ_ONCE(cgrp->max_descendants);
3363 if (descendants == INT_MAX)
3364 seq_puts(seq, "max\n");
3366 seq_printf(seq, "%d\n", descendants);
3371 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3372 char *buf, size_t nbytes, loff_t off)
3374 struct cgroup *cgrp;
3378 buf = strstrip(buf);
3379 if (!strcmp(buf, "max")) {
3380 descendants = INT_MAX;
3382 ret = kstrtoint(buf, 0, &descendants);
3387 if (descendants < 0)
3390 cgrp = cgroup_kn_lock_live(of->kn, false);
3394 cgrp->max_descendants = descendants;
3396 cgroup_kn_unlock(of->kn);
3401 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3403 struct cgroup *cgrp = seq_css(seq)->cgroup;
3404 int depth = READ_ONCE(cgrp->max_depth);
3406 if (depth == INT_MAX)
3407 seq_puts(seq, "max\n");
3409 seq_printf(seq, "%d\n", depth);
3414 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3415 char *buf, size_t nbytes, loff_t off)
3417 struct cgroup *cgrp;
3421 buf = strstrip(buf);
3422 if (!strcmp(buf, "max")) {
3425 ret = kstrtoint(buf, 0, &depth);
3433 cgrp = cgroup_kn_lock_live(of->kn, false);
3437 cgrp->max_depth = depth;
3439 cgroup_kn_unlock(of->kn);
3444 static int cgroup_events_show(struct seq_file *seq, void *v)
3446 seq_printf(seq, "populated %d\n",
3447 cgroup_is_populated(seq_css(seq)->cgroup));
3451 static int cgroup_stat_show(struct seq_file *seq, void *v)
3453 struct cgroup *cgroup = seq_css(seq)->cgroup;
3455 seq_printf(seq, "nr_descendants %d\n",
3456 cgroup->nr_descendants);
3457 seq_printf(seq, "nr_dying_descendants %d\n",
3458 cgroup->nr_dying_descendants);
3463 static int __maybe_unused cgroup_extra_stat_show(struct seq_file *seq,
3464 struct cgroup *cgrp, int ssid)
3466 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3467 struct cgroup_subsys_state *css;
3470 if (!ss->css_extra_stat_show)
3473 css = cgroup_tryget_css(cgrp, ss);
3477 ret = ss->css_extra_stat_show(seq, css);
3482 static int cpu_stat_show(struct seq_file *seq, void *v)
3484 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3487 cgroup_base_stat_cputime_show(seq);
3488 #ifdef CONFIG_CGROUP_SCHED
3489 ret = cgroup_extra_stat_show(seq, cgrp, cpu_cgrp_id);
3495 static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
3497 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_IO);
3499 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
3501 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_MEM);
3503 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
3505 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_CPU);
3509 static int cgroup_file_open(struct kernfs_open_file *of)
3511 struct cftype *cft = of->kn->priv;
3514 return cft->open(of);
3518 static void cgroup_file_release(struct&nbs