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/cpu.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];
91 * Protects cgroup_idr and css_idr so that IDs can be released without
92 * grabbing cgroup_mutex.
94 static DEFINE_SPINLOCK(cgroup_idr_lock);
97 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
98 * against file removal/re-creation across css hiding.
100 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
102 struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
104 #define cgroup_assert_mutex_or_rcu_locked() \
105 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
106 !lockdep_is_held(&cgroup_mutex), \
107 "cgroup_mutex or RCU read lock required");
110 * cgroup destruction makes heavy use of work items and there can be a lot
111 * of concurrent destructions. Use a separate workqueue so that cgroup
112 * destruction work items don't end up filling up max_active of system_wq
113 * which may lead to deadlock.
115 static struct workqueue_struct *cgroup_destroy_wq;
117 /* generate an array of cgroup subsystem pointers */
118 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
119 struct cgroup_subsys *cgroup_subsys[] = {
120 #include <linux/cgroup_subsys.h>
124 /* array of cgroup subsystem names */
125 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
126 static const char *cgroup_subsys_name[] = {
127 #include <linux/cgroup_subsys.h>
131 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
133 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
134 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
135 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
136 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
137 #include <linux/cgroup_subsys.h>
140 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
141 static struct static_key_true *cgroup_subsys_enabled_key[] = {
142 #include <linux/cgroup_subsys.h>
146 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
147 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
148 #include <linux/cgroup_subsys.h>
152 static DEFINE_PER_CPU(struct cgroup_rstat_cpu, cgrp_dfl_root_rstat_cpu);
155 * The default hierarchy, reserved for the subsystems that are otherwise
156 * unattached - it never has more than a single cgroup, and all tasks are
157 * part of that cgroup.
159 struct cgroup_root cgrp_dfl_root = { .cgrp.rstat_cpu = &cgrp_dfl_root_rstat_cpu };
160 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
163 * The default hierarchy always exists but is hidden until mounted for the
164 * first time. This is for backward compatibility.
166 static bool cgrp_dfl_visible;
168 /* some controllers are not supported in the default hierarchy */
169 static u16 cgrp_dfl_inhibit_ss_mask;
171 /* some controllers are implicitly enabled on the default hierarchy */
172 static u16 cgrp_dfl_implicit_ss_mask;
174 /* some controllers can be threaded on the default hierarchy */
175 static u16 cgrp_dfl_threaded_ss_mask;
177 /* The list of hierarchy roots */
178 LIST_HEAD(cgroup_roots);
179 static int cgroup_root_count;
181 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
182 static DEFINE_IDR(cgroup_hierarchy_idr);
185 * Assign a monotonically increasing serial number to csses. It guarantees
186 * cgroups with bigger numbers are newer than those with smaller numbers.
187 * Also, as csses are always appended to the parent's ->children list, it
188 * guarantees that sibling csses are always sorted in the ascending serial
189 * number order on the list. Protected by cgroup_mutex.
191 static u64 css_serial_nr_next = 1;
194 * These bitmasks identify subsystems with specific features to avoid
195 * having to do iterative checks repeatedly.
197 static u16 have_fork_callback __read_mostly;
198 static u16 have_exit_callback __read_mostly;
199 static u16 have_release_callback __read_mostly;
200 static u16 have_canfork_callback __read_mostly;
202 /* cgroup namespace for init task */
203 struct cgroup_namespace init_cgroup_ns = {
204 .count = REFCOUNT_INIT(2),
205 .user_ns = &init_user_ns,
206 .ns.ops = &cgroupns_operations,
207 .ns.inum = PROC_CGROUP_INIT_INO,
208 .root_cset = &init_css_set,
211 static struct file_system_type cgroup2_fs_type;
212 static struct cftype cgroup_base_files[];
214 static int cgroup_apply_control(struct cgroup *cgrp);
215 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
216 static void css_task_iter_skip(struct css_task_iter *it,
217 struct task_struct *task);
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 .dying_tasks = LIST_HEAD_INIT(init_css_set.dying_tasks),
678 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
679 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
680 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
681 .mg_src_preload_node = LIST_HEAD_INIT(init_css_set.mg_src_preload_node),
682 .mg_dst_preload_node = LIST_HEAD_INIT(init_css_set.mg_dst_preload_node),
683 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
686 * The following field is re-initialized when this cset gets linked
687 * in cgroup_init(). However, let's initialize the field
688 * statically too so that the default cgroup can be accessed safely
691 .dfl_cgrp = &cgrp_dfl_root.cgrp,
694 static int css_set_count = 1; /* 1 for init_css_set */
696 static bool css_set_threaded(struct css_set *cset)
698 return cset->dom_cset != cset;
702 * css_set_populated - does a css_set contain any tasks?
703 * @cset: target css_set
705 * css_set_populated() should be the same as !!cset->nr_tasks at steady
706 * state. However, css_set_populated() can be called while a task is being
707 * added to or removed from the linked list before the nr_tasks is
708 * properly updated. Hence, we can't just look at ->nr_tasks here.
710 static bool css_set_populated(struct css_set *cset)
712 lockdep_assert_held(&css_set_lock);
714 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
718 * cgroup_update_populated - update the populated count of a cgroup
719 * @cgrp: the target cgroup
720 * @populated: inc or dec populated count
722 * One of the css_sets associated with @cgrp is either getting its first
723 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
724 * count is propagated towards root so that a given cgroup's
725 * nr_populated_children is zero iff none of its descendants contain any
728 * @cgrp's interface file "cgroup.populated" is zero if both
729 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
730 * 1 otherwise. When the sum changes from or to zero, userland is notified
731 * that the content of the interface file has changed. This can be used to
732 * detect when @cgrp and its descendants become populated or empty.
734 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
736 struct cgroup *child = NULL;
737 int adj = populated ? 1 : -1;
739 lockdep_assert_held(&css_set_lock);
742 bool was_populated = cgroup_is_populated(cgrp);
745 cgrp->nr_populated_csets += adj;
747 if (cgroup_is_threaded(child))
748 cgrp->nr_populated_threaded_children += adj;
750 cgrp->nr_populated_domain_children += adj;
753 if (was_populated == cgroup_is_populated(cgrp))
756 cgroup1_check_for_release(cgrp);
757 cgroup_file_notify(&cgrp->events_file);
760 cgrp = cgroup_parent(cgrp);
765 * css_set_update_populated - update populated state of a css_set
766 * @cset: target css_set
767 * @populated: whether @cset is populated or depopulated
769 * @cset is either getting the first task or losing the last. Update the
770 * populated counters of all associated cgroups accordingly.
772 static void css_set_update_populated(struct css_set *cset, bool populated)
774 struct cgrp_cset_link *link;
776 lockdep_assert_held(&css_set_lock);
778 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
779 cgroup_update_populated(link->cgrp, populated);
783 * @task is leaving, advance task iterators which are pointing to it so
784 * that they can resume at the next position. Advancing an iterator might
785 * remove it from the list, use safe walk. See css_task_iter_skip() for
788 static void css_set_skip_task_iters(struct css_set *cset,
789 struct task_struct *task)
791 struct css_task_iter *it, *pos;
793 list_for_each_entry_safe(it, pos, &cset->task_iters, iters_node)
794 css_task_iter_skip(it, task);
798 * css_set_move_task - move a task from one css_set to another
799 * @task: task being moved
800 * @from_cset: css_set @task currently belongs to (may be NULL)
801 * @to_cset: new css_set @task is being moved to (may be NULL)
802 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
804 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
805 * css_set, @from_cset can be NULL. If @task is being disassociated
806 * instead of moved, @to_cset can be NULL.
808 * This function automatically handles populated counter updates and
809 * css_task_iter adjustments but the caller is responsible for managing
810 * @from_cset and @to_cset's reference counts.
812 static void css_set_move_task(struct task_struct *task,
813 struct css_set *from_cset, struct css_set *to_cset,
816 lockdep_assert_held(&css_set_lock);
818 if (to_cset && !css_set_populated(to_cset))
819 css_set_update_populated(to_cset, true);
822 WARN_ON_ONCE(list_empty(&task->cg_list));
824 css_set_skip_task_iters(from_cset, task);
825 list_del_init(&task->cg_list);
826 if (!css_set_populated(from_cset))
827 css_set_update_populated(from_cset, false);
829 WARN_ON_ONCE(!list_empty(&task->cg_list));
834 * We are synchronized through cgroup_threadgroup_rwsem
835 * against PF_EXITING setting such that we can't race
836 * against cgroup_exit() changing the css_set to
837 * init_css_set and dropping the old one.
839 WARN_ON_ONCE(task->flags & PF_EXITING);
841 rcu_assign_pointer(task->cgroups, to_cset);
842 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
848 * hash table for cgroup groups. This improves the performance to find
849 * an existing css_set. This hash doesn't (currently) take into
850 * account cgroups in empty hierarchies.
852 #define CSS_SET_HASH_BITS 7
853 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
855 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
857 unsigned long key = 0UL;
858 struct cgroup_subsys *ss;
861 for_each_subsys(ss, i)
862 key += (unsigned long)css[i];
863 key = (key >> 16) ^ key;
868 void put_css_set_locked(struct css_set *cset)
870 struct cgrp_cset_link *link, *tmp_link;
871 struct cgroup_subsys *ss;
874 lockdep_assert_held(&css_set_lock);
876 if (!refcount_dec_and_test(&cset->refcount))
879 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
881 /* This css_set is dead. unlink it and release cgroup and css refs */
882 for_each_subsys(ss, ssid) {
883 list_del(&cset->e_cset_node[ssid]);
884 css_put(cset->subsys[ssid]);
886 hash_del(&cset->hlist);
889 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
890 list_del(&link->cset_link);
891 list_del(&link->cgrp_link);
892 if (cgroup_parent(link->cgrp))
893 cgroup_put(link->cgrp);
897 if (css_set_threaded(cset)) {
898 list_del(&cset->threaded_csets_node);
899 put_css_set_locked(cset->dom_cset);
902 kfree_rcu(cset, rcu_head);
906 * compare_css_sets - helper function for find_existing_css_set().
907 * @cset: candidate css_set being tested
908 * @old_cset: existing css_set for a task
909 * @new_cgrp: cgroup that's being entered by the task
910 * @template: desired set of css pointers in css_set (pre-calculated)
912 * Returns true if "cset" matches "old_cset" except for the hierarchy
913 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
915 static bool compare_css_sets(struct css_set *cset,
916 struct css_set *old_cset,
917 struct cgroup *new_cgrp,
918 struct cgroup_subsys_state *template[])
920 struct cgroup *new_dfl_cgrp;
921 struct list_head *l1, *l2;
924 * On the default hierarchy, there can be csets which are
925 * associated with the same set of cgroups but different csses.
926 * Let's first ensure that csses match.
928 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
932 /* @cset's domain should match the default cgroup's */
933 if (cgroup_on_dfl(new_cgrp))
934 new_dfl_cgrp = new_cgrp;
936 new_dfl_cgrp = old_cset->dfl_cgrp;
938 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
942 * Compare cgroup pointers in order to distinguish between
943 * different cgroups in hierarchies. As different cgroups may
944 * share the same effective css, this comparison is always
947 l1 = &cset->cgrp_links;
948 l2 = &old_cset->cgrp_links;
950 struct cgrp_cset_link *link1, *link2;
951 struct cgroup *cgrp1, *cgrp2;
955 /* See if we reached the end - both lists are equal length. */
956 if (l1 == &cset->cgrp_links) {
957 BUG_ON(l2 != &old_cset->cgrp_links);
960 BUG_ON(l2 == &old_cset->cgrp_links);
962 /* Locate the cgroups associated with these links. */
963 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
964 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
967 /* Hierarchies should be linked in the same order. */
968 BUG_ON(cgrp1->root != cgrp2->root);
971 * If this hierarchy is the hierarchy of the cgroup
972 * that's changing, then we need to check that this
973 * css_set points to the new cgroup; if it's any other
974 * hierarchy, then this css_set should point to the
975 * same cgroup as the old css_set.
977 if (cgrp1->root == new_cgrp->root) {
978 if (cgrp1 != new_cgrp)
989 * find_existing_css_set - init css array and find the matching css_set
990 * @old_cset: the css_set that we're using before the cgroup transition
991 * @cgrp: the cgroup that we're moving into
992 * @template: out param for the new set of csses, should be clear on entry
994 static struct css_set *find_existing_css_set(struct css_set *old_cset,
996 struct cgroup_subsys_state *template[])
998 struct cgroup_root *root = cgrp->root;
999 struct cgroup_subsys *ss;
1000 struct css_set *cset;
1005 * Build the set of subsystem state objects that we want to see in the
1006 * new css_set. while subsystems can change globally, the entries here
1007 * won't change, so no need for locking.
1009 for_each_subsys(ss, i) {
1010 if (root->subsys_mask & (1UL << i)) {
1012 * @ss is in this hierarchy, so we want the
1013 * effective css from @cgrp.
1015 template[i] = cgroup_e_css(cgrp, ss);
1018 * @ss is not in this hierarchy, so we don't want
1019 * to change the css.
1021 template[i] = old_cset->subsys[i];
1025 key = css_set_hash(template);
1026 hash_for_each_possible(css_set_table, cset, hlist, key) {
1027 if (!compare_css_sets(cset, old_cset, cgrp, template))
1030 /* This css_set matches what we need */
1034 /* No existing cgroup group matched */
1038 static void free_cgrp_cset_links(struct list_head *links_to_free)
1040 struct cgrp_cset_link *link, *tmp_link;
1042 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1043 list_del(&link->cset_link);
1049 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1050 * @count: the number of links to allocate
1051 * @tmp_links: list_head the allocated links are put on
1053 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1054 * through ->cset_link. Returns 0 on success or -errno.
1056 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1058 struct cgrp_cset_link *link;
1061 INIT_LIST_HEAD(tmp_links);
1063 for (i = 0; i < count; i++) {
1064 link = kzalloc(sizeof(*link), GFP_KERNEL);
1066 free_cgrp_cset_links(tmp_links);
1069 list_add(&link->cset_link, tmp_links);
1075 * link_css_set - a helper function to link a css_set to a cgroup
1076 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1077 * @cset: the css_set to be linked
1078 * @cgrp: the destination cgroup
1080 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1081 struct cgroup *cgrp)
1083 struct cgrp_cset_link *link;
1085 BUG_ON(list_empty(tmp_links));
1087 if (cgroup_on_dfl(cgrp))
1088 cset->dfl_cgrp = cgrp;
1090 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1095 * Always add links to the tail of the lists so that the lists are
1096 * in choronological order.
1098 list_move_tail(&link->cset_link, &cgrp->cset_links);
1099 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1101 if (cgroup_parent(cgrp))
1102 cgroup_get_live(cgrp);
1106 * find_css_set - return a new css_set with one cgroup updated
1107 * @old_cset: the baseline css_set
1108 * @cgrp: the cgroup to be updated
1110 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1111 * substituted into the appropriate hierarchy.
1113 static struct css_set *find_css_set(struct css_set *old_cset,
1114 struct cgroup *cgrp)
1116 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1117 struct css_set *cset;
1118 struct list_head tmp_links;
1119 struct cgrp_cset_link *link;
1120 struct cgroup_subsys *ss;
1124 lockdep_assert_held(&cgroup_mutex);
1126 /* First see if we already have a cgroup group that matches
1127 * the desired set */
1128 spin_lock_irq(&css_set_lock);
1129 cset = find_existing_css_set(old_cset, cgrp, template);
1132 spin_unlock_irq(&css_set_lock);
1137 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1141 /* Allocate all the cgrp_cset_link objects that we'll need */
1142 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1147 refcount_set(&cset->refcount, 1);
1148 cset->dom_cset = cset;
1149 INIT_LIST_HEAD(&cset->tasks);
1150 INIT_LIST_HEAD(&cset->mg_tasks);
1151 INIT_LIST_HEAD(&cset->dying_tasks);
1152 INIT_LIST_HEAD(&cset->task_iters);
1153 INIT_LIST_HEAD(&cset->threaded_csets);
1154 INIT_HLIST_NODE(&cset->hlist);
1155 INIT_LIST_HEAD(&cset->cgrp_links);
1156 INIT_LIST_HEAD(&cset->mg_src_preload_node);
1157 INIT_LIST_HEAD(&cset->mg_dst_preload_node);
1158 INIT_LIST_HEAD(&cset->mg_node);
1160 /* Copy the set of subsystem state objects generated in
1161 * find_existing_css_set() */
1162 memcpy(cset->subsys, template, sizeof(cset->subsys));
1164 spin_lock_irq(&css_set_lock);
1165 /* Add reference counts and links from the new css_set. */
1166 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1167 struct cgroup *c = link->cgrp;
1169 if (c->root == cgrp->root)
1171 link_css_set(&tmp_links, cset, c);
1174 BUG_ON(!list_empty(&tmp_links));
1178 /* Add @cset to the hash table */
1179 key = css_set_hash(cset->subsys);
1180 hash_add(css_set_table, &cset->hlist, key);
1182 for_each_subsys(ss, ssid) {
1183 struct cgroup_subsys_state *css = cset->subsys[ssid];
1185 list_add_tail(&cset->e_cset_node[ssid],
1186 &css->cgroup->e_csets[ssid]);
1190 spin_unlock_irq(&css_set_lock);
1193 * If @cset should be threaded, look up the matching dom_cset and
1194 * link them up. We first fully initialize @cset then look for the
1195 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1196 * to stay empty until we return.
1198 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1199 struct css_set *dcset;
1201 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1207 spin_lock_irq(&css_set_lock);
1208 cset->dom_cset = dcset;
1209 list_add_tail(&cset->threaded_csets_node,
1210 &dcset->threaded_csets);
1211 spin_unlock_irq(&css_set_lock);
1217 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1219 struct cgroup *root_cgrp = kf_root->kn->priv;
1221 return root_cgrp->root;
1224 static int cgroup_init_root_id(struct cgroup_root *root)
1228 lockdep_assert_held(&cgroup_mutex);
1230 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1234 root->hierarchy_id = id;
1238 static void cgroup_exit_root_id(struct cgroup_root *root)
1240 lockdep_assert_held(&cgroup_mutex);
1242 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1245 void cgroup_free_root(struct cgroup_root *root)
1248 idr_destroy(&root->cgroup_idr);
1253 static void cgroup_destroy_root(struct cgroup_root *root)
1255 struct cgroup *cgrp = &root->cgrp;
1256 struct cgrp_cset_link *link, *tmp_link;
1258 trace_cgroup_destroy_root(root);
1260 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1262 BUG_ON(atomic_read(&root->nr_cgrps));
1263 BUG_ON(!list_empty(&cgrp->self.children));
1265 /* Rebind all subsystems back to the default hierarchy */
1266 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1269 * Release all the links from cset_links to this hierarchy's
1272 spin_lock_irq(&css_set_lock);
1274 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1275 list_del(&link->cset_link);
1276 list_del(&link->cgrp_link);
1280 spin_unlock_irq(&css_set_lock);
1282 if (!list_empty(&root->root_list)) {
1283 list_del(&root->root_list);
1284 cgroup_root_count--;
1287 cgroup_exit_root_id(root);
1289 mutex_unlock(&cgroup_mutex);
1291 kernfs_destroy_root(root->kf_root);
1292 cgroup_free_root(root);
1296 * look up cgroup associated with current task's cgroup namespace on the
1297 * specified hierarchy
1299 static struct cgroup *
1300 current_cgns_cgroup_from_root(struct cgroup_root *root)
1302 struct cgroup *res = NULL;
1303 struct css_set *cset;
1305 lockdep_assert_held(&css_set_lock);
1309 cset = current->nsproxy->cgroup_ns->root_cset;
1310 if (cset == &init_css_set) {
1313 struct cgrp_cset_link *link;
1315 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1316 struct cgroup *c = link->cgrp;
1318 if (c->root == root) {
1330 /* look up cgroup associated with given css_set on the specified hierarchy */
1331 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1332 struct cgroup_root *root)
1334 struct cgroup *res = NULL;
1336 lockdep_assert_held(&cgroup_mutex);
1337 lockdep_assert_held(&css_set_lock);
1339 if (cset == &init_css_set) {
1341 } else if (root == &cgrp_dfl_root) {
1342 res = cset->dfl_cgrp;
1344 struct cgrp_cset_link *link;
1346 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1347 struct cgroup *c = link->cgrp;
1349 if (c->root == root) {
1361 * Return the cgroup for "task" from the given hierarchy. Must be
1362 * called with cgroup_mutex and css_set_lock held.
1364 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1365 struct cgroup_root *root)
1368 * No need to lock the task - since we hold cgroup_mutex the
1369 * task can't change groups, so the only thing that can happen
1370 * is that it exits and its css is set back to init_css_set.
1372 return cset_cgroup_from_root(task_css_set(task), root);
1376 * A task must hold cgroup_mutex to modify cgroups.
1378 * Any task can increment and decrement the count field without lock.
1379 * So in general, code holding cgroup_mutex can't rely on the count
1380 * field not changing. However, if the count goes to zero, then only
1381 * cgroup_attach_task() can increment it again. Because a count of zero
1382 * means that no tasks are currently attached, therefore there is no
1383 * way a task attached to that cgroup can fork (the other way to
1384 * increment the count). So code holding cgroup_mutex can safely
1385 * assume that if the count is zero, it will stay zero. Similarly, if
1386 * a task holds cgroup_mutex on a cgroup with zero count, it
1387 * knows that the cgroup won't be removed, as cgroup_rmdir()
1390 * A cgroup can only be deleted if both its 'count' of using tasks
1391 * is zero, and its list of 'children' cgroups is empty. Since all
1392 * tasks in the system use _some_ cgroup, and since there is always at
1393 * least one task in the system (init, pid == 1), therefore, root cgroup
1394 * always has either children cgroups and/or using tasks. So we don't
1395 * need a special hack to ensure that root cgroup cannot be deleted.
1397 * P.S. One more locking exception. RCU is used to guard the
1398 * update of a tasks cgroup pointer by cgroup_attach_task()
1401 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1403 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1406 struct cgroup_subsys *ss = cft->ss;
1408 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1409 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1410 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1411 cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1414 strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1419 * cgroup_file_mode - deduce file mode of a control file
1420 * @cft: the control file in question
1422 * S_IRUGO for read, S_IWUSR for write.
1424 static umode_t cgroup_file_mode(const struct cftype *cft)
1428 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1431 if (cft->write_u64 || cft->write_s64 || cft->write) {
1432 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1442 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1443 * @subtree_control: the new subtree_control mask to consider
1444 * @this_ss_mask: available subsystems
1446 * On the default hierarchy, a subsystem may request other subsystems to be
1447 * enabled together through its ->depends_on mask. In such cases, more
1448 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1450 * This function calculates which subsystems need to be enabled if
1451 * @subtree_control is to be applied while restricted to @this_ss_mask.
1453 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1455 u16 cur_ss_mask = subtree_control;
1456 struct cgroup_subsys *ss;
1459 lockdep_assert_held(&cgroup_mutex);
1461 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1464 u16 new_ss_mask = cur_ss_mask;
1466 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1467 new_ss_mask |= ss->depends_on;
1468 } while_each_subsys_mask();
1471 * Mask out subsystems which aren't available. This can
1472 * happen only if some depended-upon subsystems were bound
1473 * to non-default hierarchies.
1475 new_ss_mask &= this_ss_mask;
1477 if (new_ss_mask == cur_ss_mask)
1479 cur_ss_mask = new_ss_mask;
1486 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1487 * @kn: the kernfs_node being serviced
1489 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1490 * the method finishes if locking succeeded. Note that once this function
1491 * returns the cgroup returned by cgroup_kn_lock_live() may become
1492 * inaccessible any time. If the caller intends to continue to access the
1493 * cgroup, it should pin it before invoking this function.
1495 void cgroup_kn_unlock(struct kernfs_node *kn)
1497 struct cgroup *cgrp;
1499 if (kernfs_type(kn) == KERNFS_DIR)
1502 cgrp = kn->parent->priv;
1504 mutex_unlock(&cgroup_mutex);
1506 kernfs_unbreak_active_protection(kn);
1511 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1512 * @kn: the kernfs_node being serviced
1513 * @drain_offline: perform offline draining on the cgroup
1515 * This helper is to be used by a cgroup kernfs method currently servicing
1516 * @kn. It breaks the active protection, performs cgroup locking and
1517 * verifies that the associated cgroup is alive. Returns the cgroup if
1518 * alive; otherwise, %NULL. A successful return should be undone by a
1519 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1520 * cgroup is drained of offlining csses before return.
1522 * Any cgroup kernfs method implementation which requires locking the
1523 * associated cgroup should use this helper. It avoids nesting cgroup
1524 * locking under kernfs active protection and allows all kernfs operations
1525 * including self-removal.
1527 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1529 struct cgroup *cgrp;
1531 if (kernfs_type(kn) == KERNFS_DIR)
1534 cgrp = kn->parent->priv;
1537 * We're gonna grab cgroup_mutex which nests outside kernfs
1538 * active_ref. cgroup liveliness check alone provides enough
1539 * protection against removal. Ensure @cgrp stays accessible and
1540 * break the active_ref protection.
1542 if (!cgroup_tryget(cgrp))
1544 kernfs_break_active_protection(kn);
1547 cgroup_lock_and_drain_offline(cgrp);
1549 mutex_lock(&cgroup_mutex);
1551 if (!cgroup_is_dead(cgrp))
1554 cgroup_kn_unlock(kn);
1558 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1560 char name[CGROUP_FILE_NAME_MAX];
1562 lockdep_assert_held(&cgroup_mutex);
1564 if (cft->file_offset) {
1565 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1566 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1568 spin_lock_irq(&cgroup_file_kn_lock);
1570 spin_unlock_irq(&cgroup_file_kn_lock);
1572 del_timer_sync(&cfile->notify_timer);
1575 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1579 * css_clear_dir - remove subsys files in a cgroup directory
1582 static void css_clear_dir(struct cgroup_subsys_state *css)
1584 struct cgroup *cgrp = css->cgroup;
1585 struct cftype *cfts;
1587 if (!(css->flags & CSS_VISIBLE))
1590 css->flags &= ~CSS_VISIBLE;
1593 if (cgroup_on_dfl(cgrp))
1594 cfts = cgroup_base_files;
1596 cfts = cgroup1_base_files;
1598 cgroup_addrm_files(css, cgrp, cfts, false);
1600 list_for_each_entry(cfts, &css->ss->cfts, node)
1601 cgroup_addrm_files(css, cgrp, cfts, false);
1606 * css_populate_dir - create subsys files in a cgroup directory
1609 * On failure, no file is added.
1611 static int css_populate_dir(struct cgroup_subsys_state *css)
1613 struct cgroup *cgrp = css->cgroup;
1614 struct cftype *cfts, *failed_cfts;
1617 if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
1621 if (cgroup_on_dfl(cgrp))
1622 cfts = cgroup_base_files;
1624 cfts = cgroup1_base_files;
1626 ret = cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1630 list_for_each_entry(cfts, &css->ss->cfts, node) {
1631 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1639 css->flags |= CSS_VISIBLE;
1643 list_for_each_entry(cfts, &css->ss->cfts, node) {
1644 if (cfts == failed_cfts)
1646 cgroup_addrm_files(css, cgrp, cfts, false);
1651 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1653 struct cgroup *dcgrp = &dst_root->cgrp;
1654 struct cgroup_subsys *ss;
1656 u16 dfl_disable_ss_mask = 0;
1658 lockdep_assert_held(&cgroup_mutex);
1660 do_each_subsys_mask(ss, ssid, ss_mask) {
1662 * If @ss has non-root csses attached to it, can't move.
1663 * If @ss is an implicit controller, it is exempt from this
1664 * rule and can be stolen.
1666 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1667 !ss->implicit_on_dfl)
1670 /* can't move between two non-dummy roots either */
1671 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1675 * Collect ssid's that need to be disabled from default
1678 if (ss->root == &cgrp_dfl_root)
1679 dfl_disable_ss_mask |= 1 << ssid;
1681 } while_each_subsys_mask();
1683 if (dfl_disable_ss_mask) {
1684 struct cgroup *scgrp = &cgrp_dfl_root.cgrp;
1687 * Controllers from default hierarchy that need to be rebound
1688 * are all disabled together in one go.
1690 cgrp_dfl_root.subsys_mask &= ~dfl_disable_ss_mask;
1691 WARN_ON(cgroup_apply_control(scgrp));
1692 cgroup_finalize_control(scgrp, 0);
1695 do_each_subsys_mask(ss, ssid, ss_mask) {
1696 struct cgroup_root *src_root = ss->root;
1697 struct cgroup *scgrp = &src_root->cgrp;
1698 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1699 struct css_set *cset, *cset_pos;
1700 struct css_task_iter *it;
1702 WARN_ON(!css || cgroup_css(dcgrp, ss));
1704 if (src_root != &cgrp_dfl_root) {
1705 /* disable from the source */
1706 src_root->subsys_mask &= ~(1 << ssid);
1707 WARN_ON(cgroup_apply_control(scgrp));
1708 cgroup_finalize_control(scgrp, 0);
1712 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1713 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1714 ss->root = dst_root;
1715 css->cgroup = dcgrp;
1717 spin_lock_irq(&css_set_lock);
1718 WARN_ON(!list_empty(&dcgrp->e_csets[ss->id]));
1719 list_for_each_entry_safe(cset, cset_pos, &scgrp->e_csets[ss->id],
1720 e_cset_node[ss->id]) {
1721 list_move_tail(&cset->e_cset_node[ss->id],
1722 &dcgrp->e_csets[ss->id]);
1724 * all css_sets of scgrp together in same order to dcgrp,
1725 * patch in-flight iterators to preserve correct iteration.
1726 * since the iterator is always advanced right away and
1727 * finished when it->cset_pos meets it->cset_head, so only
1728 * update it->cset_head is enough here.
1730 list_for_each_entry(it, &cset->task_iters, iters_node)
1731 if (it->cset_head == &scgrp->e_csets[ss->id])
1732 it->cset_head = &dcgrp->e_csets[ss->id];
1734 spin_unlock_irq(&css_set_lock);
1736 /* default hierarchy doesn't enable controllers by default */
1737 dst_root->subsys_mask |= 1 << ssid;
1738 if (dst_root == &cgrp_dfl_root) {
1739 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1741 dcgrp->subtree_control |= 1 << ssid;
1742 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1745 ret = cgroup_apply_control(dcgrp);
1747 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1752 } while_each_subsys_mask();
1754 kernfs_activate(dcgrp->kn);
1758 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1759 struct kernfs_root *kf_root)
1763 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1764 struct cgroup *ns_cgroup;
1766 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1770 spin_lock_irq(&css_set_lock);
1771 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1772 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1773 spin_unlock_irq(&css_set_lock);
1775 if (len >= PATH_MAX)
1778 seq_escape(sf, buf, " \t\n\\");
1785 static int parse_cgroup_root_flags(char *data, unsigned int *root_flags)
1791 if (!data || *data == '\0')
1794 while ((token = strsep(&data, ",")) != NULL) {
1795 if (!strcmp(token, "nsdelegate")) {
1796 *root_flags |= CGRP_ROOT_NS_DELEGATE;
1800 pr_err("cgroup2: unknown option \"%s\"\n", token);
1807 static void apply_cgroup_root_flags(unsigned int root_flags)
1809 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1810 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1811 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1813 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1817 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1819 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1820 seq_puts(seq, ",nsdelegate");
1824 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1826 unsigned int root_flags;
1829 ret = parse_cgroup_root_flags(data, &root_flags);
1833 apply_cgroup_root_flags(root_flags);
1838 * To reduce the fork() overhead for systems that are not actually using
1839 * their cgroups capability, we don't maintain the lists running through
1840 * each css_set to its tasks until we see the list actually used - in other
1841 * words after the first mount.
1843 static bool use_task_css_set_links __read_mostly;
1845 static void cgroup_enable_task_cg_lists(void)
1847 struct task_struct *p, *g;
1850 * We need tasklist_lock because RCU is not safe against
1851 * while_each_thread(). Besides, a forking task that has passed
1852 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1853 * is not guaranteed to have its child immediately visible in the
1854 * tasklist if we walk through it with RCU.
1856 read_lock(&tasklist_lock);
1857 spin_lock_irq(&css_set_lock);
1859 if (use_task_css_set_links)
1862 use_task_css_set_links = true;
1864 do_each_thread(g, p) {
1865 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1866 task_css_set(p) != &init_css_set);
1869 * We should check if the process is exiting, otherwise
1870 * it will race with cgroup_exit() in that the list
1871 * entry won't be deleted though the process has exited.
1872 * Do it while holding siglock so that we don't end up
1873 * racing against cgroup_exit().
1875 * Interrupts were already disabled while acquiring
1876 * the css_set_lock, so we do not need to disable it
1877 * again when acquiring the sighand->siglock here.
1879 spin_lock(&p->sighand->siglock);
1880 if (!(p->flags & PF_EXITING)) {
1881 struct css_set *cset = task_css_set(p);
1883 if (!css_set_populated(cset))
1884 css_set_update_populated(cset, true);
1885 list_add_tail(&p->cg_list, &cset->tasks);
1889 spin_unlock(&p->sighand->siglock);
1890 } while_each_thread(g, p);
1892 spin_unlock_irq(&css_set_lock);
1893 read_unlock(&tasklist_lock);
1896 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1898 struct cgroup_subsys *ss;
1901 INIT_LIST_HEAD(&cgrp->self.sibling);
1902 INIT_LIST_HEAD(&cgrp->self.children);
1903 INIT_LIST_HEAD(&cgrp->cset_links);
1904 INIT_LIST_HEAD(&cgrp->pidlists);
1905 mutex_init(&cgrp->pidlist_mutex);
1906 cgrp->self.cgroup = cgrp;
1907 cgrp->self.flags |= CSS_ONLINE;
1908 cgrp->dom_cgrp = cgrp;
1909 cgrp->max_descendants = INT_MAX;
1910 cgrp->max_depth = INT_MAX;
1911 INIT_LIST_HEAD(&cgrp->rstat_css_list);
1912 prev_cputime_init(&cgrp->prev_cputime);
1914 for_each_subsys(ss, ssid)
1915 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1917 init_waitqueue_head(&cgrp->offline_waitq);
1918 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
1921 void init_cgroup_root(struct cgroup_root *root, struct cgroup_sb_opts *opts)
1923 struct cgroup *cgrp = &root->cgrp;
1925 INIT_LIST_HEAD(&root->root_list);
1926 atomic_set(&root->nr_cgrps, 1);
1928 init_cgroup_housekeeping(cgrp);
1929 idr_init(&root->cgroup_idr);
1931 root->flags = opts->flags;
1932 if (opts->release_agent)
1933 strscpy(root->release_agent_path, opts->release_agent, PATH_MAX);
1935 strscpy(root->name, opts->name, MAX_CGROUP_ROOT_NAMELEN);
1936 if (opts->cpuset_clone_children)
1937 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1940 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask, int ref_flags)
1942 LIST_HEAD(tmp_links);
1943 struct cgroup *root_cgrp = &root->cgrp;
1944 struct kernfs_syscall_ops *kf_sops;
1945 struct css_set *cset;
1948 lockdep_assert_held(&cgroup_mutex);
1950 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1953 root_cgrp->id = ret;
1954 root_cgrp->ancestor_ids[0] = ret;
1956 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
1957 ref_flags, GFP_KERNEL);
1962 * We're accessing css_set_count without locking css_set_lock here,
1963 * but that's OK - it can only be increased by someone holding
1964 * cgroup_lock, and that's us. Later rebinding may disable
1965 * controllers on the default hierarchy and thus create new csets,
1966 * which can't be more than the existing ones. Allocate 2x.
1968 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
1972 ret = cgroup_init_root_id(root);
1976 kf_sops = root == &cgrp_dfl_root ?
1977 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
1979 root->kf_root = kernfs_create_root(kf_sops,
1980 KERNFS_ROOT_CREATE_DEACTIVATED |
1981 KERNFS_ROOT_SUPPORT_EXPORTOP,
1983 if (IS_ERR(root->kf_root)) {
1984 ret = PTR_ERR(root->kf_root);
1987 root_cgrp->kn = root->kf_root->kn;
1989 ret = css_populate_dir(&root_cgrp->self);
1993 ret = rebind_subsystems(root, ss_mask);
1997 ret = cgroup_bpf_inherit(root_cgrp);
2000 trace_cgroup_setup_root(root);
2003 * There must be no failure case after here, since rebinding takes
2004 * care of subsystems' refcounts, which are explicitly dropped in
2005 * the failure exit path.
2007 list_add(&root->root_list, &cgroup_roots);
2008 cgroup_root_count++;
2011 * Link the root cgroup in this hierarchy into all the css_set
2014 spin_lock_irq(&css_set_lock);
2015 hash_for_each(css_set_table, i, cset, hlist) {
2016 link_css_set(&tmp_links, cset, root_cgrp);
2017 if (css_set_populated(cset))
2018 cgroup_update_populated(root_cgrp, true);
2020 spin_unlock_irq(&css_set_lock);
2022 BUG_ON(!list_empty(&root_cgrp->self.children));
2023 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
2025 kernfs_activate(root_cgrp->kn);
2030 kernfs_destroy_root(root->kf_root);
2031 root->kf_root = NULL;
2033 cgroup_exit_root_id(root);
2035 percpu_ref_exit(&root_cgrp->self.refcnt);
2037 free_cgrp_cset_links(&tmp_links);
2041 struct dentry *cgroup_do_mount(struct file_system_type *fs_type, int flags,
2042 struct cgroup_root *root, unsigned long magic,
2043 struct cgroup_namespace *ns)
2045 struct dentry *dentry;
2046 bool new_sb = false;
2048 dentry = kernfs_mount(fs_type, flags, root->kf_root, magic, &new_sb);
2051 * In non-init cgroup namespace, instead of root cgroup's dentry,
2052 * we return the dentry corresponding to the cgroupns->root_cgrp.
2054 if (!IS_ERR(dentry) && ns != &init_cgroup_ns) {
2055 struct dentry *nsdentry;
2056 struct super_block *sb = dentry->d_sb;
2057 struct cgroup *cgrp;
2059 mutex_lock(&cgroup_mutex);
2060 spin_lock_irq(&css_set_lock);
2062 cgrp = cset_cgroup_from_root(ns->root_cset, root);
2064 spin_unlock_irq(&css_set_lock);
2065 mutex_unlock(&cgroup_mutex);
2067 nsdentry = kernfs_node_dentry(cgrp->kn, sb);
2069 if (IS_ERR(nsdentry))
2070 deactivate_locked_super(sb);
2075 cgroup_put(&root->cgrp);
2080 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
2081 int flags, const char *unused_dev_name,
2084 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
2085 struct dentry *dentry;
2090 /* Check if the caller has permission to mount. */
2091 if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) {
2093 return ERR_PTR(-EPERM);
2097 * The first time anyone tries to mount a cgroup, enable the list
2098 * linking each css_set to its tasks and fix up all existing tasks.
2100 if (!use_task_css_set_links)
2101 cgroup_enable_task_cg_lists();
2103 if (fs_type == &cgroup2_fs_type) {
2104 unsigned int root_flags;
2106 ret = parse_cgroup_root_flags(data, &root_flags);
2109 return ERR_PTR(ret);
2112 cgrp_dfl_visible = true;
2113 cgroup_get_live(&cgrp_dfl_root.cgrp);
2115 dentry = cgroup_do_mount(&cgroup2_fs_type, flags, &cgrp_dfl_root,
2116 CGROUP2_SUPER_MAGIC, ns);
2117 if (!IS_ERR(dentry))
2118 apply_cgroup_root_flags(root_flags);
2120 dentry = cgroup1_mount(&cgroup_fs_type, flags, data,
2121 CGROUP_SUPER_MAGIC, ns);
2128 static void cgroup_kill_sb(struct super_block *sb)
2130 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2131 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2134 * If @root doesn't have any mounts or children, start killing it.
2135 * This prevents new mounts by disabling percpu_ref_tryget_live().
2136 * cgroup_mount() may wait for @root's release.
2138 * And don't kill the default root.
2140 if (!list_empty(&root->cgrp.self.children) ||
2141 root == &cgrp_dfl_root)
2142 cgroup_put(&root->cgrp);
2144 percpu_ref_kill(&root->cgrp.self.refcnt);
2149 struct file_system_type cgroup_fs_type = {
2151 .mount = cgroup_mount,
2152 .kill_sb = cgroup_kill_sb,
2153 .fs_flags = FS_USERNS_MOUNT,
2156 static struct file_system_type cgroup2_fs_type = {
2158 .mount = cgroup_mount,
2159 .kill_sb = cgroup_kill_sb,
2160 .fs_flags = FS_USERNS_MOUNT,
2163 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2164 struct cgroup_namespace *ns)
2166 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2168 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2171 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2172 struct cgroup_namespace *ns)
2176 mutex_lock(&cgroup_mutex);
2177 spin_lock_irq(&css_set_lock);
2179 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2181 spin_unlock_irq(&css_set_lock);
2182 mutex_unlock(&cgroup_mutex);
2186 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2189 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2190 * @task: target task
2191 * @buf: the buffer to write the path into
2192 * @buflen: the length of the buffer
2194 * Determine @task's cgroup on the first (the one with the lowest non-zero
2195 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2196 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2197 * cgroup controller callbacks.
2199 * Return value is the same as kernfs_path().
2201 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2203 struct cgroup_root *root;
2204 struct cgroup *cgrp;
2205 int hierarchy_id = 1;
2208 mutex_lock(&cgroup_mutex);
2209 spin_lock_irq(&css_set_lock);
2211 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2214 cgrp = task_cgroup_from_root(task, root);
2215 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2217 /* if no hierarchy exists, everyone is in "/" */
2218 ret = strlcpy(buf, "/", buflen);
2221 spin_unlock_irq(&css_set_lock);
2222 mutex_unlock(&cgroup_mutex);
2225 EXPORT_SYMBOL_GPL(task_cgroup_path);
2228 * cgroup_attach_lock - Lock for ->attach()
2229 * @lock_threadgroup: whether to down_write cgroup_threadgroup_rwsem
2231 * cgroup migration sometimes needs to stabilize threadgroups against forks and
2232 * exits by write-locking cgroup_threadgroup_rwsem. However, some ->attach()
2233 * implementations (e.g. cpuset), also need to disable CPU hotplug.
2234 * Unfortunately, letting ->attach() operations acquire cpus_read_lock() can
2235 * lead to deadlocks.
2237 * Bringing up a CPU may involve creating and destroying tasks which requires
2238 * read-locking threadgroup_rwsem, so threadgroup_rwsem nests inside
2239 * cpus_read_lock(). If we call an ->attach() which acquires the cpus lock while
2240 * write-locking threadgroup_rwsem, the locking order is reversed and we end up
2241 * waiting for an on-going CPU hotplug operation which in turn is waiting for
2242 * the threadgroup_rwsem to be released to create new tasks. For more details:
2244 * http://lkml.kernel.org/r/20220711174629.uehfmqegcwn2lqzu@wubuntu
2246 * Resolve the situation by always acquiring cpus_read_lock() before optionally
2247 * write-locking cgroup_threadgroup_rwsem. This allows ->attach() to assume that
2248 * CPU hotplug is disabled on entry.
2250 static void cgroup_attach_lock(void)
2253 percpu_down_write(&cgroup_threadgroup_rwsem);
2257 * cgroup_attach_unlock - Undo cgroup_attach_lock()
2258 * @lock_threadgroup: whether to up_write cgroup_threadgroup_rwsem
2260 static void cgroup_attach_unlock(void)
2262 percpu_up_write(&cgroup_threadgroup_rwsem);
2267 * cgroup_migrate_add_task - add a migration target task to a migration context
2268 * @task: target task
2269 * @mgctx: target migration context
2271 * Add @task, which is a migration target, to @mgctx->tset. This function
2272 * becomes noop if @task doesn't need to be migrated. @task's css_set
2273 * should have been added as a migration source and @task->cg_list will be
2274 * moved from the css_set's tasks list to mg_tasks one.
2276 static void cgroup_migrate_add_task(struct task_struct *task,
2277 struct cgroup_mgctx *mgctx)
2279 struct css_set *cset;
2281 lockdep_assert_held(&css_set_lock);
2283 /* @task either already exited or can't exit until the end */
2284 if (task->flags & PF_EXITING)
2287 /* leave @task alone if post_fork() hasn't linked it yet */
2288 if (list_empty(&task->cg_list))
2291 cset = task_css_set(task);
2292 if (!cset->mg_src_cgrp)
2295 mgctx->tset.nr_tasks++;
2297 list_move_tail(&task->cg_list, &cset->mg_tasks);
2298 if (list_empty(&cset->mg_node))
2299 list_add_tail(&cset->mg_node,
2300 &mgctx->tset.src_csets);
2301 if (list_empty(&cset->mg_dst_cset->mg_node))
2302 list_add_tail(&cset->mg_dst_cset->mg_node,
2303 &mgctx->tset.dst_csets);
2307 * cgroup_taskset_first - reset taskset and return the first task
2308 * @tset: taskset of interest
2309 * @dst_cssp: output variable for the destination css
2311 * @tset iteration is initialized and the first task is returned.
2313 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2314 struct cgroup_subsys_state **dst_cssp)
2316 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2317 tset->cur_task = NULL;
2319 return cgroup_taskset_next(tset, dst_cssp);
2323 * cgroup_taskset_next - iterate to the next task in taskset
2324 * @tset: taskset of interest
2325 * @dst_cssp: output variable for the destination css
2327 * Return the next task in @tset. Iteration must have been initialized
2328 * with cgroup_taskset_first().
2330 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2331 struct cgroup_subsys_state **dst_cssp)
2333 struct css_set *cset = tset->cur_cset;
2334 struct task_struct *task = tset->cur_task;
2336 while (&cset->mg_node != tset->csets) {
2338 task = list_first_entry(&cset->mg_tasks,
2339 struct task_struct, cg_list);
2341 task = list_next_entry(task, cg_list);
2343 if (&task->cg_list != &cset->mg_tasks) {
2344 tset->cur_cset = cset;
2345 tset->cur_task = task;
2348 * This function may be called both before and
2349 * after cgroup_taskset_migrate(). The two cases
2350 * can be distinguished by looking at whether @cset
2351 * has its ->mg_dst_cset set.
2353 if (cset->mg_dst_cset)
2354 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2356 *dst_cssp = cset->subsys[tset->ssid];
2361 cset = list_next_entry(cset, mg_node);
2369 * cgroup_taskset_migrate - migrate a taskset
2370 * @mgctx: migration context
2372 * Migrate tasks in @mgctx as setup by migration preparation functions.
2373 * This function fails iff one of the ->can_attach callbacks fails and
2374 * guarantees that either all or none of the tasks in @mgctx are migrated.
2375 * @mgctx is consumed regardless of success.
2377 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2379 struct cgroup_taskset *tset = &mgctx->tset;
2380 struct cgroup_subsys *ss;
2381 struct task_struct *task, *tmp_task;
2382 struct css_set *cset, *tmp_cset;
2383 int ssid, failed_ssid, ret;
2385 /* check that we can legitimately attach to the cgroup */
2386 if (tset->nr_tasks) {
2387 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2388 if (ss->can_attach) {
2390 ret = ss->can_attach(tset);
2393 goto out_cancel_attach;
2396 } while_each_subsys_mask();
2400 * Now that we're guaranteed success, proceed to move all tasks to
2401 * the new cgroup. There are no failure cases after here, so this
2402 * is the commit point.
2404 spin_lock_irq(&css_set_lock);
2405 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2406 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2407 struct css_set *from_cset = task_css_set(task);
2408 struct css_set *to_cset = cset->mg_dst_cset;
2410 get_css_set(to_cset);
2411 to_cset->nr_tasks++;
2412 css_set_move_task(task, from_cset, to_cset, true);
2413 put_css_set_locked(from_cset);
2414 from_cset->nr_tasks--;
2417 spin_unlock_irq(&css_set_lock);
2420 * Migration is committed, all target tasks are now on dst_csets.
2421 * Nothing is sensitive to fork() after this point. Notify
2422 * controllers that migration is complete.
2424 tset->csets = &tset->dst_csets;
2426 if (tset->nr_tasks) {
2427 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2432 } while_each_subsys_mask();
2436 goto out_release_tset;
2439 if (tset->nr_tasks) {
2440 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2441 if (ssid == failed_ssid)
2443 if (ss->cancel_attach) {
2445 ss->cancel_attach(tset);
2447 } while_each_subsys_mask();
2450 spin_lock_irq(&css_set_lock);
2451 list_splice_init(&tset->dst_csets, &tset->src_csets);
2452 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2453 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2454 list_del_init(&cset->mg_node);
2456 spin_unlock_irq(&css_set_lock);
2459 * Re-initialize the cgroup_taskset structure in case it is reused
2460 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2464 tset->csets = &tset->src_csets;
2469 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2470 * @dst_cgrp: destination cgroup to test
2472 * On the default hierarchy, except for the mixable, (possible) thread root
2473 * and threaded cgroups, subtree_control must be zero for migration
2474 * destination cgroups with tasks so that child cgroups don't compete
2477 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2479 /* v1 doesn't have any restriction */
2480 if (!cgroup_on_dfl(dst_cgrp))
2483 /* verify @dst_cgrp can host resources */
2484 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2487 /* mixables don't care */
2488 if (cgroup_is_mixable(dst_cgrp))
2492 * If @dst_cgrp is already or can become a thread root or is
2493 * threaded, it doesn't matter.
2495 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2498 /* apply no-internal-process constraint */
2499 if (dst_cgrp->subtree_control)
2506 * cgroup_migrate_finish - cleanup after attach
2507 * @mgctx: migration context
2509 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2510 * those functions for details.
2512 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2514 struct css_set *cset, *tmp_cset;
2516 lockdep_assert_held(&cgroup_mutex);
2518 spin_lock_irq(&css_set_lock);
2520 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_src_csets,
2521 mg_src_preload_node) {
2522 cset->mg_src_cgrp = NULL;
2523 cset->mg_dst_cgrp = NULL;
2524 cset->mg_dst_cset = NULL;
2525 list_del_init(&cset->mg_src_preload_node);
2526 put_css_set_locked(cset);
2529 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_dst_csets,
2530 mg_dst_preload_node) {
2531 cset->mg_src_cgrp = NULL;
2532 cset->mg_dst_cgrp = NULL;
2533 cset->mg_dst_cset = NULL;
2534 list_del_init(&cset->mg_dst_preload_node);
2535 put_css_set_locked(cset);
2538 spin_unlock_irq(&css_set_lock);
2542 * cgroup_migrate_add_src - add a migration source css_set
2543 * @src_cset: the source css_set to add
2544 * @dst_cgrp: the destination cgroup
2545 * @mgctx: migration context
2547 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2548 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2549 * up by cgroup_migrate_finish().
2551 * This function may be called without holding cgroup_threadgroup_rwsem
2552 * even if the target is a process. Threads may be created and destroyed
2553 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2554 * into play and the preloaded css_sets are guaranteed to cover all
2557 void cgroup_migrate_add_src(struct css_set *src_cset,
2558 struct cgroup *dst_cgrp,
2559 struct cgroup_mgctx *mgctx)
2561 struct cgroup *src_cgrp;
2563 lockdep_assert_held(&cgroup_mutex);
2564 lockdep_assert_held(&css_set_lock);
2567 * If ->dead, @src_set is associated with one or more dead cgroups
2568 * and doesn't contain any migratable tasks. Ignore it early so
2569 * that the rest of migration path doesn't get confused by it.
2574 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2576 if (!list_empty(&src_cset->mg_src_preload_node))
2579 WARN_ON(src_cset->mg_src_cgrp);
2580 WARN_ON(src_cset->mg_dst_cgrp);
2581 WARN_ON(!list_empty(&src_cset->mg_tasks));
2582 WARN_ON(!list_empty(&src_cset->mg_node));
2584 src_cset->mg_src_cgrp = src_cgrp;
2585 src_cset->mg_dst_cgrp = dst_cgrp;
2586 get_css_set(src_cset);
2587 list_add_tail(&src_cset->mg_src_preload_node, &mgctx->preloaded_src_csets);
2591 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2592 * @mgctx: migration context
2594 * Tasks are about to be moved and all the source css_sets have been
2595 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2596 * pins all destination css_sets, links each to its source, and append them
2597 * to @mgctx->preloaded_dst_csets.
2599 * This function must be called after cgroup_migrate_add_src() has been
2600 * called on each migration source css_set. After migration is performed
2601 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2604 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2606 struct css_set *src_cset, *tmp_cset;
2608 lockdep_assert_held(&cgroup_mutex);
2610 /* look up the dst cset for each src cset and link it to src */
2611 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2612 mg_src_preload_node) {
2613 struct css_set *dst_cset;
2614 struct cgroup_subsys *ss;
2617 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2621 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2624 * If src cset equals dst, it's noop. Drop the src.
2625 * cgroup_migrate() will skip the cset too. Note that we
2626 * can't handle src == dst as some nodes are used by both.
2628 if (src_cset == dst_cset) {
2629 src_cset->mg_src_cgrp = NULL;
2630 src_cset->mg_dst_cgrp = NULL;
2631 list_del_init(&src_cset->mg_src_preload_node);
2632 put_css_set(src_cset);
2633 put_css_set(dst_cset);
2637 src_cset->mg_dst_cset = dst_cset;
2639 if (list_empty(&dst_cset->mg_dst_preload_node))
2640 list_add_tail(&dst_cset->mg_dst_preload_node,
2641 &mgctx->preloaded_dst_csets);
2643 put_css_set(dst_cset);
2645 for_each_subsys(ss, ssid)
2646 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2647 mgctx->ss_mask |= 1 << ssid;
2652 cgroup_migrate_finish(mgctx);
2657 * cgroup_migrate - migrate a process or task to a cgroup
2658 * @leader: the leader of the process or the task to migrate
2659 * @threadgroup: whether @leader points to the whole process or a single task
2660 * @mgctx: migration context
2662 * Migrate a process or task denoted by @leader. If migrating a process,
2663 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2664 * responsible for invoking cgroup_migrate_add_src() and
2665 * cgroup_migrate_prepare_dst() on the targets before invoking this
2666 * function and following up with cgroup_migrate_finish().
2668 * As long as a controller's ->can_attach() doesn't fail, this function is
2669 * guaranteed to succeed. This means that, excluding ->can_attach()
2670 * failure, when migrating multiple targets, the success or failure can be
2671 * decided for all targets by invoking group_migrate_prepare_dst() before
2672 * actually starting migrating.
2674 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2675 struct cgroup_mgctx *mgctx)
2677 struct task_struct *task;
2680 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2681 * already PF_EXITING could be freed from underneath us unless we
2682 * take an rcu_read_lock.
2684 spin_lock_irq(&css_set_lock);
2688 cgroup_migrate_add_task(task, mgctx);
2691 } while_each_thread(leader, task);
2693 spin_unlock_irq(&css_set_lock);
2695 return cgroup_migrate_execute(mgctx);
2699 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2700 * @dst_cgrp: the cgroup to attach to
2701 * @leader: the task or the leader of the threadgroup to be attached
2702 * @threadgroup: attach the whole threadgroup?
2704 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2706 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2709 DEFINE_CGROUP_MGCTX(mgctx);
2710 struct task_struct *task;
2713 ret = cgroup_migrate_vet_dst(dst_cgrp);
2717 /* look up all src csets */
2718 spin_lock_irq(&css_set_lock);
2722 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2725 } while_each_thread(leader, task);
2727 spin_unlock_irq(&css_set_lock);
2729 /* prepare dst csets and commit */
2730 ret = cgroup_migrate_prepare_dst(&mgctx);
2732 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2734 cgroup_migrate_finish(&mgctx);
2737 TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
2742 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup)
2743 __acquires(&cgroup_threadgroup_rwsem)
2745 struct task_struct *tsk;
2748 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2749 return ERR_PTR(-EINVAL);
2751 cgroup_attach_lock();
2755 tsk = find_task_by_vpid(pid);
2757 tsk = ERR_PTR(-ESRCH);
2758 goto out_unlock_threadgroup;
2765 tsk = tsk->group_leader;
2768 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2769 * If userland migrates such a kthread to a non-root cgroup, it can
2770 * become trapped in a cpuset, or RT kthread may be born in a
2771 * cgroup with no rt_runtime allocated. Just say no.
2773 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2774 tsk = ERR_PTR(-EINVAL);
2775 goto out_unlock_threadgroup;
2778 get_task_struct(tsk);
2779 goto out_unlock_rcu;
2781 out_unlock_threadgroup:
2782 cgroup_attach_unlock();
2788 void cgroup_procs_write_finish(struct task_struct *task)
2789 __releases(&cgroup_threadgroup_rwsem)
2791 struct cgroup_subsys *ss;
2794 /* release reference from cgroup_procs_write_start() */
2795 put_task_struct(task);
2797 cgroup_attach_unlock();
2798 for_each_subsys(ss, ssid)
2799 if (ss->post_attach)
2803 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2805 struct cgroup_subsys *ss;
2806 bool printed = false;
2809 do_each_subsys_mask(ss, ssid, ss_mask) {
2812 seq_printf(seq, "%s", ss->name);
2814 } while_each_subsys_mask();
2816 seq_putc(seq, '\n');
2819 /* show controllers which are enabled from the parent */
2820 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2822 struct cgroup *cgrp = seq_css(seq)->cgroup;
2824 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2828 /* show controllers which are enabled for a given cgroup's children */
2829 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2831 struct cgroup *cgrp = seq_css(seq)->cgroup;
2833 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2838 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2839 * @cgrp: root of the subtree to update csses for
2841 * @cgrp's control masks have changed and its subtree's css associations
2842 * need to be updated accordingly. This function looks up all css_sets
2843 * which are attached to the subtree, creates the matching updated css_sets
2844 * and migrates the tasks to the new ones.
2846 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2848 DEFINE_CGROUP_MGCTX(mgctx);
2849 struct cgroup_subsys_state *d_css;
2850 struct cgroup *dsct;
2851 struct css_set *src_cset;
2854 lockdep_assert_held(&cgroup_mutex);
2856 cgroup_attach_lock();
2858 /* look up all csses currently attached to @cgrp's subtree */
2859 spin_lock_irq(&css_set_lock);
2860 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2861 struct cgrp_cset_link *link;
2863 list_for_each_entry(link, &dsct->cset_links, cset_link)
2864 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2866 spin_unlock_irq(&css_set_lock);
2868 /* NULL dst indicates self on default hierarchy */
2869 ret = cgroup_migrate_prepare_dst(&mgctx);
2873 spin_lock_irq(&css_set_lock);
2874 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets,
2875 mg_src_preload_node) {
2876 struct task_struct *task, *ntask;
2878 /* all tasks in src_csets need to be migrated */
2879 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2880 cgroup_migrate_add_task(task, &mgctx);
2882 spin_unlock_irq(&css_set_lock);
2884 ret = cgroup_migrate_execute(&mgctx);
2886 cgroup_migrate_finish(&mgctx);
2887 cgroup_attach_unlock();
2892 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2893 * @cgrp: root of the target subtree
2895 * Because css offlining is asynchronous, userland may try to re-enable a
2896 * controller while the previous css is still around. This function grabs
2897 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2899 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2900 __acquires(&cgroup_mutex)
2902 struct cgroup *dsct;
2903 struct cgroup_subsys_state *d_css;
2904 struct cgroup_subsys *ss;
2908 mutex_lock(&cgroup_mutex);
2910 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2911 for_each_subsys(ss, ssid) {
2912 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2915 if (!css || !percpu_ref_is_dying(&css->refcnt))
2918 cgroup_get_live(dsct);
2919 prepare_to_wait(&dsct->offline_waitq, &wait,
2920 TASK_UNINTERRUPTIBLE);
2922 mutex_unlock(&cgroup_mutex);
2924 finish_wait(&dsct->offline_waitq, &wait);
2933 * cgroup_save_control - save control masks and dom_cgrp of a subtree
2934 * @cgrp: root of the target subtree
2936 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
2937 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2940 static void cgroup_save_control(struct cgroup *cgrp)
2942 struct cgroup *dsct;
2943 struct cgroup_subsys_state *d_css;
2945 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2946 dsct->old_subtree_control = dsct->subtree_control;
2947 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
2948 dsct->old_dom_cgrp = dsct->dom_cgrp;
2953 * cgroup_propagate_control - refresh control masks of a subtree
2954 * @cgrp: root of the target subtree
2956 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
2957 * ->subtree_control and propagate controller availability through the
2958 * subtree so that descendants don't have unavailable controllers enabled.
2960 static void cgroup_propagate_control(struct cgroup *cgrp)
2962 struct cgroup *dsct;
2963 struct cgroup_subsys_state *d_css;
2965 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2966 dsct->subtree_control &= cgroup_control(dsct);
2967 dsct->subtree_ss_mask =
2968 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
2969 cgroup_ss_mask(dsct));
2974 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
2975 * @cgrp: root of the target subtree
2977 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
2978 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2981 static void cgroup_restore_control(struct cgroup *cgrp)
2983 struct cgroup *dsct;
2984 struct cgroup_subsys_state *d_css;
2986 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2987 dsct->subtree_control = dsct->old_subtree_control;
2988 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
2989 dsct->dom_cgrp = dsct->old_dom_cgrp;
2993 static bool css_visible(struct cgroup_subsys_state *css)
2995 struct cgroup_subsys *ss = css->ss;
2996 struct cgroup *cgrp = css->cgroup;
2998 if (cgroup_control(cgrp) & (1 << ss->id))
3000 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
3002 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
3006 * cgroup_apply_control_enable - enable or show csses according to control
3007 * @cgrp: root of the target subtree
3009 * Walk @cgrp's subtree and create new csses or make the existing ones
3010 * visible. A css is created invisible if it's being implicitly enabled
3011 * through dependency. An invisible css is made visible when the userland
3012 * explicitly enables it.
3014 * Returns 0 on success, -errno on failure. On failure, csses which have
3015 * been processed already aren't cleaned up. The caller is responsible for
3016 * cleaning up with cgroup_apply_control_disable().
3018 static int cgroup_apply_control_enable(struct cgroup *cgrp)
3020 struct cgroup *dsct;
3021 struct cgroup_subsys_state *d_css;
3022 struct cgroup_subsys *ss;
3025 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3026 for_each_subsys(ss, ssid) {
3027 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3029 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
3033 css = css_create(dsct, ss);
3035 return PTR_ERR(css);
3038 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3040 if (css_visible(css)) {
3041 ret = css_populate_dir(css);
3052 * cgroup_apply_control_disable - kill or hide csses according to control
3053 * @cgrp: root of the target subtree
3055 * Walk @cgrp's subtree and kill and hide csses so that they match
3056 * cgroup_ss_mask() and cgroup_visible_mask().
3058 * A css is hidden when the userland requests it to be disabled while other
3059 * subsystems are still depending on it. The css must not actively control
3060 * resources and be in the vanilla state if it's made visible again later.
3061 * Controllers which may be depended upon should provide ->css_reset() for
3064 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3066 struct cgroup *dsct;
3067 struct cgroup_subsys_state *d_css;
3068 struct cgroup_subsys *ss;
3071 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3072 for_each_subsys(ss, ssid) {
3073 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3078 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3081 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3083 } else if (!css_visible(css)) {
3093 * cgroup_apply_control - apply control mask updates to the subtree
3094 * @cgrp: root of the target subtree
3096 * subsystems can be enabled and disabled in a subtree using the following
3099 * 1. Call cgroup_save_control() to stash the current state.
3100 * 2. Update ->subtree_control masks in the subtree as desired.
3101 * 3. Call cgroup_apply_control() to apply the changes.
3102 * 4. Optionally perform other related operations.
3103 * 5. Call cgroup_finalize_control() to finish up.
3105 * This function implements step 3 and propagates the mask changes
3106 * throughout @cgrp's subtree, updates csses accordingly and perform
3107 * process migrations.
3109 static int cgroup_apply_control(struct cgroup *cgrp)
3113 cgroup_propagate_control(cgrp);
3115 ret = cgroup_apply_control_enable(cgrp);
3120 * At this point, cgroup_e_css() results reflect the new csses
3121 * making the following cgroup_update_dfl_csses() properly update
3122 * css associations of all tasks in the subtree.
3124 ret = cgroup_update_dfl_csses(cgrp);
3132 * cgroup_finalize_control - finalize control mask update
3133 * @cgrp: root of the target subtree
3134 * @ret: the result of the update
3136 * Finalize control mask update. See cgroup_apply_control() for more info.
3138 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3141 cgroup_restore_control(cgrp);
3142 cgroup_propagate_control(cgrp);
3145 cgroup_apply_control_disable(cgrp);
3148 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3150 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3152 /* if nothing is getting enabled, nothing to worry about */
3156 /* can @cgrp host any resources? */
3157 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3160 /* mixables don't care */
3161 if (cgroup_is_mixable(cgrp))
3164 if (domain_enable) {
3165 /* can't enable domain controllers inside a thread subtree */
3166 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3170 * Threaded controllers can handle internal competitions
3171 * and are always allowed inside a (prospective) thread
3174 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3179 * Controllers can't be enabled for a cgroup with tasks to avoid
3180 * child cgroups competing against tasks.
3182 if (cgroup_has_tasks(cgrp))
3188 /* change the enabled child controllers for a cgroup in the default hierarchy */
3189 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3190 char *buf, size_t nbytes,
3193 u16 enable = 0, disable = 0;
3194 struct cgroup *cgrp, *child;
3195 struct cgroup_subsys *ss;
3200 * Parse input - space separated list of subsystem names prefixed
3201 * with either + or -.
3203 buf = strstrip(buf);
3204 while ((tok = strsep(&buf, " "))) {
3207 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3208 if (!cgroup_ssid_enabled(ssid) ||
3209 strcmp(tok + 1, ss->name))
3213 enable |= 1 << ssid;
3214 disable &= ~(1 << ssid);
3215 } else if (*tok == '-') {
3216 disable |= 1 << ssid;
3217 enable &= ~(1 << ssid);
3222 } while_each_subsys_mask();
3223 if (ssid == CGROUP_SUBSYS_COUNT)
3227 cgrp = cgroup_kn_lock_live(of->kn, true);
3231 for_each_subsys(ss, ssid) {
3232 if (enable & (1 << ssid)) {
3233 if (cgrp->subtree_control & (1 << ssid)) {
3234 enable &= ~(1 << ssid);
3238 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3242 } else if (disable & (1 << ssid)) {
3243 if (!(cgrp->subtree_control & (1 << ssid))) {
3244 disable &= ~(1 << ssid);
3248 /* a child has it enabled? */
3249 cgroup_for_each_live_child(child, cgrp) {
3250 if (child->subtree_control & (1 << ssid)) {
3258 if (!enable && !disable) {
3263 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3267 /* save and update control masks and prepare csses */
3268 cgroup_save_control(cgrp);
3270 cgrp->subtree_control |= enable;
3271 cgrp->subtree_control &= ~disable;
3273 ret = cgroup_apply_control(cgrp);
3274 cgroup_finalize_control(cgrp, ret);
3278 kernfs_activate(cgrp->kn);
3280 cgroup_kn_unlock(of->kn);
3281 return ret ?: nbytes;
3285 * cgroup_enable_threaded - make @cgrp threaded
3286 * @cgrp: the target cgroup
3288 * Called when "threaded" is written to the cgroup.type interface file and
3289 * tries to make @cgrp threaded and join the parent's resource domain.
3290 * This function is never called on the root cgroup as cgroup.type doesn't
3293 static int cgroup_enable_threaded(struct cgroup *cgrp)
3295 struct cgroup *parent = cgroup_parent(cgrp);
3296 struct cgroup *dom_cgrp = parent->dom_cgrp;
3297 struct cgroup *dsct;
3298 struct cgroup_subsys_state *d_css;
3301 lockdep_assert_held(&cgroup_mutex);
3303 /* noop if already threaded */
3304 if (cgroup_is_threaded(cgrp))
3308 * If @cgroup is populated or has domain controllers enabled, it
3309 * can't be switched. While the below cgroup_can_be_thread_root()
3310 * test can catch the same conditions, that's only when @parent is
3311 * not mixable, so let's check it explicitly.
3313 if (cgroup_is_populated(cgrp) ||
3314 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3317 /* we're joining the parent's domain, ensure its validity */
3318 if (!cgroup_is_valid_domain(dom_cgrp) ||
3319 !cgroup_can_be_thread_root(dom_cgrp))
3323 * The following shouldn't cause actual migrations and should
3326 cgroup_save_control(cgrp);
3328 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3329 if (dsct == cgrp || cgroup_is_threaded(dsct))
3330 dsct->dom_cgrp = dom_cgrp;
3332 ret = cgroup_apply_control(cgrp);
3334 parent->nr_threaded_children++;
3336 cgroup_finalize_control(cgrp, ret);
3340 static int cgroup_type_show(struct seq_file *seq, void *v)
3342 struct cgroup *cgrp = seq_css(seq)->cgroup;
3344 if (cgroup_is_threaded(cgrp))
3345 seq_puts(seq, "threaded\n");
3346 else if (!cgroup_is_valid_domain(cgrp))
3347 seq_puts(seq, "domain invalid\n");
3348 else if (cgroup_is_thread_root(cgrp))
3349 seq_puts(seq, "domain threaded\n");
3351 seq_puts(seq, "domain\n");
3356 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3357 size_t nbytes, loff_t off)
3359 struct cgroup *cgrp;
3362 /* only switching to threaded mode is supported */
3363 if (strcmp(strstrip(buf), "threaded"))
3366 /* drain dying csses before we re-apply (threaded) subtree control */
3367 cgrp = cgroup_kn_lock_live(of->kn, true);
3371 /* threaded can only be enabled */
3372 ret = cgroup_enable_threaded(cgrp);
3374 cgroup_kn_unlock(of->kn);
3375 return ret ?: nbytes;
3378 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3380 struct cgroup *cgrp = seq_css(seq)->cgroup;
3381 int descendants = READ_ONCE(cgrp->max_descendants);
3383 if (descendants == INT_MAX)
3384 seq_puts(seq, "max\n");
3386 seq_printf(seq, "%d\n", descendants);
3391 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3392 char *buf, size_t nbytes, loff_t off)
3394 struct cgroup *cgrp;
3398 buf = strstrip(buf);
3399 if (!strcmp(buf, "max")) {
3400 descendants = INT_MAX;
3402 ret = kstrtoint(buf, 0, &descendants);
3407 if (descendants < 0)
3410 cgrp = cgroup_kn_lock_live(of->kn, false);
3414 cgrp->max_descendants = descendants;
3416 cgroup_kn_unlock(of->kn);
3421 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3423 struct cgroup *cgrp = seq_css(seq)->cgroup;
3424 int depth = READ_ONCE(cgrp->max_depth);
3426 if (depth == INT_MAX)
3427 seq_puts(seq, "max\n");
3429 seq_printf(seq, "%d\n", depth);
3434 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3435 char *buf, size_t nbytes, loff_t off)
3437 struct cgroup *cgrp;
3441 buf = strstrip(buf);
3442 if (!strcmp(buf, "max")) {
3445 ret = kstrtoint(buf, 0, &depth);
3453 cgrp = cgroup_kn_lock_live(of->kn, false);
3457 cgrp->max_depth = depth;
3459 cgroup_kn_unlock(of->kn);
3464 static int cgroup_events_show(struct seq_file *seq, void *v)
3466 seq_printf(seq, "populated %d\n",
3467 cgroup_is_populated(seq_css(seq)->cgroup));
3471 static int cgroup_stat_show(struct seq_file *seq, void *v)
3473 struct cgroup *cgroup = seq_css(seq)->cgroup;
3475 seq_printf(seq, "nr_descendants %d\n",
3476 cgroup->nr_descendants);
3477 seq_printf(seq, "nr_dying_descendants %d\n",
3478 cgroup->nr_dying_descendants);
3483 static int __maybe_unused cgroup_extra_stat_show(struct seq_file *seq,
3484 struct cgroup *cgrp, int ssid)
3486 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3487 struct cgroup_subsys_state *css;
3490 if (!ss->css_extra_stat_show)
3493 css = cgroup_tryget_css(cgrp, ss);
3497 ret = ss->css_extra_stat_show(seq, css);
3502 static int cpu_stat_show(struct seq_file *seq, void *v)
3504 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3507 cgroup_base_stat_cputime_show(seq);
3508 #ifdef CONFIG_CGROUP_SCHED
3509 ret = cgroup_extra_stat_show(seq, cgrp, cpu_cgrp_id);
3514 static int cgroup_file_open(struct kernfs_open_file *of)
3516 struct cftype *cft = of->kn->priv;
3517 struct cgroup_file_ctx *ctx;
3520 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3524 ctx->ns = current->nsproxy->cgroup_ns;
3525 get_cgroup_ns(ctx->ns);
3531 ret = cft->open(of);
3533 put_cgroup_ns(ctx->ns);
3539 static void cgroup_file_release(struct kernfs_open_file *of)
3541 struct cftype *cft = of->kn->priv;
3542 struct cgroup_file_ctx *ctx = of->priv;
3546 put_cgroup_ns(ctx->ns);
3550 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3551 size_t nbytes, loff_t off)
3553 struct cgroup_file_ctx *ctx = of->priv;
3554 struct cgroup *cgrp = of->kn->parent->priv;
3555 struct cftype *cft = of->kn->priv;
3556 struct cgroup_subsys_state *css;
3560 * If namespaces are delegation boundaries, disallow writes to
3561 * files in an non-init namespace root from inside the namespace
3562 * except for the files explicitly marked delegatable -
3563 * cgroup.procs and cgroup.subtree_control.
3565 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3566 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3567 ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
3571 return cft->write(of, buf, nbytes, off);
3574 * kernfs guarantees that a file isn't deleted with operations in
3575 * flight, which means that the matching css is and stays alive and
3576 * doesn't need to be pinned. The RCU locking is not necessary
3577 * either. It's just for the convenience of using cgroup_css().
3580 css = cgroup_css(cgrp, cft->ss);
3583 if (cft->write_u64) {
3584 unsigned long long v;
3585 ret = kstrtoull(buf, 0, &v);
3587 ret = cft->write_u64(css, cft, v);
3588 } else if (cft->write_s64) {
3590 ret = kstrtoll(buf, 0, &v);
3592 ret = cft->write_s64(css, cft, v);
3597 return ret ?: nbytes;
3600 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3602 return seq_cft(seq)->seq_start(seq, ppos);
3605 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3607 return seq_cft(seq)->seq_next(seq, v, ppos);
3610 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3612 if (seq_cft(seq)->seq_stop)
3613 seq_cft(seq)->seq_stop(seq, v);
3616 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3618 struct cftype *cft = seq_cft(m);
3619 struct cgroup_subsys_state *css = seq_css(m);
3622 return cft->seq_show(m, arg);
3625 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3626 else if (cft->read_s64)
3627 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3633 static struct kernfs_ops cgroup_kf_single_ops = {
3634 .atomic_write_len = PAGE_SIZE,
3635 .open = cgroup_file_open,
3636 .release = cgroup_file_release,
3637 .write = cgroup_file_write,
3638 .seq_show = cgroup_seqfile_show,
3641 static struct kernfs_ops cgroup_kf_ops = {
3642 .atomic_write_len = PAGE_SIZE,
3643 .open = cgroup_file_open,
3644 .release = cgroup_file_release,
3645 .write = cgroup_file_write,
3646 .seq_start = cgroup_seqfile_start,
3647 .seq_next = cgroup_seqfile_next,
3648 .seq_stop = cgroup_seqfile_stop,
3649 .seq_show = cgroup_seqfile_show,
3652 /* set uid and gid of cgroup dirs and files to that of the creator */
3653 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3655 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3656 .ia_uid = current_fsuid(),
3657 .ia_gid = current_fsgid(), };
3659 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3660 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3663 return kernfs_setattr(kn, &iattr);
3666 static void cgroup_file_notify_timer(struct timer_list *timer)
3668 cgroup_file_notify(container_of(timer, struct cgroup_file,
3672 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
3675 char name[CGROUP_FILE_NAME_MAX];
3676 struct kernfs_node *kn;
3677 struct lock_class_key *key = NULL;
3680 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3681 key = &cft->lockdep_key;
3683 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3684 cgroup_file_mode(cft),
3685 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
3686 0, cft->kf_ops, cft,
3691 ret = cgroup_kn_set_ugid(kn);
3697 if (cft->file_offset) {
3698 struct cgroup_file *cfile = (void *)css + cft->file_offset;
3700 timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
3702 spin_lock_irq(&cgroup_file_kn_lock);
3704 spin_unlock_irq(&cgroup_file_kn_lock);
3711 * cgroup_addrm_files - add or remove files to a cgroup directory
3712 * @css: the target css
3713 * @cgrp: the target cgroup (usually css->cgroup)
3714 * @cfts: array of cftypes to be added
3715 * @is_add: whether to add or remove
3717 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3718 * For removals, this function never fails.
3720 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
3721 struct cgroup *cgrp, struct cftype cfts[],
3724 struct cftype *cft, *cft_end = NULL;
3727 lockdep_assert_held(&cgroup_mutex);
3730 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
3731 /* does cft->flags tell us to skip this file on @cgrp? */
3732 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3734 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3736 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3738 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3742 ret = cgroup_add_file(css, cgrp, cft);
3744 pr_warn("%s: failed to add %s, err=%d\n",
3745 __func__, cft->name, ret);
3751 cgroup_rm_file(cgrp, cft);
3757 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3759 struct cgroup_subsys *ss = cfts[0].ss;
3760 struct cgroup *root = &ss->root->cgrp;
3761 struct cgroup_subsys_state *css;
3764 lockdep_assert_held(&cgroup_mutex);
3766 /* add/rm files for all cgroups created before */
3767 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3768 struct cgroup *cgrp = css->cgroup;
3770 if (!(css->flags & CSS_VISIBLE))
3773 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
3779 kernfs_activate(root->kn);
3783 static void cgroup_exit_cftypes(struct cftype *cfts)
3787 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3788 /* free copy for custom atomic_write_len, see init_cftypes() */
3789 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3794 /* revert flags set by cgroup core while adding @cfts */
3795 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3799 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3803 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3804 struct kernfs_ops *kf_ops;
3806 WARN_ON(cft->ss || cft->kf_ops);
3809 kf_ops = &cgroup_kf_ops;
3811 kf_ops = &cgroup_kf_single_ops;
3814 * Ugh... if @cft wants a custom max_write_len, we need to
3815 * make a copy of kf_ops to set its atomic_write_len.
3817 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3818 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3820 cgroup_exit_cftypes(cfts);
3823 kf_ops->atomic_write_len = cft->max_write_len;
3826 cft->kf_ops = kf_ops;
3833 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3835 lockdep_assert_held(&cgroup_mutex);
3837 if (!cfts || !cfts[0].ss)
3840 list_del(&cfts->node);
3841 cgroup_apply_cftypes(cfts, false);
3842 cgroup_exit_cftypes(cfts);
3847 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3848 * @cfts: zero-length name terminated array of cftypes
3850 * Unregister @cfts. Files described by @cfts are removed from all
3851 * existing cgroups and all future cgroups won't have them either. This
3852 * function can be called anytime whether @cfts' subsys is attached or not.
3854 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3857 int cgroup_rm_cftypes(struct cftype *cfts)
3861 mutex_lock(&cgroup_mutex);
3862 ret = cgroup_rm_cftypes_locked(cfts);
3863 mutex_unlock(&cgroup_mutex);
3868 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3869 * @ss: target cgroup subsystem
3870 * @cfts: zero-length name terminated array of cftypes
3872 * Register @cfts to @ss. Files described by @cfts are created for all
3873 * existing cgroups to which @ss is attached and all future cgroups will
3874 * have them too. This function can be called anytime whether @ss is
3877 * Returns 0 on successful registration, -errno on failure. Note that this
3878 * function currently returns 0 as long as @cfts registration is successful
3879 * even if some file creation attempts on existing cgroups fail.
3881 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3885 if (!cgroup_ssid_enabled(ss->id))
3888 if (!cfts || cfts[0].name[0] == '\0')
3891 ret = cgroup_init_cftypes(ss, cfts);
3895 mutex_lock(&cgroup_mutex);
3897 list_add_tail(&cfts->node, &ss->cfts);
3898 ret = cgroup_apply_cftypes(cfts, true);
3900 cgroup_rm_cftypes_locked(cfts);
3902 mutex_unlock(&cgroup_mutex);
3907 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3908 * @ss: target cgroup subsystem
3909 * @cfts: zero-length name terminated array of cftypes
3911 * Similar to cgroup_add_cftypes() but the added files are only used for
3912 * the default hierarchy.
3914 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3918 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3919 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3920 return cgroup_add_cftypes(ss, cfts);
3924 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3925 * @ss: target cgroup subsystem
3926 * @cfts: zero-length name terminated array of cftypes
3928 * Similar to cgroup_add_cftypes() but the added files are only used for
3929 * the legacy hierarchies.
3931 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3935 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3936 cft->flags |= __CFTYPE_NOT_ON_DFL;
3937 return cgroup_add_cftypes(ss, cfts);
3941 * cgroup_file_notify - generate a file modified event for a cgroup_file
3942 * @cfile: target cgroup_file
3944 * @cfile must have been obtained by setting cftype->file_offset.
3946 void cgroup_file_notify(struct cgroup_file *cfile)
3948 unsigned long flags;
3950 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
3952 unsigned long last = cfile->notified_at;
3953 unsigned long next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
3955 if (time_in_range(jiffies, last, next)) {
3956 timer_reduce(&cfile->notify_timer, next);
3958 kernfs_notify(cfile->kn);
3959 cfile->notified_at = jiffies;
3962 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
3966 * css_next_child - find the next child of a given css
3967 * @pos: the current position (%NULL to initiate traversal)
3968 * @parent: css whose children to walk
3970 * This function returns the next child of @parent and should be called
3971 * under either cgroup_mutex or RCU read lock. The only requirement is
3972 * that @parent and @pos are accessible. The next sibling is guaranteed to
3973 * be returned regardless of their states.
3975 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3976 * css which finished ->css_online() is guaranteed to be visible in the
3977 * future iterations and will stay visible until the last reference is put.
3978 * A css which hasn't finished ->css_online() or already finished
3979 * ->css_offline() may show up during traversal. It's each subsystem's
3980 * responsibility to synchronize against on/offlining.
3982 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3983 struct cgroup_subsys_state *parent)
3985 struct cgroup_subsys_state *next;
3987 cgroup_assert_mutex_or_rcu_locked();
3990 * @pos could already have been unlinked from the sibling list.
3991 * Once a cgroup is removed, its ->sibling.next is no longer
3992 * updated when its next sibling changes. CSS_RELEASED is set when
3993 * @pos is taken off list, at which time its next pointer is valid,
3994 * and, as releases are serialized, the one pointed to by the next
3995 * pointer is guaranteed to not have started release yet. This
3996 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3997 * critical section, the one pointed to by its next pointer is
3998 * guaranteed to not have finished its RCU grace period even if we
3999 * have dropped rcu_read_lock() inbetween iterations.
4001 * If @pos has CSS_RELEASED set, its next pointer can't be
4002 * dereferenced; however, as each css is given a monotonically
4003 * increasing unique serial number and always appended to the
4004 * sibling list, the next one can be found by walking the parent's
4005 * children until the first css with higher serial number than
4006 * @pos's. While this path can be slower, it happens iff iteration
4007 * races against release and the race window is very small.
4010 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
4011 } else if (likely(!(pos->flags & CSS_RELEASED))) {
4012 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
4014 list_for_each_entry_rcu(next, &parent->children, sibling)
4015 if (next->serial_nr > pos->serial_nr)
4020 * @next, if not pointing to the head, can be dereferenced and is
4023 if (&next->sibling != &parent->children)
4029 * css_next_descendant_pre - find the next descendant for pre-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_pre(). Find the next descendant
4034 * to visit for pre-order traversal of @root's descendants. @root is
4035 * included in the iteration and the first 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 @root are accessible and @pos is a descendant of @root.
4042 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4043 * css which finished ->css_online() is guaranteed to be visible in the
4044 * future iterations and will stay visible until the last reference is put.
4045 * A css which hasn't finished ->css_online() or already finished
4046 * ->css_offline() may show up during traversal. It's each subsystem's
4047 * responsibility to synchronize against on/offlining.
4049 struct cgroup_subsys_state *
4050 css_next_descendant_pre(struct cgroup_subsys_state *pos,
4051 struct cgroup_subsys_state *root)
4053 struct cgroup_subsys_state *next;
4055 cgroup_assert_mutex_or_rcu_locked();
4057 /* if first iteration, visit @root */
4061 /* visit the first child if exists */
4062 next = css_next_child(NULL, pos);
4066 /* no child, visit my or the closest ancestor's next sibling */
4067 while (pos != root) {
4068 next = css_next_child(pos, pos->parent);
4078 * css_rightmost_descendant - return the rightmost descendant of a css
4079 * @pos: css of interest
4081 * Return the rightmost descendant of @pos. If there's no descendant, @pos
4082 * is returned. This can be used during pre-order traversal to skip
4085 * While this function requires cgroup_mutex or RCU read locking, it
4086 * doesn't require the whole traversal to be contained in a single critical
4087 * section. This function will return the correct rightmost descendant as
4088 * long as @pos is accessible.
4090 struct cgroup_subsys_state *
4091 css_rightmost_descendant(struct cgroup_subsys_state *pos)
4093 struct cgroup_subsys_state *last, *tmp;
4095 cgroup_assert_mutex_or_rcu_locked();
4099 /* ->prev isn't RCU safe, walk ->next till the end */
4101 css_for_each_child(tmp, last)
4108 static struct cgroup_subsys_state *
4109 css_leftmost_descendant(struct cgroup_subsys_state *pos)
4111 struct cgroup_subsys_state *last;
4115 pos = css_next_child(NULL, pos);
4122 * css_next_descendant_post - find the next descendant for post-order walk
4123 * @pos: the current position (%NULL to initiate traversal)
4124 * @root: css whose descendants to walk
4126 * To be used by css_for_each_descendant_post(). Find the next descendant
4127 * to visit for post-order traversal of @root's descendants. @root is
4128 * included in the iteration and the last node to be visited.
4130 * While this function requires cgroup_mutex or RCU read locking, it
4131 * doesn't require the whole traversal to be contained in a single critical
4132 * section. This function will return the correct next descendant as long
4133 * as both @pos and @cgroup are accessible and @pos is a descendant of
4136 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4137 * css which finished ->css_online() is guaranteed to be visible in the
4138 * future iterations and will stay visible until the last reference is put.
4139 * A css which hasn't finished ->css_online() or already finished
4140 * ->css_offline() may show up during traversal. It's each subsystem's
4141 * responsibility to synchronize against on/offlining.
4143 struct cgroup_subsys_state *
4144 css_next_descendant_post(struct cgroup_subsys_state *pos,
4145 struct cgroup_subsys_state *root)
4147 struct cgroup_subsys_state *next;
4149 cgroup_assert_mutex_or_rcu_locked();
4151 /* if first iteration, visit leftmost descendant which may be @root */
4153 return css_leftmost_descendant(root);
4155 /* if we visited @root, we're done */
4159 /* if there's an unvisited sibling, visit its leftmost descendant */
4160 next = css_next_child(pos, pos->parent);
4162 return css_leftmost_descendant(next);
4164 /* no sibling left, visit parent */
4169 * css_has_online_children - does a css have online children
4170 * @css: the target css
4172 * Returns %true if @css has any online children; otherwise, %false. This
4173 * function can be called from any context but the caller is responsible
4174 * for synchronizing against on/offlining as necessary.
4176 bool css_has_online_children(struct cgroup_subsys_state *css)
4178 struct cgroup_subsys_state *child;
4182 css_for_each_child(child, css) {
4183 if (child->flags & CSS_ONLINE) {
4192 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4194 struct list_head *l;
4195 struct cgrp_cset_link *link;
4196 struct css_set *cset;
4198 lockdep_assert_held(&css_set_lock);
4200 /* find the next threaded cset */
4201 if (it->tcset_pos) {
4202 l = it->tcset_pos->next;
4204 if (l != it->tcset_head) {
4206 return container_of(l, struct css_set,
4207 threaded_csets_node);
4210 it->tcset_pos = NULL;
4213 /* find the next cset */
4216 if (l == it->cset_head) {
4217 it->cset_pos = NULL;
4222 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4224 link = list_entry(l, struct cgrp_cset_link, cset_link);
4230 /* initialize threaded css_set walking */
4231 if (it->flags & CSS_TASK_ITER_THREADED) {
4233 put_css_set_locked(it->cur_dcset);
4234 it->cur_dcset = cset;
4237 it->tcset_head = &cset->threaded_csets;
4238 it->tcset_pos = &cset->threaded_csets;
4245 * css_task_iter_advance_css_set - advance a task itererator to the next css_set
4246 * @it: the iterator to advance
4248 * Advance @it to the next css_set to walk.
4250 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4252 struct css_set *cset;
4254 lockdep_assert_held(&css_set_lock);
4256 /* Advance to the next non-empty css_set */
4258 cset = css_task_iter_next_css_set(it);
4260 it->task_pos = NULL;
4263 } while (!css_set_populated(cset) && list_empty(&cset->dying_tasks));
4265 if (!list_empty(&cset->tasks)) {
4266 it->task_pos = cset->tasks.next;
4267 it->cur_tasks_head = &cset->tasks;
4268 } else if (!list_empty(&cset->mg_tasks)) {
4269 it->task_pos = cset->mg_tasks.next;
4270 it->cur_tasks_head = &cset->mg_tasks;
4272 it->task_pos = cset->dying_tasks.next;
4273 it->cur_tasks_head = &cset->dying_tasks;
4276 it->tasks_head = &cset->tasks;
4277 it->mg_tasks_head = &cset->mg_tasks;
4278 it->dying_tasks_head = &cset->dying_tasks;
4281 * We don't keep css_sets locked across iteration steps and thus
4282 * need to take steps to ensure that iteration can be resumed after
4283 * the lock is re-acquired. Iteration is performed at two levels -
4284 * css_sets and tasks in them.
4286 * Once created, a css_set never leaves its cgroup lists, so a
4287 * pinned css_set is guaranteed to stay put and we can resume
4288 * iteration afterwards.
4290 * Tasks may leave @cset across iteration steps. This is resolved
4291 * by registering each iterator with the css_set currently being
4292 * walked and making css_set_move_task() advance iterators whose
4293 * next task is leaving.
4296 list_del(&it->iters_node);
4297 put_css_set_locked(it->cur_cset);
4300 it->cur_cset = cset;
4301 list_add(&it->iters_node, &cset->task_iters);
4304 static void css_task_iter_skip(struct css_task_iter *it,
4305 struct task_struct *task)
4307 lockdep_assert_held(&css_set_lock);
4309 if (it->task_pos == &task->cg_list) {
4310 it->task_pos = it->task_pos->next;
4311 it->flags |= CSS_TASK_ITER_SKIPPED;
4315 static void css_task_iter_advance(struct css_task_iter *it)
4317 struct task_struct *task;
4319 lockdep_assert_held(&css_set_lock);
4323 * Advance iterator to find next entry. cset->tasks is
4324 * consumed first and then ->mg_tasks. After ->mg_tasks,
4325 * we move onto the next cset.
4327 if (it->flags & CSS_TASK_ITER_SKIPPED)
4328 it->flags &= ~CSS_TASK_ITER_SKIPPED;
4330 it->task_pos = it->task_pos->next;
4332 if (it->task_pos == it->tasks_head) {
4333 it->task_pos = it->mg_tasks_head->next;
4334 it->cur_tasks_head = it->mg_tasks_head;
4336 if (it->task_pos == it->mg_tasks_head) {
4337 it->task_pos = it->dying_tasks_head->next;
4338 it->cur_tasks_head = it->dying_tasks_head;
4340 if (it->task_pos == it->dying_tasks_head)
4341 css_task_iter_advance_css_set(it);
4343 /* called from start, proceed to the first cset */
4344 css_task_iter_advance_css_set(it);
4350 task = list_entry(it->task_pos, struct task_struct, cg_list);
4352 if (it->flags & CSS_TASK_ITER_PROCS) {
4353 /* if PROCS, skip over tasks which aren't group leaders */
4354 if (!thread_group_leader(task))
4357 /* and dying leaders w/o live member threads */
4358 if (it->cur_tasks_head == it->dying_tasks_head &&
4359 !atomic_read(&task->signal->live))
4362 /* skip all dying ones */
4363 if (it->cur_tasks_head == it->dying_tasks_head)
4369 * css_task_iter_start - initiate task iteration
4370 * @css: the css to walk tasks of
4371 * @flags: CSS_TASK_ITER_* flags
4372 * @it: the task iterator to use
4374 * Initiate iteration through the tasks of @css. The caller can call
4375 * css_task_iter_next() to walk through the tasks until the function
4376 * returns NULL. On completion of iteration, css_task_iter_end() must be
4379 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4380 struct css_task_iter *it)
4382 /* no one should try to iterate before mounting cgroups */
4383 WARN_ON_ONCE(!use_task_css_set_links);
4385 memset(it, 0, sizeof(*it));
4387 spin_lock_irq(&css_set_lock);
4393 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4395 it->cset_pos = &css->cgroup->cset_links;
4397 it->cset_head = it->cset_pos;
4399 css_task_iter_advance(it);
4401 spin_unlock_irq(&css_set_lock);
4405 * css_task_iter_next - return the next task for the iterator
4406 * @it: the task iterator being iterated
4408 * The "next" function for task iteration. @it should have been
4409 * initialized via css_task_iter_start(). Returns NULL when the iteration
4412 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4415 put_task_struct(it->cur_task);
4416 it->cur_task = NULL;
4419 spin_lock_irq(&css_set_lock);
4421 /* @it may be half-advanced by skips, finish advancing */
4422 if (it->flags & CSS_TASK_ITER_SKIPPED)
4423 css_task_iter_advance(it);
4426 it->cur_task = list_entry(it->task_pos, struct task_struct,
4428 get_task_struct(it->cur_task);
4429 css_task_iter_advance(it);
4432 spin_unlock_irq(&css_set_lock);
4434 return it->cur_task;
4438 * css_task_iter_end - finish task iteration
4439 * @it: the task iterator to finish
4441 * Finish task iteration started by css_task_iter_start().
4443 void css_task_iter_end(struct css_task_iter *it)
4446 spin_lock_irq(&css_set_lock);
4447 list_del(&it->iters_node);
4448 put_css_set_locked(it->cur_cset);
4449 spin_unlock_irq(&css_set_lock);
4453 put_css_set(it->cur_dcset);
4456 put_task_struct(it->cur_task);
4459 static void cgroup_procs_release(struct kernfs_open_file *of)
4461 struct cgroup_file_ctx *ctx = of->priv;
4463 if (ctx->procs.started)
4464 css_task_iter_end(&ctx->procs.iter);
4467 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
4469 struct kernfs_open_file *of = s->private;
4470 struct cgroup_file_ctx *ctx = of->priv;
4475 return css_task_iter_next(&ctx->procs.iter);
4478 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
4479 unsigned int iter_flags)
4481 struct kernfs_open_file *of = s->private;
4482 struct cgroup *cgrp = seq_css(s)->cgroup;
4483 struct cgroup_file_ctx *ctx = of->priv;
4484 struct css_task_iter *it = &ctx->procs.iter;
4487 * When a seq_file is seeked, it's always traversed sequentially
4488 * from position 0, so we can simply keep iterating on !0 *pos.
4490 if (!ctx->procs.started) {
4491 if (WARN_ON_ONCE((*pos)))
4492 return ERR_PTR(-EINVAL);
4493 css_task_iter_start(&cgrp->self, iter_flags, it);
4494 ctx->procs.started = true;
4495 } else if (!(*pos)) {
4496 css_task_iter_end(it);
4497 css_task_iter_start(&cgrp->self, iter_flags, it);
4499 return it->cur_task;
4501 return cgroup_procs_next(s, NULL, NULL);
4504 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
4506 struct cgroup *cgrp = seq_css(s)->cgroup;
4509 * All processes of a threaded subtree belong to the domain cgroup
4510 * of the subtree. Only threads can be distributed across the
4511 * subtree. Reject reads on cgroup.procs in the subtree proper.
4512 * They're always empty anyway.
4514 if (cgroup_is_threaded(cgrp))
4515 return ERR_PTR(-EOPNOTSUPP);
4517 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
4518 CSS_TASK_ITER_THREADED);
4521 static int cgroup_procs_show(struct seq_file *s, void *v)
4523 seq_printf(s, "%d\n", task_pid_vnr(v));
4527 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
4528 struct cgroup *dst_cgrp,
4529 struct super_block *sb,
4530 struct cgroup_namespace *ns)
4532 struct cgroup *com_cgrp = src_cgrp;
4533 struct inode *inode;
4536 lockdep_assert_held(&cgroup_mutex);
4538 /* find the common ancestor */
4539 while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
4540 com_cgrp = cgroup_parent(com_cgrp);
4542 /* %current should be authorized to migrate to the common ancestor */
4543 inode = kernfs_get_inode(sb, com_cgrp->procs_file.kn);
4547 ret = inode_permission(inode, MAY_WRITE);
4553 * If namespaces are delegation boundaries, %current must be able
4554 * to see both source and destination cgroups from its namespace.
4556 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
4557 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
4558 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
4564 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
4565 char *buf, size_t nbytes, loff_t off)
4567 struct cgroup_file_ctx *ctx = of->priv;
4568 struct cgroup *src_cgrp, *dst_cgrp;
4569 struct task_struct *task;
4570 const struct cred *saved_cred;
4573 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4577 task = cgroup_procs_write_start(buf, true);
4578 ret = PTR_ERR_OR_ZERO(task);
4582 /* find the source cgroup */
4583 spin_lock_irq(&css_set_lock);
4584 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4585 spin_unlock_irq(&css_set_lock);
4588 * Process and thread migrations follow same delegation rule. Check
4589 * permissions using the credentials from file open to protect against
4590 * inherited fd attacks.
4592 saved_cred = override_creds(of->file->f_cred);
4593 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4594 of->file->f_path.dentry->d_sb,
4596 revert_creds(saved_cred);
4600 ret = cgroup_attach_task(dst_cgrp, task, true);
4603 cgroup_procs_write_finish(task);
4605 cgroup_kn_unlock(of->kn);
4607 return ret ?: nbytes;
4610 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
4612 return __cgroup_procs_start(s, pos, 0);
4615 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
4616 char *buf, size_t nbytes, loff_t off)
4618 struct cgroup_file_ctx *ctx = of->priv;
4619 struct cgroup *src_cgrp, *dst_cgrp;
4620 struct task_struct *task;
4621 const struct cred *saved_cred;
4624 buf = strstrip(buf);
4626 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4630 task = cgroup_procs_write_start(buf, false);
4631 ret = PTR_ERR_OR_ZERO(task);
4635 /* find the source cgroup */
4636 spin_lock_irq(&css_set_lock);
4637 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4638 spin_unlock_irq(&css_set_lock);
4641 * Process and thread migrations follow same delegation rule. Check
4642 * permissions using the credentials from file open to protect against
4643 * inherited fd attacks.
4645 saved_cred = override_creds(of->file->f_cred);
4646 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4647 of->file->f_path.dentry->d_sb,
4649 revert_creds(saved_cred);
4653 /* and must be contained in the same domain */
4655 if (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp)
4658 ret = cgroup_attach_task(dst_cgrp, task, false);
4661 cgroup_procs_write_finish(task);
4663 cgroup_kn_unlock(of->kn);
4665 return ret ?: nbytes;
4668 /* cgroup core interface files for the default hierarchy */
4669 static struct cftype cgroup_base_files[] = {
4671 .name = "cgroup.type",
4672 .flags = CFTYPE_NOT_ON_ROOT,
4673 .seq_show = cgroup_type_show,
4674 .write = cgroup_type_write,
4677 .name = "cgroup.procs",
4678 .flags = CFTYPE_NS_DELEGATABLE,
4679 .file_offset = offsetof(struct cgroup, procs_file),
4680 .release = cgroup_procs_release,
4681 .seq_start = cgroup_procs_start,
4682 .seq_next = cgroup_procs_next,
4683 .seq_show = cgroup_procs_show,
4684 .write = cgroup_procs_write,
4687 .name = "cgroup.threads",
4688 .flags = CFTYPE_NS_DELEGATABLE,
4689 .release = cgroup_procs_release,
4690 .seq_start = cgroup_threads_start,
4691 .seq_next = cgroup_procs_next,
4692 .seq_show = cgroup_procs_show,
4693 .write = cgroup_threads_write,
4696 .name = "cgroup.controllers",
4697 .seq_show = cgroup_controllers_show,
4700 .name = "cgroup.subtree_control",
4701 .flags = CFTYPE_NS_DELEGATABLE,
4702 .seq_show = cgroup_subtree_control_show,
4703 .write = cgroup_subtree_control_write,
4706 .name = "cgroup.events",
4707 .flags = CFTYPE_NOT_ON_ROOT,
4708 .file_offset = offsetof(struct cgroup, events_file),
4709 .seq_show = cgroup_events_show,
4712 .name = "cgroup.max.descendants",
4713 .seq_show = cgroup_max_descendants_show,
4714 .write = cgroup_max_descendants_write,
4717 .name = "cgroup.max.depth",
4718 .seq_show = cgroup_max_depth_show,
4719 .write = cgroup_max_depth_write,
4722 .name = "cgroup.stat",
4723 .seq_show = cgroup_stat_show,
4727 .flags = CFTYPE_NOT_ON_ROOT,
4728 .seq_show = cpu_stat_show,
4734 * css destruction is four-stage process.
4736 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4737 * Implemented in kill_css().
4739 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4740 * and thus css_tryget_online() is guaranteed to fail, the css can be
4741 * offlined by invoking offline_css(). After offlining, the base ref is
4742 * put. Implemented in css_killed_work_fn().
4744 * 3. When the percpu_ref reaches zero, the only possible remaining
4745 * accessors are inside RCU read sections. css_release() schedules the
4748 * 4. After the grace period, the css can be freed. Implemented in
4749 * css_free_work_fn().
4751 * It is actually hairier because both step 2 and 4 require process context
4752 * and thus involve punting to css->destroy_work adding two additional
4753 * steps to the already complex sequence.
4755 static void css_free_rwork_fn(struct work_struct *work)
4757 struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
4758 struct cgroup_subsys_state, destroy_rwork);
4759 struct cgroup_subsys *ss = css->ss;
4760 struct cgroup *cgrp = css->cgroup;
4762 percpu_ref_exit(&css->refcnt);
4766 struct cgroup_subsys_state *parent = css->parent;
4770 cgroup_idr_remove(&ss->css_idr, id);
4776 /* cgroup free path */
4777 atomic_dec(&cgrp->root->nr_cgrps);
4778 cgroup1_pidlist_destroy_all(cgrp);
4779 cancel_work_sync(&cgrp->release_agent_work);
4781 if (cgroup_parent(cgrp)) {
4783 * We get a ref to the parent, and put the ref when
4784 * this cgroup is being freed, so it's guaranteed
4785 * that the parent won't be destroyed before its
4788 cgroup_put(cgroup_parent(cgrp));
4789 kernfs_put(cgrp->kn);
4790 if (cgroup_on_dfl(cgrp))
4791 cgroup_rstat_exit(cgrp);
4795 * This is root cgroup's refcnt reaching zero,
4796 * which indicates that the root should be
4799 cgroup_destroy_root(cgrp->root);
4804 static void css_release_work_fn(struct work_struct *work)
4806 struct cgroup_subsys_state *css =
4807 container_of(work, struct cgroup_subsys_state, destroy_work);
4808 struct cgroup_subsys *ss = css->ss;
4809 struct cgroup *cgrp = css->cgroup;
4811 mutex_lock(&cgroup_mutex);
4813 css->flags |= CSS_RELEASED;
4814 list_del_rcu(&css->sibling);
4817 /* css release path */
4818 if (!list_empty(&css->rstat_css_node)) {
4819 cgroup_rstat_flush(cgrp);
4820 list_del_rcu(&css->rstat_css_node);
4823 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4824 if (ss->css_released)
4825 ss->css_released(css);
4827 struct cgroup *tcgrp;
4829 /* cgroup release path */
4830 TRACE_CGROUP_PATH(release, cgrp);
4832 if (cgroup_on_dfl(cgrp))
4833 cgroup_rstat_flush(cgrp);
4835 spin_lock_irq(&css_set_lock);
4836 for (tcgrp = cgroup_parent(cgrp); tcgrp;
4837 tcgrp = cgroup_parent(tcgrp))
4838 tcgrp->nr_dying_descendants--;
4839 spin_unlock_irq(&css_set_lock);
4841 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4845 * There are two control paths which try to determine
4846 * cgroup from dentry without going through kernfs -
4847 * cgroupstats_build() and css_tryget_online_from_dir().
4848 * Those are supported by RCU protecting clearing of
4849 * cgrp->kn->priv backpointer.
4852 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
4855 cgroup_bpf_put(cgrp);
4858 mutex_unlock(&cgroup_mutex);
4860 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
4861 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
4864 static void css_release(struct percpu_ref *ref)
4866 struct cgroup_subsys_state *css =
4867 container_of(ref, struct cgroup_subsys_state, refcnt);
4869 INIT_WORK(&css->destroy_work, css_release_work_fn);
4870 queue_work(cgroup_destroy_wq, &css->destroy_work);
4873 static void init_and_link_css(struct cgroup_subsys_state *css,
4874 struct cgroup_subsys *ss, struct cgroup *cgrp)
4876 lockdep_assert_held(&cgroup_mutex);
4878 cgroup_get_live(cgrp);
4880 memset(css, 0, sizeof(*css));
4884 INIT_LIST_HEAD(&css->sibling);
4885 INIT_LIST_HEAD(&css->children);
4886 INIT_LIST_HEAD(&css->rstat_css_node);
4887 css->serial_nr = css_serial_nr_next++;
4888 atomic_set(&css->online_cnt, 0);
4890 if (cgroup_parent(cgrp)) {
4891 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4892 css_get(css->parent);
4895 if (cgroup_on_dfl(cgrp) && ss->css_rstat_flush)
4896 list_add_rcu(&css->rstat_css_node, &cgrp->rstat_css_list);
4898 BUG_ON(cgroup_css(cgrp, ss));
4901 /* invoke ->css_online() on a new CSS and mark it online if successful */
4902 static int online_css(struct cgroup_subsys_state *css)
4904 struct cgroup_subsys *ss = css->ss;
4907 lockdep_assert_held(&cgroup_mutex);
4910 ret = ss->css_online(css);
4912 css->flags |= CSS_ONLINE;
4913 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4915 atomic_inc(&css->online_cnt);
4917 atomic_inc(&css->parent->online_cnt);
4922 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4923 static void offline_css(struct cgroup_subsys_state *css)
4925 struct cgroup_subsys *ss = css->ss;
4927 lockdep_assert_held(&cgroup_mutex);
4929 if (!(css->flags & CSS_ONLINE))
4932 if (ss->css_offline)
4933 ss->css_offline(css);
4935 css->flags &= ~CSS_ONLINE;
4936 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4938 wake_up_all(&css->cgroup->offline_waitq);
4942 * css_create - create a cgroup_subsys_state
4943 * @cgrp: the cgroup new css will be associated with
4944 * @ss: the subsys of new css
4946 * Create a new css associated with @cgrp - @ss pair. On success, the new
4947 * css is online and installed in @cgrp. This function doesn't create the
4948 * interface files. Returns 0 on success, -errno on failure.
4950 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
4951 struct cgroup_subsys *ss)
4953 struct cgroup *parent = cgroup_parent(cgrp);
4954 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4955 struct cgroup_subsys_state *css;
4958 lockdep_assert_held(&cgroup_mutex);
4960 css = ss->css_alloc(parent_css);
4962 css = ERR_PTR(-ENOMEM);
4966 init_and_link_css(css, ss, cgrp);
4968 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4972 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
4977 /* @css is ready to be brought online now, make it visible */
4978 list_add_tail_rcu(&css->sibling, &parent_css->children);
4979 cgroup_idr_replace(&ss->css_idr, css, css->id);
4981 err = online_css(css);
4985 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4986 cgroup_parent(parent)) {
4987 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4988 current->comm, current->pid, ss->name);
4989 if (!strcmp(ss->name, "memory"))
4990 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4991 ss->warned_broken_hierarchy = true;
4997 list_del_rcu(&css->sibling);
4999 list_del_rcu(&css->rstat_css_node);
5000 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5001 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
5002 return ERR_PTR(err);
5006 * The returned cgroup is fully initialized including its control mask, but
5007 * it isn't associated with its kernfs_node and doesn't have the control
5010 static struct cgroup *cgroup_create(struct cgroup *parent)
5012 struct cgroup_root *root = parent->root;
5013 struct cgroup *cgrp, *tcgrp;
5014 int level = parent->level + 1;
5017 /* allocate the cgroup and its ID, 0 is reserved for the root */
5018 cgrp = kzalloc(struct_size(cgrp, ancestor_ids, (level + 1)),
5021 return ERR_PTR(-ENOMEM);
5023 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
5027 if (cgroup_on_dfl(parent)) {
5028 ret = cgroup_rstat_init(cgrp);
5030 goto out_cancel_ref;
5034 * Temporarily set the pointer to NULL, so idr_find() won't return
5035 * a half-baked cgroup.
5037 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
5043 init_cgroup_housekeeping(cgrp);
5045 cgrp->self.parent = &parent->self;
5047 cgrp->level = level;
5048 ret = cgroup_bpf_inherit(cgrp);
5052 spin_lock_irq(&css_set_lock);
5053 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5054 cgrp->ancestor_ids[tcgrp->level] = tcgrp->id;
5057 tcgrp->nr_descendants++;
5059 spin_unlock_irq(&css_set_lock);
5061 if (notify_on_release(parent))
5062 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
5064 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
5065 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
5067 cgrp->self.serial_nr = css_serial_nr_next++;
5069 /* allocation complete, commit to creation */
5070 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
5071 atomic_inc(&root->nr_cgrps);
5072 cgroup_get_live(parent);
5075 * @cgrp is now fully operational. If something fails after this
5076 * point, it'll be released via the normal destruction path.
5078 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
5081 * On the default hierarchy, a child doesn't automatically inherit
5082 * subtree_control from the parent. Each is configured manually.
5084 if (!cgroup_on_dfl(cgrp))
5085 cgrp->subtree_control = cgroup_control(cgrp);
5087 cgroup_propagate_control(cgrp);
5092 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
5094 if (cgroup_on_dfl(parent))
5095 cgroup_rstat_exit(cgrp);
5097 percpu_ref_exit(&cgrp->self.refcnt);
5100 return ERR_PTR(ret);
5103 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
5105 struct cgroup *cgroup;
5109 lockdep_assert_held(&cgroup_mutex);
5111 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
5112 if (cgroup->nr_descendants >= cgroup->max_descendants)
5115 if (level > cgroup->max_depth)
5126 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
5128 struct cgroup *parent, *cgrp;
5129 struct kernfs_node *kn;
5132 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
5133 if (strchr(name, '\n'))
5136 parent = cgroup_kn_lock_live(parent_kn, false);
5140 if (!cgroup_check_hierarchy_limits(parent)) {
5145 cgrp = cgroup_create(parent);
5147 ret = PTR_ERR(cgrp);
5151 /* create the directory */
5152 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
5160 * This extra ref will be put in cgroup_free_fn() and guarantees
5161 * that @cgrp->kn is always accessible.
5165 ret = cgroup_kn_set_ugid(kn);
5169 ret = css_populate_dir(&cgrp->self);
5173 ret = cgroup_apply_control_enable(cgrp);
5177 TRACE_CGROUP_PATH(mkdir, cgrp);
5179 /* let's create and online css's */
5180 kernfs_activate(kn);
5186 cgroup_destroy_locked(cgrp);
5188 cgroup_kn_unlock(parent_kn);
5193 * This is called when the refcnt of a css is confirmed to be killed.
5194 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
5195 * initate destruction and put the css ref from kill_css().
5197 static void css_killed_work_fn(struct work_struct *work)
5199 struct cgroup_subsys_state *css =
5200 container_of(work, struct cgroup_subsys_state, destroy_work);
5202 mutex_lock(&cgroup_mutex);
5207 /* @css can't go away while we're holding cgroup_mutex */
5209 } while (css && atomic_dec_and_test(&css->online_cnt));
5211 mutex_unlock(&cgroup_mutex);
5214 /* css kill confirmation processing requires process context, bounce */
5215 static void css_killed_ref_fn(struct percpu_ref *ref)
5217 struct cgroup_subsys_state *css =
5218 container_of(ref, struct cgroup_subsys_state, refcnt);
5220 if (atomic_dec_and_test(&css->online_cnt)) {
5221 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5222 queue_work(cgroup_destroy_wq, &css->destroy_work);
5227 * kill_css - destroy a css
5228 * @css: css to destroy
5230 * This function initiates destruction of @css by removing cgroup interface
5231 * files and putting its base reference. ->css_offline() will be invoked
5232 * asynchronously once css_tryget_online() is guaranteed to fail and when
5233 * the reference count reaches zero, @css will be released.
5235 static void kill_css(struct cgroup_subsys_state *css)
5237 lockdep_assert_held(&cgroup_mutex);
5239 if (css->flags & CSS_DYING)
5242 css->flags |= CSS_DYING;
5245 * This must happen before css is disassociated with its cgroup.
5246 * See seq_css() for details.
5251 * Killing would put the base ref, but we need to keep it alive
5252 * until after ->css_offline().
5257 * cgroup core guarantees that, by the time ->css_offline() is
5258 * invoked, no new css reference will be given out via
5259 * css_tryget_online(). We can't simply call percpu_ref_kill() and
5260 * proceed to offlining css's because percpu_ref_kill() doesn't
5261 * guarantee that the ref is seen as killed on all CPUs on return.
5263 * Use percpu_ref_kill_and_confirm() to get notifications as each
5264 * css is confirmed to be seen as killed on all CPUs.
5266 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5270 * cgroup_destroy_locked - the first stage of cgroup destruction
5271 * @cgrp: cgroup to be destroyed
5273 * css's make use of percpu refcnts whose killing latency shouldn't be
5274 * exposed to userland and are RCU protected. Also, cgroup core needs to
5275 * guarantee that css_tryget_online() won't succeed by the time
5276 * ->css_offline() is invoked. To satisfy all the requirements,
5277 * destruction is implemented in the following two steps.
5279 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
5280 * userland visible parts and start killing the percpu refcnts of
5281 * css's. Set up so that the next stage will be kicked off once all
5282 * the percpu refcnts are confirmed to be killed.
5284 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5285 * rest of destruction. Once all cgroup references are gone, the
5286 * cgroup is RCU-freed.
5288 * This function implements s1. After this step, @cgrp is gone as far as
5289 * the userland is concerned and a new cgroup with the same name may be
5290 * created. As cgroup doesn't care about the names internally, this
5291 * doesn't cause any problem.
5293 static int cgroup_destroy_locked(struct cgroup *cgrp)
5294 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5296 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5297 struct cgroup_subsys_state *css;
5298 struct cgrp_cset_link *link;
5301 lockdep_assert_held(&cgroup_mutex);
5304 * Only migration can raise populated from zero and we're already
5305 * holding cgroup_mutex.
5307 if (cgroup_is_populated(cgrp))
5311 * Make sure there's no live children. We can't test emptiness of
5312 * ->self.children as dead children linger on it while being
5313 * drained; otherwise, "rmdir parent/child parent" may fail.
5315 if (css_has_online_children(&cgrp->self))
5319 * Mark @cgrp and the associated csets dead. The former prevents
5320 * further task migration and child creation by disabling
5321 * cgroup_lock_live_group(). The latter makes the csets ignored by
5322 * the migration path.
5324 cgrp->self.flags &= ~CSS_ONLINE;
5326 spin_lock_irq(&css_set_lock);
5327 list_for_each_entry(link, &cgrp->cset_links, cset_link)
5328 link->cset->dead = true;
5329 spin_unlock_irq(&css_set_lock);
5331 /* initiate massacre of all css's */
5332 for_each_css(css, ssid, cgrp)
5335 /* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
5336 css_clear_dir(&cgrp->self);
5337 kernfs_remove(cgrp->kn);
5339 if (parent && cgroup_is_threaded(cgrp))
5340 parent->nr_threaded_children--;
5342 spin_lock_irq(&css_set_lock);
5343 for (tcgrp = cgroup_parent(cgrp); tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5344 tcgrp->nr_descendants--;
5345 tcgrp->nr_dying_descendants++;
5347 spin_unlock_irq(&css_set_lock);
5349 cgroup1_check_for_release(parent);
5351 /* put the base reference */
5352 percpu_ref_kill(&cgrp->self.refcnt);
5357 int cgroup_rmdir(struct kernfs_node *kn)
5359 struct cgroup *cgrp;
5362 cgrp = cgroup_kn_lock_live(kn, false);
5366 ret = cgroup_destroy_locked(cgrp);
5368 TRACE_CGROUP_PATH(rmdir, cgrp);
5370 cgroup_kn_unlock(kn);
5374 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5375 .show_options = cgroup_show_options,
5376 .remount_fs = cgroup_remount,
5377 .mkdir = cgroup_mkdir,
5378 .rmdir = cgroup_rmdir,
5379 .show_path = cgroup_show_path,
5382 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5384 struct cgroup_subsys_state *css;
5386 pr_debug("Initializing cgroup subsys %s\n", ss->name);
5388 mutex_lock(&cgroup_mutex);
5390 idr_init(&ss->css_idr);
5391 INIT_LIST_HEAD(&ss->cfts);
5393 /* Create the root cgroup state for this subsystem */
5394 ss->root = &cgrp_dfl_root;
5395 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5396 /* We don't handle early failures gracefully */
5397 BUG_ON(IS_ERR(css));
5398 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5401 * Root csses are never destroyed and we can't initialize
5402 * percpu_ref during early init. Disable refcnting.
5404 css->flags |= CSS_NO_REF;
5407 /* allocation can't be done safely during early init */
5410 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5411 BUG_ON(css->id < 0);
5414 /* Update the init_css_set to contain a subsys
5415 * pointer to this state - since the subsystem is
5416 * newly registered, all tasks and hence the
5417 * init_css_set is in the subsystem's root cgroup. */
5418 init_css_set.subsys[ss->id] = css;
5420 have_fork_callback |= (bool)ss->fork << ss->id;
5421 have_exit_callback |= (bool)ss->exit << ss->id;
5422 have_release_callback |= (bool)ss->release << ss->id;
5423 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5425 /* At system boot, before all subsystems have been
5426 * registered, no tasks have been forked, so we don't
5427 * need to invoke fork callbacks here. */
5428 BUG_ON(!list_empty(&init_task.tasks));
5430 BUG_ON(online_css(css));
5432 mutex_unlock(&cgroup_mutex);
5436 * cgroup_init_early - cgroup initialization at system boot
5438 * Initialize cgroups at system boot, and initialize any
5439 * subsystems that request early init.
5441 int __init cgroup_init_early(void)
5443 static struct cgroup_sb_opts __initdata opts;
5444 struct cgroup_subsys *ss;
5447 init_cgroup_root(&cgrp_dfl_root, &opts);
5448 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5450 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5452 for_each_subsys(ss, i) {
5453 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5454 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
5455 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5457 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5458 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5461 ss->name = cgroup_subsys_name[i];
5462 if (!ss->legacy_name)
5463 ss->legacy_name = cgroup_subsys_name[i];
5466 cgroup_init_subsys(ss, true);
5472 * cgroup_init - cgroup initialization
5474 * Register cgroup filesystem and /proc file, and initialize
5475 * any subsystems that didn't request early init.
5477 int __init cgroup_init(void)
5479 struct cgroup_subsys *ss;
5482 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
5483 BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
5484 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
5485 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
5487 cgroup_rstat_boot();
5490 * The latency of the synchronize_sched() is too high for cgroups,
5491 * avoid it at the cost of forcing all readers into the slow path.
5493 rcu_sync_enter_start(&cgroup_threadgroup_rwsem.rss);
5495 get_user_ns(init_cgroup_ns.user_ns);
5497 mutex_lock(&cgroup_mutex);
5500 * Add init_css_set to the hash table so that dfl_root can link to
5503 hash_add(css_set_table, &init_css_set.hlist,
5504 css_set_hash(init_css_set.subsys));
5506 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0, 0));
5508 mutex_unlock(&cgroup_mutex);
5510 for_each_subsys(ss, ssid) {
5511 if (ss->early_init) {
5512 struct cgroup_subsys_state *css =
5513 init_css_set.subsys[ss->id];
5515 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5517 BUG_ON(css->id < 0);
5519 cgroup_init_subsys(ss, false);
5522 list_add_tail(&init_css_set.e_cset_node[ssid],
5523 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5526 * Setting dfl_root subsys_mask needs to consider the
5527 * disabled flag and cftype registration needs kmalloc,
5528 * both of which aren't available during early_init.
5530 if (!cgroup_ssid_enabled(ssid))
5533 if (cgroup1_ssid_disabled(ssid))
5534 printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
5537 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5539 /* implicit controllers must be threaded too */
5540 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
5542 if (ss->implicit_on_dfl)
5543 cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
5544 else if (!ss->dfl_cftypes)
5545 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
5548 cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
5550 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5551 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5553 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5554 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5558 ss->bind(init_css_set.subsys[ssid]);
5560 mutex_lock(&cgroup_mutex);
5561 css_populate_dir(init_css_set.subsys[ssid]);
5562 mutex_unlock(&cgroup_mutex);
5565 /* init_css_set.subsys[] has been updated, re-hash */
5566 hash_del(&init_css_set.hlist);
5567 hash_add(css_set_table, &init_css_set.hlist,
5568 css_set_hash(init_css_set.subsys));
5570 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
5571 WARN_ON(register_filesystem(&cgroup_fs_type));
5572 WARN_ON(register_filesystem(&cgroup2_fs_type));
5573 WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show));
5578 static int __init cgroup_wq_init(void)
5581 * There isn't much point in executing destruction path in
5582 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5583 * Use 1 for @max_active.
5585 * We would prefer to do this in cgroup_init() above, but that
5586 * is called before init_workqueues(): so leave this until after.
5588 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5589 BUG_ON(!cgroup_destroy_wq);
5592 core_initcall(cgroup_wq_init);
5594 void cgroup_path_from_kernfs_id(const union kernfs_node_id *id,
5595 char *buf, size_t buflen)
5597 struct kernfs_node *kn;
5599 kn = kernfs_get_node_by_id(cgrp_dfl_root.kf_root, id);
5602 kernfs_path(kn, buf, buflen);
5607 * proc_cgroup_show()
5608 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5609 * - Used for /proc/<pid>/cgroup.
5611 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5612 struct pid *pid, struct task_struct *tsk)
5616 struct cgroup_root *root;
5619 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5623 mutex_lock(&cgroup_mutex);
5624 spin_lock_irq(&css_set_lock);
5626 for_each_root(root) {
5627 struct cgroup_subsys *ss;
5628 struct cgroup *cgrp;
5629 int ssid, count = 0;
5631 if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
5634 seq_printf(m, "%d:", root->hierarchy_id);
5635 if (root != &cgrp_dfl_root)
5636 for_each_subsys(ss, ssid)
5637 if (root->subsys_mask & (1 << ssid))
5638 seq_printf(m, "%s%s", count++ ? "," : "",
5640 if (strlen(root->name))
5641 seq_printf(m, "%sname=%s", count ? "," : "",
5645 cgrp = task_cgroup_from_root(tsk, root);
5648 * On traditional hierarchies, all zombie tasks show up as
5649 * belonging to the root cgroup. On the default hierarchy,
5650 * while a zombie doesn't show up in "cgroup.procs" and
5651 * thus can't be migrated, its /proc/PID/cgroup keeps
5652 * reporting the cgroup it belonged to before exiting. If
5653 * the cgroup is removed before the zombie is reaped,
5654 * " (deleted)" is appended to the cgroup path.
5656 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
5657 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
5658 current->nsproxy->cgroup_ns);
5659 if (retval >= PATH_MAX)
5660 retval = -ENAMETOOLONG;
5669 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
5670 seq_puts(m, " (deleted)\n");
5677 spin_unlock_irq(&css_set_lock);
5678 mutex_unlock(&cgroup_mutex);
5685 * cgroup_fork - initialize cgroup related fields during copy_process()
5686 * @child: pointer to task_struct of forking parent process.
5688 * A task is associated with the init_css_set until cgroup_post_fork()
5689 * attaches it to the parent's css_set. Empty cg_list indicates that
5690 * @child isn't holding reference to its css_set.
5692 void cgroup_fork(struct task_struct *child)
5694 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5695 INIT_LIST_HEAD(&child->cg_list);
5699 * cgroup_can_fork - called on a new task before the process is exposed
5700 * @child: the task in question.
5702 * This calls the subsystem can_fork() callbacks. If the can_fork() callback
5703 * returns an error, the fork aborts with that error code. This allows for
5704 * a cgroup subsystem to conditionally allow or deny new forks.
5706 int cgroup_can_fork(struct task_struct *child)
5708 struct cgroup_subsys *ss;
5711 do_each_subsys_mask(ss, i, have_canfork_callback) {
5712 ret = ss->can_fork(child);
5715 } while_each_subsys_mask();
5720 for_each_subsys(ss, j) {
5723 if (ss->cancel_fork)
5724 ss->cancel_fork(child);
5731 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
5732 * @child: the task in question
5734 * This calls the cancel_fork() callbacks if a fork failed *after*
5735 * cgroup_can_fork() succeded.
5737 void cgroup_cancel_fork(struct task_struct *child)
5739 struct cgroup_subsys *ss;
5742 for_each_subsys(ss, i)
5743 if (ss->cancel_fork)
5744 ss->cancel_fork(child);
5748 * cgroup_post_fork - called on a new task after adding it to the task list
5749 * @child: the task in question
5751 * Adds the task to the list running through its css_set if necessary and
5752 * call the subsystem fork() callbacks. Has to be after the task is
5753 * visible on the task list in case we race with the first call to
5754 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5757 void cgroup_post_fork(struct task_struct *child)
5759 struct cgroup_subsys *ss;
5763 * This may race against cgroup_enable_task_cg_lists(). As that
5764 * function sets use_task_css_set_links before grabbing
5765 * tasklist_lock and we just went through tasklist_lock to add
5766 * @child, it's guaranteed that either we see the set
5767 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5768 * @child during its iteration.
5770 * If we won the race, @child is associated with %current's
5771 * css_set. Grabbing css_set_lock guarantees both that the
5772 * association is stable, and, on completion of the parent's
5773 * migration, @child is visible in the source of migration or
5774 * already in the destination cgroup. This guarantee is necessary
5775 * when implementing operations which need to migrate all tasks of
5776 * a cgroup to another.
5778 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5779 * will remain in init_css_set. This is safe because all tasks are
5780 * in the init_css_set before cg_links is enabled and there's no
5781 * operation which transfers all tasks out of init_css_set.
5783 if (use_task_css_set_links) {
5784 struct css_set *cset;
5786 spin_lock_irq(&css_set_lock);
5787 cset = task_css_set(current);
5788 if (list_empty(&child->cg_list)) {
5791 css_set_move_task(child, NULL, cset, false);
5793 spin_unlock_irq(&css_set_lock);
5797 * Call ss->fork(). This must happen after @child is linked on
5798 * css_set; otherwise, @child might change state between ->fork()
5799 * and addition to css_set.
5801 do_each_subsys_mask(ss, i, have_fork_callback) {
5803 } while_each_subsys_mask();
5807 * cgroup_exit - detach cgroup from exiting task
5808 * @tsk: pointer to task_struct of exiting process
5810 * Description: Detach cgroup from @tsk and release it.
5812 * Note that cgroups marked notify_on_release force every task in
5813 * them to take the global cgroup_mutex mutex when exiting.
5814 * This could impact scaling on very large systems. Be reluctant to
5815 * use notify_on_release cgroups where very high task exit scaling
5816 * is required on large systems.
5818 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5819 * call cgroup_exit() while the task is still competent to handle
5820 * notify_on_release(), then leave the task attached to the root cgroup in
5821 * each hierarchy for the remainder of its exit. No need to bother with
5822 * init_css_set refcnting. init_css_set never goes away and we can't race
5823 * with migration path - PF_EXITING is visible to migration path.
5825 void cgroup_exit(struct task_struct *tsk)
5827 struct cgroup_subsys *ss;
5828 struct css_set *cset;
5832 * Unlink from @tsk from its css_set. As migration path can't race
5833 * with us, we can check css_set and cg_list without synchronization.
5835 cset = task_css_set(tsk);
5837 if (!list_empty(&tsk->cg_list)) {
5838 spin_lock_irq(&css_set_lock);
5839 css_set_move_task(tsk, cset, NULL, false);
5840 list_add_tail(&tsk->cg_list, &cset->dying_tasks);
5842 spin_unlock_irq(&css_set_lock);
5847 /* see cgroup_post_fork() for details */
5848 do_each_subsys_mask(ss, i, have_exit_callback) {
5850 } while_each_subsys_mask();
5853 void cgroup_release(struct task_struct *task)
5855 struct cgroup_subsys *ss;
5858 do_each_subsys_mask(ss, ssid, have_release_callback) {
5860 } while_each_subsys_mask();
5862 if (use_task_css_set_links) {
5863 spin_lock_irq(&css_set_lock);
5864 css_set_skip_task_iters(task_css_set(task), task);
5865 list_del_init(&task->cg_list);
5866 spin_unlock_irq(&css_set_lock);
5870 void cgroup_free(struct task_struct *task)
5872 struct css_set *cset = task_css_set(task);
5876 static int __init cgroup_disable(char *str)
5878 struct cgroup_subsys *ss;
5882 while ((token = strsep(&str, ",")) != NULL) {
5886 for_each_subsys(ss, i) {
5887 if (strcmp(token, ss->name) &&
5888 strcmp(token, ss->legacy_name))
5891 static_branch_disable(cgroup_subsys_enabled_key[i]);
5892 pr_info("Disabling %s control group subsystem\n",
5898 __setup("cgroup_disable=", cgroup_disable);
5901 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5902 * @dentry: directory dentry of interest
5903 * @ss: subsystem of interest
5905 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5906 * to get the corresponding css and return it. If such css doesn't exist
5907 * or can't be pinned, an ERR_PTR value is returned.
5909 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5910 struct cgroup_subsys *ss)
5912 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5913 struct file_system_type *s_type = dentry->d_sb->s_type;
5914 struct cgroup_subsys_state *css = NULL;
5915 struct cgroup *cgrp;
5917 /* is @dentry a cgroup dir? */
5918 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
5919 !kn || kernfs_type(kn) != KERNFS_DIR)
5920 return ERR_PTR(-EBADF);
5925 * This path doesn't originate from kernfs and @kn could already
5926 * have been or be removed at any point. @kn->priv is RCU
5927 * protected for this access. See css_release_work_fn() for details.
5929 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
5931 css = cgroup_css(cgrp, ss);
5933 if (!css || !css_tryget_online(css))
5934 css = ERR_PTR(-ENOENT);
5941 * css_from_id - lookup css by id
5942 * @id: the cgroup id
5943 * @ss: cgroup subsys to be looked into
5945 * Returns the css if there's valid one with @id, otherwise returns NULL.
5946 * Should be called under rcu_read_lock().
5948 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5950 WARN_ON_ONCE(!rcu_read_lock_held());
5951 return idr_find(&ss->css_idr, id);
5955 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
5956 * @path: path on the default hierarchy
5958 * Find the cgroup at @path on the default hierarchy, increment its
5959 * reference count and return it. Returns pointer to the found cgroup on
5960 * success, ERR_PTR(-ENOENT) if @path doens't exist and ERR_PTR(-ENOTDIR)
5961 * if @path points to a non-directory.
5963 struct cgroup *cgroup_get_from_path(const char *path)
5965 struct kernfs_node *kn;
5966 struct cgroup *cgrp;
5968 mutex_lock(&cgroup_mutex);
5970 kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
5972 if (kernfs_type(kn) == KERNFS_DIR) {
5974 cgroup_get_live(cgrp);
5976 cgrp = ERR_PTR(-ENOTDIR);
5980 cgrp = ERR_PTR(-ENOENT);
5983 mutex_unlock(&cgroup_mutex);
5986 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
5989 * cgroup_get_from_fd - get a cgroup pointer from a fd
5990 * @fd: fd obtained by open(cgroup2_dir)
5992 * Find the cgroup from a fd which should be obtained
5993 * by opening a cgroup directory. Returns a pointer to the
5994 * cgroup on success. ERR_PTR is returned if the cgroup
5997 struct cgroup *cgroup_get_from_fd(int fd)
5999 struct cgroup_subsys_state *css;
6000 struct cgroup *cgrp;
6005 return ERR_PTR(-EBADF);
6007 css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
6010 return ERR_CAST(css);
6013 if (!cgroup_on_dfl(cgrp)) {
6015 return ERR_PTR(-EBADF);
6020 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
6023 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
6024 * definition in cgroup-defs.h.
6026 #ifdef CONFIG_SOCK_CGROUP_DATA
6028 #if defined(CONFIG_CGROUP_NET_PRIO) || defined(CONFIG_CGROUP_NET_CLASSID)
6030 DEFINE_SPINLOCK(cgroup_sk_update_lock);
6031 static bool cgroup_sk_alloc_disabled __read_mostly;
6033 void cgroup_sk_alloc_disable(void)
6035 if (cgroup_sk_alloc_disabled)
6037 pr_info("cgroup: disabling cgroup2 socket matching due to net_prio or net_cls activation\n");
6038 cgroup_sk_alloc_disabled = true;
6043 #define cgroup_sk_alloc_disabled false
6047 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
6049 if (cgroup_sk_alloc_disabled) {
6050 skcd->no_refcnt = 1;
6054 /* Don't associate the sock with unrelated interrupted task's cgroup. */
6061 struct css_set *cset;
6063 cset = task_css_set(current);
6064 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
6065 skcd->val = (unsigned long)cset->dfl_cgrp;
6074 void cgroup_sk_clone(struct sock_cgroup_data *skcd)
6076 /* Socket clone path */
6078 if (skcd->no_refcnt)
6081 * We might be cloning a socket which is left in an empty
6082 * cgroup and the cgroup might have already been rmdir'd.
6083 * Don't use cgroup_get_live().
6085 cgroup_get(sock_cgroup_ptr(skcd));
6089 void cgroup_sk_free(struct sock_cgroup_data *skcd)
6091 if (skcd->no_refcnt)
6094 cgroup_put(sock_cgroup_ptr(skcd));
6097 #endif /* CONFIG_SOCK_CGROUP_DATA */
6099 #ifdef CONFIG_CGROUP_BPF
6100 int cgroup_bpf_attach(struct cgroup *cgrp, struct bpf_prog *prog,
6101 enum bpf_attach_type type, u32 flags)
6105 mutex_lock(&cgroup_mutex);
6106 ret = __cgroup_bpf_attach(cgrp, prog, type, flags);
6107 mutex_unlock(&cgroup_mutex);
6110 int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
6111 enum bpf_attach_type type, u32 flags)
6115 mutex_lock(&cgroup_mutex);
6116 ret = __cgroup_bpf_detach(cgrp, prog, type, flags);
6117 mutex_unlock(&cgroup_mutex);
6120 int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
6121 union bpf_attr __user *uattr)
6125 mutex_lock(&cgroup_mutex);
6126 ret = __cgroup_bpf_query(cgrp, attr, uattr);
6127 mutex_unlock(&cgroup_mutex);
6130 #endif /* CONFIG_CGROUP_BPF */
6133 static ssize_t show_delegatable_files(struct cftype *files, char *buf,
6134 ssize_t size, const char *prefix)
6139 for (cft = files; cft && cft->name[0] != '\0'; cft++) {
6140 if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
6144 ret += snprintf(buf + ret, size - ret, "%s.", prefix);
6146 ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
6148 if (unlikely(ret >= size)) {
6157 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
6160 struct cgroup_subsys *ss;
6164 ret = show_delegatable_files(cgroup_base_files, buf, PAGE_SIZE - ret,
6167 for_each_subsys(ss, ssid)
6168 ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
6170 cgroup_subsys_name[ssid]);
6174 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
6176 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
6179 return snprintf(buf, PAGE_SIZE, "nsdelegate\n");
6181 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
6183 static struct attribute *cgroup_sysfs_attrs[] = {
6184 &cgroup_delegate_attr.attr,
6185 &cgroup_features_attr.attr,
6189 static const struct attribute_group cgroup_sysfs_attr_group = {
6190 .attrs = cgroup_sysfs_attrs,
6194 static int __init cgroup_sysfs_init(void)
6196 return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
6198 subsys_initcall(cgroup_sysfs_init);
6199 #endif /* CONFIG_SYSFS */