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/psi.h>
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/cgroup.h>
66 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
68 /* let's not notify more than 100 times per second */
69 #define CGROUP_FILE_NOTIFY_MIN_INTV DIV_ROUND_UP(HZ, 100)
72 * To avoid confusing the compiler (and generating warnings) with code
73 * that attempts to access what would be a 0-element array (i.e. sized
74 * to a potentially empty array when CGROUP_SUBSYS_COUNT == 0), this
75 * constant expression can be added.
77 #define CGROUP_HAS_SUBSYS_CONFIG (CGROUP_SUBSYS_COUNT > 0)
80 * cgroup_mutex is the master lock. Any modification to cgroup or its
81 * hierarchy must be performed while holding it.
83 * css_set_lock protects task->cgroups pointer, the list of css_set
84 * objects, and the chain of tasks off each css_set.
86 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
87 * cgroup.h can use them for lockdep annotations.
89 DEFINE_MUTEX(cgroup_mutex);
90 DEFINE_SPINLOCK(css_set_lock);
92 #ifdef CONFIG_PROVE_RCU
93 EXPORT_SYMBOL_GPL(cgroup_mutex);
94 EXPORT_SYMBOL_GPL(css_set_lock);
97 DEFINE_SPINLOCK(trace_cgroup_path_lock);
98 char trace_cgroup_path[TRACE_CGROUP_PATH_LEN];
99 static bool cgroup_debug __read_mostly;
102 * Protects cgroup_idr and css_idr so that IDs can be released without
103 * grabbing cgroup_mutex.
105 static DEFINE_SPINLOCK(cgroup_idr_lock);
108 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
109 * against file removal/re-creation across css hiding.
111 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
113 DEFINE_PERCPU_RWSEM(cgroup_threadgroup_rwsem);
115 #define cgroup_assert_mutex_or_rcu_locked() \
116 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
117 !lockdep_is_held(&cgroup_mutex), \
118 "cgroup_mutex or RCU read lock required");
121 * cgroup destruction makes heavy use of work items and there can be a lot
122 * of concurrent destructions. Use a separate workqueue so that cgroup
123 * destruction work items don't end up filling up max_active of system_wq
124 * which may lead to deadlock.
126 static struct workqueue_struct *cgroup_destroy_wq;
128 /* generate an array of cgroup subsystem pointers */
129 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
130 struct cgroup_subsys *cgroup_subsys[] = {
131 #include <linux/cgroup_subsys.h>
135 /* array of cgroup subsystem names */
136 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
137 static const char *cgroup_subsys_name[] = {
138 #include <linux/cgroup_subsys.h>
142 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
144 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
145 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
146 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
147 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
148 #include <linux/cgroup_subsys.h>
151 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
152 static struct static_key_true *cgroup_subsys_enabled_key[] = {
153 #include <linux/cgroup_subsys.h>
157 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
158 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
159 #include <linux/cgroup_subsys.h>
163 static DEFINE_PER_CPU(struct cgroup_rstat_cpu, cgrp_dfl_root_rstat_cpu);
165 /* the default hierarchy */
166 struct cgroup_root cgrp_dfl_root = { .cgrp.rstat_cpu = &cgrp_dfl_root_rstat_cpu };
167 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
170 * The default hierarchy always exists but is hidden until mounted for the
171 * first time. This is for backward compatibility.
173 static bool cgrp_dfl_visible;
175 /* some controllers are not supported in the default hierarchy */
176 static u16 cgrp_dfl_inhibit_ss_mask;
178 /* some controllers are implicitly enabled on the default hierarchy */
179 static u16 cgrp_dfl_implicit_ss_mask;
181 /* some controllers can be threaded on the default hierarchy */
182 static u16 cgrp_dfl_threaded_ss_mask;
184 /* The list of hierarchy roots */
185 LIST_HEAD(cgroup_roots);
186 static int cgroup_root_count;
188 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
189 static DEFINE_IDR(cgroup_hierarchy_idr);
192 * Assign a monotonically increasing serial number to csses. It guarantees
193 * cgroups with bigger numbers are newer than those with smaller numbers.
194 * Also, as csses are always appended to the parent's ->children list, it
195 * guarantees that sibling csses are always sorted in the ascending serial
196 * number order on the list. Protected by cgroup_mutex.
198 static u64 css_serial_nr_next = 1;
201 * These bitmasks identify subsystems with specific features to avoid
202 * having to do iterative checks repeatedly.
204 static u16 have_fork_callback __read_mostly;
205 static u16 have_exit_callback __read_mostly;
206 static u16 have_release_callback __read_mostly;
207 static u16 have_canfork_callback __read_mostly;
209 /* cgroup namespace for init task */
210 struct cgroup_namespace init_cgroup_ns = {
211 .ns.count = REFCOUNT_INIT(2),
212 .user_ns = &init_user_ns,
213 .ns.ops = &cgroupns_operations,
214 .ns.inum = PROC_CGROUP_INIT_INO,
215 .root_cset = &init_css_set,
218 static struct file_system_type cgroup2_fs_type;
219 static struct cftype cgroup_base_files[];
221 /* cgroup optional features */
222 enum cgroup_opt_features {
224 OPT_FEATURE_PRESSURE,
229 static const char *cgroup_opt_feature_names[OPT_FEATURE_COUNT] = {
235 static u16 cgroup_feature_disable_mask __read_mostly;
237 static int cgroup_apply_control(struct cgroup *cgrp);
238 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
239 static void css_task_iter_skip(struct css_task_iter *it,
240 struct task_struct *task);
241 static int cgroup_destroy_locked(struct cgroup *cgrp);
242 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
243 struct cgroup_subsys *ss);
244 static void css_release(struct percpu_ref *ref);
245 static void kill_css(struct cgroup_subsys_state *css);
246 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
247 struct cgroup *cgrp, struct cftype cfts[],
251 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
252 * @ssid: subsys ID of interest
254 * cgroup_subsys_enabled() can only be used with literal subsys names which
255 * is fine for individual subsystems but unsuitable for cgroup core. This
256 * is slower static_key_enabled() based test indexed by @ssid.
258 bool cgroup_ssid_enabled(int ssid)
260 if (!CGROUP_HAS_SUBSYS_CONFIG)
263 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
267 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
268 * @cgrp: the cgroup of interest
270 * The default hierarchy is the v2 interface of cgroup and this function
271 * can be used to test whether a cgroup is on the default hierarchy for
272 * cases where a subsystem should behave differently depending on the
275 * List of changed behaviors:
277 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
278 * and "name" are disallowed.
280 * - When mounting an existing superblock, mount options should match.
282 * - Remount is disallowed.
284 * - rename(2) is disallowed.
286 * - "tasks" is removed. Everything should be at process granularity. Use
287 * "cgroup.procs" instead.
289 * - "cgroup.procs" is not sorted. pids will be unique unless they got
290 * recycled in-between reads.
292 * - "release_agent" and "notify_on_release" are removed. Replacement
293 * notification mechanism will be implemented.
295 * - "cgroup.clone_children" is removed.
297 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
298 * and its descendants contain no task; otherwise, 1. The file also
299 * generates kernfs notification which can be monitored through poll and
300 * [di]notify when the value of the file changes.
302 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
303 * take masks of ancestors with non-empty cpus/mems, instead of being
304 * moved to an ancestor.
306 * - cpuset: a task can be moved into an empty cpuset, and again it takes
307 * masks of ancestors.
309 * - blkcg: blk-throttle becomes properly hierarchical.
311 * - debug: disallowed on the default hierarchy.
313 bool cgroup_on_dfl(const struct cgroup *cgrp)
315 return cgrp->root == &cgrp_dfl_root;
318 /* IDR wrappers which synchronize using cgroup_idr_lock */
319 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
324 idr_preload(gfp_mask);
325 spin_lock_bh(&cgroup_idr_lock);
326 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
327 spin_unlock_bh(&cgroup_idr_lock);
332 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
336 spin_lock_bh(&cgroup_idr_lock);
337 ret = idr_replace(idr, ptr, id);
338 spin_unlock_bh(&cgroup_idr_lock);
342 static void cgroup_idr_remove(struct idr *idr, int id)
344 spin_lock_bh(&cgroup_idr_lock);
346 spin_unlock_bh(&cgroup_idr_lock);
349 static bool cgroup_has_tasks(struct cgroup *cgrp)
351 return cgrp->nr_populated_csets;
354 bool cgroup_is_threaded(struct cgroup *cgrp)
356 return cgrp->dom_cgrp != cgrp;
359 /* can @cgrp host both domain and threaded children? */
360 static bool cgroup_is_mixable(struct cgroup *cgrp)
363 * Root isn't under domain level resource control exempting it from
364 * the no-internal-process constraint, so it can serve as a thread
365 * root and a parent of resource domains at the same time.
367 return !cgroup_parent(cgrp);
370 /* can @cgrp become a thread root? Should always be true for a thread root */
371 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
373 /* mixables don't care */
374 if (cgroup_is_mixable(cgrp))
377 /* domain roots can't be nested under threaded */
378 if (cgroup_is_threaded(cgrp))
381 /* can only have either domain or threaded children */
382 if (cgrp->nr_populated_domain_children)
385 /* and no domain controllers can be enabled */
386 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
392 /* is @cgrp root of a threaded subtree? */
393 bool cgroup_is_thread_root(struct cgroup *cgrp)
395 /* thread root should be a domain */
396 if (cgroup_is_threaded(cgrp))
399 /* a domain w/ threaded children is a thread root */
400 if (cgrp->nr_threaded_children)
404 * A domain which has tasks and explicit threaded controllers
405 * enabled is a thread root.
407 if (cgroup_has_tasks(cgrp) &&
408 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
414 /* a domain which isn't connected to the root w/o brekage can't be used */
415 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
417 /* the cgroup itself can be a thread root */
418 if (cgroup_is_threaded(cgrp))
421 /* but the ancestors can't be unless mixable */
422 while ((cgrp = cgroup_parent(cgrp))) {
423 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
425 if (cgroup_is_threaded(cgrp))
432 /* subsystems visibly enabled on a cgroup */
433 static u16 cgroup_control(struct cgroup *cgrp)
435 struct cgroup *parent = cgroup_parent(cgrp);
436 u16 root_ss_mask = cgrp->root->subsys_mask;
439 u16 ss_mask = parent->subtree_control;
441 /* threaded cgroups can only have threaded controllers */
442 if (cgroup_is_threaded(cgrp))
443 ss_mask &= cgrp_dfl_threaded_ss_mask;
447 if (cgroup_on_dfl(cgrp))
448 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
449 cgrp_dfl_implicit_ss_mask);
453 /* subsystems enabled on a cgroup */
454 static u16 cgroup_ss_mask(struct cgroup *cgrp)
456 struct cgroup *parent = cgroup_parent(cgrp);
459 u16 ss_mask = parent->subtree_ss_mask;
461 /* threaded cgroups can only have threaded controllers */
462 if (cgroup_is_threaded(cgrp))
463 ss_mask &= cgrp_dfl_threaded_ss_mask;
467 return cgrp->root->subsys_mask;
471 * cgroup_css - obtain a cgroup's css for the specified subsystem
472 * @cgrp: the cgroup of interest
473 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
475 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
476 * function must be called either under cgroup_mutex or rcu_read_lock() and
477 * the caller is responsible for pinning the returned css if it wants to
478 * keep accessing it outside the said locks. This function may return
479 * %NULL if @cgrp doesn't have @subsys_id enabled.
481 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
482 struct cgroup_subsys *ss)
484 if (CGROUP_HAS_SUBSYS_CONFIG && ss)
485 return rcu_dereference_check(cgrp->subsys[ss->id],
486 lockdep_is_held(&cgroup_mutex));
492 * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
493 * @cgrp: the cgroup of interest
494 * @ss: the subsystem of interest
496 * Find and get @cgrp's css associated with @ss. If the css doesn't exist
497 * or is offline, %NULL is returned.
499 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
500 struct cgroup_subsys *ss)
502 struct cgroup_subsys_state *css;
505 css = cgroup_css(cgrp, ss);
506 if (css && !css_tryget_online(css))
514 * cgroup_e_css_by_mask - obtain a cgroup's effective css for the specified ss
515 * @cgrp: the cgroup of interest
516 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
518 * Similar to cgroup_css() but returns the effective css, which is defined
519 * as the matching css of the nearest ancestor including self which has @ss
520 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
521 * function is guaranteed to return non-NULL css.
523 static struct cgroup_subsys_state *cgroup_e_css_by_mask(struct cgroup *cgrp,
524 struct cgroup_subsys *ss)
526 lockdep_assert_held(&cgroup_mutex);
532 * This function is used while updating css associations and thus
533 * can't test the csses directly. Test ss_mask.
535 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
536 cgrp = cgroup_parent(cgrp);
541 return cgroup_css(cgrp, ss);
545 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
546 * @cgrp: the cgroup of interest
547 * @ss: the subsystem of interest
549 * Find and get the effective css of @cgrp for @ss. The effective css is
550 * defined as the matching css of the nearest ancestor including self which
551 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
552 * the root css is returned, so this function always returns a valid css.
554 * The returned css is not guaranteed to be online, and therefore it is the
555 * callers responsibility to try get a reference for it.
557 struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
558 struct cgroup_subsys *ss)
560 struct cgroup_subsys_state *css;
562 if (!CGROUP_HAS_SUBSYS_CONFIG)
566 css = cgroup_css(cgrp, ss);
570 cgrp = cgroup_parent(cgrp);
573 return init_css_set.subsys[ss->id];
577 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
578 * @cgrp: the cgroup of interest
579 * @ss: the subsystem of interest
581 * Find and get the effective css of @cgrp for @ss. The effective css is
582 * defined as the matching css of the nearest ancestor including self which
583 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
584 * the root css is returned, so this function always returns a valid css.
585 * The returned css must be put using css_put().
587 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
588 struct cgroup_subsys *ss)
590 struct cgroup_subsys_state *css;
592 if (!CGROUP_HAS_SUBSYS_CONFIG)
598 css = cgroup_css(cgrp, ss);
600 if (css && css_tryget_online(css))
602 cgrp = cgroup_parent(cgrp);
605 css = init_css_set.subsys[ss->id];
611 EXPORT_SYMBOL_GPL(cgroup_get_e_css);
613 static void cgroup_get_live(struct cgroup *cgrp)
615 WARN_ON_ONCE(cgroup_is_dead(cgrp));
616 css_get(&cgrp->self);
620 * __cgroup_task_count - count the number of tasks in a cgroup. The caller
621 * is responsible for taking the css_set_lock.
622 * @cgrp: the cgroup in question
624 int __cgroup_task_count(const struct cgroup *cgrp)
627 struct cgrp_cset_link *link;
629 lockdep_assert_held(&css_set_lock);
631 list_for_each_entry(link, &cgrp->cset_links, cset_link)
632 count += link->cset->nr_tasks;
638 * cgroup_task_count - count the number of tasks in a cgroup.
639 * @cgrp: the cgroup in question
641 int cgroup_task_count(const struct cgroup *cgrp)
645 spin_lock_irq(&css_set_lock);
646 count = __cgroup_task_count(cgrp);
647 spin_unlock_irq(&css_set_lock);
652 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
654 struct cgroup *cgrp = of->kn->parent->priv;
655 struct cftype *cft = of_cft(of);
658 * This is open and unprotected implementation of cgroup_css().
659 * seq_css() is only called from a kernfs file operation which has
660 * an active reference on the file. Because all the subsystem
661 * files are drained before a css is disassociated with a cgroup,
662 * the matching css from the cgroup's subsys table is guaranteed to
663 * be and stay valid until the enclosing operation is complete.
665 if (CGROUP_HAS_SUBSYS_CONFIG && cft->ss)
666 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
670 EXPORT_SYMBOL_GPL(of_css);
673 * for_each_css - iterate all css's of a cgroup
674 * @css: the iteration cursor
675 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
676 * @cgrp: the target cgroup to iterate css's of
678 * Should be called under cgroup_[tree_]mutex.
680 #define for_each_css(css, ssid, cgrp) \
681 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
682 if (!((css) = rcu_dereference_check( \
683 (cgrp)->subsys[(ssid)], \
684 lockdep_is_held(&cgroup_mutex)))) { } \
688 * for_each_e_css - iterate all effective css's of a cgroup
689 * @css: the iteration cursor
690 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
691 * @cgrp: the target cgroup to iterate css's of
693 * Should be called under cgroup_[tree_]mutex.
695 #define for_each_e_css(css, ssid, cgrp) \
696 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
697 if (!((css) = cgroup_e_css_by_mask(cgrp, \
698 cgroup_subsys[(ssid)]))) \
703 * do_each_subsys_mask - filter for_each_subsys with a bitmask
704 * @ss: the iteration cursor
705 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
706 * @ss_mask: the bitmask
708 * The block will only run for cases where the ssid-th bit (1 << ssid) of
711 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
712 unsigned long __ss_mask = (ss_mask); \
713 if (!CGROUP_HAS_SUBSYS_CONFIG) { \
717 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
718 (ss) = cgroup_subsys[ssid]; \
721 #define while_each_subsys_mask() \
726 /* iterate over child cgrps, lock should be held throughout iteration */
727 #define cgroup_for_each_live_child(child, cgrp) \
728 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
729 if (({ lockdep_assert_held(&cgroup_mutex); \
730 cgroup_is_dead(child); })) \
734 /* walk live descendants in pre order */
735 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
736 css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
737 if (({ lockdep_assert_held(&cgroup_mutex); \
738 (dsct) = (d_css)->cgroup; \
739 cgroup_is_dead(dsct); })) \
743 /* walk live descendants in postorder */
744 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
745 css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
746 if (({ lockdep_assert_held(&cgroup_mutex); \
747 (dsct) = (d_css)->cgroup; \
748 cgroup_is_dead(dsct); })) \
753 * The default css_set - used by init and its children prior to any
754 * hierarchies being mounted. It contains a pointer to the root state
755 * for each subsystem. Also used to anchor the list of css_sets. Not
756 * reference-counted, to improve performance when child cgroups
757 * haven't been created.
759 struct css_set init_css_set = {
760 .refcount = REFCOUNT_INIT(1),
761 .dom_cset = &init_css_set,
762 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
763 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
764 .dying_tasks = LIST_HEAD_INIT(init_css_set.dying_tasks),
765 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
766 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
767 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
768 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
769 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
772 * The following field is re-initialized when this cset gets linked
773 * in cgroup_init(). However, let's initialize the field
774 * statically too so that the default cgroup can be accessed safely
777 .dfl_cgrp = &cgrp_dfl_root.cgrp,
780 static int css_set_count = 1; /* 1 for init_css_set */
782 static bool css_set_threaded(struct css_set *cset)
784 return cset->dom_cset != cset;
788 * css_set_populated - does a css_set contain any tasks?
789 * @cset: target css_set
791 * css_set_populated() should be the same as !!cset->nr_tasks at steady
792 * state. However, css_set_populated() can be called while a task is being
793 * added to or removed from the linked list before the nr_tasks is
794 * properly updated. Hence, we can't just look at ->nr_tasks here.
796 static bool css_set_populated(struct css_set *cset)
798 lockdep_assert_held(&css_set_lock);
800 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
804 * cgroup_update_populated - update the populated count of a cgroup
805 * @cgrp: the target cgroup
806 * @populated: inc or dec populated count
808 * One of the css_sets associated with @cgrp is either getting its first
809 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
810 * count is propagated towards root so that a given cgroup's
811 * nr_populated_children is zero iff none of its descendants contain any
814 * @cgrp's interface file "cgroup.populated" is zero if both
815 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
816 * 1 otherwise. When the sum changes from or to zero, userland is notified
817 * that the content of the interface file has changed. This can be used to
818 * detect when @cgrp and its descendants become populated or empty.
820 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
822 struct cgroup *child = NULL;
823 int adj = populated ? 1 : -1;
825 lockdep_assert_held(&css_set_lock);
828 bool was_populated = cgroup_is_populated(cgrp);
831 cgrp->nr_populated_csets += adj;
833 if (cgroup_is_threaded(child))
834 cgrp->nr_populated_threaded_children += adj;
836 cgrp->nr_populated_domain_children += adj;
839 if (was_populated == cgroup_is_populated(cgrp))
842 cgroup1_check_for_release(cgrp);
843 TRACE_CGROUP_PATH(notify_populated, cgrp,
844 cgroup_is_populated(cgrp));
845 cgroup_file_notify(&cgrp->events_file);
848 cgrp = cgroup_parent(cgrp);
853 * css_set_update_populated - update populated state of a css_set
854 * @cset: target css_set
855 * @populated: whether @cset is populated or depopulated
857 * @cset is either getting the first task or losing the last. Update the
858 * populated counters of all associated cgroups accordingly.
860 static void css_set_update_populated(struct css_set *cset, bool populated)
862 struct cgrp_cset_link *link;
864 lockdep_assert_held(&css_set_lock);
866 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
867 cgroup_update_populated(link->cgrp, populated);
871 * @task is leaving, advance task iterators which are pointing to it so
872 * that they can resume at the next position. Advancing an iterator might
873 * remove it from the list, use safe walk. See css_task_iter_skip() for
876 static void css_set_skip_task_iters(struct css_set *cset,
877 struct task_struct *task)
879 struct css_task_iter *it, *pos;
881 list_for_each_entry_safe(it, pos, &cset->task_iters, iters_node)
882 css_task_iter_skip(it, task);
886 * css_set_move_task - move a task from one css_set to another
887 * @task: task being moved
888 * @from_cset: css_set @task currently belongs to (may be NULL)
889 * @to_cset: new css_set @task is being moved to (may be NULL)
890 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
892 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
893 * css_set, @from_cset can be NULL. If @task is being disassociated
894 * instead of moved, @to_cset can be NULL.
896 * This function automatically handles populated counter updates and
897 * css_task_iter adjustments but the caller is responsible for managing
898 * @from_cset and @to_cset's reference counts.
900 static void css_set_move_task(struct task_struct *task,
901 struct css_set *from_cset, struct css_set *to_cset,
904 lockdep_assert_held(&css_set_lock);
906 if (to_cset && !css_set_populated(to_cset))
907 css_set_update_populated(to_cset, true);
910 WARN_ON_ONCE(list_empty(&task->cg_list));
912 css_set_skip_task_iters(from_cset, task);
913 list_del_init(&task->cg_list);
914 if (!css_set_populated(from_cset))
915 css_set_update_populated(from_cset, false);
917 WARN_ON_ONCE(!list_empty(&task->cg_list));
922 * We are synchronized through cgroup_threadgroup_rwsem
923 * against PF_EXITING setting such that we can't race
924 * against cgroup_exit()/cgroup_free() dropping the css_set.
926 WARN_ON_ONCE(task->flags & PF_EXITING);
928 cgroup_move_task(task, to_cset);
929 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
935 * hash table for cgroup groups. This improves the performance to find
936 * an existing css_set. This hash doesn't (currently) take into
937 * account cgroups in empty hierarchies.
939 #define CSS_SET_HASH_BITS 7
940 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
942 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
944 unsigned long key = 0UL;
945 struct cgroup_subsys *ss;
948 for_each_subsys(ss, i)
949 key += (unsigned long)css[i];
950 key = (key >> 16) ^ key;
955 void put_css_set_locked(struct css_set *cset)
957 struct cgrp_cset_link *link, *tmp_link;
958 struct cgroup_subsys *ss;
961 lockdep_assert_held(&css_set_lock);
963 if (!refcount_dec_and_test(&cset->refcount))
966 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
968 /* This css_set is dead. Unlink it and release cgroup and css refs */
969 for_each_subsys(ss, ssid) {
970 list_del(&cset->e_cset_node[ssid]);
971 css_put(cset->subsys[ssid]);
973 hash_del(&cset->hlist);
976 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
977 list_del(&link->cset_link);
978 list_del(&link->cgrp_link);
979 if (cgroup_parent(link->cgrp))
980 cgroup_put(link->cgrp);
984 if (css_set_threaded(cset)) {
985 list_del(&cset->threaded_csets_node);
986 put_css_set_locked(cset->dom_cset);
989 kfree_rcu(cset, rcu_head);
993 * compare_css_sets - helper function for find_existing_css_set().
994 * @cset: candidate css_set being tested
995 * @old_cset: existing css_set for a task
996 * @new_cgrp: cgroup that's being entered by the task
997 * @template: desired set of css pointers in css_set (pre-calculated)
999 * Returns true if "cset" matches "old_cset" except for the hierarchy
1000 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
1002 static bool compare_css_sets(struct css_set *cset,
1003 struct css_set *old_cset,
1004 struct cgroup *new_cgrp,
1005 struct cgroup_subsys_state *template[])
1007 struct cgroup *new_dfl_cgrp;
1008 struct list_head *l1, *l2;
1011 * On the default hierarchy, there can be csets which are
1012 * associated with the same set of cgroups but different csses.
1013 * Let's first ensure that csses match.
1015 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
1019 /* @cset's domain should match the default cgroup's */
1020 if (cgroup_on_dfl(new_cgrp))
1021 new_dfl_cgrp = new_cgrp;
1023 new_dfl_cgrp = old_cset->dfl_cgrp;
1025 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
1029 * Compare cgroup pointers in order to distinguish between
1030 * different cgroups in hierarchies. As different cgroups may
1031 * share the same effective css, this comparison is always
1034 l1 = &cset->cgrp_links;
1035 l2 = &old_cset->cgrp_links;
1037 struct cgrp_cset_link *link1, *link2;
1038 struct cgroup *cgrp1, *cgrp2;
1042 /* See if we reached the end - both lists are equal length. */
1043 if (l1 == &cset->cgrp_links) {
1044 BUG_ON(l2 != &old_cset->cgrp_links);
1047 BUG_ON(l2 == &old_cset->cgrp_links);
1049 /* Locate the cgroups associated with these links. */
1050 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
1051 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
1052 cgrp1 = link1->cgrp;
1053 cgrp2 = link2->cgrp;
1054 /* Hierarchies should be linked in the same order. */
1055 BUG_ON(cgrp1->root != cgrp2->root);
1058 * If this hierarchy is the hierarchy of the cgroup
1059 * that's changing, then we need to check that this
1060 * css_set points to the new cgroup; if it's any other
1061 * hierarchy, then this css_set should point to the
1062 * same cgroup as the old css_set.
1064 if (cgrp1->root == new_cgrp->root) {
1065 if (cgrp1 != new_cgrp)
1076 * find_existing_css_set - init css array and find the matching css_set
1077 * @old_cset: the css_set that we're using before the cgroup transition
1078 * @cgrp: the cgroup that we're moving into
1079 * @template: out param for the new set of csses, should be clear on entry
1081 static struct css_set *find_existing_css_set(struct css_set *old_cset,
1082 struct cgroup *cgrp,
1083 struct cgroup_subsys_state *template[])
1085 struct cgroup_root *root = cgrp->root;
1086 struct cgroup_subsys *ss;
1087 struct css_set *cset;
1092 * Build the set of subsystem state objects that we want to see in the
1093 * new css_set. While subsystems can change globally, the entries here
1094 * won't change, so no need for locking.
1096 for_each_subsys(ss, i) {
1097 if (root->subsys_mask & (1UL << i)) {
1099 * @ss is in this hierarchy, so we want the
1100 * effective css from @cgrp.
1102 template[i] = cgroup_e_css_by_mask(cgrp, ss);
1105 * @ss is not in this hierarchy, so we don't want
1106 * to change the css.
1108 template[i] = old_cset->subsys[i];
1112 key = css_set_hash(template);
1113 hash_for_each_possible(css_set_table, cset, hlist, key) {
1114 if (!compare_css_sets(cset, old_cset, cgrp, template))
1117 /* This css_set matches what we need */
1121 /* No existing cgroup group matched */
1125 static void free_cgrp_cset_links(struct list_head *links_to_free)
1127 struct cgrp_cset_link *link, *tmp_link;
1129 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1130 list_del(&link->cset_link);
1136 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1137 * @count: the number of links to allocate
1138 * @tmp_links: list_head the allocated links are put on
1140 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1141 * through ->cset_link. Returns 0 on success or -errno.
1143 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1145 struct cgrp_cset_link *link;
1148 INIT_LIST_HEAD(tmp_links);
1150 for (i = 0; i < count; i++) {
1151 link = kzalloc(sizeof(*link), GFP_KERNEL);
1153 free_cgrp_cset_links(tmp_links);
1156 list_add(&link->cset_link, tmp_links);
1162 * link_css_set - a helper function to link a css_set to a cgroup
1163 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1164 * @cset: the css_set to be linked
1165 * @cgrp: the destination cgroup
1167 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1168 struct cgroup *cgrp)
1170 struct cgrp_cset_link *link;
1172 BUG_ON(list_empty(tmp_links));
1174 if (cgroup_on_dfl(cgrp))
1175 cset->dfl_cgrp = cgrp;
1177 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1182 * Always add links to the tail of the lists so that the lists are
1183 * in chronological order.
1185 list_move_tail(&link->cset_link, &cgrp->cset_links);
1186 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1188 if (cgroup_parent(cgrp))
1189 cgroup_get_live(cgrp);
1193 * find_css_set - return a new css_set with one cgroup updated
1194 * @old_cset: the baseline css_set
1195 * @cgrp: the cgroup to be updated
1197 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1198 * substituted into the appropriate hierarchy.
1200 static struct css_set *find_css_set(struct css_set *old_cset,
1201 struct cgroup *cgrp)
1203 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1204 struct css_set *cset;
1205 struct list_head tmp_links;
1206 struct cgrp_cset_link *link;
1207 struct cgroup_subsys *ss;
1211 lockdep_assert_held(&cgroup_mutex);
1213 /* First see if we already have a cgroup group that matches
1214 * the desired set */
1215 spin_lock_irq(&css_set_lock);
1216 cset = find_existing_css_set(old_cset, cgrp, template);
1219 spin_unlock_irq(&css_set_lock);
1224 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1228 /* Allocate all the cgrp_cset_link objects that we'll need */
1229 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1234 refcount_set(&cset->refcount, 1);
1235 cset->dom_cset = cset;
1236 INIT_LIST_HEAD(&cset->tasks);
1237 INIT_LIST_HEAD(&cset->mg_tasks);
1238 INIT_LIST_HEAD(&cset->dying_tasks);
1239 INIT_LIST_HEAD(&cset->task_iters);
1240 INIT_LIST_HEAD(&cset->threaded_csets);
1241 INIT_HLIST_NODE(&cset->hlist);
1242 INIT_LIST_HEAD(&cset->cgrp_links);
1243 INIT_LIST_HEAD(&cset->mg_preload_node);
1244 INIT_LIST_HEAD(&cset->mg_node);
1246 /* Copy the set of subsystem state objects generated in
1247 * find_existing_css_set() */
1248 memcpy(cset->subsys, template, sizeof(cset->subsys));
1250 spin_lock_irq(&css_set_lock);
1251 /* Add reference counts and links from the new css_set. */
1252 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1253 struct cgroup *c = link->cgrp;
1255 if (c->root == cgrp->root)
1257 link_css_set(&tmp_links, cset, c);
1260 BUG_ON(!list_empty(&tmp_links));
1264 /* Add @cset to the hash table */
1265 key = css_set_hash(cset->subsys);
1266 hash_add(css_set_table, &cset->hlist, key);
1268 for_each_subsys(ss, ssid) {
1269 struct cgroup_subsys_state *css = cset->subsys[ssid];
1271 list_add_tail(&cset->e_cset_node[ssid],
1272 &css->cgroup->e_csets[ssid]);
1276 spin_unlock_irq(&css_set_lock);
1279 * If @cset should be threaded, look up the matching dom_cset and
1280 * link them up. We first fully initialize @cset then look for the
1281 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1282 * to stay empty until we return.
1284 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1285 struct css_set *dcset;
1287 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1293 spin_lock_irq(&css_set_lock);
1294 cset->dom_cset = dcset;
1295 list_add_tail(&cset->threaded_csets_node,
1296 &dcset->threaded_csets);
1297 spin_unlock_irq(&css_set_lock);
1303 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1305 struct cgroup *root_cgrp = kernfs_root_to_node(kf_root)->priv;
1307 return root_cgrp->root;
1310 static int cgroup_init_root_id(struct cgroup_root *root)
1314 lockdep_assert_held(&cgroup_mutex);
1316 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1320 root->hierarchy_id = id;
1324 static void cgroup_exit_root_id(struct cgroup_root *root)
1326 lockdep_assert_held(&cgroup_mutex);
1328 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1331 void cgroup_free_root(struct cgroup_root *root)
1336 static void cgroup_destroy_root(struct cgroup_root *root)
1338 struct cgroup *cgrp = &root->cgrp;
1339 struct cgrp_cset_link *link, *tmp_link;
1341 trace_cgroup_destroy_root(root);
1343 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1345 BUG_ON(atomic_read(&root->nr_cgrps));
1346 BUG_ON(!list_empty(&cgrp->self.children));
1348 /* Rebind all subsystems back to the default hierarchy */
1349 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1352 * Release all the links from cset_links to this hierarchy's
1355 spin_lock_irq(&css_set_lock);
1357 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1358 list_del(&link->cset_link);
1359 list_del(&link->cgrp_link);
1363 spin_unlock_irq(&css_set_lock);
1365 if (!list_empty(&root->root_list)) {
1366 list_del(&root->root_list);
1367 cgroup_root_count--;
1370 cgroup_exit_root_id(root);
1372 mutex_unlock(&cgroup_mutex);
1374 cgroup_rstat_exit(cgrp);
1375 kernfs_destroy_root(root->kf_root);
1376 cgroup_free_root(root);
1380 * look up cgroup associated with current task's cgroup namespace on the
1381 * specified hierarchy
1383 static struct cgroup *
1384 current_cgns_cgroup_from_root(struct cgroup_root *root)
1386 struct cgroup *res = NULL;
1387 struct css_set *cset;
1389 lockdep_assert_held(&css_set_lock);
1393 cset = current->nsproxy->cgroup_ns->root_cset;
1394 if (cset == &init_css_set) {
1396 } else if (root == &cgrp_dfl_root) {
1397 res = cset->dfl_cgrp;
1399 struct cgrp_cset_link *link;
1401 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1402 struct cgroup *c = link->cgrp;
1404 if (c->root == root) {
1416 /* look up cgroup associated with given css_set on the specified hierarchy */
1417 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1418 struct cgroup_root *root)
1420 struct cgroup *res = NULL;
1422 lockdep_assert_held(&cgroup_mutex);
1423 lockdep_assert_held(&css_set_lock);
1425 if (cset == &init_css_set) {
1427 } else if (root == &cgrp_dfl_root) {
1428 res = cset->dfl_cgrp;
1430 struct cgrp_cset_link *link;
1432 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1433 struct cgroup *c = link->cgrp;
1435 if (c->root == root) {
1447 * Return the cgroup for "task" from the given hierarchy. Must be
1448 * called with cgroup_mutex and css_set_lock held.
1450 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1451 struct cgroup_root *root)
1454 * No need to lock the task - since we hold css_set_lock the
1455 * task can't change groups.
1457 return cset_cgroup_from_root(task_css_set(task), root);
1461 * A task must hold cgroup_mutex to modify cgroups.
1463 * Any task can increment and decrement the count field without lock.
1464 * So in general, code holding cgroup_mutex can't rely on the count
1465 * field not changing. However, if the count goes to zero, then only
1466 * cgroup_attach_task() can increment it again. Because a count of zero
1467 * means that no tasks are currently attached, therefore there is no
1468 * way a task attached to that cgroup can fork (the other way to
1469 * increment the count). So code holding cgroup_mutex can safely
1470 * assume that if the count is zero, it will stay zero. Similarly, if
1471 * a task holds cgroup_mutex on a cgroup with zero count, it
1472 * knows that the cgroup won't be removed, as cgroup_rmdir()
1475 * A cgroup can only be deleted if both its 'count' of using tasks
1476 * is zero, and its list of 'children' cgroups is empty. Since all
1477 * tasks in the system use _some_ cgroup, and since there is always at
1478 * least one task in the system (init, pid == 1), therefore, root cgroup
1479 * always has either children cgroups and/or using tasks. So we don't
1480 * need a special hack to ensure that root cgroup cannot be deleted.
1482 * P.S. One more locking exception. RCU is used to guard the
1483 * update of a tasks cgroup pointer by cgroup_attach_task()
1486 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1488 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1491 struct cgroup_subsys *ss = cft->ss;
1493 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1494 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
1495 const char *dbg = (cft->flags & CFTYPE_DEBUG) ? ".__DEBUG__." : "";
1497 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s%s.%s",
1498 dbg, cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1501 strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1507 * cgroup_file_mode - deduce file mode of a control file
1508 * @cft: the control file in question
1510 * S_IRUGO for read, S_IWUSR for write.
1512 static umode_t cgroup_file_mode(const struct cftype *cft)
1516 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1519 if (cft->write_u64 || cft->write_s64 || cft->write) {
1520 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1530 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1531 * @subtree_control: the new subtree_control mask to consider
1532 * @this_ss_mask: available subsystems
1534 * On the default hierarchy, a subsystem may request other subsystems to be
1535 * enabled together through its ->depends_on mask. In such cases, more
1536 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1538 * This function calculates which subsystems need to be enabled if
1539 * @subtree_control is to be applied while restricted to @this_ss_mask.
1541 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1543 u16 cur_ss_mask = subtree_control;
1544 struct cgroup_subsys *ss;
1547 lockdep_assert_held(&cgroup_mutex);
1549 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1552 u16 new_ss_mask = cur_ss_mask;
1554 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1555 new_ss_mask |= ss->depends_on;
1556 } while_each_subsys_mask();
1559 * Mask out subsystems which aren't available. This can
1560 * happen only if some depended-upon subsystems were bound
1561 * to non-default hierarchies.
1563 new_ss_mask &= this_ss_mask;
1565 if (new_ss_mask == cur_ss_mask)
1567 cur_ss_mask = new_ss_mask;
1574 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1575 * @kn: the kernfs_node being serviced
1577 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1578 * the method finishes if locking succeeded. Note that once this function
1579 * returns the cgroup returned by cgroup_kn_lock_live() may become
1580 * inaccessible any time. If the caller intends to continue to access the
1581 * cgroup, it should pin it before invoking this function.
1583 void cgroup_kn_unlock(struct kernfs_node *kn)
1585 struct cgroup *cgrp;
1587 if (kernfs_type(kn) == KERNFS_DIR)
1590 cgrp = kn->parent->priv;
1592 mutex_unlock(&cgroup_mutex);
1594 kernfs_unbreak_active_protection(kn);
1599 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1600 * @kn: the kernfs_node being serviced
1601 * @drain_offline: perform offline draining on the cgroup
1603 * This helper is to be used by a cgroup kernfs method currently servicing
1604 * @kn. It breaks the active protection, performs cgroup locking and
1605 * verifies that the associated cgroup is alive. Returns the cgroup if
1606 * alive; otherwise, %NULL. A successful return should be undone by a
1607 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1608 * cgroup is drained of offlining csses before return.
1610 * Any cgroup kernfs method implementation which requires locking the
1611 * associated cgroup should use this helper. It avoids nesting cgroup
1612 * locking under kernfs active protection and allows all kernfs operations
1613 * including self-removal.
1615 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1617 struct cgroup *cgrp;
1619 if (kernfs_type(kn) == KERNFS_DIR)
1622 cgrp = kn->parent->priv;
1625 * We're gonna grab cgroup_mutex which nests outside kernfs
1626 * active_ref. cgroup liveliness check alone provides enough
1627 * protection against removal. Ensure @cgrp stays accessible and
1628 * break the active_ref protection.
1630 if (!cgroup_tryget(cgrp))
1632 kernfs_break_active_protection(kn);
1635 cgroup_lock_and_drain_offline(cgrp);
1637 mutex_lock(&cgroup_mutex);
1639 if (!cgroup_is_dead(cgrp))
1642 cgroup_kn_unlock(kn);
1646 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1648 char name[CGROUP_FILE_NAME_MAX];
1650 lockdep_assert_held(&cgroup_mutex);
1652 if (cft->file_offset) {
1653 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1654 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1656 spin_lock_irq(&cgroup_file_kn_lock);
1658 spin_unlock_irq(&cgroup_file_kn_lock);
1660 del_timer_sync(&cfile->notify_timer);
1663 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1667 * css_clear_dir - remove subsys files in a cgroup directory
1670 static void css_clear_dir(struct cgroup_subsys_state *css)
1672 struct cgroup *cgrp = css->cgroup;
1673 struct cftype *cfts;
1675 if (!(css->flags & CSS_VISIBLE))
1678 css->flags &= ~CSS_VISIBLE;
1681 if (cgroup_on_dfl(cgrp))
1682 cfts = cgroup_base_files;
1684 cfts = cgroup1_base_files;
1686 cgroup_addrm_files(css, cgrp, cfts, false);
1688 list_for_each_entry(cfts, &css->ss->cfts, node)
1689 cgroup_addrm_files(css, cgrp, cfts, false);
1694 * css_populate_dir - create subsys files in a cgroup directory
1697 * On failure, no file is added.
1699 static int css_populate_dir(struct cgroup_subsys_state *css)
1701 struct cgroup *cgrp = css->cgroup;
1702 struct cftype *cfts, *failed_cfts;
1705 if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
1709 if (cgroup_on_dfl(cgrp))
1710 cfts = cgroup_base_files;
1712 cfts = cgroup1_base_files;
1714 ret = cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1718 list_for_each_entry(cfts, &css->ss->cfts, node) {
1719 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1727 css->flags |= CSS_VISIBLE;
1731 list_for_each_entry(cfts, &css->ss->cfts, node) {
1732 if (cfts == failed_cfts)
1734 cgroup_addrm_files(css, cgrp, cfts, false);
1739 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1741 struct cgroup *dcgrp = &dst_root->cgrp;
1742 struct cgroup_subsys *ss;
1744 u16 dfl_disable_ss_mask = 0;
1746 lockdep_assert_held(&cgroup_mutex);
1748 do_each_subsys_mask(ss, ssid, ss_mask) {
1750 * If @ss has non-root csses attached to it, can't move.
1751 * If @ss is an implicit controller, it is exempt from this
1752 * rule and can be stolen.
1754 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1755 !ss->implicit_on_dfl)
1758 /* can't move between two non-dummy roots either */
1759 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1763 * Collect ssid's that need to be disabled from default
1766 if (ss->root == &cgrp_dfl_root)
1767 dfl_disable_ss_mask |= 1 << ssid;
1769 } while_each_subsys_mask();
1771 if (dfl_disable_ss_mask) {
1772 struct cgroup *scgrp = &cgrp_dfl_root.cgrp;
1775 * Controllers from default hierarchy that need to be rebound
1776 * are all disabled together in one go.
1778 cgrp_dfl_root.subsys_mask &= ~dfl_disable_ss_mask;
1779 WARN_ON(cgroup_apply_control(scgrp));
1780 cgroup_finalize_control(scgrp, 0);
1783 do_each_subsys_mask(ss, ssid, ss_mask) {
1784 struct cgroup_root *src_root = ss->root;
1785 struct cgroup *scgrp = &src_root->cgrp;
1786 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1787 struct css_set *cset;
1789 WARN_ON(!css || cgroup_css(dcgrp, ss));
1791 if (src_root != &cgrp_dfl_root) {
1792 /* disable from the source */
1793 src_root->subsys_mask &= ~(1 << ssid);
1794 WARN_ON(cgroup_apply_control(scgrp));
1795 cgroup_finalize_control(scgrp, 0);
1799 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1800 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1801 ss->root = dst_root;
1802 css->cgroup = dcgrp;
1804 spin_lock_irq(&css_set_lock);
1805 hash_for_each(css_set_table, i, cset, hlist)
1806 list_move_tail(&cset->e_cset_node[ss->id],
1807 &dcgrp->e_csets[ss->id]);
1808 spin_unlock_irq(&css_set_lock);
1810 if (ss->css_rstat_flush) {
1811 list_del_rcu(&css->rstat_css_node);
1812 list_add_rcu(&css->rstat_css_node,
1813 &dcgrp->rstat_css_list);
1816 /* default hierarchy doesn't enable controllers by default */
1817 dst_root->subsys_mask |= 1 << ssid;
1818 if (dst_root == &cgrp_dfl_root) {
1819 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1821 dcgrp->subtree_control |= 1 << ssid;
1822 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1825 ret = cgroup_apply_control(dcgrp);
1827 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1832 } while_each_subsys_mask();
1834 kernfs_activate(dcgrp->kn);
1838 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1839 struct kernfs_root *kf_root)
1843 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1844 struct cgroup *ns_cgroup;
1846 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1850 spin_lock_irq(&css_set_lock);
1851 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1852 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1853 spin_unlock_irq(&css_set_lock);
1855 if (len >= PATH_MAX)
1858 seq_escape(sf, buf, " \t\n\\");
1865 enum cgroup2_param {
1867 Opt_memory_localevents,
1868 Opt_memory_recursiveprot,
1872 static const struct fs_parameter_spec cgroup2_fs_parameters[] = {
1873 fsparam_flag("nsdelegate", Opt_nsdelegate),
1874 fsparam_flag("memory_localevents", Opt_memory_localevents),
1875 fsparam_flag("memory_recursiveprot", Opt_memory_recursiveprot),
1879 static int cgroup2_parse_param(struct fs_context *fc, struct fs_parameter *param)
1881 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1882 struct fs_parse_result result;
1885 opt = fs_parse(fc, cgroup2_fs_parameters, param, &result);
1890 case Opt_nsdelegate:
1891 ctx->flags |= CGRP_ROOT_NS_DELEGATE;
1893 case Opt_memory_localevents:
1894 ctx->flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1896 case Opt_memory_recursiveprot:
1897 ctx->flags |= CGRP_ROOT_MEMORY_RECURSIVE_PROT;
1903 static void apply_cgroup_root_flags(unsigned int root_flags)
1905 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1906 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1907 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1909 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1911 if (root_flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
1912 cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1914 cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1916 if (root_flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT)
1917 cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_RECURSIVE_PROT;
1919 cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_RECURSIVE_PROT;
1923 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1925 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1926 seq_puts(seq, ",nsdelegate");
1927 if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
1928 seq_puts(seq, ",memory_localevents");
1929 if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT)
1930 seq_puts(seq, ",memory_recursiveprot");
1934 static int cgroup_reconfigure(struct fs_context *fc)
1936 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1938 apply_cgroup_root_flags(ctx->flags);
1942 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1944 struct cgroup_subsys *ss;
1947 INIT_LIST_HEAD(&cgrp->self.sibling);
1948 INIT_LIST_HEAD(&cgrp->self.children);
1949 INIT_LIST_HEAD(&cgrp->cset_links);
1950 INIT_LIST_HEAD(&cgrp->pidlists);
1951 mutex_init(&cgrp->pidlist_mutex);
1952 cgrp->self.cgroup = cgrp;
1953 cgrp->self.flags |= CSS_ONLINE;
1954 cgrp->dom_cgrp = cgrp;
1955 cgrp->max_descendants = INT_MAX;
1956 cgrp->max_depth = INT_MAX;
1957 INIT_LIST_HEAD(&cgrp->rstat_css_list);
1958 prev_cputime_init(&cgrp->prev_cputime);
1960 for_each_subsys(ss, ssid)
1961 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1963 init_waitqueue_head(&cgrp->offline_waitq);
1964 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
1967 void init_cgroup_root(struct cgroup_fs_context *ctx)
1969 struct cgroup_root *root = ctx->root;
1970 struct cgroup *cgrp = &root->cgrp;
1972 INIT_LIST_HEAD(&root->root_list);
1973 atomic_set(&root->nr_cgrps, 1);
1975 init_cgroup_housekeeping(cgrp);
1977 root->flags = ctx->flags;
1978 if (ctx->release_agent)
1979 strscpy(root->release_agent_path, ctx->release_agent, PATH_MAX);
1981 strscpy(root->name, ctx->name, MAX_CGROUP_ROOT_NAMELEN);
1982 if (ctx->cpuset_clone_children)
1983 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1986 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask)
1988 LIST_HEAD(tmp_links);
1989 struct cgroup *root_cgrp = &root->cgrp;
1990 struct kernfs_syscall_ops *kf_sops;
1991 struct css_set *cset;
1994 lockdep_assert_held(&cgroup_mutex);
1996 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
2002 * We're accessing css_set_count without locking css_set_lock here,
2003 * but that's OK - it can only be increased by someone holding
2004 * cgroup_lock, and that's us. Later rebinding may disable
2005 * controllers on the default hierarchy and thus create new csets,
2006 * which can't be more than the existing ones. Allocate 2x.
2008 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
2012 ret = cgroup_init_root_id(root);
2016 kf_sops = root == &cgrp_dfl_root ?
2017 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
2019 root->kf_root = kernfs_create_root(kf_sops,
2020 KERNFS_ROOT_CREATE_DEACTIVATED |
2021 KERNFS_ROOT_SUPPORT_EXPORTOP |
2022 KERNFS_ROOT_SUPPORT_USER_XATTR,
2024 if (IS_ERR(root->kf_root)) {
2025 ret = PTR_ERR(root->kf_root);
2028 root_cgrp->kn = kernfs_root_to_node(root->kf_root);
2029 WARN_ON_ONCE(cgroup_ino(root_cgrp) != 1);
2030 root_cgrp->ancestor_ids[0] = cgroup_id(root_cgrp);
2032 ret = css_populate_dir(&root_cgrp->self);
2036 ret = cgroup_rstat_init(root_cgrp);
2040 ret = rebind_subsystems(root, ss_mask);
2044 ret = cgroup_bpf_inherit(root_cgrp);
2047 trace_cgroup_setup_root(root);
2050 * There must be no failure case after here, since rebinding takes
2051 * care of subsystems' refcounts, which are explicitly dropped in
2052 * the failure exit path.
2054 list_add(&root->root_list, &cgroup_roots);
2055 cgroup_root_count++;
2058 * Link the root cgroup in this hierarchy into all the css_set
2061 spin_lock_irq(&css_set_lock);
2062 hash_for_each(css_set_table, i, cset, hlist) {
2063 link_css_set(&tmp_links, cset, root_cgrp);
2064 if (css_set_populated(cset))
2065 cgroup_update_populated(root_cgrp, true);
2067 spin_unlock_irq(&css_set_lock);
2069 BUG_ON(!list_empty(&root_cgrp->self.children));
2070 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
2076 cgroup_rstat_exit(root_cgrp);
2078 kernfs_destroy_root(root->kf_root);
2079 root->kf_root = NULL;
2081 cgroup_exit_root_id(root);
2083 percpu_ref_exit(&root_cgrp->self.refcnt);
2085 free_cgrp_cset_links(&tmp_links);
2089 int cgroup_do_get_tree(struct fs_context *fc)
2091 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2094 ctx->kfc.root = ctx->root->kf_root;
2095 if (fc->fs_type == &cgroup2_fs_type)
2096 ctx->kfc.magic = CGROUP2_SUPER_MAGIC;
2098 ctx->kfc.magic = CGROUP_SUPER_MAGIC;
2099 ret = kernfs_get_tree(fc);
2102 * In non-init cgroup namespace, instead of root cgroup's dentry,
2103 * we return the dentry corresponding to the cgroupns->root_cgrp.
2105 if (!ret && ctx->ns != &init_cgroup_ns) {
2106 struct dentry *nsdentry;
2107 struct super_block *sb = fc->root->d_sb;
2108 struct cgroup *cgrp;
2110 mutex_lock(&cgroup_mutex);
2111 spin_lock_irq(&css_set_lock);
2113 cgrp = cset_cgroup_from_root(ctx->ns->root_cset, ctx->root);
2115 spin_unlock_irq(&css_set_lock);
2116 mutex_unlock(&cgroup_mutex);
2118 nsdentry = kernfs_node_dentry(cgrp->kn, sb);
2120 if (IS_ERR(nsdentry)) {
2121 deactivate_locked_super(sb);
2122 ret = PTR_ERR(nsdentry);
2125 fc->root = nsdentry;
2128 if (!ctx->kfc.new_sb_created)
2129 cgroup_put(&ctx->root->cgrp);
2135 * Destroy a cgroup filesystem context.
2137 static void cgroup_fs_context_free(struct fs_context *fc)
2139 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2142 kfree(ctx->release_agent);
2143 put_cgroup_ns(ctx->ns);
2144 kernfs_free_fs_context(fc);
2148 static int cgroup_get_tree(struct fs_context *fc)
2150 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2153 cgrp_dfl_visible = true;
2154 cgroup_get_live(&cgrp_dfl_root.cgrp);
2155 ctx->root = &cgrp_dfl_root;
2157 ret = cgroup_do_get_tree(fc);
2159 apply_cgroup_root_flags(ctx->flags);
2163 static const struct fs_context_operations cgroup_fs_context_ops = {
2164 .free = cgroup_fs_context_free,
2165 .parse_param = cgroup2_parse_param,
2166 .get_tree = cgroup_get_tree,
2167 .reconfigure = cgroup_reconfigure,
2170 static const struct fs_context_operations cgroup1_fs_context_ops = {
2171 .free = cgroup_fs_context_free,
2172 .parse_param = cgroup1_parse_param,
2173 .get_tree = cgroup1_get_tree,
2174 .reconfigure = cgroup1_reconfigure,
2178 * Initialise the cgroup filesystem creation/reconfiguration context. Notably,
2179 * we select the namespace we're going to use.
2181 static int cgroup_init_fs_context(struct fs_context *fc)
2183 struct cgroup_fs_context *ctx;
2185 ctx = kzalloc(sizeof(struct cgroup_fs_context), GFP_KERNEL);
2189 ctx->ns = current->nsproxy->cgroup_ns;
2190 get_cgroup_ns(ctx->ns);
2191 fc->fs_private = &ctx->kfc;
2192 if (fc->fs_type == &cgroup2_fs_type)
2193 fc->ops = &cgroup_fs_context_ops;
2195 fc->ops = &cgroup1_fs_context_ops;
2196 put_user_ns(fc->user_ns);
2197 fc->user_ns = get_user_ns(ctx->ns->user_ns);
2202 static void cgroup_kill_sb(struct super_block *sb)
2204 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2205 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2208 * If @root doesn't have any children, start killing it.
2209 * This prevents new mounts by disabling percpu_ref_tryget_live().
2211 * And don't kill the default root.
2213 if (list_empty(&root->cgrp.self.children) && root != &cgrp_dfl_root &&
2214 !percpu_ref_is_dying(&root->cgrp.self.refcnt)) {
2215 cgroup_bpf_offline(&root->cgrp);
2216 percpu_ref_kill(&root->cgrp.self.refcnt);
2218 cgroup_put(&root->cgrp);
2222 struct file_system_type cgroup_fs_type = {
2224 .init_fs_context = cgroup_init_fs_context,
2225 .parameters = cgroup1_fs_parameters,
2226 .kill_sb = cgroup_kill_sb,
2227 .fs_flags = FS_USERNS_MOUNT,
2230 static struct file_system_type cgroup2_fs_type = {
2232 .init_fs_context = cgroup_init_fs_context,
2233 .parameters = cgroup2_fs_parameters,
2234 .kill_sb = cgroup_kill_sb,
2235 .fs_flags = FS_USERNS_MOUNT,
2238 #ifdef CONFIG_CPUSETS
2239 static const struct fs_context_operations cpuset_fs_context_ops = {
2240 .get_tree = cgroup1_get_tree,
2241 .free = cgroup_fs_context_free,
2245 * This is ugly, but preserves the userspace API for existing cpuset
2246 * users. If someone tries to mount the "cpuset" filesystem, we
2247 * silently switch it to mount "cgroup" instead
2249 static int cpuset_init_fs_context(struct fs_context *fc)
2251 char *agent = kstrdup("/sbin/cpuset_release_agent", GFP_USER);
2252 struct cgroup_fs_context *ctx;
2255 err = cgroup_init_fs_context(fc);
2261 fc->ops = &cpuset_fs_context_ops;
2263 ctx = cgroup_fc2context(fc);
2264 ctx->subsys_mask = 1 << cpuset_cgrp_id;
2265 ctx->flags |= CGRP_ROOT_NOPREFIX;
2266 ctx->release_agent = agent;
2268 get_filesystem(&cgroup_fs_type);
2269 put_filesystem(fc->fs_type);
2270 fc->fs_type = &cgroup_fs_type;
2275 static struct file_system_type cpuset_fs_type = {
2277 .init_fs_context = cpuset_init_fs_context,
2278 .fs_flags = FS_USERNS_MOUNT,
2282 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2283 struct cgroup_namespace *ns)
2285 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2287 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2290 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2291 struct cgroup_namespace *ns)
2295 mutex_lock(&cgroup_mutex);
2296 spin_lock_irq(&css_set_lock);
2298 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2300 spin_unlock_irq(&css_set_lock);
2301 mutex_unlock(&cgroup_mutex);
2305 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2308 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2309 * @task: target task
2310 * @buf: the buffer to write the path into
2311 * @buflen: the length of the buffer
2313 * Determine @task's cgroup on the first (the one with the lowest non-zero
2314 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2315 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2316 * cgroup controller callbacks.
2318 * Return value is the same as kernfs_path().
2320 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2322 struct cgroup_root *root;
2323 struct cgroup *cgrp;
2324 int hierarchy_id = 1;
2327 mutex_lock(&cgroup_mutex);
2328 spin_lock_irq(&css_set_lock);
2330 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2333 cgrp = task_cgroup_from_root(task, root);
2334 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2336 /* if no hierarchy exists, everyone is in "/" */
2337 ret = strlcpy(buf, "/", buflen);
2340 spin_unlock_irq(&css_set_lock);
2341 mutex_unlock(&cgroup_mutex);
2344 EXPORT_SYMBOL_GPL(task_cgroup_path);
2347 * cgroup_migrate_add_task - add a migration target task to a migration context
2348 * @task: target task
2349 * @mgctx: target migration context
2351 * Add @task, which is a migration target, to @mgctx->tset. This function
2352 * becomes noop if @task doesn't need to be migrated. @task's css_set
2353 * should have been added as a migration source and @task->cg_list will be
2354 * moved from the css_set's tasks list to mg_tasks one.
2356 static void cgroup_migrate_add_task(struct task_struct *task,
2357 struct cgroup_mgctx *mgctx)
2359 struct css_set *cset;
2361 lockdep_assert_held(&css_set_lock);
2363 /* @task either already exited or can't exit until the end */
2364 if (task->flags & PF_EXITING)
2367 /* cgroup_threadgroup_rwsem protects racing against forks */
2368 WARN_ON_ONCE(list_empty(&task->cg_list));
2370 cset = task_css_set(task);
2371 if (!cset->mg_src_cgrp)
2374 mgctx->tset.nr_tasks++;
2376 list_move_tail(&task->cg_list, &cset->mg_tasks);
2377 if (list_empty(&cset->mg_node))
2378 list_add_tail(&cset->mg_node,
2379 &mgctx->tset.src_csets);
2380 if (list_empty(&cset->mg_dst_cset->mg_node))
2381 list_add_tail(&cset->mg_dst_cset->mg_node,
2382 &mgctx->tset.dst_csets);
2386 * cgroup_taskset_first - reset taskset and return the first task
2387 * @tset: taskset of interest
2388 * @dst_cssp: output variable for the destination css
2390 * @tset iteration is initialized and the first task is returned.
2392 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2393 struct cgroup_subsys_state **dst_cssp)
2395 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2396 tset->cur_task = NULL;
2398 return cgroup_taskset_next(tset, dst_cssp);
2402 * cgroup_taskset_next - iterate to the next task in taskset
2403 * @tset: taskset of interest
2404 * @dst_cssp: output variable for the destination css
2406 * Return the next task in @tset. Iteration must have been initialized
2407 * with cgroup_taskset_first().
2409 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2410 struct cgroup_subsys_state **dst_cssp)
2412 struct css_set *cset = tset->cur_cset;
2413 struct task_struct *task = tset->cur_task;
2415 while (CGROUP_HAS_SUBSYS_CONFIG && &cset->mg_node != tset->csets) {
2417 task = list_first_entry(&cset->mg_tasks,
2418 struct task_struct, cg_list);
2420 task = list_next_entry(task, cg_list);
2422 if (&task->cg_list != &cset->mg_tasks) {
2423 tset->cur_cset = cset;
2424 tset->cur_task = task;
2427 * This function may be called both before and
2428 * after cgroup_taskset_migrate(). The two cases
2429 * can be distinguished by looking at whether @cset
2430 * has its ->mg_dst_cset set.
2432 if (cset->mg_dst_cset)
2433 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2435 *dst_cssp = cset->subsys[tset->ssid];
2440 cset = list_next_entry(cset, mg_node);
2448 * cgroup_migrate_execute - migrate a taskset
2449 * @mgctx: migration context
2451 * Migrate tasks in @mgctx as setup by migration preparation functions.
2452 * This function fails iff one of the ->can_attach callbacks fails and
2453 * guarantees that either all or none of the tasks in @mgctx are migrated.
2454 * @mgctx is consumed regardless of success.
2456 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2458 struct cgroup_taskset *tset = &mgctx->tset;
2459 struct cgroup_subsys *ss;
2460 struct task_struct *task, *tmp_task;
2461 struct css_set *cset, *tmp_cset;
2462 int ssid, failed_ssid, ret;
2464 /* check that we can legitimately attach to the cgroup */
2465 if (tset->nr_tasks) {
2466 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2467 if (ss->can_attach) {
2469 ret = ss->can_attach(tset);
2472 goto out_cancel_attach;
2475 } while_each_subsys_mask();
2479 * Now that we're guaranteed success, proceed to move all tasks to
2480 * the new cgroup. There are no failure cases after here, so this
2481 * is the commit point.
2483 spin_lock_irq(&css_set_lock);
2484 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2485 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2486 struct css_set *from_cset = task_css_set(task);
2487 struct css_set *to_cset = cset->mg_dst_cset;
2489 get_css_set(to_cset);
2490 to_cset->nr_tasks++;
2491 css_set_move_task(task, from_cset, to_cset, true);
2492 from_cset->nr_tasks--;
2494 * If the source or destination cgroup is frozen,
2495 * the task might require to change its state.
2497 cgroup_freezer_migrate_task(task, from_cset->dfl_cgrp,
2499 put_css_set_locked(from_cset);
2503 spin_unlock_irq(&css_set_lock);
2506 * Migration is committed, all target tasks are now on dst_csets.
2507 * Nothing is sensitive to fork() after this point. Notify
2508 * controllers that migration is complete.
2510 tset->csets = &tset->dst_csets;
2512 if (tset->nr_tasks) {
2513 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2518 } while_each_subsys_mask();
2522 goto out_release_tset;
2525 if (tset->nr_tasks) {
2526 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2527 if (ssid == failed_ssid)
2529 if (ss->cancel_attach) {
2531 ss->cancel_attach(tset);
2533 } while_each_subsys_mask();
2536 spin_lock_irq(&css_set_lock);
2537 list_splice_init(&tset->dst_csets, &tset->src_csets);
2538 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2539 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2540 list_del_init(&cset->mg_node);
2542 spin_unlock_irq(&css_set_lock);
2545 * Re-initialize the cgroup_taskset structure in case it is reused
2546 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2550 tset->csets = &tset->src_csets;
2555 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2556 * @dst_cgrp: destination cgroup to test
2558 * On the default hierarchy, except for the mixable, (possible) thread root
2559 * and threaded cgroups, subtree_control must be zero for migration
2560 * destination cgroups with tasks so that child cgroups don't compete
2563 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2565 /* v1 doesn't have any restriction */
2566 if (!cgroup_on_dfl(dst_cgrp))
2569 /* verify @dst_cgrp can host resources */
2570 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2573 /* mixables don't care */
2574 if (cgroup_is_mixable(dst_cgrp))
2578 * If @dst_cgrp is already or can become a thread root or is
2579 * threaded, it doesn't matter.
2581 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2584 /* apply no-internal-process constraint */
2585 if (dst_cgrp->subtree_control)
2592 * cgroup_migrate_finish - cleanup after attach
2593 * @mgctx: migration context
2595 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2596 * those functions for details.
2598 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2600 LIST_HEAD(preloaded);
2601 struct css_set *cset, *tmp_cset;
2603 lockdep_assert_held(&cgroup_mutex);
2605 spin_lock_irq(&css_set_lock);
2607 list_splice_tail_init(&mgctx->preloaded_src_csets, &preloaded);
2608 list_splice_tail_init(&mgctx->preloaded_dst_csets, &preloaded);
2610 list_for_each_entry_safe(cset, tmp_cset, &preloaded, mg_preload_node) {
2611 cset->mg_src_cgrp = NULL;
2612 cset->mg_dst_cgrp = NULL;
2613 cset->mg_dst_cset = NULL;
2614 list_del_init(&cset->mg_preload_node);
2615 put_css_set_locked(cset);
2618 spin_unlock_irq(&css_set_lock);
2622 * cgroup_migrate_add_src - add a migration source css_set
2623 * @src_cset: the source css_set to add
2624 * @dst_cgrp: the destination cgroup
2625 * @mgctx: migration context
2627 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2628 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2629 * up by cgroup_migrate_finish().
2631 * This function may be called without holding cgroup_threadgroup_rwsem
2632 * even if the target is a process. Threads may be created and destroyed
2633 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2634 * into play and the preloaded css_sets are guaranteed to cover all
2637 void cgroup_migrate_add_src(struct css_set *src_cset,
2638 struct cgroup *dst_cgrp,
2639 struct cgroup_mgctx *mgctx)
2641 struct cgroup *src_cgrp;
2643 lockdep_assert_held(&cgroup_mutex);
2644 lockdep_assert_held(&css_set_lock);
2647 * If ->dead, @src_set is associated with one or more dead cgroups
2648 * and doesn't contain any migratable tasks. Ignore it early so
2649 * that the rest of migration path doesn't get confused by it.
2654 if (!list_empty(&src_cset->mg_preload_node))
2657 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2659 WARN_ON(src_cset->mg_src_cgrp);
2660 WARN_ON(src_cset->mg_dst_cgrp);
2661 WARN_ON(!list_empty(&src_cset->mg_tasks));
2662 WARN_ON(!list_empty(&src_cset->mg_node));
2664 src_cset->mg_src_cgrp = src_cgrp;
2665 src_cset->mg_dst_cgrp = dst_cgrp;
2666 get_css_set(src_cset);
2667 list_add_tail(&src_cset->mg_preload_node, &mgctx->preloaded_src_csets);
2671 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2672 * @mgctx: migration context
2674 * Tasks are about to be moved and all the source css_sets have been
2675 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2676 * pins all destination css_sets, links each to its source, and append them
2677 * to @mgctx->preloaded_dst_csets.
2679 * This function must be called after cgroup_migrate_add_src() has been
2680 * called on each migration source css_set. After migration is performed
2681 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2684 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2686 struct css_set *src_cset, *tmp_cset;
2688 lockdep_assert_held(&cgroup_mutex);
2690 /* look up the dst cset for each src cset and link it to src */
2691 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2693 struct css_set *dst_cset;
2694 struct cgroup_subsys *ss;
2697 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2701 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2704 * If src cset equals dst, it's noop. Drop the src.
2705 * cgroup_migrate() will skip the cset too. Note that we
2706 * can't handle src == dst as some nodes are used by both.
2708 if (src_cset == dst_cset) {
2709 src_cset->mg_src_cgrp = NULL;
2710 src_cset->mg_dst_cgrp = NULL;
2711 list_del_init(&src_cset->mg_preload_node);
2712 put_css_set(src_cset);
2713 put_css_set(dst_cset);
2717 src_cset->mg_dst_cset = dst_cset;
2719 if (list_empty(&dst_cset->mg_preload_node))
2720 list_add_tail(&dst_cset->mg_preload_node,
2721 &mgctx->preloaded_dst_csets);
2723 put_css_set(dst_cset);
2725 for_each_subsys(ss, ssid)
2726 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2727 mgctx->ss_mask |= 1 << ssid;
2734 * cgroup_migrate - migrate a process or task to a cgroup
2735 * @leader: the leader of the process or the task to migrate
2736 * @threadgroup: whether @leader points to the whole process or a single task
2737 * @mgctx: migration context
2739 * Migrate a process or task denoted by @leader. If migrating a process,
2740 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2741 * responsible for invoking cgroup_migrate_add_src() and
2742 * cgroup_migrate_prepare_dst() on the targets before invoking this
2743 * function and following up with cgroup_migrate_finish().
2745 * As long as a controller's ->can_attach() doesn't fail, this function is
2746 * guaranteed to succeed. This means that, excluding ->can_attach()
2747 * failure, when migrating multiple targets, the success or failure can be
2748 * decided for all targets by invoking group_migrate_prepare_dst() before
2749 * actually starting migrating.
2751 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2752 struct cgroup_mgctx *mgctx)
2754 struct task_struct *task;
2757 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2758 * already PF_EXITING could be freed from underneath us unless we
2759 * take an rcu_read_lock.
2761 spin_lock_irq(&css_set_lock);
2765 cgroup_migrate_add_task(task, mgctx);
2768 } while_each_thread(leader, task);
2770 spin_unlock_irq(&css_set_lock);
2772 return cgroup_migrate_execute(mgctx);
2776 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2777 * @dst_cgrp: the cgroup to attach to
2778 * @leader: the task or the leader of the threadgroup to be attached
2779 * @threadgroup: attach the whole threadgroup?
2781 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2783 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2786 DEFINE_CGROUP_MGCTX(mgctx);
2787 struct task_struct *task;
2790 /* look up all src csets */
2791 spin_lock_irq(&css_set_lock);
2795 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2798 } while_each_thread(leader, task);
2800 spin_unlock_irq(&css_set_lock);
2802 /* prepare dst csets and commit */
2803 ret = cgroup_migrate_prepare_dst(&mgctx);
2805 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2807 cgroup_migrate_finish(&mgctx);
2810 TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
2815 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup,
2817 __acquires(&cgroup_threadgroup_rwsem)
2819 struct task_struct *tsk;
2822 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2823 return ERR_PTR(-EINVAL);
2826 * If we migrate a single thread, we don't care about threadgroup
2827 * stability. If the thread is `current`, it won't exit(2) under our
2828 * hands or change PID through exec(2). We exclude
2829 * cgroup_update_dfl_csses and other cgroup_{proc,thread}s_write
2830 * callers by cgroup_mutex.
2831 * Therefore, we can skip the global lock.
2833 lockdep_assert_held(&cgroup_mutex);
2834 if (pid || threadgroup) {
2835 percpu_down_write(&cgroup_threadgroup_rwsem);
2843 tsk = find_task_by_vpid(pid);
2845 tsk = ERR_PTR(-ESRCH);
2846 goto out_unlock_threadgroup;
2853 tsk = tsk->group_leader;
2856 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2857 * If userland migrates such a kthread to a non-root cgroup, it can
2858 * become trapped in a cpuset, or RT kthread may be born in a
2859 * cgroup with no rt_runtime allocated. Just say no.
2861 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2862 tsk = ERR_PTR(-EINVAL);
2863 goto out_unlock_threadgroup;
2866 get_task_struct(tsk);
2867 goto out_unlock_rcu;
2869 out_unlock_threadgroup:
2871 percpu_up_write(&cgroup_threadgroup_rwsem);
2879 void cgroup_procs_write_finish(struct task_struct *task, bool locked)
2880 __releases(&cgroup_threadgroup_rwsem)
2882 struct cgroup_subsys *ss;
2885 /* release reference from cgroup_procs_write_start() */
2886 put_task_struct(task);
2889 percpu_up_write(&cgroup_threadgroup_rwsem);
2890 for_each_subsys(ss, ssid)
2891 if (ss->post_attach)
2895 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2897 struct cgroup_subsys *ss;
2898 bool printed = false;
2901 do_each_subsys_mask(ss, ssid, ss_mask) {
2904 seq_puts(seq, ss->name);
2906 } while_each_subsys_mask();
2908 seq_putc(seq, '\n');
2911 /* show controllers which are enabled from the parent */
2912 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2914 struct cgroup *cgrp = seq_css(seq)->cgroup;
2916 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2920 /* show controllers which are enabled for a given cgroup's children */
2921 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2923 struct cgroup *cgrp = seq_css(seq)->cgroup;
2925 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2930 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2931 * @cgrp: root of the subtree to update csses for
2933 * @cgrp's control masks have changed and its subtree's css associations
2934 * need to be updated accordingly. This function looks up all css_sets
2935 * which are attached to the subtree, creates the matching updated css_sets
2936 * and migrates the tasks to the new ones.
2938 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2940 DEFINE_CGROUP_MGCTX(mgctx);
2941 struct cgroup_subsys_state *d_css;
2942 struct cgroup *dsct;
2943 struct css_set *src_cset;
2946 lockdep_assert_held(&cgroup_mutex);
2948 percpu_down_write(&cgroup_threadgroup_rwsem);
2950 /* look up all csses currently attached to @cgrp's subtree */
2951 spin_lock_irq(&css_set_lock);
2952 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2953 struct cgrp_cset_link *link;
2955 list_for_each_entry(link, &dsct->cset_links, cset_link)
2956 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2958 spin_unlock_irq(&css_set_lock);
2960 /* NULL dst indicates self on default hierarchy */
2961 ret = cgroup_migrate_prepare_dst(&mgctx);
2965 spin_lock_irq(&css_set_lock);
2966 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets, mg_preload_node) {
2967 struct task_struct *task, *ntask;
2969 /* all tasks in src_csets need to be migrated */
2970 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2971 cgroup_migrate_add_task(task, &mgctx);
2973 spin_unlock_irq(&css_set_lock);
2975 ret = cgroup_migrate_execute(&mgctx);
2977 cgroup_migrate_finish(&mgctx);
2978 percpu_up_write(&cgroup_threadgroup_rwsem);
2983 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2984 * @cgrp: root of the target subtree
2986 * Because css offlining is asynchronous, userland may try to re-enable a
2987 * controller while the previous css is still around. This function grabs
2988 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2990 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2991 __acquires(&cgroup_mutex)
2993 struct cgroup *dsct;
2994 struct cgroup_subsys_state *d_css;
2995 struct cgroup_subsys *ss;
2999 mutex_lock(&cgroup_mutex);
3001 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3002 for_each_subsys(ss, ssid) {
3003 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3006 if (!css || !percpu_ref_is_dying(&css->refcnt))
3009 cgroup_get_live(dsct);
3010 prepare_to_wait(&dsct->offline_waitq, &wait,
3011 TASK_UNINTERRUPTIBLE);
3013 mutex_unlock(&cgroup_mutex);
3015 finish_wait(&dsct->offline_waitq, &wait);
3024 * cgroup_save_control - save control masks and dom_cgrp of a subtree
3025 * @cgrp: root of the target subtree
3027 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
3028 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3031 static void cgroup_save_control(struct cgroup *cgrp)
3033 struct cgroup *dsct;
3034 struct cgroup_subsys_state *d_css;
3036 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3037 dsct->old_subtree_control = dsct->subtree_control;
3038 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
3039 dsct->old_dom_cgrp = dsct->dom_cgrp;
3044 * cgroup_propagate_control - refresh control masks of a subtree
3045 * @cgrp: root of the target subtree
3047 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
3048 * ->subtree_control and propagate controller availability through the
3049 * subtree so that descendants don't have unavailable controllers enabled.
3051 static void cgroup_propagate_control(struct cgroup *cgrp)
3053 struct cgroup *dsct;
3054 struct cgroup_subsys_state *d_css;
3056 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3057 dsct->subtree_control &= cgroup_control(dsct);
3058 dsct->subtree_ss_mask =
3059 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
3060 cgroup_ss_mask(dsct));
3065 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
3066 * @cgrp: root of the target subtree
3068 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
3069 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3072 static void cgroup_restore_control(struct cgroup *cgrp)
3074 struct cgroup *dsct;
3075 struct cgroup_subsys_state *d_css;
3077 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3078 dsct->subtree_control = dsct->old_subtree_control;
3079 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
3080 dsct->dom_cgrp = dsct->old_dom_cgrp;
3084 static bool css_visible(struct cgroup_subsys_state *css)
3086 struct cgroup_subsys *ss = css->ss;
3087 struct cgroup *cgrp = css->cgroup;
3089 if (cgroup_control(cgrp) & (1 << ss->id))
3091 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
3093 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
3097 * cgroup_apply_control_enable - enable or show csses according to control
3098 * @cgrp: root of the target subtree
3100 * Walk @cgrp's subtree and create new csses or make the existing ones
3101 * visible. A css is created invisible if it's being implicitly enabled
3102 * through dependency. An invisible css is made visible when the userland
3103 * explicitly enables it.
3105 * Returns 0 on success, -errno on failure. On failure, csses which have
3106 * been processed already aren't cleaned up. The caller is responsible for
3107 * cleaning up with cgroup_apply_control_disable().
3109 static int cgroup_apply_control_enable(struct cgroup *cgrp)
3111 struct cgroup *dsct;
3112 struct cgroup_subsys_state *d_css;
3113 struct cgroup_subsys *ss;
3116 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3117 for_each_subsys(ss, ssid) {
3118 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3120 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
3124 css = css_create(dsct, ss);
3126 return PTR_ERR(css);
3129 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3131 if (css_visible(css)) {
3132 ret = css_populate_dir(css);
3143 * cgroup_apply_control_disable - kill or hide csses according to control
3144 * @cgrp: root of the target subtree
3146 * Walk @cgrp's subtree and kill and hide csses so that they match
3147 * cgroup_ss_mask() and cgroup_visible_mask().
3149 * A css is hidden when the userland requests it to be disabled while other
3150 * subsystems are still depending on it. The css must not actively control
3151 * resources and be in the vanilla state if it's made visible again later.
3152 * Controllers which may be depended upon should provide ->css_reset() for
3155 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3157 struct cgroup *dsct;
3158 struct cgroup_subsys_state *d_css;
3159 struct cgroup_subsys *ss;
3162 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3163 for_each_subsys(ss, ssid) {
3164 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3169 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3172 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3174 } else if (!css_visible(css)) {
3184 * cgroup_apply_control - apply control mask updates to the subtree
3185 * @cgrp: root of the target subtree
3187 * subsystems can be enabled and disabled in a subtree using the following
3190 * 1. Call cgroup_save_control() to stash the current state.
3191 * 2. Update ->subtree_control masks in the subtree as desired.
3192 * 3. Call cgroup_apply_control() to apply the changes.
3193 * 4. Optionally perform other related operations.
3194 * 5. Call cgroup_finalize_control() to finish up.
3196 * This function implements step 3 and propagates the mask changes
3197 * throughout @cgrp's subtree, updates csses accordingly and perform
3198 * process migrations.
3200 static int cgroup_apply_control(struct cgroup *cgrp)
3204 cgroup_propagate_control(cgrp);
3206 ret = cgroup_apply_control_enable(cgrp);
3211 * At this point, cgroup_e_css_by_mask() results reflect the new csses
3212 * making the following cgroup_update_dfl_csses() properly update
3213 * css associations of all tasks in the subtree.
3215 ret = cgroup_update_dfl_csses(cgrp);
3223 * cgroup_finalize_control - finalize control mask update
3224 * @cgrp: root of the target subtree
3225 * @ret: the result of the update
3227 * Finalize control mask update. See cgroup_apply_control() for more info.
3229 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3232 cgroup_restore_control(cgrp);
3233 cgroup_propagate_control(cgrp);
3236 cgroup_apply_control_disable(cgrp);
3239 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3241 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3243 /* if nothing is getting enabled, nothing to worry about */
3247 /* can @cgrp host any resources? */
3248 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3251 /* mixables don't care */
3252 if (cgroup_is_mixable(cgrp))
3255 if (domain_enable) {
3256 /* can't enable domain controllers inside a thread subtree */
3257 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3261 * Threaded controllers can handle internal competitions
3262 * and are always allowed inside a (prospective) thread
3265 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3270 * Controllers can't be enabled for a cgroup with tasks to avoid
3271 * child cgroups competing against tasks.
3273 if (cgroup_has_tasks(cgrp))
3279 /* change the enabled child controllers for a cgroup in the default hierarchy */
3280 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3281 char *buf, size_t nbytes,
3284 u16 enable = 0, disable = 0;
3285 struct cgroup *cgrp, *child;
3286 struct cgroup_subsys *ss;
3291 * Parse input - space separated list of subsystem names prefixed
3292 * with either + or -.
3294 buf = strstrip(buf);
3295 while ((tok = strsep(&buf, " "))) {
3298 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3299 if (!cgroup_ssid_enabled(ssid) ||
3300 strcmp(tok + 1, ss->name))
3304 enable |= 1 << ssid;
3305 disable &= ~(1 << ssid);
3306 } else if (*tok == '-') {
3307 disable |= 1 << ssid;
3308 enable &= ~(1 << ssid);
3313 } while_each_subsys_mask();
3314 if (ssid == CGROUP_SUBSYS_COUNT)
3318 cgrp = cgroup_kn_lock_live(of->kn, true);
3322 for_each_subsys(ss, ssid) {
3323 if (enable & (1 << ssid)) {
3324 if (cgrp->subtree_control & (1 << ssid)) {
3325 enable &= ~(1 << ssid);
3329 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3333 } else if (disable & (1 << ssid)) {
3334 if (!(cgrp->subtree_control & (1 << ssid))) {
3335 disable &= ~(1 << ssid);
3339 /* a child has it enabled? */
3340 cgroup_for_each_live_child(child, cgrp) {
3341 if (child->subtree_control & (1 << ssid)) {
3349 if (!enable && !disable) {
3354 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3358 /* save and update control masks and prepare csses */
3359 cgroup_save_control(cgrp);
3361 cgrp->subtree_control |= enable;
3362 cgrp->subtree_control &= ~disable;
3364 ret = cgroup_apply_control(cgrp);
3365 cgroup_finalize_control(cgrp, ret);
3369 kernfs_activate(cgrp->kn);
3371 cgroup_kn_unlock(of->kn);
3372 return ret ?: nbytes;
3376 * cgroup_enable_threaded - make @cgrp threaded
3377 * @cgrp: the target cgroup
3379 * Called when "threaded" is written to the cgroup.type interface file and
3380 * tries to make @cgrp threaded and join the parent's resource domain.
3381 * This function is never called on the root cgroup as cgroup.type doesn't
3384 static int cgroup_enable_threaded(struct cgroup *cgrp)
3386 struct cgroup *parent = cgroup_parent(cgrp);
3387 struct cgroup *dom_cgrp = parent->dom_cgrp;
3388 struct cgroup *dsct;
3389 struct cgroup_subsys_state *d_css;
3392 lockdep_assert_held(&cgroup_mutex);
3394 /* noop if already threaded */
3395 if (cgroup_is_threaded(cgrp))
3399 * If @cgroup is populated or has domain controllers enabled, it
3400 * can't be switched. While the below cgroup_can_be_thread_root()
3401 * test can catch the same conditions, that's only when @parent is
3402 * not mixable, so let's check it explicitly.
3404 if (cgroup_is_populated(cgrp) ||
3405 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3408 /* we're joining the parent's domain, ensure its validity */
3409 if (!cgroup_is_valid_domain(dom_cgrp) ||
3410 !cgroup_can_be_thread_root(dom_cgrp))
3414 * The following shouldn't cause actual migrations and should
3417 cgroup_save_control(cgrp);
3419 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3420 if (dsct == cgrp || cgroup_is_threaded(dsct))
3421 dsct->dom_cgrp = dom_cgrp;
3423 ret = cgroup_apply_control(cgrp);
3425 parent->nr_threaded_children++;
3427 cgroup_finalize_control(cgrp, ret);
3431 static int cgroup_type_show(struct seq_file *seq, void *v)
3433 struct cgroup *cgrp = seq_css(seq)->cgroup;
3435 if (cgroup_is_threaded(cgrp))
3436 seq_puts(seq, "threaded\n");
3437 else if (!cgroup_is_valid_domain(cgrp))
3438 seq_puts(seq, "domain invalid\n");
3439 else if (cgroup_is_thread_root(cgrp))
3440 seq_puts(seq, "domain threaded\n");
3442 seq_puts(seq, "domain\n");
3447 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3448 size_t nbytes, loff_t off)
3450 struct cgroup *cgrp;
3453 /* only switching to threaded mode is supported */
3454 if (strcmp(strstrip(buf), "threaded"))
3457 /* drain dying csses before we re-apply (threaded) subtree control */
3458 cgrp = cgroup_kn_lock_live(of->kn, true);
3462 /* threaded can only be enabled */
3463 ret = cgroup_enable_threaded(cgrp);
3465 cgroup_kn_unlock(of->kn);
3466 return ret ?: nbytes;
3469 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3471 struct cgroup *cgrp = seq_css(seq)->cgroup;
3472 int descendants = READ_ONCE(cgrp->max_descendants);
3474 if (descendants == INT_MAX)
3475 seq_puts(seq, "max\n");
3477 seq_printf(seq, "%d\n", descendants);
3482 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3483 char *buf, size_t nbytes, loff_t off)
3485 struct cgroup *cgrp;
3489 buf = strstrip(buf);
3490 if (!strcmp(buf, "max")) {
3491 descendants = INT_MAX;
3493 ret = kstrtoint(buf, 0, &descendants);
3498 if (descendants < 0)
3501 cgrp = cgroup_kn_lock_live(of->kn, false);
3505 cgrp->max_descendants = descendants;
3507 cgroup_kn_unlock(of->kn);
3512 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3514 struct cgroup *cgrp = seq_css(seq)->cgroup;
3515 int depth = READ_ONCE(cgrp->max_depth);
3517 if (depth == INT_MAX)
3518 seq_puts(seq, "max\n");
3520 seq_printf(seq, "%d\n", depth);
3525 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3526 char *buf, size_t nbytes, loff_t off)
3528 struct cgroup *cgrp;
3532 buf = strstrip(buf);
3533 if (!strcmp(buf, "max")) {
3536 ret = kstrtoint(buf, 0, &depth);
3544 cgrp = cgroup_kn_lock_live(of->kn, false);
3548 cgrp->max_depth = depth;
3550 cgroup_kn_unlock(of->kn);
3555 static int cgroup_events_show(struct seq_file *seq, void *v)
3557 struct cgroup *cgrp = seq_css(seq)->cgroup;
3559 seq_printf(seq, "populated %d\n", cgroup_is_populated(cgrp));
3560 seq_printf(seq, "frozen %d\n", test_bit(CGRP_FROZEN, &cgrp->flags));
3565 static int cgroup_stat_show(struct seq_file *seq, void *v)
3567 struct cgroup *cgroup = seq_css(seq)->cgroup;
3569 seq_printf(seq, "nr_descendants %d\n",
3570 cgroup->nr_descendants);
3571 seq_printf(seq, "nr_dying_descendants %d\n",
3572 cgroup->nr_dying_descendants);
3577 static int __maybe_unused cgroup_extra_stat_show(struct seq_file *seq,
3578 struct cgroup *cgrp, int ssid)
3580 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3581 struct cgroup_subsys_state *css;
3584 if (!ss->css_extra_stat_show)
3587 css = cgroup_tryget_css(cgrp, ss);
3591 ret = ss->css_extra_stat_show(seq, css);
3596 static int cpu_stat_show(struct seq_file *seq, void *v)
3598 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3601 cgroup_base_stat_cputime_show(seq);
3602 #ifdef CONFIG_CGROUP_SCHED
3603 ret = cgroup_extra_stat_show(seq, cgrp, cpu_cgrp_id);
3609 static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
3611 struct cgroup *cgrp = seq_css(seq)->cgroup;
3612 struct psi_group *psi = cgroup_ino(cgrp) == 1 ? &psi_system : &cgrp->psi;
3614 return psi_show(seq, psi, PSI_IO);
3616 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
3618 struct cgroup *cgrp = seq_css(seq)->cgroup;
3619 struct psi_group *psi = cgroup_ino(cgrp) == 1 ? &psi_system : &cgrp->psi;
3621 return psi_show(seq, psi, PSI_MEM);
3623 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
3625 struct cgroup *cgrp = seq_css(seq)->cgroup;
3626 struct psi_group *psi = cgroup_ino(cgrp) == 1 ? &psi_system : &cgrp->psi;
3628 return psi_show(seq, psi, PSI_CPU);
3631 static ssize_t cgroup_pressure_write(struct kernfs_open_file *of, char *buf,
3632 size_t nbytes, enum psi_res res)
3634 struct cgroup_file_ctx *ctx = of->priv;
3635 struct psi_trigger *new;
3636 struct cgroup *cgrp;
3637 struct psi_group *psi;
3639 cgrp = cgroup_kn_lock_live(of->kn, false);
3644 cgroup_kn_unlock(of->kn);
3646 /* Allow only one trigger per file descriptor */
3647 if (ctx->psi.trigger) {
3652 psi = cgroup_ino(cgrp) == 1 ? &psi_system : &cgrp->psi;
3653 new = psi_trigger_create(psi, buf, nbytes, res);
3656 return PTR_ERR(new);
3659 smp_store_release(&ctx->psi.trigger, new);
3665 static ssize_t cgroup_io_pressure_write(struct kernfs_open_file *of,
3666 char *buf, size_t nbytes,
3669 return cgroup_pressure_write(of, buf, nbytes, PSI_IO);
3672 static ssize_t cgroup_memory_pressure_write(struct kernfs_open_file *of,
3673 char *buf, size_t nbytes,
3676 return cgroup_pressure_write(of, buf, nbytes, PSI_MEM);
3679 static ssize_t cgroup_cpu_pressure_write(struct kernfs_open_file *of,
3680 char *buf, size_t nbytes,
3683 return cgroup_pressure_write(of, buf, nbytes, PSI_CPU);
3686 static __poll_t cgroup_pressure_poll(struct kernfs_open_file *of,
3689 struct cgroup_file_ctx *ctx = of->priv;
3691 return psi_trigger_poll(&ctx->psi.trigger, of->file, pt);
3694 static void cgroup_pressure_release(struct kernfs_open_file *of)
3696 struct cgroup_file_ctx *ctx = of->priv;
3698 psi_trigger_destroy(ctx->psi.trigger);
3701 bool cgroup_psi_enabled(void)
3703 return (cgroup_feature_disable_mask & (1 << OPT_FEATURE_PRESSURE)) == 0;
3706 #else /* CONFIG_PSI */
3707 bool cgroup_psi_enabled(void)
3712 #endif /* CONFIG_PSI */
3714 static int cgroup_freeze_show(struct seq_file *seq, void *v)
3716 struct cgroup *cgrp = seq_css(seq)->cgroup;
3718 seq_printf(seq, "%d\n", cgrp->freezer.freeze);
3723 static ssize_t cgroup_freeze_write(struct kernfs_open_file *of,
3724 char *buf, size_t nbytes, loff_t off)
3726 struct cgroup *cgrp;
3730 ret = kstrtoint(strstrip(buf), 0, &freeze);
3734 if (freeze < 0 || freeze > 1)
3737 cgrp = cgroup_kn_lock_live(of->kn, false);
3741 cgroup_freeze(cgrp, freeze);
3743 cgroup_kn_unlock(of->kn);
3748 static void __cgroup_kill(struct cgroup *cgrp)
3750 struct css_task_iter it;
3751 struct task_struct *task;
3753 lockdep_assert_held(&cgroup_mutex);
3755 spin_lock_irq(&css_set_lock);
3756 set_bit(CGRP_KILL, &cgrp->flags);
3757 spin_unlock_irq(&css_set_lock);
3759 css_task_iter_start(&cgrp->self, CSS_TASK_ITER_PROCS | CSS_TASK_ITER_THREADED, &it);
3760 while ((task = css_task_iter_next(&it))) {
3761 /* Ignore kernel threads here. */
3762 if (task->flags & PF_KTHREAD)
3765 /* Skip tasks that are already dying. */
3766 if (__fatal_signal_pending(task))
3769 send_sig(SIGKILL, task, 0);
3771 css_task_iter_end(&it);
3773 spin_lock_irq(&css_set_lock);
3774 clear_bit(CGRP_KILL, &cgrp->flags);
3775 spin_unlock_irq(&css_set_lock);
3778 static void cgroup_kill(struct cgroup *cgrp)
3780 struct cgroup_subsys_state *css;
3781 struct cgroup *dsct;
3783 lockdep_assert_held(&cgroup_mutex);
3785 cgroup_for_each_live_descendant_pre(dsct, css, cgrp)
3786 __cgroup_kill(dsct);
3789 static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf,
3790 size_t nbytes, loff_t off)
3794 struct cgroup *cgrp;
3796 ret = kstrtoint(strstrip(buf), 0, &kill);
3803 cgrp = cgroup_kn_lock_live(of->kn, false);
3808 * Killing is a process directed operation, i.e. the whole thread-group
3809 * is taken down so act like we do for cgroup.procs and only make this
3810 * writable in non-threaded cgroups.
3812 if (cgroup_is_threaded(cgrp))
3817 cgroup_kn_unlock(of->kn);
3819 return ret ?: nbytes;
3822 static int cgroup_file_open(struct kernfs_open_file *of)
3824 struct cftype *cft = of_cft(of);
3825 struct cgroup_file_ctx *ctx;
3828 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3832 ctx->ns = current->nsproxy->cgroup_ns;
3833 get_cgroup_ns(ctx->ns);
3839 ret = cft->open(of);
3841 put_cgroup_ns(ctx->ns);
3847 static void cgroup_file_release(struct kernfs_open_file *of)
3849 struct cftype *cft = of_cft(of);
3850 struct cgroup_file_ctx *ctx = of->priv;
3854 put_cgroup_ns(ctx->ns);
3858 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3859 size_t nbytes, loff_t off)
3861 struct cgroup_file_ctx *ctx = of->priv;
3862 struct cgroup *cgrp = of->kn->parent->priv;
3863 struct cftype *cft = of_cft(of);
3864 struct cgroup_subsys_state *css;
3871 * If namespaces are delegation boundaries, disallow writes to
3872 * files in an non-init namespace root from inside the namespace
3873 * except for the files explicitly marked delegatable -
3874 * cgroup.procs and cgroup.subtree_control.
3876 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3877 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3878 ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
3882 return cft->write(of, buf, nbytes, off);
3885 * kernfs guarantees that a file isn't deleted with operations in
3886 * flight, which means that the matching css is and stays alive and
3887 * doesn't need to be pinned. The RCU locking is not necessary
3888 * either. It's just for the convenience of using cgroup_css().
3891 css = cgroup_css(cgrp, cft->ss);
3894 if (cft->write_u64) {
3895 unsigned long long v;
3896 ret = kstrtoull(buf, 0, &v);
3898 ret = cft->write_u64(css, cft, v);
3899 } else if (cft->write_s64) {
3901 ret = kstrtoll(buf, 0, &v);
3903 ret = cft->write_s64(css, cft, v);
3908 return ret ?: nbytes;
3911 static __poll_t cgroup_file_poll(struct kernfs_open_file *of, poll_table *pt)
3913 struct cftype *cft = of_cft(of);
3916 return cft->poll(of, pt);
3918 return kernfs_generic_poll(of, pt);
3921 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3923 return seq_cft(seq)->seq_start(seq, ppos);
3926 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3928 return seq_cft(seq)->seq_next(seq, v, ppos);
3931 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3933 if (seq_cft(seq)->seq_stop)
3934 seq_cft(seq)->seq_stop(seq, v);
3937 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3939 struct cftype *cft = seq_cft(m);
3940 struct cgroup_subsys_state *css = seq_css(m);
3943 return cft->seq_show(m, arg);
3946 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3947 else if (cft->read_s64)
3948 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3954 static struct kernfs_ops cgroup_kf_single_ops = {
3955 .atomic_write_len = PAGE_SIZE,
3956 .open = cgroup_file_open,
3957 .release = cgroup_file_release,
3958 .write = cgroup_file_write,
3959 .poll = cgroup_file_poll,
3960 .seq_show = cgroup_seqfile_show,
3963 static struct kernfs_ops cgroup_kf_ops = {
3964 .atomic_write_len = PAGE_SIZE,
3965 .open = cgroup_file_open,
3966 .release = cgroup_file_release,
3967 .write = cgroup_file_write,
3968 .poll = cgroup_file_poll,
3969 .seq_start = cgroup_seqfile_start,
3970 .seq_next = cgroup_seqfile_next,
3971 .seq_stop = cgroup_seqfile_stop,
3972 .seq_show = cgroup_seqfile_show,
3975 /* set uid and gid of cgroup dirs and files to that of the creator */
3976 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3978 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3979 .ia_uid = current_fsuid(),
3980 .ia_gid = current_fsgid(), };
3982 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3983 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3986 return kernfs_setattr(kn, &iattr);
3989 static void cgroup_file_notify_timer(struct timer_list *timer)
3991 cgroup_file_notify(container_of(timer, struct cgroup_file,
3995 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
3998 char name[CGROUP_FILE_NAME_MAX];
3999 struct kernfs_node *kn;
4000 struct lock_class_key *key = NULL;
4003 #ifdef CONFIG_DEBUG_LOCK_ALLOC
4004 key = &cft->lockdep_key;
4006 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
4007 cgroup_file_mode(cft),
4008 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
4009 0, cft->kf_ops, cft,
4014 ret = cgroup_kn_set_ugid(kn);
4020 if (cft->file_offset) {
4021 struct cgroup_file *cfile = (void *)css + cft->file_offset;
4023 timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
4025 spin_lock_irq(&cgroup_file_kn_lock);
4027 spin_unlock_irq(&cgroup_file_kn_lock);
4034 * cgroup_addrm_files - add or remove files to a cgroup directory
4035 * @css: the target css
4036 * @cgrp: the target cgroup (usually css->cgroup)
4037 * @cfts: array of cftypes to be added
4038 * @is_add: whether to add or remove
4040 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
4041 * For removals, this function never fails.
4043 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
4044 struct cgroup *cgrp, struct cftype cfts[],
4047 struct cftype *cft, *cft_end = NULL;
4050 lockdep_assert_held(&cgroup_mutex);
4053 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
4054 /* does cft->flags tell us to skip this file on @cgrp? */
4055 if ((cft->flags & CFTYPE_PRESSURE) && !cgroup_psi_enabled())
4057 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
4059 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
4061 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
4063 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
4065 if ((cft->flags & CFTYPE_DEBUG) && !cgroup_debug)
4068 ret = cgroup_add_file(css, cgrp, cft);
4070 pr_warn("%s: failed to add %s, err=%d\n",
4071 __func__, cft->name, ret);
4077 cgroup_rm_file(cgrp, cft);
4083 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
4085 struct cgroup_subsys *ss = cfts[0].ss;
4086 struct cgroup *root = &ss->root->cgrp;
4087 struct cgroup_subsys_state *css;
4090 lockdep_assert_held(&cgroup_mutex);
4092 /* add/rm files for all cgroups created before */
4093 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
4094 struct cgroup *cgrp = css->cgroup;
4096 if (!(css->flags & CSS_VISIBLE))
4099 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
4105 kernfs_activate(root->kn);
4109 static void cgroup_exit_cftypes(struct cftype *cfts)
4113 for (cft = cfts; cft->name[0] != '\0'; cft++) {
4114 /* free copy for custom atomic_write_len, see init_cftypes() */
4115 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
4120 /* revert flags set by cgroup core while adding @cfts */
4121 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
4125 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4129 for (cft = cfts; cft->name[0] != '\0'; cft++) {
4130 struct kernfs_ops *kf_ops;
4132 WARN_ON(cft->ss || cft->kf_ops);
4134 if ((cft->flags & CFTYPE_PRESSURE) && !cgroup_psi_enabled())
4138 kf_ops = &cgroup_kf_ops;
4140 kf_ops = &cgroup_kf_single_ops;
4143 * Ugh... if @cft wants a custom max_write_len, we need to
4144 * make a copy of kf_ops to set its atomic_write_len.
4146 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
4147 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
4149 cgroup_exit_cftypes(cfts);
4152 kf_ops->atomic_write_len = cft->max_write_len;
4155 cft->kf_ops = kf_ops;
4162 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
4164 lockdep_assert_held(&cgroup_mutex);
4166 if (!cfts || !cfts[0].ss)
4169 list_del(&cfts->node);
4170 cgroup_apply_cftypes(cfts, false);
4171 cgroup_exit_cftypes(cfts);
4176 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
4177 * @cfts: zero-length name terminated array of cftypes
4179 * Unregister @cfts. Files described by @cfts are removed from all
4180 * existing cgroups and all future cgroups won't have them either. This
4181 * function can be called anytime whether @cfts' subsys is attached or not.
4183 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
4186 int cgroup_rm_cftypes(struct cftype *cfts)
4190 mutex_lock(&cgroup_mutex);
4191 ret = cgroup_rm_cftypes_locked(cfts);
4192 mutex_unlock(&cgroup_mutex);
4197 * cgroup_add_cftypes - add an array of cftypes to a subsystem
4198 * @ss: target cgroup subsystem
4199 * @cfts: zero-length name terminated array of cftypes
4201 * Register @cfts to @ss. Files described by @cfts are created for all
4202 * existing cgroups to which @ss is attached and all future cgroups will
4203 * have them too. This function can be called anytime whether @ss is
4206 * Returns 0 on successful registration, -errno on failure. Note that this
4207 * function currently returns 0 as long as @cfts registration is successful
4208 * even if some file creation attempts on existing cgroups fail.
4210 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4214 if (!cgroup_ssid_enabled(ss->id))
4217 if (!cfts || cfts[0].name[0] == '\0')
4220 ret = cgroup_init_cftypes(ss, cfts);
4224 mutex_lock(&cgroup_mutex);
4226 list_add_tail(&cfts->node, &ss->cfts);
4227 ret = cgroup_apply_cftypes(cfts, true);
4229 cgroup_rm_cftypes_locked(cfts);
4231 mutex_unlock(&cgroup_mutex);
4236 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
4237 * @ss: target cgroup subsystem
4238 * @cfts: zero-length name terminated array of cftypes
4240 * Similar to cgroup_add_cftypes() but the added files are only used for
4241 * the default hierarchy.
4243 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4247 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4248 cft->flags |= __CFTYPE_ONLY_ON_DFL;
4249 return cgroup_add_cftypes(ss, cfts);
4253 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
4254 * @ss: target cgroup subsystem
4255 * @cfts: zero-length name terminated array of cftypes
4257 * Similar to cgroup_add_cftypes() but the added files are only used for
4258 * the legacy hierarchies.
4260 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4264 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4265 cft->flags |= __CFTYPE_NOT_ON_DFL;
4266 return cgroup_add_cftypes(ss, cfts);
4270 * cgroup_file_notify - generate a file modified event for a cgroup_file
4271 * @cfile: target cgroup_file
4273 * @cfile must have been obtained by setting cftype->file_offset.
4275 void cgroup_file_notify(struct cgroup_file *cfile)
4277 unsigned long flags;
4279 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
4281 unsigned long last = cfile->notified_at;
4282 unsigned long next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
4284 if (time_in_range(jiffies, last, next)) {
4285 timer_reduce(&cfile->notify_timer, next);
4287 kernfs_notify(cfile->kn);
4288 cfile->notified_at = jiffies;
4291 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
4295 * css_next_child - find the next child of a given css
4296 * @pos: the current position (%NULL to initiate traversal)
4297 * @parent: css whose children to walk
4299 * This function returns the next child of @parent and should be called
4300 * under either cgroup_mutex or RCU read lock. The only requirement is
4301 * that @parent and @pos are accessible. The next sibling is guaranteed to
4302 * be returned regardless of their states.
4304 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4305 * css which finished ->css_online() is guaranteed to be visible in the
4306 * future iterations and will stay visible until the last reference is put.
4307 * A css which hasn't finished ->css_online() or already finished
4308 * ->css_offline() may show up during traversal. It's each subsystem's
4309 * responsibility to synchronize against on/offlining.
4311 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
4312 struct cgroup_subsys_state *parent)
4314 struct cgroup_subsys_state *next;
4316 cgroup_assert_mutex_or_rcu_locked();
4319 * @pos could already have been unlinked from the sibling list.
4320 * Once a cgroup is removed, its ->sibling.next is no longer
4321 * updated when its next sibling changes. CSS_RELEASED is set when
4322 * @pos is taken off list, at which time its next pointer is valid,
4323 * and, as releases are serialized, the one pointed to by the next
4324 * pointer is guaranteed to not have started release yet. This
4325 * implies that if we observe !CSS_RELEASED on @pos in this RCU
4326 * critical section, the one pointed to by its next pointer is
4327 * guaranteed to not have finished its RCU grace period even if we
4328 * have dropped rcu_read_lock() in-between iterations.
4330 * If @pos has CSS_RELEASED set, its next pointer can't be
4331 * dereferenced; however, as each css is given a monotonically
4332 * increasing unique serial number and always appended to the
4333 * sibling list, the next one can be found by walking the parent's
4334 * children until the first css with higher serial number than
4335 * @pos's. While this path can be slower, it happens iff iteration
4336 * races against release and the race window is very small.
4339 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
4340 } else if (likely(!(pos->flags & CSS_RELEASED))) {
4341 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
4343 list_for_each_entry_rcu(next, &parent->children, sibling,
4344 lockdep_is_held(&cgroup_mutex))
4345 if (next->serial_nr > pos->serial_nr)
4350 * @next, if not pointing to the head, can be dereferenced and is
4353 if (&next->sibling != &parent->children)
4359 * css_next_descendant_pre - find the next descendant for pre-order walk
4360 * @pos: the current position (%NULL to initiate traversal)
4361 * @root: css whose descendants to walk
4363 * To be used by css_for_each_descendant_pre(). Find the next descendant
4364 * to visit for pre-order traversal of @root's descendants. @root is
4365 * included in the iteration and the first node to be visited.
4367 * While this function requires cgroup_mutex or RCU read locking, it
4368 * doesn't require the whole traversal to be contained in a single critical
4369 * section. This function will return the correct next descendant as long
4370 * as both @pos and @root are accessible and @pos is a descendant of @root.
4372 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4373 * css which finished ->css_online() is guaranteed to be visible in the
4374 * future iterations and will stay visible until the last reference is put.
4375 * A css which hasn't finished ->css_online() or already finished
4376 * ->css_offline() may show up during traversal. It's each subsystem's
4377 * responsibility to synchronize against on/offlining.
4379 struct cgroup_subsys_state *
4380 css_next_descendant_pre(struct cgroup_subsys_state *pos,
4381 struct cgroup_subsys_state *root)
4383 struct cgroup_subsys_state *next;
4385 cgroup_assert_mutex_or_rcu_locked();
4387 /* if first iteration, visit @root */
4391 /* visit the first child if exists */
4392 next = css_next_child(NULL, pos);
4396 /* no child, visit my or the closest ancestor's next sibling */
4397 while (pos != root) {
4398 next = css_next_child(pos, pos->parent);
4406 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
4409 * css_rightmost_descendant - return the rightmost descendant of a css
4410 * @pos: css of interest
4412 * Return the rightmost descendant of @pos. If there's no descendant, @pos
4413 * is returned. This can be used during pre-order traversal to skip
4416 * While this function requires cgroup_mutex or RCU read locking, it
4417 * doesn't require the whole traversal to be contained in a single critical
4418 * section. This function will return the correct rightmost descendant as
4419 * long as @pos is accessible.
4421 struct cgroup_subsys_state *
4422 css_rightmost_descendant(struct cgroup_subsys_state *pos)
4424 struct cgroup_subsys_state *last, *tmp;
4426 cgroup_assert_mutex_or_rcu_locked();
4430 /* ->prev isn't RCU safe, walk ->next till the end */
4432 css_for_each_child(tmp, last)
4439 static struct cgroup_subsys_state *
4440 css_leftmost_descendant(struct cgroup_subsys_state *pos)
4442 struct cgroup_subsys_state *last;
4446 pos = css_next_child(NULL, pos);
4453 * css_next_descendant_post - find the next descendant for post-order walk
4454 * @pos: the current position (%NULL to initiate traversal)
4455 * @root: css whose descendants to walk
4457 * To be used by css_for_each_descendant_post(). Find the next descendant
4458 * to visit for post-order traversal of @root's descendants. @root is
4459 * included in the iteration and the last node to be visited.
4461 * While this function requires cgroup_mutex or RCU read locking, it
4462 * doesn't require the whole traversal to be contained in a single critical
4463 * section. This function will return the correct next descendant as long
4464 * as both @pos and @cgroup are accessible and @pos is a descendant of
4467 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4468 * css which finished ->css_online() is guaranteed to be visible in the
4469 * future iterations and will stay visible until the last reference is put.
4470 * A css which hasn't finished ->css_online() or already finished
4471 * ->css_offline() may show up during traversal. It's each subsystem's
4472 * responsibility to synchronize against on/offlining.
4474 struct cgroup_subsys_state *
4475 css_next_descendant_post(struct cgroup_subsys_state *pos,
4476 struct cgroup_subsys_state *root)
4478 struct cgroup_subsys_state *next;
4480 cgroup_assert_mutex_or_rcu_locked();
4482 /* if first iteration, visit leftmost descendant which may be @root */
4484 return css_leftmost_descendant(root);
4486 /* if we visited @root, we're done */
4490 /* if there's an unvisited sibling, visit its leftmost descendant */
4491 next = css_next_child(pos, pos->parent);
4493 return css_leftmost_descendant(next);
4495 /* no sibling left, visit parent */
4500 * css_has_online_children - does a css have online children
4501 * @css: the target css
4503 * Returns %true if @css has any online children; otherwise, %false. This
4504 * function can be called from any context but the caller is responsible
4505 * for synchronizing against on/offlining as necessary.
4507 bool css_has_online_children(struct cgroup_subsys_state *css)
4509 struct cgroup_subsys_state *child;
4513 css_for_each_child(child, css) {
4514 if (child->flags & CSS_ONLINE) {
4523 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4525 struct list_head *l;
4526 struct cgrp_cset_link *link;
4527 struct css_set *cset;
4529 lockdep_assert_held(&css_set_lock);
4531 /* find the next threaded cset */
4532 if (it->tcset_pos) {
4533 l = it->tcset_pos->next;
4535 if (l != it->tcset_head) {
4537 return container_of(l, struct css_set,
4538 threaded_csets_node);
4541 it->tcset_pos = NULL;
4544 /* find the next cset */
4547 if (l == it->cset_head) {
4548 it->cset_pos = NULL;
4553 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4555 link = list_entry(l, struct cgrp_cset_link, cset_link);
4561 /* initialize threaded css_set walking */
4562 if (it->flags & CSS_TASK_ITER_THREADED) {
4564 put_css_set_locked(it->cur_dcset);
4565 it->cur_dcset = cset;
4568 it->tcset_head = &cset->threaded_csets;
4569 it->tcset_pos = &cset->threaded_csets;
4576 * css_task_iter_advance_css_set - advance a task iterator to the next css_set
4577 * @it: the iterator to advance
4579 * Advance @it to the next css_set to walk.
4581 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4583 struct css_set *cset;
4585 lockdep_assert_held(&css_set_lock);
4587 /* Advance to the next non-empty css_set and find first non-empty tasks list*/
4588 while ((cset = css_task_iter_next_css_set(it))) {
4589 if (!list_empty(&cset->tasks)) {
4590 it->cur_tasks_head = &cset->tasks;
4592 } else if (!list_empty(&cset->mg_tasks)) {
4593 it->cur_tasks_head = &cset->mg_tasks;
4595 } else if (!list_empty(&cset->dying_tasks)) {
4596 it->cur_tasks_head = &cset->dying_tasks;
4601 it->task_pos = NULL;
4604 it->task_pos = it->cur_tasks_head->next;
4607 * We don't keep css_sets locked across iteration steps and thus
4608 * need to take steps to ensure that iteration can be resumed after
4609 * the lock is re-acquired. Iteration is performed at two levels -
4610 * css_sets and tasks in them.
4612 * Once created, a css_set never leaves its cgroup lists, so a
4613 * pinned css_set is guaranteed to stay put and we can resume
4614 * iteration afterwards.
4616 * Tasks may leave @cset across iteration steps. This is resolved
4617 * by registering each iterator with the css_set currently being
4618 * walked and making css_set_move_task() advance iterators whose
4619 * next task is leaving.
4622 list_del(&it->iters_node);
4623 put_css_set_locked(it->cur_cset);
4626 it->cur_cset = cset;
4627 list_add(&it->iters_node, &cset->task_iters);
4630 static void css_task_iter_skip(struct css_task_iter *it,
4631 struct task_struct *task)
4633 lockdep_assert_held(&css_set_lock);
4635 if (it->task_pos == &task->cg_list) {
4636 it->task_pos = it->task_pos->next;
4637 it->flags |= CSS_TASK_ITER_SKIPPED;
4641 static void css_task_iter_advance(struct css_task_iter *it)
4643 struct task_struct *task;
4645 lockdep_assert_held(&css_set_lock);
4649 * Advance iterator to find next entry. We go through cset
4650 * tasks, mg_tasks and dying_tasks, when consumed we move onto
4653 if (it->flags & CSS_TASK_ITER_SKIPPED)
4654 it->flags &= ~CSS_TASK_ITER_SKIPPED;
4656 it->task_pos = it->task_pos->next;
4658 if (it->task_pos == &it->cur_cset->tasks) {
4659 it->cur_tasks_head = &it->cur_cset->mg_tasks;
4660 it->task_pos = it->cur_tasks_head->next;
4662 if (it->task_pos == &it->cur_cset->mg_tasks) {
4663 it->cur_tasks_head = &it->cur_cset->dying_tasks;
4664 it->task_pos = it->cur_tasks_head->next;
4666 if (it->task_pos == &it->cur_cset->dying_tasks)
4667 css_task_iter_advance_css_set(it);
4669 /* called from start, proceed to the first cset */
4670 css_task_iter_advance_css_set(it);
4676 task = list_entry(it->task_pos, struct task_struct, cg_list);
4678 if (it->flags & CSS_TASK_ITER_PROCS) {
4679 /* if PROCS, skip over tasks which aren't group leaders */
4680 if (!thread_group_leader(task))
4683 /* and dying leaders w/o live member threads */
4684 if (it->cur_tasks_head == &it->cur_cset->dying_tasks &&
4685 !atomic_read(&task->signal->live))
4688 /* skip all dying ones */
4689 if (it->cur_tasks_head == &it->cur_cset->dying_tasks)
4695 * css_task_iter_start - initiate task iteration
4696 * @css: the css to walk tasks of
4697 * @flags: CSS_TASK_ITER_* flags
4698 * @it: the task iterator to use
4700 * Initiate iteration through the tasks of @css. The caller can call
4701 * css_task_iter_next() to walk through the tasks until the function
4702 * returns NULL. On completion of iteration, css_task_iter_end() must be
4705 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4706 struct css_task_iter *it)
4708 memset(it, 0, sizeof(*it));
4710 spin_lock_irq(&css_set_lock);
4715 if (CGROUP_HAS_SUBSYS_CONFIG && it->ss)
4716 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4718 it->cset_pos = &css->cgroup->cset_links;
4720 it->cset_head = it->cset_pos;
4722 css_task_iter_advance(it);
4724 spin_unlock_irq(&css_set_lock);
4728 * css_task_iter_next - return the next task for the iterator
4729 * @it: the task iterator being iterated
4731 * The "next" function for task iteration. @it should have been
4732 * initialized via css_task_iter_start(). Returns NULL when the iteration
4735 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4738 put_task_struct(it->cur_task);
4739 it->cur_task = NULL;
4742 spin_lock_irq(&css_set_lock);
4744 /* @it may be half-advanced by skips, finish advancing */
4745 if (it->flags & CSS_TASK_ITER_SKIPPED)
4746 css_task_iter_advance(it);
4749 it->cur_task = list_entry(it->task_pos, struct task_struct,
4751 get_task_struct(it->cur_task);
4752 css_task_iter_advance(it);
4755 spin_unlock_irq(&css_set_lock);
4757 return it->cur_task;
4761 * css_task_iter_end - finish task iteration
4762 * @it: the task iterator to finish
4764 * Finish task iteration started by css_task_iter_start().
4766 void css_task_iter_end(struct css_task_iter *it)
4769 spin_lock_irq(&css_set_lock);
4770 list_del(&it->iters_node);
4771 put_css_set_locked(it->cur_cset);
4772 spin_unlock_irq(&css_set_lock);
4776 put_css_set(it->cur_dcset);
4779 put_task_struct(it->cur_task);
4782 static void cgroup_procs_release(struct kernfs_open_file *of)
4784 struct cgroup_file_ctx *ctx = of->priv;
4786 if (ctx->procs.started)
4787 css_task_iter_end(&ctx->procs.iter);
4790 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
4792 struct kernfs_open_file *of = s->private;
4793 struct cgroup_file_ctx *ctx = of->priv;
4798 return css_task_iter_next(&ctx->procs.iter);
4801 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
4802 unsigned int iter_flags)
4804 struct kernfs_open_file *of = s->private;
4805 struct cgroup *cgrp = seq_css(s)->cgroup;
4806 struct cgroup_file_ctx *ctx = of->priv;
4807 struct css_task_iter *it = &ctx->procs.iter;
4810 * When a seq_file is seeked, it's always traversed sequentially
4811 * from position 0, so we can simply keep iterating on !0 *pos.
4813 if (!ctx->procs.started) {
4814 if (WARN_ON_ONCE((*pos)))
4815 return ERR_PTR(-EINVAL);
4816 css_task_iter_start(&cgrp->self, iter_flags, it);
4817 ctx->procs.started = true;
4818 } else if (!(*pos)) {
4819 css_task_iter_end(it);
4820 css_task_iter_start(&cgrp->self, iter_flags, it);
4822 return it->cur_task;
4824 return cgroup_procs_next(s, NULL, NULL);
4827 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
4829 struct cgroup *cgrp = seq_css(s)->cgroup;
4832 * All processes of a threaded subtree belong to the domain cgroup
4833 * of the subtree. Only threads can be distributed across the
4834 * subtree. Reject reads on cgroup.procs in the subtree proper.
4835 * They're always empty anyway.
4837 if (cgroup_is_threaded(cgrp))
4838 return ERR_PTR(-EOPNOTSUPP);
4840 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
4841 CSS_TASK_ITER_THREADED);
4844 static int cgroup_procs_show(struct seq_file *s, void *v)
4846 seq_printf(s, "%d\n", task_pid_vnr(v));
4850 static int cgroup_may_write(const struct cgroup *cgrp, struct super_block *sb)
4853 struct inode *inode;
4855 lockdep_assert_held(&cgroup_mutex);
4857 inode = kernfs_get_inode(sb, cgrp->procs_file.kn);
4861 ret = inode_permission(&init_user_ns, inode, MAY_WRITE);
4866 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
4867 struct cgroup *dst_cgrp,
4868 struct super_block *sb,
4869 struct cgroup_namespace *ns)
4871 struct cgroup *com_cgrp = src_cgrp;
4874 lockdep_assert_held(&cgroup_mutex);
4876 /* find the common ancestor */
4877 while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
4878 com_cgrp = cgroup_parent(com_cgrp);
4880 /* %current should be authorized to migrate to the common ancestor */
4881 ret = cgroup_may_write(com_cgrp, sb);
4886 * If namespaces are delegation boundaries, %current must be able
4887 * to see both source and destination cgroups from its namespace.
4889 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
4890 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
4891 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
4897 static int cgroup_attach_permissions(struct cgroup *src_cgrp,
4898 struct cgroup *dst_cgrp,
4899 struct super_block *sb, bool threadgroup,
4900 struct cgroup_namespace *ns)
4904 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp, sb, ns);
4908 ret = cgroup_migrate_vet_dst(dst_cgrp);
4912 if (!threadgroup && (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp))
4918 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
4921 struct cgroup_file_ctx *ctx = of->priv;
4922 struct cgroup *src_cgrp, *dst_cgrp;
4923 struct task_struct *task;
4924 const struct cred *saved_cred;
4928 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4932 task = cgroup_procs_write_start(buf, threadgroup, &locked);
4933 ret = PTR_ERR_OR_ZERO(task);
4937 /* find the source cgroup */
4938 spin_lock_irq(&css_set_lock);
4939 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4940 spin_unlock_irq(&css_set_lock);
4943 * Process and thread migrations follow same delegation rule. Check
4944 * permissions using the credentials from file open to protect against
4945 * inherited fd attacks.
4947 saved_cred = override_creds(of->file->f_cred);
4948 ret = cgroup_attach_permissions(src_cgrp, dst_cgrp,
4949 of->file->f_path.dentry->d_sb,
4950 threadgroup, ctx->ns);
4951 revert_creds(saved_cred);
4955 ret = cgroup_attach_task(dst_cgrp, task, threadgroup);
4958 cgroup_procs_write_finish(task, locked);
4960 cgroup_kn_unlock(of->kn);
4965 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
4966 char *buf, size_t nbytes, loff_t off)
4968 return __cgroup_procs_write(of, buf, true) ?: nbytes;
4971 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
4973 return __cgroup_procs_start(s, pos, 0);
4976 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
4977 char *buf, size_t nbytes, loff_t off)
4979 return __cgroup_procs_write(of, buf, false) ?: nbytes;
4982 /* cgroup core interface files for the default hierarchy */
4983 static struct cftype cgroup_base_files[] = {
4985 .name = "cgroup.type",
4986 .flags = CFTYPE_NOT_ON_ROOT,
4987 .seq_show = cgroup_type_show,
4988 .write = cgroup_type_write,
4991 .name = "cgroup.procs",
4992 .flags = CFTYPE_NS_DELEGATABLE,
4993 .file_offset = offsetof(struct cgroup, procs_file),
4994 .release = cgroup_procs_release,
4995 .seq_start = cgroup_procs_start,
4996 .seq_next = cgroup_procs_next,
4997 .seq_show = cgroup_procs_show,
4998 .write = cgroup_procs_write,
5001 .name = "cgroup.threads",
5002 .flags = CFTYPE_NS_DELEGATABLE,
5003 .release = cgroup_procs_release,
5004 .seq_start = cgroup_threads_start,
5005 .seq_next = cgroup_procs_next,
5006 .seq_show = cgroup_procs_show,
5007 .write = cgroup_threads_write,
5010 .name = "cgroup.controllers",
5011 .seq_show = cgroup_controllers_show,
5014 .name = "cgroup.subtree_control",
5015 .flags = CFTYPE_NS_DELEGATABLE,
5016 .seq_show = cgroup_subtree_control_show,
5017 .write = cgroup_subtree_control_write,
5020 .name = "cgroup.events",
5021 .flags = CFTYPE_NOT_ON_ROOT,
5022 .file_offset = offsetof(struct cgroup, events_file),
5023 .seq_show = cgroup_events_show,
5026 .name = "cgroup.max.descendants",
5027 .seq_show = cgroup_max_descendants_show,
5028 .write = cgroup_max_descendants_write,
5031 .name = "cgroup.max.depth",
5032 .seq_show = cgroup_max_depth_show,
5033 .write = cgroup_max_depth_write,
5036 .name = "cgroup.stat",
5037 .seq_show = cgroup_stat_show,
5040 .name = "cgroup.freeze",
5041 .flags = CFTYPE_NOT_ON_ROOT,
5042 .seq_show = cgroup_freeze_show,
5043 .write = cgroup_freeze_write,
5046 .name = "cgroup.kill",
5047 .flags = CFTYPE_NOT_ON_ROOT,
5048 .write = cgroup_kill_write,
5052 .seq_show = cpu_stat_show,
5056 .name = "io.pressure",
5057 .flags = CFTYPE_PRESSURE,
5058 .seq_show = cgroup_io_pressure_show,
5059 .write = cgroup_io_pressure_write,
5060 .poll = cgroup_pressure_poll,
5061 .release = cgroup_pressure_release,
5064 .name = "memory.pressure",
5065 .flags = CFTYPE_PRESSURE,
5066 .seq_show = cgroup_memory_pressure_show,
5067 .write = cgroup_memory_pressure_write,
5068 .poll = cgroup_pressure_poll,
5069 .release = cgroup_pressure_release,
5072 .name = "cpu.pressure",
5073 .flags = CFTYPE_PRESSURE,
5074 .seq_show = cgroup_cpu_pressure_show,
5075 .write = cgroup_cpu_pressure_write,
5076 .poll = cgroup_pressure_poll,
5077 .release = cgroup_pressure_release,
5079 #endif /* CONFIG_PSI */
5084 * css destruction is four-stage process.
5086 * 1. Destruction starts. Killing of the percpu_ref is initiated.
5087 * Implemented in kill_css().
5089 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
5090 * and thus css_tryget_online() is guaranteed to fail, the css can be
5091 * offlined by invoking offline_css(). After offlining, the base ref is
5092 * put. Implemented in css_killed_work_fn().
5094 * 3. When the percpu_ref reaches zero, the only possible remaining
5095 * accessors are inside RCU read sections. css_release() schedules the
5098 * 4. After the grace period, the css can be freed. Implemented in
5099 * css_free_work_fn().
5101 * It is actually hairier because both step 2 and 4 require process context
5102 * and thus involve punting to css->destroy_work adding two additional
5103 * steps to the already complex sequence.
5105 static void css_free_rwork_fn(struct work_struct *work)
5107 struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
5108 struct cgroup_subsys_state, destroy_rwork);
5109 struct cgroup_subsys *ss = css->ss;
5110 struct cgroup *cgrp = css->cgroup;
5112 percpu_ref_exit(&css->refcnt);
5116 struct cgroup_subsys_state *parent = css->parent;
5120 cgroup_idr_remove(&ss->css_idr, id);
5126 /* cgroup free path */
5127 atomic_dec(&cgrp->root->nr_cgrps);
5128 cgroup1_pidlist_destroy_all(cgrp);
5129 cancel_work_sync(&cgrp->release_agent_work);
5131 if (cgroup_parent(cgrp)) {
5133 * We get a ref to the parent, and put the ref when
5134 * this cgroup is being freed, so it's guaranteed
5135 * that the parent won't be destroyed before its
5138 cgroup_put(cgroup_parent(cgrp));
5139 kernfs_put(cgrp->kn);
5140 psi_cgroup_free(cgrp);
5141 cgroup_rstat_exit(cgrp);
5145 * This is root cgroup's refcnt reaching zero,
5146 * which indicates that the root should be
5149 cgroup_destroy_root(cgrp->root);
5154 static void css_release_work_fn(struct work_struct *work)
5156 struct cgroup_subsys_state *css =
5157 container_of(work, struct cgroup_subsys_state, destroy_work);
5158 struct cgroup_subsys *ss = css->ss;
5159 struct cgroup *cgrp = css->cgroup;
5161 mutex_lock(&cgroup_mutex);
5163 css->flags |= CSS_RELEASED;
5164 list_del_rcu(&css->sibling);
5167 /* css release path */
5168 if (!list_empty(&css->rstat_css_node)) {
5169 cgroup_rstat_flush(cgrp);
5170 list_del_rcu(&css->rstat_css_node);
5173 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
5174 if (ss->css_released)
5175 ss->css_released(css);
5177 struct cgroup *tcgrp;
5179 /* cgroup release path */
5180 TRACE_CGROUP_PATH(release, cgrp);
5182 cgroup_rstat_flush(cgrp);
5184 spin_lock_irq(&css_set_lock);
5185 for (tcgrp = cgroup_parent(cgrp); tcgrp;
5186 tcgrp = cgroup_parent(tcgrp))
5187 tcgrp->nr_dying_descendants--;
5188 spin_unlock_irq(&css_set_lock);
5191 * There are two control paths which try to determine
5192 * cgroup from dentry without going through kernfs -
5193 * cgroupstats_build() and css_tryget_online_from_dir().
5194 * Those are supported by RCU protecting clearing of
5195 * cgrp->kn->priv backpointer.
5198 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
5202 mutex_unlock(&cgroup_mutex);
5204 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5205 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
5208 static void css_release(struct percpu_ref *ref)
5210 struct cgroup_subsys_state *css =
5211 container_of(ref, struct cgroup_subsys_state, refcnt);
5213 INIT_WORK(&css->destroy_work, css_release_work_fn);
5214 queue_work(cgroup_destroy_wq, &css->destroy_work);
5217 static void init_and_link_css(struct cgroup_subsys_state *css,
5218 struct cgroup_subsys *ss, struct cgroup *cgrp)
5220 lockdep_assert_held(&cgroup_mutex);
5222 cgroup_get_live(cgrp);
5224 memset(css, 0, sizeof(*css));
5228 INIT_LIST_HEAD(&css->sibling);
5229 INIT_LIST_HEAD(&css->children);
5230 INIT_LIST_HEAD(&css->rstat_css_node);
5231 css->serial_nr = css_serial_nr_next++;
5232 atomic_set(&css->online_cnt, 0);
5234 if (cgroup_parent(cgrp)) {
5235 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
5236 css_get(css->parent);
5239 if (ss->css_rstat_flush)
5240 list_add_rcu(&css->rstat_css_node, &cgrp->rstat_css_list);
5242 BUG_ON(cgroup_css(cgrp, ss));
5245 /* invoke ->css_online() on a new CSS and mark it online if successful */
5246 static int online_css(struct cgroup_subsys_state *css)
5248 struct cgroup_subsys *ss = css->ss;
5251 lockdep_assert_held(&cgroup_mutex);
5254 ret = ss->css_online(css);
5256 css->flags |= CSS_ONLINE;
5257 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
5259 atomic_inc(&css->online_cnt);
5261 atomic_inc(&css->parent->online_cnt);
5266 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
5267 static void offline_css(struct cgroup_subsys_state *css)
5269 struct cgroup_subsys *ss = css->ss;
5271 lockdep_assert_held(&cgroup_mutex);
5273 if (!(css->flags & CSS_ONLINE))
5276 if (ss->css_offline)
5277 ss->css_offline(css);
5279 css->flags &= ~CSS_ONLINE;
5280 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
5282 wake_up_all(&css->cgroup->offline_waitq);
5286 * css_create - create a cgroup_subsys_state
5287 * @cgrp: the cgroup new css will be associated with
5288 * @ss: the subsys of new css
5290 * Create a new css associated with @cgrp - @ss pair. On success, the new
5291 * css is online and installed in @cgrp. This function doesn't create the
5292 * interface files. Returns 0 on success, -errno on failure.
5294 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
5295 struct cgroup_subsys *ss)
5297 struct cgroup *parent = cgroup_parent(cgrp);
5298 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
5299 struct cgroup_subsys_state *css;
5302 lockdep_assert_held(&cgroup_mutex);
5304 css = ss->css_alloc(parent_css);
5306 css = ERR_PTR(-ENOMEM);
5310 init_and_link_css(css, ss, cgrp);
5312 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
5316 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
5321 /* @css is ready to be brought online now, make it visible */
5322 list_add_tail_rcu(&css->sibling, &parent_css->children);
5323 cgroup_idr_replace(&ss->css_idr, css, css->id);
5325 err = online_css(css);
5332 list_del_rcu(&css->sibling);
5334 list_del_rcu(&css->rstat_css_node);
5335 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5336 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
5337 return ERR_PTR(err);
5341 * The returned cgroup is fully initialized including its control mask, but
5342 * it isn't associated with its kernfs_node and doesn't have the control
5345 static struct cgroup *cgroup_create(struct cgroup *parent, const char *name,
5348 struct cgroup_root *root = parent->root;
5349 struct cgroup *cgrp, *tcgrp;
5350 struct kernfs_node *kn;
5351 int level = parent->level + 1;
5354 /* allocate the cgroup and its ID, 0 is reserved for the root */
5355 cgrp = kzalloc(struct_size(cgrp, ancestor_ids, (level + 1)),
5358 return ERR_PTR(-ENOMEM);
5360 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
5364 ret = cgroup_rstat_init(cgrp);
5366 goto out_cancel_ref;
5368 /* create the directory */
5369 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
5376 init_cgroup_housekeeping(cgrp);
5378 cgrp->self.parent = &parent->self;
5380 cgrp->level = level;
5382 ret = psi_cgroup_alloc(cgrp);
5384 goto out_kernfs_remove;
5386 ret = cgroup_bpf_inherit(cgrp);
5391 * New cgroup inherits effective freeze counter, and
5392 * if the parent has to be frozen, the child has too.
5394 cgrp->freezer.e_freeze = parent->freezer.e_freeze;
5395 if (cgrp->freezer.e_freeze) {
5397 * Set the CGRP_FREEZE flag, so when a process will be
5398 * attached to the child cgroup, it will become frozen.
5399 * At this point the new cgroup is unpopulated, so we can
5400 * consider it frozen immediately.
5402 set_bit(CGRP_FREEZE, &cgrp->flags);
5403 set_bit(CGRP_FROZEN, &cgrp->flags);
5406 spin_lock_irq(&css_set_lock);
5407 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5408 cgrp->ancestor_ids[tcgrp->level] = cgroup_id(tcgrp);
5410 if (tcgrp != cgrp) {
5411 tcgrp->nr_descendants++;
5414 * If the new cgroup is frozen, all ancestor cgroups
5415 * get a new frozen descendant, but their state can't
5416 * change because of this.
5418 if (cgrp->freezer.e_freeze)
5419 tcgrp->freezer.nr_frozen_descendants++;
5422 spin_unlock_irq(&css_set_lock);
5424 if (notify_on_release(parent))
5425 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
5427 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
5428 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
5430 cgrp->self.serial_nr = css_serial_nr_next++;
5432 /* allocation complete, commit to creation */
5433 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
5434 atomic_inc(&root->nr_cgrps);
5435 cgroup_get_live(parent);
5438 * On the default hierarchy, a child doesn't automatically inherit
5439 * subtree_control from the parent. Each is configured manually.
5441 if (!cgroup_on_dfl(cgrp))
5442 cgrp->subtree_control = cgroup_control(cgrp);
5444 cgroup_propagate_control(cgrp);
5449 psi_cgroup_free(cgrp);
5451 kernfs_remove(cgrp->kn);
5453 cgroup_rstat_exit(cgrp);
5455 percpu_ref_exit(&cgrp->self.refcnt);
5458 return ERR_PTR(ret);
5461 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
5463 struct cgroup *cgroup;
5467 lockdep_assert_held(&cgroup_mutex);
5469 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
5470 if (cgroup->nr_descendants >= cgroup->max_descendants)
5473 if (level > cgroup->max_depth)
5484 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
5486 struct cgroup *parent, *cgrp;
5489 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
5490 if (strchr(name, '\n'))
5493 parent = cgroup_kn_lock_live(parent_kn, false);
5497 if (!cgroup_check_hierarchy_limits(parent)) {
5502 cgrp = cgroup_create(parent, name, mode);
5504 ret = PTR_ERR(cgrp);
5509 * This extra ref will be put in cgroup_free_fn() and guarantees
5510 * that @cgrp->kn is always accessible.
5512 kernfs_get(cgrp->kn);
5514 ret = cgroup_kn_set_ugid(cgrp->kn);
5518 ret = css_populate_dir(&cgrp->self);
5522 ret = cgroup_apply_control_enable(cgrp);
5526 TRACE_CGROUP_PATH(mkdir, cgrp);
5528 /* let's create and online css's */
5529 kernfs_activate(cgrp->kn);
5535 cgroup_destroy_locked(cgrp);
5537 cgroup_kn_unlock(parent_kn);
5542 * This is called when the refcnt of a css is confirmed to be killed.
5543 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
5544 * initiate destruction and put the css ref from kill_css().
5546 static void css_killed_work_fn(struct work_struct *work)
5548 struct cgroup_subsys_state *css =
5549 container_of(work, struct cgroup_subsys_state, destroy_work);
5551 mutex_lock(&cgroup_mutex);
5556 /* @css can't go away while we're holding cgroup_mutex */
5558 } while (css && atomic_dec_and_test(&css->online_cnt));
5560 mutex_unlock(&cgroup_mutex);
5563 /* css kill confirmation processing requires process context, bounce */
5564 static void css_killed_ref_fn(struct percpu_ref *ref)
5566 struct cgroup_subsys_state *css =
5567 container_of(ref, struct cgroup_subsys_state, refcnt);
5569 if (atomic_dec_and_test(&css->online_cnt)) {
5570 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5571 queue_work(cgroup_destroy_wq, &css->destroy_work);
5576 * kill_css - destroy a css
5577 * @css: css to destroy
5579 * This function initiates destruction of @css by removing cgroup interface
5580 * files and putting its base reference. ->css_offline() will be invoked
5581 * asynchronously once css_tryget_online() is guaranteed to fail and when
5582 * the reference count reaches zero, @css will be released.
5584 static void kill_css(struct cgroup_subsys_state *css)
5586 lockdep_assert_held(&cgroup_mutex);
5588 if (css->flags & CSS_DYING)
5591 css->flags |= CSS_DYING;
5594 * This must happen before css is disassociated with its cgroup.
5595 * See seq_css() for details.
5600 * Killing would put the base ref, but we need to keep it alive
5601 * until after ->css_offline().
5606 * cgroup core guarantees that, by the time ->css_offline() is
5607 * invoked, no new css reference will be given out via
5608 * css_tryget_online(). We can't simply call percpu_ref_kill() and
5609 * proceed to offlining css's because percpu_ref_kill() doesn't
5610 * guarantee that the ref is seen as killed on all CPUs on return.
5612 * Use percpu_ref_kill_and_confirm() to get notifications as each
5613 * css is confirmed to be seen as killed on all CPUs.
5615 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5619 * cgroup_destroy_locked - the first stage of cgroup destruction
5620 * @cgrp: cgroup to be destroyed
5622 * css's make use of percpu refcnts whose killing latency shouldn't be
5623 * exposed to userland and are RCU protected. Also, cgroup core needs to
5624 * guarantee that css_tryget_online() won't succeed by the time
5625 * ->css_offline() is invoked. To satisfy all the requirements,
5626 * destruction is implemented in the following two steps.
5628 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
5629 * userland visible parts and start killing the percpu refcnts of
5630 * css's. Set up so that the next stage will be kicked off once all
5631 * the percpu refcnts are confirmed to be killed.
5633 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5634 * rest of destruction. Once all cgroup references are gone, the
5635 * cgroup is RCU-freed.
5637 * This function implements s1. After this step, @cgrp is gone as far as
5638 * the userland is concerned and a new cgroup with the same name may be
5639 * created. As cgroup doesn't care about the names internally, this
5640 * doesn't cause any problem.
5642 static int cgroup_destroy_locked(struct cgroup *cgrp)
5643 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5645 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5646 struct cgroup_subsys_state *css;
5647 struct cgrp_cset_link *link;
5650 lockdep_assert_held(&cgroup_mutex);
5653 * Only migration can raise populated from zero and we're already
5654 * holding cgroup_mutex.
5656 if (cgroup_is_populated(cgrp))
5660 * Make sure there's no live children. We can't test emptiness of
5661 * ->self.children as dead children linger on it while being
5662 * drained; otherwise, "rmdir parent/child parent" may fail.
5664 if (css_has_online_children(&cgrp->self))
5668 * Mark @cgrp and the associated csets dead. The former prevents
5669 * further task migration and child creation by disabling
5670 * cgroup_lock_live_group(). The latter makes the csets ignored by
5671 * the migration path.
5673 cgrp->self.flags &= ~CSS_ONLINE;
5675 spin_lock_irq(&css_set_lock);
5676 list_for_each_entry(link, &cgrp->cset_links, cset_link)
5677 link->cset->dead = true;
5678 spin_unlock_irq(&css_set_lock);
5680 /* initiate massacre of all css's */
5681 for_each_css(css, ssid, cgrp)
5684 /* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
5685 css_clear_dir(&cgrp->self);
5686 kernfs_remove(cgrp->kn);
5688 if (cgroup_is_threaded(cgrp))
5689 parent->nr_threaded_children--;
5691 spin_lock_irq(&css_set_lock);
5692 for (tcgrp = cgroup_parent(cgrp); tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5693 tcgrp->nr_descendants--;
5694 tcgrp->nr_dying_descendants++;
5696 * If the dying cgroup is frozen, decrease frozen descendants
5697 * counters of ancestor cgroups.
5699 if (test_bit(CGRP_FROZEN, &cgrp->flags))
5700 tcgrp->freezer.nr_frozen_descendants--;
5702 spin_unlock_irq(&css_set_lock);
5704 cgroup1_check_for_release(parent);
5706 cgroup_bpf_offline(cgrp);
5708 /* put the base reference */
5709 percpu_ref_kill(&cgrp->self.refcnt);
5714 int cgroup_rmdir(struct kernfs_node *kn)
5716 struct cgroup *cgrp;
5719 cgrp = cgroup_kn_lock_live(kn, false);
5723 ret = cgroup_destroy_locked(cgrp);
5725 TRACE_CGROUP_PATH(rmdir, cgrp);
5727 cgroup_kn_unlock(kn);
5731 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5732 .show_options = cgroup_show_options,
5733 .mkdir = cgroup_mkdir,
5734 .rmdir = cgroup_rmdir,
5735 .show_path = cgroup_show_path,
5738 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5740 struct cgroup_subsys_state *css;
5742 pr_debug("Initializing cgroup subsys %s\n", ss->name);
5744 mutex_lock(&cgroup_mutex);
5746 idr_init(&ss->css_idr);
5747 INIT_LIST_HEAD(&ss->cfts);
5749 /* Create the root cgroup state for this subsystem */
5750 ss->root = &cgrp_dfl_root;
5751 css = ss->css_alloc(NULL);
5752 /* We don't handle early failures gracefully */
5753 BUG_ON(IS_ERR(css));
5754 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5757 * Root csses are never destroyed and we can't initialize
5758 * percpu_ref during early init. Disable refcnting.
5760 css->flags |= CSS_NO_REF;
5763 /* allocation can't be done safely during early init */
5766 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5767 BUG_ON(css->id < 0);
5770 /* Update the init_css_set to contain a subsys
5771 * pointer to this state - since the subsystem is
5772 * newly registered, all tasks and hence the
5773 * init_css_set is in the subsystem's root cgroup. */
5774 init_css_set.subsys[ss->id] = css;
5776 have_fork_callback |= (bool)ss->fork << ss->id;
5777 have_exit_callback |= (bool)ss->exit << ss->id;
5778 have_release_callback |= (bool)ss->release << ss->id;
5779 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5781 /* At system boot, before all subsystems have been
5782 * registered, no tasks have been forked, so we don't
5783 * need to invoke fork callbacks here. */
5784 BUG_ON(!list_empty(&init_task.tasks));
5786 BUG_ON(online_css(css));
5788 mutex_unlock(&cgroup_mutex);
5792 * cgroup_init_early - cgroup initialization at system boot
5794 * Initialize cgroups at system boot, and initialize any
5795 * subsystems that request early init.
5797 int __init cgroup_init_early(void)
5799 static struct cgroup_fs_context __initdata ctx;
5800 struct cgroup_subsys *ss;
5803 ctx.root = &cgrp_dfl_root;
5804 init_cgroup_root(&ctx);
5805 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5807 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5809 for_each_subsys(ss, i) {
5810 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5811 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
5812 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5814 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5815 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5818 ss->name = cgroup_subsys_name[i];
5819 if (!ss->legacy_name)
5820 ss->legacy_name = cgroup_subsys_name[i];
5823 cgroup_init_subsys(ss, true);
5829 * cgroup_init - cgroup initialization
5831 * Register cgroup filesystem and /proc file, and initialize
5832 * any subsystems that didn't request early init.
5834 int __init cgroup_init(void)
5836 struct cgroup_subsys *ss;
5839 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
5840 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
5841 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
5843 cgroup_rstat_boot();
5846 * The latency of the synchronize_rcu() is too high for cgroups,
5847 * avoid it at the cost of forcing all readers into the slow path.
5849 rcu_sync_enter_start(&cgroup_threadgroup_rwsem.rss);
5851 get_user_ns(init_cgroup_ns.user_ns);
5853 mutex_lock(&cgroup_mutex);
5856 * Add init_css_set to the hash table so that dfl_root can link to
5859 hash_add(css_set_table, &init_css_set.hlist,
5860 css_set_hash(init_css_set.subsys));
5862 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
5864 mutex_unlock(&cgroup_mutex);
5866 for_each_subsys(ss, ssid) {
5867 if (ss->early_init) {
5868 struct cgroup_subsys_state *css =
5869 init_css_set.subsys[ss->id];
5871 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5873 BUG_ON(css->id < 0);
5875 cgroup_init_subsys(ss, false);
5878 list_add_tail(&init_css_set.e_cset_node[ssid],
5879 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5882 * Setting dfl_root subsys_mask needs to consider the
5883 * disabled flag and cftype registration needs kmalloc,
5884 * both of which aren't available during early_init.
5886 if (!cgroup_ssid_enabled(ssid))
5889 if (cgroup1_ssid_disabled(ssid))
5890 printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
5893 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5895 /* implicit controllers must be threaded too */
5896 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
5898 if (ss->implicit_on_dfl)
5899 cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
5900 else if (!ss->dfl_cftypes)
5901 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
5904 cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
5906 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5907 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5909 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5910 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5914 ss->bind(init_css_set.subsys[ssid]);
5916 mutex_lock(&cgroup_mutex);
5917 css_populate_dir(init_css_set.subsys[ssid]);
5918 mutex_unlock(&cgroup_mutex);
5921 /* init_css_set.subsys[] has been updated, re-hash */
5922 hash_del(&init_css_set.hlist);
5923 hash_add(css_set_table, &init_css_set.hlist,
5924 css_set_hash(init_css_set.subsys));
5926 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
5927 WARN_ON(register_filesystem(&cgroup_fs_type));
5928 WARN_ON(register_filesystem(&cgroup2_fs_type));
5929 WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show));
5930 #ifdef CONFIG_CPUSETS
5931 WARN_ON(register_filesystem(&cpuset_fs_type));
5937 static int __init cgroup_wq_init(void)
5940 * There isn't much point in executing destruction path in
5941 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5942 * Use 1 for @max_active.
5944 * We would prefer to do this in cgroup_init() above, but that
5945 * is called before init_workqueues(): so leave this until after.
5947 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5948 BUG_ON(!cgroup_destroy_wq);
5951 core_initcall(cgroup_wq_init);
5953 void cgroup_path_from_kernfs_id(u64 id, char *buf, size_t buflen)
5955 struct kernfs_node *kn;
5957 kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
5960 kernfs_path(kn, buf, buflen);
5965 * cgroup_get_from_id : get the cgroup associated with cgroup id
5967 * On success return the cgrp, on failure return NULL
5969 struct cgroup *cgroup_get_from_id(u64 id)
5971 struct kernfs_node *kn;
5972 struct cgroup *cgrp = NULL;
5974 kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
5980 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
5981 if (cgrp && !cgroup_tryget(cgrp))
5990 EXPORT_SYMBOL_GPL(cgroup_get_from_id);
5993 * proc_cgroup_show()
5994 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5995 * - Used for /proc/<pid>/cgroup.
5997 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5998 struct pid *pid, struct task_struct *tsk)
6002 struct cgroup_root *root;
6005 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6009 mutex_lock(&cgroup_mutex);
6010 spin_lock_irq(&css_set_lock);
6012 for_each_root(root) {
6013 struct cgroup_subsys *ss;
6014 struct cgroup *cgrp;
6015 int ssid, count = 0;
6017 if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
6020 seq_printf(m, "%d:", root->hierarchy_id);
6021 if (root != &cgrp_dfl_root)
6022 for_each_subsys(ss, ssid)
6023 if (root->subsys_mask & (1 << ssid))
6024 seq_printf(m, "%s%s", count++ ? "," : "",
6026 if (strlen(root->name))
6027 seq_printf(m, "%sname=%s", count ? "," : "",
6031 cgrp = task_cgroup_from_root(tsk, root);
6034 * On traditional hierarchies, all zombie tasks show up as
6035 * belonging to the root cgroup. On the default hierarchy,
6036 * while a zombie doesn't show up in "cgroup.procs" and
6037 * thus can't be migrated, its /proc/PID/cgroup keeps
6038 * reporting the cgroup it belonged to before exiting. If
6039 * the cgroup is removed before the zombie is reaped,
6040 * " (deleted)" is appended to the cgroup path.
6042 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
6043 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
6044 current->nsproxy->cgroup_ns);
6045 if (retval >= PATH_MAX)
6046 retval = -ENAMETOOLONG;
6055 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
6056 seq_puts(m, " (deleted)\n");
6063 spin_unlock_irq(&css_set_lock);
6064 mutex_unlock(&cgroup_mutex);
6071 * cgroup_fork - initialize cgroup related fields during copy_process()
6072 * @child: pointer to task_struct of forking parent process.
6074 * A task is associated with the init_css_set until cgroup_post_fork()
6075 * attaches it to the target css_set.
6077 void cgroup_fork(struct task_struct *child)
6079 RCU_INIT_POINTER(child->cgroups, &init_css_set);
6080 INIT_LIST_HEAD(&child->cg_list);
6083 static struct cgroup *cgroup_get_from_file(struct file *f)
6085 struct cgroup_subsys_state *css;
6086 struct cgroup *cgrp;
6088 css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
6090 return ERR_CAST(css);
6093 if (!cgroup_on_dfl(cgrp)) {
6095 return ERR_PTR(-EBADF);
6102 * cgroup_css_set_fork - find or create a css_set for a child process
6103 * @kargs: the arguments passed to create the child process
6105 * This functions finds or creates a new css_set which the child
6106 * process will be attached to in cgroup_post_fork(). By default,
6107 * the child process will be given the same css_set as its parent.
6109 * If CLONE_INTO_CGROUP is specified this function will try to find an
6110 * existing css_set which includes the requested cgroup and if not create
6111 * a new css_set that the child will be attached to later. If this function
6112 * succeeds it will hold cgroup_threadgroup_rwsem on return. If
6113 * CLONE_INTO_CGROUP is requested this function will grab cgroup mutex
6114 * before grabbing cgroup_threadgroup_rwsem and will hold a reference
6115 * to the target cgroup.
6117 static int cgroup_css_set_fork(struct kernel_clone_args *kargs)
6118 __acquires(&cgroup_mutex) __acquires(&cgroup_threadgroup_rwsem)
6121 struct cgroup *dst_cgrp = NULL;
6122 struct css_set *cset;
6123 struct super_block *sb;
6126 if (kargs->flags & CLONE_INTO_CGROUP)
6127 mutex_lock(&cgroup_mutex);
6129 cgroup_threadgroup_change_begin(current);
6131 spin_lock_irq(&css_set_lock);
6132 cset = task_css_set(current);
6134 spin_unlock_irq(&css_set_lock);
6136 if (!(kargs->flags & CLONE_INTO_CGROUP)) {
6141 f = fget_raw(kargs->cgroup);
6146 sb = f->f_path.dentry->d_sb;
6148 dst_cgrp = cgroup_get_from_file(f);
6149 if (IS_ERR(dst_cgrp)) {
6150 ret = PTR_ERR(dst_cgrp);
6155 if (cgroup_is_dead(dst_cgrp)) {
6161 * Verify that we the target cgroup is writable for us. This is
6162 * usually done by the vfs layer but since we're not going through
6163 * the vfs layer here we need to do it "manually".
6165 ret = cgroup_may_write(dst_cgrp, sb);
6170 * Spawning a task directly into a cgroup works by passing a file
6171 * descriptor to the target cgroup directory. This can even be an O_PATH
6172 * file descriptor. But it can never be a cgroup.procs file descriptor.
6173 * This was done on purpose so spawning into a cgroup could be
6174 * conceptualized as an atomic
6176 * fd = openat(dfd_cgroup, "cgroup.procs", ...);
6177 * write(fd, <child-pid>, ...);
6179 * sequence, i.e. it's a shorthand for the caller opening and writing
6180 * cgroup.procs of the cgroup indicated by @dfd_cgroup. This allows us
6181 * to always use the caller's credentials.
6183 ret = cgroup_attach_permissions(cset->dfl_cgrp, dst_cgrp, sb,
6184 !(kargs->flags & CLONE_THREAD),
6185 current->nsproxy->cgroup_ns);
6189 kargs->cset = find_css_set(cset, dst_cgrp);
6197 kargs->cgrp = dst_cgrp;
6201 cgroup_threadgroup_change_end(current);
6202 mutex_unlock(&cgroup_mutex);
6206 cgroup_put(dst_cgrp);
6209 put_css_set(kargs->cset);
6214 * cgroup_css_set_put_fork - drop references we took during fork
6215 * @kargs: the arguments passed to create the child process
6217 * Drop references to the prepared css_set and target cgroup if
6218 * CLONE_INTO_CGROUP was requested.
6220 static void cgroup_css_set_put_fork(struct kernel_clone_args *kargs)
6221 __releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6223 cgroup_threadgroup_change_end(current);
6225 if (kargs->flags & CLONE_INTO_CGROUP) {
6226 struct cgroup *cgrp = kargs->cgrp;
6227 struct css_set *cset = kargs->cset;
6229 mutex_unlock(&cgroup_mutex);
6244 * cgroup_can_fork - called on a new task before the process is exposed
6245 * @child: the child process
6246 * @kargs: the arguments passed to create the child process
6248 * This prepares a new css_set for the child process which the child will
6249 * be attached to in cgroup_post_fork().
6250 * This calls the subsystem can_fork() callbacks. If the cgroup_can_fork()
6251 * callback returns an error, the fork aborts with that error code. This
6252 * allows for a cgroup subsystem to conditionally allow or deny new forks.
6254 int cgroup_can_fork(struct task_struct *child, struct kernel_clone_args *kargs)
6256 struct cgroup_subsys *ss;
6259 ret = cgroup_css_set_fork(kargs);
6263 do_each_subsys_mask(ss, i, have_canfork_callback) {
6264 ret = ss->can_fork(child, kargs->cset);
6267 } while_each_subsys_mask();
6272 for_each_subsys(ss, j) {
6275 if (ss->cancel_fork)
6276 ss->cancel_fork(child, kargs->cset);
6279 cgroup_css_set_put_fork(kargs);
6285 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
6286 * @child: the child process
6287 * @kargs: the arguments passed to create the child process
6289 * This calls the cancel_fork() callbacks if a fork failed *after*
6290 * cgroup_can_fork() succeeded and cleans up references we took to
6291 * prepare a new css_set for the child process in cgroup_can_fork().
6293 void cgroup_cancel_fork(struct task_struct *child,
6294 struct kernel_clone_args *kargs)
6296 struct cgroup_subsys *ss;
6299 for_each_subsys(ss, i)
6300 if (ss->cancel_fork)
6301 ss->cancel_fork(child, kargs->cset);
6303 cgroup_css_set_put_fork(kargs);
6307 * cgroup_post_fork - finalize cgroup setup for the child process
6308 * @child: the child process
6309 * @kargs: the arguments passed to create the child process
6311 * Attach the child process to its css_set calling the subsystem fork()
6314 void cgroup_post_fork(struct task_struct *child,
6315 struct kernel_clone_args *kargs)
6316 __releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6318 unsigned long cgrp_flags = 0;
6320 struct cgroup_subsys *ss;
6321 struct css_set *cset;
6327 spin_lock_irq(&css_set_lock);
6329 /* init tasks are special, only link regular threads */
6330 if (likely(child->pid)) {
6332 cgrp_flags = kargs->cgrp->flags;
6334 cgrp_flags = cset->dfl_cgrp->flags;
6336 WARN_ON_ONCE(!list_empty(&child->cg_list));
6338 css_set_move_task(child, NULL, cset, false);
6344 if (!(child->flags & PF_KTHREAD)) {
6345 if (unlikely(test_bit(CGRP_FREEZE, &cgrp_flags))) {
6347 * If the cgroup has to be frozen, the new task has
6348 * too. Let's set the JOBCTL_TRAP_FREEZE jobctl bit to
6349 * get the task into the frozen state.
6351 spin_lock(&child->sighand->siglock);
6352 WARN_ON_ONCE(child->frozen);
6353 child->jobctl |= JOBCTL_TRAP_FREEZE;
6354 spin_unlock(&child->sighand->siglock);
6357 * Calling cgroup_update_frozen() isn't required here,
6358 * because it will be called anyway a bit later from
6359 * do_freezer_trap(). So we avoid cgroup's transient
6360 * switch from the frozen state and back.
6365 * If the cgroup is to be killed notice it now and take the
6366 * child down right after we finished preparing it for
6369 kill = test_bit(CGRP_KILL, &cgrp_flags);
6372 spin_unlock_irq(&css_set_lock);
6375 * Call ss->fork(). This must happen after @child is linked on
6376 * css_set; otherwise, @child might change state between ->fork()
6377 * and addition to css_set.
6379 do_each_subsys_mask(ss, i, have_fork_callback) {
6381 } while_each_subsys_mask();
6383 /* Make the new cset the root_cset of the new cgroup namespace. */
6384 if (kargs->flags & CLONE_NEWCGROUP) {
6385 struct css_set *rcset = child->nsproxy->cgroup_ns->root_cset;
6388 child->nsproxy->cgroup_ns->root_cset = cset;
6392 /* Cgroup has to be killed so take down child immediately. */
6394 do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, child, PIDTYPE_TGID);
6396 cgroup_css_set_put_fork(kargs);
6400 * cgroup_exit - detach cgroup from exiting task
6401 * @tsk: pointer to task_struct of exiting process
6403 * Description: Detach cgroup from @tsk.
6406 void cgroup_exit(struct task_struct *tsk)
6408 struct cgroup_subsys *ss;
6409 struct css_set *cset;
6412 spin_lock_irq(&css_set_lock);
6414 WARN_ON_ONCE(list_empty(&tsk->cg_list));
6415 cset = task_css_set(tsk);
6416 css_set_move_task(tsk, cset, NULL, false);
6417 list_add_tail(&tsk->cg_list, &cset->dying_tasks);
6420 WARN_ON_ONCE(cgroup_task_frozen(tsk));
6421 if (unlikely(!(tsk->flags & PF_KTHREAD) &&
6422 test_bit(CGRP_FREEZE, &task_dfl_cgroup(tsk)->flags)))
6423 cgroup_update_frozen(task_dfl_cgroup(tsk));
6425 spin_unlock_irq(&css_set_lock);
6427 /* see cgroup_post_fork() for details */
6428 do_each_subsys_mask(ss, i, have_exit_callback) {
6430 } while_each_subsys_mask();
6433 void cgroup_release(struct task_struct *task)
6435 struct cgroup_subsys *ss;
6438 do_each_subsys_mask(ss, ssid, have_release_callback) {
6440 } while_each_subsys_mask();
6442 spin_lock_irq(&css_set_lock);
6443 css_set_skip_task_iters(task_css_set(task), task);
6444 list_del_init(&task->cg_list);
6445 spin_unlock_irq(&css_set_lock);
6448 void cgroup_free(struct task_struct *task)
6450 struct css_set *cset = task_css_set(task);
6454 static int __init cgroup_disable(char *str)
6456 struct cgroup_subsys *ss;
6460 while ((token = strsep(&str, ",")) != NULL) {
6464 for_each_subsys(ss, i) {
6465 if (strcmp(token, ss->name) &&
6466 strcmp(token, ss->legacy_name))
6469 static_branch_disable(cgroup_subsys_enabled_key[i]);
6470 pr_info("Disabling %s control group subsystem\n",
6474 for (i = 0; i < OPT_FEATURE_COUNT; i++) {
6475 if (strcmp(token, cgroup_opt_feature_names[i]))
6477 cgroup_feature_disable_mask |= 1 << i;
6478 pr_info("Disabling %s control group feature\n",
6479 cgroup_opt_feature_names[i]);
6485 __setup("cgroup_disable=", cgroup_disable);
6487 void __init __weak enable_debug_cgroup(void) { }
6489 static int __init enable_cgroup_debug(char *str)
6491 cgroup_debug = true;
6492 enable_debug_cgroup();
6495 __setup("cgroup_debug", enable_cgroup_debug);
6498 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
6499 * @dentry: directory dentry of interest
6500 * @ss: subsystem of interest
6502 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
6503 * to get the corresponding css and return it. If such css doesn't exist
6504 * or can't be pinned, an ERR_PTR value is returned.
6506 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
6507 struct cgroup_subsys *ss)
6509 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
6510 struct file_system_type *s_type = dentry->d_sb->s_type;
6511 struct cgroup_subsys_state *css = NULL;
6512 struct cgroup *cgrp;
6514 /* is @dentry a cgroup dir? */
6515 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
6516 !kn || kernfs_type(kn) != KERNFS_DIR)
6517 return ERR_PTR(-EBADF);
6522 * This path doesn't originate from kernfs and @kn could already
6523 * have been or be removed at any point. @kn->priv is RCU
6524 * protected for this access. See css_release_work_fn() for details.
6526 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6528 css = cgroup_css(cgrp, ss);
6530 if (!css || !css_tryget_online(css))
6531 css = ERR_PTR(-ENOENT);
6538 * css_from_id - lookup css by id
6539 * @id: the cgroup id
6540 * @ss: cgroup subsys to be looked into
6542 * Returns the css if there's valid one with @id, otherwise returns NULL.
6543 * Should be called under rcu_read_lock().
6545 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
6547 WARN_ON_ONCE(!rcu_read_lock_held());
6548 return idr_find(&ss->css_idr, id);
6552 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
6553 * @path: path on the default hierarchy
6555 * Find the cgroup at @path on the default hierarchy, increment its
6556 * reference count and return it. Returns pointer to the found cgroup on
6557 * success, ERR_PTR(-ENOENT) if @path doesn't exist or if the cgroup has already
6558 * been released and ERR_PTR(-ENOTDIR) if @path points to a non-directory.
6560 struct cgroup *cgroup_get_from_path(const char *path)
6562 struct kernfs_node *kn;
6563 struct cgroup *cgrp = ERR_PTR(-ENOENT);
6565 kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
6569 if (kernfs_type(kn) != KERNFS_DIR) {
6570 cgrp = ERR_PTR(-ENOTDIR);
6576 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6577 if (!cgrp || !cgroup_tryget(cgrp))
6578 cgrp = ERR_PTR(-ENOENT);
6587 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
6590 * cgroup_get_from_fd - get a cgroup pointer from a fd
6591 * @fd: fd obtained by open(cgroup2_dir)
6593 * Find the cgroup from a fd which should be obtained
6594 * by opening a cgroup directory. Returns a pointer to the
6595 * cgroup on success. ERR_PTR is returned if the cgroup
6598 struct cgroup *cgroup_get_from_fd(int fd)
6600 struct cgroup *cgrp;
6605 return ERR_PTR(-EBADF);
6607 cgrp = cgroup_get_from_file(f);
6611 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
6613 static u64 power_of_ten(int power)
6622 * cgroup_parse_float - parse a floating number
6623 * @input: input string
6624 * @dec_shift: number of decimal digits to shift
6627 * Parse a decimal floating point number in @input and store the result in
6628 * @v with decimal point right shifted @dec_shift times. For example, if
6629 * @input is "12.3456" and @dec_shift is 3, *@v will be set to 12345.
6630 * Returns 0 on success, -errno otherwise.
6632 * There's nothing cgroup specific about this function except that it's
6633 * currently the only user.
6635 int cgroup_parse_float(const char *input, unsigned dec_shift, s64 *v)
6637 s64 whole, frac = 0;
6638 int fstart = 0, fend = 0, flen;
6640 if (!sscanf(input, "%lld.%n%lld%n", &whole, &fstart, &frac, &fend))
6645 flen = fend > fstart ? fend - fstart : 0;
6646 if (flen < dec_shift)
6647 frac *= power_of_ten(dec_shift - flen);
6649 frac = DIV_ROUND_CLOSEST_ULL(frac, power_of_ten(flen - dec_shift));
6651 *v = whole * power_of_ten(dec_shift) + frac;
6656 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
6657 * definition in cgroup-defs.h.
6659 #ifdef CONFIG_SOCK_CGROUP_DATA
6661 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
6663 struct cgroup *cgroup;
6666 /* Don't associate the sock with unrelated interrupted task's cgroup. */
6667 if (in_interrupt()) {
6668 cgroup = &cgrp_dfl_root.cgrp;
6674 struct css_set *cset;
6676 cset = task_css_set(current);
6677 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
6678 cgroup = cset->dfl_cgrp;
6684 skcd->cgroup = cgroup;
6685 cgroup_bpf_get(cgroup);
6689 void cgroup_sk_clone(struct sock_cgroup_data *skcd)
6691 struct cgroup *cgrp = sock_cgroup_ptr(skcd);
6694 * We might be cloning a socket which is left in an empty
6695 * cgroup and the cgroup might have already been rmdir'd.
6696 * Don't use cgroup_get_live().
6699 cgroup_bpf_get(cgrp);
6702 void cgroup_sk_free(struct sock_cgroup_data *skcd)
6704 struct cgroup *cgrp = sock_cgroup_ptr(skcd);
6706 cgroup_bpf_put(cgrp);
6710 #endif /* CONFIG_SOCK_CGROUP_DATA */
6713 static ssize_t show_delegatable_files(struct cftype *files, char *buf,
6714 ssize_t size, const char *prefix)
6719 for (cft = files; cft && cft->name[0] != '\0'; cft++) {
6720 if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
6723 if ((cft->flags & CFTYPE_PRESSURE) && !cgroup_psi_enabled())
6727 ret += snprintf(buf + ret, size - ret, "%s.", prefix);
6729 ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
6731 if (WARN_ON(ret >= size))
6738 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
6741 struct cgroup_subsys *ss;
6745 ret = show_delegatable_files(cgroup_base_files, buf, PAGE_SIZE - ret,
6748 for_each_subsys(ss, ssid)
6749 ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
6751 cgroup_subsys_name[ssid]);
6755 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
6757 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
6760 return snprintf(buf, PAGE_SIZE,
6762 "memory_localevents\n"
6763 "memory_recursiveprot\n");
6765 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
6767 static struct attribute *cgroup_sysfs_attrs[] = {
6768 &cgroup_delegate_attr.attr,
6769 &cgroup_features_attr.attr,
6773 static const struct attribute_group cgroup_sysfs_attr_group = {
6774 .attrs = cgroup_sysfs_attrs,
6778 static int __init cgroup_sysfs_init(void)
6780 return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
6782 subsys_initcall(cgroup_sysfs_init);
6784 #endif /* CONFIG_SYSFS */