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/bpf-cgroup.h>
34 #include <linux/cred.h>
35 #include <linux/errno.h>
36 #include <linux/init_task.h>
37 #include <linux/kernel.h>
38 #include <linux/magic.h>
39 #include <linux/mutex.h>
40 #include <linux/mount.h>
41 #include <linux/pagemap.h>
42 #include <linux/proc_fs.h>
43 #include <linux/rcupdate.h>
44 #include <linux/sched.h>
45 #include <linux/sched/task.h>
46 #include <linux/slab.h>
47 #include <linux/spinlock.h>
48 #include <linux/percpu-rwsem.h>
49 #include <linux/string.h>
50 #include <linux/hashtable.h>
51 #include <linux/idr.h>
52 #include <linux/kthread.h>
53 #include <linux/atomic.h>
54 #include <linux/cpuset.h>
55 #include <linux/proc_ns.h>
56 #include <linux/nsproxy.h>
57 #include <linux/file.h>
58 #include <linux/fs_parser.h>
59 #include <linux/sched/cputime.h>
60 #include <linux/sched/deadline.h>
61 #include <linux/psi.h>
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/cgroup.h>
67 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
69 /* let's not notify more than 100 times per second */
70 #define CGROUP_FILE_NOTIFY_MIN_INTV DIV_ROUND_UP(HZ, 100)
73 * To avoid confusing the compiler (and generating warnings) with code
74 * that attempts to access what would be a 0-element array (i.e. sized
75 * to a potentially empty array when CGROUP_SUBSYS_COUNT == 0), this
76 * constant expression can be added.
78 #define CGROUP_HAS_SUBSYS_CONFIG (CGROUP_SUBSYS_COUNT > 0)
81 * cgroup_mutex is the master lock. Any modification to cgroup or its
82 * hierarchy must be performed while holding it.
84 * css_set_lock protects task->cgroups pointer, the list of css_set
85 * objects, and the chain of tasks off each css_set.
87 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
88 * cgroup.h can use them for lockdep annotations.
90 DEFINE_MUTEX(cgroup_mutex);
91 DEFINE_SPINLOCK(css_set_lock);
93 #ifdef CONFIG_PROVE_RCU
94 EXPORT_SYMBOL_GPL(cgroup_mutex);
95 EXPORT_SYMBOL_GPL(css_set_lock);
98 DEFINE_SPINLOCK(trace_cgroup_path_lock);
99 char trace_cgroup_path[TRACE_CGROUP_PATH_LEN];
100 static bool cgroup_debug __read_mostly;
103 * Protects cgroup_idr and css_idr so that IDs can be released without
104 * grabbing cgroup_mutex.
106 static DEFINE_SPINLOCK(cgroup_idr_lock);
109 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
110 * against file removal/re-creation across css hiding.
112 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
114 DEFINE_PERCPU_RWSEM(cgroup_threadgroup_rwsem);
116 #define cgroup_assert_mutex_or_rcu_locked() \
117 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
118 !lockdep_is_held(&cgroup_mutex), \
119 "cgroup_mutex or RCU read lock required");
122 * cgroup destruction makes heavy use of work items and there can be a lot
123 * of concurrent destructions. Use a separate workqueue so that cgroup
124 * destruction work items don't end up filling up max_active of system_wq
125 * which may lead to deadlock.
127 static struct workqueue_struct *cgroup_destroy_wq;
129 /* generate an array of cgroup subsystem pointers */
130 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
131 struct cgroup_subsys *cgroup_subsys[] = {
132 #include <linux/cgroup_subsys.h>
136 /* array of cgroup subsystem names */
137 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
138 static const char *cgroup_subsys_name[] = {
139 #include <linux/cgroup_subsys.h>
143 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
145 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
146 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
147 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
148 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
149 #include <linux/cgroup_subsys.h>
152 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
153 static struct static_key_true *cgroup_subsys_enabled_key[] = {
154 #include <linux/cgroup_subsys.h>
158 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
159 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
160 #include <linux/cgroup_subsys.h>
164 static DEFINE_PER_CPU(struct cgroup_rstat_cpu, cgrp_dfl_root_rstat_cpu);
166 /* the default hierarchy */
167 struct cgroup_root cgrp_dfl_root = { .cgrp.rstat_cpu = &cgrp_dfl_root_rstat_cpu };
168 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
171 * The default hierarchy always exists but is hidden until mounted for the
172 * first time. This is for backward compatibility.
174 static bool cgrp_dfl_visible;
176 /* some controllers are not supported in the default hierarchy */
177 static u16 cgrp_dfl_inhibit_ss_mask;
179 /* some controllers are implicitly enabled on the default hierarchy */
180 static u16 cgrp_dfl_implicit_ss_mask;
182 /* some controllers can be threaded on the default hierarchy */
183 static u16 cgrp_dfl_threaded_ss_mask;
185 /* The list of hierarchy roots */
186 LIST_HEAD(cgroup_roots);
187 static int cgroup_root_count;
189 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
190 static DEFINE_IDR(cgroup_hierarchy_idr);
193 * Assign a monotonically increasing serial number to csses. It guarantees
194 * cgroups with bigger numbers are newer than those with smaller numbers.
195 * Also, as csses are always appended to the parent's ->children list, it
196 * guarantees that sibling csses are always sorted in the ascending serial
197 * number order on the list. Protected by cgroup_mutex.
199 static u64 css_serial_nr_next = 1;
202 * These bitmasks identify subsystems with specific features to avoid
203 * having to do iterative checks repeatedly.
205 static u16 have_fork_callback __read_mostly;
206 static u16 have_exit_callback __read_mostly;
207 static u16 have_release_callback __read_mostly;
208 static u16 have_canfork_callback __read_mostly;
210 /* cgroup namespace for init task */
211 struct cgroup_namespace init_cgroup_ns = {
212 .ns.count = REFCOUNT_INIT(2),
213 .user_ns = &init_user_ns,
214 .ns.ops = &cgroupns_operations,
215 .ns.inum = PROC_CGROUP_INIT_INO,
216 .root_cset = &init_css_set,
219 static struct file_system_type cgroup2_fs_type;
220 static struct cftype cgroup_base_files[];
221 static struct cftype cgroup_psi_files[];
223 /* cgroup optional features */
224 enum cgroup_opt_features {
226 OPT_FEATURE_PRESSURE,
231 static const char *cgroup_opt_feature_names[OPT_FEATURE_COUNT] = {
237 static u16 cgroup_feature_disable_mask __read_mostly;
239 static int cgroup_apply_control(struct cgroup *cgrp);
240 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
241 static void css_task_iter_skip(struct css_task_iter *it,
242 struct task_struct *task);
243 static int cgroup_destroy_locked(struct cgroup *cgrp);
244 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
245 struct cgroup_subsys *ss);
246 static void css_release(struct percpu_ref *ref);
247 static void kill_css(struct cgroup_subsys_state *css);
248 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
249 struct cgroup *cgrp, struct cftype cfts[],
252 #ifdef CONFIG_DEBUG_CGROUP_REF
253 #define CGROUP_REF_FN_ATTRS noinline
254 #define CGROUP_REF_EXPORT(fn) EXPORT_SYMBOL_GPL(fn);
255 #include <linux/cgroup_refcnt.h>
259 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
260 * @ssid: subsys ID of interest
262 * cgroup_subsys_enabled() can only be used with literal subsys names which
263 * is fine for individual subsystems but unsuitable for cgroup core. This
264 * is slower static_key_enabled() based test indexed by @ssid.
266 bool cgroup_ssid_enabled(int ssid)
268 if (!CGROUP_HAS_SUBSYS_CONFIG)
271 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
275 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
276 * @cgrp: the cgroup of interest
278 * The default hierarchy is the v2 interface of cgroup and this function
279 * can be used to test whether a cgroup is on the default hierarchy for
280 * cases where a subsystem should behave differently depending on the
283 * List of changed behaviors:
285 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
286 * and "name" are disallowed.
288 * - When mounting an existing superblock, mount options should match.
290 * - rename(2) is disallowed.
292 * - "tasks" is removed. Everything should be at process granularity. Use
293 * "cgroup.procs" instead.
295 * - "cgroup.procs" is not sorted. pids will be unique unless they got
296 * recycled in-between reads.
298 * - "release_agent" and "notify_on_release" are removed. Replacement
299 * notification mechanism will be implemented.
301 * - "cgroup.clone_children" is removed.
303 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
304 * and its descendants contain no task; otherwise, 1. The file also
305 * generates kernfs notification which can be monitored through poll and
306 * [di]notify when the value of the file changes.
308 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
309 * take masks of ancestors with non-empty cpus/mems, instead of being
310 * moved to an ancestor.
312 * - cpuset: a task can be moved into an empty cpuset, and again it takes
313 * masks of ancestors.
315 * - blkcg: blk-throttle becomes properly hierarchical.
317 bool cgroup_on_dfl(const struct cgroup *cgrp)
319 return cgrp->root == &cgrp_dfl_root;
322 /* IDR wrappers which synchronize using cgroup_idr_lock */
323 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
328 idr_preload(gfp_mask);
329 spin_lock_bh(&cgroup_idr_lock);
330 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
331 spin_unlock_bh(&cgroup_idr_lock);
336 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
340 spin_lock_bh(&cgroup_idr_lock);
341 ret = idr_replace(idr, ptr, id);
342 spin_unlock_bh(&cgroup_idr_lock);
346 static void cgroup_idr_remove(struct idr *idr, int id)
348 spin_lock_bh(&cgroup_idr_lock);
350 spin_unlock_bh(&cgroup_idr_lock);
353 static bool cgroup_has_tasks(struct cgroup *cgrp)
355 return cgrp->nr_populated_csets;
358 static bool cgroup_is_threaded(struct cgroup *cgrp)
360 return cgrp->dom_cgrp != cgrp;
363 /* can @cgrp host both domain and threaded children? */
364 static bool cgroup_is_mixable(struct cgroup *cgrp)
367 * Root isn't under domain level resource control exempting it from
368 * the no-internal-process constraint, so it can serve as a thread
369 * root and a parent of resource domains at the same time.
371 return !cgroup_parent(cgrp);
374 /* can @cgrp become a thread root? Should always be true for a thread root */
375 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
377 /* mixables don't care */
378 if (cgroup_is_mixable(cgrp))
381 /* domain roots can't be nested under threaded */
382 if (cgroup_is_threaded(cgrp))
385 /* can only have either domain or threaded children */
386 if (cgrp->nr_populated_domain_children)
389 /* and no domain controllers can be enabled */
390 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
396 /* is @cgrp root of a threaded subtree? */
397 static bool cgroup_is_thread_root(struct cgroup *cgrp)
399 /* thread root should be a domain */
400 if (cgroup_is_threaded(cgrp))
403 /* a domain w/ threaded children is a thread root */
404 if (cgrp->nr_threaded_children)
408 * A domain which has tasks and explicit threaded controllers
409 * enabled is a thread root.
411 if (cgroup_has_tasks(cgrp) &&
412 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
418 /* a domain which isn't connected to the root w/o brekage can't be used */
419 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
421 /* the cgroup itself can be a thread root */
422 if (cgroup_is_threaded(cgrp))
425 /* but the ancestors can't be unless mixable */
426 while ((cgrp = cgroup_parent(cgrp))) {
427 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
429 if (cgroup_is_threaded(cgrp))
436 /* subsystems visibly enabled on a cgroup */
437 static u16 cgroup_control(struct cgroup *cgrp)
439 struct cgroup *parent = cgroup_parent(cgrp);
440 u16 root_ss_mask = cgrp->root->subsys_mask;
443 u16 ss_mask = parent->subtree_control;
445 /* threaded cgroups can only have threaded controllers */
446 if (cgroup_is_threaded(cgrp))
447 ss_mask &= cgrp_dfl_threaded_ss_mask;
451 if (cgroup_on_dfl(cgrp))
452 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
453 cgrp_dfl_implicit_ss_mask);
457 /* subsystems enabled on a cgroup */
458 static u16 cgroup_ss_mask(struct cgroup *cgrp)
460 struct cgroup *parent = cgroup_parent(cgrp);
463 u16 ss_mask = parent->subtree_ss_mask;
465 /* threaded cgroups can only have threaded controllers */
466 if (cgroup_is_threaded(cgrp))
467 ss_mask &= cgrp_dfl_threaded_ss_mask;
471 return cgrp->root->subsys_mask;
475 * cgroup_css - obtain a cgroup's css for the specified subsystem
476 * @cgrp: the cgroup of interest
477 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
479 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
480 * function must be called either under cgroup_mutex or rcu_read_lock() and
481 * the caller is responsible for pinning the returned css if it wants to
482 * keep accessing it outside the said locks. This function may return
483 * %NULL if @cgrp doesn't have @subsys_id enabled.
485 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
486 struct cgroup_subsys *ss)
488 if (CGROUP_HAS_SUBSYS_CONFIG && ss)
489 return rcu_dereference_check(cgrp->subsys[ss->id],
490 lockdep_is_held(&cgroup_mutex));
496 * cgroup_e_css_by_mask - obtain a cgroup's effective css for the specified ss
497 * @cgrp: the cgroup of interest
498 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
500 * Similar to cgroup_css() but returns the effective css, which is defined
501 * as the matching css of the nearest ancestor including self which has @ss
502 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
503 * function is guaranteed to return non-NULL css.
505 static struct cgroup_subsys_state *cgroup_e_css_by_mask(struct cgroup *cgrp,
506 struct cgroup_subsys *ss)
508 lockdep_assert_held(&cgroup_mutex);
514 * This function is used while updating css associations and thus
515 * can't test the csses directly. Test ss_mask.
517 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
518 cgrp = cgroup_parent(cgrp);
523 return cgroup_css(cgrp, ss);
527 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
528 * @cgrp: the cgroup of interest
529 * @ss: the subsystem of interest
531 * Find and get the effective css of @cgrp for @ss. The effective css is
532 * defined as the matching css of the nearest ancestor including self which
533 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
534 * the root css is returned, so this function always returns a valid css.
536 * The returned css is not guaranteed to be online, and therefore it is the
537 * callers responsibility to try get a reference for it.
539 struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
540 struct cgroup_subsys *ss)
542 struct cgroup_subsys_state *css;
544 if (!CGROUP_HAS_SUBSYS_CONFIG)
548 css = cgroup_css(cgrp, ss);
552 cgrp = cgroup_parent(cgrp);
555 return init_css_set.subsys[ss->id];
559 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
560 * @cgrp: the cgroup of interest
561 * @ss: the subsystem of interest
563 * Find and get the effective css of @cgrp for @ss. The effective css is
564 * defined as the matching css of the nearest ancestor including self which
565 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
566 * the root css is returned, so this function always returns a valid css.
567 * The returned css must be put using css_put().
569 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
570 struct cgroup_subsys *ss)
572 struct cgroup_subsys_state *css;
574 if (!CGROUP_HAS_SUBSYS_CONFIG)
580 css = cgroup_css(cgrp, ss);
582 if (css && css_tryget_online(css))
584 cgrp = cgroup_parent(cgrp);
587 css = init_css_set.subsys[ss->id];
593 EXPORT_SYMBOL_GPL(cgroup_get_e_css);
595 static void cgroup_get_live(struct cgroup *cgrp)
597 WARN_ON_ONCE(cgroup_is_dead(cgrp));
602 * __cgroup_task_count - count the number of tasks in a cgroup. The caller
603 * is responsible for taking the css_set_lock.
604 * @cgrp: the cgroup in question
606 int __cgroup_task_count(const struct cgroup *cgrp)
609 struct cgrp_cset_link *link;
611 lockdep_assert_held(&css_set_lock);
613 list_for_each_entry(link, &cgrp->cset_links, cset_link)
614 count += link->cset->nr_tasks;
620 * cgroup_task_count - count the number of tasks in a cgroup.
621 * @cgrp: the cgroup in question
623 int cgroup_task_count(const struct cgroup *cgrp)
627 spin_lock_irq(&css_set_lock);
628 count = __cgroup_task_count(cgrp);
629 spin_unlock_irq(&css_set_lock);
634 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
636 struct cgroup *cgrp = of->kn->parent->priv;
637 struct cftype *cft = of_cft(of);
640 * This is open and unprotected implementation of cgroup_css().
641 * seq_css() is only called from a kernfs file operation which has
642 * an active reference on the file. Because all the subsystem
643 * files are drained before a css is disassociated with a cgroup,
644 * the matching css from the cgroup's subsys table is guaranteed to
645 * be and stay valid until the enclosing operation is complete.
647 if (CGROUP_HAS_SUBSYS_CONFIG && cft->ss)
648 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
652 EXPORT_SYMBOL_GPL(of_css);
655 * for_each_css - iterate all css's of a cgroup
656 * @css: the iteration cursor
657 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
658 * @cgrp: the target cgroup to iterate css's of
660 * Should be called under cgroup_mutex.
662 #define for_each_css(css, ssid, cgrp) \
663 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
664 if (!((css) = rcu_dereference_check( \
665 (cgrp)->subsys[(ssid)], \
666 lockdep_is_held(&cgroup_mutex)))) { } \
670 * do_each_subsys_mask - filter for_each_subsys with a bitmask
671 * @ss: the iteration cursor
672 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
673 * @ss_mask: the bitmask
675 * The block will only run for cases where the ssid-th bit (1 << ssid) of
678 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
679 unsigned long __ss_mask = (ss_mask); \
680 if (!CGROUP_HAS_SUBSYS_CONFIG) { \
684 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
685 (ss) = cgroup_subsys[ssid]; \
688 #define while_each_subsys_mask() \
693 /* iterate over child cgrps, lock should be held throughout iteration */
694 #define cgroup_for_each_live_child(child, cgrp) \
695 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
696 if (({ lockdep_assert_held(&cgroup_mutex); \
697 cgroup_is_dead(child); })) \
701 /* walk live descendants in pre order */
702 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
703 css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
704 if (({ lockdep_assert_held(&cgroup_mutex); \
705 (dsct) = (d_css)->cgroup; \
706 cgroup_is_dead(dsct); })) \
710 /* walk live descendants in postorder */
711 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
712 css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
713 if (({ lockdep_assert_held(&cgroup_mutex); \
714 (dsct) = (d_css)->cgroup; \
715 cgroup_is_dead(dsct); })) \
720 * The default css_set - used by init and its children prior to any
721 * hierarchies being mounted. It contains a pointer to the root state
722 * for each subsystem. Also used to anchor the list of css_sets. Not
723 * reference-counted, to improve performance when child cgroups
724 * haven't been created.
726 struct css_set init_css_set = {
727 .refcount = REFCOUNT_INIT(1),
728 .dom_cset = &init_css_set,
729 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
730 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
731 .dying_tasks = LIST_HEAD_INIT(init_css_set.dying_tasks),
732 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
733 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
734 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
735 .mg_src_preload_node = LIST_HEAD_INIT(init_css_set.mg_src_preload_node),
736 .mg_dst_preload_node = LIST_HEAD_INIT(init_css_set.mg_dst_preload_node),
737 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
740 * The following field is re-initialized when this cset gets linked
741 * in cgroup_init(). However, let's initialize the field
742 * statically too so that the default cgroup can be accessed safely
745 .dfl_cgrp = &cgrp_dfl_root.cgrp,
748 static int css_set_count = 1; /* 1 for init_css_set */
750 static bool css_set_threaded(struct css_set *cset)
752 return cset->dom_cset != cset;
756 * css_set_populated - does a css_set contain any tasks?
757 * @cset: target css_set
759 * css_set_populated() should be the same as !!cset->nr_tasks at steady
760 * state. However, css_set_populated() can be called while a task is being
761 * added to or removed from the linked list before the nr_tasks is
762 * properly updated. Hence, we can't just look at ->nr_tasks here.
764 static bool css_set_populated(struct css_set *cset)
766 lockdep_assert_held(&css_set_lock);
768 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
772 * cgroup_update_populated - update the populated count of a cgroup
773 * @cgrp: the target cgroup
774 * @populated: inc or dec populated count
776 * One of the css_sets associated with @cgrp is either getting its first
777 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
778 * count is propagated towards root so that a given cgroup's
779 * nr_populated_children is zero iff none of its descendants contain any
782 * @cgrp's interface file "cgroup.populated" is zero if both
783 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
784 * 1 otherwise. When the sum changes from or to zero, userland is notified
785 * that the content of the interface file has changed. This can be used to
786 * detect when @cgrp and its descendants become populated or empty.
788 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
790 struct cgroup *child = NULL;
791 int adj = populated ? 1 : -1;
793 lockdep_assert_held(&css_set_lock);
796 bool was_populated = cgroup_is_populated(cgrp);
799 cgrp->nr_populated_csets += adj;
801 if (cgroup_is_threaded(child))
802 cgrp->nr_populated_threaded_children += adj;
804 cgrp->nr_populated_domain_children += adj;
807 if (was_populated == cgroup_is_populated(cgrp))
810 cgroup1_check_for_release(cgrp);
811 TRACE_CGROUP_PATH(notify_populated, cgrp,
812 cgroup_is_populated(cgrp));
813 cgroup_file_notify(&cgrp->events_file);
816 cgrp = cgroup_parent(cgrp);
821 * css_set_update_populated - update populated state of a css_set
822 * @cset: target css_set
823 * @populated: whether @cset is populated or depopulated
825 * @cset is either getting the first task or losing the last. Update the
826 * populated counters of all associated cgroups accordingly.
828 static void css_set_update_populated(struct css_set *cset, bool populated)
830 struct cgrp_cset_link *link;
832 lockdep_assert_held(&css_set_lock);
834 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
835 cgroup_update_populated(link->cgrp, populated);
839 * @task is leaving, advance task iterators which are pointing to it so
840 * that they can resume at the next position. Advancing an iterator might
841 * remove it from the list, use safe walk. See css_task_iter_skip() for
844 static void css_set_skip_task_iters(struct css_set *cset,
845 struct task_struct *task)
847 struct css_task_iter *it, *pos;
849 list_for_each_entry_safe(it, pos, &cset->task_iters, iters_node)
850 css_task_iter_skip(it, task);
854 * css_set_move_task - move a task from one css_set to another
855 * @task: task being moved
856 * @from_cset: css_set @task currently belongs to (may be NULL)
857 * @to_cset: new css_set @task is being moved to (may be NULL)
858 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
860 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
861 * css_set, @from_cset can be NULL. If @task is being disassociated
862 * instead of moved, @to_cset can be NULL.
864 * This function automatically handles populated counter updates and
865 * css_task_iter adjustments but the caller is responsible for managing
866 * @from_cset and @to_cset's reference counts.
868 static void css_set_move_task(struct task_struct *task,
869 struct css_set *from_cset, struct css_set *to_cset,
872 lockdep_assert_held(&css_set_lock);
874 if (to_cset && !css_set_populated(to_cset))
875 css_set_update_populated(to_cset, true);
878 WARN_ON_ONCE(list_empty(&task->cg_list));
880 css_set_skip_task_iters(from_cset, task);
881 list_del_init(&task->cg_list);
882 if (!css_set_populated(from_cset))
883 css_set_update_populated(from_cset, false);
885 WARN_ON_ONCE(!list_empty(&task->cg_list));
890 * We are synchronized through cgroup_threadgroup_rwsem
891 * against PF_EXITING setting such that we can't race
892 * against cgroup_exit()/cgroup_free() dropping the css_set.
894 WARN_ON_ONCE(task->flags & PF_EXITING);
896 cgroup_move_task(task, to_cset);
897 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
903 * hash table for cgroup groups. This improves the performance to find
904 * an existing css_set. This hash doesn't (currently) take into
905 * account cgroups in empty hierarchies.
907 #define CSS_SET_HASH_BITS 7
908 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
910 static unsigned long css_set_hash(struct cgroup_subsys_state **css)
912 unsigned long key = 0UL;
913 struct cgroup_subsys *ss;
916 for_each_subsys(ss, i)
917 key += (unsigned long)css[i];
918 key = (key >> 16) ^ key;
923 void put_css_set_locked(struct css_set *cset)
925 struct cgrp_cset_link *link, *tmp_link;
926 struct cgroup_subsys *ss;
929 lockdep_assert_held(&css_set_lock);
931 if (!refcount_dec_and_test(&cset->refcount))
934 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
936 /* This css_set is dead. Unlink it and release cgroup and css refs */
937 for_each_subsys(ss, ssid) {
938 list_del(&cset->e_cset_node[ssid]);
939 css_put(cset->subsys[ssid]);
941 hash_del(&cset->hlist);
944 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
945 list_del(&link->cset_link);
946 list_del(&link->cgrp_link);
947 if (cgroup_parent(link->cgrp))
948 cgroup_put(link->cgrp);
952 if (css_set_threaded(cset)) {
953 list_del(&cset->threaded_csets_node);
954 put_css_set_locked(cset->dom_cset);
957 kfree_rcu(cset, rcu_head);
961 * compare_css_sets - helper function for find_existing_css_set().
962 * @cset: candidate css_set being tested
963 * @old_cset: existing css_set for a task
964 * @new_cgrp: cgroup that's being entered by the task
965 * @template: desired set of css pointers in css_set (pre-calculated)
967 * Returns true if "cset" matches "old_cset" except for the hierarchy
968 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
970 static bool compare_css_sets(struct css_set *cset,
971 struct css_set *old_cset,
972 struct cgroup *new_cgrp,
973 struct cgroup_subsys_state *template[])
975 struct cgroup *new_dfl_cgrp;
976 struct list_head *l1, *l2;
979 * On the default hierarchy, there can be csets which are
980 * associated with the same set of cgroups but different csses.
981 * Let's first ensure that csses match.
983 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
987 /* @cset's domain should match the default cgroup's */
988 if (cgroup_on_dfl(new_cgrp))
989 new_dfl_cgrp = new_cgrp;
991 new_dfl_cgrp = old_cset->dfl_cgrp;
993 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
997 * Compare cgroup pointers in order to distinguish between
998 * different cgroups in hierarchies. As different cgroups may
999 * share the same effective css, this comparison is always
1002 l1 = &cset->cgrp_links;
1003 l2 = &old_cset->cgrp_links;
1005 struct cgrp_cset_link *link1, *link2;
1006 struct cgroup *cgrp1, *cgrp2;
1010 /* See if we reached the end - both lists are equal length. */
1011 if (l1 == &cset->cgrp_links) {
1012 BUG_ON(l2 != &old_cset->cgrp_links);
1015 BUG_ON(l2 == &old_cset->cgrp_links);
1017 /* Locate the cgroups associated with these links. */
1018 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
1019 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
1020 cgrp1 = link1->cgrp;
1021 cgrp2 = link2->cgrp;
1022 /* Hierarchies should be linked in the same order. */
1023 BUG_ON(cgrp1->root != cgrp2->root);
1026 * If this hierarchy is the hierarchy of the cgroup
1027 * that's changing, then we need to check that this
1028 * css_set points to the new cgroup; if it's any other
1029 * hierarchy, then this css_set should point to the
1030 * same cgroup as the old css_set.
1032 if (cgrp1->root == new_cgrp->root) {
1033 if (cgrp1 != new_cgrp)
1044 * find_existing_css_set - init css array and find the matching css_set
1045 * @old_cset: the css_set that we're using before the cgroup transition
1046 * @cgrp: the cgroup that we're moving into
1047 * @template: out param for the new set of csses, should be clear on entry
1049 static struct css_set *find_existing_css_set(struct css_set *old_cset,
1050 struct cgroup *cgrp,
1051 struct cgroup_subsys_state **template)
1053 struct cgroup_root *root = cgrp->root;
1054 struct cgroup_subsys *ss;
1055 struct css_set *cset;
1060 * Build the set of subsystem state objects that we want to see in the
1061 * new css_set. While subsystems can change globally, the entries here
1062 * won't change, so no need for locking.
1064 for_each_subsys(ss, i) {
1065 if (root->subsys_mask & (1UL << i)) {
1067 * @ss is in this hierarchy, so we want the
1068 * effective css from @cgrp.
1070 template[i] = cgroup_e_css_by_mask(cgrp, ss);
1073 * @ss is not in this hierarchy, so we don't want
1074 * to change the css.
1076 template[i] = old_cset->subsys[i];
1080 key = css_set_hash(template);
1081 hash_for_each_possible(css_set_table, cset, hlist, key) {
1082 if (!compare_css_sets(cset, old_cset, cgrp, template))
1085 /* This css_set matches what we need */
1089 /* No existing cgroup group matched */
1093 static void free_cgrp_cset_links(struct list_head *links_to_free)
1095 struct cgrp_cset_link *link, *tmp_link;
1097 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1098 list_del(&link->cset_link);
1104 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1105 * @count: the number of links to allocate
1106 * @tmp_links: list_head the allocated links are put on
1108 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1109 * through ->cset_link. Returns 0 on success or -errno.
1111 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1113 struct cgrp_cset_link *link;
1116 INIT_LIST_HEAD(tmp_links);
1118 for (i = 0; i < count; i++) {
1119 link = kzalloc(sizeof(*link), GFP_KERNEL);
1121 free_cgrp_cset_links(tmp_links);
1124 list_add(&link->cset_link, tmp_links);
1130 * link_css_set - a helper function to link a css_set to a cgroup
1131 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1132 * @cset: the css_set to be linked
1133 * @cgrp: the destination cgroup
1135 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1136 struct cgroup *cgrp)
1138 struct cgrp_cset_link *link;
1140 BUG_ON(list_empty(tmp_links));
1142 if (cgroup_on_dfl(cgrp))
1143 cset->dfl_cgrp = cgrp;
1145 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1150 * Always add links to the tail of the lists so that the lists are
1151 * in chronological order.
1153 list_move_tail(&link->cset_link, &cgrp->cset_links);
1154 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1156 if (cgroup_parent(cgrp))
1157 cgroup_get_live(cgrp);
1161 * find_css_set - return a new css_set with one cgroup updated
1162 * @old_cset: the baseline css_set
1163 * @cgrp: the cgroup to be updated
1165 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1166 * substituted into the appropriate hierarchy.
1168 static struct css_set *find_css_set(struct css_set *old_cset,
1169 struct cgroup *cgrp)
1171 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1172 struct css_set *cset;
1173 struct list_head tmp_links;
1174 struct cgrp_cset_link *link;
1175 struct cgroup_subsys *ss;
1179 lockdep_assert_held(&cgroup_mutex);
1181 /* First see if we already have a cgroup group that matches
1182 * the desired set */
1183 spin_lock_irq(&css_set_lock);
1184 cset = find_existing_css_set(old_cset, cgrp, template);
1187 spin_unlock_irq(&css_set_lock);
1192 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1196 /* Allocate all the cgrp_cset_link objects that we'll need */
1197 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1202 refcount_set(&cset->refcount, 1);
1203 cset->dom_cset = cset;
1204 INIT_LIST_HEAD(&cset->tasks);
1205 INIT_LIST_HEAD(&cset->mg_tasks);
1206 INIT_LIST_HEAD(&cset->dying_tasks);
1207 INIT_LIST_HEAD(&cset->task_iters);
1208 INIT_LIST_HEAD(&cset->threaded_csets);
1209 INIT_HLIST_NODE(&cset->hlist);
1210 INIT_LIST_HEAD(&cset->cgrp_links);
1211 INIT_LIST_HEAD(&cset->mg_src_preload_node);
1212 INIT_LIST_HEAD(&cset->mg_dst_preload_node);
1213 INIT_LIST_HEAD(&cset->mg_node);
1215 /* Copy the set of subsystem state objects generated in
1216 * find_existing_css_set() */
1217 memcpy(cset->subsys, template, sizeof(cset->subsys));
1219 spin_lock_irq(&css_set_lock);
1220 /* Add reference counts and links from the new css_set. */
1221 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1222 struct cgroup *c = link->cgrp;
1224 if (c->root == cgrp->root)
1226 link_css_set(&tmp_links, cset, c);
1229 BUG_ON(!list_empty(&tmp_links));
1233 /* Add @cset to the hash table */
1234 key = css_set_hash(cset->subsys);
1235 hash_add(css_set_table, &cset->hlist, key);
1237 for_each_subsys(ss, ssid) {
1238 struct cgroup_subsys_state *css = cset->subsys[ssid];
1240 list_add_tail(&cset->e_cset_node[ssid],
1241 &css->cgroup->e_csets[ssid]);
1245 spin_unlock_irq(&css_set_lock);
1248 * If @cset should be threaded, look up the matching dom_cset and
1249 * link them up. We first fully initialize @cset then look for the
1250 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1251 * to stay empty until we return.
1253 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1254 struct css_set *dcset;
1256 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1262 spin_lock_irq(&css_set_lock);
1263 cset->dom_cset = dcset;
1264 list_add_tail(&cset->threaded_csets_node,
1265 &dcset->threaded_csets);
1266 spin_unlock_irq(&css_set_lock);
1272 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1274 struct cgroup *root_cgrp = kernfs_root_to_node(kf_root)->priv;
1276 return root_cgrp->root;
1279 void cgroup_favor_dynmods(struct cgroup_root *root, bool favor)
1281 bool favoring = root->flags & CGRP_ROOT_FAVOR_DYNMODS;
1283 /* see the comment above CGRP_ROOT_FAVOR_DYNMODS definition */
1284 if (favor && !favoring) {
1285 rcu_sync_enter(&cgroup_threadgroup_rwsem.rss);
1286 root->flags |= CGRP_ROOT_FAVOR_DYNMODS;
1287 } else if (!favor && favoring) {
1288 rcu_sync_exit(&cgroup_threadgroup_rwsem.rss);
1289 root->flags &= ~CGRP_ROOT_FAVOR_DYNMODS;
1293 static int cgroup_init_root_id(struct cgroup_root *root)
1297 lockdep_assert_held(&cgroup_mutex);
1299 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1303 root->hierarchy_id = id;
1307 static void cgroup_exit_root_id(struct cgroup_root *root)
1309 lockdep_assert_held(&cgroup_mutex);
1311 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1314 void cgroup_free_root(struct cgroup_root *root)
1319 static void cgroup_destroy_root(struct cgroup_root *root)
1321 struct cgroup *cgrp = &root->cgrp;
1322 struct cgrp_cset_link *link, *tmp_link;
1324 trace_cgroup_destroy_root(root);
1326 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1328 BUG_ON(atomic_read(&root->nr_cgrps));
1329 BUG_ON(!list_empty(&cgrp->self.children));
1331 /* Rebind all subsystems back to the default hierarchy */
1332 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1335 * Release all the links from cset_links to this hierarchy's
1338 spin_lock_irq(&css_set_lock);
1340 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1341 list_del(&link->cset_link);
1342 list_del(&link->cgrp_link);
1346 spin_unlock_irq(&css_set_lock);
1348 if (!list_empty(&root->root_list)) {
1349 list_del(&root->root_list);
1350 cgroup_root_count--;
1353 cgroup_favor_dynmods(root, false);
1354 cgroup_exit_root_id(root);
1358 cgroup_rstat_exit(cgrp);
1359 kernfs_destroy_root(root->kf_root);
1360 cgroup_free_root(root);
1364 * Returned cgroup is without refcount but it's valid as long as cset pins it.
1366 static inline struct cgroup *__cset_cgroup_from_root(struct css_set *cset,
1367 struct cgroup_root *root)
1369 struct cgroup *res_cgroup = NULL;
1371 if (cset == &init_css_set) {
1372 res_cgroup = &root->cgrp;
1373 } else if (root == &cgrp_dfl_root) {
1374 res_cgroup = cset->dfl_cgrp;
1376 struct cgrp_cset_link *link;
1377 lockdep_assert_held(&css_set_lock);
1379 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1380 struct cgroup *c = link->cgrp;
1382 if (c->root == root) {
1389 BUG_ON(!res_cgroup);
1394 * look up cgroup associated with current task's cgroup namespace on the
1395 * specified hierarchy
1397 static struct cgroup *
1398 current_cgns_cgroup_from_root(struct cgroup_root *root)
1400 struct cgroup *res = NULL;
1401 struct css_set *cset;
1403 lockdep_assert_held(&css_set_lock);
1407 cset = current->nsproxy->cgroup_ns->root_cset;
1408 res = __cset_cgroup_from_root(cset, root);
1416 * Look up cgroup associated with current task's cgroup namespace on the default
1419 * Unlike current_cgns_cgroup_from_root(), this doesn't need locks:
1420 * - Internal rcu_read_lock is unnecessary because we don't dereference any rcu
1422 * - css_set_lock is not needed because we just read cset->dfl_cgrp.
1423 * - As a bonus returned cgrp is pinned with the current because it cannot
1424 * switch cgroup_ns asynchronously.
1426 static struct cgroup *current_cgns_cgroup_dfl(void)
1428 struct css_set *cset;
1430 if (current->nsproxy) {
1431 cset = current->nsproxy->cgroup_ns->root_cset;
1432 return __cset_cgroup_from_root(cset, &cgrp_dfl_root);
1435 * NOTE: This function may be called from bpf_cgroup_from_id()
1436 * on a task which has already passed exit_task_namespaces() and
1437 * nsproxy == NULL. Fall back to cgrp_dfl_root which will make all
1438 * cgroups visible for lookups.
1440 return &cgrp_dfl_root.cgrp;
1444 /* look up cgroup associated with given css_set on the specified hierarchy */
1445 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1446 struct cgroup_root *root)
1448 lockdep_assert_held(&cgroup_mutex);
1449 lockdep_assert_held(&css_set_lock);
1451 return __cset_cgroup_from_root(cset, root);
1455 * Return the cgroup for "task" from the given hierarchy. Must be
1456 * called with cgroup_mutex and css_set_lock held.
1458 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1459 struct cgroup_root *root)
1462 * No need to lock the task - since we hold css_set_lock the
1463 * task can't change groups.
1465 return cset_cgroup_from_root(task_css_set(task), root);
1469 * A task must hold cgroup_mutex to modify cgroups.
1471 * Any task can increment and decrement the count field without lock.
1472 * So in general, code holding cgroup_mutex can't rely on the count
1473 * field not changing. However, if the count goes to zero, then only
1474 * cgroup_attach_task() can increment it again. Because a count of zero
1475 * means that no tasks are currently attached, therefore there is no
1476 * way a task attached to that cgroup can fork (the other way to
1477 * increment the count). So code holding cgroup_mutex can safely
1478 * assume that if the count is zero, it will stay zero. Similarly, if
1479 * a task holds cgroup_mutex on a cgroup with zero count, it
1480 * knows that the cgroup won't be removed, as cgroup_rmdir()
1483 * A cgroup can only be deleted if both its 'count' of using tasks
1484 * is zero, and its list of 'children' cgroups is empty. Since all
1485 * tasks in the system use _some_ cgroup, and since there is always at
1486 * least one task in the system (init, pid == 1), therefore, root cgroup
1487 * always has either children cgroups and/or using tasks. So we don't
1488 * need a special hack to ensure that root cgroup cannot be deleted.
1490 * P.S. One more locking exception. RCU is used to guard the
1491 * update of a tasks cgroup pointer by cgroup_attach_task()
1494 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1496 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1499 struct cgroup_subsys *ss = cft->ss;
1501 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1502 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
1503 const char *dbg = (cft->flags & CFTYPE_DEBUG) ? ".__DEBUG__." : "";
1505 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s%s.%s",
1506 dbg, cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1509 strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1515 * cgroup_file_mode - deduce file mode of a control file
1516 * @cft: the control file in question
1518 * S_IRUGO for read, S_IWUSR for write.
1520 static umode_t cgroup_file_mode(const struct cftype *cft)
1524 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1527 if (cft->write_u64 || cft->write_s64 || cft->write) {
1528 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1538 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1539 * @subtree_control: the new subtree_control mask to consider
1540 * @this_ss_mask: available subsystems
1542 * On the default hierarchy, a subsystem may request other subsystems to be
1543 * enabled together through its ->depends_on mask. In such cases, more
1544 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1546 * This function calculates which subsystems need to be enabled if
1547 * @subtree_control is to be applied while restricted to @this_ss_mask.
1549 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1551 u16 cur_ss_mask = subtree_control;
1552 struct cgroup_subsys *ss;
1555 lockdep_assert_held(&cgroup_mutex);
1557 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1560 u16 new_ss_mask = cur_ss_mask;
1562 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1563 new_ss_mask |= ss->depends_on;
1564 } while_each_subsys_mask();
1567 * Mask out subsystems which aren't available. This can
1568 * happen only if some depended-upon subsystems were bound
1569 * to non-default hierarchies.
1571 new_ss_mask &= this_ss_mask;
1573 if (new_ss_mask == cur_ss_mask)
1575 cur_ss_mask = new_ss_mask;
1582 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1583 * @kn: the kernfs_node being serviced
1585 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1586 * the method finishes if locking succeeded. Note that once this function
1587 * returns the cgroup returned by cgroup_kn_lock_live() may become
1588 * inaccessible any time. If the caller intends to continue to access the
1589 * cgroup, it should pin it before invoking this function.
1591 void cgroup_kn_unlock(struct kernfs_node *kn)
1593 struct cgroup *cgrp;
1595 if (kernfs_type(kn) == KERNFS_DIR)
1598 cgrp = kn->parent->priv;
1602 kernfs_unbreak_active_protection(kn);
1607 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1608 * @kn: the kernfs_node being serviced
1609 * @drain_offline: perform offline draining on the cgroup
1611 * This helper is to be used by a cgroup kernfs method currently servicing
1612 * @kn. It breaks the active protection, performs cgroup locking and
1613 * verifies that the associated cgroup is alive. Returns the cgroup if
1614 * alive; otherwise, %NULL. A successful return should be undone by a
1615 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1616 * cgroup is drained of offlining csses before return.
1618 * Any cgroup kernfs method implementation which requires locking the
1619 * associated cgroup should use this helper. It avoids nesting cgroup
1620 * locking under kernfs active protection and allows all kernfs operations
1621 * including self-removal.
1623 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1625 struct cgroup *cgrp;
1627 if (kernfs_type(kn) == KERNFS_DIR)
1630 cgrp = kn->parent->priv;
1633 * We're gonna grab cgroup_mutex which nests outside kernfs
1634 * active_ref. cgroup liveliness check alone provides enough
1635 * protection against removal. Ensure @cgrp stays accessible and
1636 * break the active_ref protection.
1638 if (!cgroup_tryget(cgrp))
1640 kernfs_break_active_protection(kn);
1643 cgroup_lock_and_drain_offline(cgrp);
1647 if (!cgroup_is_dead(cgrp))
1650 cgroup_kn_unlock(kn);
1654 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1656 char name[CGROUP_FILE_NAME_MAX];
1658 lockdep_assert_held(&cgroup_mutex);
1660 if (cft->file_offset) {
1661 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1662 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1664 spin_lock_irq(&cgroup_file_kn_lock);
1666 spin_unlock_irq(&cgroup_file_kn_lock);
1668 del_timer_sync(&cfile->notify_timer);
1671 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1675 * css_clear_dir - remove subsys files in a cgroup directory
1678 static void css_clear_dir(struct cgroup_subsys_state *css)
1680 struct cgroup *cgrp = css->cgroup;
1681 struct cftype *cfts;
1683 if (!(css->flags & CSS_VISIBLE))
1686 css->flags &= ~CSS_VISIBLE;
1689 if (cgroup_on_dfl(cgrp)) {
1690 cgroup_addrm_files(css, cgrp,
1691 cgroup_base_files, false);
1692 if (cgroup_psi_enabled())
1693 cgroup_addrm_files(css, cgrp,
1694 cgroup_psi_files, false);
1696 cgroup_addrm_files(css, cgrp,
1697 cgroup1_base_files, false);
1700 list_for_each_entry(cfts, &css->ss->cfts, node)
1701 cgroup_addrm_files(css, cgrp, cfts, false);
1706 * css_populate_dir - create subsys files in a cgroup directory
1709 * On failure, no file is added.
1711 static int css_populate_dir(struct cgroup_subsys_state *css)
1713 struct cgroup *cgrp = css->cgroup;
1714 struct cftype *cfts, *failed_cfts;
1717 if (css->flags & CSS_VISIBLE)
1721 if (cgroup_on_dfl(cgrp)) {
1722 ret = cgroup_addrm_files(&cgrp->self, cgrp,
1723 cgroup_base_files, true);
1727 if (cgroup_psi_enabled()) {
1728 ret = cgroup_addrm_files(&cgrp->self, cgrp,
1729 cgroup_psi_files, true);
1734 cgroup_addrm_files(css, cgrp,
1735 cgroup1_base_files, true);
1738 list_for_each_entry(cfts, &css->ss->cfts, node) {
1739 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1747 css->flags |= CSS_VISIBLE;
1751 list_for_each_entry(cfts, &css->ss->cfts, node) {
1752 if (cfts == failed_cfts)
1754 cgroup_addrm_files(css, cgrp, cfts, false);
1759 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1761 struct cgroup *dcgrp = &dst_root->cgrp;
1762 struct cgroup_subsys *ss;
1764 u16 dfl_disable_ss_mask = 0;
1766 lockdep_assert_held(&cgroup_mutex);
1768 do_each_subsys_mask(ss, ssid, ss_mask) {
1770 * If @ss has non-root csses attached to it, can't move.
1771 * If @ss is an implicit controller, it is exempt from this
1772 * rule and can be stolen.
1774 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1775 !ss->implicit_on_dfl)
1778 /* can't move between two non-dummy roots either */
1779 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1783 * Collect ssid's that need to be disabled from default
1786 if (ss->root == &cgrp_dfl_root)
1787 dfl_disable_ss_mask |= 1 << ssid;
1789 } while_each_subsys_mask();
1791 if (dfl_disable_ss_mask) {
1792 struct cgroup *scgrp = &cgrp_dfl_root.cgrp;
1795 * Controllers from default hierarchy that need to be rebound
1796 * are all disabled together in one go.
1798 cgrp_dfl_root.subsys_mask &= ~dfl_disable_ss_mask;
1799 WARN_ON(cgroup_apply_control(scgrp));
1800 cgroup_finalize_control(scgrp, 0);
1803 do_each_subsys_mask(ss, ssid, ss_mask) {
1804 struct cgroup_root *src_root = ss->root;
1805 struct cgroup *scgrp = &src_root->cgrp;
1806 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1807 struct css_set *cset, *cset_pos;
1808 struct css_task_iter *it;
1810 WARN_ON(!css || cgroup_css(dcgrp, ss));
1812 if (src_root != &cgrp_dfl_root) {
1813 /* disable from the source */
1814 src_root->subsys_mask &= ~(1 << ssid);
1815 WARN_ON(cgroup_apply_control(scgrp));
1816 cgroup_finalize_control(scgrp, 0);
1820 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1821 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1822 ss->root = dst_root;
1823 css->cgroup = dcgrp;
1825 spin_lock_irq(&css_set_lock);
1826 WARN_ON(!list_empty(&dcgrp->e_csets[ss->id]));
1827 list_for_each_entry_safe(cset, cset_pos, &scgrp->e_csets[ss->id],
1828 e_cset_node[ss->id]) {
1829 list_move_tail(&cset->e_cset_node[ss->id],
1830 &dcgrp->e_csets[ss->id]);
1832 * all css_sets of scgrp together in same order to dcgrp,
1833 * patch in-flight iterators to preserve correct iteration.
1834 * since the iterator is always advanced right away and
1835 * finished when it->cset_pos meets it->cset_head, so only
1836 * update it->cset_head is enough here.
1838 list_for_each_entry(it, &cset->task_iters, iters_node)
1839 if (it->cset_head == &scgrp->e_csets[ss->id])
1840 it->cset_head = &dcgrp->e_csets[ss->id];
1842 spin_unlock_irq(&css_set_lock);
1844 if (ss->css_rstat_flush) {
1845 list_del_rcu(&css->rstat_css_node);
1847 list_add_rcu(&css->rstat_css_node,
1848 &dcgrp->rstat_css_list);
1851 /* default hierarchy doesn't enable controllers by default */
1852 dst_root->subsys_mask |= 1 << ssid;
1853 if (dst_root == &cgrp_dfl_root) {
1854 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1856 dcgrp->subtree_control |= 1 << ssid;
1857 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1860 ret = cgroup_apply_control(dcgrp);
1862 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1867 } while_each_subsys_mask();
1869 kernfs_activate(dcgrp->kn);
1873 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1874 struct kernfs_root *kf_root)
1878 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1879 struct cgroup *ns_cgroup;
1881 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1885 spin_lock_irq(&css_set_lock);
1886 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1887 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1888 spin_unlock_irq(&css_set_lock);
1890 if (len >= PATH_MAX)
1893 seq_escape(sf, buf, " \t\n\\");
1900 enum cgroup2_param {
1903 Opt_memory_localevents,
1904 Opt_memory_recursiveprot,
1908 static const struct fs_parameter_spec cgroup2_fs_parameters[] = {
1909 fsparam_flag("nsdelegate", Opt_nsdelegate),
1910 fsparam_flag("favordynmods", Opt_favordynmods),
1911 fsparam_flag("memory_localevents", Opt_memory_localevents),
1912 fsparam_flag("memory_recursiveprot", Opt_memory_recursiveprot),
1916 static int cgroup2_parse_param(struct fs_context *fc, struct fs_parameter *param)
1918 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1919 struct fs_parse_result result;
1922 opt = fs_parse(fc, cgroup2_fs_parameters, param, &result);
1927 case Opt_nsdelegate:
1928 ctx->flags |= CGRP_ROOT_NS_DELEGATE;
1930 case Opt_favordynmods:
1931 ctx->flags |= CGRP_ROOT_FAVOR_DYNMODS;
1933 case Opt_memory_localevents:
1934 ctx->flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1936 case Opt_memory_recursiveprot:
1937 ctx->flags |= CGRP_ROOT_MEMORY_RECURSIVE_PROT;
1943 static void apply_cgroup_root_flags(unsigned int root_flags)
1945 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1946 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1947 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1949 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1951 cgroup_favor_dynmods(&cgrp_dfl_root,
1952 root_flags & CGRP_ROOT_FAVOR_DYNMODS);
1954 if (root_flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
1955 cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1957 cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1959 if (root_flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT)
1960 cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_RECURSIVE_PROT;
1962 cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_RECURSIVE_PROT;
1966 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1968 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1969 seq_puts(seq, ",nsdelegate");
1970 if (cgrp_dfl_root.flags & CGRP_ROOT_FAVOR_DYNMODS)
1971 seq_puts(seq, ",favordynmods");
1972 if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
1973 seq_puts(seq, ",memory_localevents");
1974 if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT)
1975 seq_puts(seq, ",memory_recursiveprot");
1979 static int cgroup_reconfigure(struct fs_context *fc)
1981 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1983 apply_cgroup_root_flags(ctx->flags);
1987 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1989 struct cgroup_subsys *ss;
1992 INIT_LIST_HEAD(&cgrp->self.sibling);
1993 INIT_LIST_HEAD(&cgrp->self.children);
1994 INIT_LIST_HEAD(&cgrp->cset_links);
1995 INIT_LIST_HEAD(&cgrp->pidlists);
1996 mutex_init(&cgrp->pidlist_mutex);
1997 cgrp->self.cgroup = cgrp;
1998 cgrp->self.flags |= CSS_ONLINE;
1999 cgrp->dom_cgrp = cgrp;
2000 cgrp->max_descendants = INT_MAX;
2001 cgrp->max_depth = INT_MAX;
2002 INIT_LIST_HEAD(&cgrp->rstat_css_list);
2003 prev_cputime_init(&cgrp->prev_cputime);
2005 for_each_subsys(ss, ssid)
2006 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
2008 init_waitqueue_head(&cgrp->offline_waitq);
2009 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
2012 void init_cgroup_root(struct cgroup_fs_context *ctx)
2014 struct cgroup_root *root = ctx->root;
2015 struct cgroup *cgrp = &root->cgrp;
2017 INIT_LIST_HEAD(&root->root_list);
2018 atomic_set(&root->nr_cgrps, 1);
2020 init_cgroup_housekeeping(cgrp);
2022 /* DYNMODS must be modified through cgroup_favor_dynmods() */
2023 root->flags = ctx->flags & ~CGRP_ROOT_FAVOR_DYNMODS;
2024 if (ctx->release_agent)
2025 strscpy(root->release_agent_path, ctx->release_agent, PATH_MAX);
2027 strscpy(root->name, ctx->name, MAX_CGROUP_ROOT_NAMELEN);
2028 if (ctx->cpuset_clone_children)
2029 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
2032 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask)
2034 LIST_HEAD(tmp_links);
2035 struct cgroup *root_cgrp = &root->cgrp;
2036 struct kernfs_syscall_ops *kf_sops;
2037 struct css_set *cset;
2040 lockdep_assert_held(&cgroup_mutex);
2042 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
2048 * We're accessing css_set_count without locking css_set_lock here,
2049 * but that's OK - it can only be increased by someone holding
2050 * cgroup_lock, and that's us. Later rebinding may disable
2051 * controllers on the default hierarchy and thus create new csets,
2052 * which can't be more than the existing ones. Allocate 2x.
2054 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
2058 ret = cgroup_init_root_id(root);
2062 kf_sops = root == &cgrp_dfl_root ?
2063 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
2065 root->kf_root = kernfs_create_root(kf_sops,
2066 KERNFS_ROOT_CREATE_DEACTIVATED |
2067 KERNFS_ROOT_SUPPORT_EXPORTOP |
2068 KERNFS_ROOT_SUPPORT_USER_XATTR,
2070 if (IS_ERR(root->kf_root)) {
2071 ret = PTR_ERR(root->kf_root);
2074 root_cgrp->kn = kernfs_root_to_node(root->kf_root);
2075 WARN_ON_ONCE(cgroup_ino(root_cgrp) != 1);
2076 root_cgrp->ancestors[0] = root_cgrp;
2078 ret = css_populate_dir(&root_cgrp->self);
2082 ret = cgroup_rstat_init(root_cgrp);
2086 ret = rebind_subsystems(root, ss_mask);
2090 ret = cgroup_bpf_inherit(root_cgrp);
2093 trace_cgroup_setup_root(root);
2096 * There must be no failure case after here, since rebinding takes
2097 * care of subsystems' refcounts, which are explicitly dropped in
2098 * the failure exit path.
2100 list_add(&root->root_list, &cgroup_roots);
2101 cgroup_root_count++;
2104 * Link the root cgroup in this hierarchy into all the css_set
2107 spin_lock_irq(&css_set_lock);
2108 hash_for_each(css_set_table, i, cset, hlist) {
2109 link_css_set(&tmp_links, cset, root_cgrp);
2110 if (css_set_populated(cset))
2111 cgroup_update_populated(root_cgrp, true);
2113 spin_unlock_irq(&css_set_lock);
2115 BUG_ON(!list_empty(&root_cgrp->self.children));
2116 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
2122 cgroup_rstat_exit(root_cgrp);
2124 kernfs_destroy_root(root->kf_root);
2125 root->kf_root = NULL;
2127 cgroup_exit_root_id(root);
2129 percpu_ref_exit(&root_cgrp->self.refcnt);
2131 free_cgrp_cset_links(&tmp_links);
2135 int cgroup_do_get_tree(struct fs_context *fc)
2137 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2140 ctx->kfc.root = ctx->root->kf_root;
2141 if (fc->fs_type == &cgroup2_fs_type)
2142 ctx->kfc.magic = CGROUP2_SUPER_MAGIC;
2144 ctx->kfc.magic = CGROUP_SUPER_MAGIC;
2145 ret = kernfs_get_tree(fc);
2148 * In non-init cgroup namespace, instead of root cgroup's dentry,
2149 * we return the dentry corresponding to the cgroupns->root_cgrp.
2151 if (!ret && ctx->ns != &init_cgroup_ns) {
2152 struct dentry *nsdentry;
2153 struct super_block *sb = fc->root->d_sb;
2154 struct cgroup *cgrp;
2157 spin_lock_irq(&css_set_lock);
2159 cgrp = cset_cgroup_from_root(ctx->ns->root_cset, ctx->root);
2161 spin_unlock_irq(&css_set_lock);
2164 nsdentry = kernfs_node_dentry(cgrp->kn, sb);
2166 if (IS_ERR(nsdentry)) {
2167 deactivate_locked_super(sb);
2168 ret = PTR_ERR(nsdentry);
2171 fc->root = nsdentry;
2174 if (!ctx->kfc.new_sb_created)
2175 cgroup_put(&ctx->root->cgrp);
2181 * Destroy a cgroup filesystem context.
2183 static void cgroup_fs_context_free(struct fs_context *fc)
2185 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2188 kfree(ctx->release_agent);
2189 put_cgroup_ns(ctx->ns);
2190 kernfs_free_fs_context(fc);
2194 static int cgroup_get_tree(struct fs_context *fc)
2196 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2199 WRITE_ONCE(cgrp_dfl_visible, true);
2200 cgroup_get_live(&cgrp_dfl_root.cgrp);
2201 ctx->root = &cgrp_dfl_root;
2203 ret = cgroup_do_get_tree(fc);
2205 apply_cgroup_root_flags(ctx->flags);
2209 static const struct fs_context_operations cgroup_fs_context_ops = {
2210 .free = cgroup_fs_context_free,
2211 .parse_param = cgroup2_parse_param,
2212 .get_tree = cgroup_get_tree,
2213 .reconfigure = cgroup_reconfigure,
2216 static const struct fs_context_operations cgroup1_fs_context_ops = {
2217 .free = cgroup_fs_context_free,
2218 .parse_param = cgroup1_parse_param,
2219 .get_tree = cgroup1_get_tree,
2220 .reconfigure = cgroup1_reconfigure,
2224 * Initialise the cgroup filesystem creation/reconfiguration context. Notably,
2225 * we select the namespace we're going to use.
2227 static int cgroup_init_fs_context(struct fs_context *fc)
2229 struct cgroup_fs_context *ctx;
2231 ctx = kzalloc(sizeof(struct cgroup_fs_context), GFP_KERNEL);
2235 ctx->ns = current->nsproxy->cgroup_ns;
2236 get_cgroup_ns(ctx->ns);
2237 fc->fs_private = &ctx->kfc;
2238 if (fc->fs_type == &cgroup2_fs_type)
2239 fc->ops = &cgroup_fs_context_ops;
2241 fc->ops = &cgroup1_fs_context_ops;
2242 put_user_ns(fc->user_ns);
2243 fc->user_ns = get_user_ns(ctx->ns->user_ns);
2246 #ifdef CONFIG_CGROUP_FAVOR_DYNMODS
2247 ctx->flags |= CGRP_ROOT_FAVOR_DYNMODS;
2252 static void cgroup_kill_sb(struct super_block *sb)
2254 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2255 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2258 * If @root doesn't have any children, start killing it.
2259 * This prevents new mounts by disabling percpu_ref_tryget_live().
2261 * And don't kill the default root.
2263 if (list_empty(&root->cgrp.self.children) && root != &cgrp_dfl_root &&
2264 !percpu_ref_is_dying(&root->cgrp.self.refcnt)) {
2265 cgroup_bpf_offline(&root->cgrp);
2266 percpu_ref_kill(&root->cgrp.self.refcnt);
2268 cgroup_put(&root->cgrp);
2272 struct file_system_type cgroup_fs_type = {
2274 .init_fs_context = cgroup_init_fs_context,
2275 .parameters = cgroup1_fs_parameters,
2276 .kill_sb = cgroup_kill_sb,
2277 .fs_flags = FS_USERNS_MOUNT,
2280 static struct file_system_type cgroup2_fs_type = {
2282 .init_fs_context = cgroup_init_fs_context,
2283 .parameters = cgroup2_fs_parameters,
2284 .kill_sb = cgroup_kill_sb,
2285 .fs_flags = FS_USERNS_MOUNT,
2288 #ifdef CONFIG_CPUSETS
2289 static const struct fs_context_operations cpuset_fs_context_ops = {
2290 .get_tree = cgroup1_get_tree,
2291 .free = cgroup_fs_context_free,
2295 * This is ugly, but preserves the userspace API for existing cpuset
2296 * users. If someone tries to mount the "cpuset" filesystem, we
2297 * silently switch it to mount "cgroup" instead
2299 static int cpuset_init_fs_context(struct fs_context *fc)
2301 char *agent = kstrdup("/sbin/cpuset_release_agent", GFP_USER);
2302 struct cgroup_fs_context *ctx;
2305 err = cgroup_init_fs_context(fc);
2311 fc->ops = &cpuset_fs_context_ops;
2313 ctx = cgroup_fc2context(fc);
2314 ctx->subsys_mask = 1 << cpuset_cgrp_id;
2315 ctx->flags |= CGRP_ROOT_NOPREFIX;
2316 ctx->release_agent = agent;
2318 get_filesystem(&cgroup_fs_type);
2319 put_filesystem(fc->fs_type);
2320 fc->fs_type = &cgroup_fs_type;
2325 static struct file_system_type cpuset_fs_type = {
2327 .init_fs_context = cpuset_init_fs_context,
2328 .fs_flags = FS_USERNS_MOUNT,
2332 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2333 struct cgroup_namespace *ns)
2335 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2337 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2340 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2341 struct cgroup_namespace *ns)
2346 spin_lock_irq(&css_set_lock);
2348 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2350 spin_unlock_irq(&css_set_lock);
2355 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2358 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2359 * @task: target task
2360 * @buf: the buffer to write the path into
2361 * @buflen: the length of the buffer
2363 * Determine @task's cgroup on the first (the one with the lowest non-zero
2364 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2365 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2366 * cgroup controller callbacks.
2368 * Return value is the same as kernfs_path().
2370 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2372 struct cgroup_root *root;
2373 struct cgroup *cgrp;
2374 int hierarchy_id = 1;
2378 spin_lock_irq(&css_set_lock);
2380 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2383 cgrp = task_cgroup_from_root(task, root);
2384 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2386 /* if no hierarchy exists, everyone is in "/" */
2387 ret = strscpy(buf, "/", buflen);
2390 spin_unlock_irq(&css_set_lock);
2394 EXPORT_SYMBOL_GPL(task_cgroup_path);
2397 * cgroup_attach_lock - Lock for ->attach()
2398 * @lock_threadgroup: whether to down_write cgroup_threadgroup_rwsem
2400 * cgroup migration sometimes needs to stabilize threadgroups against forks and
2401 * exits by write-locking cgroup_threadgroup_rwsem. However, some ->attach()
2402 * implementations (e.g. cpuset), also need to disable CPU hotplug.
2403 * Unfortunately, letting ->attach() operations acquire cpus_read_lock() can
2404 * lead to deadlocks.
2406 * Bringing up a CPU may involve creating and destroying tasks which requires
2407 * read-locking threadgroup_rwsem, so threadgroup_rwsem nests inside
2408 * cpus_read_lock(). If we call an ->attach() which acquires the cpus lock while
2409 * write-locking threadgroup_rwsem, the locking order is reversed and we end up
2410 * waiting for an on-going CPU hotplug operation which in turn is waiting for
2411 * the threadgroup_rwsem to be released to create new tasks. For more details:
2413 * http://lkml.kernel.org/r/20220711174629.uehfmqegcwn2lqzu@wubuntu
2415 * Resolve the situation by always acquiring cpus_read_lock() before optionally
2416 * write-locking cgroup_threadgroup_rwsem. This allows ->attach() to assume that
2417 * CPU hotplug is disabled on entry.
2419 void cgroup_attach_lock(bool lock_threadgroup)
2422 if (lock_threadgroup)
2423 percpu_down_write(&cgroup_threadgroup_rwsem);
2427 * cgroup_attach_unlock - Undo cgroup_attach_lock()
2428 * @lock_threadgroup: whether to up_write cgroup_threadgroup_rwsem
2430 void cgroup_attach_unlock(bool lock_threadgroup)
2432 if (lock_threadgroup)
2433 percpu_up_write(&cgroup_threadgroup_rwsem);
2438 * cgroup_migrate_add_task - add a migration target task to a migration context
2439 * @task: target task
2440 * @mgctx: target migration context
2442 * Add @task, which is a migration target, to @mgctx->tset. This function
2443 * becomes noop if @task doesn't need to be migrated. @task's css_set
2444 * should have been added as a migration source and @task->cg_list will be
2445 * moved from the css_set's tasks list to mg_tasks one.
2447 static void cgroup_migrate_add_task(struct task_struct *task,
2448 struct cgroup_mgctx *mgctx)
2450 struct css_set *cset;
2452 lockdep_assert_held(&css_set_lock);
2454 /* @task either already exited or can't exit until the end */
2455 if (task->flags & PF_EXITING)
2458 /* cgroup_threadgroup_rwsem protects racing against forks */
2459 WARN_ON_ONCE(list_empty(&task->cg_list));
2461 cset = task_css_set(task);
2462 if (!cset->mg_src_cgrp)
2465 mgctx->tset.nr_tasks++;
2467 list_move_tail(&task->cg_list, &cset->mg_tasks);
2468 if (list_empty(&cset->mg_node))
2469 list_add_tail(&cset->mg_node,
2470 &mgctx->tset.src_csets);
2471 if (list_empty(&cset->mg_dst_cset->mg_node))
2472 list_add_tail(&cset->mg_dst_cset->mg_node,
2473 &mgctx->tset.dst_csets);
2477 * cgroup_taskset_first - reset taskset and return the first task
2478 * @tset: taskset of interest
2479 * @dst_cssp: output variable for the destination css
2481 * @tset iteration is initialized and the first task is returned.
2483 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2484 struct cgroup_subsys_state **dst_cssp)
2486 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2487 tset->cur_task = NULL;
2489 return cgroup_taskset_next(tset, dst_cssp);
2493 * cgroup_taskset_next - iterate to the next task in taskset
2494 * @tset: taskset of interest
2495 * @dst_cssp: output variable for the destination css
2497 * Return the next task in @tset. Iteration must have been initialized
2498 * with cgroup_taskset_first().
2500 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2501 struct cgroup_subsys_state **dst_cssp)
2503 struct css_set *cset = tset->cur_cset;
2504 struct task_struct *task = tset->cur_task;
2506 while (CGROUP_HAS_SUBSYS_CONFIG && &cset->mg_node != tset->csets) {
2508 task = list_first_entry(&cset->mg_tasks,
2509 struct task_struct, cg_list);
2511 task = list_next_entry(task, cg_list);
2513 if (&task->cg_list != &cset->mg_tasks) {
2514 tset->cur_cset = cset;
2515 tset->cur_task = task;
2518 * This function may be called both before and
2519 * after cgroup_migrate_execute(). The two cases
2520 * can be distinguished by looking at whether @cset
2521 * has its ->mg_dst_cset set.
2523 if (cset->mg_dst_cset)
2524 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2526 *dst_cssp = cset->subsys[tset->ssid];
2531 cset = list_next_entry(cset, mg_node);
2539 * cgroup_migrate_execute - migrate a taskset
2540 * @mgctx: migration context
2542 * Migrate tasks in @mgctx as setup by migration preparation functions.
2543 * This function fails iff one of the ->can_attach callbacks fails and
2544 * guarantees that either all or none of the tasks in @mgctx are migrated.
2545 * @mgctx is consumed regardless of success.
2547 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2549 struct cgroup_taskset *tset = &mgctx->tset;
2550 struct cgroup_subsys *ss;
2551 struct task_struct *task, *tmp_task;
2552 struct css_set *cset, *tmp_cset;
2553 int ssid, failed_ssid, ret;
2555 /* check that we can legitimately attach to the cgroup */
2556 if (tset->nr_tasks) {
2557 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2558 if (ss->can_attach) {
2560 ret = ss->can_attach(tset);
2563 goto out_cancel_attach;
2566 } while_each_subsys_mask();
2570 * Now that we're guaranteed success, proceed to move all tasks to
2571 * the new cgroup. There are no failure cases after here, so this
2572 * is the commit point.
2574 spin_lock_irq(&css_set_lock);
2575 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2576 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2577 struct css_set *from_cset = task_css_set(task);
2578 struct css_set *to_cset = cset->mg_dst_cset;
2580 get_css_set(to_cset);
2581 to_cset->nr_tasks++;
2582 css_set_move_task(task, from_cset, to_cset, true);
2583 from_cset->nr_tasks--;
2585 * If the source or destination cgroup is frozen,
2586 * the task might require to change its state.
2588 cgroup_freezer_migrate_task(task, from_cset->dfl_cgrp,
2590 put_css_set_locked(from_cset);
2594 spin_unlock_irq(&css_set_lock);
2597 * Migration is committed, all target tasks are now on dst_csets.
2598 * Nothing is sensitive to fork() after this point. Notify
2599 * controllers that migration is complete.
2601 tset->csets = &tset->dst_csets;
2603 if (tset->nr_tasks) {
2604 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2609 } while_each_subsys_mask();
2613 goto out_release_tset;
2616 if (tset->nr_tasks) {
2617 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2618 if (ssid == failed_ssid)
2620 if (ss->cancel_attach) {
2622 ss->cancel_attach(tset);
2624 } while_each_subsys_mask();
2627 spin_lock_irq(&css_set_lock);
2628 list_splice_init(&tset->dst_csets, &tset->src_csets);
2629 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2630 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2631 list_del_init(&cset->mg_node);
2633 spin_unlock_irq(&css_set_lock);
2636 * Re-initialize the cgroup_taskset structure in case it is reused
2637 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2641 tset->csets = &tset->src_csets;
2646 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2647 * @dst_cgrp: destination cgroup to test
2649 * On the default hierarchy, except for the mixable, (possible) thread root
2650 * and threaded cgroups, subtree_control must be zero for migration
2651 * destination cgroups with tasks so that child cgroups don't compete
2654 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2656 /* v1 doesn't have any restriction */
2657 if (!cgroup_on_dfl(dst_cgrp))
2660 /* verify @dst_cgrp can host resources */
2661 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2665 * If @dst_cgrp is already or can become a thread root or is
2666 * threaded, it doesn't matter.
2668 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2671 /* apply no-internal-process constraint */
2672 if (dst_cgrp->subtree_control)
2679 * cgroup_migrate_finish - cleanup after attach
2680 * @mgctx: migration context
2682 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2683 * those functions for details.
2685 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2687 struct css_set *cset, *tmp_cset;
2689 lockdep_assert_held(&cgroup_mutex);
2691 spin_lock_irq(&css_set_lock);
2693 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_src_csets,
2694 mg_src_preload_node) {
2695 cset->mg_src_cgrp = NULL;
2696 cset->mg_dst_cgrp = NULL;
2697 cset->mg_dst_cset = NULL;
2698 list_del_init(&cset->mg_src_preload_node);
2699 put_css_set_locked(cset);
2702 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_dst_csets,
2703 mg_dst_preload_node) {
2704 cset->mg_src_cgrp = NULL;
2705 cset->mg_dst_cgrp = NULL;
2706 cset->mg_dst_cset = NULL;
2707 list_del_init(&cset->mg_dst_preload_node);
2708 put_css_set_locked(cset);
2711 spin_unlock_irq(&css_set_lock);
2715 * cgroup_migrate_add_src - add a migration source css_set
2716 * @src_cset: the source css_set to add
2717 * @dst_cgrp: the destination cgroup
2718 * @mgctx: migration context
2720 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2721 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2722 * up by cgroup_migrate_finish().
2724 * This function may be called without holding cgroup_threadgroup_rwsem
2725 * even if the target is a process. Threads may be created and destroyed
2726 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2727 * into play and the preloaded css_sets are guaranteed to cover all
2730 void cgroup_migrate_add_src(struct css_set *src_cset,
2731 struct cgroup *dst_cgrp,
2732 struct cgroup_mgctx *mgctx)
2734 struct cgroup *src_cgrp;
2736 lockdep_assert_held(&cgroup_mutex);
2737 lockdep_assert_held(&css_set_lock);
2740 * If ->dead, @src_set is associated with one or more dead cgroups
2741 * and doesn't contain any migratable tasks. Ignore it early so
2742 * that the rest of migration path doesn't get confused by it.
2747 if (!list_empty(&src_cset->mg_src_preload_node))
2750 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2752 WARN_ON(src_cset->mg_src_cgrp);
2753 WARN_ON(src_cset->mg_dst_cgrp);
2754 WARN_ON(!list_empty(&src_cset->mg_tasks));
2755 WARN_ON(!list_empty(&src_cset->mg_node));
2757 src_cset->mg_src_cgrp = src_cgrp;
2758 src_cset->mg_dst_cgrp = dst_cgrp;
2759 get_css_set(src_cset);
2760 list_add_tail(&src_cset->mg_src_preload_node, &mgctx->preloaded_src_csets);
2764 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2765 * @mgctx: migration context
2767 * Tasks are about to be moved and all the source css_sets have been
2768 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2769 * pins all destination css_sets, links each to its source, and append them
2770 * to @mgctx->preloaded_dst_csets.
2772 * This function must be called after cgroup_migrate_add_src() has been
2773 * called on each migration source css_set. After migration is performed
2774 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2777 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2779 struct css_set *src_cset, *tmp_cset;
2781 lockdep_assert_held(&cgroup_mutex);
2783 /* look up the dst cset for each src cset and link it to src */
2784 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2785 mg_src_preload_node) {
2786 struct css_set *dst_cset;
2787 struct cgroup_subsys *ss;
2790 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2794 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2797 * If src cset equals dst, it's noop. Drop the src.
2798 * cgroup_migrate() will skip the cset too. Note that we
2799 * can't handle src == dst as some nodes are used by both.
2801 if (src_cset == dst_cset) {
2802 src_cset->mg_src_cgrp = NULL;
2803 src_cset->mg_dst_cgrp = NULL;
2804 list_del_init(&src_cset->mg_src_preload_node);
2805 put_css_set(src_cset);
2806 put_css_set(dst_cset);
2810 src_cset->mg_dst_cset = dst_cset;
2812 if (list_empty(&dst_cset->mg_dst_preload_node))
2813 list_add_tail(&dst_cset->mg_dst_preload_node,
2814 &mgctx->preloaded_dst_csets);
2816 put_css_set(dst_cset);
2818 for_each_subsys(ss, ssid)
2819 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2820 mgctx->ss_mask |= 1 << ssid;
2827 * cgroup_migrate - migrate a process or task to a cgroup
2828 * @leader: the leader of the process or the task to migrate
2829 * @threadgroup: whether @leader points to the whole process or a single task
2830 * @mgctx: migration context
2832 * Migrate a process or task denoted by @leader. If migrating a process,
2833 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2834 * responsible for invoking cgroup_migrate_add_src() and
2835 * cgroup_migrate_prepare_dst() on the targets before invoking this
2836 * function and following up with cgroup_migrate_finish().
2838 * As long as a controller's ->can_attach() doesn't fail, this function is
2839 * guaranteed to succeed. This means that, excluding ->can_attach()
2840 * failure, when migrating multiple targets, the success or failure can be
2841 * decided for all targets by invoking group_migrate_prepare_dst() before
2842 * actually starting migrating.
2844 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2845 struct cgroup_mgctx *mgctx)
2847 struct task_struct *task;
2850 * The following thread iteration should be inside an RCU critical
2851 * section to prevent tasks from being freed while taking the snapshot.
2852 * spin_lock_irq() implies RCU critical section here.
2854 spin_lock_irq(&css_set_lock);
2857 cgroup_migrate_add_task(task, mgctx);
2860 } while_each_thread(leader, task);
2861 spin_unlock_irq(&css_set_lock);
2863 return cgroup_migrate_execute(mgctx);
2867 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2868 * @dst_cgrp: the cgroup to attach to
2869 * @leader: the task or the leader of the threadgroup to be attached
2870 * @threadgroup: attach the whole threadgroup?
2872 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2874 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2877 DEFINE_CGROUP_MGCTX(mgctx);
2878 struct task_struct *task;
2881 /* look up all src csets */
2882 spin_lock_irq(&css_set_lock);
2886 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2889 } while_each_thread(leader, task);
2891 spin_unlock_irq(&css_set_lock);
2893 /* prepare dst csets and commit */
2894 ret = cgroup_migrate_prepare_dst(&mgctx);
2896 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2898 cgroup_migrate_finish(&mgctx);
2901 TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
2906 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup,
2907 bool *threadgroup_locked)
2909 struct task_struct *tsk;
2912 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2913 return ERR_PTR(-EINVAL);
2916 * If we migrate a single thread, we don't care about threadgroup
2917 * stability. If the thread is `current`, it won't exit(2) under our
2918 * hands or change PID through exec(2). We exclude
2919 * cgroup_update_dfl_csses and other cgroup_{proc,thread}s_write
2920 * callers by cgroup_mutex.
2921 * Therefore, we can skip the global lock.
2923 lockdep_assert_held(&cgroup_mutex);
2924 *threadgroup_locked = pid || threadgroup;
2925 cgroup_attach_lock(*threadgroup_locked);
2929 tsk = find_task_by_vpid(pid);
2931 tsk = ERR_PTR(-ESRCH);
2932 goto out_unlock_threadgroup;
2939 tsk = tsk->group_leader;
2942 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2943 * If userland migrates such a kthread to a non-root cgroup, it can
2944 * become trapped in a cpuset, or RT kthread may be born in a
2945 * cgroup with no rt_runtime allocated. Just say no.
2947 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2948 tsk = ERR_PTR(-EINVAL);
2949 goto out_unlock_threadgroup;
2952 get_task_struct(tsk);
2953 goto out_unlock_rcu;
2955 out_unlock_threadgroup:
2956 cgroup_attach_unlock(*threadgroup_locked);
2957 *threadgroup_locked = false;
2963 void cgroup_procs_write_finish(struct task_struct *task, bool threadgroup_locked)
2965 struct cgroup_subsys *ss;
2968 /* release reference from cgroup_procs_write_start() */
2969 put_task_struct(task);
2971 cgroup_attach_unlock(threadgroup_locked);
2973 for_each_subsys(ss, ssid)
2974 if (ss->post_attach)
2978 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2980 struct cgroup_subsys *ss;
2981 bool printed = false;
2984 do_each_subsys_mask(ss, ssid, ss_mask) {
2987 seq_puts(seq, ss->name);
2989 } while_each_subsys_mask();
2991 seq_putc(seq, '\n');
2994 /* show controllers which are enabled from the parent */
2995 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2997 struct cgroup *cgrp = seq_css(seq)->cgroup;
2999 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
3003 /* show controllers which are enabled for a given cgroup's children */
3004 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
3006 struct cgroup *cgrp = seq_css(seq)->cgroup;
3008 cgroup_print_ss_mask(seq, cgrp->subtree_control);
3013 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
3014 * @cgrp: root of the subtree to update csses for
3016 * @cgrp's control masks have changed and its subtree's css associations
3017 * need to be updated accordingly. This function looks up all css_sets
3018 * which are attached to the subtree, creates the matching updated css_sets
3019 * and migrates the tasks to the new ones.
3021 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
3023 DEFINE_CGROUP_MGCTX(mgctx);
3024 struct cgroup_subsys_state *d_css;
3025 struct cgroup *dsct;
3026 struct css_set *src_cset;
3030 lockdep_assert_held(&cgroup_mutex);
3032 /* look up all csses currently attached to @cgrp's subtree */
3033 spin_lock_irq(&css_set_lock);
3034 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3035 struct cgrp_cset_link *link;
3038 * As cgroup_update_dfl_csses() is only called by
3039 * cgroup_apply_control(). The csses associated with the
3040 * given cgrp will not be affected by changes made to
3041 * its subtree_control file. We can skip them.
3046 list_for_each_entry(link, &dsct->cset_links, cset_link)
3047 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
3049 spin_unlock_irq(&css_set_lock);
3052 * We need to write-lock threadgroup_rwsem while migrating tasks.
3053 * However, if there are no source csets for @cgrp, changing its
3054 * controllers isn't gonna produce any task migrations and the
3055 * write-locking can be skipped safely.
3057 has_tasks = !list_empty(&mgctx.preloaded_src_csets);
3058 cgroup_attach_lock(has_tasks);
3060 /* NULL dst indicates self on default hierarchy */
3061 ret = cgroup_migrate_prepare_dst(&mgctx);
3065 spin_lock_irq(&css_set_lock);
3066 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets,
3067 mg_src_preload_node) {
3068 struct task_struct *task, *ntask;
3070 /* all tasks in src_csets need to be migrated */
3071 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
3072 cgroup_migrate_add_task(task, &mgctx);
3074 spin_unlock_irq(&css_set_lock);
3076 ret = cgroup_migrate_execute(&mgctx);
3078 cgroup_migrate_finish(&mgctx);
3079 cgroup_attach_unlock(has_tasks);
3084 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
3085 * @cgrp: root of the target subtree
3087 * Because css offlining is asynchronous, userland may try to re-enable a
3088 * controller while the previous css is still around. This function grabs
3089 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
3091 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
3092 __acquires(&cgroup_mutex)
3094 struct cgroup *dsct;
3095 struct cgroup_subsys_state *d_css;
3096 struct cgroup_subsys *ss;
3102 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3103 for_each_subsys(ss, ssid) {
3104 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3107 if (!css || !percpu_ref_is_dying(&css->refcnt))
3110 cgroup_get_live(dsct);
3111 prepare_to_wait(&dsct->offline_waitq, &wait,
3112 TASK_UNINTERRUPTIBLE);
3116 finish_wait(&dsct->offline_waitq, &wait);
3125 * cgroup_save_control - save control masks and dom_cgrp of a subtree
3126 * @cgrp: root of the target subtree
3128 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
3129 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3132 static void cgroup_save_control(struct cgroup *cgrp)
3134 struct cgroup *dsct;
3135 struct cgroup_subsys_state *d_css;
3137 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3138 dsct->old_subtree_control = dsct->subtree_control;
3139 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
3140 dsct->old_dom_cgrp = dsct->dom_cgrp;
3145 * cgroup_propagate_control - refresh control masks of a subtree
3146 * @cgrp: root of the target subtree
3148 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
3149 * ->subtree_control and propagate controller availability through the
3150 * subtree so that descendants don't have unavailable controllers enabled.
3152 static void cgroup_propagate_control(struct cgroup *cgrp)
3154 struct cgroup *dsct;
3155 struct cgroup_subsys_state *d_css;
3157 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3158 dsct->subtree_control &= cgroup_control(dsct);
3159 dsct->subtree_ss_mask =
3160 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
3161 cgroup_ss_mask(dsct));
3166 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
3167 * @cgrp: root of the target subtree
3169 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
3170 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3173 static void cgroup_restore_control(struct cgroup *cgrp)
3175 struct cgroup *dsct;
3176 struct cgroup_subsys_state *d_css;
3178 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3179 dsct->subtree_control = dsct->old_subtree_control;
3180 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
3181 dsct->dom_cgrp = dsct->old_dom_cgrp;
3185 static bool css_visible(struct cgroup_subsys_state *css)
3187 struct cgroup_subsys *ss = css->ss;
3188 struct cgroup *cgrp = css->cgroup;
3190 if (cgroup_control(cgrp) & (1 << ss->id))
3192 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
3194 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
3198 * cgroup_apply_control_enable - enable or show csses according to control
3199 * @cgrp: root of the target subtree
3201 * Walk @cgrp's subtree and create new csses or make the existing ones
3202 * visible. A css is created invisible if it's being implicitly enabled
3203 * through dependency. An invisible css is made visible when the userland
3204 * explicitly enables it.
3206 * Returns 0 on success, -errno on failure. On failure, csses which have
3207 * been processed already aren't cleaned up. The caller is responsible for
3208 * cleaning up with cgroup_apply_control_disable().
3210 static int cgroup_apply_control_enable(struct cgroup *cgrp)
3212 struct cgroup *dsct;
3213 struct cgroup_subsys_state *d_css;
3214 struct cgroup_subsys *ss;
3217 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3218 for_each_subsys(ss, ssid) {
3219 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3221 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
3225 css = css_create(dsct, ss);
3227 return PTR_ERR(css);
3230 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3232 if (css_visible(css)) {
3233 ret = css_populate_dir(css);
3244 * cgroup_apply_control_disable - kill or hide csses according to control
3245 * @cgrp: root of the target subtree
3247 * Walk @cgrp's subtree and kill and hide csses so that they match
3248 * cgroup_ss_mask() and cgroup_visible_mask().
3250 * A css is hidden when the userland requests it to be disabled while other
3251 * subsystems are still depending on it. The css must not actively control
3252 * resources and be in the vanilla state if it's made visible again later.
3253 * Controllers which may be depended upon should provide ->css_reset() for
3256 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3258 struct cgroup *dsct;
3259 struct cgroup_subsys_state *d_css;
3260 struct cgroup_subsys *ss;
3263 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3264 for_each_subsys(ss, ssid) {
3265 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3270 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3273 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3275 } else if (!css_visible(css)) {
3285 * cgroup_apply_control - apply control mask updates to the subtree
3286 * @cgrp: root of the target subtree
3288 * subsystems can be enabled and disabled in a subtree using the following
3291 * 1. Call cgroup_save_control() to stash the current state.
3292 * 2. Update ->subtree_control masks in the subtree as desired.
3293 * 3. Call cgroup_apply_control() to apply the changes.
3294 * 4. Optionally perform other related operations.
3295 * 5. Call cgroup_finalize_control() to finish up.
3297 * This function implements step 3 and propagates the mask changes
3298 * throughout @cgrp's subtree, updates csses accordingly and perform
3299 * process migrations.
3301 static int cgroup_apply_control(struct cgroup *cgrp)
3305 cgroup_propagate_control(cgrp);
3307 ret = cgroup_apply_control_enable(cgrp);
3312 * At this point, cgroup_e_css_by_mask() results reflect the new csses
3313 * making the following cgroup_update_dfl_csses() properly update
3314 * css associations of all tasks in the subtree.
3316 return cgroup_update_dfl_csses(cgrp);
3320 * cgroup_finalize_control - finalize control mask update
3321 * @cgrp: root of the target subtree
3322 * @ret: the result of the update
3324 * Finalize control mask update. See cgroup_apply_control() for more info.
3326 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3329 cgroup_restore_control(cgrp);
3330 cgroup_propagate_control(cgrp);
3333 cgroup_apply_control_disable(cgrp);
3336 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3338 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3340 /* if nothing is getting enabled, nothing to worry about */
3344 /* can @cgrp host any resources? */
3345 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3348 /* mixables don't care */
3349 if (cgroup_is_mixable(cgrp))
3352 if (domain_enable) {
3353 /* can't enable domain controllers inside a thread subtree */
3354 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3358 * Threaded controllers can handle internal competitions
3359 * and are always allowed inside a (prospective) thread
3362 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3367 * Controllers can't be enabled for a cgroup with tasks to avoid
3368 * child cgroups competing against tasks.
3370 if (cgroup_has_tasks(cgrp))
3376 /* change the enabled child controllers for a cgroup in the default hierarchy */
3377 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3378 char *buf, size_t nbytes,
3381 u16 enable = 0, disable = 0;
3382 struct cgroup *cgrp, *child;
3383 struct cgroup_subsys *ss;
3388 * Parse input - space separated list of subsystem names prefixed
3389 * with either + or -.
3391 buf = strstrip(buf);
3392 while ((tok = strsep(&buf, " "))) {
3395 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3396 if (!cgroup_ssid_enabled(ssid) ||
3397 strcmp(tok + 1, ss->name))
3401 enable |= 1 << ssid;
3402 disable &= ~(1 << ssid);
3403 } else if (*tok == '-') {
3404 disable |= 1 << ssid;
3405 enable &= ~(1 << ssid);
3410 } while_each_subsys_mask();
3411 if (ssid == CGROUP_SUBSYS_COUNT)
3415 cgrp = cgroup_kn_lock_live(of->kn, true);
3419 for_each_subsys(ss, ssid) {
3420 if (enable & (1 << ssid)) {
3421 if (cgrp->subtree_control & (1 << ssid)) {
3422 enable &= ~(1 << ssid);
3426 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3430 } else if (disable & (1 << ssid)) {
3431 if (!(cgrp->subtree_control & (1 << ssid))) {
3432 disable &= ~(1 << ssid);
3436 /* a child has it enabled? */
3437 cgroup_for_each_live_child(child, cgrp) {
3438 if (child->subtree_control & (1 << ssid)) {
3446 if (!enable && !disable) {
3451 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3455 /* save and update control masks and prepare csses */
3456 cgroup_save_control(cgrp);
3458 cgrp->subtree_control |= enable;
3459 cgrp->subtree_control &= ~disable;
3461 ret = cgroup_apply_control(cgrp);
3462 cgroup_finalize_control(cgrp, ret);
3466 kernfs_activate(cgrp->kn);
3468 cgroup_kn_unlock(of->kn);
3469 return ret ?: nbytes;
3473 * cgroup_enable_threaded - make @cgrp threaded
3474 * @cgrp: the target cgroup
3476 * Called when "threaded" is written to the cgroup.type interface file and
3477 * tries to make @cgrp threaded and join the parent's resource domain.
3478 * This function is never called on the root cgroup as cgroup.type doesn't
3481 static int cgroup_enable_threaded(struct cgroup *cgrp)
3483 struct cgroup *parent = cgroup_parent(cgrp);
3484 struct cgroup *dom_cgrp = parent->dom_cgrp;
3485 struct cgroup *dsct;
3486 struct cgroup_subsys_state *d_css;
3489 lockdep_assert_held(&cgroup_mutex);
3491 /* noop if already threaded */
3492 if (cgroup_is_threaded(cgrp))
3496 * If @cgroup is populated or has domain controllers enabled, it
3497 * can't be switched. While the below cgroup_can_be_thread_root()
3498 * test can catch the same conditions, that's only when @parent is
3499 * not mixable, so let's check it explicitly.
3501 if (cgroup_is_populated(cgrp) ||
3502 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3505 /* we're joining the parent's domain, ensure its validity */
3506 if (!cgroup_is_valid_domain(dom_cgrp) ||
3507 !cgroup_can_be_thread_root(dom_cgrp))
3511 * The following shouldn't cause actual migrations and should
3514 cgroup_save_control(cgrp);
3516 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3517 if (dsct == cgrp || cgroup_is_threaded(dsct))
3518 dsct->dom_cgrp = dom_cgrp;
3520 ret = cgroup_apply_control(cgrp);
3522 parent->nr_threaded_children++;
3524 cgroup_finalize_control(cgrp, ret);
3528 static int cgroup_type_show(struct seq_file *seq, void *v)
3530 struct cgroup *cgrp = seq_css(seq)->cgroup;
3532 if (cgroup_is_threaded(cgrp))
3533 seq_puts(seq, "threaded\n");
3534 else if (!cgroup_is_valid_domain(cgrp))
3535 seq_puts(seq, "domain invalid\n");
3536 else if (cgroup_is_thread_root(cgrp))
3537 seq_puts(seq, "domain threaded\n");
3539 seq_puts(seq, "domain\n");
3544 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3545 size_t nbytes, loff_t off)
3547 struct cgroup *cgrp;
3550 /* only switching to threaded mode is supported */
3551 if (strcmp(strstrip(buf), "threaded"))
3554 /* drain dying csses before we re-apply (threaded) subtree control */
3555 cgrp = cgroup_kn_lock_live(of->kn, true);
3559 /* threaded can only be enabled */
3560 ret = cgroup_enable_threaded(cgrp);
3562 cgroup_kn_unlock(of->kn);
3563 return ret ?: nbytes;
3566 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3568 struct cgroup *cgrp = seq_css(seq)->cgroup;
3569 int descendants = READ_ONCE(cgrp->max_descendants);
3571 if (descendants == INT_MAX)
3572 seq_puts(seq, "max\n");
3574 seq_printf(seq, "%d\n", descendants);
3579 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3580 char *buf, size_t nbytes, loff_t off)
3582 struct cgroup *cgrp;
3586 buf = strstrip(buf);
3587 if (!strcmp(buf, "max")) {
3588 descendants = INT_MAX;
3590 ret = kstrtoint(buf, 0, &descendants);
3595 if (descendants < 0)
3598 cgrp = cgroup_kn_lock_live(of->kn, false);
3602 cgrp->max_descendants = descendants;
3604 cgroup_kn_unlock(of->kn);
3609 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3611 struct cgroup *cgrp = seq_css(seq)->cgroup;
3612 int depth = READ_ONCE(cgrp->max_depth);
3614 if (depth == INT_MAX)
3615 seq_puts(seq, "max\n");
3617 seq_printf(seq, "%d\n", depth);
3622 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3623 char *buf, size_t nbytes, loff_t off)
3625 struct cgroup *cgrp;
3629 buf = strstrip(buf);
3630 if (!strcmp(buf, "max")) {
3633 ret = kstrtoint(buf, 0, &depth);
3641 cgrp = cgroup_kn_lock_live(of->kn, false);
3645 cgrp->max_depth = depth;
3647 cgroup_kn_unlock(of->kn);
3652 static int cgroup_events_show(struct seq_file *seq, void *v)
3654 struct cgroup *cgrp = seq_css(seq)->cgroup;
3656 seq_printf(seq, "populated %d\n", cgroup_is_populated(cgrp));
3657 seq_printf(seq, "frozen %d\n", test_bit(CGRP_FROZEN, &cgrp->flags));
3662 static int cgroup_stat_show(struct seq_file *seq, void *v)
3664 struct cgroup *cgroup = seq_css(seq)->cgroup;
3666 seq_printf(seq, "nr_descendants %d\n",
3667 cgroup->nr_descendants);
3668 seq_printf(seq, "nr_dying_descendants %d\n",
3669 cgroup->nr_dying_descendants);
3674 #ifdef CONFIG_CGROUP_SCHED
3676 * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
3677 * @cgrp: the cgroup of interest
3678 * @ss: the subsystem of interest
3680 * Find and get @cgrp's css associated with @ss. If the css doesn't exist
3681 * or is offline, %NULL is returned.
3683 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
3684 struct cgroup_subsys *ss)
3686 struct cgroup_subsys_state *css;
3689 css = cgroup_css(cgrp, ss);
3690 if (css && !css_tryget_online(css))
3697 static int cgroup_extra_stat_show(struct seq_file *seq, int ssid)
3699 struct cgroup *cgrp = seq_css(seq)->cgroup;
3700 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3701 struct cgroup_subsys_state *css;
3704 if (!ss->css_extra_stat_show)
3707 css = cgroup_tryget_css(cgrp, ss);
3711 ret = ss->css_extra_stat_show(seq, css);
3716 static int cgroup_local_stat_show(struct seq_file *seq,
3717 struct cgroup *cgrp, int ssid)
3719 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3720 struct cgroup_subsys_state *css;
3723 if (!ss->css_local_stat_show)
3726 css = cgroup_tryget_css(cgrp, ss);
3730 ret = ss->css_local_stat_show(seq, css);
3736 static int cpu_stat_show(struct seq_file *seq, void *v)
3740 cgroup_base_stat_cputime_show(seq);
3741 #ifdef CONFIG_CGROUP_SCHED
3742 ret = cgroup_extra_stat_show(seq, cpu_cgrp_id);
3747 static int cpu_local_stat_show(struct seq_file *seq, void *v)
3749 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3752 #ifdef CONFIG_CGROUP_SCHED
3753 ret = cgroup_local_stat_show(seq, cgrp, cpu_cgrp_id);
3759 static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
3761 struct cgroup *cgrp = seq_css(seq)->cgroup;
3762 struct psi_group *psi = cgroup_psi(cgrp);
3764 return psi_show(seq, psi, PSI_IO);
3766 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
3768 struct cgroup *cgrp = seq_css(seq)->cgroup;
3769 struct psi_group *psi = cgroup_psi(cgrp);
3771 return psi_show(seq, psi, PSI_MEM);
3773 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
3775 struct cgroup *cgrp = seq_css(seq)->cgroup;
3776 struct psi_group *psi = cgroup_psi(cgrp);
3778 return psi_show(seq, psi, PSI_CPU);
3781 static ssize_t pressure_write(struct kernfs_open_file *of, char *buf,
3782 size_t nbytes, enum psi_res res)
3784 struct cgroup_file_ctx *ctx = of->priv;
3785 struct psi_trigger *new;
3786 struct cgroup *cgrp;
3787 struct psi_group *psi;
3789 cgrp = cgroup_kn_lock_live(of->kn, false);
3794 cgroup_kn_unlock(of->kn);
3796 /* Allow only one trigger per file descriptor */
3797 if (ctx->psi.trigger) {
3802 psi = cgroup_psi(cgrp);
3803 new = psi_trigger_create(psi, buf, res, of->file, of);
3806 return PTR_ERR(new);
3809 smp_store_release(&ctx->psi.trigger, new);
3815 static ssize_t cgroup_io_pressure_write(struct kernfs_open_file *of,
3816 char *buf, size_t nbytes,
3819 return pressure_write(of, buf, nbytes, PSI_IO);
3822 static ssize_t cgroup_memory_pressure_write(struct kernfs_open_file *of,
3823 char *buf, size_t nbytes,
3826 return pressure_write(of, buf, nbytes, PSI_MEM);
3829 static ssize_t cgroup_cpu_pressure_write(struct kernfs_open_file *of,
3830 char *buf, size_t nbytes,
3833 return pressure_write(of, buf, nbytes, PSI_CPU);
3836 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
3837 static int cgroup_irq_pressure_show(struct seq_file *seq, void *v)
3839 struct cgroup *cgrp = seq_css(seq)->cgroup;
3840 struct psi_group *psi = cgroup_psi(cgrp);
3842 return psi_show(seq, psi, PSI_IRQ);
3845 static ssize_t cgroup_irq_pressure_write(struct kernfs_open_file *of,
3846 char *buf, size_t nbytes,
3849 return pressure_write(of, buf, nbytes, PSI_IRQ);
3853 static int cgroup_pressure_show(struct seq_file *seq, void *v)
3855 struct cgroup *cgrp = seq_css(seq)->cgroup;
3856 struct psi_group *psi = cgroup_psi(cgrp);
3858 seq_printf(seq, "%d\n", psi->enabled);
3863 static ssize_t cgroup_pressure_write(struct kernfs_open_file *of,
3864 char *buf, size_t nbytes,
3869 struct cgroup *cgrp;
3870 struct psi_group *psi;
3872 ret = kstrtoint(strstrip(buf), 0, &enable);
3876 if (enable < 0 || enable > 1)
3879 cgrp = cgroup_kn_lock_live(of->kn, false);
3883 psi = cgroup_psi(cgrp);
3884 if (psi->enabled != enable) {
3887 /* show or hide {cpu,memory,io,irq}.pressure files */
3888 for (i = 0; i < NR_PSI_RESOURCES; i++)
3889 cgroup_file_show(&cgrp->psi_files[i], enable);
3891 psi->enabled = enable;
3893 psi_cgroup_restart(psi);
3896 cgroup_kn_unlock(of->kn);
3901 static __poll_t cgroup_pressure_poll(struct kernfs_open_file *of,
3904 struct cgroup_file_ctx *ctx = of->priv;
3906 return psi_trigger_poll(&ctx->psi.trigger, of->file, pt);
3909 static void cgroup_pressure_release(struct kernfs_open_file *of)
3911 struct cgroup_file_ctx *ctx = of->priv;
3913 psi_trigger_destroy(ctx->psi.trigger);
3916 bool cgroup_psi_enabled(void)
3918 if (static_branch_likely(&psi_disabled))
3921 return (cgroup_feature_disable_mask & (1 << OPT_FEATURE_PRESSURE)) == 0;
3924 #else /* CONFIG_PSI */
3925 bool cgroup_psi_enabled(void)
3930 #endif /* CONFIG_PSI */
3932 static int cgroup_freeze_show(struct seq_file *seq, void *v)
3934 struct cgroup *cgrp = seq_css(seq)->cgroup;
3936 seq_printf(seq, "%d\n", cgrp->freezer.freeze);
3941 static ssize_t cgroup_freeze_write(struct kernfs_open_file *of,
3942 char *buf, size_t nbytes, loff_t off)
3944 struct cgroup *cgrp;
3948 ret = kstrtoint(strstrip(buf), 0, &freeze);
3952 if (freeze < 0 || freeze > 1)
3955 cgrp = cgroup_kn_lock_live(of->kn, false);
3959 cgroup_freeze(cgrp, freeze);
3961 cgroup_kn_unlock(of->kn);
3966 static void __cgroup_kill(struct cgroup *cgrp)
3968 struct css_task_iter it;
3969 struct task_struct *task;
3971 lockdep_assert_held(&cgroup_mutex);
3973 spin_lock_irq(&css_set_lock);
3974 set_bit(CGRP_KILL, &cgrp->flags);
3975 spin_unlock_irq(&css_set_lock);
3977 css_task_iter_start(&cgrp->self, CSS_TASK_ITER_PROCS | CSS_TASK_ITER_THREADED, &it);
3978 while ((task = css_task_iter_next(&it))) {
3979 /* Ignore kernel threads here. */
3980 if (task->flags & PF_KTHREAD)
3983 /* Skip tasks that are already dying. */
3984 if (__fatal_signal_pending(task))
3987 send_sig(SIGKILL, task, 0);
3989 css_task_iter_end(&it);
3991 spin_lock_irq(&css_set_lock);
3992 clear_bit(CGRP_KILL, &cgrp->flags);
3993 spin_unlock_irq(&css_set_lock);
3996 static void cgroup_kill(struct cgroup *cgrp)
3998 struct cgroup_subsys_state *css;
3999 struct cgroup *dsct;
4001 lockdep_assert_held(&cgroup_mutex);
4003 cgroup_for_each_live_descendant_pre(dsct, css, cgrp)
4004 __cgroup_kill(dsct);
4007 static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf,
4008 size_t nbytes, loff_t off)
4012 struct cgroup *cgrp;
4014 ret = kstrtoint(strstrip(buf), 0, &kill);
4021 cgrp = cgroup_kn_lock_live(of->kn, false);
4026 * Killing is a process directed operation, i.e. the whole thread-group
4027 * is taken down so act like we do for cgroup.procs and only make this
4028 * writable in non-threaded cgroups.
4030 if (cgroup_is_threaded(cgrp))
4035 cgroup_kn_unlock(of->kn);
4037 return ret ?: nbytes;
4040 static int cgroup_file_open(struct kernfs_open_file *of)
4042 struct cftype *cft = of_cft(of);
4043 struct cgroup_file_ctx *ctx;
4046 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
4050 ctx->ns = current->nsproxy->cgroup_ns;
4051 get_cgroup_ns(ctx->ns);
4057 ret = cft->open(of);
4059 put_cgroup_ns(ctx->ns);
4065 static void cgroup_file_release(struct kernfs_open_file *of)
4067 struct cftype *cft = of_cft(of);
4068 struct cgroup_file_ctx *ctx = of->priv;
4072 put_cgroup_ns(ctx->ns);
4076 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
4077 size_t nbytes, loff_t off)
4079 struct cgroup_file_ctx *ctx = of->priv;
4080 struct cgroup *cgrp = of->kn->parent->priv;
4081 struct cftype *cft = of_cft(of);
4082 struct cgroup_subsys_state *css;
4089 * If namespaces are delegation boundaries, disallow writes to
4090 * files in an non-init namespace root from inside the namespace
4091 * except for the files explicitly marked delegatable -
4092 * cgroup.procs and cgroup.subtree_control.
4094 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
4095 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
4096 ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
4100 return cft->write(of, buf, nbytes, off);
4103 * kernfs guarantees that a file isn't deleted with operations in
4104 * flight, which means that the matching css is and stays alive and
4105 * doesn't need to be pinned. The RCU locking is not necessary
4106 * either. It's just for the convenience of using cgroup_css().
4109 css = cgroup_css(cgrp, cft->ss);
4112 if (cft->write_u64) {
4113 unsigned long long v;
4114 ret = kstrtoull(buf, 0, &v);
4116 ret = cft->write_u64(css, cft, v);
4117 } else if (cft->write_s64) {
4119 ret = kstrtoll(buf, 0, &v);
4121 ret = cft->write_s64(css, cft, v);
4126 return ret ?: nbytes;
4129 static __poll_t cgroup_file_poll(struct kernfs_open_file *of, poll_table *pt)
4131 struct cftype *cft = of_cft(of);
4134 return cft->poll(of, pt);
4136 return kernfs_generic_poll(of, pt);
4139 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
4141 return seq_cft(seq)->seq_start(seq, ppos);
4144 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
4146 return seq_cft(seq)->seq_next(seq, v, ppos);
4149 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
4151 if (seq_cft(seq)->seq_stop)
4152 seq_cft(seq)->seq_stop(seq, v);
4155 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
4157 struct cftype *cft = seq_cft(m);
4158 struct cgroup_subsys_state *css = seq_css(m);
4161 return cft->seq_show(m, arg);
4164 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
4165 else if (cft->read_s64)
4166 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
4172 static struct kernfs_ops cgroup_kf_single_ops = {
4173 .atomic_write_len = PAGE_SIZE,
4174 .open = cgroup_file_open,
4175 .release = cgroup_file_release,
4176 .write = cgroup_file_write,
4177 .poll = cgroup_file_poll,
4178 .seq_show = cgroup_seqfile_show,
4181 static struct kernfs_ops cgroup_kf_ops = {
4182 .atomic_write_len = PAGE_SIZE,
4183 .open = cgroup_file_open,
4184 .release = cgroup_file_release,
4185 .write = cgroup_file_write,
4186 .poll = cgroup_file_poll,
4187 .seq_start = cgroup_seqfile_start,
4188 .seq_next = cgroup_seqfile_next,
4189 .seq_stop = cgroup_seqfile_stop,
4190 .seq_show = cgroup_seqfile_show,
4193 /* set uid and gid of cgroup dirs and files to that of the creator */
4194 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
4196 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
4197 .ia_uid = current_fsuid(),
4198 .ia_gid = current_fsgid(), };
4200 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
4201 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
4204 return kernfs_setattr(kn, &iattr);
4207 static void cgroup_file_notify_timer(struct timer_list *timer)
4209 cgroup_file_notify(container_of(timer, struct cgroup_file,
4213 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
4216 char name[CGROUP_FILE_NAME_MAX];
4217 struct kernfs_node *kn;
4218 struct lock_class_key *key = NULL;
4221 #ifdef CONFIG_DEBUG_LOCK_ALLOC
4222 key = &cft->lockdep_key;
4224 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
4225 cgroup_file_mode(cft),
4226 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
4227 0, cft->kf_ops, cft,
4232 ret = cgroup_kn_set_ugid(kn);
4238 if (cft->file_offset) {
4239 struct cgroup_file *cfile = (void *)css + cft->file_offset;
4241 timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
4243 spin_lock_irq(&cgroup_file_kn_lock);
4245 spin_unlock_irq(&cgroup_file_kn_lock);
4252 * cgroup_addrm_files - add or remove files to a cgroup directory
4253 * @css: the target css
4254 * @cgrp: the target cgroup (usually css->cgroup)
4255 * @cfts: array of cftypes to be added
4256 * @is_add: whether to add or remove
4258 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
4259 * For removals, this function never fails.
4261 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
4262 struct cgroup *cgrp, struct cftype cfts[],
4265 struct cftype *cft, *cft_end = NULL;
4268 lockdep_assert_held(&cgroup_mutex);
4271 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
4272 /* does cft->flags tell us to skip this file on @cgrp? */
4273 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
4275 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
4277 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
4279 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
4281 if ((cft->flags & CFTYPE_DEBUG) && !cgroup_debug)
4284 ret = cgroup_add_file(css, cgrp, cft);
4286 pr_warn("%s: failed to add %s, err=%d\n",
4287 __func__, cft->name, ret);
4293 cgroup_rm_file(cgrp, cft);
4299 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
4301 struct cgroup_subsys *ss = cfts[0].ss;
4302 struct cgroup *root = &ss->root->cgrp;
4303 struct cgroup_subsys_state *css;
4306 lockdep_assert_held(&cgroup_mutex);
4308 /* add/rm files for all cgroups created before */
4309 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
4310 struct cgroup *cgrp = css->cgroup;
4312 if (!(css->flags & CSS_VISIBLE))
4315 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
4321 kernfs_activate(root->kn);
4325 static void cgroup_exit_cftypes(struct cftype *cfts)
4329 for (cft = cfts; cft->name[0] != '\0'; cft++) {
4330 /* free copy for custom atomic_write_len, see init_cftypes() */
4331 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
4336 /* revert flags set by cgroup core while adding @cfts */
4337 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL |
4342 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4347 for (cft = cfts; cft->name[0] != '\0'; cft++) {
4348 struct kernfs_ops *kf_ops;
4350 WARN_ON(cft->ss || cft->kf_ops);
4352 if (cft->flags & __CFTYPE_ADDED) {
4358 kf_ops = &cgroup_kf_ops;
4360 kf_ops = &cgroup_kf_single_ops;
4363 * Ugh... if @cft wants a custom max_write_len, we need to
4364 * make a copy of kf_ops to set its atomic_write_len.
4366 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
4367 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
4372 kf_ops->atomic_write_len = cft->max_write_len;
4375 cft->kf_ops = kf_ops;
4377 cft->flags |= __CFTYPE_ADDED;
4381 cgroup_exit_cftypes(cfts);
4385 static void cgroup_rm_cftypes_locked(struct cftype *cfts)
4387 lockdep_assert_held(&cgroup_mutex);
4389 list_del(&cfts->node);
4390 cgroup_apply_cftypes(cfts, false);
4391 cgroup_exit_cftypes(cfts);
4395 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
4396 * @cfts: zero-length name terminated array of cftypes
4398 * Unregister @cfts. Files described by @cfts are removed from all
4399 * existing cgroups and all future cgroups won't have them either. This
4400 * function can be called anytime whether @cfts' subsys is attached or not.
4402 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
4405 int cgroup_rm_cftypes(struct cftype *cfts)
4407 if (!cfts || cfts[0].name[0] == '\0')
4410 if (!(cfts[0].flags & __CFTYPE_ADDED))
4414 cgroup_rm_cftypes_locked(cfts);
4420 * cgroup_add_cftypes - add an array of cftypes to a subsystem
4421 * @ss: target cgroup subsystem
4422 * @cfts: zero-length name terminated array of cftypes
4424 * Register @cfts to @ss. Files described by @cfts are created for all
4425 * existing cgroups to which @ss is attached and all future cgroups will
4426 * have them too. This function can be called anytime whether @ss is
4429 * Returns 0 on successful registration, -errno on failure. Note that this
4430 * function currently returns 0 as long as @cfts registration is successful
4431 * even if some file creation attempts on existing cgroups fail.
4433 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4437 if (!cgroup_ssid_enabled(ss->id))
4440 if (!cfts || cfts[0].name[0] == '\0')
4443 ret = cgroup_init_cftypes(ss, cfts);
4449 list_add_tail(&cfts->node, &ss->cfts);
4450 ret = cgroup_apply_cftypes(cfts, true);
4452 cgroup_rm_cftypes_locked(cfts);
4459 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
4460 * @ss: target cgroup subsystem
4461 * @cfts: zero-length name terminated array of cftypes
4463 * Similar to cgroup_add_cftypes() but the added files are only used for
4464 * the default hierarchy.
4466 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4470 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4471 cft->flags |= __CFTYPE_ONLY_ON_DFL;
4472 return cgroup_add_cftypes(ss, cfts);
4476 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
4477 * @ss: target cgroup subsystem
4478 * @cfts: zero-length name terminated array of cftypes
4480 * Similar to cgroup_add_cftypes() but the added files are only used for
4481 * the legacy hierarchies.
4483 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4487 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4488 cft->flags |= __CFTYPE_NOT_ON_DFL;
4489 return cgroup_add_cftypes(ss, cfts);
4493 * cgroup_file_notify - generate a file modified event for a cgroup_file
4494 * @cfile: target cgroup_file
4496 * @cfile must have been obtained by setting cftype->file_offset.
4498 void cgroup_file_notify(struct cgroup_file *cfile)
4500 unsigned long flags;
4502 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
4504 unsigned long last = cfile->notified_at;
4505 unsigned long next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
4507 if (time_in_range(jiffies, last, next)) {
4508 timer_reduce(&cfile->notify_timer, next);
4510 kernfs_notify(cfile->kn);
4511 cfile->notified_at = jiffies;
4514 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
4518 * cgroup_file_show - show or hide a hidden cgroup file
4519 * @cfile: target cgroup_file obtained by setting cftype->file_offset
4520 * @show: whether to show or hide
4522 void cgroup_file_show(struct cgroup_file *cfile, bool show)
4524 struct kernfs_node *kn;
4526 spin_lock_irq(&cgroup_file_kn_lock);
4529 spin_unlock_irq(&cgroup_file_kn_lock);
4532 kernfs_show(kn, show);
4538 * css_next_child - find the next child of a given css
4539 * @pos: the current position (%NULL to initiate traversal)
4540 * @parent: css whose children to walk
4542 * This function returns the next child of @parent and should be called
4543 * under either cgroup_mutex or RCU read lock. The only requirement is
4544 * that @parent and @pos are accessible. The next sibling is guaranteed to
4545 * be returned regardless of their states.
4547 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4548 * css which finished ->css_online() is guaranteed to be visible in the
4549 * future iterations and will stay visible until the last reference is put.
4550 * A css which hasn't finished ->css_online() or already finished
4551 * ->css_offline() may show up during traversal. It's each subsystem's
4552 * responsibility to synchronize against on/offlining.
4554 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
4555 struct cgroup_subsys_state *parent)
4557 struct cgroup_subsys_state *next;
4559 cgroup_assert_mutex_or_rcu_locked();
4562 * @pos could already have been unlinked from the sibling list.
4563 * Once a cgroup is removed, its ->sibling.next is no longer
4564 * updated when its next sibling changes. CSS_RELEASED is set when
4565 * @pos is taken off list, at which time its next pointer is valid,
4566 * and, as releases are serialized, the one pointed to by the next
4567 * pointer is guaranteed to not have started release yet. This
4568 * implies that if we observe !CSS_RELEASED on @pos in this RCU
4569 * critical section, the one pointed to by its next pointer is
4570 * guaranteed to not have finished its RCU grace period even if we
4571 * have dropped rcu_read_lock() in-between iterations.
4573 * If @pos has CSS_RELEASED set, its next pointer can't be
4574 * dereferenced; however, as each css is given a monotonically
4575 * increasing unique serial number and always appended to the
4576 * sibling list, the next one can be found by walking the parent's
4577 * children until the first css with higher serial number than
4578 * @pos's. While this path can be slower, it happens iff iteration
4579 * races against release and the race window is very small.
4582 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
4583 } else if (likely(!(pos->flags & CSS_RELEASED))) {
4584 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
4586 list_for_each_entry_rcu(next, &parent->children, sibling,
4587 lockdep_is_held(&cgroup_mutex))
4588 if (next->serial_nr > pos->serial_nr)
4593 * @next, if not pointing to the head, can be dereferenced and is
4596 if (&next->sibling != &parent->children)
4602 * css_next_descendant_pre - find the next descendant for pre-order walk
4603 * @pos: the current position (%NULL to initiate traversal)
4604 * @root: css whose descendants to walk
4606 * To be used by css_for_each_descendant_pre(). Find the next descendant
4607 * to visit for pre-order traversal of @root's descendants. @root is
4608 * included in the iteration and the first node to be visited.
4610 * While this function requires cgroup_mutex or RCU read locking, it
4611 * doesn't require the whole traversal to be contained in a single critical
4612 * section. This function will return the correct next descendant as long
4613 * as both @pos and @root are accessible and @pos is a descendant of @root.
4615 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4616 * css which finished ->css_online() is guaranteed to be visible in the
4617 * future iterations and will stay visible until the last reference is put.
4618 * A css which hasn't finished ->css_online() or already finished
4619 * ->css_offline() may show up during traversal. It's each subsystem's
4620 * responsibility to synchronize against on/offlining.
4622 struct cgroup_subsys_state *
4623 css_next_descendant_pre(struct cgroup_subsys_state *pos,
4624 struct cgroup_subsys_state *root)
4626 struct cgroup_subsys_state *next;
4628 cgroup_assert_mutex_or_rcu_locked();
4630 /* if first iteration, visit @root */
4634 /* visit the first child if exists */
4635 next = css_next_child(NULL, pos);
4639 /* no child, visit my or the closest ancestor's next sibling */
4640 while (pos != root) {
4641 next = css_next_child(pos, pos->parent);
4649 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
4652 * css_rightmost_descendant - return the rightmost descendant of a css
4653 * @pos: css of interest
4655 * Return the rightmost descendant of @pos. If there's no descendant, @pos
4656 * is returned. This can be used during pre-order traversal to skip
4659 * While this function requires cgroup_mutex or RCU read locking, it
4660 * doesn't require the whole traversal to be contained in a single critical
4661 * section. This function will return the correct rightmost descendant as
4662 * long as @pos is accessible.
4664 struct cgroup_subsys_state *
4665 css_rightmost_descendant(struct cgroup_subsys_state *pos)
4667 struct cgroup_subsys_state *last, *tmp;
4669 cgroup_assert_mutex_or_rcu_locked();
4673 /* ->prev isn't RCU safe, walk ->next till the end */
4675 css_for_each_child(tmp, last)
4682 static struct cgroup_subsys_state *
4683 css_leftmost_descendant(struct cgroup_subsys_state *pos)
4685 struct cgroup_subsys_state *last;
4689 pos = css_next_child(NULL, pos);
4696 * css_next_descendant_post - find the next descendant for post-order walk
4697 * @pos: the current position (%NULL to initiate traversal)
4698 * @root: css whose descendants to walk
4700 * To be used by css_for_each_descendant_post(). Find the next descendant
4701 * to visit for post-order traversal of @root's descendants. @root is
4702 * included in the iteration and the last node to be visited.
4704 * While this function requires cgroup_mutex or RCU read locking, it
4705 * doesn't require the whole traversal to be contained in a single critical
4706 * section. This function will return the correct next descendant as long
4707 * as both @pos and @cgroup are accessible and @pos is a descendant of
4710 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4711 * css which finished ->css_online() is guaranteed to be visible in the
4712 * future iterations and will stay visible until the last reference is put.
4713 * A css which hasn't finished ->css_online() or already finished
4714 * ->css_offline() may show up during traversal. It's each subsystem's
4715 * responsibility to synchronize against on/offlining.
4717 struct cgroup_subsys_state *
4718 css_next_descendant_post(struct cgroup_subsys_state *pos,
4719 struct cgroup_subsys_state *root)
4721 struct cgroup_subsys_state *next;
4723 cgroup_assert_mutex_or_rcu_locked();
4725 /* if first iteration, visit leftmost descendant which may be @root */
4727 return css_leftmost_descendant(root);
4729 /* if we visited @root, we're done */
4733 /* if there's an unvisited sibling, visit its leftmost descendant */
4734 next = css_next_child(pos, pos->parent);
4736 return css_leftmost_descendant(next);
4738 /* no sibling left, visit parent */
4743 * css_has_online_children - does a css have online children
4744 * @css: the target css
4746 * Returns %true if @css has any online children; otherwise, %false. This
4747 * function can be called from any context but the caller is responsible
4748 * for synchronizing against on/offlining as necessary.
4750 bool css_has_online_children(struct cgroup_subsys_state *css)
4752 struct cgroup_subsys_state *child;
4756 css_for_each_child(child, css) {
4757 if (child->flags & CSS_ONLINE) {
4766 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4768 struct list_head *l;
4769 struct cgrp_cset_link *link;
4770 struct css_set *cset;
4772 lockdep_assert_held(&css_set_lock);
4774 /* find the next threaded cset */
4775 if (it->tcset_pos) {
4776 l = it->tcset_pos->next;
4778 if (l != it->tcset_head) {
4780 return container_of(l, struct css_set,
4781 threaded_csets_node);
4784 it->tcset_pos = NULL;
4787 /* find the next cset */
4790 if (l == it->cset_head) {
4791 it->cset_pos = NULL;
4796 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4798 link = list_entry(l, struct cgrp_cset_link, cset_link);
4804 /* initialize threaded css_set walking */
4805 if (it->flags & CSS_TASK_ITER_THREADED) {
4807 put_css_set_locked(it->cur_dcset);
4808 it->cur_dcset = cset;
4811 it->tcset_head = &cset->threaded_csets;
4812 it->tcset_pos = &cset->threaded_csets;
4819 * css_task_iter_advance_css_set - advance a task iterator to the next css_set
4820 * @it: the iterator to advance
4822 * Advance @it to the next css_set to walk.
4824 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4826 struct css_set *cset;
4828 lockdep_assert_held(&css_set_lock);
4830 /* Advance to the next non-empty css_set and find first non-empty tasks list*/
4831 while ((cset = css_task_iter_next_css_set(it))) {
4832 if (!list_empty(&cset->tasks)) {
4833 it->cur_tasks_head = &cset->tasks;
4835 } else if (!list_empty(&cset->mg_tasks)) {
4836 it->cur_tasks_head = &cset->mg_tasks;
4838 } else if (!list_empty(&cset->dying_tasks)) {
4839 it->cur_tasks_head = &cset->dying_tasks;
4844 it->task_pos = NULL;
4847 it->task_pos = it->cur_tasks_head->next;
4850 * We don't keep css_sets locked across iteration steps and thus
4851 * need to take steps to ensure that iteration can be resumed after
4852 * the lock is re-acquired. Iteration is performed at two levels -
4853 * css_sets and tasks in them.
4855 * Once created, a css_set never leaves its cgroup lists, so a
4856 * pinned css_set is guaranteed to stay put and we can resume
4857 * iteration afterwards.
4859 * Tasks may leave @cset across iteration steps. This is resolved
4860 * by registering each iterator with the css_set currently being
4861 * walked and making css_set_move_task() advance iterators whose
4862 * next task is leaving.
4865 list_del(&it->iters_node);
4866 put_css_set_locked(it->cur_cset);
4869 it->cur_cset = cset;
4870 list_add(&it->iters_node, &cset->task_iters);
4873 static void css_task_iter_skip(struct css_task_iter *it,
4874 struct task_struct *task)
4876 lockdep_assert_held(&css_set_lock);
4878 if (it->task_pos == &task->cg_list) {
4879 it->task_pos = it->task_pos->next;
4880 it->flags |= CSS_TASK_ITER_SKIPPED;
4884 static void css_task_iter_advance(struct css_task_iter *it)
4886 struct task_struct *task;
4888 lockdep_assert_held(&css_set_lock);
4892 * Advance iterator to find next entry. We go through cset
4893 * tasks, mg_tasks and dying_tasks, when consumed we move onto
4896 if (it->flags & CSS_TASK_ITER_SKIPPED)
4897 it->flags &= ~CSS_TASK_ITER_SKIPPED;
4899 it->task_pos = it->task_pos->next;
4901 if (it->task_pos == &it->cur_cset->tasks) {
4902 it->cur_tasks_head = &it->cur_cset->mg_tasks;
4903 it->task_pos = it->cur_tasks_head->next;
4905 if (it->task_pos == &it->cur_cset->mg_tasks) {
4906 it->cur_tasks_head = &it->cur_cset->dying_tasks;
4907 it->task_pos = it->cur_tasks_head->next;
4909 if (it->task_pos == &it->cur_cset->dying_tasks)
4910 css_task_iter_advance_css_set(it);
4912 /* called from start, proceed to the first cset */
4913 css_task_iter_advance_css_set(it);
4919 task = list_entry(it->task_pos, struct task_struct, cg_list);
4921 if (it->flags & CSS_TASK_ITER_PROCS) {
4922 /* if PROCS, skip over tasks which aren't group leaders */
4923 if (!thread_group_leader(task))
4926 /* and dying leaders w/o live member threads */
4927 if (it->cur_tasks_head == &it->cur_cset->dying_tasks &&
4928 !atomic_read(&task->signal->live))
4931 /* skip all dying ones */
4932 if (it->cur_tasks_head == &it->cur_cset->dying_tasks)
4938 * css_task_iter_start - initiate task iteration
4939 * @css: the css to walk tasks of
4940 * @flags: CSS_TASK_ITER_* flags
4941 * @it: the task iterator to use
4943 * Initiate iteration through the tasks of @css. The caller can call
4944 * css_task_iter_next() to walk through the tasks until the function
4945 * returns NULL. On completion of iteration, css_task_iter_end() must be
4948 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4949 struct css_task_iter *it)
4951 memset(it, 0, sizeof(*it));
4953 spin_lock_irq(&css_set_lock);
4958 if (CGROUP_HAS_SUBSYS_CONFIG && it->ss)
4959 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4961 it->cset_pos = &css->cgroup->cset_links;
4963 it->cset_head = it->cset_pos;
4965 css_task_iter_advance(it);
4967 spin_unlock_irq(&css_set_lock);
4971 * css_task_iter_next - return the next task for the iterator
4972 * @it: the task iterator being iterated
4974 * The "next" function for task iteration. @it should have been
4975 * initialized via css_task_iter_start(). Returns NULL when the iteration
4978 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4981 put_task_struct(it->cur_task);
4982 it->cur_task = NULL;
4985 spin_lock_irq(&css_set_lock);
4987 /* @it may be half-advanced by skips, finish advancing */
4988 if (it->flags & CSS_TASK_ITER_SKIPPED)
4989 css_task_iter_advance(it);
4992 it->cur_task = list_entry(it->task_pos, struct task_struct,
4994 get_task_struct(it->cur_task);
4995 css_task_iter_advance(it);
4998 spin_unlock_irq(&css_set_lock);
5000 return it->cur_task;
5004 * css_task_iter_end - finish task iteration
5005 * @it: the task iterator to finish
5007 * Finish task iteration started by css_task_iter_start().
5009 void css_task_iter_end(struct css_task_iter *it)
5012 spin_lock_irq(&css_set_lock);
5013 list_del(&it->iters_node);
5014 put_css_set_locked(it->cur_cset);
5015 spin_unlock_irq(&css_set_lock);
5019 put_css_set(it->cur_dcset);
5022 put_task_struct(it->cur_task);
5025 static void cgroup_procs_release(struct kernfs_open_file *of)
5027 struct cgroup_file_ctx *ctx = of->priv;
5029 if (ctx->procs.started)
5030 css_task_iter_end(&ctx->procs.iter);
5033 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
5035 struct kernfs_open_file *of = s->private;
5036 struct cgroup_file_ctx *ctx = of->priv;
5041 return css_task_iter_next(&ctx->procs.iter);
5044 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
5045 unsigned int iter_flags)
5047 struct kernfs_open_file *of = s->private;
5048 struct cgroup *cgrp = seq_css(s)->cgroup;
5049 struct cgroup_file_ctx *ctx = of->priv;
5050 struct css_task_iter *it = &ctx->procs.iter;
5053 * When a seq_file is seeked, it's always traversed sequentially
5054 * from position 0, so we can simply keep iterating on !0 *pos.
5056 if (!ctx->procs.started) {
5057 if (WARN_ON_ONCE((*pos)))
5058 return ERR_PTR(-EINVAL);
5059 css_task_iter_start(&cgrp->self, iter_flags, it);
5060 ctx->procs.started = true;
5061 } else if (!(*pos)) {
5062 css_task_iter_end(it);
5063 css_task_iter_start(&cgrp->self, iter_flags, it);
5065 return it->cur_task;
5067 return cgroup_procs_next(s, NULL, NULL);
5070 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
5072 struct cgroup *cgrp = seq_css(s)->cgroup;
5075 * All processes of a threaded subtree belong to the domain cgroup
5076 * of the subtree. Only threads can be distributed across the
5077 * subtree. Reject reads on cgroup.procs in the subtree proper.
5078 * They're always empty anyway.
5080 if (cgroup_is_threaded(cgrp))
5081 return ERR_PTR(-EOPNOTSUPP);
5083 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
5084 CSS_TASK_ITER_THREADED);
5087 static int cgroup_procs_show(struct seq_file *s, void *v)
5089 seq_printf(s, "%d\n", task_pid_vnr(v));
5093 static int cgroup_may_write(const struct cgroup *cgrp, struct super_block *sb)
5096 struct inode *inode;
5098 lockdep_assert_held(&cgroup_mutex);
5100 inode = kernfs_get_inode(sb, cgrp->procs_file.kn);
5104 ret = inode_permission(&nop_mnt_idmap, inode, MAY_WRITE);
5109 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
5110 struct cgroup *dst_cgrp,
5111 struct super_block *sb,
5112 struct cgroup_namespace *ns)
5114 struct cgroup *com_cgrp = src_cgrp;
5117 lockdep_assert_held(&cgroup_mutex);
5119 /* find the common ancestor */
5120 while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
5121 com_cgrp = cgroup_parent(com_cgrp);
5123 /* %current should be authorized to migrate to the common ancestor */
5124 ret = cgroup_may_write(com_cgrp, sb);
5129 * If namespaces are delegation boundaries, %current must be able
5130 * to see both source and destination cgroups from its namespace.
5132 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
5133 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
5134 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
5140 static int cgroup_attach_permissions(struct cgroup *src_cgrp,
5141 struct cgroup *dst_cgrp,
5142 struct super_block *sb, bool threadgroup,
5143 struct cgroup_namespace *ns)
5147 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp, sb, ns);
5151 ret = cgroup_migrate_vet_dst(dst_cgrp);
5155 if (!threadgroup && (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp))
5161 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
5164 struct cgroup_file_ctx *ctx = of->priv;
5165 struct cgroup *src_cgrp, *dst_cgrp;
5166 struct task_struct *task;
5167 const struct cred *saved_cred;
5169 bool threadgroup_locked;
5171 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
5175 task = cgroup_procs_write_start(buf, threadgroup, &threadgroup_locked);
5176 ret = PTR_ERR_OR_ZERO(task);
5180 /* find the source cgroup */
5181 spin_lock_irq(&css_set_lock);
5182 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
5183 spin_unlock_irq(&css_set_lock);
5186 * Process and thread migrations follow same delegation rule. Check
5187 * permissions using the credentials from file open to protect against
5188 * inherited fd attacks.
5190 saved_cred = override_creds(of->file->f_cred);
5191 ret = cgroup_attach_permissions(src_cgrp, dst_cgrp,
5192 of->file->f_path.dentry->d_sb,
5193 threadgroup, ctx->ns);
5194 revert_creds(saved_cred);
5198 ret = cgroup_attach_task(dst_cgrp, task, threadgroup);
5201 cgroup_procs_write_finish(task, threadgroup_locked);
5203 cgroup_kn_unlock(of->kn);
5208 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
5209 char *buf, size_t nbytes, loff_t off)
5211 return __cgroup_procs_write(of, buf, true) ?: nbytes;
5214 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
5216 return __cgroup_procs_start(s, pos, 0);
5219 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
5220 char *buf, size_t nbytes, loff_t off)
5222 return __cgroup_procs_write(of, buf, false) ?: nbytes;
5225 /* cgroup core interface files for the default hierarchy */
5226 static struct cftype cgroup_base_files[] = {
5228 .name = "cgroup.type",
5229 .flags = CFTYPE_NOT_ON_ROOT,
5230 .seq_show = cgroup_type_show,
5231 .write = cgroup_type_write,
5234 .name = "cgroup.procs",
5235 .flags = CFTYPE_NS_DELEGATABLE,
5236 .file_offset = offsetof(struct cgroup, procs_file),
5237 .release = cgroup_procs_release,
5238 .seq_start = cgroup_procs_start,
5239 .seq_next = cgroup_procs_next,
5240 .seq_show = cgroup_procs_show,
5241 .write = cgroup_procs_write,
5244 .name = "cgroup.threads",
5245 .flags = CFTYPE_NS_DELEGATABLE,
5246 .release = cgroup_procs_release,
5247 .seq_start = cgroup_threads_start,
5248 .seq_next = cgroup_procs_next,
5249 .seq_show = cgroup_procs_show,
5250 .write = cgroup_threads_write,
5253 .name = "cgroup.controllers",
5254 .seq_show = cgroup_controllers_show,
5257 .name = "cgroup.subtree_control",
5258 .flags = CFTYPE_NS_DELEGATABLE,
5259 .seq_show = cgroup_subtree_control_show,
5260 .write = cgroup_subtree_control_write,
5263 .name = "cgroup.events",
5264 .flags = CFTYPE_NOT_ON_ROOT,
5265 .file_offset = offsetof(struct cgroup, events_file),
5266 .seq_show = cgroup_events_show,
5269 .name = "cgroup.max.descendants",
5270 .seq_show = cgroup_max_descendants_show,
5271 .write = cgroup_max_descendants_write,
5274 .name = "cgroup.max.depth",
5275 .seq_show = cgroup_max_depth_show,
5276 .write = cgroup_max_depth_write,
5279 .name = "cgroup.stat",
5280 .seq_show = cgroup_stat_show,
5283 .name = "cgroup.freeze",
5284 .flags = CFTYPE_NOT_ON_ROOT,
5285 .seq_show = cgroup_freeze_show,
5286 .write = cgroup_freeze_write,
5289 .name = "cgroup.kill",
5290 .flags = CFTYPE_NOT_ON_ROOT,
5291 .write = cgroup_kill_write,
5295 .seq_show = cpu_stat_show,
5298 .name = "cpu.stat.local",
5299 .seq_show = cpu_local_stat_show,
5304 static struct cftype cgroup_psi_files[] = {
5307 .name = "io.pressure",
5308 .file_offset = offsetof(struct cgroup, psi_files[PSI_IO]),
5309 .seq_show = cgroup_io_pressure_show,
5310 .write = cgroup_io_pressure_write,
5311 .poll = cgroup_pressure_poll,
5312 .release = cgroup_pressure_release,
5315 .name = "memory.pressure",
5316 .file_offset = offsetof(struct cgroup, psi_files[PSI_MEM]),
5317 .seq_show = cgroup_memory_pressure_show,
5318 .write = cgroup_memory_pressure_write,
5319 .poll = cgroup_pressure_poll,
5320 .release = cgroup_pressure_release,
5323 .name = "cpu.pressure",
5324 .file_offset = offsetof(struct cgroup, psi_files[PSI_CPU]),
5325 .seq_show = cgroup_cpu_pressure_show,
5326 .write = cgroup_cpu_pressure_write,
5327 .poll = cgroup_pressure_poll,
5328 .release = cgroup_pressure_release,
5330 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
5332 .name = "irq.pressure",
5333 .file_offset = offsetof(struct cgroup, psi_files[PSI_IRQ]),
5334 .seq_show = cgroup_irq_pressure_show,
5335 .write = cgroup_irq_pressure_write,
5336 .poll = cgroup_pressure_poll,
5337 .release = cgroup_pressure_release,
5341 .name = "cgroup.pressure",
5342 .seq_show = cgroup_pressure_show,
5343 .write = cgroup_pressure_write,
5345 #endif /* CONFIG_PSI */
5350 * css destruction is four-stage process.
5352 * 1. Destruction starts. Killing of the percpu_ref is initiated.
5353 * Implemented in kill_css().
5355 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
5356 * and thus css_tryget_online() is guaranteed to fail, the css can be
5357 * offlined by invoking offline_css(). After offlining, the base ref is
5358 * put. Implemented in css_killed_work_fn().
5360 * 3. When the percpu_ref reaches zero, the only possible remaining
5361 * accessors are inside RCU read sections. css_release() schedules the
5364 * 4. After the grace period, the css can be freed. Implemented in
5365 * css_free_rwork_fn().
5367 * It is actually hairier because both step 2 and 4 require process context
5368 * and thus involve punting to css->destroy_work adding two additional
5369 * steps to the already complex sequence.
5371 static void css_free_rwork_fn(struct work_struct *work)
5373 struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
5374 struct cgroup_subsys_state, destroy_rwork);
5375 struct cgroup_subsys *ss = css->ss;
5376 struct cgroup *cgrp = css->cgroup;
5378 percpu_ref_exit(&css->refcnt);
5382 struct cgroup_subsys_state *parent = css->parent;
5386 cgroup_idr_remove(&ss->css_idr, id);
5392 /* cgroup free path */
5393 atomic_dec(&cgrp->root->nr_cgrps);
5394 cgroup1_pidlist_destroy_all(cgrp);
5395 cancel_work_sync(&cgrp->release_agent_work);
5396 bpf_cgrp_storage_free(cgrp);
5398 if (cgroup_parent(cgrp)) {
5400 * We get a ref to the parent, and put the ref when
5401 * this cgroup is being freed, so it's guaranteed
5402 * that the parent won't be destroyed before its
5405 cgroup_put(cgroup_parent(cgrp));
5406 kernfs_put(cgrp->kn);
5407 psi_cgroup_free(cgrp);
5408 cgroup_rstat_exit(cgrp);
5412 * This is root cgroup's refcnt reaching zero,
5413 * which indicates that the root should be
5416 cgroup_destroy_root(cgrp->root);
5421 static void css_release_work_fn(struct work_struct *work)
5423 struct cgroup_subsys_state *css =
5424 container_of(work, struct cgroup_subsys_state, destroy_work);
5425 struct cgroup_subsys *ss = css->ss;
5426 struct cgroup *cgrp = css->cgroup;
5430 css->flags |= CSS_RELEASED;
5431 list_del_rcu(&css->sibling);
5434 /* css release path */
5435 if (!list_empty(&css->rstat_css_node)) {
5436 cgroup_rstat_flush(cgrp);
5437 list_del_rcu(&css->rstat_css_node);
5440 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
5441 if (ss->css_released)
5442 ss->css_released(css);
5444 struct cgroup *tcgrp;
5446 /* cgroup release path */
5447 TRACE_CGROUP_PATH(release, cgrp);
5449 cgroup_rstat_flush(cgrp);
5451 spin_lock_irq(&css_set_lock);
5452 for (tcgrp = cgroup_parent(cgrp); tcgrp;
5453 tcgrp = cgroup_parent(tcgrp))
5454 tcgrp->nr_dying_descendants--;
5455 spin_unlock_irq(&css_set_lock);
5458 * There are two control paths which try to determine
5459 * cgroup from dentry without going through kernfs -
5460 * cgroupstats_build() and css_tryget_online_from_dir().
5461 * Those are supported by RCU protecting clearing of
5462 * cgrp->kn->priv backpointer.
5465 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
5471 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5472 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
5475 static void css_release(struct percpu_ref *ref)
5477 struct cgroup_subsys_state *css =
5478 container_of(ref, struct cgroup_subsys_state, refcnt);
5480 INIT_WORK(&css->destroy_work, css_release_work_fn);
5481 queue_work(cgroup_destroy_wq, &css->destroy_work);
5484 static void init_and_link_css(struct cgroup_subsys_state *css,
5485 struct cgroup_subsys *ss, struct cgroup *cgrp)
5487 lockdep_assert_held(&cgroup_mutex);
5489 cgroup_get_live(cgrp);
5491 memset(css, 0, sizeof(*css));
5495 INIT_LIST_HEAD(&css->sibling);
5496 INIT_LIST_HEAD(&css->children);
5497 INIT_LIST_HEAD(&css->rstat_css_node);
5498 css->serial_nr = css_serial_nr_next++;
5499 atomic_set(&css->online_cnt, 0);
5501 if (cgroup_parent(cgrp)) {
5502 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
5503 css_get(css->parent);
5506 if (ss->css_rstat_flush)
5507 list_add_rcu(&css->rstat_css_node, &cgrp->rstat_css_list);
5509 BUG_ON(cgroup_css(cgrp, ss));
5512 /* invoke ->css_online() on a new CSS and mark it online if successful */
5513 static int online_css(struct cgroup_subsys_state *css)
5515 struct cgroup_subsys *ss = css->ss;
5518 lockdep_assert_held(&cgroup_mutex);
5521 ret = ss->css_online(css);
5523 css->flags |= CSS_ONLINE;
5524 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
5526 atomic_inc(&css->online_cnt);
5528 atomic_inc(&css->parent->online_cnt);
5533 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
5534 static void offline_css(struct cgroup_subsys_state *css)
5536 struct cgroup_subsys *ss = css->ss;
5538 lockdep_assert_held(&cgroup_mutex);
5540 if (!(css->flags & CSS_ONLINE))
5543 if (ss->css_offline)
5544 ss->css_offline(css);
5546 css->flags &= ~CSS_ONLINE;
5547 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
5549 wake_up_all(&css->cgroup->offline_waitq);
5553 * css_create - create a cgroup_subsys_state
5554 * @cgrp: the cgroup new css will be associated with
5555 * @ss: the subsys of new css
5557 * Create a new css associated with @cgrp - @ss pair. On success, the new
5558 * css is online and installed in @cgrp. This function doesn't create the
5559 * interface files. Returns 0 on success, -errno on failure.
5561 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
5562 struct cgroup_subsys *ss)
5564 struct cgroup *parent = cgroup_parent(cgrp);
5565 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
5566 struct cgroup_subsys_state *css;
5569 lockdep_assert_held(&cgroup_mutex);
5571 css = ss->css_alloc(parent_css);
5573 css = ERR_PTR(-ENOMEM);
5577 init_and_link_css(css, ss, cgrp);
5579 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
5583 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
5588 /* @css is ready to be brought online now, make it visible */
5589 list_add_tail_rcu(&css->sibling, &parent_css->children);
5590 cgroup_idr_replace(&ss->css_idr, css, css->id);
5592 err = online_css(css);
5599 list_del_rcu(&css->sibling);
5601 list_del_rcu(&css->rstat_css_node);
5602 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5603 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
5604 return ERR_PTR(err);
5608 * The returned cgroup is fully initialized including its control mask, but
5609 * it doesn't have the control mask applied.
5611 static struct cgroup *cgroup_create(struct cgroup *parent, const char *name,
5614 struct cgroup_root *root = parent->root;
5615 struct cgroup *cgrp, *tcgrp;
5616 struct kernfs_node *kn;
5617 int level = parent->level + 1;
5620 /* allocate the cgroup and its ID, 0 is reserved for the root */
5621 cgrp = kzalloc(struct_size(cgrp, ancestors, (level + 1)), GFP_KERNEL);
5623 return ERR_PTR(-ENOMEM);
5625 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
5629 ret = cgroup_rstat_init(cgrp);
5631 goto out_cancel_ref;
5633 /* create the directory */
5634 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
5641 init_cgroup_housekeeping(cgrp);
5643 cgrp->self.parent = &parent->self;
5645 cgrp->level = level;
5647 ret = psi_cgroup_alloc(cgrp);
5649 goto out_kernfs_remove;
5651 ret = cgroup_bpf_inherit(cgrp);
5656 * New cgroup inherits effective freeze counter, and
5657 * if the parent has to be frozen, the child has too.
5659 cgrp->freezer.e_freeze = parent->freezer.e_freeze;
5660 if (cgrp->freezer.e_freeze) {
5662 * Set the CGRP_FREEZE flag, so when a process will be
5663 * attached to the child cgroup, it will become frozen.
5664 * At this point the new cgroup is unpopulated, so we can
5665 * consider it frozen immediately.
5667 set_bit(CGRP_FREEZE, &cgrp->flags);
5668 set_bit(CGRP_FROZEN, &cgrp->flags);
5671 spin_lock_irq(&css_set_lock);
5672 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5673 cgrp->ancestors[tcgrp->level] = tcgrp;
5675 if (tcgrp != cgrp) {
5676 tcgrp->nr_descendants++;
5679 * If the new cgroup is frozen, all ancestor cgroups
5680 * get a new frozen descendant, but their state can't
5681 * change because of this.
5683 if (cgrp->freezer.e_freeze)
5684 tcgrp->freezer.nr_frozen_descendants++;
5687 spin_unlock_irq(&css_set_lock);
5689 if (notify_on_release(parent))
5690 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
5692 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
5693 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
5695 cgrp->self.serial_nr = css_serial_nr_next++;
5697 /* allocation complete, commit to creation */
5698 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
5699 atomic_inc(&root->nr_cgrps);
5700 cgroup_get_live(parent);
5703 * On the default hierarchy, a child doesn't automatically inherit
5704 * subtree_control from the parent. Each is configured manually.
5706 if (!cgroup_on_dfl(cgrp))
5707 cgrp->subtree_control = cgroup_control(cgrp);
5709 cgroup_propagate_control(cgrp);
5714 psi_cgroup_free(cgrp);
5716 kernfs_remove(cgrp->kn);
5718 cgroup_rstat_exit(cgrp);
5720 percpu_ref_exit(&cgrp->self.refcnt);
5723 return ERR_PTR(ret);
5726 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
5728 struct cgroup *cgroup;
5732 lockdep_assert_held(&cgroup_mutex);
5734 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
5735 if (cgroup->nr_descendants >= cgroup->max_descendants)
5738 if (level > cgroup->max_depth)
5749 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
5751 struct cgroup *parent, *cgrp;
5754 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
5755 if (strchr(name, '\n'))
5758 parent = cgroup_kn_lock_live(parent_kn, false);
5762 if (!cgroup_check_hierarchy_limits(parent)) {
5767 cgrp = cgroup_create(parent, name, mode);
5769 ret = PTR_ERR(cgrp);
5774 * This extra ref will be put in cgroup_free_fn() and guarantees
5775 * that @cgrp->kn is always accessible.
5777 kernfs_get(cgrp->kn);
5779 ret = cgroup_kn_set_ugid(cgrp->kn);
5783 ret = css_populate_dir(&cgrp->self);
5787 ret = cgroup_apply_control_enable(cgrp);
5791 TRACE_CGROUP_PATH(mkdir, cgrp);
5793 /* let's create and online css's */
5794 kernfs_activate(cgrp->kn);
5800 cgroup_destroy_locked(cgrp);
5802 cgroup_kn_unlock(parent_kn);
5807 * This is called when the refcnt of a css is confirmed to be killed.
5808 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
5809 * initiate destruction and put the css ref from kill_css().
5811 static void css_killed_work_fn(struct work_struct *work)
5813 struct cgroup_subsys_state *css =
5814 container_of(work, struct cgroup_subsys_state, destroy_work);
5821 /* @css can't go away while we're holding cgroup_mutex */
5823 } while (css && atomic_dec_and_test(&css->online_cnt));
5828 /* css kill confirmation processing requires process context, bounce */
5829 static void css_killed_ref_fn(struct percpu_ref *ref)
5831 struct cgroup_subsys_state *css =
5832 container_of(ref, struct cgroup_subsys_state, refcnt);
5834 if (atomic_dec_and_test(&css->online_cnt)) {
5835 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5836 queue_work(cgroup_destroy_wq, &css->destroy_work);
5841 * kill_css - destroy a css
5842 * @css: css to destroy
5844 * This function initiates destruction of @css by removing cgroup interface
5845 * files and putting its base reference. ->css_offline() will be invoked
5846 * asynchronously once css_tryget_online() is guaranteed to fail and when
5847 * the reference count reaches zero, @css will be released.
5849 static void kill_css(struct cgroup_subsys_state *css)
5851 lockdep_assert_held(&cgroup_mutex);
5853 if (css->flags & CSS_DYING)
5856 css->flags |= CSS_DYING;
5859 * This must happen before css is disassociated with its cgroup.
5860 * See seq_css() for details.
5865 * Killing would put the base ref, but we need to keep it alive
5866 * until after ->css_offline().
5871 * cgroup core guarantees that, by the time ->css_offline() is
5872 * invoked, no new css reference will be given out via
5873 * css_tryget_online(). We can't simply call percpu_ref_kill() and
5874 * proceed to offlining css's because percpu_ref_kill() doesn't
5875 * guarantee that the ref is seen as killed on all CPUs on return.
5877 * Use percpu_ref_kill_and_confirm() to get notifications as each
5878 * css is confirmed to be seen as killed on all CPUs.
5880 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5884 * cgroup_destroy_locked - the first stage of cgroup destruction
5885 * @cgrp: cgroup to be destroyed
5887 * css's make use of percpu refcnts whose killing latency shouldn't be
5888 * exposed to userland and are RCU protected. Also, cgroup core needs to
5889 * guarantee that css_tryget_online() won't succeed by the time
5890 * ->css_offline() is invoked. To satisfy all the requirements,
5891 * destruction is implemented in the following two steps.
5893 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
5894 * userland visible parts and start killing the percpu refcnts of
5895 * css's. Set up so that the next stage will be kicked off once all
5896 * the percpu refcnts are confirmed to be killed.
5898 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5899 * rest of destruction. Once all cgroup references are gone, the
5900 * cgroup is RCU-freed.
5902 * This function implements s1. After this step, @cgrp is gone as far as
5903 * the userland is concerned and a new cgroup with the same name may be
5904 * created. As cgroup doesn't care about the names internally, this
5905 * doesn't cause any problem.
5907 static int cgroup_destroy_locked(struct cgroup *cgrp)
5908 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5910 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5911 struct cgroup_subsys_state *css;
5912 struct cgrp_cset_link *link;
5915 lockdep_assert_held(&cgroup_mutex);
5918 * Only migration can raise populated from zero and we're already
5919 * holding cgroup_mutex.
5921 if (cgroup_is_populated(cgrp))
5925 * Make sure there's no live children. We can't test emptiness of
5926 * ->self.children as dead children linger on it while being
5927 * drained; otherwise, "rmdir parent/child parent" may fail.
5929 if (css_has_online_children(&cgrp->self))
5933 * Mark @cgrp and the associated csets dead. The former prevents
5934 * further task migration and child creation by disabling
5935 * cgroup_kn_lock_live(). The latter makes the csets ignored by
5936 * the migration path.
5938 cgrp->self.flags &= ~CSS_ONLINE;
5940 spin_lock_irq(&css_set_lock);
5941 list_for_each_entry(link, &cgrp->cset_links, cset_link)
5942 link->cset->dead = true;
5943 spin_unlock_irq(&css_set_lock);
5945 /* initiate massacre of all css's */
5946 for_each_css(css, ssid, cgrp)
5949 /* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
5950 css_clear_dir(&cgrp->self);
5951 kernfs_remove(cgrp->kn);
5953 if (cgroup_is_threaded(cgrp))
5954 parent->nr_threaded_children--;
5956 spin_lock_irq(&css_set_lock);
5957 for (tcgrp = parent; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5958 tcgrp->nr_descendants--;
5959 tcgrp->nr_dying_descendants++;
5961 * If the dying cgroup is frozen, decrease frozen descendants
5962 * counters of ancestor cgroups.
5964 if (test_bit(CGRP_FROZEN, &cgrp->flags))
5965 tcgrp->freezer.nr_frozen_descendants--;
5967 spin_unlock_irq(&css_set_lock);
5969 cgroup1_check_for_release(parent);
5971 cgroup_bpf_offline(cgrp);
5973 /* put the base reference */
5974 percpu_ref_kill(&cgrp->self.refcnt);
5979 int cgroup_rmdir(struct kernfs_node *kn)
5981 struct cgroup *cgrp;
5984 cgrp = cgroup_kn_lock_live(kn, false);
5988 ret = cgroup_destroy_locked(cgrp);
5990 TRACE_CGROUP_PATH(rmdir, cgrp);
5992 cgroup_kn_unlock(kn);
5996 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5997 .show_options = cgroup_show_options,
5998 .mkdir = cgroup_mkdir,
5999 .rmdir = cgroup_rmdir,
6000 .show_path = cgroup_show_path,
6003 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
6005 struct cgroup_subsys_state *css;
6007 pr_debug("Initializing cgroup subsys %s\n", ss->name);
6011 idr_init(&ss->css_idr);
6012 INIT_LIST_HEAD(&ss->cfts);
6014 /* Create the root cgroup state for this subsystem */
6015 ss->root = &cgrp_dfl_root;
6016 css = ss->css_alloc(NULL);
6017 /* We don't handle early failures gracefully */
6018 BUG_ON(IS_ERR(css));
6019 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
6022 * Root csses are never destroyed and we can't initialize
6023 * percpu_ref during early init. Disable refcnting.
6025 css->flags |= CSS_NO_REF;
6028 /* allocation can't be done safely during early init */
6031 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
6032 BUG_ON(css->id < 0);
6035 /* Update the init_css_set to contain a subsys
6036 * pointer to this state - since the subsystem is
6037 * newly registered, all tasks and hence the
6038 * init_css_set is in the subsystem's root cgroup. */
6039 init_css_set.subsys[ss->id] = css;
6041 have_fork_callback |= (bool)ss->fork << ss->id;
6042 have_exit_callback |= (bool)ss->exit << ss->id;
6043 have_release_callback |= (bool)ss->release << ss->id;
6044 have_canfork_callback |= (bool)ss->can_fork << ss->id;
6046 /* At system boot, before all subsystems have been
6047 * registered, no tasks have been forked, so we don't
6048 * need to invoke fork callbacks here. */
6049 BUG_ON(!list_empty(&init_task.tasks));
6051 BUG_ON(online_css(css));
6057 * cgroup_init_early - cgroup initialization at system boot
6059 * Initialize cgroups at system boot, and initialize any
6060 * subsystems that request early init.
6062 int __init cgroup_init_early(void)
6064 static struct cgroup_fs_context __initdata ctx;
6065 struct cgroup_subsys *ss;
6068 ctx.root = &cgrp_dfl_root;
6069 init_cgroup_root(&ctx);
6070 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
6072 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
6074 for_each_subsys(ss, i) {
6075 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
6076 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
6077 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
6079 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
6080 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
6083 ss->name = cgroup_subsys_name[i];
6084 if (!ss->legacy_name)
6085 ss->legacy_name = cgroup_subsys_name[i];
6088 cgroup_init_subsys(ss, true);
6093 static u16 cgroup_enable_mask __initdata;
6094 static int __init cgroup_disable(char *str);
6097 * cgroup_init - cgroup initialization
6099 * Register cgroup filesystem and /proc file, and initialize
6100 * any subsystems that didn't request early init.
6102 int __init cgroup_init(void)
6104 struct cgroup_subsys *ss;
6107 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
6108 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
6109 BUG_ON(cgroup_init_cftypes(NULL, cgroup_psi_files));
6110 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
6112 cgroup_rstat_boot();
6114 get_user_ns(init_cgroup_ns.user_ns);
6119 * Add init_css_set to the hash table so that dfl_root can link to
6122 hash_add(css_set_table, &init_css_set.hlist,
6123 css_set_hash(init_css_set.subsys));
6125 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
6130 * Apply an implicit disable, knowing that an explicit enable will
6131 * prevent if from doing anything.
6133 cgroup_disable("memory");
6135 for_each_subsys(ss, ssid) {
6136 if (ss->early_init) {
6137 struct cgroup_subsys_state *css =
6138 init_css_set.subsys[ss->id];
6140 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
6142 BUG_ON(css->id < 0);
6144 cgroup_init_subsys(ss, false);
6147 list_add_tail(&init_css_set.e_cset_node[ssid],
6148 &cgrp_dfl_root.cgrp.e_csets[ssid]);
6151 * Setting dfl_root subsys_mask needs to consider the
6152 * disabled flag and cftype registration needs kmalloc,
6153 * both of which aren't available during early_init.
6155 if (!cgroup_ssid_enabled(ssid))
6158 if (cgroup1_ssid_disabled(ssid))
6159 pr_info("Disabling %s control group subsystem in v1 mounts\n",
6162 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
6164 /* implicit controllers must be threaded too */
6165 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
6167 if (ss->implicit_on_dfl)
6168 cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
6169 else if (!ss->dfl_cftypes)
6170 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
6173 cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
6175 if (ss->dfl_cftypes == ss->legacy_cftypes) {
6176 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
6178 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
6179 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
6183 ss->bind(init_css_set.subsys[ssid]);
6186 css_populate_dir(init_css_set.subsys[ssid]);
6190 /* init_css_set.subsys[] has been updated, re-hash */
6191 hash_del(&init_css_set.hlist);
6192 hash_add(css_set_table, &init_css_set.hlist,
6193 css_set_hash(init_css_set.subsys));
6195 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
6196 WARN_ON(register_filesystem(&cgroup_fs_type));
6197 WARN_ON(register_filesystem(&cgroup2_fs_type));
6198 WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show));
6199 #ifdef CONFIG_CPUSETS
6200 WARN_ON(register_filesystem(&cpuset_fs_type));
6206 static int __init cgroup_wq_init(void)
6209 * There isn't much point in executing destruction path in
6210 * parallel. Good chunk is serialized with cgroup_mutex anyway.
6211 * Use 1 for @max_active.
6213 * We would prefer to do this in cgroup_init() above, but that
6214 * is called before init_workqueues(): so leave this until after.
6216 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
6217 BUG_ON(!cgroup_destroy_wq);
6220 core_initcall(cgroup_wq_init);
6222 void cgroup_path_from_kernfs_id(u64 id, char *buf, size_t buflen)
6224 struct kernfs_node *kn;
6226 kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6229 kernfs_path(kn, buf, buflen);
6234 * cgroup_get_from_id : get the cgroup associated with cgroup id
6236 * On success return the cgrp or ERR_PTR on failure
6237 * Only cgroups within current task's cgroup NS are valid.
6239 struct cgroup *cgroup_get_from_id(u64 id)
6241 struct kernfs_node *kn;
6242 struct cgroup *cgrp, *root_cgrp;
6244 kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6246 return ERR_PTR(-ENOENT);
6248 if (kernfs_type(kn) != KERNFS_DIR) {
6250 return ERR_PTR(-ENOENT);
6255 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6256 if (cgrp && !cgroup_tryget(cgrp))
6263 return ERR_PTR(-ENOENT);
6265 root_cgrp = current_cgns_cgroup_dfl();
6266 if (!cgroup_is_descendant(cgrp, root_cgrp)) {
6268 return ERR_PTR(-ENOENT);
6273 EXPORT_SYMBOL_GPL(cgroup_get_from_id);
6276 * proc_cgroup_show()
6277 * - Print task's cgroup paths into seq_file, one line for each hierarchy
6278 * - Used for /proc/<pid>/cgroup.
6280 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
6281 struct pid *pid, struct task_struct *tsk)
6285 struct cgroup_root *root;
6288 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6293 spin_lock_irq(&css_set_lock);
6295 for_each_root(root) {
6296 struct cgroup_subsys *ss;
6297 struct cgroup *cgrp;
6298 int ssid, count = 0;
6300 if (root == &cgrp_dfl_root && !READ_ONCE(cgrp_dfl_visible))
6303 seq_printf(m, "%d:", root->hierarchy_id);
6304 if (root != &cgrp_dfl_root)
6305 for_each_subsys(ss, ssid)
6306 if (root->subsys_mask & (1 << ssid))
6307 seq_printf(m, "%s%s", count++ ? "," : "",
6309 if (strlen(root->name))
6310 seq_printf(m, "%sname=%s", count ? "," : "",
6314 cgrp = task_cgroup_from_root(tsk, root);
6317 * On traditional hierarchies, all zombie tasks show up as
6318 * belonging to the root cgroup. On the default hierarchy,
6319 * while a zombie doesn't show up in "cgroup.procs" and
6320 * thus can't be migrated, its /proc/PID/cgroup keeps
6321 * reporting the cgroup it belonged to before exiting. If
6322 * the cgroup is removed before the zombie is reaped,
6323 * " (deleted)" is appended to the cgroup path.
6325 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
6326 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
6327 current->nsproxy->cgroup_ns);
6328 if (retval >= PATH_MAX)
6329 retval = -ENAMETOOLONG;
6338 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
6339 seq_puts(m, " (deleted)\n");
6346 spin_unlock_irq(&css_set_lock);
6354 * cgroup_fork - initialize cgroup related fields during copy_process()
6355 * @child: pointer to task_struct of forking parent process.
6357 * A task is associated with the init_css_set until cgroup_post_fork()
6358 * attaches it to the target css_set.
6360 void cgroup_fork(struct task_struct *child)
6362 RCU_INIT_POINTER(child->cgroups, &init_css_set);
6363 INIT_LIST_HEAD(&child->cg_list);
6367 * cgroup_v1v2_get_from_file - get a cgroup pointer from a file pointer
6368 * @f: file corresponding to cgroup_dir
6370 * Find the cgroup from a file pointer associated with a cgroup directory.
6371 * Returns a pointer to the cgroup on success. ERR_PTR is returned if the
6372 * cgroup cannot be found.
6374 static struct cgroup *cgroup_v1v2_get_from_file(struct file *f)
6376 struct cgroup_subsys_state *css;
6378 css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
6380 return ERR_CAST(css);
6386 * cgroup_get_from_file - same as cgroup_v1v2_get_from_file, but only supports
6388 * @f: file corresponding to cgroup2_dir
6390 static struct cgroup *cgroup_get_from_file(struct file *f)
6392 struct cgroup *cgrp = cgroup_v1v2_get_from_file(f);
6395 return ERR_CAST(cgrp);
6397 if (!cgroup_on_dfl(cgrp)) {
6399 return ERR_PTR(-EBADF);
6406 * cgroup_css_set_fork - find or create a css_set for a child process
6407 * @kargs: the arguments passed to create the child process
6409 * This functions finds or creates a new css_set which the child
6410 * process will be attached to in cgroup_post_fork(). By default,
6411 * the child process will be given the same css_set as its parent.
6413 * If CLONE_INTO_CGROUP is specified this function will try to find an
6414 * existing css_set which includes the requested cgroup and if not create
6415 * a new css_set that the child will be attached to later. If this function
6416 * succeeds it will hold cgroup_threadgroup_rwsem on return. If
6417 * CLONE_INTO_CGROUP is requested this function will grab cgroup mutex
6418 * before grabbing cgroup_threadgroup_rwsem and will hold a reference
6419 * to the target cgroup.
6421 static int cgroup_css_set_fork(struct kernel_clone_args *kargs)
6422 __acquires(&cgroup_mutex) __acquires(&cgroup_threadgroup_rwsem)
6425 struct cgroup *dst_cgrp = NULL;
6426 struct css_set *cset;
6427 struct super_block *sb;
6430 if (kargs->flags & CLONE_INTO_CGROUP)
6433 cgroup_threadgroup_change_begin(current);
6435 spin_lock_irq(&css_set_lock);
6436 cset = task_css_set(current);
6438 spin_unlock_irq(&css_set_lock);
6440 if (!(kargs->flags & CLONE_INTO_CGROUP)) {
6445 f = fget_raw(kargs->cgroup);
6450 sb = f->f_path.dentry->d_sb;
6452 dst_cgrp = cgroup_get_from_file(f);
6453 if (IS_ERR(dst_cgrp)) {
6454 ret = PTR_ERR(dst_cgrp);
6459 if (cgroup_is_dead(dst_cgrp)) {
6465 * Verify that we the target cgroup is writable for us. This is
6466 * usually done by the vfs layer but since we're not going through
6467 * the vfs layer here we need to do it "manually".
6469 ret = cgroup_may_write(dst_cgrp, sb);
6474 * Spawning a task directly into a cgroup works by passing a file
6475 * descriptor to the target cgroup directory. This can even be an O_PATH
6476 * file descriptor. But it can never be a cgroup.procs file descriptor.
6477 * This was done on purpose so spawning into a cgroup could be
6478 * conceptualized as an atomic
6480 * fd = openat(dfd_cgroup, "cgroup.procs", ...);
6481 * write(fd, <child-pid>, ...);
6483 * sequence, i.e. it's a shorthand for the caller opening and writing
6484 * cgroup.procs of the cgroup indicated by @dfd_cgroup. This allows us
6485 * to always use the caller's credentials.
6487 ret = cgroup_attach_permissions(cset->dfl_cgrp, dst_cgrp, sb,
6488 !(kargs->flags & CLONE_THREAD),
6489 current->nsproxy->cgroup_ns);
6493 kargs->cset = find_css_set(cset, dst_cgrp);
6501 kargs->cgrp = dst_cgrp;
6505 cgroup_threadgroup_change_end(current);
6510 cgroup_put(dst_cgrp);
6513 put_css_set(kargs->cset);
6518 * cgroup_css_set_put_fork - drop references we took during fork
6519 * @kargs: the arguments passed to create the child process
6521 * Drop references to the prepared css_set and target cgroup if
6522 * CLONE_INTO_CGROUP was requested.
6524 static void cgroup_css_set_put_fork(struct kernel_clone_args *kargs)
6525 __releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6527 struct cgroup *cgrp = kargs->cgrp;
6528 struct css_set *cset = kargs->cset;
6530 cgroup_threadgroup_change_end(current);
6537 if (kargs->flags & CLONE_INTO_CGROUP) {
6547 * cgroup_can_fork - called on a new task before the process is exposed
6548 * @child: the child process
6549 * @kargs: the arguments passed to create the child process
6551 * This prepares a new css_set for the child process which the child will
6552 * be attached to in cgroup_post_fork().
6553 * This calls the subsystem can_fork() callbacks. If the cgroup_can_fork()
6554 * callback returns an error, the fork aborts with that error code. This
6555 * allows for a cgroup subsystem to conditionally allow or deny new forks.
6557 int cgroup_can_fork(struct task_struct *child, struct kernel_clone_args *kargs)
6559 struct cgroup_subsys *ss;
6562 ret = cgroup_css_set_fork(kargs);
6566 do_each_subsys_mask(ss, i, have_canfork_callback) {
6567 ret = ss->can_fork(child, kargs->cset);
6570 } while_each_subsys_mask();
6575 for_each_subsys(ss, j) {
6578 if (ss->cancel_fork)
6579 ss->cancel_fork(child, kargs->cset);
6582 cgroup_css_set_put_fork(kargs);
6588 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
6589 * @child: the child process
6590 * @kargs: the arguments passed to create the child process
6592 * This calls the cancel_fork() callbacks if a fork failed *after*
6593 * cgroup_can_fork() succeeded and cleans up references we took to
6594 * prepare a new css_set for the child process in cgroup_can_fork().
6596 void cgroup_cancel_fork(struct task_struct *child,
6597 struct kernel_clone_args *kargs)
6599 struct cgroup_subsys *ss;
6602 for_each_subsys(ss, i)
6603 if (ss->cancel_fork)
6604 ss->cancel_fork(child, kargs->cset);
6606 cgroup_css_set_put_fork(kargs);
6610 * cgroup_post_fork - finalize cgroup setup for the child process
6611 * @child: the child process
6612 * @kargs: the arguments passed to create the child process
6614 * Attach the child process to its css_set calling the subsystem fork()
6617 void cgroup_post_fork(struct task_struct *child,
6618 struct kernel_clone_args *kargs)
6619 __releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6621 unsigned long cgrp_flags = 0;
6623 struct cgroup_subsys *ss;
6624 struct css_set *cset;
6630 spin_lock_irq(&css_set_lock);
6632 /* init tasks are special, only link regular threads */
6633 if (likely(child->pid)) {
6635 cgrp_flags = kargs->cgrp->flags;
6637 cgrp_flags = cset->dfl_cgrp->flags;
6639 WARN_ON_ONCE(!list_empty(&child->cg_list));
6641 css_set_move_task(child, NULL, cset, false);
6647 if (!(child->flags & PF_KTHREAD)) {
6648 if (unlikely(test_bit(CGRP_FREEZE, &cgrp_flags))) {
6650 * If the cgroup has to be frozen, the new task has
6651 * too. Let's set the JOBCTL_TRAP_FREEZE jobctl bit to
6652 * get the task into the frozen state.
6654 spin_lock(&child->sighand->siglock);
6655 WARN_ON_ONCE(child->frozen);
6656 child->jobctl |= JOBCTL_TRAP_FREEZE;
6657 spin_unlock(&child->sighand->siglock);
6660 * Calling cgroup_update_frozen() isn't required here,
6661 * because it will be called anyway a bit later from
6662 * do_freezer_trap(). So we avoid cgroup's transient
6663 * switch from the frozen state and back.
6668 * If the cgroup is to be killed notice it now and take the
6669 * child down right after we finished preparing it for
6672 kill = test_bit(CGRP_KILL, &cgrp_flags);
6675 spin_unlock_irq(&css_set_lock);
6678 * Call ss->fork(). This must happen after @child is linked on
6679 * css_set; otherwise, @child might change state between ->fork()
6680 * and addition to css_set.
6682 do_each_subsys_mask(ss, i, have_fork_callback) {
6684 } while_each_subsys_mask();
6686 /* Make the new cset the root_cset of the new cgroup namespace. */
6687 if (kargs->flags & CLONE_NEWCGROUP) {
6688 struct css_set *rcset = child->nsproxy->cgroup_ns->root_cset;
6691 child->nsproxy->cgroup_ns->root_cset = cset;
6695 /* Cgroup has to be killed so take down child immediately. */
6697 do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, child, PIDTYPE_TGID);
6699 cgroup_css_set_put_fork(kargs);
6703 * cgroup_exit - detach cgroup from exiting task
6704 * @tsk: pointer to task_struct of exiting process
6706 * Description: Detach cgroup from @tsk.
6709 void cgroup_exit(struct task_struct *tsk)
6711 struct cgroup_subsys *ss;
6712 struct css_set *cset;
6715 spin_lock_irq(&css_set_lock);
6717 WARN_ON_ONCE(list_empty(&tsk->cg_list));
6718 cset = task_css_set(tsk);
6719 css_set_move_task(tsk, cset, NULL, false);
6720 list_add_tail(&tsk->cg_list, &cset->dying_tasks);
6724 dec_dl_tasks_cs(tsk);
6726 WARN_ON_ONCE(cgroup_task_frozen(tsk));
6727 if (unlikely(!(tsk->flags & PF_KTHREAD) &&
6728 test_bit(CGRP_FREEZE, &task_dfl_cgroup(tsk)->flags)))
6729 cgroup_update_frozen(task_dfl_cgroup(tsk));
6731 spin_unlock_irq(&css_set_lock);
6733 /* see cgroup_post_fork() for details */
6734 do_each_subsys_mask(ss, i, have_exit_callback) {
6736 } while_each_subsys_mask();
6739 void cgroup_release(struct task_struct *task)
6741 struct cgroup_subsys *ss;
6744 do_each_subsys_mask(ss, ssid, have_release_callback) {
6746 } while_each_subsys_mask();
6748 spin_lock_irq(&css_set_lock);
6749 css_set_skip_task_iters(task_css_set(task), task);
6750 list_del_init(&task->cg_list);
6751 spin_unlock_irq(&css_set_lock);
6754 void cgroup_free(struct task_struct *task)
6756 struct css_set *cset = task_css_set(task);
6760 static int __init cgroup_disable(char *str)
6762 struct cgroup_subsys *ss;
6766 while ((token = strsep(&str, ",")) != NULL) {
6770 for_each_subsys(ss, i) {
6771 if (strcmp(token, ss->name) &&
6772 strcmp(token, ss->legacy_name))
6775 /* An explicit cgroup_enable overrides a disable */
6776 if (cgroup_enable_mask & (1 << i))
6779 static_branch_disable(cgroup_subsys_enabled_key[i]);
6780 pr_info("Disabling %s control group subsystem\n",
6784 for (i = 0; i < OPT_FEATURE_COUNT; i++) {
6785 if (strcmp(token, cgroup_opt_feature_names[i]))
6787 cgroup_feature_disable_mask |= 1 << i;
6788 pr_info("Disabling %s control group feature\n",
6789 cgroup_opt_feature_names[i]);
6795 __setup("cgroup_disable=", cgroup_disable);
6797 static int __init cgroup_enable(char *str)
6799 struct cgroup_subsys *ss;
6803 while ((token = strsep(&str, ",")) != NULL) {
6807 for_each_subsys(ss, i) {
6808 if (strcmp(token, ss->name) &&
6809 strcmp(token, ss->legacy_name))
6812 cgroup_enable_mask |= 1 << i;
6813 static_branch_enable(cgroup_subsys_enabled_key[i]);
6814 pr_info("Enabling %s control group subsystem\n",
6820 __setup("cgroup_enable=", cgroup_enable);
6822 void __init __weak enable_debug_cgroup(void) { }
6824 static int __init enable_cgroup_debug(char *str)
6826 cgroup_debug = true;
6827 enable_debug_cgroup();
6830 __setup("cgroup_debug", enable_cgroup_debug);
6833 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
6834 * @dentry: directory dentry of interest
6835 * @ss: subsystem of interest
6837 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
6838 * to get the corresponding css and return it. If such css doesn't exist
6839 * or can't be pinned, an ERR_PTR value is returned.
6841 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
6842 struct cgroup_subsys *ss)
6844 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
6845 struct file_system_type *s_type = dentry->d_sb->s_type;
6846 struct cgroup_subsys_state *css = NULL;
6847 struct cgroup *cgrp;
6849 /* is @dentry a cgroup dir? */
6850 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
6851 !kn || kernfs_type(kn) != KERNFS_DIR)
6852 return ERR_PTR(-EBADF);
6857 * This path doesn't originate from kernfs and @kn could already
6858 * have been or be removed at any point. @kn->priv is RCU
6859 * protected for this access. See css_release_work_fn() for details.
6861 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6863 css = cgroup_css(cgrp, ss);
6865 if (!css || !css_tryget_online(css))
6866 css = ERR_PTR(-ENOENT);
6873 * css_from_id - lookup css by id
6874 * @id: the cgroup id
6875 * @ss: cgroup subsys to be looked into
6877 * Returns the css if there's valid one with @id, otherwise returns NULL.
6878 * Should be called under rcu_read_lock().
6880 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
6882 WARN_ON_ONCE(!rcu_read_lock_held());
6883 return idr_find(&ss->css_idr, id);
6887 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
6888 * @path: path on the default hierarchy
6890 * Find the cgroup at @path on the default hierarchy, increment its
6891 * reference count and return it. Returns pointer to the found cgroup on
6892 * success, ERR_PTR(-ENOENT) if @path doesn't exist or if the cgroup has already
6893 * been released and ERR_PTR(-ENOTDIR) if @path points to a non-directory.
6895 struct cgroup *cgroup_get_from_path(const char *path)
6897 struct kernfs_node *kn;
6898 struct cgroup *cgrp = ERR_PTR(-ENOENT);
6899 struct cgroup *root_cgrp;
6901 root_cgrp = current_cgns_cgroup_dfl();
6902 kn = kernfs_walk_and_get(root_cgrp->kn, path);
6906 if (kernfs_type(kn) != KERNFS_DIR) {
6907 cgrp = ERR_PTR(-ENOTDIR);
6913 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6914 if (!cgrp || !cgroup_tryget(cgrp))
6915 cgrp = ERR_PTR(-ENOENT);
6924 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
6927 * cgroup_v1v2_get_from_fd - get a cgroup pointer from a fd
6928 * @fd: fd obtained by open(cgroup_dir)
6930 * Find the cgroup from a fd which should be obtained
6931 * by opening a cgroup directory. Returns a pointer to the
6932 * cgroup on success. ERR_PTR is returned if the cgroup
6935 struct cgroup *cgroup_v1v2_get_from_fd(int fd)
6937 struct cgroup *cgrp;
6938 struct fd f = fdget_raw(fd);
6940 return ERR_PTR(-EBADF);
6942 cgrp = cgroup_v1v2_get_from_file(f.file);
6948 * cgroup_get_from_fd - same as cgroup_v1v2_get_from_fd, but only supports
6950 * @fd: fd obtained by open(cgroup2_dir)
6952 struct cgroup *cgroup_get_from_fd(int fd)
6954 struct cgroup *cgrp = cgroup_v1v2_get_from_fd(fd);
6957 return ERR_CAST(cgrp);
6959 if (!cgroup_on_dfl(cgrp)) {
6961 return ERR_PTR(-EBADF);
6965 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
6967 static u64 power_of_ten(int power)
6976 * cgroup_parse_float - parse a floating number
6977 * @input: input string
6978 * @dec_shift: number of decimal digits to shift
6981 * Parse a decimal floating point number in @input and store the result in
6982 * @v with decimal point right shifted @dec_shift times. For example, if
6983 * @input is "12.3456" and @dec_shift is 3, *@v will be set to 12345.
6984 * Returns 0 on success, -errno otherwise.
6986 * There's nothing cgroup specific about this function except that it's
6987 * currently the only user.
6989 int cgroup_parse_float(const char *input, unsigned dec_shift, s64 *v)
6991 s64 whole, frac = 0;
6992 int fstart = 0, fend = 0, flen;
6994 if (!sscanf(input, "%lld.%n%lld%n", &whole, &fstart, &frac, &fend))
6999 flen = fend > fstart ? fend - fstart : 0;
7000 if (flen < dec_shift)
7001 frac *= power_of_ten(dec_shift - flen);
7003 frac = DIV_ROUND_CLOSEST_ULL(frac, power_of_ten(flen - dec_shift));
7005 *v = whole * power_of_ten(dec_shift) + frac;
7010 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
7011 * definition in cgroup-defs.h.
7013 #ifdef CONFIG_SOCK_CGROUP_DATA
7015 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
7017 struct cgroup *cgroup;
7020 /* Don't associate the sock with unrelated interrupted task's cgroup. */
7021 if (in_interrupt()) {
7022 cgroup = &cgrp_dfl_root.cgrp;
7028 struct css_set *cset;
7030 cset = task_css_set(current);
7031 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
7032 cgroup = cset->dfl_cgrp;
7038 skcd->cgroup = cgroup;
7039 cgroup_bpf_get(cgroup);
7043 void cgroup_sk_clone(struct sock_cgroup_data *skcd)
7045 struct cgroup *cgrp = sock_cgroup_ptr(skcd);
7048 * We might be cloning a socket which is left in an empty
7049 * cgroup and the cgroup might have already been rmdir'd.
7050 * Don't use cgroup_get_live().
7053 cgroup_bpf_get(cgrp);
7056 void cgroup_sk_free(struct sock_cgroup_data *skcd)
7058 struct cgroup *cgrp = sock_cgroup_ptr(skcd);
7060 cgroup_bpf_put(cgrp);
7064 #endif /* CONFIG_SOCK_CGROUP_DATA */
7067 static ssize_t show_delegatable_files(struct cftype *files, char *buf,
7068 ssize_t size, const char *prefix)
7073 for (cft = files; cft && cft->name[0] != '\0'; cft++) {
7074 if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
7078 ret += snprintf(buf + ret, size - ret, "%s.", prefix);
7080 ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
7082 if (WARN_ON(ret >= size))
7089 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
7092 struct cgroup_subsys *ss;
7096 ret = show_delegatable_files(cgroup_base_files, buf + ret,
7097 PAGE_SIZE - ret, NULL);
7098 if (cgroup_psi_enabled())
7099 ret += show_delegatable_files(cgroup_psi_files, buf + ret,
7100 PAGE_SIZE - ret, NULL);
7102 for_each_subsys(ss, ssid)
7103 ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
7105 cgroup_subsys_name[ssid]);
7109 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
7111 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
7114 return snprintf(buf, PAGE_SIZE,
7117 "memory_localevents\n"
7118 "memory_recursiveprot\n");
7120 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
7122 static struct attribute *cgroup_sysfs_attrs[] = {
7123 &cgroup_delegate_attr.attr,
7124 &cgroup_features_attr.attr,
7128 static const struct attribute_group cgroup_sysfs_attr_group = {
7129 .attrs = cgroup_sysfs_attrs,
7133 static int __init cgroup_sysfs_init(void)
7135 return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
7137 subsys_initcall(cgroup_sysfs_init);
7139 #endif /* CONFIG_SYSFS */