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/cpu.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 * cgroup_mutex is the master lock. Any modification to cgroup or its
73 * hierarchy must be performed while holding it.
75 * css_set_lock protects task->cgroups pointer, the list of css_set
76 * objects, and the chain of tasks off each css_set.
78 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
79 * cgroup.h can use them for lockdep annotations.
81 DEFINE_MUTEX(cgroup_mutex);
82 DEFINE_SPINLOCK(css_set_lock);
84 #ifdef CONFIG_PROVE_RCU
85 EXPORT_SYMBOL_GPL(cgroup_mutex);
86 EXPORT_SYMBOL_GPL(css_set_lock);
89 DEFINE_SPINLOCK(trace_cgroup_path_lock);
90 char trace_cgroup_path[TRACE_CGROUP_PATH_LEN];
91 bool cgroup_debug __read_mostly;
94 * Protects cgroup_idr and css_idr so that IDs can be released without
95 * grabbing cgroup_mutex.
97 static DEFINE_SPINLOCK(cgroup_idr_lock);
100 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
101 * against file removal/re-creation across css hiding.
103 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
105 DEFINE_PERCPU_RWSEM(cgroup_threadgroup_rwsem);
107 #define cgroup_assert_mutex_or_rcu_locked() \
108 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
109 !lockdep_is_held(&cgroup_mutex), \
110 "cgroup_mutex or RCU read lock required");
113 * cgroup destruction makes heavy use of work items and there can be a lot
114 * of concurrent destructions. Use a separate workqueue so that cgroup
115 * destruction work items don't end up filling up max_active of system_wq
116 * which may lead to deadlock.
118 static struct workqueue_struct *cgroup_destroy_wq;
120 /* generate an array of cgroup subsystem pointers */
121 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
122 struct cgroup_subsys *cgroup_subsys[] = {
123 #include <linux/cgroup_subsys.h>
127 /* array of cgroup subsystem names */
128 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
129 static const char *cgroup_subsys_name[] = {
130 #include <linux/cgroup_subsys.h>
134 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
136 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
137 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
138 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
139 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
140 #include <linux/cgroup_subsys.h>
143 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
144 static struct static_key_true *cgroup_subsys_enabled_key[] = {
145 #include <linux/cgroup_subsys.h>
149 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
150 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
151 #include <linux/cgroup_subsys.h>
155 static DEFINE_PER_CPU(struct cgroup_rstat_cpu, cgrp_dfl_root_rstat_cpu);
158 * The default hierarchy, reserved for the subsystems that are otherwise
159 * unattached - it never has more than a single cgroup, and all tasks are
160 * part of that cgroup.
162 struct cgroup_root cgrp_dfl_root = { .cgrp.rstat_cpu = &cgrp_dfl_root_rstat_cpu };
163 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
166 * The default hierarchy always exists but is hidden until mounted for the
167 * first time. This is for backward compatibility.
169 static bool cgrp_dfl_visible;
171 /* some controllers are not supported in the default hierarchy */
172 static u16 cgrp_dfl_inhibit_ss_mask;
174 /* some controllers are implicitly enabled on the default hierarchy */
175 static u16 cgrp_dfl_implicit_ss_mask;
177 /* some controllers can be threaded on the default hierarchy */
178 static u16 cgrp_dfl_threaded_ss_mask;
180 /* The list of hierarchy roots */
181 LIST_HEAD(cgroup_roots);
182 static int cgroup_root_count;
184 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
185 static DEFINE_IDR(cgroup_hierarchy_idr);
188 * Assign a monotonically increasing serial number to csses. It guarantees
189 * cgroups with bigger numbers are newer than those with smaller numbers.
190 * Also, as csses are always appended to the parent's ->children list, it
191 * guarantees that sibling csses are always sorted in the ascending serial
192 * number order on the list. Protected by cgroup_mutex.
194 static u64 css_serial_nr_next = 1;
197 * These bitmasks identify subsystems with specific features to avoid
198 * having to do iterative checks repeatedly.
200 static u16 have_fork_callback __read_mostly;
201 static u16 have_exit_callback __read_mostly;
202 static u16 have_release_callback __read_mostly;
203 static u16 have_canfork_callback __read_mostly;
205 /* cgroup namespace for init task */
206 struct cgroup_namespace init_cgroup_ns = {
207 .count = REFCOUNT_INIT(2),
208 .user_ns = &init_user_ns,
209 .ns.ops = &cgroupns_operations,
210 .ns.inum = PROC_CGROUP_INIT_INO,
211 .root_cset = &init_css_set,
214 static struct file_system_type cgroup2_fs_type;
215 static struct cftype cgroup_base_files[];
217 static int cgroup_apply_control(struct cgroup *cgrp);
218 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
219 static void css_task_iter_skip(struct css_task_iter *it,
220 struct task_struct *task);
221 static int cgroup_destroy_locked(struct cgroup *cgrp);
222 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
223 struct cgroup_subsys *ss);
224 static void css_release(struct percpu_ref *ref);
225 static void kill_css(struct cgroup_subsys_state *css);
226 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
227 struct cgroup *cgrp, struct cftype cfts[],
231 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
232 * @ssid: subsys ID of interest
234 * cgroup_subsys_enabled() can only be used with literal subsys names which
235 * is fine for individual subsystems but unsuitable for cgroup core. This
236 * is slower static_key_enabled() based test indexed by @ssid.
238 bool cgroup_ssid_enabled(int ssid)
240 if (CGROUP_SUBSYS_COUNT == 0)
243 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
247 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
248 * @cgrp: the cgroup of interest
250 * The default hierarchy is the v2 interface of cgroup and this function
251 * can be used to test whether a cgroup is on the default hierarchy for
252 * cases where a subsystem should behave differnetly depending on the
255 * The set of behaviors which change on the default hierarchy are still
256 * being determined and the mount option is prefixed with __DEVEL__.
258 * List of changed behaviors:
260 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
261 * and "name" are disallowed.
263 * - When mounting an existing superblock, mount options should match.
265 * - Remount is disallowed.
267 * - rename(2) is disallowed.
269 * - "tasks" is removed. Everything should be at process granularity. Use
270 * "cgroup.procs" instead.
272 * - "cgroup.procs" is not sorted. pids will be unique unless they got
273 * recycled inbetween reads.
275 * - "release_agent" and "notify_on_release" are removed. Replacement
276 * notification mechanism will be implemented.
278 * - "cgroup.clone_children" is removed.
280 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
281 * and its descendants contain no task; otherwise, 1. The file also
282 * generates kernfs notification which can be monitored through poll and
283 * [di]notify when the value of the file changes.
285 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
286 * take masks of ancestors with non-empty cpus/mems, instead of being
287 * moved to an ancestor.
289 * - cpuset: a task can be moved into an empty cpuset, and again it takes
290 * masks of ancestors.
292 * - memcg: use_hierarchy is on by default and the cgroup file for the flag
295 * - blkcg: blk-throttle becomes properly hierarchical.
297 * - debug: disallowed on the default hierarchy.
299 bool cgroup_on_dfl(const struct cgroup *cgrp)
301 return cgrp->root == &cgrp_dfl_root;
304 /* IDR wrappers which synchronize using cgroup_idr_lock */
305 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
310 idr_preload(gfp_mask);
311 spin_lock_bh(&cgroup_idr_lock);
312 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
313 spin_unlock_bh(&cgroup_idr_lock);
318 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
322 spin_lock_bh(&cgroup_idr_lock);
323 ret = idr_replace(idr, ptr, id);
324 spin_unlock_bh(&cgroup_idr_lock);
328 static void cgroup_idr_remove(struct idr *idr, int id)
330 spin_lock_bh(&cgroup_idr_lock);
332 spin_unlock_bh(&cgroup_idr_lock);
335 static bool cgroup_has_tasks(struct cgroup *cgrp)
337 return cgrp->nr_populated_csets;
340 bool cgroup_is_threaded(struct cgroup *cgrp)
342 return cgrp->dom_cgrp != cgrp;
345 /* can @cgrp host both domain and threaded children? */
346 static bool cgroup_is_mixable(struct cgroup *cgrp)
349 * Root isn't under domain level resource control exempting it from
350 * the no-internal-process constraint, so it can serve as a thread
351 * root and a parent of resource domains at the same time.
353 return !cgroup_parent(cgrp);
356 /* can @cgrp become a thread root? should always be true for a thread root */
357 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
359 /* mixables don't care */
360 if (cgroup_is_mixable(cgrp))
363 /* domain roots can't be nested under threaded */
364 if (cgroup_is_threaded(cgrp))
367 /* can only have either domain or threaded children */
368 if (cgrp->nr_populated_domain_children)
371 /* and no domain controllers can be enabled */
372 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
378 /* is @cgrp root of a threaded subtree? */
379 bool cgroup_is_thread_root(struct cgroup *cgrp)
381 /* thread root should be a domain */
382 if (cgroup_is_threaded(cgrp))
385 /* a domain w/ threaded children is a thread root */
386 if (cgrp->nr_threaded_children)
390 * A domain which has tasks and explicit threaded controllers
391 * enabled is a thread root.
393 if (cgroup_has_tasks(cgrp) &&
394 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
400 /* a domain which isn't connected to the root w/o brekage can't be used */
401 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
403 /* the cgroup itself can be a thread root */
404 if (cgroup_is_threaded(cgrp))
407 /* but the ancestors can't be unless mixable */
408 while ((cgrp = cgroup_parent(cgrp))) {
409 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
411 if (cgroup_is_threaded(cgrp))
418 /* subsystems visibly enabled on a cgroup */
419 static u16 cgroup_control(struct cgroup *cgrp)
421 struct cgroup *parent = cgroup_parent(cgrp);
422 u16 root_ss_mask = cgrp->root->subsys_mask;
425 u16 ss_mask = parent->subtree_control;
427 /* threaded cgroups can only have threaded controllers */
428 if (cgroup_is_threaded(cgrp))
429 ss_mask &= cgrp_dfl_threaded_ss_mask;
433 if (cgroup_on_dfl(cgrp))
434 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
435 cgrp_dfl_implicit_ss_mask);
439 /* subsystems enabled on a cgroup */
440 static u16 cgroup_ss_mask(struct cgroup *cgrp)
442 struct cgroup *parent = cgroup_parent(cgrp);
445 u16 ss_mask = parent->subtree_ss_mask;
447 /* threaded cgroups can only have threaded controllers */
448 if (cgroup_is_threaded(cgrp))
449 ss_mask &= cgrp_dfl_threaded_ss_mask;
453 return cgrp->root->subsys_mask;
457 * cgroup_css - obtain a cgroup's css for the specified subsystem
458 * @cgrp: the cgroup of interest
459 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
461 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
462 * function must be called either under cgroup_mutex or rcu_read_lock() and
463 * the caller is responsible for pinning the returned css if it wants to
464 * keep accessing it outside the said locks. This function may return
465 * %NULL if @cgrp doesn't have @subsys_id enabled.
467 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
468 struct cgroup_subsys *ss)
471 return rcu_dereference_check(cgrp->subsys[ss->id],
472 lockdep_is_held(&cgroup_mutex));
478 * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
479 * @cgrp: the cgroup of interest
480 * @ss: the subsystem of interest
482 * Find and get @cgrp's css assocaited with @ss. If the css doesn't exist
483 * or is offline, %NULL is returned.
485 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
486 struct cgroup_subsys *ss)
488 struct cgroup_subsys_state *css;
491 css = cgroup_css(cgrp, ss);
492 if (css && !css_tryget_online(css))
500 * cgroup_e_css_by_mask - obtain a cgroup's effective css for the specified ss
501 * @cgrp: the cgroup of interest
502 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
504 * Similar to cgroup_css() but returns the effective css, which is defined
505 * as the matching css of the nearest ancestor including self which has @ss
506 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
507 * function is guaranteed to return non-NULL css.
509 static struct cgroup_subsys_state *cgroup_e_css_by_mask(struct cgroup *cgrp,
510 struct cgroup_subsys *ss)
512 lockdep_assert_held(&cgroup_mutex);
518 * This function is used while updating css associations and thus
519 * can't test the csses directly. Test ss_mask.
521 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
522 cgrp = cgroup_parent(cgrp);
527 return cgroup_css(cgrp, ss);
531 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
532 * @cgrp: the cgroup of interest
533 * @ss: the subsystem of interest
535 * Find and get the effective css of @cgrp for @ss. The effective css is
536 * defined as the matching css of the nearest ancestor including self which
537 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
538 * the root css is returned, so this function always returns a valid css.
540 * The returned css is not guaranteed to be online, and therefore it is the
541 * callers responsiblity to tryget a reference for it.
543 struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
544 struct cgroup_subsys *ss)
546 struct cgroup_subsys_state *css;
549 css = cgroup_css(cgrp, ss);
553 cgrp = cgroup_parent(cgrp);
556 return init_css_set.subsys[ss->id];
560 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
561 * @cgrp: the cgroup of interest
562 * @ss: the subsystem of interest
564 * Find and get the effective css of @cgrp for @ss. The effective css is
565 * defined as the matching css of the nearest ancestor including self which
566 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
567 * the root css is returned, so this function always returns a valid css.
568 * The returned css must be put using css_put().
570 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
571 struct cgroup_subsys *ss)
573 struct cgroup_subsys_state *css;
578 css = cgroup_css(cgrp, ss);
580 if (css && css_tryget_online(css))
582 cgrp = cgroup_parent(cgrp);
585 css = init_css_set.subsys[ss->id];
592 static void cgroup_get_live(struct cgroup *cgrp)
594 WARN_ON_ONCE(cgroup_is_dead(cgrp));
595 css_get(&cgrp->self);
599 * __cgroup_task_count - count the number of tasks in a cgroup. The caller
600 * is responsible for taking the css_set_lock.
601 * @cgrp: the cgroup in question
603 int __cgroup_task_count(const struct cgroup *cgrp)
606 struct cgrp_cset_link *link;
608 lockdep_assert_held(&css_set_lock);
610 list_for_each_entry(link, &cgrp->cset_links, cset_link)
611 count += link->cset->nr_tasks;
617 * cgroup_task_count - count the number of tasks in a cgroup.
618 * @cgrp: the cgroup in question
620 int cgroup_task_count(const struct cgroup *cgrp)
624 spin_lock_irq(&css_set_lock);
625 count = __cgroup_task_count(cgrp);
626 spin_unlock_irq(&css_set_lock);
631 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
633 struct cgroup *cgrp = of->kn->parent->priv;
634 struct cftype *cft = of_cft(of);
637 * This is open and unprotected implementation of cgroup_css().
638 * seq_css() is only called from a kernfs file operation which has
639 * an active reference on the file. Because all the subsystem
640 * files are drained before a css is disassociated with a cgroup,
641 * the matching css from the cgroup's subsys table is guaranteed to
642 * be and stay valid until the enclosing operation is complete.
645 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
649 EXPORT_SYMBOL_GPL(of_css);
652 * for_each_css - iterate all css's of a cgroup
653 * @css: the iteration cursor
654 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
655 * @cgrp: the target cgroup to iterate css's of
657 * Should be called under cgroup_[tree_]mutex.
659 #define for_each_css(css, ssid, cgrp) \
660 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
661 if (!((css) = rcu_dereference_check( \
662 (cgrp)->subsys[(ssid)], \
663 lockdep_is_held(&cgroup_mutex)))) { } \
667 * for_each_e_css - iterate all effective css's of a cgroup
668 * @css: the iteration cursor
669 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
670 * @cgrp: the target cgroup to iterate css's of
672 * Should be called under cgroup_[tree_]mutex.
674 #define for_each_e_css(css, ssid, cgrp) \
675 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
676 if (!((css) = cgroup_e_css_by_mask(cgrp, \
677 cgroup_subsys[(ssid)]))) \
682 * do_each_subsys_mask - filter for_each_subsys with a bitmask
683 * @ss: the iteration cursor
684 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
685 * @ss_mask: the bitmask
687 * The block will only run for cases where the ssid-th bit (1 << ssid) of
690 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
691 unsigned long __ss_mask = (ss_mask); \
692 if (!CGROUP_SUBSYS_COUNT) { /* to avoid spurious gcc warning */ \
696 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
697 (ss) = cgroup_subsys[ssid]; \
700 #define while_each_subsys_mask() \
705 /* iterate over child cgrps, lock should be held throughout iteration */
706 #define cgroup_for_each_live_child(child, cgrp) \
707 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
708 if (({ lockdep_assert_held(&cgroup_mutex); \
709 cgroup_is_dead(child); })) \
713 /* walk live descendants in preorder */
714 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
715 css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
716 if (({ lockdep_assert_held(&cgroup_mutex); \
717 (dsct) = (d_css)->cgroup; \
718 cgroup_is_dead(dsct); })) \
722 /* walk live descendants in postorder */
723 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
724 css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
725 if (({ lockdep_assert_held(&cgroup_mutex); \
726 (dsct) = (d_css)->cgroup; \
727 cgroup_is_dead(dsct); })) \
732 * The default css_set - used by init and its children prior to any
733 * hierarchies being mounted. It contains a pointer to the root state
734 * for each subsystem. Also used to anchor the list of css_sets. Not
735 * reference-counted, to improve performance when child cgroups
736 * haven't been created.
738 struct css_set init_css_set = {
739 .refcount = REFCOUNT_INIT(1),
740 .dom_cset = &init_css_set,
741 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
742 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
743 .dying_tasks = LIST_HEAD_INIT(init_css_set.dying_tasks),
744 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
745 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
746 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
747 .mg_src_preload_node = LIST_HEAD_INIT(init_css_set.mg_src_preload_node),
748 .mg_dst_preload_node = LIST_HEAD_INIT(init_css_set.mg_dst_preload_node),
749 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
752 * The following field is re-initialized when this cset gets linked
753 * in cgroup_init(). However, let's initialize the field
754 * statically too so that the default cgroup can be accessed safely
757 .dfl_cgrp = &cgrp_dfl_root.cgrp,
760 static int css_set_count = 1; /* 1 for init_css_set */
762 static bool css_set_threaded(struct css_set *cset)
764 return cset->dom_cset != cset;
768 * css_set_populated - does a css_set contain any tasks?
769 * @cset: target css_set
771 * css_set_populated() should be the same as !!cset->nr_tasks at steady
772 * state. However, css_set_populated() can be called while a task is being
773 * added to or removed from the linked list before the nr_tasks is
774 * properly updated. Hence, we can't just look at ->nr_tasks here.
776 static bool css_set_populated(struct css_set *cset)
778 lockdep_assert_held(&css_set_lock);
780 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
784 * cgroup_update_populated - update the populated count of a cgroup
785 * @cgrp: the target cgroup
786 * @populated: inc or dec populated count
788 * One of the css_sets associated with @cgrp is either getting its first
789 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
790 * count is propagated towards root so that a given cgroup's
791 * nr_populated_children is zero iff none of its descendants contain any
794 * @cgrp's interface file "cgroup.populated" is zero if both
795 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
796 * 1 otherwise. When the sum changes from or to zero, userland is notified
797 * that the content of the interface file has changed. This can be used to
798 * detect when @cgrp and its descendants become populated or empty.
800 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
802 struct cgroup *child = NULL;
803 int adj = populated ? 1 : -1;
805 lockdep_assert_held(&css_set_lock);
808 bool was_populated = cgroup_is_populated(cgrp);
811 cgrp->nr_populated_csets += adj;
813 if (cgroup_is_threaded(child))
814 cgrp->nr_populated_threaded_children += adj;
816 cgrp->nr_populated_domain_children += adj;
819 if (was_populated == cgroup_is_populated(cgrp))
822 cgroup1_check_for_release(cgrp);
823 TRACE_CGROUP_PATH(notify_populated, cgrp,
824 cgroup_is_populated(cgrp));
825 cgroup_file_notify(&cgrp->events_file);
828 cgrp = cgroup_parent(cgrp);
833 * css_set_update_populated - update populated state of a css_set
834 * @cset: target css_set
835 * @populated: whether @cset is populated or depopulated
837 * @cset is either getting the first task or losing the last. Update the
838 * populated counters of all associated cgroups accordingly.
840 static void css_set_update_populated(struct css_set *cset, bool populated)
842 struct cgrp_cset_link *link;
844 lockdep_assert_held(&css_set_lock);
846 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
847 cgroup_update_populated(link->cgrp, populated);
851 * @task is leaving, advance task iterators which are pointing to it so
852 * that they can resume at the next position. Advancing an iterator might
853 * remove it from the list, use safe walk. See css_task_iter_skip() for
856 static void css_set_skip_task_iters(struct css_set *cset,
857 struct task_struct *task)
859 struct css_task_iter *it, *pos;
861 list_for_each_entry_safe(it, pos, &cset->task_iters, iters_node)
862 css_task_iter_skip(it, task);
866 * css_set_move_task - move a task from one css_set to another
867 * @task: task being moved
868 * @from_cset: css_set @task currently belongs to (may be NULL)
869 * @to_cset: new css_set @task is being moved to (may be NULL)
870 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
872 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
873 * css_set, @from_cset can be NULL. If @task is being disassociated
874 * instead of moved, @to_cset can be NULL.
876 * This function automatically handles populated counter updates and
877 * css_task_iter adjustments but the caller is responsible for managing
878 * @from_cset and @to_cset's reference counts.
880 static void css_set_move_task(struct task_struct *task,
881 struct css_set *from_cset, struct css_set *to_cset,
884 lockdep_assert_held(&css_set_lock);
886 if (to_cset && !css_set_populated(to_cset))
887 css_set_update_populated(to_cset, true);
890 WARN_ON_ONCE(list_empty(&task->cg_list));
892 css_set_skip_task_iters(from_cset, task);
893 list_del_init(&task->cg_list);
894 if (!css_set_populated(from_cset))
895 css_set_update_populated(from_cset, false);
897 WARN_ON_ONCE(!list_empty(&task->cg_list));
902 * We are synchronized through cgroup_threadgroup_rwsem
903 * against PF_EXITING setting such that we can't race
904 * against cgroup_exit() changing the css_set to
905 * init_css_set and dropping the old one.
907 WARN_ON_ONCE(task->flags & PF_EXITING);
909 cgroup_move_task(task, to_cset);
910 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
916 * hash table for cgroup groups. This improves the performance to find
917 * an existing css_set. This hash doesn't (currently) take into
918 * account cgroups in empty hierarchies.
920 #define CSS_SET_HASH_BITS 7
921 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
923 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
925 unsigned long key = 0UL;
926 struct cgroup_subsys *ss;
929 for_each_subsys(ss, i)
930 key += (unsigned long)css[i];
931 key = (key >> 16) ^ key;
936 void put_css_set_locked(struct css_set *cset)
938 struct cgrp_cset_link *link, *tmp_link;
939 struct cgroup_subsys *ss;
942 lockdep_assert_held(&css_set_lock);
944 if (!refcount_dec_and_test(&cset->refcount))
947 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
949 /* This css_set is dead. unlink it and release cgroup and css refs */
950 for_each_subsys(ss, ssid) {
951 list_del(&cset->e_cset_node[ssid]);
952 css_put(cset->subsys[ssid]);
954 hash_del(&cset->hlist);
957 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
958 list_del(&link->cset_link);
959 list_del(&link->cgrp_link);
960 if (cgroup_parent(link->cgrp))
961 cgroup_put(link->cgrp);
965 if (css_set_threaded(cset)) {
966 list_del(&cset->threaded_csets_node);
967 put_css_set_locked(cset->dom_cset);
970 kfree_rcu(cset, rcu_head);
974 * compare_css_sets - helper function for find_existing_css_set().
975 * @cset: candidate css_set being tested
976 * @old_cset: existing css_set for a task
977 * @new_cgrp: cgroup that's being entered by the task
978 * @template: desired set of css pointers in css_set (pre-calculated)
980 * Returns true if "cset" matches "old_cset" except for the hierarchy
981 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
983 static bool compare_css_sets(struct css_set *cset,
984 struct css_set *old_cset,
985 struct cgroup *new_cgrp,
986 struct cgroup_subsys_state *template[])
988 struct cgroup *new_dfl_cgrp;
989 struct list_head *l1, *l2;
992 * On the default hierarchy, there can be csets which are
993 * associated with the same set of cgroups but different csses.
994 * Let's first ensure that csses match.
996 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
1000 /* @cset's domain should match the default cgroup's */
1001 if (cgroup_on_dfl(new_cgrp))
1002 new_dfl_cgrp = new_cgrp;
1004 new_dfl_cgrp = old_cset->dfl_cgrp;
1006 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
1010 * Compare cgroup pointers in order to distinguish between
1011 * different cgroups in hierarchies. As different cgroups may
1012 * share the same effective css, this comparison is always
1015 l1 = &cset->cgrp_links;
1016 l2 = &old_cset->cgrp_links;
1018 struct cgrp_cset_link *link1, *link2;
1019 struct cgroup *cgrp1, *cgrp2;
1023 /* See if we reached the end - both lists are equal length. */
1024 if (l1 == &cset->cgrp_links) {
1025 BUG_ON(l2 != &old_cset->cgrp_links);
1028 BUG_ON(l2 == &old_cset->cgrp_links);
1030 /* Locate the cgroups associated with these links. */
1031 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
1032 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
1033 cgrp1 = link1->cgrp;
1034 cgrp2 = link2->cgrp;
1035 /* Hierarchies should be linked in the same order. */
1036 BUG_ON(cgrp1->root != cgrp2->root);
1039 * If this hierarchy is the hierarchy of the cgroup
1040 * that's changing, then we need to check that this
1041 * css_set points to the new cgroup; if it's any other
1042 * hierarchy, then this css_set should point to the
1043 * same cgroup as the old css_set.
1045 if (cgrp1->root == new_cgrp->root) {
1046 if (cgrp1 != new_cgrp)
1057 * find_existing_css_set - init css array and find the matching css_set
1058 * @old_cset: the css_set that we're using before the cgroup transition
1059 * @cgrp: the cgroup that we're moving into
1060 * @template: out param for the new set of csses, should be clear on entry
1062 static struct css_set *find_existing_css_set(struct css_set *old_cset,
1063 struct cgroup *cgrp,
1064 struct cgroup_subsys_state *template[])
1066 struct cgroup_root *root = cgrp->root;
1067 struct cgroup_subsys *ss;
1068 struct css_set *cset;
1073 * Build the set of subsystem state objects that we want to see in the
1074 * new css_set. while subsystems can change globally, the entries here
1075 * won't change, so no need for locking.
1077 for_each_subsys(ss, i) {
1078 if (root->subsys_mask & (1UL << i)) {
1080 * @ss is in this hierarchy, so we want the
1081 * effective css from @cgrp.
1083 template[i] = cgroup_e_css_by_mask(cgrp, ss);
1086 * @ss is not in this hierarchy, so we don't want
1087 * to change the css.
1089 template[i] = old_cset->subsys[i];
1093 key = css_set_hash(template);
1094 hash_for_each_possible(css_set_table, cset, hlist, key) {
1095 if (!compare_css_sets(cset, old_cset, cgrp, template))
1098 /* This css_set matches what we need */
1102 /* No existing cgroup group matched */
1106 static void free_cgrp_cset_links(struct list_head *links_to_free)
1108 struct cgrp_cset_link *link, *tmp_link;
1110 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1111 list_del(&link->cset_link);
1117 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1118 * @count: the number of links to allocate
1119 * @tmp_links: list_head the allocated links are put on
1121 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1122 * through ->cset_link. Returns 0 on success or -errno.
1124 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1126 struct cgrp_cset_link *link;
1129 INIT_LIST_HEAD(tmp_links);
1131 for (i = 0; i < count; i++) {
1132 link = kzalloc(sizeof(*link), GFP_KERNEL);
1134 free_cgrp_cset_links(tmp_links);
1137 list_add(&link->cset_link, tmp_links);
1143 * link_css_set - a helper function to link a css_set to a cgroup
1144 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1145 * @cset: the css_set to be linked
1146 * @cgrp: the destination cgroup
1148 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1149 struct cgroup *cgrp)
1151 struct cgrp_cset_link *link;
1153 BUG_ON(list_empty(tmp_links));
1155 if (cgroup_on_dfl(cgrp))
1156 cset->dfl_cgrp = cgrp;
1158 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1163 * Always add links to the tail of the lists so that the lists are
1164 * in choronological order.
1166 list_move_tail(&link->cset_link, &cgrp->cset_links);
1167 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1169 if (cgroup_parent(cgrp))
1170 cgroup_get_live(cgrp);
1174 * find_css_set - return a new css_set with one cgroup updated
1175 * @old_cset: the baseline css_set
1176 * @cgrp: the cgroup to be updated
1178 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1179 * substituted into the appropriate hierarchy.
1181 static struct css_set *find_css_set(struct css_set *old_cset,
1182 struct cgroup *cgrp)
1184 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1185 struct css_set *cset;
1186 struct list_head tmp_links;
1187 struct cgrp_cset_link *link;
1188 struct cgroup_subsys *ss;
1192 lockdep_assert_held(&cgroup_mutex);
1194 /* First see if we already have a cgroup group that matches
1195 * the desired set */
1196 spin_lock_irq(&css_set_lock);
1197 cset = find_existing_css_set(old_cset, cgrp, template);
1200 spin_unlock_irq(&css_set_lock);
1205 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1209 /* Allocate all the cgrp_cset_link objects that we'll need */
1210 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1215 refcount_set(&cset->refcount, 1);
1216 cset->dom_cset = cset;
1217 INIT_LIST_HEAD(&cset->tasks);
1218 INIT_LIST_HEAD(&cset->mg_tasks);
1219 INIT_LIST_HEAD(&cset->dying_tasks);
1220 INIT_LIST_HEAD(&cset->task_iters);
1221 INIT_LIST_HEAD(&cset->threaded_csets);
1222 INIT_HLIST_NODE(&cset->hlist);
1223 INIT_LIST_HEAD(&cset->cgrp_links);
1224 INIT_LIST_HEAD(&cset->mg_src_preload_node);
1225 INIT_LIST_HEAD(&cset->mg_dst_preload_node);
1226 INIT_LIST_HEAD(&cset->mg_node);
1228 /* Copy the set of subsystem state objects generated in
1229 * find_existing_css_set() */
1230 memcpy(cset->subsys, template, sizeof(cset->subsys));
1232 spin_lock_irq(&css_set_lock);
1233 /* Add reference counts and links from the new css_set. */
1234 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1235 struct cgroup *c = link->cgrp;
1237 if (c->root == cgrp->root)
1239 link_css_set(&tmp_links, cset, c);
1242 BUG_ON(!list_empty(&tmp_links));
1246 /* Add @cset to the hash table */
1247 key = css_set_hash(cset->subsys);
1248 hash_add(css_set_table, &cset->hlist, key);
1250 for_each_subsys(ss, ssid) {
1251 struct cgroup_subsys_state *css = cset->subsys[ssid];
1253 list_add_tail(&cset->e_cset_node[ssid],
1254 &css->cgroup->e_csets[ssid]);
1258 spin_unlock_irq(&css_set_lock);
1261 * If @cset should be threaded, look up the matching dom_cset and
1262 * link them up. We first fully initialize @cset then look for the
1263 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1264 * to stay empty until we return.
1266 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1267 struct css_set *dcset;
1269 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1275 spin_lock_irq(&css_set_lock);
1276 cset->dom_cset = dcset;
1277 list_add_tail(&cset->threaded_csets_node,
1278 &dcset->threaded_csets);
1279 spin_unlock_irq(&css_set_lock);
1285 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1287 struct cgroup *root_cgrp = kf_root->kn->priv;
1289 return root_cgrp->root;
1292 static int cgroup_init_root_id(struct cgroup_root *root)
1296 lockdep_assert_held(&cgroup_mutex);
1298 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1302 root->hierarchy_id = id;
1306 static void cgroup_exit_root_id(struct cgroup_root *root)
1308 lockdep_assert_held(&cgroup_mutex);
1310 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1313 void cgroup_free_root(struct cgroup_root *root)
1316 idr_destroy(&root->cgroup_idr);
1321 static void cgroup_destroy_root(struct cgroup_root *root)
1323 struct cgroup *cgrp = &root->cgrp;
1324 struct cgrp_cset_link *link, *tmp_link;
1326 trace_cgroup_destroy_root(root);
1328 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1330 BUG_ON(atomic_read(&root->nr_cgrps));
1331 BUG_ON(!list_empty(&cgrp->self.children));
1333 /* Rebind all subsystems back to the default hierarchy */
1334 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1337 * Release all the links from cset_links to this hierarchy's
1340 spin_lock_irq(&css_set_lock);
1342 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1343 list_del(&link->cset_link);
1344 list_del(&link->cgrp_link);
1348 spin_unlock_irq(&css_set_lock);
1350 if (!list_empty(&root->root_list)) {
1351 list_del(&root->root_list);
1352 cgroup_root_count--;
1355 cgroup_exit_root_id(root);
1357 mutex_unlock(&cgroup_mutex);
1359 kernfs_destroy_root(root->kf_root);
1360 cgroup_free_root(root);
1364 * look up cgroup associated with current task's cgroup namespace on the
1365 * specified hierarchy
1367 static struct cgroup *
1368 current_cgns_cgroup_from_root(struct cgroup_root *root)
1370 struct cgroup *res = NULL;
1371 struct css_set *cset;
1373 lockdep_assert_held(&css_set_lock);
1377 cset = current->nsproxy->cgroup_ns->root_cset;
1378 if (cset == &init_css_set) {
1381 struct cgrp_cset_link *link;
1383 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1384 struct cgroup *c = link->cgrp;
1386 if (c->root == root) {
1398 /* look up cgroup associated with given css_set on the specified hierarchy */
1399 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1400 struct cgroup_root *root)
1402 struct cgroup *res = NULL;
1404 lockdep_assert_held(&cgroup_mutex);
1405 lockdep_assert_held(&css_set_lock);
1407 if (cset == &init_css_set) {
1409 } else if (root == &cgrp_dfl_root) {
1410 res = cset->dfl_cgrp;
1412 struct cgrp_cset_link *link;
1414 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1415 struct cgroup *c = link->cgrp;
1417 if (c->root == root) {
1429 * Return the cgroup for "task" from the given hierarchy. Must be
1430 * called with cgroup_mutex and css_set_lock held.
1432 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1433 struct cgroup_root *root)
1436 * No need to lock the task - since we hold cgroup_mutex the
1437 * task can't change groups, so the only thing that can happen
1438 * is that it exits and its css is set back to init_css_set.
1440 return cset_cgroup_from_root(task_css_set(task), root);
1444 * A task must hold cgroup_mutex to modify cgroups.
1446 * Any task can increment and decrement the count field without lock.
1447 * So in general, code holding cgroup_mutex can't rely on the count
1448 * field not changing. However, if the count goes to zero, then only
1449 * cgroup_attach_task() can increment it again. Because a count of zero
1450 * means that no tasks are currently attached, therefore there is no
1451 * way a task attached to that cgroup can fork (the other way to
1452 * increment the count). So code holding cgroup_mutex can safely
1453 * assume that if the count is zero, it will stay zero. Similarly, if
1454 * a task holds cgroup_mutex on a cgroup with zero count, it
1455 * knows that the cgroup won't be removed, as cgroup_rmdir()
1458 * A cgroup can only be deleted if both its 'count' of using tasks
1459 * is zero, and its list of 'children' cgroups is empty. Since all
1460 * tasks in the system use _some_ cgroup, and since there is always at
1461 * least one task in the system (init, pid == 1), therefore, root cgroup
1462 * always has either children cgroups and/or using tasks. So we don't
1463 * need a special hack to ensure that root cgroup cannot be deleted.
1465 * P.S. One more locking exception. RCU is used to guard the
1466 * update of a tasks cgroup pointer by cgroup_attach_task()
1469 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1471 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1474 struct cgroup_subsys *ss = cft->ss;
1476 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1477 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
1478 const char *dbg = (cft->flags & CFTYPE_DEBUG) ? ".__DEBUG__." : "";
1480 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s%s.%s",
1481 dbg, cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1484 strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1490 * cgroup_file_mode - deduce file mode of a control file
1491 * @cft: the control file in question
1493 * S_IRUGO for read, S_IWUSR for write.
1495 static umode_t cgroup_file_mode(const struct cftype *cft)
1499 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1502 if (cft->write_u64 || cft->write_s64 || cft->write) {
1503 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1513 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1514 * @subtree_control: the new subtree_control mask to consider
1515 * @this_ss_mask: available subsystems
1517 * On the default hierarchy, a subsystem may request other subsystems to be
1518 * enabled together through its ->depends_on mask. In such cases, more
1519 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1521 * This function calculates which subsystems need to be enabled if
1522 * @subtree_control is to be applied while restricted to @this_ss_mask.
1524 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1526 u16 cur_ss_mask = subtree_control;
1527 struct cgroup_subsys *ss;
1530 lockdep_assert_held(&cgroup_mutex);
1532 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1535 u16 new_ss_mask = cur_ss_mask;
1537 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1538 new_ss_mask |= ss->depends_on;
1539 } while_each_subsys_mask();
1542 * Mask out subsystems which aren't available. This can
1543 * happen only if some depended-upon subsystems were bound
1544 * to non-default hierarchies.
1546 new_ss_mask &= this_ss_mask;
1548 if (new_ss_mask == cur_ss_mask)
1550 cur_ss_mask = new_ss_mask;
1557 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1558 * @kn: the kernfs_node being serviced
1560 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1561 * the method finishes if locking succeeded. Note that once this function
1562 * returns the cgroup returned by cgroup_kn_lock_live() may become
1563 * inaccessible any time. If the caller intends to continue to access the
1564 * cgroup, it should pin it before invoking this function.
1566 void cgroup_kn_unlock(struct kernfs_node *kn)
1568 struct cgroup *cgrp;
1570 if (kernfs_type(kn) == KERNFS_DIR)
1573 cgrp = kn->parent->priv;
1575 mutex_unlock(&cgroup_mutex);
1577 kernfs_unbreak_active_protection(kn);
1582 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1583 * @kn: the kernfs_node being serviced
1584 * @drain_offline: perform offline draining on the cgroup
1586 * This helper is to be used by a cgroup kernfs method currently servicing
1587 * @kn. It breaks the active protection, performs cgroup locking and
1588 * verifies that the associated cgroup is alive. Returns the cgroup if
1589 * alive; otherwise, %NULL. A successful return should be undone by a
1590 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1591 * cgroup is drained of offlining csses before return.
1593 * Any cgroup kernfs method implementation which requires locking the
1594 * associated cgroup should use this helper. It avoids nesting cgroup
1595 * locking under kernfs active protection and allows all kernfs operations
1596 * including self-removal.
1598 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1600 struct cgroup *cgrp;
1602 if (kernfs_type(kn) == KERNFS_DIR)
1605 cgrp = kn->parent->priv;
1608 * We're gonna grab cgroup_mutex which nests outside kernfs
1609 * active_ref. cgroup liveliness check alone provides enough
1610 * protection against removal. Ensure @cgrp stays accessible and
1611 * break the active_ref protection.
1613 if (!cgroup_tryget(cgrp))
1615 kernfs_break_active_protection(kn);
1618 cgroup_lock_and_drain_offline(cgrp);
1620 mutex_lock(&cgroup_mutex);
1622 if (!cgroup_is_dead(cgrp))
1625 cgroup_kn_unlock(kn);
1629 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1631 char name[CGROUP_FILE_NAME_MAX];
1633 lockdep_assert_held(&cgroup_mutex);
1635 if (cft->file_offset) {
1636 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1637 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1639 spin_lock_irq(&cgroup_file_kn_lock);
1641 spin_unlock_irq(&cgroup_file_kn_lock);
1643 del_timer_sync(&cfile->notify_timer);
1646 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1650 * css_clear_dir - remove subsys files in a cgroup directory
1653 static void css_clear_dir(struct cgroup_subsys_state *css)
1655 struct cgroup *cgrp = css->cgroup;
1656 struct cftype *cfts;
1658 if (!(css->flags & CSS_VISIBLE))
1661 css->flags &= ~CSS_VISIBLE;
1664 if (cgroup_on_dfl(cgrp))
1665 cfts = cgroup_base_files;
1667 cfts = cgroup1_base_files;
1669 cgroup_addrm_files(css, cgrp, cfts, false);
1671 list_for_each_entry(cfts, &css->ss->cfts, node)
1672 cgroup_addrm_files(css, cgrp, cfts, false);
1677 * css_populate_dir - create subsys files in a cgroup directory
1680 * On failure, no file is added.
1682 static int css_populate_dir(struct cgroup_subsys_state *css)
1684 struct cgroup *cgrp = css->cgroup;
1685 struct cftype *cfts, *failed_cfts;
1688 if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
1692 if (cgroup_on_dfl(cgrp))
1693 cfts = cgroup_base_files;
1695 cfts = cgroup1_base_files;
1697 ret = cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1701 list_for_each_entry(cfts, &css->ss->cfts, node) {
1702 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1710 css->flags |= CSS_VISIBLE;
1714 list_for_each_entry(cfts, &css->ss->cfts, node) {
1715 if (cfts == failed_cfts)
1717 cgroup_addrm_files(css, cgrp, cfts, false);
1722 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1724 struct cgroup *dcgrp = &dst_root->cgrp;
1725 struct cgroup_subsys *ss;
1727 u16 dfl_disable_ss_mask = 0;
1729 lockdep_assert_held(&cgroup_mutex);
1731 do_each_subsys_mask(ss, ssid, ss_mask) {
1733 * If @ss has non-root csses attached to it, can't move.
1734 * If @ss is an implicit controller, it is exempt from this
1735 * rule and can be stolen.
1737 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1738 !ss->implicit_on_dfl)
1741 /* can't move between two non-dummy roots either */
1742 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1746 * Collect ssid's that need to be disabled from default
1749 if (ss->root == &cgrp_dfl_root)
1750 dfl_disable_ss_mask |= 1 << ssid;
1752 } while_each_subsys_mask();
1754 if (dfl_disable_ss_mask) {
1755 struct cgroup *scgrp = &cgrp_dfl_root.cgrp;
1758 * Controllers from default hierarchy that need to be rebound
1759 * are all disabled together in one go.
1761 cgrp_dfl_root.subsys_mask &= ~dfl_disable_ss_mask;
1762 WARN_ON(cgroup_apply_control(scgrp));
1763 cgroup_finalize_control(scgrp, 0);
1766 do_each_subsys_mask(ss, ssid, ss_mask) {
1767 struct cgroup_root *src_root = ss->root;
1768 struct cgroup *scgrp = &src_root->cgrp;
1769 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1770 struct css_set *cset, *cset_pos;
1771 struct css_task_iter *it;
1773 WARN_ON(!css || cgroup_css(dcgrp, ss));
1775 if (src_root != &cgrp_dfl_root) {
1776 /* disable from the source */
1777 src_root->subsys_mask &= ~(1 << ssid);
1778 WARN_ON(cgroup_apply_control(scgrp));
1779 cgroup_finalize_control(scgrp, 0);
1783 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1784 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1785 ss->root = dst_root;
1786 css->cgroup = dcgrp;
1788 spin_lock_irq(&css_set_lock);
1789 WARN_ON(!list_empty(&dcgrp->e_csets[ss->id]));
1790 list_for_each_entry_safe(cset, cset_pos, &scgrp->e_csets[ss->id],
1791 e_cset_node[ss->id]) {
1792 list_move_tail(&cset->e_cset_node[ss->id],
1793 &dcgrp->e_csets[ss->id]);
1795 * all css_sets of scgrp together in same order to dcgrp,
1796 * patch in-flight iterators to preserve correct iteration.
1797 * since the iterator is always advanced right away and
1798 * finished when it->cset_pos meets it->cset_head, so only
1799 * update it->cset_head is enough here.
1801 list_for_each_entry(it, &cset->task_iters, iters_node)
1802 if (it->cset_head == &scgrp->e_csets[ss->id])
1803 it->cset_head = &dcgrp->e_csets[ss->id];
1805 spin_unlock_irq(&css_set_lock);
1807 /* default hierarchy doesn't enable controllers by default */
1808 dst_root->subsys_mask |= 1 << ssid;
1809 if (dst_root == &cgrp_dfl_root) {
1810 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1812 dcgrp->subtree_control |= 1 << ssid;
1813 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1816 ret = cgroup_apply_control(dcgrp);
1818 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1823 } while_each_subsys_mask();
1825 kernfs_activate(dcgrp->kn);
1829 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1830 struct kernfs_root *kf_root)
1834 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1835 struct cgroup *ns_cgroup;
1837 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1841 spin_lock_irq(&css_set_lock);
1842 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1843 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1844 spin_unlock_irq(&css_set_lock);
1846 if (len >= PATH_MAX)
1849 seq_escape(sf, buf, " \t\n\\");
1856 enum cgroup2_param {
1858 Opt_memory_localevents,
1862 static const struct fs_parameter_spec cgroup2_param_specs[] = {
1863 fsparam_flag("nsdelegate", Opt_nsdelegate),
1864 fsparam_flag("memory_localevents", Opt_memory_localevents),
1868 static const struct fs_parameter_description cgroup2_fs_parameters = {
1870 .specs = cgroup2_param_specs,
1873 static int cgroup2_parse_param(struct fs_context *fc, struct fs_parameter *param)
1875 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1876 struct fs_parse_result result;
1879 opt = fs_parse(fc, &cgroup2_fs_parameters, param, &result);
1884 case Opt_nsdelegate:
1885 ctx->flags |= CGRP_ROOT_NS_DELEGATE;
1887 case Opt_memory_localevents:
1888 ctx->flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1894 static void apply_cgroup_root_flags(unsigned int root_flags)
1896 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1897 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1898 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1900 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1902 if (root_flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
1903 cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1905 cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1909 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1911 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1912 seq_puts(seq, ",nsdelegate");
1913 if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
1914 seq_puts(seq, ",memory_localevents");
1918 static int cgroup_reconfigure(struct fs_context *fc)
1920 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1922 apply_cgroup_root_flags(ctx->flags);
1927 * To reduce the fork() overhead for systems that are not actually using
1928 * their cgroups capability, we don't maintain the lists running through
1929 * each css_set to its tasks until we see the list actually used - in other
1930 * words after the first mount.
1932 static bool use_task_css_set_links __read_mostly;
1934 void cgroup_enable_task_cg_lists(void)
1936 struct task_struct *p, *g;
1939 * We need tasklist_lock because RCU is not safe against
1940 * while_each_thread(). Besides, a forking task that has passed
1941 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1942 * is not guaranteed to have its child immediately visible in the
1943 * tasklist if we walk through it with RCU.
1945 read_lock(&tasklist_lock);
1946 spin_lock_irq(&css_set_lock);
1948 if (use_task_css_set_links)
1951 use_task_css_set_links = true;
1953 do_each_thread(g, p) {
1954 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1955 task_css_set(p) != &init_css_set);
1958 * We should check if the process is exiting, otherwise
1959 * it will race with cgroup_exit() in that the list
1960 * entry won't be deleted though the process has exited.
1961 * Do it while holding siglock so that we don't end up
1962 * racing against cgroup_exit().
1964 * Interrupts were already disabled while acquiring
1965 * the css_set_lock, so we do not need to disable it
1966 * again when acquiring the sighand->siglock here.
1968 spin_lock(&p->sighand->siglock);
1969 if (!(p->flags & PF_EXITING)) {
1970 struct css_set *cset = task_css_set(p);
1972 if (!css_set_populated(cset))
1973 css_set_update_populated(cset, true);
1974 list_add_tail(&p->cg_list, &cset->tasks);
1978 spin_unlock(&p->sighand->siglock);
1979 } while_each_thread(g, p);
1981 spin_unlock_irq(&css_set_lock);
1982 read_unlock(&tasklist_lock);
1985 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1987 struct cgroup_subsys *ss;
1990 INIT_LIST_HEAD(&cgrp->self.sibling);
1991 INIT_LIST_HEAD(&cgrp->self.children);
1992 INIT_LIST_HEAD(&cgrp->cset_links);
1993 INIT_LIST_HEAD(&cgrp->pidlists);
1994 mutex_init(&cgrp->pidlist_mutex);
1995 cgrp->self.cgroup = cgrp;
1996 cgrp->self.flags |= CSS_ONLINE;
1997 cgrp->dom_cgrp = cgrp;
1998 cgrp->max_descendants = INT_MAX;
1999 cgrp->max_depth = INT_MAX;
2000 INIT_LIST_HEAD(&cgrp->rstat_css_list);
2001 prev_cputime_init(&cgrp->prev_cputime);
2003 for_each_subsys(ss, ssid)
2004 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
2006 init_waitqueue_head(&cgrp->offline_waitq);
2007 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
2010 void init_cgroup_root(struct cgroup_fs_context *ctx)
2012 struct cgroup_root *root = ctx->root;
2013 struct cgroup *cgrp = &root->cgrp;
2015 INIT_LIST_HEAD(&root->root_list);
2016 atomic_set(&root->nr_cgrps, 1);
2018 init_cgroup_housekeeping(cgrp);
2019 idr_init(&root->cgroup_idr);
2021 root->flags = ctx->flags;
2022 if (ctx->release_agent)
2023 strscpy(root->release_agent_path, ctx->release_agent, PATH_MAX);
2025 strscpy(root->name, ctx->name, MAX_CGROUP_ROOT_NAMELEN);
2026 if (ctx->cpuset_clone_children)
2027 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
2030 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask)
2032 LIST_HEAD(tmp_links);
2033 struct cgroup *root_cgrp = &root->cgrp;
2034 struct kernfs_syscall_ops *kf_sops;
2035 struct css_set *cset;
2038 lockdep_assert_held(&cgroup_mutex);
2040 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
2043 root_cgrp->id = ret;
2044 root_cgrp->ancestor_ids[0] = ret;
2046 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
2052 * We're accessing css_set_count without locking css_set_lock here,
2053 * but that's OK - it can only be increased by someone holding
2054 * cgroup_lock, and that's us. Later rebinding may disable
2055 * controllers on the default hierarchy and thus create new csets,
2056 * which can't be more than the existing ones. Allocate 2x.
2058 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
2062 ret = cgroup_init_root_id(root);
2066 kf_sops = root == &cgrp_dfl_root ?
2067 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
2069 root->kf_root = kernfs_create_root(kf_sops,
2070 KERNFS_ROOT_CREATE_DEACTIVATED |
2071 KERNFS_ROOT_SUPPORT_EXPORTOP,
2073 if (IS_ERR(root->kf_root)) {
2074 ret = PTR_ERR(root->kf_root);
2077 root_cgrp->kn = root->kf_root->kn;
2079 ret = css_populate_dir(&root_cgrp->self);
2083 ret = rebind_subsystems(root, ss_mask);
2087 ret = cgroup_bpf_inherit(root_cgrp);
2090 trace_cgroup_setup_root(root);
2093 * There must be no failure case after here, since rebinding takes
2094 * care of subsystems' refcounts, which are explicitly dropped in
2095 * the failure exit path.
2097 list_add(&root->root_list, &cgroup_roots);
2098 cgroup_root_count++;
2101 * Link the root cgroup in this hierarchy into all the css_set
2104 spin_lock_irq(&css_set_lock);
2105 hash_for_each(css_set_table, i, cset, hlist) {
2106 link_css_set(&tmp_links, cset, root_cgrp);
2107 if (css_set_populated(cset))
2108 cgroup_update_populated(root_cgrp, true);
2110 spin_unlock_irq(&css_set_lock);
2112 BUG_ON(!list_empty(&root_cgrp->self.children));
2113 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
2115 kernfs_activate(root_cgrp->kn);
2120 kernfs_destroy_root(root->kf_root);
2121 root->kf_root = NULL;
2123 cgroup_exit_root_id(root);
2125 percpu_ref_exit(&root_cgrp->self.refcnt);
2127 free_cgrp_cset_links(&tmp_links);
2131 int cgroup_do_get_tree(struct fs_context *fc)
2133 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2136 ctx->kfc.root = ctx->root->kf_root;
2137 if (fc->fs_type == &cgroup2_fs_type)
2138 ctx->kfc.magic = CGROUP2_SUPER_MAGIC;
2140 ctx->kfc.magic = CGROUP_SUPER_MAGIC;
2141 ret = kernfs_get_tree(fc);
2144 * In non-init cgroup namespace, instead of root cgroup's dentry,
2145 * we return the dentry corresponding to the cgroupns->root_cgrp.
2147 if (!ret && ctx->ns != &init_cgroup_ns) {
2148 struct dentry *nsdentry;
2149 struct super_block *sb = fc->root->d_sb;
2150 struct cgroup *cgrp;
2152 mutex_lock(&cgroup_mutex);
2153 spin_lock_irq(&css_set_lock);
2155 cgrp = cset_cgroup_from_root(ctx->ns->root_cset, ctx->root);
2157 spin_unlock_irq(&css_set_lock);
2158 mutex_unlock(&cgroup_mutex);
2160 nsdentry = kernfs_node_dentry(cgrp->kn, sb);
2162 if (IS_ERR(nsdentry)) {
2163 deactivate_locked_super(sb);
2164 ret = PTR_ERR(nsdentry);
2167 fc->root = nsdentry;
2170 if (!ctx->kfc.new_sb_created)
2171 cgroup_put(&ctx->root->cgrp);
2177 * Destroy a cgroup filesystem context.
2179 static void cgroup_fs_context_free(struct fs_context *fc)
2181 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2184 kfree(ctx->release_agent);
2185 put_cgroup_ns(ctx->ns);
2186 kernfs_free_fs_context(fc);
2190 static int cgroup_get_tree(struct fs_context *fc)
2192 struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2195 cgrp_dfl_visible = true;
2196 cgroup_get_live(&cgrp_dfl_root.cgrp);
2197 ctx->root = &cgrp_dfl_root;
2199 ret = cgroup_do_get_tree(fc);
2201 apply_cgroup_root_flags(ctx->flags);
2205 static const struct fs_context_operations cgroup_fs_context_ops = {
2206 .free = cgroup_fs_context_free,
2207 .parse_param = cgroup2_parse_param,
2208 .get_tree = cgroup_get_tree,
2209 .reconfigure = cgroup_reconfigure,
2212 static const struct fs_context_operations cgroup1_fs_context_ops = {
2213 .free = cgroup_fs_context_free,
2214 .parse_param = cgroup1_parse_param,
2215 .get_tree = cgroup1_get_tree,
2216 .reconfigure = cgroup1_reconfigure,
2220 * Initialise the cgroup filesystem creation/reconfiguration context. Notably,
2221 * we select the namespace we're going to use.
2223 static int cgroup_init_fs_context(struct fs_context *fc)
2225 struct cgroup_fs_context *ctx;
2227 ctx = kzalloc(sizeof(struct cgroup_fs_context), GFP_KERNEL);
2232 * The first time anyone tries to mount a cgroup, enable the list
2233 * linking each css_set to its tasks and fix up all existing tasks.
2235 if (!use_task_css_set_links)
2236 cgroup_enable_task_cg_lists();
2238 ctx->ns = current->nsproxy->cgroup_ns;
2239 get_cgroup_ns(ctx->ns);
2240 fc->fs_private = &ctx->kfc;
2241 if (fc->fs_type == &cgroup2_fs_type)
2242 fc->ops = &cgroup_fs_context_ops;
2244 fc->ops = &cgroup1_fs_context_ops;
2245 put_user_ns(fc->user_ns);
2246 fc->user_ns = get_user_ns(ctx->ns->user_ns);
2251 static void cgroup_kill_sb(struct super_block *sb)
2253 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2254 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2257 * If @root doesn't have any children, start killing it.
2258 * This prevents new mounts by disabling percpu_ref_tryget_live().
2259 * cgroup_mount() may wait for @root's release.
2261 * And don't kill the default root.
2263 if (list_empty(&root->cgrp.self.children) && root != &cgrp_dfl_root &&
2264 !percpu_ref_is_dying(&root->cgrp.self.refcnt))
2265 percpu_ref_kill(&root->cgrp.self.refcnt);
2266 cgroup_put(&root->cgrp);
2270 struct file_system_type cgroup_fs_type = {
2272 .init_fs_context = cgroup_init_fs_context,
2273 .parameters = &cgroup1_fs_parameters,
2274 .kill_sb = cgroup_kill_sb,
2275 .fs_flags = FS_USERNS_MOUNT,
2278 static struct file_system_type cgroup2_fs_type = {
2280 .init_fs_context = cgroup_init_fs_context,
2281 .parameters = &cgroup2_fs_parameters,
2282 .kill_sb = cgroup_kill_sb,
2283 .fs_flags = FS_USERNS_MOUNT,
2286 #ifdef CONFIG_CPUSETS
2287 static const struct fs_context_operations cpuset_fs_context_ops = {
2288 .get_tree = cgroup1_get_tree,
2289 .free = cgroup_fs_context_free,
2293 * This is ugly, but preserves the userspace API for existing cpuset
2294 * users. If someone tries to mount the "cpuset" filesystem, we
2295 * silently switch it to mount "cgroup" instead
2297 static int cpuset_init_fs_context(struct fs_context *fc)
2299 char *agent = kstrdup("/sbin/cpuset_release_agent", GFP_USER);
2300 struct cgroup_fs_context *ctx;
2303 err = cgroup_init_fs_context(fc);
2309 fc->ops = &cpuset_fs_context_ops;
2311 ctx = cgroup_fc2context(fc);
2312 ctx->subsys_mask = 1 << cpuset_cgrp_id;
2313 ctx->flags |= CGRP_ROOT_NOPREFIX;
2314 ctx->release_agent = agent;
2316 get_filesystem(&cgroup_fs_type);
2317 put_filesystem(fc->fs_type);
2318 fc->fs_type = &cgroup_fs_type;
2323 static struct file_system_type cpuset_fs_type = {
2325 .init_fs_context = cpuset_init_fs_context,
2326 .fs_flags = FS_USERNS_MOUNT,
2330 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2331 struct cgroup_namespace *ns)
2333 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2335 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2338 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2339 struct cgroup_namespace *ns)
2343 mutex_lock(&cgroup_mutex);
2344 spin_lock_irq(&css_set_lock);
2346 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2348 spin_unlock_irq(&css_set_lock);
2349 mutex_unlock(&cgroup_mutex);
2353 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2356 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2357 * @task: target task
2358 * @buf: the buffer to write the path into
2359 * @buflen: the length of the buffer
2361 * Determine @task's cgroup on the first (the one with the lowest non-zero
2362 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2363 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2364 * cgroup controller callbacks.
2366 * Return value is the same as kernfs_path().
2368 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2370 struct cgroup_root *root;
2371 struct cgroup *cgrp;
2372 int hierarchy_id = 1;
2375 mutex_lock(&cgroup_mutex);
2376 spin_lock_irq(&css_set_lock);
2378 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2381 cgrp = task_cgroup_from_root(task, root);
2382 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2384 /* if no hierarchy exists, everyone is in "/" */
2385 ret = strlcpy(buf, "/", buflen);
2388 spin_unlock_irq(&css_set_lock);
2389 mutex_unlock(&cgroup_mutex);
2392 EXPORT_SYMBOL_GPL(task_cgroup_path);
2395 * cgroup_attach_lock - Lock for ->attach()
2396 * @lock_threadgroup: whether to down_write cgroup_threadgroup_rwsem
2398 * cgroup migration sometimes needs to stabilize threadgroups against forks and
2399 * exits by write-locking cgroup_threadgroup_rwsem. However, some ->attach()
2400 * implementations (e.g. cpuset), also need to disable CPU hotplug.
2401 * Unfortunately, letting ->attach() operations acquire cpus_read_lock() can
2402 * lead to deadlocks.
2404 * Bringing up a CPU may involve creating and destroying tasks which requires
2405 * read-locking threadgroup_rwsem, so threadgroup_rwsem nests inside
2406 * cpus_read_lock(). If we call an ->attach() which acquires the cpus lock while
2407 * write-locking threadgroup_rwsem, the locking order is reversed and we end up
2408 * waiting for an on-going CPU hotplug operation which in turn is waiting for
2409 * the threadgroup_rwsem to be released to create new tasks. For more details:
2411 * http://lkml.kernel.org/r/20220711174629.uehfmqegcwn2lqzu@wubuntu
2413 * Resolve the situation by always acquiring cpus_read_lock() before optionally
2414 * write-locking cgroup_threadgroup_rwsem. This allows ->attach() to assume that
2415 * CPU hotplug is disabled on entry.
2417 static void cgroup_attach_lock(bool lock_threadgroup)
2420 if (lock_threadgroup)
2421 percpu_down_write(&cgroup_threadgroup_rwsem);
2425 * cgroup_attach_unlock - Undo cgroup_attach_lock()
2426 * @lock_threadgroup: whether to up_write cgroup_threadgroup_rwsem
2428 static void cgroup_attach_unlock(bool lock_threadgroup)
2430 if (lock_threadgroup)
2431 percpu_up_write(&cgroup_threadgroup_rwsem);
2436 * cgroup_migrate_add_task - add a migration target task to a migration context
2437 * @task: target task
2438 * @mgctx: target migration context
2440 * Add @task, which is a migration target, to @mgctx->tset. This function
2441 * becomes noop if @task doesn't need to be migrated. @task's css_set
2442 * should have been added as a migration source and @task->cg_list will be
2443 * moved from the css_set's tasks list to mg_tasks one.
2445 static void cgroup_migrate_add_task(struct task_struct *task,
2446 struct cgroup_mgctx *mgctx)
2448 struct css_set *cset;
2450 lockdep_assert_held(&css_set_lock);
2452 /* @task either already exited or can't exit until the end */
2453 if (task->flags & PF_EXITING)
2456 /* leave @task alone if post_fork() hasn't linked it yet */
2457 if (list_empty(&task->cg_list))
2460 cset = task_css_set(task);
2461 if (!cset->mg_src_cgrp)
2464 mgctx->tset.nr_tasks++;
2466 list_move_tail(&task->cg_list, &cset->mg_tasks);
2467 if (list_empty(&cset->mg_node))
2468 list_add_tail(&cset->mg_node,
2469 &mgctx->tset.src_csets);
2470 if (list_empty(&cset->mg_dst_cset->mg_node))
2471 list_add_tail(&cset->mg_dst_cset->mg_node,
2472 &mgctx->tset.dst_csets);
2476 * cgroup_taskset_first - reset taskset and return the first task
2477 * @tset: taskset of interest
2478 * @dst_cssp: output variable for the destination css
2480 * @tset iteration is initialized and the first task is returned.
2482 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2483 struct cgroup_subsys_state **dst_cssp)
2485 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2486 tset->cur_task = NULL;
2488 return cgroup_taskset_next(tset, dst_cssp);
2492 * cgroup_taskset_next - iterate to the next task in taskset
2493 * @tset: taskset of interest
2494 * @dst_cssp: output variable for the destination css
2496 * Return the next task in @tset. Iteration must have been initialized
2497 * with cgroup_taskset_first().
2499 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2500 struct cgroup_subsys_state **dst_cssp)
2502 struct css_set *cset = tset->cur_cset;
2503 struct task_struct *task = tset->cur_task;
2505 while (&cset->mg_node != tset->csets) {
2507 task = list_first_entry(&cset->mg_tasks,
2508 struct task_struct, cg_list);
2510 task = list_next_entry(task, cg_list);
2512 if (&task->cg_list != &cset->mg_tasks) {
2513 tset->cur_cset = cset;
2514 tset->cur_task = task;
2517 * This function may be called both before and
2518 * after cgroup_taskset_migrate(). The two cases
2519 * can be distinguished by looking at whether @cset
2520 * has its ->mg_dst_cset set.
2522 if (cset->mg_dst_cset)
2523 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2525 *dst_cssp = cset->subsys[tset->ssid];
2530 cset = list_next_entry(cset, mg_node);
2538 * cgroup_taskset_migrate - migrate a taskset
2539 * @mgctx: migration context
2541 * Migrate tasks in @mgctx as setup by migration preparation functions.
2542 * This function fails iff one of the ->can_attach callbacks fails and
2543 * guarantees that either all or none of the tasks in @mgctx are migrated.
2544 * @mgctx is consumed regardless of success.
2546 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2548 struct cgroup_taskset *tset = &mgctx->tset;
2549 struct cgroup_subsys *ss;
2550 struct task_struct *task, *tmp_task;
2551 struct css_set *cset, *tmp_cset;
2552 int ssid, failed_ssid, ret;
2554 /* check that we can legitimately attach to the cgroup */
2555 if (tset->nr_tasks) {
2556 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2557 if (ss->can_attach) {
2559 ret = ss->can_attach(tset);
2562 goto out_cancel_attach;
2565 } while_each_subsys_mask();
2569 * Now that we're guaranteed success, proceed to move all tasks to
2570 * the new cgroup. There are no failure cases after here, so this
2571 * is the commit point.
2573 spin_lock_irq(&css_set_lock);
2574 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2575 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2576 struct css_set *from_cset = task_css_set(task);
2577 struct css_set *to_cset = cset->mg_dst_cset;
2579 get_css_set(to_cset);
2580 to_cset->nr_tasks++;
2581 css_set_move_task(task, from_cset, to_cset, true);
2582 from_cset->nr_tasks--;
2584 * If the source or destination cgroup is frozen,
2585 * the task might require to change its state.
2587 cgroup_freezer_migrate_task(task, from_cset->dfl_cgrp,
2589 put_css_set_locked(from_cset);
2593 spin_unlock_irq(&css_set_lock);
2596 * Migration is committed, all target tasks are now on dst_csets.
2597 * Nothing is sensitive to fork() after this point. Notify
2598 * controllers that migration is complete.
2600 tset->csets = &tset->dst_csets;
2602 if (tset->nr_tasks) {
2603 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2608 } while_each_subsys_mask();
2612 goto out_release_tset;
2615 if (tset->nr_tasks) {
2616 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2617 if (ssid == failed_ssid)
2619 if (ss->cancel_attach) {
2621 ss->cancel_attach(tset);
2623 } while_each_subsys_mask();
2626 spin_lock_irq(&css_set_lock);
2627 list_splice_init(&tset->dst_csets, &tset->src_csets);
2628 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2629 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2630 list_del_init(&cset->mg_node);
2632 spin_unlock_irq(&css_set_lock);
2635 * Re-initialize the cgroup_taskset structure in case it is reused
2636 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2640 tset->csets = &tset->src_csets;
2645 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2646 * @dst_cgrp: destination cgroup to test
2648 * On the default hierarchy, except for the mixable, (possible) thread root
2649 * and threaded cgroups, subtree_control must be zero for migration
2650 * destination cgroups with tasks so that child cgroups don't compete
2653 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2655 /* v1 doesn't have any restriction */
2656 if (!cgroup_on_dfl(dst_cgrp))
2659 /* verify @dst_cgrp can host resources */
2660 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2663 /* mixables don't care */
2664 if (cgroup_is_mixable(dst_cgrp))
2668 * If @dst_cgrp is already or can become a thread root or is
2669 * threaded, it doesn't matter.
2671 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2674 /* apply no-internal-process constraint */
2675 if (dst_cgrp->subtree_control)
2682 * cgroup_migrate_finish - cleanup after attach
2683 * @mgctx: migration context
2685 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2686 * those functions for details.
2688 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2690 struct css_set *cset, *tmp_cset;
2692 lockdep_assert_held(&cgroup_mutex);
2694 spin_lock_irq(&css_set_lock);
2696 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_src_csets,
2697 mg_src_preload_node) {
2698 cset->mg_src_cgrp = NULL;
2699 cset->mg_dst_cgrp = NULL;
2700 cset->mg_dst_cset = NULL;
2701 list_del_init(&cset->mg_src_preload_node);
2702 put_css_set_locked(cset);
2705 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_dst_csets,
2706 mg_dst_preload_node) {
2707 cset->mg_src_cgrp = NULL;
2708 cset->mg_dst_cgrp = NULL;
2709 cset->mg_dst_cset = NULL;
2710 list_del_init(&cset->mg_dst_preload_node);
2711 put_css_set_locked(cset);
2714 spin_unlock_irq(&css_set_lock);
2718 * cgroup_migrate_add_src - add a migration source css_set
2719 * @src_cset: the source css_set to add
2720 * @dst_cgrp: the destination cgroup
2721 * @mgctx: migration context
2723 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2724 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2725 * up by cgroup_migrate_finish().
2727 * This function may be called without holding cgroup_threadgroup_rwsem
2728 * even if the target is a process. Threads may be created and destroyed
2729 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2730 * into play and the preloaded css_sets are guaranteed to cover all
2733 void cgroup_migrate_add_src(struct css_set *src_cset,
2734 struct cgroup *dst_cgrp,
2735 struct cgroup_mgctx *mgctx)
2737 struct cgroup *src_cgrp;
2739 lockdep_assert_held(&cgroup_mutex);
2740 lockdep_assert_held(&css_set_lock);
2743 * If ->dead, @src_set is associated with one or more dead cgroups
2744 * and doesn't contain any migratable tasks. Ignore it early so
2745 * that the rest of migration path doesn't get confused by it.
2750 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2752 if (!list_empty(&src_cset->mg_src_preload_node))
2755 WARN_ON(src_cset->mg_src_cgrp);
2756 WARN_ON(src_cset->mg_dst_cgrp);
2757 WARN_ON(!list_empty(&src_cset->mg_tasks));
2758 WARN_ON(!list_empty(&src_cset->mg_node));
2760 src_cset->mg_src_cgrp = src_cgrp;
2761 src_cset->mg_dst_cgrp = dst_cgrp;
2762 get_css_set(src_cset);
2763 list_add_tail(&src_cset->mg_src_preload_node, &mgctx->preloaded_src_csets);
2767 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2768 * @mgctx: migration context
2770 * Tasks are about to be moved and all the source css_sets have been
2771 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2772 * pins all destination css_sets, links each to its source, and append them
2773 * to @mgctx->preloaded_dst_csets.
2775 * This function must be called after cgroup_migrate_add_src() has been
2776 * called on each migration source css_set. After migration is performed
2777 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2780 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2782 struct css_set *src_cset, *tmp_cset;
2784 lockdep_assert_held(&cgroup_mutex);
2786 /* look up the dst cset for each src cset and link it to src */
2787 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2788 mg_src_preload_node) {
2789 struct css_set *dst_cset;
2790 struct cgroup_subsys *ss;
2793 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2797 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2800 * If src cset equals dst, it's noop. Drop the src.
2801 * cgroup_migrate() will skip the cset too. Note that we
2802 * can't handle src == dst as some nodes are used by both.
2804 if (src_cset == dst_cset) {
2805 src_cset->mg_src_cgrp = NULL;
2806 src_cset->mg_dst_cgrp = NULL;
2807 list_del_init(&src_cset->mg_src_preload_node);
2808 put_css_set(src_cset);
2809 put_css_set(dst_cset);
2813 src_cset->mg_dst_cset = dst_cset;
2815 if (list_empty(&dst_cset->mg_dst_preload_node))
2816 list_add_tail(&dst_cset->mg_dst_preload_node,
2817 &mgctx->preloaded_dst_csets);
2819 put_css_set(dst_cset);
2821 for_each_subsys(ss, ssid)
2822 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2823 mgctx->ss_mask |= 1 << ssid;
2830 * cgroup_migrate - migrate a process or task to a cgroup
2831 * @leader: the leader of the process or the task to migrate
2832 * @threadgroup: whether @leader points to the whole process or a single task
2833 * @mgctx: migration context
2835 * Migrate a process or task denoted by @leader. If migrating a process,
2836 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2837 * responsible for invoking cgroup_migrate_add_src() and
2838 * cgroup_migrate_prepare_dst() on the targets before invoking this
2839 * function and following up with cgroup_migrate_finish().
2841 * As long as a controller's ->can_attach() doesn't fail, this function is
2842 * guaranteed to succeed. This means that, excluding ->can_attach()
2843 * failure, when migrating multiple targets, the success or failure can be
2844 * decided for all targets by invoking group_migrate_prepare_dst() before
2845 * actually starting migrating.
2847 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2848 struct cgroup_mgctx *mgctx)
2850 struct task_struct *task;
2853 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2854 * already PF_EXITING could be freed from underneath us unless we
2855 * take an rcu_read_lock.
2857 spin_lock_irq(&css_set_lock);
2861 cgroup_migrate_add_task(task, mgctx);
2864 } while_each_thread(leader, task);
2866 spin_unlock_irq(&css_set_lock);
2868 return cgroup_migrate_execute(mgctx);
2872 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2873 * @dst_cgrp: the cgroup to attach to
2874 * @leader: the task or the leader of the threadgroup to be attached
2875 * @threadgroup: attach the whole threadgroup?
2877 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2879 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2882 DEFINE_CGROUP_MGCTX(mgctx);
2883 struct task_struct *task;
2886 ret = cgroup_migrate_vet_dst(dst_cgrp);
2890 /* look up all src csets */
2891 spin_lock_irq(&css_set_lock);
2895 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2898 } while_each_thread(leader, task);
2900 spin_unlock_irq(&css_set_lock);
2902 /* prepare dst csets and commit */
2903 ret = cgroup_migrate_prepare_dst(&mgctx);
2905 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2907 cgroup_migrate_finish(&mgctx);
2910 TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
2915 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup,
2916 bool *threadgroup_locked)
2918 struct task_struct *tsk;
2921 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2922 return ERR_PTR(-EINVAL);
2925 * If we migrate a single thread, we don't care about threadgroup
2926 * stability. If the thread is `current`, it won't exit(2) under our
2927 * hands or change PID through exec(2). We exclude
2928 * cgroup_update_dfl_csses and other cgroup_{proc,thread}s_write
2929 * callers by cgroup_mutex.
2930 * Therefore, we can skip the global lock.
2932 lockdep_assert_held(&cgroup_mutex);
2933 *threadgroup_locked = pid || threadgroup;
2934 cgroup_attach_lock(*threadgroup_locked);
2938 tsk = find_task_by_vpid(pid);
2940 tsk = ERR_PTR(-ESRCH);
2941 goto out_unlock_threadgroup;
2948 tsk = tsk->group_leader;
2951 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2952 * If userland migrates such a kthread to a non-root cgroup, it can
2953 * become trapped in a cpuset, or RT kthread may be born in a
2954 * cgroup with no rt_runtime allocated. Just say no.
2956 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2957 tsk = ERR_PTR(-EINVAL);
2958 goto out_unlock_threadgroup;
2961 get_task_struct(tsk);
2962 goto out_unlock_rcu;
2964 out_unlock_threadgroup:
2965 cgroup_attach_unlock(*threadgroup_locked);
2966 *threadgroup_locked = false;
2972 void cgroup_procs_write_finish(struct task_struct *task, bool threadgroup_locked)
2974 struct cgroup_subsys *ss;
2977 /* release reference from cgroup_procs_write_start() */
2978 put_task_struct(task);
2980 cgroup_attach_unlock(threadgroup_locked);
2982 for_each_subsys(ss, ssid)
2983 if (ss->post_attach)
2987 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2989 struct cgroup_subsys *ss;
2990 bool printed = false;
2993 do_each_subsys_mask(ss, ssid, ss_mask) {
2996 seq_puts(seq, ss->name);
2998 } while_each_subsys_mask();
3000 seq_putc(seq, '\n');
3003 /* show controllers which are enabled from the parent */
3004 static int cgroup_controllers_show(struct seq_file *seq, void *v)
3006 struct cgroup *cgrp = seq_css(seq)->cgroup;
3008 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
3012 /* show controllers which are enabled for a given cgroup's children */
3013 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
3015 struct cgroup *cgrp = seq_css(seq)->cgroup;
3017 cgroup_print_ss_mask(seq, cgrp->subtree_control);
3022 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
3023 * @cgrp: root of the subtree to update csses for
3025 * @cgrp's control masks have changed and its subtree's css associations
3026 * need to be updated accordingly. This function looks up all css_sets
3027 * which are attached to the subtree, creates the matching updated css_sets
3028 * and migrates the tasks to the new ones.
3030 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
3032 DEFINE_CGROUP_MGCTX(mgctx);
3033 struct cgroup_subsys_state *d_css;
3034 struct cgroup *dsct;
3035 struct css_set *src_cset;
3039 lockdep_assert_held(&cgroup_mutex);
3041 /* look up all csses currently attached to @cgrp's subtree */
3042 spin_lock_irq(&css_set_lock);
3043 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3044 struct cgrp_cset_link *link;
3046 list_for_each_entry(link, &dsct->cset_links, cset_link)
3047 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
3049 spin_unlock_irq(&css_set_lock);
3052 * We need to write-lock threadgroup_rwsem while migrating tasks.
3053 * However, if there are no source csets for @cgrp, changing its
3054 * controllers isn't gonna produce any task migrations and the
3055 * write-locking can be skipped safely.
3057 has_tasks = !list_empty(&mgctx.preloaded_src_csets);
3058 cgroup_attach_lock(has_tasks);
3060 /* NULL dst indicates self on default hierarchy */
3061 ret = cgroup_migrate_prepare_dst(&mgctx);
3065 spin_lock_irq(&css_set_lock);
3066 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets,
3067 mg_src_preload_node) {
3068 struct task_struct *task, *ntask;
3070 /* all tasks in src_csets need to be migrated */
3071 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
3072 cgroup_migrate_add_task(task, &mgctx);
3074 spin_unlock_irq(&css_set_lock);
3076 ret = cgroup_migrate_execute(&mgctx);
3078 cgroup_migrate_finish(&mgctx);
3079 cgroup_attach_unlock(has_tasks);
3084 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
3085 * @cgrp: root of the target subtree
3087 * Because css offlining is asynchronous, userland may try to re-enable a
3088 * controller while the previous css is still around. This function grabs
3089 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
3091 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
3092 __acquires(&cgroup_mutex)
3094 struct cgroup *dsct;
3095 struct cgroup_subsys_state *d_css;
3096 struct cgroup_subsys *ss;
3100 mutex_lock(&cgroup_mutex);
3102 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3103 for_each_subsys(ss, ssid) {
3104 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3107 if (!css || !percpu_ref_is_dying(&css->refcnt))
3110 cgroup_get_live(dsct);
3111 prepare_to_wait(&dsct->offline_waitq, &wait,
3112 TASK_UNINTERRUPTIBLE);
3114 mutex_unlock(&cgroup_mutex);
3116 finish_wait(&dsct->offline_waitq, &wait);
3125 * cgroup_save_control - save control masks and dom_cgrp of a subtree
3126 * @cgrp: root of the target subtree
3128 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
3129 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3132 static void cgroup_save_control(struct cgroup *cgrp)
3134 struct cgroup *dsct;
3135 struct cgroup_subsys_state *d_css;
3137 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3138 dsct->old_subtree_control = dsct->subtree_control;
3139 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
3140 dsct->old_dom_cgrp = dsct->dom_cgrp;
3145 * cgroup_propagate_control - refresh control masks of a subtree
3146 * @cgrp: root of the target subtree
3148 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
3149 * ->subtree_control and propagate controller availability through the
3150 * subtree so that descendants don't have unavailable controllers enabled.
3152 static void cgroup_propagate_control(struct cgroup *cgrp)
3154 struct cgroup *dsct;
3155 struct cgroup_subsys_state *d_css;
3157 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3158 dsct->subtree_control &= cgroup_control(dsct);
3159 dsct->subtree_ss_mask =
3160 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
3161 cgroup_ss_mask(dsct));
3166 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
3167 * @cgrp: root of the target subtree
3169 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
3170 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3173 static void cgroup_restore_control(struct cgroup *cgrp)
3175 struct cgroup *dsct;
3176 struct cgroup_subsys_state *d_css;
3178 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3179 dsct->subtree_control = dsct->old_subtree_control;
3180 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
3181 dsct->dom_cgrp = dsct->old_dom_cgrp;
3185 static bool css_visible(struct cgroup_subsys_state *css)
3187 struct cgroup_subsys *ss = css->ss;
3188 struct cgroup *cgrp = css->cgroup;
3190 if (cgroup_control(cgrp) & (1 << ss->id))
3192 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
3194 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
3198 * cgroup_apply_control_enable - enable or show csses according to control
3199 * @cgrp: root of the target subtree
3201 * Walk @cgrp's subtree and create new csses or make the existing ones
3202 * visible. A css is created invisible if it's being implicitly enabled
3203 * through dependency. An invisible css is made visible when the userland
3204 * explicitly enables it.
3206 * Returns 0 on success, -errno on failure. On failure, csses which have
3207 * been processed already aren't cleaned up. The caller is responsible for
3208 * cleaning up with cgroup_apply_control_disable().
3210 static int cgroup_apply_control_enable(struct cgroup *cgrp)
3212 struct cgroup *dsct;
3213 struct cgroup_subsys_state *d_css;
3214 struct cgroup_subsys *ss;
3217 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3218 for_each_subsys(ss, ssid) {
3219 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3221 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
3225 css = css_create(dsct, ss);
3227 return PTR_ERR(css);
3230 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3232 if (css_visible(css)) {
3233 ret = css_populate_dir(css);
3244 * cgroup_apply_control_disable - kill or hide csses according to control
3245 * @cgrp: root of the target subtree
3247 * Walk @cgrp's subtree and kill and hide csses so that they match
3248 * cgroup_ss_mask() and cgroup_visible_mask().
3250 * A css is hidden when the userland requests it to be disabled while other
3251 * subsystems are still depending on it. The css must not actively control
3252 * resources and be in the vanilla state if it's made visible again later.
3253 * Controllers which may be depended upon should provide ->css_reset() for
3256 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3258 struct cgroup *dsct;
3259 struct cgroup_subsys_state *d_css;
3260 struct cgroup_subsys *ss;
3263 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3264 for_each_subsys(ss, ssid) {
3265 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3270 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3273 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3275 } else if (!css_visible(css)) {
3285 * cgroup_apply_control - apply control mask updates to the subtree
3286 * @cgrp: root of the target subtree
3288 * subsystems can be enabled and disabled in a subtree using the following
3291 * 1. Call cgroup_save_control() to stash the current state.
3292 * 2. Update ->subtree_control masks in the subtree as desired.
3293 * 3. Call cgroup_apply_control() to apply the changes.
3294 * 4. Optionally perform other related operations.
3295 * 5. Call cgroup_finalize_control() to finish up.
3297 * This function implements step 3 and propagates the mask changes
3298 * throughout @cgrp's subtree, updates csses accordingly and perform
3299 * process migrations.
3301 static int cgroup_apply_control(struct cgroup *cgrp)
3305 cgroup_propagate_control(cgrp);
3307 ret = cgroup_apply_control_enable(cgrp);
3312 * At this point, cgroup_e_css_by_mask() results reflect the new csses
3313 * making the following cgroup_update_dfl_csses() properly update
3314 * css associations of all tasks in the subtree.
3316 ret = cgroup_update_dfl_csses(cgrp);
3324 * cgroup_finalize_control - finalize control mask update
3325 * @cgrp: root of the target subtree
3326 * @ret: the result of the update
3328 * Finalize control mask update. See cgroup_apply_control() for more info.
3330 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3333 cgroup_restore_control(cgrp);
3334 cgroup_propagate_control(cgrp);
3337 cgroup_apply_control_disable(cgrp);
3340 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3342 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3344 /* if nothing is getting enabled, nothing to worry about */
3348 /* can @cgrp host any resources? */
3349 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3352 /* mixables don't care */
3353 if (cgroup_is_mixable(cgrp))
3356 if (domain_enable) {
3357 /* can't enable domain controllers inside a thread subtree */
3358 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3362 * Threaded controllers can handle internal competitions
3363 * and are always allowed inside a (prospective) thread
3366 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3371 * Controllers can't be enabled for a cgroup with tasks to avoid
3372 * child cgroups competing against tasks.
3374 if (cgroup_has_tasks(cgrp))
3380 /* change the enabled child controllers for a cgroup in the default hierarchy */
3381 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3382 char *buf, size_t nbytes,
3385 u16 enable = 0, disable = 0;
3386 struct cgroup *cgrp, *child;
3387 struct cgroup_subsys *ss;
3392 * Parse input - space separated list of subsystem names prefixed
3393 * with either + or -.
3395 buf = strstrip(buf);
3396 while ((tok = strsep(&buf, " "))) {
3399 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3400 if (!cgroup_ssid_enabled(ssid) ||
3401 strcmp(tok + 1, ss->name))
3405 enable |= 1 << ssid;
3406 disable &= ~(1 << ssid);
3407 } else if (*tok == '-') {
3408 disable |= 1 << ssid;
3409 enable &= ~(1 << ssid);
3414 } while_each_subsys_mask();
3415 if (ssid == CGROUP_SUBSYS_COUNT)
3419 cgrp = cgroup_kn_lock_live(of->kn, true);
3423 for_each_subsys(ss, ssid) {
3424 if (enable & (1 << ssid)) {
3425 if (cgrp->subtree_control & (1 << ssid)) {
3426 enable &= ~(1 << ssid);
3430 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3434 } else if (disable & (1 << ssid)) {
3435 if (!(cgrp->subtree_control & (1 << ssid))) {
3436 disable &= ~(1 << ssid);
3440 /* a child has it enabled? */
3441 cgroup_for_each_live_child(child, cgrp) {
3442 if (child->subtree_control & (1 << ssid)) {
3450 if (!enable && !disable) {
3455 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3459 /* save and update control masks and prepare csses */
3460 cgroup_save_control(cgrp);
3462 cgrp->subtree_control |= enable;
3463 cgrp->subtree_control &= ~disable;
3465 ret = cgroup_apply_control(cgrp);
3466 cgroup_finalize_control(cgrp, ret);
3470 kernfs_activate(cgrp->kn);
3472 cgroup_kn_unlock(of->kn);
3473 return ret ?: nbytes;
3477 * cgroup_enable_threaded - make @cgrp threaded
3478 * @cgrp: the target cgroup
3480 * Called when "threaded" is written to the cgroup.type interface file and
3481 * tries to make @cgrp threaded and join the parent's resource domain.
3482 * This function is never called on the root cgroup as cgroup.type doesn't
3485 static int cgroup_enable_threaded(struct cgroup *cgrp)
3487 struct cgroup *parent = cgroup_parent(cgrp);
3488 struct cgroup *dom_cgrp = parent->dom_cgrp;
3489 struct cgroup *dsct;
3490 struct cgroup_subsys_state *d_css;
3493 lockdep_assert_held(&cgroup_mutex);
3495 /* noop if already threaded */
3496 if (cgroup_is_threaded(cgrp))
3500 * If @cgroup is populated or has domain controllers enabled, it
3501 * can't be switched. While the below cgroup_can_be_thread_root()
3502 * test can catch the same conditions, that's only when @parent is
3503 * not mixable, so let's check it explicitly.
3505 if (cgroup_is_populated(cgrp) ||
3506 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3509 /* we're joining the parent's domain, ensure its validity */
3510 if (!cgroup_is_valid_domain(dom_cgrp) ||
3511 !cgroup_can_be_thread_root(dom_cgrp))
3515 * The following shouldn't cause actual migrations and should
3518 cgroup_save_control(cgrp);
3520 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3521 if (dsct == cgrp || cgroup_is_threaded(dsct))
3522 dsct->dom_cgrp = dom_cgrp;
3524 ret = cgroup_apply_control(cgrp);
3526 parent->nr_threaded_children++;
3528 cgroup_finalize_control(cgrp, ret);
3532 static int cgroup_type_show(struct seq_file *seq, void *v)
3534 struct cgroup *cgrp = seq_css(seq)->cgroup;
3536 if (cgroup_is_threaded(cgrp))
3537 seq_puts(seq, "threaded\n");
3538 else if (!cgroup_is_valid_domain(cgrp))
3539 seq_puts(seq, "domain invalid\n");
3540 else if (cgroup_is_thread_root(cgrp))
3541 seq_puts(seq, "domain threaded\n");
3543 seq_puts(seq, "domain\n");
3548 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3549 size_t nbytes, loff_t off)
3551 struct cgroup *cgrp;
3554 /* only switching to threaded mode is supported */
3555 if (strcmp(strstrip(buf), "threaded"))
3558 /* drain dying csses before we re-apply (threaded) subtree control */
3559 cgrp = cgroup_kn_lock_live(of->kn, true);
3563 /* threaded can only be enabled */
3564 ret = cgroup_enable_threaded(cgrp);
3566 cgroup_kn_unlock(of->kn);
3567 return ret ?: nbytes;
3570 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3572 struct cgroup *cgrp = seq_css(seq)->cgroup;
3573 int descendants = READ_ONCE(cgrp->max_descendants);
3575 if (descendants == INT_MAX)
3576 seq_puts(seq, "max\n");
3578 seq_printf(seq, "%d\n", descendants);
3583 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3584 char *buf, size_t nbytes, loff_t off)
3586 struct cgroup *cgrp;
3590 buf = strstrip(buf);
3591 if (!strcmp(buf, "max")) {
3592 descendants = INT_MAX;
3594 ret = kstrtoint(buf, 0, &descendants);
3599 if (descendants < 0)
3602 cgrp = cgroup_kn_lock_live(of->kn, false);
3606 cgrp->max_descendants = descendants;
3608 cgroup_kn_unlock(of->kn);
3613 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3615 struct cgroup *cgrp = seq_css(seq)->cgroup;
3616 int depth = READ_ONCE(cgrp->max_depth);
3618 if (depth == INT_MAX)
3619 seq_puts(seq, "max\n");
3621 seq_printf(seq, "%d\n", depth);
3626 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3627 char *buf, size_t nbytes, loff_t off)
3629 struct cgroup *cgrp;
3633 buf = strstrip(buf);
3634 if (!strcmp(buf, "max")) {
3637 ret = kstrtoint(buf, 0, &depth);
3645 cgrp = cgroup_kn_lock_live(of->kn, false);
3649 cgrp->max_depth = depth;
3651 cgroup_kn_unlock(of->kn);
3656 static int cgroup_events_show(struct seq_file *seq, void *v)
3658 struct cgroup *cgrp = seq_css(seq)->cgroup;
3660 seq_printf(seq, "populated %d\n", cgroup_is_populated(cgrp));
3661 seq_printf(seq, "frozen %d\n", test_bit(CGRP_FROZEN, &cgrp->flags));
3666 static int cgroup_stat_show(struct seq_file *seq, void *v)
3668 struct cgroup *cgroup = seq_css(seq)->cgroup;
3670 seq_printf(seq, "nr_descendants %d\n",
3671 cgroup->nr_descendants);
3672 seq_printf(seq, "nr_dying_descendants %d\n",
3673 cgroup->nr_dying_descendants);
3678 static int __maybe_unused cgroup_extra_stat_show(struct seq_file *seq,
3679 struct cgroup *cgrp, int ssid)
3681 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3682 struct cgroup_subsys_state *css;
3685 if (!ss->css_extra_stat_show)
3688 css = cgroup_tryget_css(cgrp, ss);
3692 ret = ss->css_extra_stat_show(seq, css);
3697 static int cpu_stat_show(struct seq_file *seq, void *v)
3699 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3702 cgroup_base_stat_cputime_show(seq);
3703 #ifdef CONFIG_CGROUP_SCHED
3704 ret = cgroup_extra_stat_show(seq, cgrp, cpu_cgrp_id);
3710 static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
3712 struct cgroup *cgroup = seq_css(seq)->cgroup;
3713 struct psi_group *psi = cgroup->id == 1 ? &psi_system : &cgroup->psi;
3715 return psi_show(seq, psi, PSI_IO);
3717 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
3719 struct cgroup *cgroup = seq_css(seq)->cgroup;
3720 struct psi_group *psi = cgroup->id == 1 ? &psi_system : &cgroup->psi;
3722 return psi_show(seq, psi, PSI_MEM);
3724 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
3726 struct cgroup *cgroup = seq_css(seq)->cgroup;
3727 struct psi_group *psi = cgroup->id == 1 ? &psi_system : &cgroup->psi;
3729 return psi_show(seq, psi, PSI_CPU);
3732 static ssize_t cgroup_pressure_write(struct kernfs_open_file *of, char *buf,
3733 size_t nbytes, enum psi_res res)
3735 struct cgroup_file_ctx *ctx = of->priv;
3736 struct psi_trigger *new;
3737 struct cgroup *cgrp;
3738 struct psi_group *psi;
3740 cgrp = cgroup_kn_lock_live(of->kn, false);
3745 cgroup_kn_unlock(of->kn);
3747 /* Allow only one trigger per file descriptor */
3748 if (ctx->psi.trigger) {
3753 psi = cgroup_ino(cgrp) == 1 ? &psi_system : &cgrp->psi;
3754 new = psi_trigger_create(psi, buf, nbytes, res);
3757 return PTR_ERR(new);
3760 smp_store_release(&ctx->psi.trigger, new);
3766 static ssize_t cgroup_io_pressure_write(struct kernfs_open_file *of,
3767 char *buf, size_t nbytes,
3770 return cgroup_pressure_write(of, buf, nbytes, PSI_IO);
3773 static ssize_t cgroup_memory_pressure_write(struct kernfs_open_file *of,
3774 char *buf, size_t nbytes,
3777 return cgroup_pressure_write(of, buf, nbytes, PSI_MEM);
3780 static ssize_t cgroup_cpu_pressure_write(struct kernfs_open_file *of,
3781 char *buf, size_t nbytes,
3784 return cgroup_pressure_write(of, buf, nbytes, PSI_CPU);
3787 static __poll_t cgroup_pressure_poll(struct kernfs_open_file *of,
3790 struct cgroup_file_ctx *ctx = of->priv;
3791 return psi_trigger_poll(&ctx->psi.trigger, of->file, pt);
3794 static void cgroup_pressure_release(struct kernfs_open_file *of)
3796 struct cgroup_file_ctx *ctx = of->priv;
3798 psi_trigger_destroy(ctx->psi.trigger);
3800 #endif /* CONFIG_PSI */
3802 static int cgroup_freeze_show(struct seq_file *seq, void *v)
3804 struct cgroup *cgrp = seq_css(seq)->cgroup;
3806 seq_printf(seq, "%d\n", cgrp->freezer.freeze);
3811 static ssize_t cgroup_freeze_write(struct kernfs_open_file *of,
3812 char *buf, size_t nbytes, loff_t off)
3814 struct cgroup *cgrp;
3818 ret = kstrtoint(strstrip(buf), 0, &freeze);
3822 if (freeze < 0 || freeze > 1)
3825 cgrp = cgroup_kn_lock_live(of->kn, false);
3829 cgroup_freeze(cgrp, freeze);
3831 cgroup_kn_unlock(of->kn);
3836 static int cgroup_file_open(struct kernfs_open_file *of)
3838 struct cftype *cft = of->kn->priv;
3839 struct cgroup_file_ctx *ctx;
3842 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3846 ctx->ns = current->nsproxy->cgroup_ns;
3847 get_cgroup_ns(ctx->ns);
3853 ret = cft->open(of);
3855 put_cgroup_ns(ctx->ns);
3861 static void cgroup_file_release(struct kernfs_open_file *of)
3863 struct cftype *cft = of->kn->priv;
3864 struct cgroup_file_ctx *ctx = of->priv;
3868 put_cgroup_ns(ctx->ns);
3872 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3873 size_t nbytes, loff_t off)
3875 struct cgroup_file_ctx *ctx = of->priv;
3876 struct cgroup *cgrp = of->kn->parent->priv;
3877 struct cftype *cft = of->kn->priv;
3878 struct cgroup_subsys_state *css;
3882 * If namespaces are delegation boundaries, disallow writes to
3883 * files in an non-init namespace root from inside the namespace
3884 * except for the files explicitly marked delegatable -
3885 * cgroup.procs and cgroup.subtree_control.
3887 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3888 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3889 ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
3893 return cft->write(of, buf, nbytes, off);
3896 * kernfs guarantees that a file isn't deleted with operations in
3897 * flight, which means that the matching css is and stays alive and
3898 * doesn't need to be pinned. The RCU locking is not necessary
3899 * either. It's just for the convenience of using cgroup_css().
3902 css = cgroup_css(cgrp, cft->ss);
3905 if (cft->write_u64) {
3906 unsigned long long v;
3907 ret = kstrtoull(buf, 0, &v);
3909 ret = cft->write_u64(css, cft, v);
3910 } else if (cft->write_s64) {
3912 ret = kstrtoll(buf, 0, &v);
3914 ret = cft->write_s64(css, cft, v);
3919 return ret ?: nbytes;
3922 static __poll_t cgroup_file_poll(struct kernfs_open_file *of, poll_table *pt)
3924 struct cftype *cft = of->kn->priv;
3927 return cft->poll(of, pt);
3929 return kernfs_generic_poll(of, pt);
3932 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3934 return seq_cft(seq)->seq_start(seq, ppos);
3937 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3939 return seq_cft(seq)->seq_next(seq, v, ppos);
3942 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3944 if (seq_cft(seq)->seq_stop)
3945 seq_cft(seq)->seq_stop(seq, v);
3948 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3950 struct cftype *cft = seq_cft(m);
3951 struct cgroup_subsys_state *css = seq_css(m);
3954 return cft->seq_show(m, arg);
3957 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3958 else if (cft->read_s64)
3959 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3965 static struct kernfs_ops cgroup_kf_single_ops = {
3966 .atomic_write_len = PAGE_SIZE,
3967 .open = cgroup_file_open,
3968 .release = cgroup_file_release,
3969 .write = cgroup_file_write,
3970 .poll = cgroup_file_poll,
3971 .seq_show = cgroup_seqfile_show,
3974 static struct kernfs_ops cgroup_kf_ops = {
3975 .atomic_write_len = PAGE_SIZE,
3976 .open = cgroup_file_open,
3977 .release = cgroup_file_release,
3978 .write = cgroup_file_write,
3979 .poll = cgroup_file_poll,
3980 .seq_start = cgroup_seqfile_start,
3981 .seq_next = cgroup_seqfile_next,
3982 .seq_stop = cgroup_seqfile_stop,
3983 .seq_show = cgroup_seqfile_show,
3986 /* set uid and gid of cgroup dirs and files to that of the creator */
3987 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3989 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3990 .ia_uid = current_fsuid(),
3991 .ia_gid = current_fsgid(), };
3993 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3994 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3997 return kernfs_setattr(kn, &iattr);
4000 static void cgroup_file_notify_timer(struct timer_list *timer)
4002 cgroup_file_notify(container_of(timer, struct cgroup_file,
4006 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
4009 char name[CGROUP_FILE_NAME_MAX];
4010 struct kernfs_node *kn;
4011 struct lock_class_key *key = NULL;
4014 #ifdef CONFIG_DEBUG_LOCK_ALLOC
4015 key = &cft->lockdep_key;
4017 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
4018 cgroup_file_mode(cft),
4019 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
4020 0, cft->kf_ops, cft,
4025 ret = cgroup_kn_set_ugid(kn);
4031 if (cft->file_offset) {
4032 struct cgroup_file *cfile = (void *)css + cft->file_offset;
4034 timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
4036 spin_lock_irq(&cgroup_file_kn_lock);
4038 spin_unlock_irq(&cgroup_file_kn_lock);
4045 * cgroup_addrm_files - add or remove files to a cgroup directory
4046 * @css: the target css
4047 * @cgrp: the target cgroup (usually css->cgroup)
4048 * @cfts: array of cftypes to be added
4049 * @is_add: whether to add or remove
4051 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
4052 * For removals, this function never fails.
4054 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
4055 struct cgroup *cgrp, struct cftype cfts[],
4058 struct cftype *cft, *cft_end = NULL;
4061 lockdep_assert_held(&cgroup_mutex);
4064 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
4065 /* does cft->flags tell us to skip this file on @cgrp? */
4066 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
4068 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
4070 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
4072 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
4074 if ((cft->flags & CFTYPE_DEBUG) && !cgroup_debug)
4077 ret = cgroup_add_file(css, cgrp, cft);
4079 pr_warn("%s: failed to add %s, err=%d\n",
4080 __func__, cft->name, ret);
4086 cgroup_rm_file(cgrp, cft);
4092 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
4094 struct cgroup_subsys *ss = cfts[0].ss;
4095 struct cgroup *root = &ss->root->cgrp;
4096 struct cgroup_subsys_state *css;
4099 lockdep_assert_held(&cgroup_mutex);
4101 /* add/rm files for all cgroups created before */
4102 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
4103 struct cgroup *cgrp = css->cgroup;
4105 if (!(css->flags & CSS_VISIBLE))
4108 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
4114 kernfs_activate(root->kn);
4118 static void cgroup_exit_cftypes(struct cftype *cfts)
4122 for (cft = cfts; cft->name[0] != '\0'; cft++) {
4123 /* free copy for custom atomic_write_len, see init_cftypes() */
4124 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
4129 /* revert flags set by cgroup core while adding @cfts */
4130 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
4134 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4138 for (cft = cfts; cft->name[0] != '\0'; cft++) {
4139 struct kernfs_ops *kf_ops;
4141 WARN_ON(cft->ss || cft->kf_ops);
4144 kf_ops = &cgroup_kf_ops;
4146 kf_ops = &cgroup_kf_single_ops;
4149 * Ugh... if @cft wants a custom max_write_len, we need to
4150 * make a copy of kf_ops to set its atomic_write_len.
4152 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
4153 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
4155 cgroup_exit_cftypes(cfts);
4158 kf_ops->atomic_write_len = cft->max_write_len;
4161 cft->kf_ops = kf_ops;
4168 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
4170 lockdep_assert_held(&cgroup_mutex);
4172 if (!cfts || !cfts[0].ss)
4175 list_del(&cfts->node);
4176 cgroup_apply_cftypes(cfts, false);
4177 cgroup_exit_cftypes(cfts);
4182 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
4183 * @cfts: zero-length name terminated array of cftypes
4185 * Unregister @cfts. Files described by @cfts are removed from all
4186 * existing cgroups and all future cgroups won't have them either. This
4187 * function can be called anytime whether @cfts' subsys is attached or not.
4189 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
4192 int cgroup_rm_cftypes(struct cftype *cfts)
4196 mutex_lock(&cgroup_mutex);
4197 ret = cgroup_rm_cftypes_locked(cfts);
4198 mutex_unlock(&cgroup_mutex);
4203 * cgroup_add_cftypes - add an array of cftypes to a subsystem
4204 * @ss: target cgroup subsystem
4205 * @cfts: zero-length name terminated array of cftypes
4207 * Register @cfts to @ss. Files described by @cfts are created for all
4208 * existing cgroups to which @ss is attached and all future cgroups will
4209 * have them too. This function can be called anytime whether @ss is
4212 * Returns 0 on successful registration, -errno on failure. Note that this
4213 * function currently returns 0 as long as @cfts registration is successful
4214 * even if some file creation attempts on existing cgroups fail.
4216 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4220 if (!cgroup_ssid_enabled(ss->id))
4223 if (!cfts || cfts[0].name[0] == '\0')
4226 ret = cgroup_init_cftypes(ss, cfts);
4230 mutex_lock(&cgroup_mutex);
4232 list_add_tail(&cfts->node, &ss->cfts);
4233 ret = cgroup_apply_cftypes(cfts, true);
4235 cgroup_rm_cftypes_locked(cfts);
4237 mutex_unlock(&cgroup_mutex);
4242 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
4243 * @ss: target cgroup subsystem
4244 * @cfts: zero-length name terminated array of cftypes
4246 * Similar to cgroup_add_cftypes() but the added files are only used for
4247 * the default hierarchy.
4249 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4253 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4254 cft->flags |= __CFTYPE_ONLY_ON_DFL;
4255 return cgroup_add_cftypes(ss, cfts);
4259 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
4260 * @ss: target cgroup subsystem
4261 * @cfts: zero-length name terminated array of cftypes
4263 * Similar to cgroup_add_cftypes() but the added files are only used for
4264 * the legacy hierarchies.
4266 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4270 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4271 cft->flags |= __CFTYPE_NOT_ON_DFL;
4272 return cgroup_add_cftypes(ss, cfts);
4276 * cgroup_file_notify - generate a file modified event for a cgroup_file
4277 * @cfile: target cgroup_file
4279 * @cfile must have been obtained by setting cftype->file_offset.
4281 void cgroup_file_notify(struct cgroup_file *cfile)
4283 unsigned long flags;
4285 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
4287 unsigned long last = cfile->notified_at;
4288 unsigned long next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
4290 if (time_in_range(jiffies, last, next)) {
4291 timer_reduce(&cfile->notify_timer, next);
4293 kernfs_notify(cfile->kn);
4294 cfile->notified_at = jiffies;
4297 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
4301 * css_next_child - find the next child of a given css
4302 * @pos: the current position (%NULL to initiate traversal)
4303 * @parent: css whose children to walk
4305 * This function returns the next child of @parent and should be called
4306 * under either cgroup_mutex or RCU read lock. The only requirement is
4307 * that @parent and @pos are accessible. The next sibling is guaranteed to
4308 * be returned regardless of their states.
4310 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4311 * css which finished ->css_online() is guaranteed to be visible in the
4312 * future iterations and will stay visible until the last reference is put.
4313 * A css which hasn't finished ->css_online() or already finished
4314 * ->css_offline() may show up during traversal. It's each subsystem's
4315 * responsibility to synchronize against on/offlining.
4317 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
4318 struct cgroup_subsys_state *parent)
4320 struct cgroup_subsys_state *next;
4322 cgroup_assert_mutex_or_rcu_locked();
4325 * @pos could already have been unlinked from the sibling list.
4326 * Once a cgroup is removed, its ->sibling.next is no longer
4327 * updated when its next sibling changes. CSS_RELEASED is set when
4328 * @pos is taken off list, at which time its next pointer is valid,
4329 * and, as releases are serialized, the one pointed to by the next
4330 * pointer is guaranteed to not have started release yet. This
4331 * implies that if we observe !CSS_RELEASED on @pos in this RCU
4332 * critical section, the one pointed to by its next pointer is
4333 * guaranteed to not have finished its RCU grace period even if we
4334 * have dropped rcu_read_lock() inbetween iterations.
4336 * If @pos has CSS_RELEASED set, its next pointer can't be
4337 * dereferenced; however, as each css is given a monotonically
4338 * increasing unique serial number and always appended to the
4339 * sibling list, the next one can be found by walking the parent's
4340 * children until the first css with higher serial number than
4341 * @pos's. While this path can be slower, it happens iff iteration
4342 * races against release and the race window is very small.
4345 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
4346 } else if (likely(!(pos->flags & CSS_RELEASED))) {
4347 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
4349 list_for_each_entry_rcu(next, &parent->children, sibling)
4350 if (next->serial_nr > pos->serial_nr)
4355 * @next, if not pointing to the head, can be dereferenced and is
4358 if (&next->sibling != &parent->children)
4364 * css_next_descendant_pre - find the next descendant for pre-order walk
4365 * @pos: the current position (%NULL to initiate traversal)
4366 * @root: css whose descendants to walk
4368 * To be used by css_for_each_descendant_pre(). Find the next descendant
4369 * to visit for pre-order traversal of @root's descendants. @root is
4370 * included in the iteration and the first node to be visited.
4372 * While this function requires cgroup_mutex or RCU read locking, it
4373 * doesn't require the whole traversal to be contained in a single critical
4374 * section. This function will return the correct next descendant as long
4375 * as both @pos and @root are accessible and @pos is a descendant of @root.
4377 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4378 * css which finished ->css_online() is guaranteed to be visible in the
4379 * future iterations and will stay visible until the last reference is put.
4380 * A css which hasn't finished ->css_online() or already finished
4381 * ->css_offline() may show up during traversal. It's each subsystem's
4382 * responsibility to synchronize against on/offlining.
4384 struct cgroup_subsys_state *
4385 css_next_descendant_pre(struct cgroup_subsys_state *pos,
4386 struct cgroup_subsys_state *root)
4388 struct cgroup_subsys_state *next;
4390 cgroup_assert_mutex_or_rcu_locked();
4392 /* if first iteration, visit @root */
4396 /* visit the first child if exists */
4397 next = css_next_child(NULL, pos);
4401 /* no child, visit my or the closest ancestor's next sibling */
4402 while (pos != root) {
4403 next = css_next_child(pos, pos->parent);
4411 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
4414 * css_rightmost_descendant - return the rightmost descendant of a css
4415 * @pos: css of interest
4417 * Return the rightmost descendant of @pos. If there's no descendant, @pos
4418 * is returned. This can be used during pre-order traversal to skip
4421 * While this function requires cgroup_mutex or RCU read locking, it
4422 * doesn't require the whole traversal to be contained in a single critical
4423 * section. This function will return the correct rightmost descendant as
4424 * long as @pos is accessible.
4426 struct cgroup_subsys_state *
4427 css_rightmost_descendant(struct cgroup_subsys_state *pos)
4429 struct cgroup_subsys_state *last, *tmp;
4431 cgroup_assert_mutex_or_rcu_locked();
4435 /* ->prev isn't RCU safe, walk ->next till the end */
4437 css_for_each_child(tmp, last)
4444 static struct cgroup_subsys_state *
4445 css_leftmost_descendant(struct cgroup_subsys_state *pos)
4447 struct cgroup_subsys_state *last;
4451 pos = css_next_child(NULL, pos);
4458 * css_next_descendant_post - find the next descendant for post-order walk
4459 * @pos: the current position (%NULL to initiate traversal)
4460 * @root: css whose descendants to walk
4462 * To be used by css_for_each_descendant_post(). Find the next descendant
4463 * to visit for post-order traversal of @root's descendants. @root is
4464 * included in the iteration and the last node to be visited.
4466 * While this function requires cgroup_mutex or RCU read locking, it
4467 * doesn't require the whole traversal to be contained in a single critical
4468 * section. This function will return the correct next descendant as long
4469 * as both @pos and @cgroup are accessible and @pos is a descendant of
4472 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4473 * css which finished ->css_online() is guaranteed to be visible in the
4474 * future iterations and will stay visible until the last reference is put.
4475 * A css which hasn't finished ->css_online() or already finished
4476 * ->css_offline() may show up during traversal. It's each subsystem's
4477 * responsibility to synchronize against on/offlining.
4479 struct cgroup_subsys_state *
4480 css_next_descendant_post(struct cgroup_subsys_state *pos,
4481 struct cgroup_subsys_state *root)
4483 struct cgroup_subsys_state *next;
4485 cgroup_assert_mutex_or_rcu_locked();
4487 /* if first iteration, visit leftmost descendant which may be @root */
4489 return css_leftmost_descendant(root);
4491 /* if we visited @root, we're done */
4495 /* if there's an unvisited sibling, visit its leftmost descendant */
4496 next = css_next_child(pos, pos->parent);
4498 return css_leftmost_descendant(next);
4500 /* no sibling left, visit parent */
4505 * css_has_online_children - does a css have online children
4506 * @css: the target css
4508 * Returns %true if @css has any online children; otherwise, %false. This
4509 * function can be called from any context but the caller is responsible
4510 * for synchronizing against on/offlining as necessary.
4512 bool css_has_online_children(struct cgroup_subsys_state *css)
4514 struct cgroup_subsys_state *child;
4518 css_for_each_child(child, css) {
4519 if (child->flags & CSS_ONLINE) {
4528 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4530 struct list_head *l;
4531 struct cgrp_cset_link *link;
4532 struct css_set *cset;
4534 lockdep_assert_held(&css_set_lock);
4536 /* find the next threaded cset */
4537 if (it->tcset_pos) {
4538 l = it->tcset_pos->next;
4540 if (l != it->tcset_head) {
4542 return container_of(l, struct css_set,
4543 threaded_csets_node);
4546 it->tcset_pos = NULL;
4549 /* find the next cset */
4552 if (l == it->cset_head) {
4553 it->cset_pos = NULL;
4558 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4560 link = list_entry(l, struct cgrp_cset_link, cset_link);
4566 /* initialize threaded css_set walking */
4567 if (it->flags & CSS_TASK_ITER_THREADED) {
4569 put_css_set_locked(it->cur_dcset);
4570 it->cur_dcset = cset;
4573 it->tcset_head = &cset->threaded_csets;
4574 it->tcset_pos = &cset->threaded_csets;
4581 * css_task_iter_advance_css_set - advance a task itererator to the next css_set
4582 * @it: the iterator to advance
4584 * Advance @it to the next css_set to walk.
4586 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4588 struct css_set *cset;
4590 lockdep_assert_held(&css_set_lock);
4592 /* Advance to the next non-empty css_set */
4594 cset = css_task_iter_next_css_set(it);
4596 it->task_pos = NULL;
4599 } while (!css_set_populated(cset) && list_empty(&cset->dying_tasks));
4601 if (!list_empty(&cset->tasks)) {
4602 it->task_pos = cset->tasks.next;
4603 it->cur_tasks_head = &cset->tasks;
4604 } else if (!list_empty(&cset->mg_tasks)) {
4605 it->task_pos = cset->mg_tasks.next;
4606 it->cur_tasks_head = &cset->mg_tasks;
4608 it->task_pos = cset->dying_tasks.next;
4609 it->cur_tasks_head = &cset->dying_tasks;
4612 it->tasks_head = &cset->tasks;
4613 it->mg_tasks_head = &cset->mg_tasks;
4614 it->dying_tasks_head = &cset->dying_tasks;
4617 * We don't keep css_sets locked across iteration steps and thus
4618 * need to take steps to ensure that iteration can be resumed after
4619 * the lock is re-acquired. Iteration is performed at two levels -
4620 * css_sets and tasks in them.
4622 * Once created, a css_set never leaves its cgroup lists, so a
4623 * pinned css_set is guaranteed to stay put and we can resume
4624 * iteration afterwards.
4626 * Tasks may leave @cset across iteration steps. This is resolved
4627 * by registering each iterator with the css_set currently being
4628 * walked and making css_set_move_task() advance iterators whose
4629 * next task is leaving.
4632 list_del(&it->iters_node);
4633 put_css_set_locked(it->cur_cset);
4636 it->cur_cset = cset;
4637 list_add(&it->iters_node, &cset->task_iters);
4640 static void css_task_iter_skip(struct css_task_iter *it,
4641 struct task_struct *task)
4643 lockdep_assert_held(&css_set_lock);
4645 if (it->task_pos == &task->cg_list) {
4646 it->task_pos = it->task_pos->next;
4647 it->flags |= CSS_TASK_ITER_SKIPPED;
4651 static void css_task_iter_advance(struct css_task_iter *it)
4653 struct task_struct *task;
4655 lockdep_assert_held(&css_set_lock);
4659 * Advance iterator to find next entry. cset->tasks is
4660 * consumed first and then ->mg_tasks. After ->mg_tasks,
4661 * we move onto the next cset.
4663 if (it->flags & CSS_TASK_ITER_SKIPPED)
4664 it->flags &= ~CSS_TASK_ITER_SKIPPED;
4666 it->task_pos = it->task_pos->next;
4668 if (it->task_pos == it->tasks_head) {
4669 it->task_pos = it->mg_tasks_head->next;
4670 it->cur_tasks_head = it->mg_tasks_head;
4672 if (it->task_pos == it->mg_tasks_head) {
4673 it->task_pos = it->dying_tasks_head->next;
4674 it->cur_tasks_head = it->dying_tasks_head;
4676 if (it->task_pos == it->dying_tasks_head)
4677 css_task_iter_advance_css_set(it);
4679 /* called from start, proceed to the first cset */
4680 css_task_iter_advance_css_set(it);
4686 task = list_entry(it->task_pos, struct task_struct, cg_list);
4688 if (it->flags & CSS_TASK_ITER_PROCS) {
4689 /* if PROCS, skip over tasks which aren't group leaders */
4690 if (!thread_group_leader(task))
4693 /* and dying leaders w/o live member threads */
4694 if (it->cur_tasks_head == it->dying_tasks_head &&
4695 !atomic_read(&task->signal->live))
4698 /* skip all dying ones */
4699 if (it->cur_tasks_head == it->dying_tasks_head)
4705 * css_task_iter_start - initiate task iteration
4706 * @css: the css to walk tasks of
4707 * @flags: CSS_TASK_ITER_* flags
4708 * @it: the task iterator to use
4710 * Initiate iteration through the tasks of @css. The caller can call
4711 * css_task_iter_next() to walk through the tasks until the function
4712 * returns NULL. On completion of iteration, css_task_iter_end() must be
4715 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4716 struct css_task_iter *it)
4718 /* no one should try to iterate before mounting cgroups */
4719 WARN_ON_ONCE(!use_task_css_set_links);
4721 memset(it, 0, sizeof(*it));
4723 spin_lock_irq(&css_set_lock);
4729 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4731 it->cset_pos = &css->cgroup->cset_links;
4733 it->cset_head = it->cset_pos;
4735 css_task_iter_advance(it);
4737 spin_unlock_irq(&css_set_lock);
4741 * css_task_iter_next - return the next task for the iterator
4742 * @it: the task iterator being iterated
4744 * The "next" function for task iteration. @it should have been
4745 * initialized via css_task_iter_start(). Returns NULL when the iteration
4748 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4751 put_task_struct(it->cur_task);
4752 it->cur_task = NULL;
4755 spin_lock_irq(&css_set_lock);
4757 /* @it may be half-advanced by skips, finish advancing */
4758 if (it->flags & CSS_TASK_ITER_SKIPPED)
4759 css_task_iter_advance(it);
4762 it->cur_task = list_entry(it->task_pos, struct task_struct,
4764 get_task_struct(it->cur_task);
4765 css_task_iter_advance(it);
4768 spin_unlock_irq(&css_set_lock);
4770 return it->cur_task;
4774 * css_task_iter_end - finish task iteration
4775 * @it: the task iterator to finish
4777 * Finish task iteration started by css_task_iter_start().
4779 void css_task_iter_end(struct css_task_iter *it)
4782 spin_lock_irq(&css_set_lock);
4783 list_del(&it->iters_node);
4784 put_css_set_locked(it->cur_cset);
4785 spin_unlock_irq(&css_set_lock);
4789 put_css_set(it->cur_dcset);
4792 put_task_struct(it->cur_task);
4795 static void cgroup_procs_release(struct kernfs_open_file *of)
4797 struct cgroup_file_ctx *ctx = of->priv;
4799 if (ctx->procs.started)
4800 css_task_iter_end(&ctx->procs.iter);
4803 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
4805 struct kernfs_open_file *of = s->private;
4806 struct cgroup_file_ctx *ctx = of->priv;
4811 return css_task_iter_next(&ctx->procs.iter);
4814 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
4815 unsigned int iter_flags)
4817 struct kernfs_open_file *of = s->private;
4818 struct cgroup *cgrp = seq_css(s)->cgroup;
4819 struct cgroup_file_ctx *ctx = of->priv;
4820 struct css_task_iter *it = &ctx->procs.iter;
4823 * When a seq_file is seeked, it's always traversed sequentially
4824 * from position 0, so we can simply keep iterating on !0 *pos.
4826 if (!ctx->procs.started) {
4827 if (WARN_ON_ONCE((*pos)))
4828 return ERR_PTR(-EINVAL);
4829 css_task_iter_start(&cgrp->self, iter_flags, it);
4830 ctx->procs.started = true;
4831 } else if (!(*pos)) {
4832 css_task_iter_end(it);
4833 css_task_iter_start(&cgrp->self, iter_flags, it);
4835 return it->cur_task;
4837 return cgroup_procs_next(s, NULL, NULL);
4840 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
4842 struct cgroup *cgrp = seq_css(s)->cgroup;
4845 * All processes of a threaded subtree belong to the domain cgroup
4846 * of the subtree. Only threads can be distributed across the
4847 * subtree. Reject reads on cgroup.procs in the subtree proper.
4848 * They're always empty anyway.
4850 if (cgroup_is_threaded(cgrp))
4851 return ERR_PTR(-EOPNOTSUPP);
4853 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
4854 CSS_TASK_ITER_THREADED);
4857 static int cgroup_procs_show(struct seq_file *s, void *v)
4859 seq_printf(s, "%d\n", task_pid_vnr(v));
4863 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
4864 struct cgroup *dst_cgrp,
4865 struct super_block *sb,
4866 struct cgroup_namespace *ns)
4868 struct cgroup *com_cgrp = src_cgrp;
4869 struct inode *inode;
4872 lockdep_assert_held(&cgroup_mutex);
4874 /* find the common ancestor */
4875 while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
4876 com_cgrp = cgroup_parent(com_cgrp);
4878 /* %current should be authorized to migrate to the common ancestor */
4879 inode = kernfs_get_inode(sb, com_cgrp->procs_file.kn);
4883 ret = inode_permission(inode, MAY_WRITE);
4889 * If namespaces are delegation boundaries, %current must be able
4890 * to see both source and destination cgroups from its namespace.
4892 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
4893 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
4894 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
4900 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
4901 char *buf, size_t nbytes, loff_t off)
4903 struct cgroup_file_ctx *ctx = of->priv;
4904 struct cgroup *src_cgrp, *dst_cgrp;
4905 struct task_struct *task;
4906 const struct cred *saved_cred;
4908 bool threadgroup_locked;
4910 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4914 task = cgroup_procs_write_start(buf, true, &threadgroup_locked);
4915 ret = PTR_ERR_OR_ZERO(task);
4919 /* find the source cgroup */
4920 spin_lock_irq(&css_set_lock);
4921 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4922 spin_unlock_irq(&css_set_lock);
4925 * Process and thread migrations follow same delegation rule. Check
4926 * permissions using the credentials from file open to protect against
4927 * inherited fd attacks.
4929 saved_cred = override_creds(of->file->f_cred);
4930 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4931 of->file->f_path.dentry->d_sb,
4933 revert_creds(saved_cred);
4937 ret = cgroup_attach_task(dst_cgrp, task, true);
4940 cgroup_procs_write_finish(task, threadgroup_locked);
4942 cgroup_kn_unlock(of->kn);
4944 return ret ?: nbytes;
4947 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
4949 return __cgroup_procs_start(s, pos, 0);
4952 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
4953 char *buf, size_t nbytes, loff_t off)
4955 struct cgroup_file_ctx *ctx = of->priv;
4956 struct cgroup *src_cgrp, *dst_cgrp;
4957 struct task_struct *task;
4958 const struct cred *saved_cred;
4962 buf = strstrip(buf);
4964 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4968 task = cgroup_procs_write_start(buf, false, &locked);
4969 ret = PTR_ERR_OR_ZERO(task);
4973 /* find the source cgroup */
4974 spin_lock_irq(&css_set_lock);
4975 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4976 spin_unlock_irq(&css_set_lock);
4979 * Process and thread migrations follow same delegation rule. Check
4980 * permissions using the credentials from file open to protect against
4981 * inherited fd attacks.
4983 saved_cred = override_creds(of->file->f_cred);
4984 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4985 of->file->f_path.dentry->d_sb,
4987 revert_creds(saved_cred);
4991 /* and must be contained in the same domain */
4993 if (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp)
4996 ret = cgroup_attach_task(dst_cgrp, task, false);
4999 cgroup_procs_write_finish(task, locked);
5001 cgroup_kn_unlock(of->kn);
5003 return ret ?: nbytes;
5006 /* cgroup core interface files for the default hierarchy */
5007 static struct cftype cgroup_base_files[] = {
5009 .name = "cgroup.type",
5010 .flags = CFTYPE_NOT_ON_ROOT,
5011 .seq_show = cgroup_type_show,
5012 .write = cgroup_type_write,
5015 .name = "cgroup.procs",
5016 .flags = CFTYPE_NS_DELEGATABLE,
5017 .file_offset = offsetof(struct cgroup, procs_file),
5018 .release = cgroup_procs_release,
5019 .seq_start = cgroup_procs_start,
5020 .seq_next = cgroup_procs_next,
5021 .seq_show = cgroup_procs_show,
5022 .write = cgroup_procs_write,
5025 .name = "cgroup.threads",
5026 .flags = CFTYPE_NS_DELEGATABLE,
5027 .release = cgroup_procs_release,
5028 .seq_start = cgroup_threads_start,
5029 .seq_next = cgroup_procs_next,
5030 .seq_show = cgroup_procs_show,
5031 .write = cgroup_threads_write,
5034 .name = "cgroup.controllers",
5035 .seq_show = cgroup_controllers_show,
5038 .name = "cgroup.subtree_control",
5039 .flags = CFTYPE_NS_DELEGATABLE,
5040 .seq_show = cgroup_subtree_control_show,
5041 .write = cgroup_subtree_control_write,
5044 .name = "cgroup.events",
5045 .flags = CFTYPE_NOT_ON_ROOT,
5046 .file_offset = offsetof(struct cgroup, events_file),
5047 .seq_show = cgroup_events_show,
5050 .name = "cgroup.max.descendants",
5051 .seq_show = cgroup_max_descendants_show,
5052 .write = cgroup_max_descendants_write,
5055 .name = "cgroup.max.depth",
5056 .seq_show = cgroup_max_depth_show,
5057 .write = cgroup_max_depth_write,
5060 .name = "cgroup.stat",
5061 .seq_show = cgroup_stat_show,
5064 .name = "cgroup.freeze",
5065 .flags = CFTYPE_NOT_ON_ROOT,
5066 .seq_show = cgroup_freeze_show,
5067 .write = cgroup_freeze_write,
5071 .flags = CFTYPE_NOT_ON_ROOT,
5072 .seq_show = cpu_stat_show,
5076 .name = "io.pressure",
5077 .seq_show = cgroup_io_pressure_show,
5078 .write = cgroup_io_pressure_write,
5079 .poll = cgroup_pressure_poll,
5080 .release = cgroup_pressure_release,
5083 .name = "memory.pressure",
5084 .seq_show = cgroup_memory_pressure_show,
5085 .write = cgroup_memory_pressure_write,
5086 .poll = cgroup_pressure_poll,
5087 .release = cgroup_pressure_release,
5090 .name = "cpu.pressure",
5091 .seq_show = cgroup_cpu_pressure_show,
5092 .write = cgroup_cpu_pressure_write,
5093 .poll = cgroup_pressure_poll,
5094 .release = cgroup_pressure_release,
5096 #endif /* CONFIG_PSI */
5101 * css destruction is four-stage process.
5103 * 1. Destruction starts. Killing of the percpu_ref is initiated.
5104 * Implemented in kill_css().
5106 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
5107 * and thus css_tryget_online() is guaranteed to fail, the css can be
5108 * offlined by invoking offline_css(). After offlining, the base ref is
5109 * put. Implemented in css_killed_work_fn().
5111 * 3. When the percpu_ref reaches zero, the only possible remaining
5112 * accessors are inside RCU read sections. css_release() schedules the
5115 * 4. After the grace period, the css can be freed. Implemented in
5116 * css_free_work_fn().
5118 * It is actually hairier because both step 2 and 4 require process context
5119 * and thus involve punting to css->destroy_work adding two additional
5120 * steps to the already complex sequence.
5122 static void css_free_rwork_fn(struct work_struct *work)
5124 struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
5125 struct cgroup_subsys_state, destroy_rwork);
5126 struct cgroup_subsys *ss = css->ss;
5127 struct cgroup *cgrp = css->cgroup;
5129 percpu_ref_exit(&css->refcnt);
5133 struct cgroup_subsys_state *parent = css->parent;
5137 cgroup_idr_remove(&ss->css_idr, id);
5143 /* cgroup free path */
5144 atomic_dec(&cgrp->root->nr_cgrps);
5145 cgroup1_pidlist_destroy_all(cgrp);
5146 cancel_work_sync(&cgrp->release_agent_work);
5148 if (cgroup_parent(cgrp)) {
5150 * We get a ref to the parent, and put the ref when
5151 * this cgroup is being freed, so it's guaranteed
5152 * that the parent won't be destroyed before its
5155 cgroup_put(cgroup_parent(cgrp));
5156 kernfs_put(cgrp->kn);
5157 psi_cgroup_free(cgrp);
5158 if (cgroup_on_dfl(cgrp))
5159 cgroup_rstat_exit(cgrp);
5163 * This is root cgroup's refcnt reaching zero,
5164 * which indicates that the root should be
5167 cgroup_destroy_root(cgrp->root);
5172 static void css_release_work_fn(struct work_struct *work)
5174 struct cgroup_subsys_state *css =
5175 container_of(work, struct cgroup_subsys_state, destroy_work);
5176 struct cgroup_subsys *ss = css->ss;
5177 struct cgroup *cgrp = css->cgroup;
5179 mutex_lock(&cgroup_mutex);
5181 css->flags |= CSS_RELEASED;
5182 list_del_rcu(&css->sibling);
5185 /* css release path */
5186 if (!list_empty(&css->rstat_css_node)) {
5187 cgroup_rstat_flush(cgrp);
5188 list_del_rcu(&css->rstat_css_node);
5191 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
5192 if (ss->css_released)
5193 ss->css_released(css);
5195 struct cgroup *tcgrp;
5197 /* cgroup release path */
5198 TRACE_CGROUP_PATH(release, cgrp);
5200 if (cgroup_on_dfl(cgrp))
5201 cgroup_rstat_flush(cgrp);
5203 spin_lock_irq(&css_set_lock);
5204 for (tcgrp = cgroup_parent(cgrp); tcgrp;
5205 tcgrp = cgroup_parent(tcgrp))
5206 tcgrp->nr_dying_descendants--;
5207 spin_unlock_irq(&css_set_lock);
5209 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
5213 * There are two control paths which try to determine
5214 * cgroup from dentry without going through kernfs -
5215 * cgroupstats_build() and css_tryget_online_from_dir().
5216 * Those are supported by RCU protecting clearing of
5217 * cgrp->kn->priv backpointer.
5220 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
5224 mutex_unlock(&cgroup_mutex);
5226 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5227 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
5230 static void css_release(struct percpu_ref *ref)
5232 struct cgroup_subsys_state *css =
5233 container_of(ref, struct cgroup_subsys_state, refcnt);
5235 INIT_WORK(&css->destroy_work, css_release_work_fn);
5236 queue_work(cgroup_destroy_wq, &css->destroy_work);
5239 static void init_and_link_css(struct cgroup_subsys_state *css,
5240 struct cgroup_subsys *ss, struct cgroup *cgrp)
5242 lockdep_assert_held(&cgroup_mutex);
5244 cgroup_get_live(cgrp);
5246 memset(css, 0, sizeof(*css));
5250 INIT_LIST_HEAD(&css->sibling);
5251 INIT_LIST_HEAD(&css->children);
5252 INIT_LIST_HEAD(&css->rstat_css_node);
5253 css->serial_nr = css_serial_nr_next++;
5254 atomic_set(&css->online_cnt, 0);
5256 if (cgroup_parent(cgrp)) {
5257 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
5258 css_get(css->parent);
5261 if (cgroup_on_dfl(cgrp) && ss->css_rstat_flush)
5262 list_add_rcu(&css->rstat_css_node, &cgrp->rstat_css_list);
5264 BUG_ON(cgroup_css(cgrp, ss));
5267 /* invoke ->css_online() on a new CSS and mark it online if successful */
5268 static int online_css(struct cgroup_subsys_state *css)
5270 struct cgroup_subsys *ss = css->ss;
5273 lockdep_assert_held(&cgroup_mutex);
5276 ret = ss->css_online(css);
5278 css->flags |= CSS_ONLINE;
5279 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
5281 atomic_inc(&css->online_cnt);
5283 atomic_inc(&css->parent->online_cnt);
5288 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
5289 static void offline_css(struct cgroup_subsys_state *css)
5291 struct cgroup_subsys *ss = css->ss;
5293 lockdep_assert_held(&cgroup_mutex);
5295 if (!(css->flags & CSS_ONLINE))
5298 if (ss->css_offline)
5299 ss->css_offline(css);
5301 css->flags &= ~CSS_ONLINE;
5302 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
5304 wake_up_all(&css->cgroup->offline_waitq);
5308 * css_create - create a cgroup_subsys_state
5309 * @cgrp: the cgroup new css will be associated with
5310 * @ss: the subsys of new css
5312 * Create a new css associated with @cgrp - @ss pair. On success, the new
5313 * css is online and installed in @cgrp. This function doesn't create the
5314 * interface files. Returns 0 on success, -errno on failure.
5316 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
5317 struct cgroup_subsys *ss)
5319 struct cgroup *parent = cgroup_parent(cgrp);
5320 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
5321 struct cgroup_subsys_state *css;
5324 lockdep_assert_held(&cgroup_mutex);
5326 css = ss->css_alloc(parent_css);
5328 css = ERR_PTR(-ENOMEM);
5332 init_and_link_css(css, ss, cgrp);
5334 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
5338 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
5343 /* @css is ready to be brought online now, make it visible */
5344 list_add_tail_rcu(&css->sibling, &parent_css->children);
5345 cgroup_idr_replace(&ss->css_idr, css, css->id);
5347 err = online_css(css);
5351 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
5352 cgroup_parent(parent)) {
5353 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
5354 current->comm, current->pid, ss->name);
5355 if (!strcmp(ss->name, "memory"))
5356 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
5357 ss->warned_broken_hierarchy = true;
5363 list_del_rcu(&css->sibling);
5365 list_del_rcu(&css->rstat_css_node);
5366 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5367 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
5368 return ERR_PTR(err);
5372 * The returned cgroup is fully initialized including its control mask, but
5373 * it isn't associated with its kernfs_node and doesn't have the control
5376 static struct cgroup *cgroup_create(struct cgroup *parent)
5378 struct cgroup_root *root = parent->root;
5379 struct cgroup *cgrp, *tcgrp;
5380 int level = parent->level + 1;
5383 /* allocate the cgroup and its ID, 0 is reserved for the root */
5384 cgrp = kzalloc(struct_size(cgrp, ancestor_ids, (level + 1)),
5387 return ERR_PTR(-ENOMEM);
5389 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
5393 if (cgroup_on_dfl(parent)) {
5394 ret = cgroup_rstat_init(cgrp);
5396 goto out_cancel_ref;
5400 * Temporarily set the pointer to NULL, so idr_find() won't return
5401 * a half-baked cgroup.
5403 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
5409 init_cgroup_housekeeping(cgrp);
5411 cgrp->self.parent = &parent->self;
5413 cgrp->level = level;
5415 ret = psi_cgroup_alloc(cgrp);
5419 ret = cgroup_bpf_inherit(cgrp);
5424 * New cgroup inherits effective freeze counter, and
5425 * if the parent has to be frozen, the child has too.
5427 cgrp->freezer.e_freeze = parent->freezer.e_freeze;
5428 if (cgrp->freezer.e_freeze) {
5430 * Set the CGRP_FREEZE flag, so when a process will be
5431 * attached to the child cgroup, it will become frozen.
5432 * At this point the new cgroup is unpopulated, so we can
5433 * consider it frozen immediately.
5435 set_bit(CGRP_FREEZE, &cgrp->flags);
5436 set_bit(CGRP_FROZEN, &cgrp->flags);
5439 spin_lock_irq(&css_set_lock);
5440 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5441 cgrp->ancestor_ids[tcgrp->level] = tcgrp->id;
5443 if (tcgrp != cgrp) {
5444 tcgrp->nr_descendants++;
5447 * If the new cgroup is frozen, all ancestor cgroups
5448 * get a new frozen descendant, but their state can't
5449 * change because of this.
5451 if (cgrp->freezer.e_freeze)
5452 tcgrp->freezer.nr_frozen_descendants++;
5455 spin_unlock_irq(&css_set_lock);
5457 if (notify_on_release(parent))
5458 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
5460 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
5461 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
5463 cgrp->self.serial_nr = css_serial_nr_next++;
5465 /* allocation complete, commit to creation */
5466 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
5467 atomic_inc(&root->nr_cgrps);
5468 cgroup_get_live(parent);
5471 * @cgrp is now fully operational. If something fails after this
5472 * point, it'll be released via the normal destruction path.
5474 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
5477 * On the default hierarchy, a child doesn't automatically inherit
5478 * subtree_control from the parent. Each is configured manually.
5480 if (!cgroup_on_dfl(cgrp))
5481 cgrp->subtree_control = cgroup_control(cgrp);
5483 cgroup_propagate_control(cgrp);
5488 psi_cgroup_free(cgrp);
5490 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
5492 if (cgroup_on_dfl(parent))
5493 cgroup_rstat_exit(cgrp);
5495 percpu_ref_exit(&cgrp->self.refcnt);
5498 return ERR_PTR(ret);
5501 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
5503 struct cgroup *cgroup;
5507 lockdep_assert_held(&cgroup_mutex);
5509 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
5510 if (cgroup->nr_descendants >= cgroup->max_descendants)
5513 if (level > cgroup->max_depth)
5524 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
5526 struct cgroup *parent, *cgrp;
5527 struct kernfs_node *kn;
5530 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
5531 if (strchr(name, '\n'))
5534 parent = cgroup_kn_lock_live(parent_kn, false);
5538 if (!cgroup_check_hierarchy_limits(parent)) {
5543 cgrp = cgroup_create(parent);
5545 ret = PTR_ERR(cgrp);
5549 /* create the directory */
5550 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
5558 * This extra ref will be put in cgroup_free_fn() and guarantees
5559 * that @cgrp->kn is always accessible.
5563 ret = cgroup_kn_set_ugid(kn);
5567 ret = css_populate_dir(&cgrp->self);
5571 ret = cgroup_apply_control_enable(cgrp);
5575 TRACE_CGROUP_PATH(mkdir, cgrp);
5577 /* let's create and online css's */
5578 kernfs_activate(kn);
5584 cgroup_destroy_locked(cgrp);
5586 cgroup_kn_unlock(parent_kn);
5591 * This is called when the refcnt of a css is confirmed to be killed.
5592 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
5593 * initate destruction and put the css ref from kill_css().
5595 static void css_killed_work_fn(struct work_struct *work)
5597 struct cgroup_subsys_state *css =
5598 container_of(work, struct cgroup_subsys_state, destroy_work);
5600 mutex_lock(&cgroup_mutex);
5605 /* @css can't go away while we're holding cgroup_mutex */
5607 } while (css && atomic_dec_and_test(&css->online_cnt));
5609 mutex_unlock(&cgroup_mutex);
5612 /* css kill confirmation processing requires process context, bounce */
5613 static void css_killed_ref_fn(struct percpu_ref *ref)
5615 struct cgroup_subsys_state *css =
5616 container_of(ref, struct cgroup_subsys_state, refcnt);
5618 if (atomic_dec_and_test(&css->online_cnt)) {
5619 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5620 queue_work(cgroup_destroy_wq, &css->destroy_work);
5625 * kill_css - destroy a css
5626 * @css: css to destroy
5628 * This function initiates destruction of @css by removing cgroup interface
5629 * files and putting its base reference. ->css_offline() will be invoked
5630 * asynchronously once css_tryget_online() is guaranteed to fail and when
5631 * the reference count reaches zero, @css will be released.
5633 static void kill_css(struct cgroup_subsys_state *css)
5635 lockdep_assert_held(&cgroup_mutex);
5637 if (css->flags & CSS_DYING)
5640 css->flags |= CSS_DYING;
5643 * This must happen before css is disassociated with its cgroup.
5644 * See seq_css() for details.
5649 * Killing would put the base ref, but we need to keep it alive
5650 * until after ->css_offline().
5655 * cgroup core guarantees that, by the time ->css_offline() is
5656 * invoked, no new css reference will be given out via
5657 * css_tryget_online(). We can't simply call percpu_ref_kill() and
5658 * proceed to offlining css's because percpu_ref_kill() doesn't
5659 * guarantee that the ref is seen as killed on all CPUs on return.
5661 * Use percpu_ref_kill_and_confirm() to get notifications as each
5662 * css is confirmed to be seen as killed on all CPUs.
5664 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5668 * cgroup_destroy_locked - the first stage of cgroup destruction
5669 * @cgrp: cgroup to be destroyed
5671 * css's make use of percpu refcnts whose killing latency shouldn't be
5672 * exposed to userland and are RCU protected. Also, cgroup core needs to
5673 * guarantee that css_tryget_online() won't succeed by the time
5674 * ->css_offline() is invoked. To satisfy all the requirements,
5675 * destruction is implemented in the following two steps.
5677 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
5678 * userland visible parts and start killing the percpu refcnts of
5679 * css's. Set up so that the next stage will be kicked off once all
5680 * the percpu refcnts are confirmed to be killed.
5682 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5683 * rest of destruction. Once all cgroup references are gone, the
5684 * cgroup is RCU-freed.
5686 * This function implements s1. After this step, @cgrp is gone as far as
5687 * the userland is concerned and a new cgroup with the same name may be
5688 * created. As cgroup doesn't care about the names internally, this
5689 * doesn't cause any problem.
5691 static int cgroup_destroy_locked(struct cgroup *cgrp)
5692 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5694 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5695 struct cgroup_subsys_state *css;
5696 struct cgrp_cset_link *link;
5699 lockdep_assert_held(&cgroup_mutex);
5702 * Only migration can raise populated from zero and we're already
5703 * holding cgroup_mutex.
5705 if (cgroup_is_populated(cgrp))
5709 * Make sure there's no live children. We can't test emptiness of
5710 * ->self.children as dead children linger on it while being
5711 * drained; otherwise, "rmdir parent/child parent" may fail.
5713 if (css_has_online_children(&cgrp->self))
5717 * Mark @cgrp and the associated csets dead. The former prevents
5718 * further task migration and child creation by disabling
5719 * cgroup_lock_live_group(). The latter makes the csets ignored by
5720 * the migration path.
5722 cgrp->self.flags &= ~CSS_ONLINE;
5724 spin_lock_irq(&css_set_lock);
5725 list_for_each_entry(link, &cgrp->cset_links, cset_link)
5726 link->cset->dead = true;
5727 spin_unlock_irq(&css_set_lock);
5729 /* initiate massacre of all css's */
5730 for_each_css(css, ssid, cgrp)
5733 /* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
5734 css_clear_dir(&cgrp->self);
5735 kernfs_remove(cgrp->kn);
5737 if (parent && cgroup_is_threaded(cgrp))
5738 parent->nr_threaded_children--;
5740 spin_lock_irq(&css_set_lock);
5741 for (tcgrp = cgroup_parent(cgrp); tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5742 tcgrp->nr_descendants--;
5743 tcgrp->nr_dying_descendants++;
5745 * If the dying cgroup is frozen, decrease frozen descendants
5746 * counters of ancestor cgroups.
5748 if (test_bit(CGRP_FROZEN, &cgrp->flags))
5749 tcgrp->freezer.nr_frozen_descendants--;
5751 spin_unlock_irq(&css_set_lock);
5753 cgroup1_check_for_release(parent);
5755 cgroup_bpf_offline(cgrp);
5757 /* put the base reference */
5758 percpu_ref_kill(&cgrp->self.refcnt);
5763 int cgroup_rmdir(struct kernfs_node *kn)
5765 struct cgroup *cgrp;
5768 cgrp = cgroup_kn_lock_live(kn, false);
5772 ret = cgroup_destroy_locked(cgrp);
5774 TRACE_CGROUP_PATH(rmdir, cgrp);
5776 cgroup_kn_unlock(kn);
5780 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5781 .show_options = cgroup_show_options,
5782 .mkdir = cgroup_mkdir,
5783 .rmdir = cgroup_rmdir,
5784 .show_path = cgroup_show_path,
5787 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5789 struct cgroup_subsys_state *css;
5791 pr_debug("Initializing cgroup subsys %s\n", ss->name);
5793 mutex_lock(&cgroup_mutex);
5795 idr_init(&ss->css_idr);
5796 INIT_LIST_HEAD(&ss->cfts);
5798 /* Create the root cgroup state for this subsystem */
5799 ss->root = &cgrp_dfl_root;
5800 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5801 /* We don't handle early failures gracefully */
5802 BUG_ON(IS_ERR(css));
5803 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5806 * Root csses are never destroyed and we can't initialize
5807 * percpu_ref during early init. Disable refcnting.
5809 css->flags |= CSS_NO_REF;
5812 /* allocation can't be done safely during early init */
5815 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5816 BUG_ON(css->id < 0);
5819 /* Update the init_css_set to contain a subsys
5820 * pointer to this state - since the subsystem is
5821 * newly registered, all tasks and hence the
5822 * init_css_set is in the subsystem's root cgroup. */
5823 init_css_set.subsys[ss->id] = css;
5825 have_fork_callback |= (bool)ss->fork << ss->id;
5826 have_exit_callback |= (bool)ss->exit << ss->id;
5827 have_release_callback |= (bool)ss->release << ss->id;
5828 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5830 /* At system boot, before all subsystems have been
5831 * registered, no tasks have been forked, so we don't
5832 * need to invoke fork callbacks here. */
5833 BUG_ON(!list_empty(&init_task.tasks));
5835 BUG_ON(online_css(css));
5837 mutex_unlock(&cgroup_mutex);
5841 * cgroup_init_early - cgroup initialization at system boot
5843 * Initialize cgroups at system boot, and initialize any
5844 * subsystems that request early init.
5846 int __init cgroup_init_early(void)
5848 static struct cgroup_fs_context __initdata ctx;
5849 struct cgroup_subsys *ss;
5852 ctx.root = &cgrp_dfl_root;
5853 init_cgroup_root(&ctx);
5854 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5856 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5858 for_each_subsys(ss, i) {
5859 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5860 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
5861 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5863 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5864 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5867 ss->name = cgroup_subsys_name[i];
5868 if (!ss->legacy_name)
5869 ss->legacy_name = cgroup_subsys_name[i];
5872 cgroup_init_subsys(ss, true);
5878 * cgroup_init - cgroup initialization
5880 * Register cgroup filesystem and /proc file, and initialize
5881 * any subsystems that didn't request early init.
5883 int __init cgroup_init(void)
5885 struct cgroup_subsys *ss;
5888 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
5889 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
5890 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
5892 cgroup_rstat_boot();
5895 * The latency of the synchronize_rcu() is too high for cgroups,
5896 * avoid it at the cost of forcing all readers into the slow path.
5898 rcu_sync_enter_start(&cgroup_threadgroup_rwsem.rss);
5900 get_user_ns(init_cgroup_ns.user_ns);
5902 mutex_lock(&cgroup_mutex);
5905 * Add init_css_set to the hash table so that dfl_root can link to
5908 hash_add(css_set_table, &init_css_set.hlist,
5909 css_set_hash(init_css_set.subsys));
5911 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
5913 mutex_unlock(&cgroup_mutex);
5915 for_each_subsys(ss, ssid) {
5916 if (ss->early_init) {
5917 struct cgroup_subsys_state *css =
5918 init_css_set.subsys[ss->id];
5920 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5922 BUG_ON(css->id < 0);
5924 cgroup_init_subsys(ss, false);
5927 list_add_tail(&init_css_set.e_cset_node[ssid],
5928 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5931 * Setting dfl_root subsys_mask needs to consider the
5932 * disabled flag and cftype registration needs kmalloc,
5933 * both of which aren't available during early_init.
5935 if (!cgroup_ssid_enabled(ssid))
5938 if (cgroup1_ssid_disabled(ssid))
5939 printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
5942 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5944 /* implicit controllers must be threaded too */
5945 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
5947 if (ss->implicit_on_dfl)
5948 cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
5949 else if (!ss->dfl_cftypes)
5950 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
5953 cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
5955 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5956 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5958 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5959 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5963 ss->bind(init_css_set.subsys[ssid]);
5965 mutex_lock(&cgroup_mutex);
5966 css_populate_dir(init_css_set.subsys[ssid]);
5967 mutex_unlock(&cgroup_mutex);
5970 /* init_css_set.subsys[] has been updated, re-hash */
5971 hash_del(&init_css_set.hlist);
5972 hash_add(css_set_table, &init_css_set.hlist,
5973 css_set_hash(init_css_set.subsys));
5975 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
5976 WARN_ON(register_filesystem(&cgroup_fs_type));
5977 WARN_ON(register_filesystem(&cgroup2_fs_type));
5978 WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show));
5979 #ifdef CONFIG_CPUSETS
5980 WARN_ON(register_filesystem(&cpuset_fs_type));
5986 static int __init cgroup_wq_init(void)
5989 * There isn't much point in executing destruction path in
5990 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5991 * Use 1 for @max_active.
5993 * We would prefer to do this in cgroup_init() above, but that
5994 * is called before init_workqueues(): so leave this until after.
5996 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5997 BUG_ON(!cgroup_destroy_wq);
6000 core_initcall(cgroup_wq_init);
6002 void cgroup_path_from_kernfs_id(const union kernfs_node_id *id,
6003 char *buf, size_t buflen)
6005 struct kernfs_node *kn;
6007 kn = kernfs_get_node_by_id(cgrp_dfl_root.kf_root, id);
6010 kernfs_path(kn, buf, buflen);
6015 * proc_cgroup_show()
6016 * - Print task's cgroup paths into seq_file, one line for each hierarchy
6017 * - Used for /proc/<pid>/cgroup.
6019 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
6020 struct pid *pid, struct task_struct *tsk)
6024 struct cgroup_root *root;
6027 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6031 mutex_lock(&cgroup_mutex);
6032 spin_lock_irq(&css_set_lock);
6034 for_each_root(root) {
6035 struct cgroup_subsys *ss;
6036 struct cgroup *cgrp;
6037 int ssid, count = 0;
6039 if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
6042 seq_printf(m, "%d:", root->hierarchy_id);
6043 if (root != &cgrp_dfl_root)
6044 for_each_subsys(ss, ssid)
6045 if (root->subsys_mask & (1 << ssid))
6046 seq_printf(m, "%s%s", count++ ? "," : "",
6048 if (strlen(root->name))
6049 seq_printf(m, "%sname=%s", count ? "," : "",
6053 cgrp = task_cgroup_from_root(tsk, root);
6056 * On traditional hierarchies, all zombie tasks show up as
6057 * belonging to the root cgroup. On the default hierarchy,
6058 * while a zombie doesn't show up in "cgroup.procs" and
6059 * thus can't be migrated, its /proc/PID/cgroup keeps
6060 * reporting the cgroup it belonged to before exiting. If
6061 * the cgroup is removed before the zombie is reaped,
6062 * " (deleted)" is appended to the cgroup path.
6064 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
6065 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
6066 current->nsproxy->cgroup_ns);
6067 if (retval >= PATH_MAX)
6068 retval = -ENAMETOOLONG;
6077 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
6078 seq_puts(m, " (deleted)\n");
6085 spin_unlock_irq(&css_set_lock);
6086 mutex_unlock(&cgroup_mutex);
6093 * cgroup_fork - initialize cgroup related fields during copy_process()
6094 * @child: pointer to task_struct of forking parent process.
6096 * A task is associated with the init_css_set until cgroup_post_fork()
6097 * attaches it to the parent's css_set. Empty cg_list indicates that
6098 * @child isn't holding reference to its css_set.
6100 void cgroup_fork(struct task_struct *child)
6102 RCU_INIT_POINTER(child->cgroups, &init_css_set);
6103 INIT_LIST_HEAD(&child->cg_list);
6107 * cgroup_can_fork - called on a new task before the process is exposed
6108 * @child: the task in question.
6110 * This calls the subsystem can_fork() callbacks. If the can_fork() callback
6111 * returns an error, the fork aborts with that error code. This allows for
6112 * a cgroup subsystem to conditionally allow or deny new forks.
6114 int cgroup_can_fork(struct task_struct *child)
6116 struct cgroup_subsys *ss;
6119 do_each_subsys_mask(ss, i, have_canfork_callback) {
6120 ret = ss->can_fork(child);
6123 } while_each_subsys_mask();
6128 for_each_subsys(ss, j) {
6131 if (ss->cancel_fork)
6132 ss->cancel_fork(child);
6139 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
6140 * @child: the task in question
6142 * This calls the cancel_fork() callbacks if a fork failed *after*
6143 * cgroup_can_fork() succeded.
6145 void cgroup_cancel_fork(struct task_struct *child)
6147 struct cgroup_subsys *ss;
6150 for_each_subsys(ss, i)
6151 if (ss->cancel_fork)
6152 ss->cancel_fork(child);
6156 * cgroup_post_fork - called on a new task after adding it to the task list
6157 * @child: the task in question
6159 * Adds the task to the list running through its css_set if necessary and
6160 * call the subsystem fork() callbacks. Has to be after the task is
6161 * visible on the task list in case we race with the first call to
6162 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
6165 void cgroup_post_fork(struct task_struct *child)
6167 struct cgroup_subsys *ss;
6171 * This may race against cgroup_enable_task_cg_lists(). As that
6172 * function sets use_task_css_set_links before grabbing
6173 * tasklist_lock and we just went through tasklist_lock to add
6174 * @child, it's guaranteed that either we see the set
6175 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
6176 * @child during its iteration.
6178 * If we won the race, @child is associated with %current's
6179 * css_set. Grabbing css_set_lock guarantees both that the
6180 * association is stable, and, on completion of the parent's
6181 * migration, @child is visible in the source of migration or
6182 * already in the destination cgroup. This guarantee is necessary
6183 * when implementing operations which need to migrate all tasks of
6184 * a cgroup to another.
6186 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
6187 * will remain in init_css_set. This is safe because all tasks are
6188 * in the init_css_set before cg_links is enabled and there's no
6189 * operation which transfers all tasks out of init_css_set.
6191 if (use_task_css_set_links) {
6192 struct css_set *cset;
6194 spin_lock_irq(&css_set_lock);
6195 cset = task_css_set(current);
6196 if (list_empty(&child->cg_list)) {
6199 css_set_move_task(child, NULL, cset, false);
6203 * If the cgroup has to be frozen, the new task has too.
6204 * Let's set the JOBCTL_TRAP_FREEZE jobctl bit to get
6205 * the task into the frozen state.
6207 if (unlikely(cgroup_task_freeze(child))) {
6208 spin_lock(&child->sighand->siglock);
6209 WARN_ON_ONCE(child->frozen);
6210 child->jobctl |= JOBCTL_TRAP_FREEZE;
6211 spin_unlock(&child->sighand->siglock);
6214 * Calling cgroup_update_frozen() isn't required here,
6215 * because it will be called anyway a bit later
6216 * from do_freezer_trap(). So we avoid cgroup's
6217 * transient switch from the frozen state and back.
6221 spin_unlock_irq(&css_set_lock);
6225 * Call ss->fork(). This must happen after @child is linked on
6226 * css_set; otherwise, @child might change state between ->fork()
6227 * and addition to css_set.
6229 do_each_subsys_mask(ss, i, have_fork_callback) {
6231 } while_each_subsys_mask();
6235 * cgroup_exit - detach cgroup from exiting task
6236 * @tsk: pointer to task_struct of exiting process
6238 * Description: Detach cgroup from @tsk and release it.
6240 * Note that cgroups marked notify_on_release force every task in
6241 * them to take the global cgroup_mutex mutex when exiting.
6242 * This could impact scaling on very large systems. Be reluctant to
6243 * use notify_on_release cgroups where very high task exit scaling
6244 * is required on large systems.
6246 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
6247 * call cgroup_exit() while the task is still competent to handle
6248 * notify_on_release(), then leave the task attached to the root cgroup in
6249 * each hierarchy for the remainder of its exit. No need to bother with
6250 * init_css_set refcnting. init_css_set never goes away and we can't race
6251 * with migration path - PF_EXITING is visible to migration path.
6253 void cgroup_exit(struct task_struct *tsk)
6255 struct cgroup_subsys *ss;
6256 struct css_set *cset;
6260 * Unlink from @tsk from its css_set. As migration path can't race
6261 * with us, we can check css_set and cg_list without synchronization.
6263 cset = task_css_set(tsk);
6265 if (!list_empty(&tsk->cg_list)) {
6266 spin_lock_irq(&css_set_lock);
6267 css_set_move_task(tsk, cset, NULL, false);
6268 list_add_tail(&tsk->cg_list, &cset->dying_tasks);
6271 WARN_ON_ONCE(cgroup_task_frozen(tsk));
6272 if (unlikely(cgroup_task_freeze(tsk)))
6273 cgroup_update_frozen(task_dfl_cgroup(tsk));
6275 spin_unlock_irq(&css_set_lock);
6280 /* see cgroup_post_fork() for details */
6281 do_each_subsys_mask(ss, i, have_exit_callback) {
6283 } while_each_subsys_mask();
6286 void cgroup_release(struct task_struct *task)
6288 struct cgroup_subsys *ss;
6291 do_each_subsys_mask(ss, ssid, have_release_callback) {
6293 } while_each_subsys_mask();
6295 if (use_task_css_set_links) {
6296 spin_lock_irq(&css_set_lock);
6297 css_set_skip_task_iters(task_css_set(task), task);
6298 list_del_init(&task->cg_list);
6299 spin_unlock_irq(&css_set_lock);
6303 void cgroup_free(struct task_struct *task)
6305 struct css_set *cset = task_css_set(task);
6309 static int __init cgroup_disable(char *str)
6311 struct cgroup_subsys *ss;
6315 while ((token = strsep(&str, ",")) != NULL) {
6319 for_each_subsys(ss, i) {
6320 if (strcmp(token, ss->name) &&
6321 strcmp(token, ss->legacy_name))
6324 static_branch_disable(cgroup_subsys_enabled_key[i]);
6325 pr_info("Disabling %s control group subsystem\n",
6331 __setup("cgroup_disable=", cgroup_disable);
6333 void __init __weak enable_debug_cgroup(void) { }
6335 static int __init enable_cgroup_debug(char *str)
6337 cgroup_debug = true;
6338 enable_debug_cgroup();
6341 __setup("cgroup_debug", enable_cgroup_debug);
6344 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
6345 * @dentry: directory dentry of interest
6346 * @ss: subsystem of interest
6348 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
6349 * to get the corresponding css and return it. If such css doesn't exist
6350 * or can't be pinned, an ERR_PTR value is returned.
6352 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
6353 struct cgroup_subsys *ss)
6355 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
6356 struct file_system_type *s_type = dentry->d_sb->s_type;
6357 struct cgroup_subsys_state *css = NULL;
6358 struct cgroup *cgrp;
6360 /* is @dentry a cgroup dir? */
6361 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
6362 !kn || kernfs_type(kn) != KERNFS_DIR)
6363 return ERR_PTR(-EBADF);
6368 * This path doesn't originate from kernfs and @kn could already
6369 * have been or be removed at any point. @kn->priv is RCU
6370 * protected for this access. See css_release_work_fn() for details.
6372 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6374 css = cgroup_css(cgrp, ss);
6376 if (!css || !css_tryget_online(css))
6377 css = ERR_PTR(-ENOENT);
6384 * css_from_id - lookup css by id
6385 * @id: the cgroup id
6386 * @ss: cgroup subsys to be looked into
6388 * Returns the css if there's valid one with @id, otherwise returns NULL.
6389 * Should be called under rcu_read_lock().
6391 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
6393 WARN_ON_ONCE(!rcu_read_lock_held());
6394 return idr_find(&ss->css_idr, id);
6398 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
6399 * @path: path on the default hierarchy
6401 * Find the cgroup at @path on the default hierarchy, increment its
6402 * reference count and return it. Returns pointer to the found cgroup on
6403 * success, ERR_PTR(-ENOENT) if @path doens't exist and ERR_PTR(-ENOTDIR)
6404 * if @path points to a non-directory.
6406 struct cgroup *cgroup_get_from_path(const char *path)
6408 struct kernfs_node *kn;
6409 struct cgroup *cgrp;
6411 mutex_lock(&cgroup_mutex);
6413 kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
6415 if (kernfs_type(kn) == KERNFS_DIR) {
6417 cgroup_get_live(cgrp);
6419 cgrp = ERR_PTR(-ENOTDIR);
6423 cgrp = ERR_PTR(-ENOENT);
6426 mutex_unlock(&cgroup_mutex);
6429 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
6432 * cgroup_get_from_fd - get a cgroup pointer from a fd
6433 * @fd: fd obtained by open(cgroup2_dir)
6435 * Find the cgroup from a fd which should be obtained
6436 * by opening a cgroup directory. Returns a pointer to the
6437 * cgroup on success. ERR_PTR is returned if the cgroup
6440 struct cgroup *cgroup_get_from_fd(int fd)
6442 struct cgroup_subsys_state *css;
6443 struct cgroup *cgrp;
6448 return ERR_PTR(-EBADF);
6450 css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
6453 return ERR_CAST(css);
6456 if (!cgroup_on_dfl(cgrp)) {
6458 return ERR_PTR(-EBADF);
6463 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
6465 static u64 power_of_ten(int power)
6474 * cgroup_parse_float - parse a floating number
6475 * @input: input string
6476 * @dec_shift: number of decimal digits to shift
6479 * Parse a decimal floating point number in @input and store the result in
6480 * @v with decimal point right shifted @dec_shift times. For example, if
6481 * @input is "12.3456" and @dec_shift is 3, *@v will be set to 12345.
6482 * Returns 0 on success, -errno otherwise.
6484 * There's nothing cgroup specific about this function except that it's
6485 * currently the only user.
6487 int cgroup_parse_float(const char *input, unsigned dec_shift, s64 *v)
6489 s64 whole, frac = 0;
6490 int fstart = 0, fend = 0, flen;
6492 if (!sscanf(input, "%lld.%n%lld%n", &whole, &fstart, &frac, &fend))
6497 flen = fend > fstart ? fend - fstart : 0;
6498 if (flen < dec_shift)
6499 frac *= power_of_ten(dec_shift - flen);
6501 frac = DIV_ROUND_CLOSEST_ULL(frac, power_of_ten(flen - dec_shift));
6503 *v = whole * power_of_ten(dec_shift) + frac;
6508 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
6509 * definition in cgroup-defs.h.
6511 #ifdef CONFIG_SOCK_CGROUP_DATA
6513 #if defined(CONFIG_CGROUP_NET_PRIO) || defined(CONFIG_CGROUP_NET_CLASSID)
6515 DEFINE_SPINLOCK(cgroup_sk_update_lock);
6516 static bool cgroup_sk_alloc_disabled __read_mostly;
6518 void cgroup_sk_alloc_disable(void)
6520 if (cgroup_sk_alloc_disabled)
6522 pr_info("cgroup: disabling cgroup2 socket matching due to net_prio or net_cls activation\n");
6523 cgroup_sk_alloc_disabled = true;
6528 #define cgroup_sk_alloc_disabled false
6532 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
6534 if (cgroup_sk_alloc_disabled) {
6535 skcd->no_refcnt = 1;
6539 /* Don't associate the sock with unrelated interrupted task's cgroup. */
6546 struct css_set *cset;
6548 cset = task_css_set(current);
6549 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
6550 skcd->val = (unsigned long)cset->dfl_cgrp;
6551 cgroup_bpf_get(cset->dfl_cgrp);
6560 void cgroup_sk_clone(struct sock_cgroup_data *skcd)
6563 if (skcd->no_refcnt)
6566 * We might be cloning a socket which is left in an empty
6567 * cgroup and the cgroup might have already been rmdir'd.
6568 * Don't use cgroup_get_live().
6570 cgroup_get(sock_cgroup_ptr(skcd));
6571 cgroup_bpf_get(sock_cgroup_ptr(skcd));
6575 void cgroup_sk_free(struct sock_cgroup_data *skcd)
6577 struct cgroup *cgrp = sock_cgroup_ptr(skcd);
6579 if (skcd->no_refcnt)
6581 cgroup_bpf_put(cgrp);
6585 #endif /* CONFIG_SOCK_CGROUP_DATA */
6587 #ifdef CONFIG_CGROUP_BPF
6588 int cgroup_bpf_attach(struct cgroup *cgrp, struct bpf_prog *prog,
6589 enum bpf_attach_type type, u32 flags)
6593 mutex_lock(&cgroup_mutex);
6594 ret = __cgroup_bpf_attach(cgrp, prog, type, flags);
6595 mutex_unlock(&cgroup_mutex);
6598 int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
6599 enum bpf_attach_type type, u32 flags)
6603 mutex_lock(&cgroup_mutex);
6604 ret = __cgroup_bpf_detach(cgrp, prog, type);
6605 mutex_unlock(&cgroup_mutex);
6608 int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
6609 union bpf_attr __user *uattr)
6613 mutex_lock(&cgroup_mutex);
6614 ret = __cgroup_bpf_query(cgrp, attr, uattr);
6615 mutex_unlock(&cgroup_mutex);
6618 #endif /* CONFIG_CGROUP_BPF */
6621 static ssize_t show_delegatable_files(struct cftype *files, char *buf,
6622 ssize_t size, const char *prefix)
6627 for (cft = files; cft && cft->name[0] != '\0'; cft++) {
6628 if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
6632 ret += snprintf(buf + ret, size - ret, "%s.", prefix);
6634 ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
6636 if (WARN_ON(ret >= size))
6643 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
6646 struct cgroup_subsys *ss;
6650 ret = show_delegatable_files(cgroup_base_files, buf, PAGE_SIZE - ret,
6653 for_each_subsys(ss, ssid)
6654 ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
6656 cgroup_subsys_name[ssid]);
6660 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
6662 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
6665 return snprintf(buf, PAGE_SIZE, "nsdelegate\nmemory_localevents\n");
6667 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
6669 static struct attribute *cgroup_sysfs_attrs[] = {
6670 &cgroup_delegate_attr.attr,
6671 &cgroup_features_attr.attr,
6675 static const struct attribute_group cgroup_sysfs_attr_group = {
6676 .attrs = cgroup_sysfs_attrs,
6680 static int __init cgroup_sysfs_init(void)
6682 return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
6684 subsys_initcall(cgroup_sysfs_init);
6686 #endif /* CONFIG_SYSFS */