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>
58 #include <linux/psi.h>
61 #define CREATE_TRACE_POINTS
62 #include <trace/events/cgroup.h>
64 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
66 /* let's not notify more than 100 times per second */
67 #define CGROUP_FILE_NOTIFY_MIN_INTV DIV_ROUND_UP(HZ, 100)
70 * cgroup_mutex is the master lock. Any modification to cgroup or its
71 * hierarchy must be performed while holding it.
73 * css_set_lock protects task->cgroups pointer, the list of css_set
74 * objects, and the chain of tasks off each css_set.
76 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
77 * cgroup.h can use them for lockdep annotations.
79 DEFINE_MUTEX(cgroup_mutex);
80 DEFINE_SPINLOCK(css_set_lock);
82 #ifdef CONFIG_PROVE_RCU
83 EXPORT_SYMBOL_GPL(cgroup_mutex);
84 EXPORT_SYMBOL_GPL(css_set_lock);
87 DEFINE_SPINLOCK(trace_cgroup_path_lock);
88 char trace_cgroup_path[TRACE_CGROUP_PATH_LEN];
89 bool cgroup_debug __read_mostly;
92 * Protects cgroup_idr and css_idr so that IDs can be released without
93 * grabbing cgroup_mutex.
95 static DEFINE_SPINLOCK(cgroup_idr_lock);
98 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
99 * against file removal/re-creation across css hiding.
101 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
103 struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
105 #define cgroup_assert_mutex_or_rcu_locked() \
106 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
107 !lockdep_is_held(&cgroup_mutex), \
108 "cgroup_mutex or RCU read lock required");
111 * cgroup destruction makes heavy use of work items and there can be a lot
112 * of concurrent destructions. Use a separate workqueue so that cgroup
113 * destruction work items don't end up filling up max_active of system_wq
114 * which may lead to deadlock.
116 static struct workqueue_struct *cgroup_destroy_wq;
118 /* generate an array of cgroup subsystem pointers */
119 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
120 struct cgroup_subsys *cgroup_subsys[] = {
121 #include <linux/cgroup_subsys.h>
125 /* array of cgroup subsystem names */
126 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
127 static const char *cgroup_subsys_name[] = {
128 #include <linux/cgroup_subsys.h>
132 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
134 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
135 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
136 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
137 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
138 #include <linux/cgroup_subsys.h>
141 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
142 static struct static_key_true *cgroup_subsys_enabled_key[] = {
143 #include <linux/cgroup_subsys.h>
147 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
148 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
149 #include <linux/cgroup_subsys.h>
153 static DEFINE_PER_CPU(struct cgroup_rstat_cpu, cgrp_dfl_root_rstat_cpu);
156 * The default hierarchy, reserved for the subsystems that are otherwise
157 * unattached - it never has more than a single cgroup, and all tasks are
158 * part of that cgroup.
160 struct cgroup_root cgrp_dfl_root = { .cgrp.rstat_cpu = &cgrp_dfl_root_rstat_cpu };
161 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
164 * The default hierarchy always exists but is hidden until mounted for the
165 * first time. This is for backward compatibility.
167 static bool cgrp_dfl_visible;
169 /* some controllers are not supported in the default hierarchy */
170 static u16 cgrp_dfl_inhibit_ss_mask;
172 /* some controllers are implicitly enabled on the default hierarchy */
173 static u16 cgrp_dfl_implicit_ss_mask;
175 /* some controllers can be threaded on the default hierarchy */
176 static u16 cgrp_dfl_threaded_ss_mask;
178 /* The list of hierarchy roots */
179 LIST_HEAD(cgroup_roots);
180 static int cgroup_root_count;
182 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
183 static DEFINE_IDR(cgroup_hierarchy_idr);
186 * Assign a monotonically increasing serial number to csses. It guarantees
187 * cgroups with bigger numbers are newer than those with smaller numbers.
188 * Also, as csses are always appended to the parent's ->children list, it
189 * guarantees that sibling csses are always sorted in the ascending serial
190 * number order on the list. Protected by cgroup_mutex.
192 static u64 css_serial_nr_next = 1;
195 * These bitmasks identify subsystems with specific features to avoid
196 * having to do iterative checks repeatedly.
198 static u16 have_fork_callback __read_mostly;
199 static u16 have_exit_callback __read_mostly;
200 static u16 have_free_callback __read_mostly;
201 static u16 have_canfork_callback __read_mostly;
203 /* cgroup namespace for init task */
204 struct cgroup_namespace init_cgroup_ns = {
205 .count = REFCOUNT_INIT(2),
206 .user_ns = &init_user_ns,
207 .ns.ops = &cgroupns_operations,
208 .ns.inum = PROC_CGROUP_INIT_INO,
209 .root_cset = &init_css_set,
212 static struct file_system_type cgroup2_fs_type;
213 static struct cftype cgroup_base_files[];
215 static int cgroup_apply_control(struct cgroup *cgrp);
216 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
217 static void css_task_iter_advance(struct css_task_iter *it);
218 static int cgroup_destroy_locked(struct cgroup *cgrp);
219 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
220 struct cgroup_subsys *ss);
221 static void css_release(struct percpu_ref *ref);
222 static void kill_css(struct cgroup_subsys_state *css);
223 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
224 struct cgroup *cgrp, struct cftype cfts[],
228 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
229 * @ssid: subsys ID of interest
231 * cgroup_subsys_enabled() can only be used with literal subsys names which
232 * is fine for individual subsystems but unsuitable for cgroup core. This
233 * is slower static_key_enabled() based test indexed by @ssid.
235 bool cgroup_ssid_enabled(int ssid)
237 if (CGROUP_SUBSYS_COUNT == 0)
240 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
244 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
245 * @cgrp: the cgroup of interest
247 * The default hierarchy is the v2 interface of cgroup and this function
248 * can be used to test whether a cgroup is on the default hierarchy for
249 * cases where a subsystem should behave differnetly depending on the
252 * The set of behaviors which change on the default hierarchy are still
253 * being determined and the mount option is prefixed with __DEVEL__.
255 * List of changed behaviors:
257 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
258 * and "name" are disallowed.
260 * - When mounting an existing superblock, mount options should match.
262 * - Remount is disallowed.
264 * - rename(2) is disallowed.
266 * - "tasks" is removed. Everything should be at process granularity. Use
267 * "cgroup.procs" instead.
269 * - "cgroup.procs" is not sorted. pids will be unique unless they got
270 * recycled inbetween reads.
272 * - "release_agent" and "notify_on_release" are removed. Replacement
273 * notification mechanism will be implemented.
275 * - "cgroup.clone_children" is removed.
277 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
278 * and its descendants contain no task; otherwise, 1. The file also
279 * generates kernfs notification which can be monitored through poll and
280 * [di]notify when the value of the file changes.
282 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
283 * take masks of ancestors with non-empty cpus/mems, instead of being
284 * moved to an ancestor.
286 * - cpuset: a task can be moved into an empty cpuset, and again it takes
287 * masks of ancestors.
289 * - memcg: use_hierarchy is on by default and the cgroup file for the flag
292 * - blkcg: blk-throttle becomes properly hierarchical.
294 * - debug: disallowed on the default hierarchy.
296 bool cgroup_on_dfl(const struct cgroup *cgrp)
298 return cgrp->root == &cgrp_dfl_root;
301 /* IDR wrappers which synchronize using cgroup_idr_lock */
302 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
307 idr_preload(gfp_mask);
308 spin_lock_bh(&cgroup_idr_lock);
309 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
310 spin_unlock_bh(&cgroup_idr_lock);
315 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
319 spin_lock_bh(&cgroup_idr_lock);
320 ret = idr_replace(idr, ptr, id);
321 spin_unlock_bh(&cgroup_idr_lock);
325 static void cgroup_idr_remove(struct idr *idr, int id)
327 spin_lock_bh(&cgroup_idr_lock);
329 spin_unlock_bh(&cgroup_idr_lock);
332 static bool cgroup_has_tasks(struct cgroup *cgrp)
334 return cgrp->nr_populated_csets;
337 bool cgroup_is_threaded(struct cgroup *cgrp)
339 return cgrp->dom_cgrp != cgrp;
342 /* can @cgrp host both domain and threaded children? */
343 static bool cgroup_is_mixable(struct cgroup *cgrp)
346 * Root isn't under domain level resource control exempting it from
347 * the no-internal-process constraint, so it can serve as a thread
348 * root and a parent of resource domains at the same time.
350 return !cgroup_parent(cgrp);
353 /* can @cgrp become a thread root? should always be true for a thread root */
354 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
356 /* mixables don't care */
357 if (cgroup_is_mixable(cgrp))
360 /* domain roots can't be nested under threaded */
361 if (cgroup_is_threaded(cgrp))
364 /* can only have either domain or threaded children */
365 if (cgrp->nr_populated_domain_children)
368 /* and no domain controllers can be enabled */
369 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
375 /* is @cgrp root of a threaded subtree? */
376 bool cgroup_is_thread_root(struct cgroup *cgrp)
378 /* thread root should be a domain */
379 if (cgroup_is_threaded(cgrp))
382 /* a domain w/ threaded children is a thread root */
383 if (cgrp->nr_threaded_children)
387 * A domain which has tasks and explicit threaded controllers
388 * enabled is a thread root.
390 if (cgroup_has_tasks(cgrp) &&
391 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
397 /* a domain which isn't connected to the root w/o brekage can't be used */
398 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
400 /* the cgroup itself can be a thread root */
401 if (cgroup_is_threaded(cgrp))
404 /* but the ancestors can't be unless mixable */
405 while ((cgrp = cgroup_parent(cgrp))) {
406 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
408 if (cgroup_is_threaded(cgrp))
415 /* subsystems visibly enabled on a cgroup */
416 static u16 cgroup_control(struct cgroup *cgrp)
418 struct cgroup *parent = cgroup_parent(cgrp);
419 u16 root_ss_mask = cgrp->root->subsys_mask;
422 u16 ss_mask = parent->subtree_control;
424 /* threaded cgroups can only have threaded controllers */
425 if (cgroup_is_threaded(cgrp))
426 ss_mask &= cgrp_dfl_threaded_ss_mask;
430 if (cgroup_on_dfl(cgrp))
431 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
432 cgrp_dfl_implicit_ss_mask);
436 /* subsystems enabled on a cgroup */
437 static u16 cgroup_ss_mask(struct cgroup *cgrp)
439 struct cgroup *parent = cgroup_parent(cgrp);
442 u16 ss_mask = parent->subtree_ss_mask;
444 /* threaded cgroups can only have threaded controllers */
445 if (cgroup_is_threaded(cgrp))
446 ss_mask &= cgrp_dfl_threaded_ss_mask;
450 return cgrp->root->subsys_mask;
454 * cgroup_css - obtain a cgroup's css for the specified subsystem
455 * @cgrp: the cgroup of interest
456 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
458 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
459 * function must be called either under cgroup_mutex or rcu_read_lock() and
460 * the caller is responsible for pinning the returned css if it wants to
461 * keep accessing it outside the said locks. This function may return
462 * %NULL if @cgrp doesn't have @subsys_id enabled.
464 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
465 struct cgroup_subsys *ss)
468 return rcu_dereference_check(cgrp->subsys[ss->id],
469 lockdep_is_held(&cgroup_mutex));
475 * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
476 * @cgrp: the cgroup of interest
477 * @ss: the subsystem of interest
479 * Find and get @cgrp's css assocaited with @ss. If the css doesn't exist
480 * or is offline, %NULL is returned.
482 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
483 struct cgroup_subsys *ss)
485 struct cgroup_subsys_state *css;
488 css = cgroup_css(cgrp, ss);
489 if (!css || !css_tryget_online(css))
497 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
498 * @cgrp: the cgroup of interest
499 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
501 * Similar to cgroup_css() but returns the effective css, which is defined
502 * as the matching css of the nearest ancestor including self which has @ss
503 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
504 * function is guaranteed to return non-NULL css.
506 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
507 struct cgroup_subsys *ss)
509 lockdep_assert_held(&cgroup_mutex);
515 * This function is used while updating css associations and thus
516 * can't test the csses directly. Test ss_mask.
518 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
519 cgrp = cgroup_parent(cgrp);
524 return cgroup_css(cgrp, ss);
528 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
529 * @cgrp: the cgroup of interest
530 * @ss: the subsystem of interest
532 * Find and get the effective css of @cgrp for @ss. The effective css is
533 * defined as the matching css of the nearest ancestor including self which
534 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
535 * the root css is returned, so this function always returns a valid css.
536 * The returned css must be put using css_put().
538 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
539 struct cgroup_subsys *ss)
541 struct cgroup_subsys_state *css;
546 css = cgroup_css(cgrp, ss);
548 if (css && css_tryget_online(css))
550 cgrp = cgroup_parent(cgrp);
553 css = init_css_set.subsys[ss->id];
560 static void cgroup_get_live(struct cgroup *cgrp)
562 WARN_ON_ONCE(cgroup_is_dead(cgrp));
563 css_get(&cgrp->self);
566 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
568 struct cgroup *cgrp = of->kn->parent->priv;
569 struct cftype *cft = of_cft(of);
572 * This is open and unprotected implementation of cgroup_css().
573 * seq_css() is only called from a kernfs file operation which has
574 * an active reference on the file. Because all the subsystem
575 * files are drained before a css is disassociated with a cgroup,
576 * the matching css from the cgroup's subsys table is guaranteed to
577 * be and stay valid until the enclosing operation is complete.
580 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
584 EXPORT_SYMBOL_GPL(of_css);
587 * for_each_css - iterate all css's of a cgroup
588 * @css: the iteration cursor
589 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
590 * @cgrp: the target cgroup to iterate css's of
592 * Should be called under cgroup_[tree_]mutex.
594 #define for_each_css(css, ssid, cgrp) \
595 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
596 if (!((css) = rcu_dereference_check( \
597 (cgrp)->subsys[(ssid)], \
598 lockdep_is_held(&cgroup_mutex)))) { } \
602 * for_each_e_css - iterate all effective css's of a cgroup
603 * @css: the iteration cursor
604 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
605 * @cgrp: the target cgroup to iterate css's of
607 * Should be called under cgroup_[tree_]mutex.
609 #define for_each_e_css(css, ssid, cgrp) \
610 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
611 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
616 * do_each_subsys_mask - filter for_each_subsys with a bitmask
617 * @ss: the iteration cursor
618 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
619 * @ss_mask: the bitmask
621 * The block will only run for cases where the ssid-th bit (1 << ssid) of
624 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
625 unsigned long __ss_mask = (ss_mask); \
626 if (!CGROUP_SUBSYS_COUNT) { /* to avoid spurious gcc warning */ \
630 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
631 (ss) = cgroup_subsys[ssid]; \
634 #define while_each_subsys_mask() \
639 /* iterate over child cgrps, lock should be held throughout iteration */
640 #define cgroup_for_each_live_child(child, cgrp) \
641 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
642 if (({ lockdep_assert_held(&cgroup_mutex); \
643 cgroup_is_dead(child); })) \
647 /* walk live descendants in preorder */
648 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
649 css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
650 if (({ lockdep_assert_held(&cgroup_mutex); \
651 (dsct) = (d_css)->cgroup; \
652 cgroup_is_dead(dsct); })) \
656 /* walk live descendants in postorder */
657 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
658 css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
659 if (({ lockdep_assert_held(&cgroup_mutex); \
660 (dsct) = (d_css)->cgroup; \
661 cgroup_is_dead(dsct); })) \
666 * The default css_set - used by init and its children prior to any
667 * hierarchies being mounted. It contains a pointer to the root state
668 * for each subsystem. Also used to anchor the list of css_sets. Not
669 * reference-counted, to improve performance when child cgroups
670 * haven't been created.
672 struct css_set init_css_set = {
673 .refcount = REFCOUNT_INIT(1),
674 .dom_cset = &init_css_set,
675 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
676 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
677 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
678 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
679 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
680 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
681 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
684 * The following field is re-initialized when this cset gets linked
685 * in cgroup_init(). However, let's initialize the field
686 * statically too so that the default cgroup can be accessed safely
689 .dfl_cgrp = &cgrp_dfl_root.cgrp,
692 static int css_set_count = 1; /* 1 for init_css_set */
694 static bool css_set_threaded(struct css_set *cset)
696 return cset->dom_cset != cset;
700 * css_set_populated - does a css_set contain any tasks?
701 * @cset: target css_set
703 * css_set_populated() should be the same as !!cset->nr_tasks at steady
704 * state. However, css_set_populated() can be called while a task is being
705 * added to or removed from the linked list before the nr_tasks is
706 * properly updated. Hence, we can't just look at ->nr_tasks here.
708 static bool css_set_populated(struct css_set *cset)
710 lockdep_assert_held(&css_set_lock);
712 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
716 * cgroup_update_populated - update the populated count of a cgroup
717 * @cgrp: the target cgroup
718 * @populated: inc or dec populated count
720 * One of the css_sets associated with @cgrp is either getting its first
721 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
722 * count is propagated towards root so that a given cgroup's
723 * nr_populated_children is zero iff none of its descendants contain any
726 * @cgrp's interface file "cgroup.populated" is zero if both
727 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
728 * 1 otherwise. When the sum changes from or to zero, userland is notified
729 * that the content of the interface file has changed. This can be used to
730 * detect when @cgrp and its descendants become populated or empty.
732 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
734 struct cgroup *child = NULL;
735 int adj = populated ? 1 : -1;
737 lockdep_assert_held(&css_set_lock);
740 bool was_populated = cgroup_is_populated(cgrp);
743 cgrp->nr_populated_csets += adj;
745 if (cgroup_is_threaded(child))
746 cgrp->nr_populated_threaded_children += adj;
748 cgrp->nr_populated_domain_children += adj;
751 if (was_populated == cgroup_is_populated(cgrp))
754 cgroup1_check_for_release(cgrp);
755 cgroup_file_notify(&cgrp->events_file);
758 cgrp = cgroup_parent(cgrp);
763 * css_set_update_populated - update populated state of a css_set
764 * @cset: target css_set
765 * @populated: whether @cset is populated or depopulated
767 * @cset is either getting the first task or losing the last. Update the
768 * populated counters of all associated cgroups accordingly.
770 static void css_set_update_populated(struct css_set *cset, bool populated)
772 struct cgrp_cset_link *link;
774 lockdep_assert_held(&css_set_lock);
776 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
777 cgroup_update_populated(link->cgrp, populated);
781 * css_set_move_task - move a task from one css_set to another
782 * @task: task being moved
783 * @from_cset: css_set @task currently belongs to (may be NULL)
784 * @to_cset: new css_set @task is being moved to (may be NULL)
785 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
787 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
788 * css_set, @from_cset can be NULL. If @task is being disassociated
789 * instead of moved, @to_cset can be NULL.
791 * This function automatically handles populated counter updates and
792 * css_task_iter adjustments but the caller is responsible for managing
793 * @from_cset and @to_cset's reference counts.
795 static void css_set_move_task(struct task_struct *task,
796 struct css_set *from_cset, struct css_set *to_cset,
799 lockdep_assert_held(&css_set_lock);
801 if (to_cset && !css_set_populated(to_cset))
802 css_set_update_populated(to_cset, true);
805 struct css_task_iter *it, *pos;
807 WARN_ON_ONCE(list_empty(&task->cg_list));
810 * @task is leaving, advance task iterators which are
811 * pointing to it so that they can resume at the next
812 * position. Advancing an iterator might remove it from
813 * the list, use safe walk. See css_task_iter_advance*()
816 list_for_each_entry_safe(it, pos, &from_cset->task_iters,
818 if (it->task_pos == &task->cg_list)
819 css_task_iter_advance(it);
821 list_del_init(&task->cg_list);
822 if (!css_set_populated(from_cset))
823 css_set_update_populated(from_cset, false);
825 WARN_ON_ONCE(!list_empty(&task->cg_list));
830 * We are synchronized through cgroup_threadgroup_rwsem
831 * against PF_EXITING setting such that we can't race
832 * against cgroup_exit() changing the css_set to
833 * init_css_set and dropping the old one.
835 WARN_ON_ONCE(task->flags & PF_EXITING);
837 cgroup_move_task(task, to_cset);
838 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
844 * hash table for cgroup groups. This improves the performance to find
845 * an existing css_set. This hash doesn't (currently) take into
846 * account cgroups in empty hierarchies.
848 #define CSS_SET_HASH_BITS 7
849 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
851 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
853 unsigned long key = 0UL;
854 struct cgroup_subsys *ss;
857 for_each_subsys(ss, i)
858 key += (unsigned long)css[i];
859 key = (key >> 16) ^ key;
864 void put_css_set_locked(struct css_set *cset)
866 struct cgrp_cset_link *link, *tmp_link;
867 struct cgroup_subsys *ss;
870 lockdep_assert_held(&css_set_lock);
872 if (!refcount_dec_and_test(&cset->refcount))
875 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
877 /* This css_set is dead. unlink it and release cgroup and css refs */
878 for_each_subsys(ss, ssid) {
879 list_del(&cset->e_cset_node[ssid]);
880 css_put(cset->subsys[ssid]);
882 hash_del(&cset->hlist);
885 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
886 list_del(&link->cset_link);
887 list_del(&link->cgrp_link);
888 if (cgroup_parent(link->cgrp))
889 cgroup_put(link->cgrp);
893 if (css_set_threaded(cset)) {
894 list_del(&cset->threaded_csets_node);
895 put_css_set_locked(cset->dom_cset);
898 kfree_rcu(cset, rcu_head);
902 * compare_css_sets - helper function for find_existing_css_set().
903 * @cset: candidate css_set being tested
904 * @old_cset: existing css_set for a task
905 * @new_cgrp: cgroup that's being entered by the task
906 * @template: desired set of css pointers in css_set (pre-calculated)
908 * Returns true if "cset" matches "old_cset" except for the hierarchy
909 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
911 static bool compare_css_sets(struct css_set *cset,
912 struct css_set *old_cset,
913 struct cgroup *new_cgrp,
914 struct cgroup_subsys_state *template[])
916 struct cgroup *new_dfl_cgrp;
917 struct list_head *l1, *l2;
920 * On the default hierarchy, there can be csets which are
921 * associated with the same set of cgroups but different csses.
922 * Let's first ensure that csses match.
924 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
928 /* @cset's domain should match the default cgroup's */
929 if (cgroup_on_dfl(new_cgrp))
930 new_dfl_cgrp = new_cgrp;
932 new_dfl_cgrp = old_cset->dfl_cgrp;
934 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
938 * Compare cgroup pointers in order to distinguish between
939 * different cgroups in hierarchies. As different cgroups may
940 * share the same effective css, this comparison is always
943 l1 = &cset->cgrp_links;
944 l2 = &old_cset->cgrp_links;
946 struct cgrp_cset_link *link1, *link2;
947 struct cgroup *cgrp1, *cgrp2;
951 /* See if we reached the end - both lists are equal length. */
952 if (l1 == &cset->cgrp_links) {
953 BUG_ON(l2 != &old_cset->cgrp_links);
956 BUG_ON(l2 == &old_cset->cgrp_links);
958 /* Locate the cgroups associated with these links. */
959 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
960 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
963 /* Hierarchies should be linked in the same order. */
964 BUG_ON(cgrp1->root != cgrp2->root);
967 * If this hierarchy is the hierarchy of the cgroup
968 * that's changing, then we need to check that this
969 * css_set points to the new cgroup; if it's any other
970 * hierarchy, then this css_set should point to the
971 * same cgroup as the old css_set.
973 if (cgrp1->root == new_cgrp->root) {
974 if (cgrp1 != new_cgrp)
985 * find_existing_css_set - init css array and find the matching css_set
986 * @old_cset: the css_set that we're using before the cgroup transition
987 * @cgrp: the cgroup that we're moving into
988 * @template: out param for the new set of csses, should be clear on entry
990 static struct css_set *find_existing_css_set(struct css_set *old_cset,
992 struct cgroup_subsys_state *template[])
994 struct cgroup_root *root = cgrp->root;
995 struct cgroup_subsys *ss;
996 struct css_set *cset;
1001 * Build the set of subsystem state objects that we want to see in the
1002 * new css_set. while subsystems can change globally, the entries here
1003 * won't change, so no need for locking.
1005 for_each_subsys(ss, i) {
1006 if (root->subsys_mask & (1UL << i)) {
1008 * @ss is in this hierarchy, so we want the
1009 * effective css from @cgrp.
1011 template[i] = cgroup_e_css(cgrp, ss);
1014 * @ss is not in this hierarchy, so we don't want
1015 * to change the css.
1017 template[i] = old_cset->subsys[i];
1021 key = css_set_hash(template);
1022 hash_for_each_possible(css_set_table, cset, hlist, key) {
1023 if (!compare_css_sets(cset, old_cset, cgrp, template))
1026 /* This css_set matches what we need */
1030 /* No existing cgroup group matched */
1034 static void free_cgrp_cset_links(struct list_head *links_to_free)
1036 struct cgrp_cset_link *link, *tmp_link;
1038 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1039 list_del(&link->cset_link);
1045 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1046 * @count: the number of links to allocate
1047 * @tmp_links: list_head the allocated links are put on
1049 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1050 * through ->cset_link. Returns 0 on success or -errno.
1052 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1054 struct cgrp_cset_link *link;
1057 INIT_LIST_HEAD(tmp_links);
1059 for (i = 0; i < count; i++) {
1060 link = kzalloc(sizeof(*link), GFP_KERNEL);
1062 free_cgrp_cset_links(tmp_links);
1065 list_add(&link->cset_link, tmp_links);
1071 * link_css_set - a helper function to link a css_set to a cgroup
1072 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1073 * @cset: the css_set to be linked
1074 * @cgrp: the destination cgroup
1076 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1077 struct cgroup *cgrp)
1079 struct cgrp_cset_link *link;
1081 BUG_ON(list_empty(tmp_links));
1083 if (cgroup_on_dfl(cgrp))
1084 cset->dfl_cgrp = cgrp;
1086 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1091 * Always add links to the tail of the lists so that the lists are
1092 * in choronological order.
1094 list_move_tail(&link->cset_link, &cgrp->cset_links);
1095 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1097 if (cgroup_parent(cgrp))
1098 cgroup_get_live(cgrp);
1102 * find_css_set - return a new css_set with one cgroup updated
1103 * @old_cset: the baseline css_set
1104 * @cgrp: the cgroup to be updated
1106 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1107 * substituted into the appropriate hierarchy.
1109 static struct css_set *find_css_set(struct css_set *old_cset,
1110 struct cgroup *cgrp)
1112 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1113 struct css_set *cset;
1114 struct list_head tmp_links;
1115 struct cgrp_cset_link *link;
1116 struct cgroup_subsys *ss;
1120 lockdep_assert_held(&cgroup_mutex);
1122 /* First see if we already have a cgroup group that matches
1123 * the desired set */
1124 spin_lock_irq(&css_set_lock);
1125 cset = find_existing_css_set(old_cset, cgrp, template);
1128 spin_unlock_irq(&css_set_lock);
1133 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1137 /* Allocate all the cgrp_cset_link objects that we'll need */
1138 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1143 refcount_set(&cset->refcount, 1);
1144 cset->dom_cset = cset;
1145 INIT_LIST_HEAD(&cset->tasks);
1146 INIT_LIST_HEAD(&cset->mg_tasks);
1147 INIT_LIST_HEAD(&cset->task_iters);
1148 INIT_LIST_HEAD(&cset->threaded_csets);
1149 INIT_HLIST_NODE(&cset->hlist);
1150 INIT_LIST_HEAD(&cset->cgrp_links);
1151 INIT_LIST_HEAD(&cset->mg_preload_node);
1152 INIT_LIST_HEAD(&cset->mg_node);
1154 /* Copy the set of subsystem state objects generated in
1155 * find_existing_css_set() */
1156 memcpy(cset->subsys, template, sizeof(cset->subsys));
1158 spin_lock_irq(&css_set_lock);
1159 /* Add reference counts and links from the new css_set. */
1160 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1161 struct cgroup *c = link->cgrp;
1163 if (c->root == cgrp->root)
1165 link_css_set(&tmp_links, cset, c);
1168 BUG_ON(!list_empty(&tmp_links));
1172 /* Add @cset to the hash table */
1173 key = css_set_hash(cset->subsys);
1174 hash_add(css_set_table, &cset->hlist, key);
1176 for_each_subsys(ss, ssid) {
1177 struct cgroup_subsys_state *css = cset->subsys[ssid];
1179 list_add_tail(&cset->e_cset_node[ssid],
1180 &css->cgroup->e_csets[ssid]);
1184 spin_unlock_irq(&css_set_lock);
1187 * If @cset should be threaded, look up the matching dom_cset and
1188 * link them up. We first fully initialize @cset then look for the
1189 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1190 * to stay empty until we return.
1192 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1193 struct css_set *dcset;
1195 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1201 spin_lock_irq(&css_set_lock);
1202 cset->dom_cset = dcset;
1203 list_add_tail(&cset->threaded_csets_node,
1204 &dcset->threaded_csets);
1205 spin_unlock_irq(&css_set_lock);
1211 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1213 struct cgroup *root_cgrp = kf_root->kn->priv;
1215 return root_cgrp->root;
1218 static int cgroup_init_root_id(struct cgroup_root *root)
1222 lockdep_assert_held(&cgroup_mutex);
1224 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1228 root->hierarchy_id = id;
1232 static void cgroup_exit_root_id(struct cgroup_root *root)
1234 lockdep_assert_held(&cgroup_mutex);
1236 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1239 void cgroup_free_root(struct cgroup_root *root)
1242 idr_destroy(&root->cgroup_idr);
1247 static void cgroup_destroy_root(struct cgroup_root *root)
1249 struct cgroup *cgrp = &root->cgrp;
1250 struct cgrp_cset_link *link, *tmp_link;
1252 trace_cgroup_destroy_root(root);
1254 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1256 BUG_ON(atomic_read(&root->nr_cgrps));
1257 BUG_ON(!list_empty(&cgrp->self.children));
1259 /* Rebind all subsystems back to the default hierarchy */
1260 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1263 * Release all the links from cset_links to this hierarchy's
1266 spin_lock_irq(&css_set_lock);
1268 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1269 list_del(&link->cset_link);
1270 list_del(&link->cgrp_link);
1274 spin_unlock_irq(&css_set_lock);
1276 if (!list_empty(&root->root_list)) {
1277 list_del(&root->root_list);
1278 cgroup_root_count--;
1281 cgroup_exit_root_id(root);
1283 mutex_unlock(&cgroup_mutex);
1285 kernfs_destroy_root(root->kf_root);
1286 cgroup_free_root(root);
1290 * look up cgroup associated with current task's cgroup namespace on the
1291 * specified hierarchy
1293 static struct cgroup *
1294 current_cgns_cgroup_from_root(struct cgroup_root *root)
1296 struct cgroup *res = NULL;
1297 struct css_set *cset;
1299 lockdep_assert_held(&css_set_lock);
1303 cset = current->nsproxy->cgroup_ns->root_cset;
1304 if (cset == &init_css_set) {
1307 struct cgrp_cset_link *link;
1309 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1310 struct cgroup *c = link->cgrp;
1312 if (c->root == root) {
1324 /* look up cgroup associated with given css_set on the specified hierarchy */
1325 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1326 struct cgroup_root *root)
1328 struct cgroup *res = NULL;
1330 lockdep_assert_held(&cgroup_mutex);
1331 lockdep_assert_held(&css_set_lock);
1333 if (cset == &init_css_set) {
1335 } else if (root == &cgrp_dfl_root) {
1336 res = cset->dfl_cgrp;
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 * Return the cgroup for "task" from the given hierarchy. Must be
1356 * called with cgroup_mutex and css_set_lock held.
1358 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1359 struct cgroup_root *root)
1362 * No need to lock the task - since we hold cgroup_mutex the
1363 * task can't change groups, so the only thing that can happen
1364 * is that it exits and its css is set back to init_css_set.
1366 return cset_cgroup_from_root(task_css_set(task), root);
1370 * A task must hold cgroup_mutex to modify cgroups.
1372 * Any task can increment and decrement the count field without lock.
1373 * So in general, code holding cgroup_mutex can't rely on the count
1374 * field not changing. However, if the count goes to zero, then only
1375 * cgroup_attach_task() can increment it again. Because a count of zero
1376 * means that no tasks are currently attached, therefore there is no
1377 * way a task attached to that cgroup can fork (the other way to
1378 * increment the count). So code holding cgroup_mutex can safely
1379 * assume that if the count is zero, it will stay zero. Similarly, if
1380 * a task holds cgroup_mutex on a cgroup with zero count, it
1381 * knows that the cgroup won't be removed, as cgroup_rmdir()
1384 * A cgroup can only be deleted if both its 'count' of using tasks
1385 * is zero, and its list of 'children' cgroups is empty. Since all
1386 * tasks in the system use _some_ cgroup, and since there is always at
1387 * least one task in the system (init, pid == 1), therefore, root cgroup
1388 * always has either children cgroups and/or using tasks. So we don't
1389 * need a special hack to ensure that root cgroup cannot be deleted.
1391 * P.S. One more locking exception. RCU is used to guard the
1392 * update of a tasks cgroup pointer by cgroup_attach_task()
1395 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1397 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1400 struct cgroup_subsys *ss = cft->ss;
1402 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1403 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
1404 const char *dbg = (cft->flags & CFTYPE_DEBUG) ? ".__DEBUG__." : "";
1406 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s%s.%s",
1407 dbg, cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1410 strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1416 * cgroup_file_mode - deduce file mode of a control file
1417 * @cft: the control file in question
1419 * S_IRUGO for read, S_IWUSR for write.
1421 static umode_t cgroup_file_mode(const struct cftype *cft)
1425 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1428 if (cft->write_u64 || cft->write_s64 || cft->write) {
1429 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1439 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1440 * @subtree_control: the new subtree_control mask to consider
1441 * @this_ss_mask: available subsystems
1443 * On the default hierarchy, a subsystem may request other subsystems to be
1444 * enabled together through its ->depends_on mask. In such cases, more
1445 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1447 * This function calculates which subsystems need to be enabled if
1448 * @subtree_control is to be applied while restricted to @this_ss_mask.
1450 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1452 u16 cur_ss_mask = subtree_control;
1453 struct cgroup_subsys *ss;
1456 lockdep_assert_held(&cgroup_mutex);
1458 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1461 u16 new_ss_mask = cur_ss_mask;
1463 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1464 new_ss_mask |= ss->depends_on;
1465 } while_each_subsys_mask();
1468 * Mask out subsystems which aren't available. This can
1469 * happen only if some depended-upon subsystems were bound
1470 * to non-default hierarchies.
1472 new_ss_mask &= this_ss_mask;
1474 if (new_ss_mask == cur_ss_mask)
1476 cur_ss_mask = new_ss_mask;
1483 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1484 * @kn: the kernfs_node being serviced
1486 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1487 * the method finishes if locking succeeded. Note that once this function
1488 * returns the cgroup returned by cgroup_kn_lock_live() may become
1489 * inaccessible any time. If the caller intends to continue to access the
1490 * cgroup, it should pin it before invoking this function.
1492 void cgroup_kn_unlock(struct kernfs_node *kn)
1494 struct cgroup *cgrp;
1496 if (kernfs_type(kn) == KERNFS_DIR)
1499 cgrp = kn->parent->priv;
1501 mutex_unlock(&cgroup_mutex);
1503 kernfs_unbreak_active_protection(kn);
1508 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1509 * @kn: the kernfs_node being serviced
1510 * @drain_offline: perform offline draining on the cgroup
1512 * This helper is to be used by a cgroup kernfs method currently servicing
1513 * @kn. It breaks the active protection, performs cgroup locking and
1514 * verifies that the associated cgroup is alive. Returns the cgroup if
1515 * alive; otherwise, %NULL. A successful return should be undone by a
1516 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1517 * cgroup is drained of offlining csses before return.
1519 * Any cgroup kernfs method implementation which requires locking the
1520 * associated cgroup should use this helper. It avoids nesting cgroup
1521 * locking under kernfs active protection and allows all kernfs operations
1522 * including self-removal.
1524 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1526 struct cgroup *cgrp;
1528 if (kernfs_type(kn) == KERNFS_DIR)
1531 cgrp = kn->parent->priv;
1534 * We're gonna grab cgroup_mutex which nests outside kernfs
1535 * active_ref. cgroup liveliness check alone provides enough
1536 * protection against removal. Ensure @cgrp stays accessible and
1537 * break the active_ref protection.
1539 if (!cgroup_tryget(cgrp))
1541 kernfs_break_active_protection(kn);
1544 cgroup_lock_and_drain_offline(cgrp);
1546 mutex_lock(&cgroup_mutex);
1548 if (!cgroup_is_dead(cgrp))
1551 cgroup_kn_unlock(kn);
1555 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1557 char name[CGROUP_FILE_NAME_MAX];
1559 lockdep_assert_held(&cgroup_mutex);
1561 if (cft->file_offset) {
1562 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1563 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1565 spin_lock_irq(&cgroup_file_kn_lock);
1567 spin_unlock_irq(&cgroup_file_kn_lock);
1569 del_timer_sync(&cfile->notify_timer);
1572 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1576 * css_clear_dir - remove subsys files in a cgroup directory
1579 static void css_clear_dir(struct cgroup_subsys_state *css)
1581 struct cgroup *cgrp = css->cgroup;
1582 struct cftype *cfts;
1584 if (!(css->flags & CSS_VISIBLE))
1587 css->flags &= ~CSS_VISIBLE;
1590 if (cgroup_on_dfl(cgrp))
1591 cfts = cgroup_base_files;
1593 cfts = cgroup1_base_files;
1595 cgroup_addrm_files(css, cgrp, cfts, false);
1597 list_for_each_entry(cfts, &css->ss->cfts, node)
1598 cgroup_addrm_files(css, cgrp, cfts, false);
1603 * css_populate_dir - create subsys files in a cgroup directory
1606 * On failure, no file is added.
1608 static int css_populate_dir(struct cgroup_subsys_state *css)
1610 struct cgroup *cgrp = css->cgroup;
1611 struct cftype *cfts, *failed_cfts;
1614 if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
1618 if (cgroup_on_dfl(cgrp))
1619 cfts = cgroup_base_files;
1621 cfts = cgroup1_base_files;
1623 ret = cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1627 list_for_each_entry(cfts, &css->ss->cfts, node) {
1628 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1636 css->flags |= CSS_VISIBLE;
1640 list_for_each_entry(cfts, &css->ss->cfts, node) {
1641 if (cfts == failed_cfts)
1643 cgroup_addrm_files(css, cgrp, cfts, false);
1648 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1650 struct cgroup *dcgrp = &dst_root->cgrp;
1651 struct cgroup_subsys *ss;
1654 lockdep_assert_held(&cgroup_mutex);
1656 do_each_subsys_mask(ss, ssid, ss_mask) {
1658 * If @ss has non-root csses attached to it, can't move.
1659 * If @ss is an implicit controller, it is exempt from this
1660 * rule and can be stolen.
1662 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1663 !ss->implicit_on_dfl)
1666 /* can't move between two non-dummy roots either */
1667 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1669 } while_each_subsys_mask();
1671 do_each_subsys_mask(ss, ssid, ss_mask) {
1672 struct cgroup_root *src_root = ss->root;
1673 struct cgroup *scgrp = &src_root->cgrp;
1674 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1675 struct css_set *cset;
1677 WARN_ON(!css || cgroup_css(dcgrp, ss));
1679 /* disable from the source */
1680 src_root->subsys_mask &= ~(1 << ssid);
1681 WARN_ON(cgroup_apply_control(scgrp));
1682 cgroup_finalize_control(scgrp, 0);
1685 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1686 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1687 ss->root = dst_root;
1688 css->cgroup = dcgrp;
1690 spin_lock_irq(&css_set_lock);
1691 hash_for_each(css_set_table, i, cset, hlist)
1692 list_move_tail(&cset->e_cset_node[ss->id],
1693 &dcgrp->e_csets[ss->id]);
1694 spin_unlock_irq(&css_set_lock);
1696 /* default hierarchy doesn't enable controllers by default */
1697 dst_root->subsys_mask |= 1 << ssid;
1698 if (dst_root == &cgrp_dfl_root) {
1699 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1701 dcgrp->subtree_control |= 1 << ssid;
1702 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1705 ret = cgroup_apply_control(dcgrp);
1707 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1712 } while_each_subsys_mask();
1714 kernfs_activate(dcgrp->kn);
1718 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1719 struct kernfs_root *kf_root)
1723 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1724 struct cgroup *ns_cgroup;
1726 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1730 spin_lock_irq(&css_set_lock);
1731 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1732 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1733 spin_unlock_irq(&css_set_lock);
1735 if (len >= PATH_MAX)
1738 seq_escape(sf, buf, " \t\n\\");
1745 static int parse_cgroup_root_flags(char *data, unsigned int *root_flags)
1751 if (!data || *data == '\0')
1754 while ((token = strsep(&data, ",")) != NULL) {
1755 if (!strcmp(token, "nsdelegate")) {
1756 *root_flags |= CGRP_ROOT_NS_DELEGATE;
1760 pr_err("cgroup2: unknown option \"%s\"\n", token);
1767 static void apply_cgroup_root_flags(unsigned int root_flags)
1769 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1770 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1771 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1773 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1777 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1779 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1780 seq_puts(seq, ",nsdelegate");
1784 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1786 unsigned int root_flags;
1789 ret = parse_cgroup_root_flags(data, &root_flags);
1793 apply_cgroup_root_flags(root_flags);
1798 * To reduce the fork() overhead for systems that are not actually using
1799 * their cgroups capability, we don't maintain the lists running through
1800 * each css_set to its tasks until we see the list actually used - in other
1801 * words after the first mount.
1803 static bool use_task_css_set_links __read_mostly;
1805 static void cgroup_enable_task_cg_lists(void)
1807 struct task_struct *p, *g;
1810 * We need tasklist_lock because RCU is not safe against
1811 * while_each_thread(). Besides, a forking task that has passed
1812 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1813 * is not guaranteed to have its child immediately visible in the
1814 * tasklist if we walk through it with RCU.
1816 read_lock(&tasklist_lock);
1817 spin_lock_irq(&css_set_lock);
1819 if (use_task_css_set_links)
1822 use_task_css_set_links = true;
1824 do_each_thread(g, p) {
1825 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1826 task_css_set(p) != &init_css_set);
1829 * We should check if the process is exiting, otherwise
1830 * it will race with cgroup_exit() in that the list
1831 * entry won't be deleted though the process has exited.
1832 * Do it while holding siglock so that we don't end up
1833 * racing against cgroup_exit().
1835 * Interrupts were already disabled while acquiring
1836 * the css_set_lock, so we do not need to disable it
1837 * again when acquiring the sighand->siglock here.
1839 spin_lock(&p->sighand->siglock);
1840 if (!(p->flags & PF_EXITING)) {
1841 struct css_set *cset = task_css_set(p);
1843 if (!css_set_populated(cset))
1844 css_set_update_populated(cset, true);
1845 list_add_tail(&p->cg_list, &cset->tasks);
1849 spin_unlock(&p->sighand->siglock);
1850 } while_each_thread(g, p);
1852 spin_unlock_irq(&css_set_lock);
1853 read_unlock(&tasklist_lock);
1856 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1858 struct cgroup_subsys *ss;
1861 INIT_LIST_HEAD(&cgrp->self.sibling);
1862 INIT_LIST_HEAD(&cgrp->self.children);
1863 INIT_LIST_HEAD(&cgrp->cset_links);
1864 INIT_LIST_HEAD(&cgrp->pidlists);
1865 mutex_init(&cgrp->pidlist_mutex);
1866 cgrp->self.cgroup = cgrp;
1867 cgrp->self.flags |= CSS_ONLINE;
1868 cgrp->dom_cgrp = cgrp;
1869 cgrp->max_descendants = INT_MAX;
1870 cgrp->max_depth = INT_MAX;
1871 INIT_LIST_HEAD(&cgrp->rstat_css_list);
1872 prev_cputime_init(&cgrp->prev_cputime);
1874 for_each_subsys(ss, ssid)
1875 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1877 init_waitqueue_head(&cgrp->offline_waitq);
1878 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
1881 void init_cgroup_root(struct cgroup_root *root, struct cgroup_sb_opts *opts)
1883 struct cgroup *cgrp = &root->cgrp;
1885 INIT_LIST_HEAD(&root->root_list);
1886 atomic_set(&root->nr_cgrps, 1);
1888 init_cgroup_housekeeping(cgrp);
1889 idr_init(&root->cgroup_idr);
1891 root->flags = opts->flags;
1892 if (opts->release_agent)
1893 strscpy(root->release_agent_path, opts->release_agent, PATH_MAX);
1895 strscpy(root->name, opts->name, MAX_CGROUP_ROOT_NAMELEN);
1896 if (opts->cpuset_clone_children)
1897 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1900 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask, int ref_flags)
1902 LIST_HEAD(tmp_links);
1903 struct cgroup *root_cgrp = &root->cgrp;
1904 struct kernfs_syscall_ops *kf_sops;
1905 struct css_set *cset;
1908 lockdep_assert_held(&cgroup_mutex);
1910 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1913 root_cgrp->id = ret;
1914 root_cgrp->ancestor_ids[0] = ret;
1916 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
1917 ref_flags, GFP_KERNEL);
1922 * We're accessing css_set_count without locking css_set_lock here,
1923 * but that's OK - it can only be increased by someone holding
1924 * cgroup_lock, and that's us. Later rebinding may disable
1925 * controllers on the default hierarchy and thus create new csets,
1926 * which can't be more than the existing ones. Allocate 2x.
1928 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
1932 ret = cgroup_init_root_id(root);
1936 kf_sops = root == &cgrp_dfl_root ?
1937 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
1939 root->kf_root = kernfs_create_root(kf_sops,
1940 KERNFS_ROOT_CREATE_DEACTIVATED |
1941 KERNFS_ROOT_SUPPORT_EXPORTOP,
1943 if (IS_ERR(root->kf_root)) {
1944 ret = PTR_ERR(root->kf_root);
1947 root_cgrp->kn = root->kf_root->kn;
1949 ret = css_populate_dir(&root_cgrp->self);
1953 ret = rebind_subsystems(root, ss_mask);
1957 ret = cgroup_bpf_inherit(root_cgrp);
1960 trace_cgroup_setup_root(root);
1963 * There must be no failure case after here, since rebinding takes
1964 * care of subsystems' refcounts, which are explicitly dropped in
1965 * the failure exit path.
1967 list_add(&root->root_list, &cgroup_roots);
1968 cgroup_root_count++;
1971 * Link the root cgroup in this hierarchy into all the css_set
1974 spin_lock_irq(&css_set_lock);
1975 hash_for_each(css_set_table, i, cset, hlist) {
1976 link_css_set(&tmp_links, cset, root_cgrp);
1977 if (css_set_populated(cset))
1978 cgroup_update_populated(root_cgrp, true);
1980 spin_unlock_irq(&css_set_lock);
1982 BUG_ON(!list_empty(&root_cgrp->self.children));
1983 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1985 kernfs_activate(root_cgrp->kn);
1990 kernfs_destroy_root(root->kf_root);
1991 root->kf_root = NULL;
1993 cgroup_exit_root_id(root);
1995 percpu_ref_exit(&root_cgrp->self.refcnt);
1997 free_cgrp_cset_links(&tmp_links);
2001 struct dentry *cgroup_do_mount(struct file_system_type *fs_type, int flags,
2002 struct cgroup_root *root, unsigned long magic,
2003 struct cgroup_namespace *ns)
2005 struct dentry *dentry;
2008 dentry = kernfs_mount(fs_type, flags, root->kf_root, magic, &new_sb);
2011 * In non-init cgroup namespace, instead of root cgroup's dentry,
2012 * we return the dentry corresponding to the cgroupns->root_cgrp.
2014 if (!IS_ERR(dentry) && ns != &init_cgroup_ns) {
2015 struct dentry *nsdentry;
2016 struct cgroup *cgrp;
2018 mutex_lock(&cgroup_mutex);
2019 spin_lock_irq(&css_set_lock);
2021 cgrp = cset_cgroup_from_root(ns->root_cset, root);
2023 spin_unlock_irq(&css_set_lock);
2024 mutex_unlock(&cgroup_mutex);
2026 nsdentry = kernfs_node_dentry(cgrp->kn, dentry->d_sb);
2031 if (IS_ERR(dentry) || !new_sb)
2032 cgroup_put(&root->cgrp);
2037 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
2038 int flags, const char *unused_dev_name,
2041 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
2042 struct dentry *dentry;
2047 /* Check if the caller has permission to mount. */
2048 if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) {
2050 return ERR_PTR(-EPERM);
2054 * The first time anyone tries to mount a cgroup, enable the list
2055 * linking each css_set to its tasks and fix up all existing tasks.
2057 if (!use_task_css_set_links)
2058 cgroup_enable_task_cg_lists();
2060 if (fs_type == &cgroup2_fs_type) {
2061 unsigned int root_flags;
2063 ret = parse_cgroup_root_flags(data, &root_flags);
2066 return ERR_PTR(ret);
2069 cgrp_dfl_visible = true;
2070 cgroup_get_live(&cgrp_dfl_root.cgrp);
2072 dentry = cgroup_do_mount(&cgroup2_fs_type, flags, &cgrp_dfl_root,
2073 CGROUP2_SUPER_MAGIC, ns);
2074 if (!IS_ERR(dentry))
2075 apply_cgroup_root_flags(root_flags);
2077 dentry = cgroup1_mount(&cgroup_fs_type, flags, data,
2078 CGROUP_SUPER_MAGIC, ns);
2085 static void cgroup_kill_sb(struct super_block *sb)
2087 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2088 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2091 * If @root doesn't have any mounts or children, start killing it.
2092 * This prevents new mounts by disabling percpu_ref_tryget_live().
2093 * cgroup_mount() may wait for @root's release.
2095 * And don't kill the default root.
2097 if (!list_empty(&root->cgrp.self.children) ||
2098 root == &cgrp_dfl_root)
2099 cgroup_put(&root->cgrp);
2101 percpu_ref_kill(&root->cgrp.self.refcnt);
2106 struct file_system_type cgroup_fs_type = {
2108 .mount = cgroup_mount,
2109 .kill_sb = cgroup_kill_sb,
2110 .fs_flags = FS_USERNS_MOUNT,
2113 static struct file_system_type cgroup2_fs_type = {
2115 .mount = cgroup_mount,
2116 .kill_sb = cgroup_kill_sb,
2117 .fs_flags = FS_USERNS_MOUNT,
2120 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2121 struct cgroup_namespace *ns)
2123 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2125 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2128 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2129 struct cgroup_namespace *ns)
2133 mutex_lock(&cgroup_mutex);
2134 spin_lock_irq(&css_set_lock);
2136 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2138 spin_unlock_irq(&css_set_lock);
2139 mutex_unlock(&cgroup_mutex);
2143 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2146 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2147 * @task: target task
2148 * @buf: the buffer to write the path into
2149 * @buflen: the length of the buffer
2151 * Determine @task's cgroup on the first (the one with the lowest non-zero
2152 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2153 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2154 * cgroup controller callbacks.
2156 * Return value is the same as kernfs_path().
2158 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2160 struct cgroup_root *root;
2161 struct cgroup *cgrp;
2162 int hierarchy_id = 1;
2165 mutex_lock(&cgroup_mutex);
2166 spin_lock_irq(&css_set_lock);
2168 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2171 cgrp = task_cgroup_from_root(task, root);
2172 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2174 /* if no hierarchy exists, everyone is in "/" */
2175 ret = strlcpy(buf, "/", buflen);
2178 spin_unlock_irq(&css_set_lock);
2179 mutex_unlock(&cgroup_mutex);
2182 EXPORT_SYMBOL_GPL(task_cgroup_path);
2185 * cgroup_migrate_add_task - add a migration target task to a migration context
2186 * @task: target task
2187 * @mgctx: target migration context
2189 * Add @task, which is a migration target, to @mgctx->tset. This function
2190 * becomes noop if @task doesn't need to be migrated. @task's css_set
2191 * should have been added as a migration source and @task->cg_list will be
2192 * moved from the css_set's tasks list to mg_tasks one.
2194 static void cgroup_migrate_add_task(struct task_struct *task,
2195 struct cgroup_mgctx *mgctx)
2197 struct css_set *cset;
2199 lockdep_assert_held(&css_set_lock);
2201 /* @task either already exited or can't exit until the end */
2202 if (task->flags & PF_EXITING)
2205 /* leave @task alone if post_fork() hasn't linked it yet */
2206 if (list_empty(&task->cg_list))
2209 cset = task_css_set(task);
2210 if (!cset->mg_src_cgrp)
2213 mgctx->tset.nr_tasks++;
2215 list_move_tail(&task->cg_list, &cset->mg_tasks);
2216 if (list_empty(&cset->mg_node))
2217 list_add_tail(&cset->mg_node,
2218 &mgctx->tset.src_csets);
2219 if (list_empty(&cset->mg_dst_cset->mg_node))
2220 list_add_tail(&cset->mg_dst_cset->mg_node,
2221 &mgctx->tset.dst_csets);
2225 * cgroup_taskset_first - reset taskset and return the first task
2226 * @tset: taskset of interest
2227 * @dst_cssp: output variable for the destination css
2229 * @tset iteration is initialized and the first task is returned.
2231 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2232 struct cgroup_subsys_state **dst_cssp)
2234 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2235 tset->cur_task = NULL;
2237 return cgroup_taskset_next(tset, dst_cssp);
2241 * cgroup_taskset_next - iterate to the next task in taskset
2242 * @tset: taskset of interest
2243 * @dst_cssp: output variable for the destination css
2245 * Return the next task in @tset. Iteration must have been initialized
2246 * with cgroup_taskset_first().
2248 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2249 struct cgroup_subsys_state **dst_cssp)
2251 struct css_set *cset = tset->cur_cset;
2252 struct task_struct *task = tset->cur_task;
2254 while (&cset->mg_node != tset->csets) {
2256 task = list_first_entry(&cset->mg_tasks,
2257 struct task_struct, cg_list);
2259 task = list_next_entry(task, cg_list);
2261 if (&task->cg_list != &cset->mg_tasks) {
2262 tset->cur_cset = cset;
2263 tset->cur_task = task;
2266 * This function may be called both before and
2267 * after cgroup_taskset_migrate(). The two cases
2268 * can be distinguished by looking at whether @cset
2269 * has its ->mg_dst_cset set.
2271 if (cset->mg_dst_cset)
2272 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2274 *dst_cssp = cset->subsys[tset->ssid];
2279 cset = list_next_entry(cset, mg_node);
2287 * cgroup_taskset_migrate - migrate a taskset
2288 * @mgctx: migration context
2290 * Migrate tasks in @mgctx as setup by migration preparation functions.
2291 * This function fails iff one of the ->can_attach callbacks fails and
2292 * guarantees that either all or none of the tasks in @mgctx are migrated.
2293 * @mgctx is consumed regardless of success.
2295 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2297 struct cgroup_taskset *tset = &mgctx->tset;
2298 struct cgroup_subsys *ss;
2299 struct task_struct *task, *tmp_task;
2300 struct css_set *cset, *tmp_cset;
2301 int ssid, failed_ssid, ret;
2303 /* check that we can legitimately attach to the cgroup */
2304 if (tset->nr_tasks) {
2305 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2306 if (ss->can_attach) {
2308 ret = ss->can_attach(tset);
2311 goto out_cancel_attach;
2314 } while_each_subsys_mask();
2318 * Now that we're guaranteed success, proceed to move all tasks to
2319 * the new cgroup. There are no failure cases after here, so this
2320 * is the commit point.
2322 spin_lock_irq(&css_set_lock);
2323 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2324 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2325 struct css_set *from_cset = task_css_set(task);
2326 struct css_set *to_cset = cset->mg_dst_cset;
2328 get_css_set(to_cset);
2329 to_cset->nr_tasks++;
2330 css_set_move_task(task, from_cset, to_cset, true);
2331 put_css_set_locked(from_cset);
2332 from_cset->nr_tasks--;
2335 spin_unlock_irq(&css_set_lock);
2338 * Migration is committed, all target tasks are now on dst_csets.
2339 * Nothing is sensitive to fork() after this point. Notify
2340 * controllers that migration is complete.
2342 tset->csets = &tset->dst_csets;
2344 if (tset->nr_tasks) {
2345 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2350 } while_each_subsys_mask();
2354 goto out_release_tset;
2357 if (tset->nr_tasks) {
2358 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2359 if (ssid == failed_ssid)
2361 if (ss->cancel_attach) {
2363 ss->cancel_attach(tset);
2365 } while_each_subsys_mask();
2368 spin_lock_irq(&css_set_lock);
2369 list_splice_init(&tset->dst_csets, &tset->src_csets);
2370 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2371 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2372 list_del_init(&cset->mg_node);
2374 spin_unlock_irq(&css_set_lock);
2377 * Re-initialize the cgroup_taskset structure in case it is reused
2378 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2382 tset->csets = &tset->src_csets;
2387 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2388 * @dst_cgrp: destination cgroup to test
2390 * On the default hierarchy, except for the mixable, (possible) thread root
2391 * and threaded cgroups, subtree_control must be zero for migration
2392 * destination cgroups with tasks so that child cgroups don't compete
2395 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2397 /* v1 doesn't have any restriction */
2398 if (!cgroup_on_dfl(dst_cgrp))
2401 /* verify @dst_cgrp can host resources */
2402 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2405 /* mixables don't care */
2406 if (cgroup_is_mixable(dst_cgrp))
2410 * If @dst_cgrp is already or can become a thread root or is
2411 * threaded, it doesn't matter.
2413 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2416 /* apply no-internal-process constraint */
2417 if (dst_cgrp->subtree_control)
2424 * cgroup_migrate_finish - cleanup after attach
2425 * @mgctx: migration context
2427 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2428 * those functions for details.
2430 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2432 LIST_HEAD(preloaded);
2433 struct css_set *cset, *tmp_cset;
2435 lockdep_assert_held(&cgroup_mutex);
2437 spin_lock_irq(&css_set_lock);
2439 list_splice_tail_init(&mgctx->preloaded_src_csets, &preloaded);
2440 list_splice_tail_init(&mgctx->preloaded_dst_csets, &preloaded);
2442 list_for_each_entry_safe(cset, tmp_cset, &preloaded, mg_preload_node) {
2443 cset->mg_src_cgrp = NULL;
2444 cset->mg_dst_cgrp = NULL;
2445 cset->mg_dst_cset = NULL;
2446 list_del_init(&cset->mg_preload_node);
2447 put_css_set_locked(cset);
2450 spin_unlock_irq(&css_set_lock);
2454 * cgroup_migrate_add_src - add a migration source css_set
2455 * @src_cset: the source css_set to add
2456 * @dst_cgrp: the destination cgroup
2457 * @mgctx: migration context
2459 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2460 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2461 * up by cgroup_migrate_finish().
2463 * This function may be called without holding cgroup_threadgroup_rwsem
2464 * even if the target is a process. Threads may be created and destroyed
2465 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2466 * into play and the preloaded css_sets are guaranteed to cover all
2469 void cgroup_migrate_add_src(struct css_set *src_cset,
2470 struct cgroup *dst_cgrp,
2471 struct cgroup_mgctx *mgctx)
2473 struct cgroup *src_cgrp;
2475 lockdep_assert_held(&cgroup_mutex);
2476 lockdep_assert_held(&css_set_lock);
2479 * If ->dead, @src_set is associated with one or more dead cgroups
2480 * and doesn't contain any migratable tasks. Ignore it early so
2481 * that the rest of migration path doesn't get confused by it.
2486 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2488 if (!list_empty(&src_cset->mg_preload_node))
2491 WARN_ON(src_cset->mg_src_cgrp);
2492 WARN_ON(src_cset->mg_dst_cgrp);
2493 WARN_ON(!list_empty(&src_cset->mg_tasks));
2494 WARN_ON(!list_empty(&src_cset->mg_node));
2496 src_cset->mg_src_cgrp = src_cgrp;
2497 src_cset->mg_dst_cgrp = dst_cgrp;
2498 get_css_set(src_cset);
2499 list_add_tail(&src_cset->mg_preload_node, &mgctx->preloaded_src_csets);
2503 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2504 * @mgctx: migration context
2506 * Tasks are about to be moved and all the source css_sets have been
2507 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2508 * pins all destination css_sets, links each to its source, and append them
2509 * to @mgctx->preloaded_dst_csets.
2511 * This function must be called after cgroup_migrate_add_src() has been
2512 * called on each migration source css_set. After migration is performed
2513 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2516 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2518 struct css_set *src_cset, *tmp_cset;
2520 lockdep_assert_held(&cgroup_mutex);
2522 /* look up the dst cset for each src cset and link it to src */
2523 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2525 struct css_set *dst_cset;
2526 struct cgroup_subsys *ss;
2529 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2533 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2536 * If src cset equals dst, it's noop. Drop the src.
2537 * cgroup_migrate() will skip the cset too. Note that we
2538 * can't handle src == dst as some nodes are used by both.
2540 if (src_cset == dst_cset) {
2541 src_cset->mg_src_cgrp = NULL;
2542 src_cset->mg_dst_cgrp = NULL;
2543 list_del_init(&src_cset->mg_preload_node);
2544 put_css_set(src_cset);
2545 put_css_set(dst_cset);
2549 src_cset->mg_dst_cset = dst_cset;
2551 if (list_empty(&dst_cset->mg_preload_node))
2552 list_add_tail(&dst_cset->mg_preload_node,
2553 &mgctx->preloaded_dst_csets);
2555 put_css_set(dst_cset);
2557 for_each_subsys(ss, ssid)
2558 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2559 mgctx->ss_mask |= 1 << ssid;
2564 cgroup_migrate_finish(mgctx);
2569 * cgroup_migrate - migrate a process or task to a cgroup
2570 * @leader: the leader of the process or the task to migrate
2571 * @threadgroup: whether @leader points to the whole process or a single task
2572 * @mgctx: migration context
2574 * Migrate a process or task denoted by @leader. If migrating a process,
2575 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2576 * responsible for invoking cgroup_migrate_add_src() and
2577 * cgroup_migrate_prepare_dst() on the targets before invoking this
2578 * function and following up with cgroup_migrate_finish().
2580 * As long as a controller's ->can_attach() doesn't fail, this function is
2581 * guaranteed to succeed. This means that, excluding ->can_attach()
2582 * failure, when migrating multiple targets, the success or failure can be
2583 * decided for all targets by invoking group_migrate_prepare_dst() before
2584 * actually starting migrating.
2586 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2587 struct cgroup_mgctx *mgctx)
2589 struct task_struct *task;
2592 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2593 * already PF_EXITING could be freed from underneath us unless we
2594 * take an rcu_read_lock.
2596 spin_lock_irq(&css_set_lock);
2600 cgroup_migrate_add_task(task, mgctx);
2603 } while_each_thread(leader, task);
2605 spin_unlock_irq(&css_set_lock);
2607 return cgroup_migrate_execute(mgctx);
2611 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2612 * @dst_cgrp: the cgroup to attach to
2613 * @leader: the task or the leader of the threadgroup to be attached
2614 * @threadgroup: attach the whole threadgroup?
2616 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2618 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2621 DEFINE_CGROUP_MGCTX(mgctx);
2622 struct task_struct *task;
2625 ret = cgroup_migrate_vet_dst(dst_cgrp);
2629 /* look up all src csets */
2630 spin_lock_irq(&css_set_lock);
2634 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2637 } while_each_thread(leader, task);
2639 spin_unlock_irq(&css_set_lock);
2641 /* prepare dst csets and commit */
2642 ret = cgroup_migrate_prepare_dst(&mgctx);
2644 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2646 cgroup_migrate_finish(&mgctx);
2649 TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
2654 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup)
2655 __acquires(&cgroup_threadgroup_rwsem)
2657 struct task_struct *tsk;
2660 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2661 return ERR_PTR(-EINVAL);
2663 percpu_down_write(&cgroup_threadgroup_rwsem);
2667 tsk = find_task_by_vpid(pid);
2669 tsk = ERR_PTR(-ESRCH);
2670 goto out_unlock_threadgroup;
2677 tsk = tsk->group_leader;
2680 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2681 * If userland migrates such a kthread to a non-root cgroup, it can
2682 * become trapped in a cpuset, or RT kthread may be born in a
2683 * cgroup with no rt_runtime allocated. Just say no.
2685 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2686 tsk = ERR_PTR(-EINVAL);
2687 goto out_unlock_threadgroup;
2690 get_task_struct(tsk);
2691 goto out_unlock_rcu;
2693 out_unlock_threadgroup:
2694 percpu_up_write(&cgroup_threadgroup_rwsem);
2700 void cgroup_procs_write_finish(struct task_struct *task)
2701 __releases(&cgroup_threadgroup_rwsem)
2703 struct cgroup_subsys *ss;
2706 /* release reference from cgroup_procs_write_start() */
2707 put_task_struct(task);
2709 percpu_up_write(&cgroup_threadgroup_rwsem);
2710 for_each_subsys(ss, ssid)
2711 if (ss->post_attach)
2715 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2717 struct cgroup_subsys *ss;
2718 bool printed = false;
2721 do_each_subsys_mask(ss, ssid, ss_mask) {
2724 seq_printf(seq, "%s", ss->name);
2726 } while_each_subsys_mask();
2728 seq_putc(seq, '\n');
2731 /* show controllers which are enabled from the parent */
2732 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2734 struct cgroup *cgrp = seq_css(seq)->cgroup;
2736 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2740 /* show controllers which are enabled for a given cgroup's children */
2741 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2743 struct cgroup *cgrp = seq_css(seq)->cgroup;
2745 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2750 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2751 * @cgrp: root of the subtree to update csses for
2753 * @cgrp's control masks have changed and its subtree's css associations
2754 * need to be updated accordingly. This function looks up all css_sets
2755 * which are attached to the subtree, creates the matching updated css_sets
2756 * and migrates the tasks to the new ones.
2758 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2760 DEFINE_CGROUP_MGCTX(mgctx);
2761 struct cgroup_subsys_state *d_css;
2762 struct cgroup *dsct;
2763 struct css_set *src_cset;
2766 lockdep_assert_held(&cgroup_mutex);
2768 percpu_down_write(&cgroup_threadgroup_rwsem);
2770 /* look up all csses currently attached to @cgrp's subtree */
2771 spin_lock_irq(&css_set_lock);
2772 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2773 struct cgrp_cset_link *link;
2775 list_for_each_entry(link, &dsct->cset_links, cset_link)
2776 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2778 spin_unlock_irq(&css_set_lock);
2780 /* NULL dst indicates self on default hierarchy */
2781 ret = cgroup_migrate_prepare_dst(&mgctx);
2785 spin_lock_irq(&css_set_lock);
2786 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets, mg_preload_node) {
2787 struct task_struct *task, *ntask;
2789 /* all tasks in src_csets need to be migrated */
2790 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2791 cgroup_migrate_add_task(task, &mgctx);
2793 spin_unlock_irq(&css_set_lock);
2795 ret = cgroup_migrate_execute(&mgctx);
2797 cgroup_migrate_finish(&mgctx);
2798 percpu_up_write(&cgroup_threadgroup_rwsem);
2803 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2804 * @cgrp: root of the target subtree
2806 * Because css offlining is asynchronous, userland may try to re-enable a
2807 * controller while the previous css is still around. This function grabs
2808 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2810 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2811 __acquires(&cgroup_mutex)
2813 struct cgroup *dsct;
2814 struct cgroup_subsys_state *d_css;
2815 struct cgroup_subsys *ss;
2819 mutex_lock(&cgroup_mutex);
2821 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2822 for_each_subsys(ss, ssid) {
2823 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2826 if (!css || !percpu_ref_is_dying(&css->refcnt))
2829 cgroup_get_live(dsct);
2830 prepare_to_wait(&dsct->offline_waitq, &wait,
2831 TASK_UNINTERRUPTIBLE);
2833 mutex_unlock(&cgroup_mutex);
2835 finish_wait(&dsct->offline_waitq, &wait);
2844 * cgroup_save_control - save control masks and dom_cgrp of a subtree
2845 * @cgrp: root of the target subtree
2847 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
2848 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2851 static void cgroup_save_control(struct cgroup *cgrp)
2853 struct cgroup *dsct;
2854 struct cgroup_subsys_state *d_css;
2856 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2857 dsct->old_subtree_control = dsct->subtree_control;
2858 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
2859 dsct->old_dom_cgrp = dsct->dom_cgrp;
2864 * cgroup_propagate_control - refresh control masks of a subtree
2865 * @cgrp: root of the target subtree
2867 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
2868 * ->subtree_control and propagate controller availability through the
2869 * subtree so that descendants don't have unavailable controllers enabled.
2871 static void cgroup_propagate_control(struct cgroup *cgrp)
2873 struct cgroup *dsct;
2874 struct cgroup_subsys_state *d_css;
2876 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2877 dsct->subtree_control &= cgroup_control(dsct);
2878 dsct->subtree_ss_mask =
2879 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
2880 cgroup_ss_mask(dsct));
2885 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
2886 * @cgrp: root of the target subtree
2888 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
2889 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2892 static void cgroup_restore_control(struct cgroup *cgrp)
2894 struct cgroup *dsct;
2895 struct cgroup_subsys_state *d_css;
2897 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2898 dsct->subtree_control = dsct->old_subtree_control;
2899 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
2900 dsct->dom_cgrp = dsct->old_dom_cgrp;
2904 static bool css_visible(struct cgroup_subsys_state *css)
2906 struct cgroup_subsys *ss = css->ss;
2907 struct cgroup *cgrp = css->cgroup;
2909 if (cgroup_control(cgrp) & (1 << ss->id))
2911 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
2913 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
2917 * cgroup_apply_control_enable - enable or show csses according to control
2918 * @cgrp: root of the target subtree
2920 * Walk @cgrp's subtree and create new csses or make the existing ones
2921 * visible. A css is created invisible if it's being implicitly enabled
2922 * through dependency. An invisible css is made visible when the userland
2923 * explicitly enables it.
2925 * Returns 0 on success, -errno on failure. On failure, csses which have
2926 * been processed already aren't cleaned up. The caller is responsible for
2927 * cleaning up with cgroup_apply_control_disable().
2929 static int cgroup_apply_control_enable(struct cgroup *cgrp)
2931 struct cgroup *dsct;
2932 struct cgroup_subsys_state *d_css;
2933 struct cgroup_subsys *ss;
2936 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2937 for_each_subsys(ss, ssid) {
2938 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2940 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
2942 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
2946 css = css_create(dsct, ss);
2948 return PTR_ERR(css);
2951 if (css_visible(css)) {
2952 ret = css_populate_dir(css);
2963 * cgroup_apply_control_disable - kill or hide csses according to control
2964 * @cgrp: root of the target subtree
2966 * Walk @cgrp's subtree and kill and hide csses so that they match
2967 * cgroup_ss_mask() and cgroup_visible_mask().
2969 * A css is hidden when the userland requests it to be disabled while other
2970 * subsystems are still depending on it. The css must not actively control
2971 * resources and be in the vanilla state if it's made visible again later.
2972 * Controllers which may be depended upon should provide ->css_reset() for
2975 static void cgroup_apply_control_disable(struct cgroup *cgrp)
2977 struct cgroup *dsct;
2978 struct cgroup_subsys_state *d_css;
2979 struct cgroup_subsys *ss;
2982 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2983 for_each_subsys(ss, ssid) {
2984 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2986 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
2992 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
2994 } else if (!css_visible(css)) {
3004 * cgroup_apply_control - apply control mask updates to the subtree
3005 * @cgrp: root of the target subtree
3007 * subsystems can be enabled and disabled in a subtree using the following
3010 * 1. Call cgroup_save_control() to stash the current state.
3011 * 2. Update ->subtree_control masks in the subtree as desired.
3012 * 3. Call cgroup_apply_control() to apply the changes.
3013 * 4. Optionally perform other related operations.
3014 * 5. Call cgroup_finalize_control() to finish up.
3016 * This function implements step 3 and propagates the mask changes
3017 * throughout @cgrp's subtree, updates csses accordingly and perform
3018 * process migrations.
3020 static int cgroup_apply_control(struct cgroup *cgrp)
3024 cgroup_propagate_control(cgrp);
3026 ret = cgroup_apply_control_enable(cgrp);
3031 * At this point, cgroup_e_css() results reflect the new csses
3032 * making the following cgroup_update_dfl_csses() properly update
3033 * css associations of all tasks in the subtree.
3035 ret = cgroup_update_dfl_csses(cgrp);
3043 * cgroup_finalize_control - finalize control mask update
3044 * @cgrp: root of the target subtree
3045 * @ret: the result of the update
3047 * Finalize control mask update. See cgroup_apply_control() for more info.
3049 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3052 cgroup_restore_control(cgrp);
3053 cgroup_propagate_control(cgrp);
3056 cgroup_apply_control_disable(cgrp);
3059 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3061 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3063 /* if nothing is getting enabled, nothing to worry about */
3067 /* can @cgrp host any resources? */
3068 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3071 /* mixables don't care */
3072 if (cgroup_is_mixable(cgrp))
3075 if (domain_enable) {
3076 /* can't enable domain controllers inside a thread subtree */
3077 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3081 * Threaded controllers can handle internal competitions
3082 * and are always allowed inside a (prospective) thread
3085 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3090 * Controllers can't be enabled for a cgroup with tasks to avoid
3091 * child cgroups competing against tasks.
3093 if (cgroup_has_tasks(cgrp))
3099 /* change the enabled child controllers for a cgroup in the default hierarchy */
3100 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3101 char *buf, size_t nbytes,
3104 u16 enable = 0, disable = 0;
3105 struct cgroup *cgrp, *child;
3106 struct cgroup_subsys *ss;
3111 * Parse input - space separated list of subsystem names prefixed
3112 * with either + or -.
3114 buf = strstrip(buf);
3115 while ((tok = strsep(&buf, " "))) {
3118 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3119 if (!cgroup_ssid_enabled(ssid) ||
3120 strcmp(tok + 1, ss->name))
3124 enable |= 1 << ssid;
3125 disable &= ~(1 << ssid);
3126 } else if (*tok == '-') {
3127 disable |= 1 << ssid;
3128 enable &= ~(1 << ssid);
3133 } while_each_subsys_mask();
3134 if (ssid == CGROUP_SUBSYS_COUNT)
3138 cgrp = cgroup_kn_lock_live(of->kn, true);
3142 for_each_subsys(ss, ssid) {
3143 if (enable & (1 << ssid)) {
3144 if (cgrp->subtree_control & (1 << ssid)) {
3145 enable &= ~(1 << ssid);
3149 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3153 } else if (disable & (1 << ssid)) {
3154 if (!(cgrp->subtree_control & (1 << ssid))) {
3155 disable &= ~(1 << ssid);
3159 /* a child has it enabled? */
3160 cgroup_for_each_live_child(child, cgrp) {
3161 if (child->subtree_control & (1 << ssid)) {
3169 if (!enable && !disable) {
3174 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3178 /* save and update control masks and prepare csses */
3179 cgroup_save_control(cgrp);
3181 cgrp->subtree_control |= enable;
3182 cgrp->subtree_control &= ~disable;
3184 ret = cgroup_apply_control(cgrp);
3185 cgroup_finalize_control(cgrp, ret);
3189 kernfs_activate(cgrp->kn);
3191 cgroup_kn_unlock(of->kn);
3192 return ret ?: nbytes;
3196 * cgroup_enable_threaded - make @cgrp threaded
3197 * @cgrp: the target cgroup
3199 * Called when "threaded" is written to the cgroup.type interface file and
3200 * tries to make @cgrp threaded and join the parent's resource domain.
3201 * This function is never called on the root cgroup as cgroup.type doesn't
3204 static int cgroup_enable_threaded(struct cgroup *cgrp)
3206 struct cgroup *parent = cgroup_parent(cgrp);
3207 struct cgroup *dom_cgrp = parent->dom_cgrp;
3208 struct cgroup *dsct;
3209 struct cgroup_subsys_state *d_css;
3212 lockdep_assert_held(&cgroup_mutex);
3214 /* noop if already threaded */
3215 if (cgroup_is_threaded(cgrp))
3219 * If @cgroup is populated or has domain controllers enabled, it
3220 * can't be switched. While the below cgroup_can_be_thread_root()
3221 * test can catch the same conditions, that's only when @parent is
3222 * not mixable, so let's check it explicitly.
3224 if (cgroup_is_populated(cgrp) ||
3225 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3228 /* we're joining the parent's domain, ensure its validity */
3229 if (!cgroup_is_valid_domain(dom_cgrp) ||
3230 !cgroup_can_be_thread_root(dom_cgrp))
3234 * The following shouldn't cause actual migrations and should
3237 cgroup_save_control(cgrp);
3239 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3240 if (dsct == cgrp || cgroup_is_threaded(dsct))
3241 dsct->dom_cgrp = dom_cgrp;
3243 ret = cgroup_apply_control(cgrp);
3245 parent->nr_threaded_children++;
3247 cgroup_finalize_control(cgrp, ret);
3251 static int cgroup_type_show(struct seq_file *seq, void *v)
3253 struct cgroup *cgrp = seq_css(seq)->cgroup;
3255 if (cgroup_is_threaded(cgrp))
3256 seq_puts(seq, "threaded\n");
3257 else if (!cgroup_is_valid_domain(cgrp))
3258 seq_puts(seq, "domain invalid\n");
3259 else if (cgroup_is_thread_root(cgrp))
3260 seq_puts(seq, "domain threaded\n");
3262 seq_puts(seq, "domain\n");
3267 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3268 size_t nbytes, loff_t off)
3270 struct cgroup *cgrp;
3273 /* only switching to threaded mode is supported */
3274 if (strcmp(strstrip(buf), "threaded"))
3277 cgrp = cgroup_kn_lock_live(of->kn, false);
3281 /* threaded can only be enabled */
3282 ret = cgroup_enable_threaded(cgrp);
3284 cgroup_kn_unlock(of->kn);
3285 return ret ?: nbytes;
3288 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3290 struct cgroup *cgrp = seq_css(seq)->cgroup;
3291 int descendants = READ_ONCE(cgrp->max_descendants);
3293 if (descendants == INT_MAX)
3294 seq_puts(seq, "max\n");
3296 seq_printf(seq, "%d\n", descendants);
3301 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3302 char *buf, size_t nbytes, loff_t off)
3304 struct cgroup *cgrp;
3308 buf = strstrip(buf);
3309 if (!strcmp(buf, "max")) {
3310 descendants = INT_MAX;
3312 ret = kstrtoint(buf, 0, &descendants);
3317 if (descendants < 0)
3320 cgrp = cgroup_kn_lock_live(of->kn, false);
3324 cgrp->max_descendants = descendants;
3326 cgroup_kn_unlock(of->kn);
3331 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3333 struct cgroup *cgrp = seq_css(seq)->cgroup;
3334 int depth = READ_ONCE(cgrp->max_depth);
3336 if (depth == INT_MAX)
3337 seq_puts(seq, "max\n");
3339 seq_printf(seq, "%d\n", depth);
3344 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3345 char *buf, size_t nbytes, loff_t off)
3347 struct cgroup *cgrp;
3351 buf = strstrip(buf);
3352 if (!strcmp(buf, "max")) {
3355 ret = kstrtoint(buf, 0, &depth);
3363 cgrp = cgroup_kn_lock_live(of->kn, false);
3367 cgrp->max_depth = depth;
3369 cgroup_kn_unlock(of->kn);
3374 static int cgroup_events_show(struct seq_file *seq, void *v)
3376 seq_printf(seq, "populated %d\n",
3377 cgroup_is_populated(seq_css(seq)->cgroup));
3381 static int cgroup_stat_show(struct seq_file *seq, void *v)
3383 struct cgroup *cgroup = seq_css(seq)->cgroup;
3385 seq_printf(seq, "nr_descendants %d\n",
3386 cgroup->nr_descendants);
3387 seq_printf(seq, "nr_dying_descendants %d\n",
3388 cgroup->nr_dying_descendants);
3393 static int __maybe_unused cgroup_extra_stat_show(struct seq_file *seq,
3394 struct cgroup *cgrp, int ssid)
3396 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3397 struct cgroup_subsys_state *css;
3400 if (!ss->css_extra_stat_show)
3403 css = cgroup_tryget_css(cgrp, ss);
3407 ret = ss->css_extra_stat_show(seq, css);
3412 static int cpu_stat_show(struct seq_file *seq, void *v)
3414 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3417 cgroup_base_stat_cputime_show(seq);
3418 #ifdef CONFIG_CGROUP_SCHED
3419 ret = cgroup_extra_stat_show(seq, cgrp, cpu_cgrp_id);
3425 static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
3427 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_IO);
3429 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
3431 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_MEM);
3433 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
3435 return psi_show(seq, &seq_css(seq)->cgroup->psi, PSI_CPU);
3439 static int cgroup_file_open(struct kernfs_open_file *of)
3441 struct cftype *cft = of->kn->priv;
3444 return cft->open(of);
3448 static void cgroup_file_release(struct kernfs_open_file *of)
3450 struct cftype *cft = of->kn->priv;
3456 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3457 size_t nbytes, loff_t off)
3459 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
3460 struct cgroup *cgrp = of->kn->parent->priv;
3461 struct cftype *cft = of->kn->priv;
3462 struct cgroup_subsys_state *css;
3466 * If namespaces are delegation boundaries, disallow writes to
3467 * files in an non-init namespace root from inside the namespace
3468 * except for the files explicitly marked delegatable -
3469 * cgroup.procs and cgroup.subtree_control.
3471 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3472 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3473 ns != &init_cgroup_ns && ns->root_cset->dfl_cgrp == cgrp)
3477 return cft->write(of, buf, nbytes, off);
3480 * kernfs guarantees that a file isn't deleted with operations in
3481 * flight, which means that the matching css is and stays alive and
3482 * doesn't need to be pinned. The RCU locking is not necessary
3483 * either. It's just for the convenience of using cgroup_css().
3486 css = cgroup_css(cgrp, cft->ss);
3489 if (cft->write_u64) {
3490 unsigned long long v;
3491 ret = kstrtoull(buf, 0, &v);
3493 ret = cft->write_u64(css, cft, v);
3494 } else if (cft->write_s64) {
3496 ret = kstrtoll(buf, 0, &v);
3498 ret = cft->write_s64(css, cft, v);
3503 return ret ?: nbytes;
3506 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3508 return seq_cft(seq)->seq_start(seq, ppos);
3511 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3513 return seq_cft(seq)->seq_next(seq, v, ppos);
3516 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3518 if (seq_cft(seq)->seq_stop)
3519 seq_cft(seq)->seq_stop(seq, v);
3522 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3524 struct cftype *cft = seq_cft(m);
3525 struct cgroup_subsys_state *css = seq_css(m);
3528 return cft->seq_show(m, arg);
3531 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3532 else if (cft->read_s64)
3533 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3539 static struct kernfs_ops cgroup_kf_single_ops = {
3540 .atomic_write_len = PAGE_SIZE,
3541 .open = cgroup_file_open,
3542 .release = cgroup_file_release,
3543 .write = cgroup_file_write,
3544 .seq_show = cgroup_seqfile_show,
3547 static struct kernfs_ops cgroup_kf_ops = {
3548 .atomic_write_len = PAGE_SIZE,
3549 .open = cgroup_file_open,
3550 .release = cgroup_file_release,
3551 .write = cgroup_file_write,
3552 .seq_start = cgroup_seqfile_start,
3553 .seq_next = cgroup_seqfile_next,
3554 .seq_stop = cgroup_seqfile_stop,
3555 .seq_show = cgroup_seqfile_show,
3558 /* set uid and gid of cgroup dirs and files to that of the creator */
3559 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3561 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3562 .ia_uid = current_fsuid(),
3563 .ia_gid = current_fsgid(), };
3565 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3566 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3569 return kernfs_setattr(kn, &iattr);
3572 static void cgroup_file_notify_timer(struct timer_list *timer)
3574 cgroup_file_notify(container_of(timer, struct cgroup_file,
3578 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
3581 char name[CGROUP_FILE_NAME_MAX];
3582 struct kernfs_node *kn;
3583 struct lock_class_key *key = NULL;
3586 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3587 key = &cft->lockdep_key;
3589 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3590 cgroup_file_mode(cft),
3591 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
3592 0, cft->kf_ops, cft,
3597 ret = cgroup_kn_set_ugid(kn);
3603 if (cft->file_offset) {
3604 struct cgroup_file *cfile = (void *)css + cft->file_offset;
3606 timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
3608 spin_lock_irq(&cgroup_file_kn_lock);
3610 spin_unlock_irq(&cgroup_file_kn_lock);
3617 * cgroup_addrm_files - add or remove files to a cgroup directory
3618 * @css: the target css
3619 * @cgrp: the target cgroup (usually css->cgroup)
3620 * @cfts: array of cftypes to be added
3621 * @is_add: whether to add or remove
3623 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3624 * For removals, this function never fails.
3626 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
3627 struct cgroup *cgrp, struct cftype cfts[],
3630 struct cftype *cft, *cft_end = NULL;
3633 lockdep_assert_held(&cgroup_mutex);
3636 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
3637 /* does cft->flags tell us to skip this file on @cgrp? */
3638 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3640 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3642 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3644 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3646 if ((cft->flags & CFTYPE_DEBUG) && !cgroup_debug)
3649 ret = cgroup_add_file(css, cgrp, cft);
3651 pr_warn("%s: failed to add %s, err=%d\n",
3652 __func__, cft->name, ret);
3658 cgroup_rm_file(cgrp, cft);
3664 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3666 struct cgroup_subsys *ss = cfts[0].ss;
3667 struct cgroup *root = &ss->root->cgrp;
3668 struct cgroup_subsys_state *css;
3671 lockdep_assert_held(&cgroup_mutex);
3673 /* add/rm files for all cgroups created before */
3674 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3675 struct cgroup *cgrp = css->cgroup;
3677 if (!(css->flags & CSS_VISIBLE))
3680 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
3686 kernfs_activate(root->kn);
3690 static void cgroup_exit_cftypes(struct cftype *cfts)
3694 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3695 /* free copy for custom atomic_write_len, see init_cftypes() */
3696 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3701 /* revert flags set by cgroup core while adding @cfts */
3702 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3706 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3710 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3711 struct kernfs_ops *kf_ops;
3713 WARN_ON(cft->ss || cft->kf_ops);
3716 kf_ops = &cgroup_kf_ops;
3718 kf_ops = &cgroup_kf_single_ops;
3721 * Ugh... if @cft wants a custom max_write_len, we need to
3722 * make a copy of kf_ops to set its atomic_write_len.
3724 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3725 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3727 cgroup_exit_cftypes(cfts);
3730 kf_ops->atomic_write_len = cft->max_write_len;
3733 cft->kf_ops = kf_ops;
3740 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3742 lockdep_assert_held(&cgroup_mutex);
3744 if (!cfts || !cfts[0].ss)
3747 list_del(&cfts->node);
3748 cgroup_apply_cftypes(cfts, false);
3749 cgroup_exit_cftypes(cfts);
3754 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3755 * @cfts: zero-length name terminated array of cftypes
3757 * Unregister @cfts. Files described by @cfts are removed from all
3758 * existing cgroups and all future cgroups won't have them either. This
3759 * function can be called anytime whether @cfts' subsys is attached or not.
3761 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3764 int cgroup_rm_cftypes(struct cftype *cfts)
3768 mutex_lock(&cgroup_mutex);
3769 ret = cgroup_rm_cftypes_locked(cfts);
3770 mutex_unlock(&cgroup_mutex);
3775 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3776 * @ss: target cgroup subsystem
3777 * @cfts: zero-length name terminated array of cftypes
3779 * Register @cfts to @ss. Files described by @cfts are created for all
3780 * existing cgroups to which @ss is attached and all future cgroups will
3781 * have them too. This function can be called anytime whether @ss is
3784 * Returns 0 on successful registration, -errno on failure. Note that this
3785 * function currently returns 0 as long as @cfts registration is successful
3786 * even if some file creation attempts on existing cgroups fail.
3788 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3792 if (!cgroup_ssid_enabled(ss->id))
3795 if (!cfts || cfts[0].name[0] == '\0')
3798 ret = cgroup_init_cftypes(ss, cfts);
3802 mutex_lock(&cgroup_mutex);
3804 list_add_tail(&cfts->node, &ss->cfts);
3805 ret = cgroup_apply_cftypes(cfts, true);
3807 cgroup_rm_cftypes_locked(cfts);
3809 mutex_unlock(&cgroup_mutex);
3814 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3815 * @ss: target cgroup subsystem
3816 * @cfts: zero-length name terminated array of cftypes
3818 * Similar to cgroup_add_cftypes() but the added files are only used for
3819 * the default hierarchy.
3821 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3825 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3826 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3827 return cgroup_add_cftypes(ss, cfts);
3831 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3832 * @ss: target cgroup subsystem
3833 * @cfts: zero-length name terminated array of cftypes
3835 * Similar to cgroup_add_cftypes() but the added files are only used for
3836 * the legacy hierarchies.
3838 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3842 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3843 cft->flags |= __CFTYPE_NOT_ON_DFL;
3844 return cgroup_add_cftypes(ss, cfts);
3848 * cgroup_file_notify - generate a file modified event for a cgroup_file
3849 * @cfile: target cgroup_file
3851 * @cfile must have been obtained by setting cftype->file_offset.
3853 void cgroup_file_notify(struct cgroup_file *cfile)
3855 unsigned long flags;
3857 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
3859 unsigned long last = cfile->notified_at;
3860 unsigned long next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
3862 if (time_in_range(jiffies, last, next)) {
3863 timer_reduce(&cfile->notify_timer, next);
3865 kernfs_notify(cfile->kn);
3866 cfile->notified_at = jiffies;
3869 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
3873 * css_next_child - find the next child of a given css
3874 * @pos: the current position (%NULL to initiate traversal)
3875 * @parent: css whose children to walk
3877 * This function returns the next child of @parent and should be called
3878 * under either cgroup_mutex or RCU read lock. The only requirement is
3879 * that @parent and @pos are accessible. The next sibling is guaranteed to
3880 * be returned regardless of their states.
3882 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3883 * css which finished ->css_online() is guaranteed to be visible in the
3884 * future iterations and will stay visible until the last reference is put.
3885 * A css which hasn't finished ->css_online() or already finished
3886 * ->css_offline() may show up during traversal. It's each subsystem's
3887 * responsibility to synchronize against on/offlining.
3889 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3890 struct cgroup_subsys_state *parent)
3892 struct cgroup_subsys_state *next;
3894 cgroup_assert_mutex_or_rcu_locked();
3897 * @pos could already have been unlinked from the sibling list.
3898 * Once a cgroup is removed, its ->sibling.next is no longer
3899 * updated when its next sibling changes. CSS_RELEASED is set when
3900 * @pos is taken off list, at which time its next pointer is valid,
3901 * and, as releases are serialized, the one pointed to by the next
3902 * pointer is guaranteed to not have started release yet. This
3903 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3904 * critical section, the one pointed to by its next pointer is
3905 * guaranteed to not have finished its RCU grace period even if we
3906 * have dropped rcu_read_lock() inbetween iterations.
3908 * If @pos has CSS_RELEASED set, its next pointer can't be
3909 * dereferenced; however, as each css is given a monotonically
3910 * increasing unique serial number and always appended to the
3911 * sibling list, the next one can be found by walking the parent's
3912 * children until the first css with higher serial number than
3913 * @pos's. While this path can be slower, it happens iff iteration
3914 * races against release and the race window is very small.
3917 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3918 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3919 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3921 list_for_each_entry_rcu(next, &parent->children, sibling)
3922 if (next->serial_nr > pos->serial_nr)
3927 * @next, if not pointing to the head, can be dereferenced and is
3930 if (&next->sibling != &parent->children)
3936 * css_next_descendant_pre - find the next descendant for pre-order walk
3937 * @pos: the current position (%NULL to initiate traversal)
3938 * @root: css whose descendants to walk
3940 * To be used by css_for_each_descendant_pre(). Find the next descendant
3941 * to visit for pre-order traversal of @root's descendants. @root is
3942 * included in the iteration and the first node to be visited.
3944 * While this function requires cgroup_mutex or RCU read locking, it
3945 * doesn't require the whole traversal to be contained in a single critical
3946 * section. This function will return the correct next descendant as long
3947 * as both @pos and @root are accessible and @pos is a descendant of @root.
3949 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3950 * css which finished ->css_online() is guaranteed to be visible in the
3951 * future iterations and will stay visible until the last reference is put.
3952 * A css which hasn't finished ->css_online() or already finished
3953 * ->css_offline() may show up during traversal. It's each subsystem's
3954 * responsibility to synchronize against on/offlining.
3956 struct cgroup_subsys_state *
3957 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3958 struct cgroup_subsys_state *root)
3960 struct cgroup_subsys_state *next;
3962 cgroup_assert_mutex_or_rcu_locked();
3964 /* if first iteration, visit @root */
3968 /* visit the first child if exists */
3969 next = css_next_child(NULL, pos);
3973 /* no child, visit my or the closest ancestor's next sibling */
3974 while (pos != root) {
3975 next = css_next_child(pos, pos->parent);
3985 * css_rightmost_descendant - return the rightmost descendant of a css
3986 * @pos: css of interest
3988 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3989 * is returned. This can be used during pre-order traversal to skip
3992 * While this function requires cgroup_mutex or RCU read locking, it
3993 * doesn't require the whole traversal to be contained in a single critical
3994 * section. This function will return the correct rightmost descendant as
3995 * long as @pos is accessible.
3997 struct cgroup_subsys_state *
3998 css_rightmost_descendant(struct cgroup_subsys_state *pos)
4000 struct cgroup_subsys_state *last, *tmp;
4002 cgroup_assert_mutex_or_rcu_locked();
4006 /* ->prev isn't RCU safe, walk ->next till the end */
4008 css_for_each_child(tmp, last)
4015 static struct cgroup_subsys_state *
4016 css_leftmost_descendant(struct cgroup_subsys_state *pos)
4018 struct cgroup_subsys_state *last;
4022 pos = css_next_child(NULL, pos);
4029 * css_next_descendant_post - find the next descendant for post-order walk
4030 * @pos: the current position (%NULL to initiate traversal)
4031 * @root: css whose descendants to walk
4033 * To be used by css_for_each_descendant_post(). Find the next descendant
4034 * to visit for post-order traversal of @root's descendants. @root is
4035 * included in the iteration and the last node to be visited.
4037 * While this function requires cgroup_mutex or RCU read locking, it
4038 * doesn't require the whole traversal to be contained in a single critical
4039 * section. This function will return the correct next descendant as long
4040 * as both @pos and @cgroup are accessible and @pos is a descendant of
4043 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4044 * css which finished ->css_online() is guaranteed to be visible in the
4045 * future iterations and will stay visible until the last reference is put.
4046 * A css which hasn't finished ->css_online() or already finished
4047 * ->css_offline() may show up during traversal. It's each subsystem's
4048 * responsibility to synchronize against on/offlining.
4050 struct cgroup_subsys_state *
4051 css_next_descendant_post(struct cgroup_subsys_state *pos,
4052 struct cgroup_subsys_state *root)
4054 struct cgroup_subsys_state *next;
4056 cgroup_assert_mutex_or_rcu_locked();
4058 /* if first iteration, visit leftmost descendant which may be @root */
4060 return css_leftmost_descendant(root);
4062 /* if we visited @root, we're done */
4066 /* if there's an unvisited sibling, visit its leftmost descendant */
4067 next = css_next_child(pos, pos->parent);
4069 return css_leftmost_descendant(next);
4071 /* no sibling left, visit parent */
4076 * css_has_online_children - does a css have online children
4077 * @css: the target css
4079 * Returns %true if @css has any online children; otherwise, %false. This
4080 * function can be called from any context but the caller is responsible
4081 * for synchronizing against on/offlining as necessary.
4083 bool css_has_online_children(struct cgroup_subsys_state *css)
4085 struct cgroup_subsys_state *child;
4089 css_for_each_child(child, css) {
4090 if (child->flags & CSS_ONLINE) {
4099 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4101 struct list_head *l;
4102 struct cgrp_cset_link *link;
4103 struct css_set *cset;
4105 lockdep_assert_held(&css_set_lock);
4107 /* find the next threaded cset */
4108 if (it->tcset_pos) {
4109 l = it->tcset_pos->next;
4111 if (l != it->tcset_head) {
4113 return container_of(l, struct css_set,
4114 threaded_csets_node);
4117 it->tcset_pos = NULL;
4120 /* find the next cset */
4123 if (l == it->cset_head) {
4124 it->cset_pos = NULL;
4129 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4131 link = list_entry(l, struct cgrp_cset_link, cset_link);
4137 /* initialize threaded css_set walking */
4138 if (it->flags & CSS_TASK_ITER_THREADED) {
4140 put_css_set_locked(it->cur_dcset);
4141 it->cur_dcset = cset;
4144 it->tcset_head = &cset->threaded_csets;
4145 it->tcset_pos = &cset->threaded_csets;
4152 * css_task_iter_advance_css_set - advance a task itererator to the next css_set
4153 * @it: the iterator to advance
4155 * Advance @it to the next css_set to walk.
4157 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4159 struct css_set *cset;
4161 lockdep_assert_held(&css_set_lock);
4163 /* Advance to the next non-empty css_set */
4165 cset = css_task_iter_next_css_set(it);
4167 it->task_pos = NULL;
4170 } while (!css_set_populated(cset));
4172 if (!list_empty(&cset->tasks))
4173 it->task_pos = cset->tasks.next;
4175 it->task_pos = cset->mg_tasks.next;
4177 it->tasks_head = &cset->tasks;
4178 it->mg_tasks_head = &cset->mg_tasks;
4181 * We don't keep css_sets locked across iteration steps and thus
4182 * need to take steps to ensure that iteration can be resumed after
4183 * the lock is re-acquired. Iteration is performed at two levels -
4184 * css_sets and tasks in them.
4186 * Once created, a css_set never leaves its cgroup lists, so a
4187 * pinned css_set is guaranteed to stay put and we can resume
4188 * iteration afterwards.
4190 * Tasks may leave @cset across iteration steps. This is resolved
4191 * by registering each iterator with the css_set currently being
4192 * walked and making css_set_move_task() advance iterators whose
4193 * next task is leaving.
4196 list_del(&it->iters_node);
4197 put_css_set_locked(it->cur_cset);
4200 it->cur_cset = cset;
4201 list_add(&it->iters_node, &cset->task_iters);
4204 static void css_task_iter_advance(struct css_task_iter *it)
4206 struct list_head *next;
4208 lockdep_assert_held(&css_set_lock);
4212 * Advance iterator to find next entry. cset->tasks is
4213 * consumed first and then ->mg_tasks. After ->mg_tasks,
4214 * we move onto the next cset.
4216 next = it->task_pos->next;
4218 if (next == it->tasks_head)
4219 next = it->mg_tasks_head->next;
4221 if (next == it->mg_tasks_head)
4222 css_task_iter_advance_css_set(it);
4224 it->task_pos = next;
4226 /* called from start, proceed to the first cset */
4227 css_task_iter_advance_css_set(it);
4230 /* if PROCS, skip over tasks which aren't group leaders */
4231 if ((it->flags & CSS_TASK_ITER_PROCS) && it->task_pos &&
4232 !thread_group_leader(list_entry(it->task_pos, struct task_struct,
4238 * css_task_iter_start - initiate task iteration
4239 * @css: the css to walk tasks of
4240 * @flags: CSS_TASK_ITER_* flags
4241 * @it: the task iterator to use
4243 * Initiate iteration through the tasks of @css. The caller can call
4244 * css_task_iter_next() to walk through the tasks until the function
4245 * returns NULL. On completion of iteration, css_task_iter_end() must be
4248 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4249 struct css_task_iter *it)
4251 /* no one should try to iterate before mounting cgroups */
4252 WARN_ON_ONCE(!use_task_css_set_links);
4254 memset(it, 0, sizeof(*it));
4256 spin_lock_irq(&css_set_lock);
4262 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4264 it->cset_pos = &css->cgroup->cset_links;
4266 it->cset_head = it->cset_pos;
4268 css_task_iter_advance(it);
4270 spin_unlock_irq(&css_set_lock);
4274 * css_task_iter_next - return the next task for the iterator
4275 * @it: the task iterator being iterated
4277 * The "next" function for task iteration. @it should have been
4278 * initialized via css_task_iter_start(). Returns NULL when the iteration
4281 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4284 put_task_struct(it->cur_task);
4285 it->cur_task = NULL;
4288 spin_lock_irq(&css_set_lock);
4291 it->cur_task = list_entry(it->task_pos, struct task_struct,
4293 get_task_struct(it->cur_task);
4294 css_task_iter_advance(it);
4297 spin_unlock_irq(&css_set_lock);
4299 return it->cur_task;
4303 * css_task_iter_end - finish task iteration
4304 * @it: the task iterator to finish
4306 * Finish task iteration started by css_task_iter_start().
4308 void css_task_iter_end(struct css_task_iter *it)
4311 spin_lock_irq(&css_set_lock);
4312 list_del(&it->iters_node);
4313 put_css_set_locked(it->cur_cset);
4314 spin_unlock_irq(&css_set_lock);
4318 put_css_set(it->cur_dcset);
4321 put_task_struct(it->cur_task);
4324 static void cgroup_procs_release(struct kernfs_open_file *of)
4327 css_task_iter_end(of->priv);
4332 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
4334 struct kernfs_open_file *of = s->private;
4335 struct css_task_iter *it = of->priv;
4337 return css_task_iter_next(it);
4340 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
4341 unsigned int iter_flags)
4343 struct kernfs_open_file *of = s->private;
4344 struct cgroup *cgrp = seq_css(s)->cgroup;
4345 struct css_task_iter *it = of->priv;
4348 * When a seq_file is seeked, it's always traversed sequentially
4349 * from position 0, so we can simply keep iterating on !0 *pos.
4352 if (WARN_ON_ONCE((*pos)++))
4353 return ERR_PTR(-EINVAL);
4355 it = kzalloc(sizeof(*it), GFP_KERNEL);
4357 return ERR_PTR(-ENOMEM);
4359 css_task_iter_start(&cgrp->self, iter_flags, it);
4360 } else if (!(*pos)++) {
4361 css_task_iter_end(it);
4362 css_task_iter_start(&cgrp->self, iter_flags, it);
4365 return cgroup_procs_next(s, NULL, NULL);
4368 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
4370 struct cgroup *cgrp = seq_css(s)->cgroup;
4373 * All processes of a threaded subtree belong to the domain cgroup
4374 * of the subtree. Only threads can be distributed across the
4375 * subtree. Reject reads on cgroup.procs in the subtree proper.
4376 * They're always empty anyway.
4378 if (cgroup_is_threaded(cgrp))
4379 return ERR_PTR(-EOPNOTSUPP);
4381 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
4382 CSS_TASK_ITER_THREADED);
4385 static int cgroup_procs_show(struct seq_file *s, void *v)
4387 seq_printf(s, "%d\n", task_pid_vnr(v));
4391 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
4392 struct cgroup *dst_cgrp,
4393 struct super_block *sb)
4395 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
4396 struct cgroup *com_cgrp = src_cgrp;
4397 struct inode *inode;
4400 lockdep_assert_held(&cgroup_mutex);
4402 /* find the common ancestor */
4403 while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
4404 com_cgrp = cgroup_parent(com_cgrp);
4406 /* %current should be authorized to migrate to the common ancestor */
4407 inode = kernfs_get_inode(sb, com_cgrp->procs_file.kn);
4411 ret = inode_permission(inode, MAY_WRITE);
4417 * If namespaces are delegation boundaries, %current must be able
4418 * to see both source and destination cgroups from its namespace.
4420 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
4421 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
4422 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
4428 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
4429 char *buf, size_t nbytes, loff_t off)
4431 struct cgroup *src_cgrp, *dst_cgrp;
4432 struct task_struct *task;
4435 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4439 task = cgroup_procs_write_start(buf, true);
4440 ret = PTR_ERR_OR_ZERO(task);
4444 /* find the source cgroup */
4445 spin_lock_irq(&css_set_lock);
4446 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4447 spin_unlock_irq(&css_set_lock);
4449 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4450 of->file->f_path.dentry->d_sb);
4454 ret = cgroup_attach_task(dst_cgrp, task, true);
4457 cgroup_procs_write_finish(task);
4459 cgroup_kn_unlock(of->kn);
4461 return ret ?: nbytes;
4464 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
4466 return __cgroup_procs_start(s, pos, 0);
4469 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
4470 char *buf, size_t nbytes, loff_t off)
4472 struct cgroup *src_cgrp, *dst_cgrp;
4473 struct task_struct *task;
4476 buf = strstrip(buf);
4478 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4482 task = cgroup_procs_write_start(buf, false);
4483 ret = PTR_ERR_OR_ZERO(task);
4487 /* find the source cgroup */
4488 spin_lock_irq(&css_set_lock);
4489 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4490 spin_unlock_irq(&css_set_lock);
4492 /* thread migrations follow the cgroup.procs delegation rule */
4493 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4494 of->file->f_path.dentry->d_sb);
4498 /* and must be contained in the same domain */
4500 if (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp)
4503 ret = cgroup_attach_task(dst_cgrp, task, false);
4506 cgroup_procs_write_finish(task);
4508 cgroup_kn_unlock(of->kn);
4510 return ret ?: nbytes;
4513 /* cgroup core interface files for the default hierarchy */
4514 static struct cftype cgroup_base_files[] = {
4516 .name = "cgroup.type",
4517 .flags = CFTYPE_NOT_ON_ROOT,
4518 .seq_show = cgroup_type_show,
4519 .write = cgroup_type_write,
4522 .name = "cgroup.procs",
4523 .flags = CFTYPE_NS_DELEGATABLE,
4524 .file_offset = offsetof(struct cgroup, procs_file),
4525 .release = cgroup_procs_release,
4526 .seq_start = cgroup_procs_start,
4527 .seq_next = cgroup_procs_next,
4528 .seq_show = cgroup_procs_show,
4529 .write = cgroup_procs_write,
4532 .name = "cgroup.threads",
4533 .flags = CFTYPE_NS_DELEGATABLE,
4534 .release = cgroup_procs_release,
4535 .seq_start = cgroup_threads_start,
4536 .seq_next = cgroup_procs_next,
4537 .seq_show = cgroup_procs_show,
4538 .write = cgroup_threads_write,
4541 .name = "cgroup.controllers",
4542 .seq_show = cgroup_controllers_show,
4545 .name = "cgroup.subtree_control",
4546 .flags = CFTYPE_NS_DELEGATABLE,
4547 .seq_show = cgroup_subtree_control_show,
4548 .write = cgroup_subtree_control_write,
4551 .name = "cgroup.events",
4552 .flags = CFTYPE_NOT_ON_ROOT,
4553 .file_offset = offsetof(struct cgroup, events_file),
4554 .seq_show = cgroup_events_show,
4557 .name = "cgroup.max.descendants",
4558 .seq_show = cgroup_max_descendants_show,
4559 .write = cgroup_max_descendants_write,
4562 .name = "cgroup.max.depth",
4563 .seq_show = cgroup_max_depth_show,
4564 .write = cgroup_max_depth_write,
4567 .name = "cgroup.stat",
4568 .seq_show = cgroup_stat_show,
4572 .flags = CFTYPE_NOT_ON_ROOT,
4573 .seq_show = cpu_stat_show,
4577 .name = "io.pressure",
4578 .flags = CFTYPE_NOT_ON_ROOT,
4579 .seq_show = cgroup_io_pressure_show,
4582 .name = "memory.pressure",
4583 .flags = CFTYPE_NOT_ON_ROOT,
4584 .seq_show = cgroup_memory_pressure_show,
4587 .name = "cpu.pressure",
4588 .flags = CFTYPE_NOT_ON_ROOT,
4589 .seq_show = cgroup_cpu_pressure_show,
4596 * css destruction is four-stage process.
4598 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4599 * Implemented in kill_css().
4601 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4602 * and thus css_tryget_online() is guaranteed to fail, the css can be
4603 * offlined by invoking offline_css(). After offlining, the base ref is
4604 * put. Implemented in css_killed_work_fn().
4606 * 3. When the percpu_ref reaches zero, the only possible remaining
4607 * accessors are inside RCU read sections. css_release() schedules the
4610 * 4. After the grace period, the css can be freed. Implemented in
4611 * css_free_work_fn().
4613 * It is actually hairier because both step 2 and 4 require process context
4614 * and thus involve punting to css->destroy_work adding two additional
4615 * steps to the already complex sequence.
4617 static void css_free_rwork_fn(struct work_struct *work)
4619 struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
4620 struct cgroup_subsys_state, destroy_rwork);
4621 struct cgroup_subsys *ss = css->ss;
4622 struct cgroup *cgrp = css->cgroup;
4624 percpu_ref_exit(&css->refcnt);
4628 struct cgroup_subsys_state *parent = css->parent;
4632 cgroup_idr_remove(&ss->css_idr, id);
4638 /* cgroup free path */
4639 atomic_dec(&cgrp->root->nr_cgrps);
4640 cgroup1_pidlist_destroy_all(cgrp);
4641 cancel_work_sync(&cgrp->release_agent_work);
4643 if (cgroup_parent(cgrp)) {
4645 * We get a ref to the parent, and put the ref when
4646 * this cgroup is being freed, so it's guaranteed
4647 * that the parent won't be destroyed before its
4650 cgroup_put(cgroup_parent(cgrp));
4651 kernfs_put(cgrp->kn);
4652 psi_cgroup_free(cgrp);
4653 if (cgroup_on_dfl(cgrp))
4654 cgroup_rstat_exit(cgrp);
4658 * This is root cgroup's refcnt reaching zero,
4659 * which indicates that the root should be
4662 cgroup_destroy_root(cgrp->root);
4667 static void css_release_work_fn(struct work_struct *work)
4669 struct cgroup_subsys_state *css =
4670 container_of(work, struct cgroup_subsys_state, destroy_work);
4671 struct cgroup_subsys *ss = css->ss;
4672 struct cgroup *cgrp = css->cgroup;
4674 mutex_lock(&cgroup_mutex);
4676 css->flags |= CSS_RELEASED;
4677 list_del_rcu(&css->sibling);
4680 /* css release path */
4681 if (!list_empty(&css->rstat_css_node)) {
4682 cgroup_rstat_flush(cgrp);
4683 list_del_rcu(&css->rstat_css_node);
4686 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4687 if (ss->css_released)
4688 ss->css_released(css);
4690 struct cgroup *tcgrp;
4692 /* cgroup release path */
4693 TRACE_CGROUP_PATH(release, cgrp);
4695 if (cgroup_on_dfl(cgrp))
4696 cgroup_rstat_flush(cgrp);
4698 for (tcgrp = cgroup_parent(cgrp); tcgrp;
4699 tcgrp = cgroup_parent(tcgrp))
4700 tcgrp->nr_dying_descendants--;
4702 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4706 * There are two control paths which try to determine
4707 * cgroup from dentry without going through kernfs -
4708 * cgroupstats_build() and css_tryget_online_from_dir().
4709 * Those are supported by RCU protecting clearing of
4710 * cgrp->kn->priv backpointer.
4713 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
4716 cgroup_bpf_put(cgrp);
4719 mutex_unlock(&cgroup_mutex);
4721 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
4722 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
4725 static void css_release(struct percpu_ref *ref)
4727 struct cgroup_subsys_state *css =
4728 container_of(ref, struct cgroup_subsys_state, refcnt);
4730 INIT_WORK(&css->destroy_work, css_release_work_fn);
4731 queue_work(cgroup_destroy_wq, &css->destroy_work);
4734 static void init_and_link_css(struct cgroup_subsys_state *css,
4735 struct cgroup_subsys *ss, struct cgroup *cgrp)
4737 lockdep_assert_held(&cgroup_mutex);
4739 cgroup_get_live(cgrp);
4741 memset(css, 0, sizeof(*css));
4745 INIT_LIST_HEAD(&css->sibling);
4746 INIT_LIST_HEAD(&css->children);
4747 INIT_LIST_HEAD(&css->rstat_css_node);
4748 css->serial_nr = css_serial_nr_next++;
4749 atomic_set(&css->online_cnt, 0);
4751 if (cgroup_parent(cgrp)) {
4752 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4753 css_get(css->parent);
4756 if (cgroup_on_dfl(cgrp) && ss->css_rstat_flush)
4757 list_add_rcu(&css->rstat_css_node, &cgrp->rstat_css_list);
4759 BUG_ON(cgroup_css(cgrp, ss));
4762 /* invoke ->css_online() on a new CSS and mark it online if successful */
4763 static int online_css(struct cgroup_subsys_state *css)
4765 struct cgroup_subsys *ss = css->ss;
4768 lockdep_assert_held(&cgroup_mutex);
4771 ret = ss->css_online(css);
4773 css->flags |= CSS_ONLINE;
4774 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4776 atomic_inc(&css->online_cnt);
4778 atomic_inc(&css->parent->online_cnt);
4783 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4784 static void offline_css(struct cgroup_subsys_state *css)
4786 struct cgroup_subsys *ss = css->ss;
4788 lockdep_assert_held(&cgroup_mutex);
4790 if (!(css->flags & CSS_ONLINE))
4793 if (ss->css_offline)
4794 ss->css_offline(css);
4796 css->flags &= ~CSS_ONLINE;
4797 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4799 wake_up_all(&css->cgroup->offline_waitq);
4803 * css_create - create a cgroup_subsys_state
4804 * @cgrp: the cgroup new css will be associated with
4805 * @ss: the subsys of new css
4807 * Create a new css associated with @cgrp - @ss pair. On success, the new
4808 * css is online and installed in @cgrp. This function doesn't create the
4809 * interface files. Returns 0 on success, -errno on failure.
4811 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
4812 struct cgroup_subsys *ss)
4814 struct cgroup *parent = cgroup_parent(cgrp);
4815 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4816 struct cgroup_subsys_state *css;
4819 lockdep_assert_held(&cgroup_mutex);
4821 css = ss->css_alloc(parent_css);
4823 css = ERR_PTR(-ENOMEM);
4827 init_and_link_css(css, ss, cgrp);
4829 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4833 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
4838 /* @css is ready to be brought online now, make it visible */
4839 list_add_tail_rcu(&css->sibling, &parent_css->children);
4840 cgroup_idr_replace(&ss->css_idr, css, css->id);
4842 err = online_css(css);
4846 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4847 cgroup_parent(parent)) {
4848 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4849 current->comm, current->pid, ss->name);
4850 if (!strcmp(ss->name, "memory"))
4851 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4852 ss->warned_broken_hierarchy = true;
4858 list_del_rcu(&css->sibling);
4860 list_del_rcu(&css->rstat_css_node);
4861 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
4862 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
4863 return ERR_PTR(err);
4867 * The returned cgroup is fully initialized including its control mask, but
4868 * it isn't associated with its kernfs_node and doesn't have the control
4871 static struct cgroup *cgroup_create(struct cgroup *parent)
4873 struct cgroup_root *root = parent->root;
4874 struct cgroup *cgrp, *tcgrp;
4875 int level = parent->level + 1;
4878 /* allocate the cgroup and its ID, 0 is reserved for the root */
4879 cgrp = kzalloc(struct_size(cgrp, ancestor_ids, (level + 1)),
4882 return ERR_PTR(-ENOMEM);
4884 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
4888 if (cgroup_on_dfl(parent)) {
4889 ret = cgroup_rstat_init(cgrp);
4891 goto out_cancel_ref;
4895 * Temporarily set the pointer to NULL, so idr_find() won't return
4896 * a half-baked cgroup.
4898 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
4904 init_cgroup_housekeeping(cgrp);
4906 cgrp->self.parent = &parent->self;
4908 cgrp->level = level;
4910 ret = psi_cgroup_alloc(cgrp);
4914 ret = cgroup_bpf_inherit(cgrp);
4918 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
4919 cgrp->ancestor_ids[tcgrp->level] = tcgrp->id;
4922 tcgrp->nr_descendants++;
4925 if (notify_on_release(parent))
4926 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4928 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4929 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4931 cgrp->self.serial_nr = css_serial_nr_next++;
4933 /* allocation complete, commit to creation */
4934 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4935 atomic_inc(&root->nr_cgrps);
4936 cgroup_get_live(parent);
4939 * @cgrp is now fully operational. If something fails after this
4940 * point, it'll be released via the normal destruction path.
4942 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4945 * On the default hierarchy, a child doesn't automatically inherit
4946 * subtree_control from the parent. Each is configured manually.
4948 if (!cgroup_on_dfl(cgrp))
4949 cgrp->subtree_control = cgroup_control(cgrp);
4951 cgroup_propagate_control(cgrp);
4956 psi_cgroup_free(cgrp);
4958 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4960 if (cgroup_on_dfl(parent))
4961 cgroup_rstat_exit(cgrp);
4963 percpu_ref_exit(&cgrp->self.refcnt);
4966 return ERR_PTR(ret);
4969 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
4971 struct cgroup *cgroup;
4975 lockdep_assert_held(&cgroup_mutex);
4977 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
4978 if (cgroup->nr_descendants >= cgroup->max_descendants)
4981 if (level > cgroup->max_depth)
4992 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
4994 struct cgroup *parent, *cgrp;
4995 struct kernfs_node *kn;
4998 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
4999 if (strchr(name, '\n'))
5002 parent = cgroup_kn_lock_live(parent_kn, false);
5006 if (!cgroup_check_hierarchy_limits(parent)) {
5011 cgrp = cgroup_create(parent);
5013 ret = PTR_ERR(cgrp);
5017 /* create the directory */
5018 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
5026 * This extra ref will be put in cgroup_free_fn() and guarantees
5027 * that @cgrp->kn is always accessible.
5031 ret = cgroup_kn_set_ugid(kn);
5035 ret = css_populate_dir(&cgrp->self);
5039 ret = cgroup_apply_control_enable(cgrp);
5043 TRACE_CGROUP_PATH(mkdir, cgrp);
5045 /* let's create and online css's */
5046 kernfs_activate(kn);
5052 cgroup_destroy_locked(cgrp);
5054 cgroup_kn_unlock(parent_kn);
5059 * This is called when the refcnt of a css is confirmed to be killed.
5060 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
5061 * initate destruction and put the css ref from kill_css().
5063 static void css_killed_work_fn(struct work_struct *work)
5065 struct cgroup_subsys_state *css =
5066 container_of(work, struct cgroup_subsys_state, destroy_work);
5068 mutex_lock(&cgroup_mutex);
5073 /* @css can't go away while we're holding cgroup_mutex */
5075 } while (css && atomic_dec_and_test(&css->online_cnt));
5077 mutex_unlock(&cgroup_mutex);
5080 /* css kill confirmation processing requires process context, bounce */
5081 static void css_killed_ref_fn(struct percpu_ref *ref)
5083 struct cgroup_subsys_state *css =
5084 container_of(ref, struct cgroup_subsys_state, refcnt);
5086 if (atomic_dec_and_test(&css->online_cnt)) {
5087 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5088 queue_work(cgroup_destroy_wq, &css->destroy_work);
5093 * kill_css - destroy a css
5094 * @css: css to destroy
5096 * This function initiates destruction of @css by removing cgroup interface
5097 * files and putting its base reference. ->css_offline() will be invoked
5098 * asynchronously once css_tryget_online() is guaranteed to fail and when
5099 * the reference count reaches zero, @css will be released.
5101 static void kill_css(struct cgroup_subsys_state *css)
5103 lockdep_assert_held(&cgroup_mutex);
5105 if (css->flags & CSS_DYING)
5108 css->flags |= CSS_DYING;
5111 * This must happen before css is disassociated with its cgroup.
5112 * See seq_css() for details.
5117 * Killing would put the base ref, but we need to keep it alive
5118 * until after ->css_offline().
5123 * cgroup core guarantees that, by the time ->css_offline() is
5124 * invoked, no new css reference will be given out via
5125 * css_tryget_online(). We can't simply call percpu_ref_kill() and
5126 * proceed to offlining css's because percpu_ref_kill() doesn't
5127 * guarantee that the ref is seen as killed on all CPUs on return.
5129 * Use percpu_ref_kill_and_confirm() to get notifications as each
5130 * css is confirmed to be seen as killed on all CPUs.
5132 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5136 * cgroup_destroy_locked - the first stage of cgroup destruction
5137 * @cgrp: cgroup to be destroyed
5139 * css's make use of percpu refcnts whose killing latency shouldn't be
5140 * exposed to userland and are RCU protected. Also, cgroup core needs to
5141 * guarantee that css_tryget_online() won't succeed by the time
5142 * ->css_offline() is invoked. To satisfy all the requirements,
5143 * destruction is implemented in the following two steps.
5145 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
5146 * userland visible parts and start killing the percpu refcnts of
5147 * css's. Set up so that the next stage will be kicked off once all
5148 * the percpu refcnts are confirmed to be killed.
5150 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5151 * rest of destruction. Once all cgroup references are gone, the
5152 * cgroup is RCU-freed.
5154 * This function implements s1. After this step, @cgrp is gone as far as
5155 * the userland is concerned and a new cgroup with the same name may be
5156 * created. As cgroup doesn't care about the names internally, this
5157 * doesn't cause any problem.
5159 static int cgroup_destroy_locked(struct cgroup *cgrp)
5160 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5162 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5163 struct cgroup_subsys_state *css;
5164 struct cgrp_cset_link *link;
5167 lockdep_assert_held(&cgroup_mutex);
5170 * Only migration can raise populated from zero and we're already
5171 * holding cgroup_mutex.
5173 if (cgroup_is_populated(cgrp))
5177 * Make sure there's no live children. We can't test emptiness of
5178 * ->self.children as dead children linger on it while being
5179 * drained; otherwise, "rmdir parent/child parent" may fail.
5181 if (css_has_online_children(&cgrp->self))
5185 * Mark @cgrp and the associated csets dead. The former prevents
5186 * further task migration and child creation by disabling
5187 * cgroup_lock_live_group(). The latter makes the csets ignored by
5188 * the migration path.
5190 cgrp->self.flags &= ~CSS_ONLINE;
5192 spin_lock_irq(&css_set_lock);
5193 list_for_each_entry(link, &cgrp->cset_links, cset_link)
5194 link->cset->dead = true;
5195 spin_unlock_irq(&css_set_lock);
5197 /* initiate massacre of all css's */
5198 for_each_css(css, ssid, cgrp)
5201 /* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
5202 css_clear_dir(&cgrp->self);
5203 kernfs_remove(cgrp->kn);
5205 if (parent && cgroup_is_threaded(cgrp))
5206 parent->nr_threaded_children--;
5208 for (tcgrp = cgroup_parent(cgrp); tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5209 tcgrp->nr_descendants--;
5210 tcgrp->nr_dying_descendants++;
5213 cgroup1_check_for_release(parent);
5215 /* put the base reference */
5216 percpu_ref_kill(&cgrp->self.refcnt);
5221 int cgroup_rmdir(struct kernfs_node *kn)
5223 struct cgroup *cgrp;
5226 cgrp = cgroup_kn_lock_live(kn, false);
5230 ret = cgroup_destroy_locked(cgrp);
5232 TRACE_CGROUP_PATH(rmdir, cgrp);
5234 cgroup_kn_unlock(kn);
5238 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5239 .show_options = cgroup_show_options,
5240 .remount_fs = cgroup_remount,
5241 .mkdir = cgroup_mkdir,
5242 .rmdir = cgroup_rmdir,
5243 .show_path = cgroup_show_path,
5246 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5248 struct cgroup_subsys_state *css;
5250 pr_debug("Initializing cgroup subsys %s\n", ss->name);
5252 mutex_lock(&cgroup_mutex);
5254 idr_init(&ss->css_idr);
5255 INIT_LIST_HEAD(&ss->cfts);
5257 /* Create the root cgroup state for this subsystem */
5258 ss->root = &cgrp_dfl_root;
5259 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5260 /* We don't handle early failures gracefully */
5261 BUG_ON(IS_ERR(css));
5262 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5265 * Root csses are never destroyed and we can't initialize
5266 * percpu_ref during early init. Disable refcnting.
5268 css->flags |= CSS_NO_REF;
5271 /* allocation can't be done safely during early init */
5274 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5275 BUG_ON(css->id < 0);
5278 /* Update the init_css_set to contain a subsys
5279 * pointer to this state - since the subsystem is
5280 * newly registered, all tasks and hence the
5281 * init_css_set is in the subsystem's root cgroup. */
5282 init_css_set.subsys[ss->id] = css;
5284 have_fork_callback |= (bool)ss->fork << ss->id;
5285 have_exit_callback |= (bool)ss->exit << ss->id;
5286 have_free_callback |= (bool)ss->free << ss->id;
5287 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5289 /* At system boot, before all subsystems have been
5290 * registered, no tasks have been forked, so we don't
5291 * need to invoke fork callbacks here. */
5292 BUG_ON(!list_empty(&init_task.tasks));
5294 BUG_ON(online_css(css));
5296 mutex_unlock(&cgroup_mutex);
5300 * cgroup_init_early - cgroup initialization at system boot
5302 * Initialize cgroups at system boot, and initialize any
5303 * subsystems that request early init.
5305 int __init cgroup_init_early(void)
5307 static struct cgroup_sb_opts __initdata opts;
5308 struct cgroup_subsys *ss;
5311 init_cgroup_root(&cgrp_dfl_root, &opts);
5312 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5314 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5316 for_each_subsys(ss, i) {
5317 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5318 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
5319 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5321 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5322 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5325 ss->name = cgroup_subsys_name[i];
5326 if (!ss->legacy_name)
5327 ss->legacy_name = cgroup_subsys_name[i];
5330 cgroup_init_subsys(ss, true);
5335 static u16 cgroup_disable_mask __initdata;
5338 * cgroup_init - cgroup initialization
5340 * Register cgroup filesystem and /proc file, and initialize
5341 * any subsystems that didn't request early init.
5343 int __init cgroup_init(void)
5345 struct cgroup_subsys *ss;
5348 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
5349 BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
5350 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
5351 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
5353 cgroup_rstat_boot();
5356 * The latency of the synchronize_sched() is too high for cgroups,
5357 * avoid it at the cost of forcing all readers into the slow path.
5359 rcu_sync_enter_start(&cgroup_threadgroup_rwsem.rss);
5361 get_user_ns(init_cgroup_ns.user_ns);
5363 mutex_lock(&cgroup_mutex);
5366 * Add init_css_set to the hash table so that dfl_root can link to
5369 hash_add(css_set_table, &init_css_set.hlist,
5370 css_set_hash(init_css_set.subsys));
5372 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0, 0));
5374 mutex_unlock(&cgroup_mutex);
5376 for_each_subsys(ss, ssid) {
5377 if (ss->early_init) {
5378 struct cgroup_subsys_state *css =
5379 init_css_set.subsys[ss->id];
5381 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5383 BUG_ON(css->id < 0);
5385 cgroup_init_subsys(ss, false);
5388 list_add_tail(&init_css_set.e_cset_node[ssid],
5389 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5392 * Setting dfl_root subsys_mask needs to consider the
5393 * disabled flag and cftype registration needs kmalloc,
5394 * both of which aren't available during early_init.
5396 if (cgroup_disable_mask & (1 << ssid)) {
5397 static_branch_disable(cgroup_subsys_enabled_key[ssid]);
5398 printk(KERN_INFO "Disabling %s control group subsystem\n",
5403 if (cgroup1_ssid_disabled(ssid))
5404 printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
5407 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5409 /* implicit controllers must be threaded too */
5410 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
5412 if (ss->implicit_on_dfl)
5413 cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
5414 else if (!ss->dfl_cftypes)
5415 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
5418 cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
5420 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5421 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5423 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5424 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5428 ss->bind(init_css_set.subsys[ssid]);
5430 mutex_lock(&cgroup_mutex);
5431 css_populate_dir(init_css_set.subsys[ssid]);
5432 mutex_unlock(&cgroup_mutex);
5435 /* init_css_set.subsys[] has been updated, re-hash */
5436 hash_del(&init_css_set.hlist);
5437 hash_add(css_set_table, &init_css_set.hlist,
5438 css_set_hash(init_css_set.subsys));
5440 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
5441 WARN_ON(register_filesystem(&cgroup_fs_type));
5442 WARN_ON(register_filesystem(&cgroup2_fs_type));
5443 WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show));
5448 static int __init cgroup_wq_init(void)
5451 * There isn't much point in executing destruction path in
5452 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5453 * Use 1 for @max_active.
5455 * We would prefer to do this in cgroup_init() above, but that
5456 * is called before init_workqueues(): so leave this until after.
5458 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5459 BUG_ON(!cgroup_destroy_wq);
5462 core_initcall(cgroup_wq_init);
5464 void cgroup_path_from_kernfs_id(const union kernfs_node_id *id,
5465 char *buf, size_t buflen)
5467 struct kernfs_node *kn;
5469 kn = kernfs_get_node_by_id(cgrp_dfl_root.kf_root, id);
5472 kernfs_path(kn, buf, buflen);
5477 * proc_cgroup_show()
5478 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5479 * - Used for /proc/<pid>/cgroup.
5481 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5482 struct pid *pid, struct task_struct *tsk)
5486 struct cgroup_root *root;
5489 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5493 mutex_lock(&cgroup_mutex);
5494 spin_lock_irq(&css_set_lock);
5496 for_each_root(root) {
5497 struct cgroup_subsys *ss;
5498 struct cgroup *cgrp;
5499 int ssid, count = 0;
5501 if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
5504 seq_printf(m, "%d:", root->hierarchy_id);
5505 if (root != &cgrp_dfl_root)
5506 for_each_subsys(ss, ssid)
5507 if (root->subsys_mask & (1 << ssid))
5508 seq_printf(m, "%s%s", count++ ? "," : "",
5510 if (strlen(root->name))
5511 seq_printf(m, "%sname=%s", count ? "," : "",
5515 cgrp = task_cgroup_from_root(tsk, root);
5518 * On traditional hierarchies, all zombie tasks show up as
5519 * belonging to the root cgroup. On the default hierarchy,
5520 * while a zombie doesn't show up in "cgroup.procs" and
5521 * thus can't be migrated, its /proc/PID/cgroup keeps
5522 * reporting the cgroup it belonged to before exiting. If
5523 * the cgroup is removed before the zombie is reaped,
5524 * " (deleted)" is appended to the cgroup path.
5526 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
5527 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
5528 current->nsproxy->cgroup_ns);
5529 if (retval >= PATH_MAX)
5530 retval = -ENAMETOOLONG;
5539 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
5540 seq_puts(m, " (deleted)\n");
5547 spin_unlock_irq(&css_set_lock);
5548 mutex_unlock(&cgroup_mutex);
5555 * cgroup_fork - initialize cgroup related fields during copy_process()
5556 * @child: pointer to task_struct of forking parent process.
5558 * A task is associated with the init_css_set until cgroup_post_fork()
5559 * attaches it to the parent's css_set. Empty cg_list indicates that
5560 * @child isn't holding reference to its css_set.
5562 void cgroup_fork(struct task_struct *child)
5564 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5565 INIT_LIST_HEAD(&child->cg_list);
5569 * cgroup_can_fork - called on a new task before the process is exposed
5570 * @child: the task in question.
5572 * This calls the subsystem can_fork() callbacks. If the can_fork() callback
5573 * returns an error, the fork aborts with that error code. This allows for
5574 * a cgroup subsystem to conditionally allow or deny new forks.
5576 int cgroup_can_fork(struct task_struct *child)
5578 struct cgroup_subsys *ss;
5581 do_each_subsys_mask(ss, i, have_canfork_callback) {
5582 ret = ss->can_fork(child);
5585 } while_each_subsys_mask();
5590 for_each_subsys(ss, j) {
5593 if (ss->cancel_fork)
5594 ss->cancel_fork(child);
5601 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
5602 * @child: the task in question
5604 * This calls the cancel_fork() callbacks if a fork failed *after*
5605 * cgroup_can_fork() succeded.
5607 void cgroup_cancel_fork(struct task_struct *child)
5609 struct cgroup_subsys *ss;
5612 for_each_subsys(ss, i)
5613 if (ss->cancel_fork)
5614 ss->cancel_fork(child);
5618 * cgroup_post_fork - called on a new task after adding it to the task list
5619 * @child: the task in question
5621 * Adds the task to the list running through its css_set if necessary and
5622 * call the subsystem fork() callbacks. Has to be after the task is
5623 * visible on the task list in case we race with the first call to
5624 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5627 void cgroup_post_fork(struct task_struct *child)
5629 struct cgroup_subsys *ss;
5633 * This may race against cgroup_enable_task_cg_lists(). As that
5634 * function sets use_task_css_set_links before grabbing
5635 * tasklist_lock and we just went through tasklist_lock to add
5636 * @child, it's guaranteed that either we see the set
5637 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5638 * @child during its iteration.
5640 * If we won the race, @child is associated with %current's
5641 * css_set. Grabbing css_set_lock guarantees both that the
5642 * association is stable, and, on completion of the parent's
5643 * migration, @child is visible in the source of migration or
5644 * already in the destination cgroup. This guarantee is necessary
5645 * when implementing operations which need to migrate all tasks of
5646 * a cgroup to another.
5648 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5649 * will remain in init_css_set. This is safe because all tasks are
5650 * in the init_css_set before cg_links is enabled and there's no
5651 * operation which transfers all tasks out of init_css_set.
5653 if (use_task_css_set_links) {
5654 struct css_set *cset;
5656 spin_lock_irq(&css_set_lock);
5657 cset = task_css_set(current);
5658 if (list_empty(&child->cg_list)) {
5661 css_set_move_task(child, NULL, cset, false);
5663 spin_unlock_irq(&css_set_lock);
5667 * Call ss->fork(). This must happen after @child is linked on
5668 * css_set; otherwise, @child might change state between ->fork()
5669 * and addition to css_set.
5671 do_each_subsys_mask(ss, i, have_fork_callback) {
5673 } while_each_subsys_mask();
5677 * cgroup_exit - detach cgroup from exiting task
5678 * @tsk: pointer to task_struct of exiting process
5680 * Description: Detach cgroup from @tsk and release it.
5682 * Note that cgroups marked notify_on_release force every task in
5683 * them to take the global cgroup_mutex mutex when exiting.
5684 * This could impact scaling on very large systems. Be reluctant to
5685 * use notify_on_release cgroups where very high task exit scaling
5686 * is required on large systems.
5688 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5689 * call cgroup_exit() while the task is still competent to handle
5690 * notify_on_release(), then leave the task attached to the root cgroup in
5691 * each hierarchy for the remainder of its exit. No need to bother with
5692 * init_css_set refcnting. init_css_set never goes away and we can't race
5693 * with migration path - PF_EXITING is visible to migration path.
5695 void cgroup_exit(struct task_struct *tsk)
5697 struct cgroup_subsys *ss;
5698 struct css_set *cset;
5702 * Unlink from @tsk from its css_set. As migration path can't race
5703 * with us, we can check css_set and cg_list without synchronization.
5705 cset = task_css_set(tsk);
5707 if (!list_empty(&tsk->cg_list)) {
5708 spin_lock_irq(&css_set_lock);
5709 css_set_move_task(tsk, cset, NULL, false);
5711 spin_unlock_irq(&css_set_lock);
5716 /* see cgroup_post_fork() for details */
5717 do_each_subsys_mask(ss, i, have_exit_callback) {
5719 } while_each_subsys_mask();
5722 void cgroup_free(struct task_struct *task)
5724 struct css_set *cset = task_css_set(task);
5725 struct cgroup_subsys *ss;
5728 do_each_subsys_mask(ss, ssid, have_free_callback) {
5730 } while_each_subsys_mask();
5735 static int __init cgroup_disable(char *str)
5737 struct cgroup_subsys *ss;
5741 while ((token = strsep(&str, ",")) != NULL) {
5745 for_each_subsys(ss, i) {
5746 if (strcmp(token, ss->name) &&
5747 strcmp(token, ss->legacy_name))
5749 cgroup_disable_mask |= 1 << i;
5754 __setup("cgroup_disable=", cgroup_disable);
5756 void __init __weak enable_debug_cgroup(void) { }
5758 static int __init enable_cgroup_debug(char *str)
5760 cgroup_debug = true;
5761 enable_debug_cgroup();
5764 __setup("cgroup_debug", enable_cgroup_debug);
5767 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5768 * @dentry: directory dentry of interest
5769 * @ss: subsystem of interest
5771 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5772 * to get the corresponding css and return it. If such css doesn't exist
5773 * or can't be pinned, an ERR_PTR value is returned.
5775 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5776 struct cgroup_subsys *ss)
5778 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5779 struct file_system_type *s_type = dentry->d_sb->s_type;
5780 struct cgroup_subsys_state *css = NULL;
5781 struct cgroup *cgrp;
5783 /* is @dentry a cgroup dir? */
5784 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
5785 !kn || kernfs_type(kn) != KERNFS_DIR)
5786 return ERR_PTR(-EBADF);
5791 * This path doesn't originate from kernfs and @kn could already
5792 * have been or be removed at any point. @kn->priv is RCU
5793 * protected for this access. See css_release_work_fn() for details.
5795 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
5797 css = cgroup_css(cgrp, ss);
5799 if (!css || !css_tryget_online(css))
5800 css = ERR_PTR(-ENOENT);
5807 * css_from_id - lookup css by id
5808 * @id: the cgroup id
5809 * @ss: cgroup subsys to be looked into
5811 * Returns the css if there's valid one with @id, otherwise returns NULL.
5812 * Should be called under rcu_read_lock().
5814 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5816 WARN_ON_ONCE(!rcu_read_lock_held());
5817 return idr_find(&ss->css_idr, id);
5821 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
5822 * @path: path on the default hierarchy
5824 * Find the cgroup at @path on the default hierarchy, increment its
5825 * reference count and return it. Returns pointer to the found cgroup on
5826 * success, ERR_PTR(-ENOENT) if @path doens't exist and ERR_PTR(-ENOTDIR)
5827 * if @path points to a non-directory.
5829 struct cgroup *cgroup_get_from_path(const char *path)
5831 struct kernfs_node *kn;
5832 struct cgroup *cgrp;
5834 mutex_lock(&cgroup_mutex);
5836 kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
5838 if (kernfs_type(kn) == KERNFS_DIR) {
5840 cgroup_get_live(cgrp);
5842 cgrp = ERR_PTR(-ENOTDIR);
5846 cgrp = ERR_PTR(-ENOENT);
5849 mutex_unlock(&cgroup_mutex);
5852 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
5855 * cgroup_get_from_fd - get a cgroup pointer from a fd
5856 * @fd: fd obtained by open(cgroup2_dir)
5858 * Find the cgroup from a fd which should be obtained
5859 * by opening a cgroup directory. Returns a pointer to the
5860 * cgroup on success. ERR_PTR is returned if the cgroup
5863 struct cgroup *cgroup_get_from_fd(int fd)
5865 struct cgroup_subsys_state *css;
5866 struct cgroup *cgrp;
5871 return ERR_PTR(-EBADF);
5873 css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
5876 return ERR_CAST(css);
5879 if (!cgroup_on_dfl(cgrp)) {
5881 return ERR_PTR(-EBADF);
5886 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
5889 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
5890 * definition in cgroup-defs.h.
5892 #ifdef CONFIG_SOCK_CGROUP_DATA
5894 #if defined(CONFIG_CGROUP_NET_PRIO) || defined(CONFIG_CGROUP_NET_CLASSID)
5896 DEFINE_SPINLOCK(cgroup_sk_update_lock);
5897 static bool cgroup_sk_alloc_disabled __read_mostly;
5899 void cgroup_sk_alloc_disable(void)
5901 if (cgroup_sk_alloc_disabled)
5903 pr_info("cgroup: disabling cgroup2 socket matching due to net_prio or net_cls activation\n");
5904 cgroup_sk_alloc_disabled = true;
5909 #define cgroup_sk_alloc_disabled false
5913 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
5915 if (cgroup_sk_alloc_disabled)
5918 /* Socket clone path */
5921 * We might be cloning a socket which is left in an empty
5922 * cgroup and the cgroup might have already been rmdir'd.
5923 * Don't use cgroup_get_live().
5925 cgroup_get(sock_cgroup_ptr(skcd));
5932 struct css_set *cset;
5934 cset = task_css_set(current);
5935 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
5936 skcd->val = (unsigned long)cset->dfl_cgrp;
5945 void cgroup_sk_free(struct sock_cgroup_data *skcd)
5947 cgroup_put(sock_cgroup_ptr(skcd));
5950 #endif /* CONFIG_SOCK_CGROUP_DATA */
5952 #ifdef CONFIG_CGROUP_BPF
5953 int cgroup_bpf_attach(struct cgroup *cgrp, struct bpf_prog *prog,
5954 enum bpf_attach_type type, u32 flags)
5958 mutex_lock(&cgroup_mutex);
5959 ret = __cgroup_bpf_attach(cgrp, prog, type, flags);
5960 mutex_unlock(&cgroup_mutex);
5963 int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
5964 enum bpf_attach_type type, u32 flags)
5968 mutex_lock(&cgroup_mutex);
5969 ret = __cgroup_bpf_detach(cgrp, prog, type, flags);
5970 mutex_unlock(&cgroup_mutex);
5973 int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
5974 union bpf_attr __user *uattr)
5978 mutex_lock(&cgroup_mutex);
5979 ret = __cgroup_bpf_query(cgrp, attr, uattr);
5980 mutex_unlock(&cgroup_mutex);
5983 #endif /* CONFIG_CGROUP_BPF */
5986 static ssize_t show_delegatable_files(struct cftype *files, char *buf,
5987 ssize_t size, const char *prefix)
5992 for (cft = files; cft && cft->name[0] != '\0'; cft++) {
5993 if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
5997 ret += snprintf(buf + ret, size - ret, "%s.", prefix);
5999 ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
6001 if (WARN_ON(ret >= size))
6008 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
6011 struct cgroup_subsys *ss;
6015 ret = show_delegatable_files(cgroup_base_files, buf, PAGE_SIZE - ret,
6018 for_each_subsys(ss, ssid)
6019 ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
6021 cgroup_subsys_name[ssid]);
6025 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
6027 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
6030 return snprintf(buf, PAGE_SIZE, "nsdelegate\n");
6032 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
6034 static struct attribute *cgroup_sysfs_attrs[] = {
6035 &cgroup_delegate_attr.attr,
6036 &cgroup_features_attr.attr,
6040 static const struct attribute_group cgroup_sysfs_attr_group = {
6041 .attrs = cgroup_sysfs_attrs,
6045 static int __init cgroup_sysfs_init(void)
6047 return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
6049 subsys_initcall(cgroup_sysfs_init);
6050 #endif /* CONFIG_SYSFS */