2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31 #include "cgroup-internal.h"
33 #include <linux/cred.h>
34 #include <linux/errno.h>
35 #include <linux/init_task.h>
36 #include <linux/kernel.h>
37 #include <linux/magic.h>
38 #include <linux/mutex.h>
39 #include <linux/mount.h>
40 #include <linux/pagemap.h>
41 #include <linux/proc_fs.h>
42 #include <linux/rcupdate.h>
43 #include <linux/sched.h>
44 #include <linux/sched/task.h>
45 #include <linux/slab.h>
46 #include <linux/spinlock.h>
47 #include <linux/percpu-rwsem.h>
48 #include <linux/string.h>
49 #include <linux/hashtable.h>
50 #include <linux/idr.h>
51 #include <linux/kthread.h>
52 #include <linux/atomic.h>
53 #include <linux/cpuset.h>
54 #include <linux/proc_ns.h>
55 #include <linux/nsproxy.h>
56 #include <linux/file.h>
57 #include <linux/sched/cputime.h>
60 #define CREATE_TRACE_POINTS
61 #include <trace/events/cgroup.h>
63 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
65 /* let's not notify more than 100 times per second */
66 #define CGROUP_FILE_NOTIFY_MIN_INTV DIV_ROUND_UP(HZ, 100)
69 * cgroup_mutex is the master lock. Any modification to cgroup or its
70 * hierarchy must be performed while holding it.
72 * css_set_lock protects task->cgroups pointer, the list of css_set
73 * objects, and the chain of tasks off each css_set.
75 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
76 * cgroup.h can use them for lockdep annotations.
78 DEFINE_MUTEX(cgroup_mutex);
79 DEFINE_SPINLOCK(css_set_lock);
81 #ifdef CONFIG_PROVE_RCU
82 EXPORT_SYMBOL_GPL(cgroup_mutex);
83 EXPORT_SYMBOL_GPL(css_set_lock);
86 DEFINE_SPINLOCK(trace_cgroup_path_lock);
87 char trace_cgroup_path[TRACE_CGROUP_PATH_LEN];
90 * Protects cgroup_idr and css_idr so that IDs can be released without
91 * grabbing cgroup_mutex.
93 static DEFINE_SPINLOCK(cgroup_idr_lock);
96 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
97 * against file removal/re-creation across css hiding.
99 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
101 struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
103 #define cgroup_assert_mutex_or_rcu_locked() \
104 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
105 !lockdep_is_held(&cgroup_mutex), \
106 "cgroup_mutex or RCU read lock required");
109 * cgroup destruction makes heavy use of work items and there can be a lot
110 * of concurrent destructions. Use a separate workqueue so that cgroup
111 * destruction work items don't end up filling up max_active of system_wq
112 * which may lead to deadlock.
114 static struct workqueue_struct *cgroup_destroy_wq;
116 /* generate an array of cgroup subsystem pointers */
117 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
118 struct cgroup_subsys *cgroup_subsys[] = {
119 #include <linux/cgroup_subsys.h>
123 /* array of cgroup subsystem names */
124 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
125 static const char *cgroup_subsys_name[] = {
126 #include <linux/cgroup_subsys.h>
130 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
132 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
133 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
134 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
135 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
136 #include <linux/cgroup_subsys.h>
139 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
140 static struct static_key_true *cgroup_subsys_enabled_key[] = {
141 #include <linux/cgroup_subsys.h>
145 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
146 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
147 #include <linux/cgroup_subsys.h>
151 static DEFINE_PER_CPU(struct cgroup_rstat_cpu, cgrp_dfl_root_rstat_cpu);
154 * The default hierarchy, reserved for the subsystems that are otherwise
155 * unattached - it never has more than a single cgroup, and all tasks are
156 * part of that cgroup.
158 struct cgroup_root cgrp_dfl_root = { .cgrp.rstat_cpu = &cgrp_dfl_root_rstat_cpu };
159 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
162 * The default hierarchy always exists but is hidden until mounted for the
163 * first time. This is for backward compatibility.
165 static bool cgrp_dfl_visible;
167 /* some controllers are not supported in the default hierarchy */
168 static u16 cgrp_dfl_inhibit_ss_mask;
170 /* some controllers are implicitly enabled on the default hierarchy */
171 static u16 cgrp_dfl_implicit_ss_mask;
173 /* some controllers can be threaded on the default hierarchy */
174 static u16 cgrp_dfl_threaded_ss_mask;
176 /* The list of hierarchy roots */
177 LIST_HEAD(cgroup_roots);
178 static int cgroup_root_count;
180 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
181 static DEFINE_IDR(cgroup_hierarchy_idr);
184 * Assign a monotonically increasing serial number to csses. It guarantees
185 * cgroups with bigger numbers are newer than those with smaller numbers.
186 * Also, as csses are always appended to the parent's ->children list, it
187 * guarantees that sibling csses are always sorted in the ascending serial
188 * number order on the list. Protected by cgroup_mutex.
190 static u64 css_serial_nr_next = 1;
193 * These bitmasks identify subsystems with specific features to avoid
194 * having to do iterative checks repeatedly.
196 static u16 have_fork_callback __read_mostly;
197 static u16 have_exit_callback __read_mostly;
198 static u16 have_release_callback __read_mostly;
199 static u16 have_canfork_callback __read_mostly;
201 /* cgroup namespace for init task */
202 struct cgroup_namespace init_cgroup_ns = {
203 .count = REFCOUNT_INIT(2),
204 .user_ns = &init_user_ns,
205 .ns.ops = &cgroupns_operations,
206 .ns.inum = PROC_CGROUP_INIT_INO,
207 .root_cset = &init_css_set,
210 static struct file_system_type cgroup2_fs_type;
211 static struct cftype cgroup_base_files[];
213 static int cgroup_apply_control(struct cgroup *cgrp);
214 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
215 static void css_task_iter_skip(struct css_task_iter *it,
216 struct task_struct *task);
217 static int cgroup_destroy_locked(struct cgroup *cgrp);
218 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
219 struct cgroup_subsys *ss);
220 static void css_release(struct percpu_ref *ref);
221 static void kill_css(struct cgroup_subsys_state *css);
222 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
223 struct cgroup *cgrp, struct cftype cfts[],
227 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
228 * @ssid: subsys ID of interest
230 * cgroup_subsys_enabled() can only be used with literal subsys names which
231 * is fine for individual subsystems but unsuitable for cgroup core. This
232 * is slower static_key_enabled() based test indexed by @ssid.
234 bool cgroup_ssid_enabled(int ssid)
236 if (CGROUP_SUBSYS_COUNT == 0)
239 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
243 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
244 * @cgrp: the cgroup of interest
246 * The default hierarchy is the v2 interface of cgroup and this function
247 * can be used to test whether a cgroup is on the default hierarchy for
248 * cases where a subsystem should behave differnetly depending on the
251 * The set of behaviors which change on the default hierarchy are still
252 * being determined and the mount option is prefixed with __DEVEL__.
254 * List of changed behaviors:
256 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
257 * and "name" are disallowed.
259 * - When mounting an existing superblock, mount options should match.
261 * - Remount is disallowed.
263 * - rename(2) is disallowed.
265 * - "tasks" is removed. Everything should be at process granularity. Use
266 * "cgroup.procs" instead.
268 * - "cgroup.procs" is not sorted. pids will be unique unless they got
269 * recycled inbetween reads.
271 * - "release_agent" and "notify_on_release" are removed. Replacement
272 * notification mechanism will be implemented.
274 * - "cgroup.clone_children" is removed.
276 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
277 * and its descendants contain no task; otherwise, 1. The file also
278 * generates kernfs notification which can be monitored through poll and
279 * [di]notify when the value of the file changes.
281 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
282 * take masks of ancestors with non-empty cpus/mems, instead of being
283 * moved to an ancestor.
285 * - cpuset: a task can be moved into an empty cpuset, and again it takes
286 * masks of ancestors.
288 * - memcg: use_hierarchy is on by default and the cgroup file for the flag
291 * - blkcg: blk-throttle becomes properly hierarchical.
293 * - debug: disallowed on the default hierarchy.
295 bool cgroup_on_dfl(const struct cgroup *cgrp)
297 return cgrp->root == &cgrp_dfl_root;
300 /* IDR wrappers which synchronize using cgroup_idr_lock */
301 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
306 idr_preload(gfp_mask);
307 spin_lock_bh(&cgroup_idr_lock);
308 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
309 spin_unlock_bh(&cgroup_idr_lock);
314 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
318 spin_lock_bh(&cgroup_idr_lock);
319 ret = idr_replace(idr, ptr, id);
320 spin_unlock_bh(&cgroup_idr_lock);
324 static void cgroup_idr_remove(struct idr *idr, int id)
326 spin_lock_bh(&cgroup_idr_lock);
328 spin_unlock_bh(&cgroup_idr_lock);
331 static bool cgroup_has_tasks(struct cgroup *cgrp)
333 return cgrp->nr_populated_csets;
336 bool cgroup_is_threaded(struct cgroup *cgrp)
338 return cgrp->dom_cgrp != cgrp;
341 /* can @cgrp host both domain and threaded children? */
342 static bool cgroup_is_mixable(struct cgroup *cgrp)
345 * Root isn't under domain level resource control exempting it from
346 * the no-internal-process constraint, so it can serve as a thread
347 * root and a parent of resource domains at the same time.
349 return !cgroup_parent(cgrp);
352 /* can @cgrp become a thread root? should always be true for a thread root */
353 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
355 /* mixables don't care */
356 if (cgroup_is_mixable(cgrp))
359 /* domain roots can't be nested under threaded */
360 if (cgroup_is_threaded(cgrp))
363 /* can only have either domain or threaded children */
364 if (cgrp->nr_populated_domain_children)
367 /* and no domain controllers can be enabled */
368 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
374 /* is @cgrp root of a threaded subtree? */
375 bool cgroup_is_thread_root(struct cgroup *cgrp)
377 /* thread root should be a domain */
378 if (cgroup_is_threaded(cgrp))
381 /* a domain w/ threaded children is a thread root */
382 if (cgrp->nr_threaded_children)
386 * A domain which has tasks and explicit threaded controllers
387 * enabled is a thread root.
389 if (cgroup_has_tasks(cgrp) &&
390 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
396 /* a domain which isn't connected to the root w/o brekage can't be used */
397 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
399 /* the cgroup itself can be a thread root */
400 if (cgroup_is_threaded(cgrp))
403 /* but the ancestors can't be unless mixable */
404 while ((cgrp = cgroup_parent(cgrp))) {
405 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
407 if (cgroup_is_threaded(cgrp))
414 /* subsystems visibly enabled on a cgroup */
415 static u16 cgroup_control(struct cgroup *cgrp)
417 struct cgroup *parent = cgroup_parent(cgrp);
418 u16 root_ss_mask = cgrp->root->subsys_mask;
421 u16 ss_mask = parent->subtree_control;
423 /* threaded cgroups can only have threaded controllers */
424 if (cgroup_is_threaded(cgrp))
425 ss_mask &= cgrp_dfl_threaded_ss_mask;
429 if (cgroup_on_dfl(cgrp))
430 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
431 cgrp_dfl_implicit_ss_mask);
435 /* subsystems enabled on a cgroup */
436 static u16 cgroup_ss_mask(struct cgroup *cgrp)
438 struct cgroup *parent = cgroup_parent(cgrp);
441 u16 ss_mask = parent->subtree_ss_mask;
443 /* threaded cgroups can only have threaded controllers */
444 if (cgroup_is_threaded(cgrp))
445 ss_mask &= cgrp_dfl_threaded_ss_mask;
449 return cgrp->root->subsys_mask;
453 * cgroup_css - obtain a cgroup's css for the specified subsystem
454 * @cgrp: the cgroup of interest
455 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
457 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
458 * function must be called either under cgroup_mutex or rcu_read_lock() and
459 * the caller is responsible for pinning the returned css if it wants to
460 * keep accessing it outside the said locks. This function may return
461 * %NULL if @cgrp doesn't have @subsys_id enabled.
463 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
464 struct cgroup_subsys *ss)
467 return rcu_dereference_check(cgrp->subsys[ss->id],
468 lockdep_is_held(&cgroup_mutex));
474 * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
475 * @cgrp: the cgroup of interest
476 * @ss: the subsystem of interest
478 * Find and get @cgrp's css assocaited with @ss. If the css doesn't exist
479 * or is offline, %NULL is returned.
481 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
482 struct cgroup_subsys *ss)
484 struct cgroup_subsys_state *css;
487 css = cgroup_css(cgrp, ss);
488 if (!css || !css_tryget_online(css))
496 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
497 * @cgrp: the cgroup of interest
498 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
500 * Similar to cgroup_css() but returns the effective css, which is defined
501 * as the matching css of the nearest ancestor including self which has @ss
502 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
503 * function is guaranteed to return non-NULL css.
505 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
506 struct cgroup_subsys *ss)
508 lockdep_assert_held(&cgroup_mutex);
514 * This function is used while updating css associations and thus
515 * can't test the csses directly. Test ss_mask.
517 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
518 cgrp = cgroup_parent(cgrp);
523 return cgroup_css(cgrp, ss);
527 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
528 * @cgrp: the cgroup of interest
529 * @ss: the subsystem of interest
531 * Find and get the effective css of @cgrp for @ss. The effective css is
532 * defined as the matching css of the nearest ancestor including self which
533 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
534 * the root css is returned, so this function always returns a valid css.
535 * The returned css must be put using css_put().
537 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
538 struct cgroup_subsys *ss)
540 struct cgroup_subsys_state *css;
545 css = cgroup_css(cgrp, ss);
547 if (css && css_tryget_online(css))
549 cgrp = cgroup_parent(cgrp);
552 css = init_css_set.subsys[ss->id];
559 static void cgroup_get_live(struct cgroup *cgrp)
561 WARN_ON_ONCE(cgroup_is_dead(cgrp));
562 css_get(&cgrp->self);
565 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
567 struct cgroup *cgrp = of->kn->parent->priv;
568 struct cftype *cft = of_cft(of);
571 * This is open and unprotected implementation of cgroup_css().
572 * seq_css() is only called from a kernfs file operation which has
573 * an active reference on the file. Because all the subsystem
574 * files are drained before a css is disassociated with a cgroup,
575 * the matching css from the cgroup's subsys table is guaranteed to
576 * be and stay valid until the enclosing operation is complete.
579 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
583 EXPORT_SYMBOL_GPL(of_css);
586 * for_each_css - iterate all css's of a cgroup
587 * @css: the iteration cursor
588 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
589 * @cgrp: the target cgroup to iterate css's of
591 * Should be called under cgroup_[tree_]mutex.
593 #define for_each_css(css, ssid, cgrp) \
594 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
595 if (!((css) = rcu_dereference_check( \
596 (cgrp)->subsys[(ssid)], \
597 lockdep_is_held(&cgroup_mutex)))) { } \
601 * for_each_e_css - iterate all effective css's of a cgroup
602 * @css: the iteration cursor
603 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
604 * @cgrp: the target cgroup to iterate css's of
606 * Should be called under cgroup_[tree_]mutex.
608 #define for_each_e_css(css, ssid, cgrp) \
609 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
610 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
615 * do_each_subsys_mask - filter for_each_subsys with a bitmask
616 * @ss: the iteration cursor
617 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
618 * @ss_mask: the bitmask
620 * The block will only run for cases where the ssid-th bit (1 << ssid) of
623 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
624 unsigned long __ss_mask = (ss_mask); \
625 if (!CGROUP_SUBSYS_COUNT) { /* to avoid spurious gcc warning */ \
629 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
630 (ss) = cgroup_subsys[ssid]; \
633 #define while_each_subsys_mask() \
638 /* iterate over child cgrps, lock should be held throughout iteration */
639 #define cgroup_for_each_live_child(child, cgrp) \
640 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
641 if (({ lockdep_assert_held(&cgroup_mutex); \
642 cgroup_is_dead(child); })) \
646 /* walk live descendants in preorder */
647 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
648 css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
649 if (({ lockdep_assert_held(&cgroup_mutex); \
650 (dsct) = (d_css)->cgroup; \
651 cgroup_is_dead(dsct); })) \
655 /* walk live descendants in postorder */
656 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
657 css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
658 if (({ lockdep_assert_held(&cgroup_mutex); \
659 (dsct) = (d_css)->cgroup; \
660 cgroup_is_dead(dsct); })) \
665 * The default css_set - used by init and its children prior to any
666 * hierarchies being mounted. It contains a pointer to the root state
667 * for each subsystem. Also used to anchor the list of css_sets. Not
668 * reference-counted, to improve performance when child cgroups
669 * haven't been created.
671 struct css_set init_css_set = {
672 .refcount = REFCOUNT_INIT(1),
673 .dom_cset = &init_css_set,
674 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
675 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
676 .dying_tasks = LIST_HEAD_INIT(init_css_set.dying_tasks),
677 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
678 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
679 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
680 .mg_src_preload_node = LIST_HEAD_INIT(init_css_set.mg_src_preload_node),
681 .mg_dst_preload_node = LIST_HEAD_INIT(init_css_set.mg_dst_preload_node),
682 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
685 * The following field is re-initialized when this cset gets linked
686 * in cgroup_init(). However, let's initialize the field
687 * statically too so that the default cgroup can be accessed safely
690 .dfl_cgrp = &cgrp_dfl_root.cgrp,
693 static int css_set_count = 1; /* 1 for init_css_set */
695 static bool css_set_threaded(struct css_set *cset)
697 return cset->dom_cset != cset;
701 * css_set_populated - does a css_set contain any tasks?
702 * @cset: target css_set
704 * css_set_populated() should be the same as !!cset->nr_tasks at steady
705 * state. However, css_set_populated() can be called while a task is being
706 * added to or removed from the linked list before the nr_tasks is
707 * properly updated. Hence, we can't just look at ->nr_tasks here.
709 static bool css_set_populated(struct css_set *cset)
711 lockdep_assert_held(&css_set_lock);
713 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
717 * cgroup_update_populated - update the populated count of a cgroup
718 * @cgrp: the target cgroup
719 * @populated: inc or dec populated count
721 * One of the css_sets associated with @cgrp is either getting its first
722 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
723 * count is propagated towards root so that a given cgroup's
724 * nr_populated_children is zero iff none of its descendants contain any
727 * @cgrp's interface file "cgroup.populated" is zero if both
728 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
729 * 1 otherwise. When the sum changes from or to zero, userland is notified
730 * that the content of the interface file has changed. This can be used to
731 * detect when @cgrp and its descendants become populated or empty.
733 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
735 struct cgroup *child = NULL;
736 int adj = populated ? 1 : -1;
738 lockdep_assert_held(&css_set_lock);
741 bool was_populated = cgroup_is_populated(cgrp);
744 cgrp->nr_populated_csets += adj;
746 if (cgroup_is_threaded(child))
747 cgrp->nr_populated_threaded_children += adj;
749 cgrp->nr_populated_domain_children += adj;
752 if (was_populated == cgroup_is_populated(cgrp))
755 cgroup1_check_for_release(cgrp);
756 cgroup_file_notify(&cgrp->events_file);
759 cgrp = cgroup_parent(cgrp);
764 * css_set_update_populated - update populated state of a css_set
765 * @cset: target css_set
766 * @populated: whether @cset is populated or depopulated
768 * @cset is either getting the first task or losing the last. Update the
769 * populated counters of all associated cgroups accordingly.
771 static void css_set_update_populated(struct css_set *cset, bool populated)
773 struct cgrp_cset_link *link;
775 lockdep_assert_held(&css_set_lock);
777 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
778 cgroup_update_populated(link->cgrp, populated);
782 * @task is leaving, advance task iterators which are pointing to it so
783 * that they can resume at the next position. Advancing an iterator might
784 * remove it from the list, use safe walk. See css_task_iter_skip() for
787 static void css_set_skip_task_iters(struct css_set *cset,
788 struct task_struct *task)
790 struct css_task_iter *it, *pos;
792 list_for_each_entry_safe(it, pos, &cset->task_iters, iters_node)
793 css_task_iter_skip(it, task);
797 * css_set_move_task - move a task from one css_set to another
798 * @task: task being moved
799 * @from_cset: css_set @task currently belongs to (may be NULL)
800 * @to_cset: new css_set @task is being moved to (may be NULL)
801 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
803 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
804 * css_set, @from_cset can be NULL. If @task is being disassociated
805 * instead of moved, @to_cset can be NULL.
807 * This function automatically handles populated counter updates and
808 * css_task_iter adjustments but the caller is responsible for managing
809 * @from_cset and @to_cset's reference counts.
811 static void css_set_move_task(struct task_struct *task,
812 struct css_set *from_cset, struct css_set *to_cset,
815 lockdep_assert_held(&css_set_lock);
817 if (to_cset && !css_set_populated(to_cset))
818 css_set_update_populated(to_cset, true);
821 WARN_ON_ONCE(list_empty(&task->cg_list));
823 css_set_skip_task_iters(from_cset, task);
824 list_del_init(&task->cg_list);
825 if (!css_set_populated(from_cset))
826 css_set_update_populated(from_cset, false);
828 WARN_ON_ONCE(!list_empty(&task->cg_list));
833 * We are synchronized through cgroup_threadgroup_rwsem
834 * against PF_EXITING setting such that we can't race
835 * against cgroup_exit() changing the css_set to
836 * init_css_set and dropping the old one.
838 WARN_ON_ONCE(task->flags & PF_EXITING);
840 rcu_assign_pointer(task->cgroups, to_cset);
841 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
847 * hash table for cgroup groups. This improves the performance to find
848 * an existing css_set. This hash doesn't (currently) take into
849 * account cgroups in empty hierarchies.
851 #define CSS_SET_HASH_BITS 7
852 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
854 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
856 unsigned long key = 0UL;
857 struct cgroup_subsys *ss;
860 for_each_subsys(ss, i)
861 key += (unsigned long)css[i];
862 key = (key >> 16) ^ key;
867 void put_css_set_locked(struct css_set *cset)
869 struct cgrp_cset_link *link, *tmp_link;
870 struct cgroup_subsys *ss;
873 lockdep_assert_held(&css_set_lock);
875 if (!refcount_dec_and_test(&cset->refcount))
878 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
880 /* This css_set is dead. unlink it and release cgroup and css refs */
881 for_each_subsys(ss, ssid) {
882 list_del(&cset->e_cset_node[ssid]);
883 css_put(cset->subsys[ssid]);
885 hash_del(&cset->hlist);
888 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
889 list_del(&link->cset_link);
890 list_del(&link->cgrp_link);
891 if (cgroup_parent(link->cgrp))
892 cgroup_put(link->cgrp);
896 if (css_set_threaded(cset)) {
897 list_del(&cset->threaded_csets_node);
898 put_css_set_locked(cset->dom_cset);
901 kfree_rcu(cset, rcu_head);
905 * compare_css_sets - helper function for find_existing_css_set().
906 * @cset: candidate css_set being tested
907 * @old_cset: existing css_set for a task
908 * @new_cgrp: cgroup that's being entered by the task
909 * @template: desired set of css pointers in css_set (pre-calculated)
911 * Returns true if "cset" matches "old_cset" except for the hierarchy
912 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
914 static bool compare_css_sets(struct css_set *cset,
915 struct css_set *old_cset,
916 struct cgroup *new_cgrp,
917 struct cgroup_subsys_state *template[])
919 struct cgroup *new_dfl_cgrp;
920 struct list_head *l1, *l2;
923 * On the default hierarchy, there can be csets which are
924 * associated with the same set of cgroups but different csses.
925 * Let's first ensure that csses match.
927 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
931 /* @cset's domain should match the default cgroup's */
932 if (cgroup_on_dfl(new_cgrp))
933 new_dfl_cgrp = new_cgrp;
935 new_dfl_cgrp = old_cset->dfl_cgrp;
937 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
941 * Compare cgroup pointers in order to distinguish between
942 * different cgroups in hierarchies. As different cgroups may
943 * share the same effective css, this comparison is always
946 l1 = &cset->cgrp_links;
947 l2 = &old_cset->cgrp_links;
949 struct cgrp_cset_link *link1, *link2;
950 struct cgroup *cgrp1, *cgrp2;
954 /* See if we reached the end - both lists are equal length. */
955 if (l1 == &cset->cgrp_links) {
956 BUG_ON(l2 != &old_cset->cgrp_links);
959 BUG_ON(l2 == &old_cset->cgrp_links);
961 /* Locate the cgroups associated with these links. */
962 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
963 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
966 /* Hierarchies should be linked in the same order. */
967 BUG_ON(cgrp1->root != cgrp2->root);
970 * If this hierarchy is the hierarchy of the cgroup
971 * that's changing, then we need to check that this
972 * css_set points to the new cgroup; if it's any other
973 * hierarchy, then this css_set should point to the
974 * same cgroup as the old css_set.
976 if (cgrp1->root == new_cgrp->root) {
977 if (cgrp1 != new_cgrp)
988 * find_existing_css_set - init css array and find the matching css_set
989 * @old_cset: the css_set that we're using before the cgroup transition
990 * @cgrp: the cgroup that we're moving into
991 * @template: out param for the new set of csses, should be clear on entry
993 static struct css_set *find_existing_css_set(struct css_set *old_cset,
995 struct cgroup_subsys_state *template[])
997 struct cgroup_root *root = cgrp->root;
998 struct cgroup_subsys *ss;
999 struct css_set *cset;
1004 * Build the set of subsystem state objects that we want to see in the
1005 * new css_set. while subsystems can change globally, the entries here
1006 * won't change, so no need for locking.
1008 for_each_subsys(ss, i) {
1009 if (root->subsys_mask & (1UL << i)) {
1011 * @ss is in this hierarchy, so we want the
1012 * effective css from @cgrp.
1014 template[i] = cgroup_e_css(cgrp, ss);
1017 * @ss is not in this hierarchy, so we don't want
1018 * to change the css.
1020 template[i] = old_cset->subsys[i];
1024 key = css_set_hash(template);
1025 hash_for_each_possible(css_set_table, cset, hlist, key) {
1026 if (!compare_css_sets(cset, old_cset, cgrp, template))
1029 /* This css_set matches what we need */
1033 /* No existing cgroup group matched */
1037 static void free_cgrp_cset_links(struct list_head *links_to_free)
1039 struct cgrp_cset_link *link, *tmp_link;
1041 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1042 list_del(&link->cset_link);
1048 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1049 * @count: the number of links to allocate
1050 * @tmp_links: list_head the allocated links are put on
1052 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1053 * through ->cset_link. Returns 0 on success or -errno.
1055 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1057 struct cgrp_cset_link *link;
1060 INIT_LIST_HEAD(tmp_links);
1062 for (i = 0; i < count; i++) {
1063 link = kzalloc(sizeof(*link), GFP_KERNEL);
1065 free_cgrp_cset_links(tmp_links);
1068 list_add(&link->cset_link, tmp_links);
1074 * link_css_set - a helper function to link a css_set to a cgroup
1075 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1076 * @cset: the css_set to be linked
1077 * @cgrp: the destination cgroup
1079 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1080 struct cgroup *cgrp)
1082 struct cgrp_cset_link *link;
1084 BUG_ON(list_empty(tmp_links));
1086 if (cgroup_on_dfl(cgrp))
1087 cset->dfl_cgrp = cgrp;
1089 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1094 * Always add links to the tail of the lists so that the lists are
1095 * in choronological order.
1097 list_move_tail(&link->cset_link, &cgrp->cset_links);
1098 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1100 if (cgroup_parent(cgrp))
1101 cgroup_get_live(cgrp);
1105 * find_css_set - return a new css_set with one cgroup updated
1106 * @old_cset: the baseline css_set
1107 * @cgrp: the cgroup to be updated
1109 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1110 * substituted into the appropriate hierarchy.
1112 static struct css_set *find_css_set(struct css_set *old_cset,
1113 struct cgroup *cgrp)
1115 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1116 struct css_set *cset;
1117 struct list_head tmp_links;
1118 struct cgrp_cset_link *link;
1119 struct cgroup_subsys *ss;
1123 lockdep_assert_held(&cgroup_mutex);
1125 /* First see if we already have a cgroup group that matches
1126 * the desired set */
1127 spin_lock_irq(&css_set_lock);
1128 cset = find_existing_css_set(old_cset, cgrp, template);
1131 spin_unlock_irq(&css_set_lock);
1136 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1140 /* Allocate all the cgrp_cset_link objects that we'll need */
1141 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1146 refcount_set(&cset->refcount, 1);
1147 cset->dom_cset = cset;
1148 INIT_LIST_HEAD(&cset->tasks);
1149 INIT_LIST_HEAD(&cset->mg_tasks);
1150 INIT_LIST_HEAD(&cset->dying_tasks);
1151 INIT_LIST_HEAD(&cset->task_iters);
1152 INIT_LIST_HEAD(&cset->threaded_csets);
1153 INIT_HLIST_NODE(&cset->hlist);
1154 INIT_LIST_HEAD(&cset->cgrp_links);
1155 INIT_LIST_HEAD(&cset->mg_src_preload_node);
1156 INIT_LIST_HEAD(&cset->mg_dst_preload_node);
1157 INIT_LIST_HEAD(&cset->mg_node);
1159 /* Copy the set of subsystem state objects generated in
1160 * find_existing_css_set() */
1161 memcpy(cset->subsys, template, sizeof(cset->subsys));
1163 spin_lock_irq(&css_set_lock);
1164 /* Add reference counts and links from the new css_set. */
1165 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1166 struct cgroup *c = link->cgrp;
1168 if (c->root == cgrp->root)
1170 link_css_set(&tmp_links, cset, c);
1173 BUG_ON(!list_empty(&tmp_links));
1177 /* Add @cset to the hash table */
1178 key = css_set_hash(cset->subsys);
1179 hash_add(css_set_table, &cset->hlist, key);
1181 for_each_subsys(ss, ssid) {
1182 struct cgroup_subsys_state *css = cset->subsys[ssid];
1184 list_add_tail(&cset->e_cset_node[ssid],
1185 &css->cgroup->e_csets[ssid]);
1189 spin_unlock_irq(&css_set_lock);
1192 * If @cset should be threaded, look up the matching dom_cset and
1193 * link them up. We first fully initialize @cset then look for the
1194 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1195 * to stay empty until we return.
1197 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1198 struct css_set *dcset;
1200 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1206 spin_lock_irq(&css_set_lock);
1207 cset->dom_cset = dcset;
1208 list_add_tail(&cset->threaded_csets_node,
1209 &dcset->threaded_csets);
1210 spin_unlock_irq(&css_set_lock);
1216 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1218 struct cgroup *root_cgrp = kf_root->kn->priv;
1220 return root_cgrp->root;
1223 static int cgroup_init_root_id(struct cgroup_root *root)
1227 lockdep_assert_held(&cgroup_mutex);
1229 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1233 root->hierarchy_id = id;
1237 static void cgroup_exit_root_id(struct cgroup_root *root)
1239 lockdep_assert_held(&cgroup_mutex);
1241 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1244 void cgroup_free_root(struct cgroup_root *root)
1247 idr_destroy(&root->cgroup_idr);
1252 static void cgroup_destroy_root(struct cgroup_root *root)
1254 struct cgroup *cgrp = &root->cgrp;
1255 struct cgrp_cset_link *link, *tmp_link;
1257 trace_cgroup_destroy_root(root);
1259 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1261 BUG_ON(atomic_read(&root->nr_cgrps));
1262 BUG_ON(!list_empty(&cgrp->self.children));
1264 /* Rebind all subsystems back to the default hierarchy */
1265 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1268 * Release all the links from cset_links to this hierarchy's
1271 spin_lock_irq(&css_set_lock);
1273 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1274 list_del(&link->cset_link);
1275 list_del(&link->cgrp_link);
1279 spin_unlock_irq(&css_set_lock);
1281 if (!list_empty(&root->root_list)) {
1282 list_del(&root->root_list);
1283 cgroup_root_count--;
1286 cgroup_exit_root_id(root);
1288 mutex_unlock(&cgroup_mutex);
1290 kernfs_destroy_root(root->kf_root);
1291 cgroup_free_root(root);
1295 * look up cgroup associated with current task's cgroup namespace on the
1296 * specified hierarchy
1298 static struct cgroup *
1299 current_cgns_cgroup_from_root(struct cgroup_root *root)
1301 struct cgroup *res = NULL;
1302 struct css_set *cset;
1304 lockdep_assert_held(&css_set_lock);
1308 cset = current->nsproxy->cgroup_ns->root_cset;
1309 if (cset == &init_css_set) {
1312 struct cgrp_cset_link *link;
1314 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1315 struct cgroup *c = link->cgrp;
1317 if (c->root == root) {
1329 /* look up cgroup associated with given css_set on the specified hierarchy */
1330 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1331 struct cgroup_root *root)
1333 struct cgroup *res = NULL;
1335 lockdep_assert_held(&cgroup_mutex);
1336 lockdep_assert_held(&css_set_lock);
1338 if (cset == &init_css_set) {
1340 } else if (root == &cgrp_dfl_root) {
1341 res = cset->dfl_cgrp;
1343 struct cgrp_cset_link *link;
1345 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1346 struct cgroup *c = link->cgrp;
1348 if (c->root == root) {
1360 * Return the cgroup for "task" from the given hierarchy. Must be
1361 * called with cgroup_mutex and css_set_lock held.
1363 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1364 struct cgroup_root *root)
1367 * No need to lock the task - since we hold cgroup_mutex the
1368 * task can't change groups, so the only thing that can happen
1369 * is that it exits and its css is set back to init_css_set.
1371 return cset_cgroup_from_root(task_css_set(task), root);
1375 * A task must hold cgroup_mutex to modify cgroups.
1377 * Any task can increment and decrement the count field without lock.
1378 * So in general, code holding cgroup_mutex can't rely on the count
1379 * field not changing. However, if the count goes to zero, then only
1380 * cgroup_attach_task() can increment it again. Because a count of zero
1381 * means that no tasks are currently attached, therefore there is no
1382 * way a task attached to that cgroup can fork (the other way to
1383 * increment the count). So code holding cgroup_mutex can safely
1384 * assume that if the count is zero, it will stay zero. Similarly, if
1385 * a task holds cgroup_mutex on a cgroup with zero count, it
1386 * knows that the cgroup won't be removed, as cgroup_rmdir()
1389 * A cgroup can only be deleted if both its 'count' of using tasks
1390 * is zero, and its list of 'children' cgroups is empty. Since all
1391 * tasks in the system use _some_ cgroup, and since there is always at
1392 * least one task in the system (init, pid == 1), therefore, root cgroup
1393 * always has either children cgroups and/or using tasks. So we don't
1394 * need a special hack to ensure that root cgroup cannot be deleted.
1396 * P.S. One more locking exception. RCU is used to guard the
1397 * update of a tasks cgroup pointer by cgroup_attach_task()
1400 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1402 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1405 struct cgroup_subsys *ss = cft->ss;
1407 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1408 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1409 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1410 cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1413 strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1418 * cgroup_file_mode - deduce file mode of a control file
1419 * @cft: the control file in question
1421 * S_IRUGO for read, S_IWUSR for write.
1423 static umode_t cgroup_file_mode(const struct cftype *cft)
1427 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1430 if (cft->write_u64 || cft->write_s64 || cft->write) {
1431 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1441 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1442 * @subtree_control: the new subtree_control mask to consider
1443 * @this_ss_mask: available subsystems
1445 * On the default hierarchy, a subsystem may request other subsystems to be
1446 * enabled together through its ->depends_on mask. In such cases, more
1447 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1449 * This function calculates which subsystems need to be enabled if
1450 * @subtree_control is to be applied while restricted to @this_ss_mask.
1452 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1454 u16 cur_ss_mask = subtree_control;
1455 struct cgroup_subsys *ss;
1458 lockdep_assert_held(&cgroup_mutex);
1460 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1463 u16 new_ss_mask = cur_ss_mask;
1465 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1466 new_ss_mask |= ss->depends_on;
1467 } while_each_subsys_mask();
1470 * Mask out subsystems which aren't available. This can
1471 * happen only if some depended-upon subsystems were bound
1472 * to non-default hierarchies.
1474 new_ss_mask &= this_ss_mask;
1476 if (new_ss_mask == cur_ss_mask)
1478 cur_ss_mask = new_ss_mask;
1485 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1486 * @kn: the kernfs_node being serviced
1488 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1489 * the method finishes if locking succeeded. Note that once this function
1490 * returns the cgroup returned by cgroup_kn_lock_live() may become
1491 * inaccessible any time. If the caller intends to continue to access the
1492 * cgroup, it should pin it before invoking this function.
1494 void cgroup_kn_unlock(struct kernfs_node *kn)
1496 struct cgroup *cgrp;
1498 if (kernfs_type(kn) == KERNFS_DIR)
1501 cgrp = kn->parent->priv;
1503 mutex_unlock(&cgroup_mutex);
1505 kernfs_unbreak_active_protection(kn);
1510 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1511 * @kn: the kernfs_node being serviced
1512 * @drain_offline: perform offline draining on the cgroup
1514 * This helper is to be used by a cgroup kernfs method currently servicing
1515 * @kn. It breaks the active protection, performs cgroup locking and
1516 * verifies that the associated cgroup is alive. Returns the cgroup if
1517 * alive; otherwise, %NULL. A successful return should be undone by a
1518 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1519 * cgroup is drained of offlining csses before return.
1521 * Any cgroup kernfs method implementation which requires locking the
1522 * associated cgroup should use this helper. It avoids nesting cgroup
1523 * locking under kernfs active protection and allows all kernfs operations
1524 * including self-removal.
1526 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1528 struct cgroup *cgrp;
1530 if (kernfs_type(kn) == KERNFS_DIR)
1533 cgrp = kn->parent->priv;
1536 * We're gonna grab cgroup_mutex which nests outside kernfs
1537 * active_ref. cgroup liveliness check alone provides enough
1538 * protection against removal. Ensure @cgrp stays accessible and
1539 * break the active_ref protection.
1541 if (!cgroup_tryget(cgrp))
1543 kernfs_break_active_protection(kn);
1546 cgroup_lock_and_drain_offline(cgrp);
1548 mutex_lock(&cgroup_mutex);
1550 if (!cgroup_is_dead(cgrp))
1553 cgroup_kn_unlock(kn);
1557 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1559 char name[CGROUP_FILE_NAME_MAX];
1561 lockdep_assert_held(&cgroup_mutex);
1563 if (cft->file_offset) {
1564 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1565 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1567 spin_lock_irq(&cgroup_file_kn_lock);
1569 spin_unlock_irq(&cgroup_file_kn_lock);
1571 del_timer_sync(&cfile->notify_timer);
1574 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1578 * css_clear_dir - remove subsys files in a cgroup directory
1581 static void css_clear_dir(struct cgroup_subsys_state *css)
1583 struct cgroup *cgrp = css->cgroup;
1584 struct cftype *cfts;
1586 if (!(css->flags & CSS_VISIBLE))
1589 css->flags &= ~CSS_VISIBLE;
1592 if (cgroup_on_dfl(cgrp))
1593 cfts = cgroup_base_files;
1595 cfts = cgroup1_base_files;
1597 cgroup_addrm_files(css, cgrp, cfts, false);
1599 list_for_each_entry(cfts, &css->ss->cfts, node)
1600 cgroup_addrm_files(css, cgrp, cfts, false);
1605 * css_populate_dir - create subsys files in a cgroup directory
1608 * On failure, no file is added.
1610 static int css_populate_dir(struct cgroup_subsys_state *css)
1612 struct cgroup *cgrp = css->cgroup;
1613 struct cftype *cfts, *failed_cfts;
1616 if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
1620 if (cgroup_on_dfl(cgrp))
1621 cfts = cgroup_base_files;
1623 cfts = cgroup1_base_files;
1625 ret = cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1629 list_for_each_entry(cfts, &css->ss->cfts, node) {
1630 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1638 css->flags |= CSS_VISIBLE;
1642 list_for_each_entry(cfts, &css->ss->cfts, node) {
1643 if (cfts == failed_cfts)
1645 cgroup_addrm_files(css, cgrp, cfts, false);
1650 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1652 struct cgroup *dcgrp = &dst_root->cgrp;
1653 struct cgroup_subsys *ss;
1655 u16 dfl_disable_ss_mask = 0;
1657 lockdep_assert_held(&cgroup_mutex);
1659 do_each_subsys_mask(ss, ssid, ss_mask) {
1661 * If @ss has non-root csses attached to it, can't move.
1662 * If @ss is an implicit controller, it is exempt from this
1663 * rule and can be stolen.
1665 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1666 !ss->implicit_on_dfl)
1669 /* can't move between two non-dummy roots either */
1670 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1674 * Collect ssid's that need to be disabled from default
1677 if (ss->root == &cgrp_dfl_root)
1678 dfl_disable_ss_mask |= 1 << ssid;
1680 } while_each_subsys_mask();
1682 if (dfl_disable_ss_mask) {
1683 struct cgroup *scgrp = &cgrp_dfl_root.cgrp;
1686 * Controllers from default hierarchy that need to be rebound
1687 * are all disabled together in one go.
1689 cgrp_dfl_root.subsys_mask &= ~dfl_disable_ss_mask;
1690 WARN_ON(cgroup_apply_control(scgrp));
1691 cgroup_finalize_control(scgrp, 0);
1694 do_each_subsys_mask(ss, ssid, ss_mask) {
1695 struct cgroup_root *src_root = ss->root;
1696 struct cgroup *scgrp = &src_root->cgrp;
1697 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1698 struct css_set *cset;
1700 WARN_ON(!css || cgroup_css(dcgrp, ss));
1702 if (src_root != &cgrp_dfl_root) {
1703 /* disable from the source */
1704 src_root->subsys_mask &= ~(1 << ssid);
1705 WARN_ON(cgroup_apply_control(scgrp));
1706 cgroup_finalize_control(scgrp, 0);
1710 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1711 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1712 ss->root = dst_root;
1713 css->cgroup = dcgrp;
1715 spin_lock_irq(&css_set_lock);
1716 hash_for_each(css_set_table, i, cset, hlist)
1717 list_move_tail(&cset->e_cset_node[ss->id],
1718 &dcgrp->e_csets[ss->id]);
1719 spin_unlock_irq(&css_set_lock);
1721 /* default hierarchy doesn't enable controllers by default */
1722 dst_root->subsys_mask |= 1 << ssid;
1723 if (dst_root == &cgrp_dfl_root) {
1724 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1726 dcgrp->subtree_control |= 1 << ssid;
1727 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1730 ret = cgroup_apply_control(dcgrp);
1732 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1737 } while_each_subsys_mask();
1739 kernfs_activate(dcgrp->kn);
1743 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1744 struct kernfs_root *kf_root)
1748 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1749 struct cgroup *ns_cgroup;
1751 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1755 spin_lock_irq(&css_set_lock);
1756 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1757 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1758 spin_unlock_irq(&css_set_lock);
1760 if (len >= PATH_MAX)
1763 seq_escape(sf, buf, " \t\n\\");
1770 static int parse_cgroup_root_flags(char *data, unsigned int *root_flags)
1776 if (!data || *data == '\0')
1779 while ((token = strsep(&data, ",")) != NULL) {
1780 if (!strcmp(token, "nsdelegate")) {
1781 *root_flags |= CGRP_ROOT_NS_DELEGATE;
1785 pr_err("cgroup2: unknown option \"%s\"\n", token);
1792 static void apply_cgroup_root_flags(unsigned int root_flags)
1794 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1795 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1796 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1798 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1802 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1804 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1805 seq_puts(seq, ",nsdelegate");
1809 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1811 unsigned int root_flags;
1814 ret = parse_cgroup_root_flags(data, &root_flags);
1818 apply_cgroup_root_flags(root_flags);
1823 * To reduce the fork() overhead for systems that are not actually using
1824 * their cgroups capability, we don't maintain the lists running through
1825 * each css_set to its tasks until we see the list actually used - in other
1826 * words after the first mount.
1828 static bool use_task_css_set_links __read_mostly;
1830 static void cgroup_enable_task_cg_lists(void)
1832 struct task_struct *p, *g;
1835 * We need tasklist_lock because RCU is not safe against
1836 * while_each_thread(). Besides, a forking task that has passed
1837 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1838 * is not guaranteed to have its child immediately visible in the
1839 * tasklist if we walk through it with RCU.
1841 read_lock(&tasklist_lock);
1842 spin_lock_irq(&css_set_lock);
1844 if (use_task_css_set_links)
1847 use_task_css_set_links = true;
1849 do_each_thread(g, p) {
1850 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1851 task_css_set(p) != &init_css_set);
1854 * We should check if the process is exiting, otherwise
1855 * it will race with cgroup_exit() in that the list
1856 * entry won't be deleted though the process has exited.
1857 * Do it while holding siglock so that we don't end up
1858 * racing against cgroup_exit().
1860 * Interrupts were already disabled while acquiring
1861 * the css_set_lock, so we do not need to disable it
1862 * again when acquiring the sighand->siglock here.
1864 spin_lock(&p->sighand->siglock);
1865 if (!(p->flags & PF_EXITING)) {
1866 struct css_set *cset = task_css_set(p);
1868 if (!css_set_populated(cset))
1869 css_set_update_populated(cset, true);
1870 list_add_tail(&p->cg_list, &cset->tasks);
1874 spin_unlock(&p->sighand->siglock);
1875 } while_each_thread(g, p);
1877 spin_unlock_irq(&css_set_lock);
1878 read_unlock(&tasklist_lock);
1881 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1883 struct cgroup_subsys *ss;
1886 INIT_LIST_HEAD(&cgrp->self.sibling);
1887 INIT_LIST_HEAD(&cgrp->self.children);
1888 INIT_LIST_HEAD(&cgrp->cset_links);
1889 INIT_LIST_HEAD(&cgrp->pidlists);
1890 mutex_init(&cgrp->pidlist_mutex);
1891 cgrp->self.cgroup = cgrp;
1892 cgrp->self.flags |= CSS_ONLINE;
1893 cgrp->dom_cgrp = cgrp;
1894 cgrp->max_descendants = INT_MAX;
1895 cgrp->max_depth = INT_MAX;
1896 INIT_LIST_HEAD(&cgrp->rstat_css_list);
1897 prev_cputime_init(&cgrp->prev_cputime);
1899 for_each_subsys(ss, ssid)
1900 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1902 init_waitqueue_head(&cgrp->offline_waitq);
1903 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
1906 void init_cgroup_root(struct cgroup_root *root, struct cgroup_sb_opts *opts)
1908 struct cgroup *cgrp = &root->cgrp;
1910 INIT_LIST_HEAD(&root->root_list);
1911 atomic_set(&root->nr_cgrps, 1);
1913 init_cgroup_housekeeping(cgrp);
1914 idr_init(&root->cgroup_idr);
1916 root->flags = opts->flags;
1917 if (opts->release_agent)
1918 strscpy(root->release_agent_path, opts->release_agent, PATH_MAX);
1920 strscpy(root->name, opts->name, MAX_CGROUP_ROOT_NAMELEN);
1921 if (opts->cpuset_clone_children)
1922 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1925 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask, int ref_flags)
1927 LIST_HEAD(tmp_links);
1928 struct cgroup *root_cgrp = &root->cgrp;
1929 struct kernfs_syscall_ops *kf_sops;
1930 struct css_set *cset;
1933 lockdep_assert_held(&cgroup_mutex);
1935 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1938 root_cgrp->id = ret;
1939 root_cgrp->ancestor_ids[0] = ret;
1941 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
1942 ref_flags, GFP_KERNEL);
1947 * We're accessing css_set_count without locking css_set_lock here,
1948 * but that's OK - it can only be increased by someone holding
1949 * cgroup_lock, and that's us. Later rebinding may disable
1950 * controllers on the default hierarchy and thus create new csets,
1951 * which can't be more than the existing ones. Allocate 2x.
1953 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
1957 ret = cgroup_init_root_id(root);
1961 kf_sops = root == &cgrp_dfl_root ?
1962 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
1964 root->kf_root = kernfs_create_root(kf_sops,
1965 KERNFS_ROOT_CREATE_DEACTIVATED |
1966 KERNFS_ROOT_SUPPORT_EXPORTOP,
1968 if (IS_ERR(root->kf_root)) {
1969 ret = PTR_ERR(root->kf_root);
1972 root_cgrp->kn = root->kf_root->kn;
1974 ret = css_populate_dir(&root_cgrp->self);
1978 ret = rebind_subsystems(root, ss_mask);
1982 ret = cgroup_bpf_inherit(root_cgrp);
1985 trace_cgroup_setup_root(root);
1988 * There must be no failure case after here, since rebinding takes
1989 * care of subsystems' refcounts, which are explicitly dropped in
1990 * the failure exit path.
1992 list_add(&root->root_list, &cgroup_roots);
1993 cgroup_root_count++;
1996 * Link the root cgroup in this hierarchy into all the css_set
1999 spin_lock_irq(&css_set_lock);
2000 hash_for_each(css_set_table, i, cset, hlist) {
2001 link_css_set(&tmp_links, cset, root_cgrp);
2002 if (css_set_populated(cset))
2003 cgroup_update_populated(root_cgrp, true);
2005 spin_unlock_irq(&css_set_lock);
2007 BUG_ON(!list_empty(&root_cgrp->self.children));
2008 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
2010 kernfs_activate(root_cgrp->kn);
2015 kernfs_destroy_root(root->kf_root);
2016 root->kf_root = NULL;
2018 cgroup_exit_root_id(root);
2020 percpu_ref_exit(&root_cgrp->self.refcnt);
2022 free_cgrp_cset_links(&tmp_links);
2026 struct dentry *cgroup_do_mount(struct file_system_type *fs_type, int flags,
2027 struct cgroup_root *root, unsigned long magic,
2028 struct cgroup_namespace *ns)
2030 struct dentry *dentry;
2031 bool new_sb = false;
2033 dentry = kernfs_mount(fs_type, flags, root->kf_root, magic, &new_sb);
2036 * In non-init cgroup namespace, instead of root cgroup's dentry,
2037 * we return the dentry corresponding to the cgroupns->root_cgrp.
2039 if (!IS_ERR(dentry) && ns != &init_cgroup_ns) {
2040 struct dentry *nsdentry;
2041 struct super_block *sb = dentry->d_sb;
2042 struct cgroup *cgrp;
2044 mutex_lock(&cgroup_mutex);
2045 spin_lock_irq(&css_set_lock);
2047 cgrp = cset_cgroup_from_root(ns->root_cset, root);
2049 spin_unlock_irq(&css_set_lock);
2050 mutex_unlock(&cgroup_mutex);
2052 nsdentry = kernfs_node_dentry(cgrp->kn, sb);
2054 if (IS_ERR(nsdentry))
2055 deactivate_locked_super(sb);
2060 cgroup_put(&root->cgrp);
2065 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
2066 int flags, const char *unused_dev_name,
2069 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
2070 struct dentry *dentry;
2075 /* Check if the caller has permission to mount. */
2076 if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) {
2078 return ERR_PTR(-EPERM);
2082 * The first time anyone tries to mount a cgroup, enable the list
2083 * linking each css_set to its tasks and fix up all existing tasks.
2085 if (!use_task_css_set_links)
2086 cgroup_enable_task_cg_lists();
2088 if (fs_type == &cgroup2_fs_type) {
2089 unsigned int root_flags;
2091 ret = parse_cgroup_root_flags(data, &root_flags);
2094 return ERR_PTR(ret);
2097 cgrp_dfl_visible = true;
2098 cgroup_get_live(&cgrp_dfl_root.cgrp);
2100 dentry = cgroup_do_mount(&cgroup2_fs_type, flags, &cgrp_dfl_root,
2101 CGROUP2_SUPER_MAGIC, ns);
2102 if (!IS_ERR(dentry))
2103 apply_cgroup_root_flags(root_flags);
2105 dentry = cgroup1_mount(&cgroup_fs_type, flags, data,
2106 CGROUP_SUPER_MAGIC, ns);
2113 static void cgroup_kill_sb(struct super_block *sb)
2115 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2116 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2119 * If @root doesn't have any mounts or children, start killing it.
2120 * This prevents new mounts by disabling percpu_ref_tryget_live().
2121 * cgroup_mount() may wait for @root's release.
2123 * And don't kill the default root.
2125 if (!list_empty(&root->cgrp.self.children) ||
2126 root == &cgrp_dfl_root)
2127 cgroup_put(&root->cgrp);
2129 percpu_ref_kill(&root->cgrp.self.refcnt);
2134 struct file_system_type cgroup_fs_type = {
2136 .mount = cgroup_mount,
2137 .kill_sb = cgroup_kill_sb,
2138 .fs_flags = FS_USERNS_MOUNT,
2141 static struct file_system_type cgroup2_fs_type = {
2143 .mount = cgroup_mount,
2144 .kill_sb = cgroup_kill_sb,
2145 .fs_flags = FS_USERNS_MOUNT,
2148 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2149 struct cgroup_namespace *ns)
2151 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2153 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2156 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2157 struct cgroup_namespace *ns)
2161 mutex_lock(&cgroup_mutex);
2162 spin_lock_irq(&css_set_lock);
2164 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2166 spin_unlock_irq(&css_set_lock);
2167 mutex_unlock(&cgroup_mutex);
2171 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2174 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2175 * @task: target task
2176 * @buf: the buffer to write the path into
2177 * @buflen: the length of the buffer
2179 * Determine @task's cgroup on the first (the one with the lowest non-zero
2180 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2181 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2182 * cgroup controller callbacks.
2184 * Return value is the same as kernfs_path().
2186 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2188 struct cgroup_root *root;
2189 struct cgroup *cgrp;
2190 int hierarchy_id = 1;
2193 mutex_lock(&cgroup_mutex);
2194 spin_lock_irq(&css_set_lock);
2196 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2199 cgrp = task_cgroup_from_root(task, root);
2200 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2202 /* if no hierarchy exists, everyone is in "/" */
2203 ret = strlcpy(buf, "/", buflen);
2206 spin_unlock_irq(&css_set_lock);
2207 mutex_unlock(&cgroup_mutex);
2210 EXPORT_SYMBOL_GPL(task_cgroup_path);
2213 * cgroup_migrate_add_task - add a migration target task to a migration context
2214 * @task: target task
2215 * @mgctx: target migration context
2217 * Add @task, which is a migration target, to @mgctx->tset. This function
2218 * becomes noop if @task doesn't need to be migrated. @task's css_set
2219 * should have been added as a migration source and @task->cg_list will be
2220 * moved from the css_set's tasks list to mg_tasks one.
2222 static void cgroup_migrate_add_task(struct task_struct *task,
2223 struct cgroup_mgctx *mgctx)
2225 struct css_set *cset;
2227 lockdep_assert_held(&css_set_lock);
2229 /* @task either already exited or can't exit until the end */
2230 if (task->flags & PF_EXITING)
2233 /* leave @task alone if post_fork() hasn't linked it yet */
2234 if (list_empty(&task->cg_list))
2237 cset = task_css_set(task);
2238 if (!cset->mg_src_cgrp)
2241 mgctx->tset.nr_tasks++;
2243 list_move_tail(&task->cg_list, &cset->mg_tasks);
2244 if (list_empty(&cset->mg_node))
2245 list_add_tail(&cset->mg_node,
2246 &mgctx->tset.src_csets);
2247 if (list_empty(&cset->mg_dst_cset->mg_node))
2248 list_add_tail(&cset->mg_dst_cset->mg_node,
2249 &mgctx->tset.dst_csets);
2253 * cgroup_taskset_first - reset taskset and return the first task
2254 * @tset: taskset of interest
2255 * @dst_cssp: output variable for the destination css
2257 * @tset iteration is initialized and the first task is returned.
2259 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2260 struct cgroup_subsys_state **dst_cssp)
2262 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2263 tset->cur_task = NULL;
2265 return cgroup_taskset_next(tset, dst_cssp);
2269 * cgroup_taskset_next - iterate to the next task in taskset
2270 * @tset: taskset of interest
2271 * @dst_cssp: output variable for the destination css
2273 * Return the next task in @tset. Iteration must have been initialized
2274 * with cgroup_taskset_first().
2276 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2277 struct cgroup_subsys_state **dst_cssp)
2279 struct css_set *cset = tset->cur_cset;
2280 struct task_struct *task = tset->cur_task;
2282 while (&cset->mg_node != tset->csets) {
2284 task = list_first_entry(&cset->mg_tasks,
2285 struct task_struct, cg_list);
2287 task = list_next_entry(task, cg_list);
2289 if (&task->cg_list != &cset->mg_tasks) {
2290 tset->cur_cset = cset;
2291 tset->cur_task = task;
2294 * This function may be called both before and
2295 * after cgroup_taskset_migrate(). The two cases
2296 * can be distinguished by looking at whether @cset
2297 * has its ->mg_dst_cset set.
2299 if (cset->mg_dst_cset)
2300 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2302 *dst_cssp = cset->subsys[tset->ssid];
2307 cset = list_next_entry(cset, mg_node);
2315 * cgroup_taskset_migrate - migrate a taskset
2316 * @mgctx: migration context
2318 * Migrate tasks in @mgctx as setup by migration preparation functions.
2319 * This function fails iff one of the ->can_attach callbacks fails and
2320 * guarantees that either all or none of the tasks in @mgctx are migrated.
2321 * @mgctx is consumed regardless of success.
2323 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2325 struct cgroup_taskset *tset = &mgctx->tset;
2326 struct cgroup_subsys *ss;
2327 struct task_struct *task, *tmp_task;
2328 struct css_set *cset, *tmp_cset;
2329 int ssid, failed_ssid, ret;
2331 /* check that we can legitimately attach to the cgroup */
2332 if (tset->nr_tasks) {
2333 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2334 if (ss->can_attach) {
2336 ret = ss->can_attach(tset);
2339 goto out_cancel_attach;
2342 } while_each_subsys_mask();
2346 * Now that we're guaranteed success, proceed to move all tasks to
2347 * the new cgroup. There are no failure cases after here, so this
2348 * is the commit point.
2350 spin_lock_irq(&css_set_lock);
2351 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2352 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2353 struct css_set *from_cset = task_css_set(task);
2354 struct css_set *to_cset = cset->mg_dst_cset;
2356 get_css_set(to_cset);
2357 to_cset->nr_tasks++;
2358 css_set_move_task(task, from_cset, to_cset, true);
2359 put_css_set_locked(from_cset);
2360 from_cset->nr_tasks--;
2363 spin_unlock_irq(&css_set_lock);
2366 * Migration is committed, all target tasks are now on dst_csets.
2367 * Nothing is sensitive to fork() after this point. Notify
2368 * controllers that migration is complete.
2370 tset->csets = &tset->dst_csets;
2372 if (tset->nr_tasks) {
2373 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2378 } while_each_subsys_mask();
2382 goto out_release_tset;
2385 if (tset->nr_tasks) {
2386 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2387 if (ssid == failed_ssid)
2389 if (ss->cancel_attach) {
2391 ss->cancel_attach(tset);
2393 } while_each_subsys_mask();
2396 spin_lock_irq(&css_set_lock);
2397 list_splice_init(&tset->dst_csets, &tset->src_csets);
2398 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2399 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2400 list_del_init(&cset->mg_node);
2402 spin_unlock_irq(&css_set_lock);
2405 * Re-initialize the cgroup_taskset structure in case it is reused
2406 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2410 tset->csets = &tset->src_csets;
2415 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2416 * @dst_cgrp: destination cgroup to test
2418 * On the default hierarchy, except for the mixable, (possible) thread root
2419 * and threaded cgroups, subtree_control must be zero for migration
2420 * destination cgroups with tasks so that child cgroups don't compete
2423 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2425 /* v1 doesn't have any restriction */
2426 if (!cgroup_on_dfl(dst_cgrp))
2429 /* verify @dst_cgrp can host resources */
2430 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2433 /* mixables don't care */
2434 if (cgroup_is_mixable(dst_cgrp))
2438 * If @dst_cgrp is already or can become a thread root or is
2439 * threaded, it doesn't matter.
2441 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2444 /* apply no-internal-process constraint */
2445 if (dst_cgrp->subtree_control)
2452 * cgroup_migrate_finish - cleanup after attach
2453 * @mgctx: migration context
2455 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2456 * those functions for details.
2458 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2460 struct css_set *cset, *tmp_cset;
2462 lockdep_assert_held(&cgroup_mutex);
2464 spin_lock_irq(&css_set_lock);
2466 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_src_csets,
2467 mg_src_preload_node) {
2468 cset->mg_src_cgrp = NULL;
2469 cset->mg_dst_cgrp = NULL;
2470 cset->mg_dst_cset = NULL;
2471 list_del_init(&cset->mg_src_preload_node);
2472 put_css_set_locked(cset);
2475 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_dst_csets,
2476 mg_dst_preload_node) {
2477 cset->mg_src_cgrp = NULL;
2478 cset->mg_dst_cgrp = NULL;
2479 cset->mg_dst_cset = NULL;
2480 list_del_init(&cset->mg_dst_preload_node);
2481 put_css_set_locked(cset);
2484 spin_unlock_irq(&css_set_lock);
2488 * cgroup_migrate_add_src - add a migration source css_set
2489 * @src_cset: the source css_set to add
2490 * @dst_cgrp: the destination cgroup
2491 * @mgctx: migration context
2493 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2494 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2495 * up by cgroup_migrate_finish().
2497 * This function may be called without holding cgroup_threadgroup_rwsem
2498 * even if the target is a process. Threads may be created and destroyed
2499 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2500 * into play and the preloaded css_sets are guaranteed to cover all
2503 void cgroup_migrate_add_src(struct css_set *src_cset,
2504 struct cgroup *dst_cgrp,
2505 struct cgroup_mgctx *mgctx)
2507 struct cgroup *src_cgrp;
2509 lockdep_assert_held(&cgroup_mutex);
2510 lockdep_assert_held(&css_set_lock);
2513 * If ->dead, @src_set is associated with one or more dead cgroups
2514 * and doesn't contain any migratable tasks. Ignore it early so
2515 * that the rest of migration path doesn't get confused by it.
2520 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2522 if (!list_empty(&src_cset->mg_src_preload_node))
2525 WARN_ON(src_cset->mg_src_cgrp);
2526 WARN_ON(src_cset->mg_dst_cgrp);
2527 WARN_ON(!list_empty(&src_cset->mg_tasks));
2528 WARN_ON(!list_empty(&src_cset->mg_node));
2530 src_cset->mg_src_cgrp = src_cgrp;
2531 src_cset->mg_dst_cgrp = dst_cgrp;
2532 get_css_set(src_cset);
2533 list_add_tail(&src_cset->mg_src_preload_node, &mgctx->preloaded_src_csets);
2537 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2538 * @mgctx: migration context
2540 * Tasks are about to be moved and all the source css_sets have been
2541 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2542 * pins all destination css_sets, links each to its source, and append them
2543 * to @mgctx->preloaded_dst_csets.
2545 * This function must be called after cgroup_migrate_add_src() has been
2546 * called on each migration source css_set. After migration is performed
2547 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2550 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2552 struct css_set *src_cset, *tmp_cset;
2554 lockdep_assert_held(&cgroup_mutex);
2556 /* look up the dst cset for each src cset and link it to src */
2557 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2558 mg_src_preload_node) {
2559 struct css_set *dst_cset;
2560 struct cgroup_subsys *ss;
2563 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2567 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2570 * If src cset equals dst, it's noop. Drop the src.
2571 * cgroup_migrate() will skip the cset too. Note that we
2572 * can't handle src == dst as some nodes are used by both.
2574 if (src_cset == dst_cset) {
2575 src_cset->mg_src_cgrp = NULL;
2576 src_cset->mg_dst_cgrp = NULL;
2577 list_del_init(&src_cset->mg_src_preload_node);
2578 put_css_set(src_cset);
2579 put_css_set(dst_cset);
2583 src_cset->mg_dst_cset = dst_cset;
2585 if (list_empty(&dst_cset->mg_dst_preload_node))
2586 list_add_tail(&dst_cset->mg_dst_preload_node,
2587 &mgctx->preloaded_dst_csets);
2589 put_css_set(dst_cset);
2591 for_each_subsys(ss, ssid)
2592 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2593 mgctx->ss_mask |= 1 << ssid;
2598 cgroup_migrate_finish(mgctx);
2603 * cgroup_migrate - migrate a process or task to a cgroup
2604 * @leader: the leader of the process or the task to migrate
2605 * @threadgroup: whether @leader points to the whole process or a single task
2606 * @mgctx: migration context
2608 * Migrate a process or task denoted by @leader. If migrating a process,
2609 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2610 * responsible for invoking cgroup_migrate_add_src() and
2611 * cgroup_migrate_prepare_dst() on the targets before invoking this
2612 * function and following up with cgroup_migrate_finish().
2614 * As long as a controller's ->can_attach() doesn't fail, this function is
2615 * guaranteed to succeed. This means that, excluding ->can_attach()
2616 * failure, when migrating multiple targets, the success or failure can be
2617 * decided for all targets by invoking group_migrate_prepare_dst() before
2618 * actually starting migrating.
2620 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2621 struct cgroup_mgctx *mgctx)
2623 struct task_struct *task;
2626 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2627 * already PF_EXITING could be freed from underneath us unless we
2628 * take an rcu_read_lock.
2630 spin_lock_irq(&css_set_lock);
2634 cgroup_migrate_add_task(task, mgctx);
2637 } while_each_thread(leader, task);
2639 spin_unlock_irq(&css_set_lock);
2641 return cgroup_migrate_execute(mgctx);
2645 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2646 * @dst_cgrp: the cgroup to attach to
2647 * @leader: the task or the leader of the threadgroup to be attached
2648 * @threadgroup: attach the whole threadgroup?
2650 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2652 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2655 DEFINE_CGROUP_MGCTX(mgctx);
2656 struct task_struct *task;
2659 ret = cgroup_migrate_vet_dst(dst_cgrp);
2663 /* look up all src csets */
2664 spin_lock_irq(&css_set_lock);
2668 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2671 } while_each_thread(leader, task);
2673 spin_unlock_irq(&css_set_lock);
2675 /* prepare dst csets and commit */
2676 ret = cgroup_migrate_prepare_dst(&mgctx);
2678 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2680 cgroup_migrate_finish(&mgctx);
2683 TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
2688 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup)
2689 __acquires(&cgroup_threadgroup_rwsem)
2691 struct task_struct *tsk;
2694 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2695 return ERR_PTR(-EINVAL);
2697 percpu_down_write(&cgroup_threadgroup_rwsem);
2701 tsk = find_task_by_vpid(pid);
2703 tsk = ERR_PTR(-ESRCH);
2704 goto out_unlock_threadgroup;
2711 tsk = tsk->group_leader;
2714 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2715 * If userland migrates such a kthread to a non-root cgroup, it can
2716 * become trapped in a cpuset, or RT kthread may be born in a
2717 * cgroup with no rt_runtime allocated. Just say no.
2719 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2720 tsk = ERR_PTR(-EINVAL);
2721 goto out_unlock_threadgroup;
2724 get_task_struct(tsk);
2725 goto out_unlock_rcu;
2727 out_unlock_threadgroup:
2728 percpu_up_write(&cgroup_threadgroup_rwsem);
2734 void cgroup_procs_write_finish(struct task_struct *task)
2735 __releases(&cgroup_threadgroup_rwsem)
2737 struct cgroup_subsys *ss;
2740 /* release reference from cgroup_procs_write_start() */
2741 put_task_struct(task);
2743 percpu_up_write(&cgroup_threadgroup_rwsem);
2744 for_each_subsys(ss, ssid)
2745 if (ss->post_attach)
2749 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2751 struct cgroup_subsys *ss;
2752 bool printed = false;
2755 do_each_subsys_mask(ss, ssid, ss_mask) {
2758 seq_printf(seq, "%s", ss->name);
2760 } while_each_subsys_mask();
2762 seq_putc(seq, '\n');
2765 /* show controllers which are enabled from the parent */
2766 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2768 struct cgroup *cgrp = seq_css(seq)->cgroup;
2770 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2774 /* show controllers which are enabled for a given cgroup's children */
2775 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2777 struct cgroup *cgrp = seq_css(seq)->cgroup;
2779 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2784 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2785 * @cgrp: root of the subtree to update csses for
2787 * @cgrp's control masks have changed and its subtree's css associations
2788 * need to be updated accordingly. This function looks up all css_sets
2789 * which are attached to the subtree, creates the matching updated css_sets
2790 * and migrates the tasks to the new ones.
2792 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2794 DEFINE_CGROUP_MGCTX(mgctx);
2795 struct cgroup_subsys_state *d_css;
2796 struct cgroup *dsct;
2797 struct css_set *src_cset;
2800 lockdep_assert_held(&cgroup_mutex);
2802 percpu_down_write(&cgroup_threadgroup_rwsem);
2804 /* look up all csses currently attached to @cgrp's subtree */
2805 spin_lock_irq(&css_set_lock);
2806 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2807 struct cgrp_cset_link *link;
2809 list_for_each_entry(link, &dsct->cset_links, cset_link)
2810 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2812 spin_unlock_irq(&css_set_lock);
2814 /* NULL dst indicates self on default hierarchy */
2815 ret = cgroup_migrate_prepare_dst(&mgctx);
2819 spin_lock_irq(&css_set_lock);
2820 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets,
2821 mg_src_preload_node) {
2822 struct task_struct *task, *ntask;
2824 /* all tasks in src_csets need to be migrated */
2825 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2826 cgroup_migrate_add_task(task, &mgctx);
2828 spin_unlock_irq(&css_set_lock);
2830 ret = cgroup_migrate_execute(&mgctx);
2832 cgroup_migrate_finish(&mgctx);
2833 percpu_up_write(&cgroup_threadgroup_rwsem);
2838 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2839 * @cgrp: root of the target subtree
2841 * Because css offlining is asynchronous, userland may try to re-enable a
2842 * controller while the previous css is still around. This function grabs
2843 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2845 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2846 __acquires(&cgroup_mutex)
2848 struct cgroup *dsct;
2849 struct cgroup_subsys_state *d_css;
2850 struct cgroup_subsys *ss;
2854 mutex_lock(&cgroup_mutex);
2856 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2857 for_each_subsys(ss, ssid) {
2858 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2861 if (!css || !percpu_ref_is_dying(&css->refcnt))
2864 cgroup_get_live(dsct);
2865 prepare_to_wait(&dsct->offline_waitq, &wait,
2866 TASK_UNINTERRUPTIBLE);
2868 mutex_unlock(&cgroup_mutex);
2870 finish_wait(&dsct->offline_waitq, &wait);
2879 * cgroup_save_control - save control masks and dom_cgrp of a subtree
2880 * @cgrp: root of the target subtree
2882 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
2883 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2886 static void cgroup_save_control(struct cgroup *cgrp)
2888 struct cgroup *dsct;
2889 struct cgroup_subsys_state *d_css;
2891 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2892 dsct->old_subtree_control = dsct->subtree_control;
2893 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
2894 dsct->old_dom_cgrp = dsct->dom_cgrp;
2899 * cgroup_propagate_control - refresh control masks of a subtree
2900 * @cgrp: root of the target subtree
2902 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
2903 * ->subtree_control and propagate controller availability through the
2904 * subtree so that descendants don't have unavailable controllers enabled.
2906 static void cgroup_propagate_control(struct cgroup *cgrp)
2908 struct cgroup *dsct;
2909 struct cgroup_subsys_state *d_css;
2911 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2912 dsct->subtree_control &= cgroup_control(dsct);
2913 dsct->subtree_ss_mask =
2914 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
2915 cgroup_ss_mask(dsct));
2920 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
2921 * @cgrp: root of the target subtree
2923 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
2924 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2927 static void cgroup_restore_control(struct cgroup *cgrp)
2929 struct cgroup *dsct;
2930 struct cgroup_subsys_state *d_css;
2932 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2933 dsct->subtree_control = dsct->old_subtree_control;
2934 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
2935 dsct->dom_cgrp = dsct->old_dom_cgrp;
2939 static bool css_visible(struct cgroup_subsys_state *css)
2941 struct cgroup_subsys *ss = css->ss;
2942 struct cgroup *cgrp = css->cgroup;
2944 if (cgroup_control(cgrp) & (1 << ss->id))
2946 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
2948 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
2952 * cgroup_apply_control_enable - enable or show csses according to control
2953 * @cgrp: root of the target subtree
2955 * Walk @cgrp's subtree and create new csses or make the existing ones
2956 * visible. A css is created invisible if it's being implicitly enabled
2957 * through dependency. An invisible css is made visible when the userland
2958 * explicitly enables it.
2960 * Returns 0 on success, -errno on failure. On failure, csses which have
2961 * been processed already aren't cleaned up. The caller is responsible for
2962 * cleaning up with cgroup_apply_control_disable().
2964 static int cgroup_apply_control_enable(struct cgroup *cgrp)
2966 struct cgroup *dsct;
2967 struct cgroup_subsys_state *d_css;
2968 struct cgroup_subsys *ss;
2971 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2972 for_each_subsys(ss, ssid) {
2973 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2975 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
2979 css = css_create(dsct, ss);
2981 return PTR_ERR(css);
2984 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
2986 if (css_visible(css)) {
2987 ret = css_populate_dir(css);
2998 * cgroup_apply_control_disable - kill or hide csses according to control
2999 * @cgrp: root of the target subtree
3001 * Walk @cgrp's subtree and kill and hide csses so that they match
3002 * cgroup_ss_mask() and cgroup_visible_mask().
3004 * A css is hidden when the userland requests it to be disabled while other
3005 * subsystems are still depending on it. The css must not actively control
3006 * resources and be in the vanilla state if it's made visible again later.
3007 * Controllers which may be depended upon should provide ->css_reset() for
3010 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3012 struct cgroup *dsct;
3013 struct cgroup_subsys_state *d_css;
3014 struct cgroup_subsys *ss;
3017 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3018 for_each_subsys(ss, ssid) {
3019 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3024 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3027 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3029 } else if (!css_visible(css)) {
3039 * cgroup_apply_control - apply control mask updates to the subtree
3040 * @cgrp: root of the target subtree
3042 * subsystems can be enabled and disabled in a subtree using the following
3045 * 1. Call cgroup_save_control() to stash the current state.
3046 * 2. Update ->subtree_control masks in the subtree as desired.
3047 * 3. Call cgroup_apply_control() to apply the changes.
3048 * 4. Optionally perform other related operations.
3049 * 5. Call cgroup_finalize_control() to finish up.
3051 * This function implements step 3 and propagates the mask changes
3052 * throughout @cgrp's subtree, updates csses accordingly and perform
3053 * process migrations.
3055 static int cgroup_apply_control(struct cgroup *cgrp)
3059 cgroup_propagate_control(cgrp);
3061 ret = cgroup_apply_control_enable(cgrp);
3066 * At this point, cgroup_e_css() results reflect the new csses
3067 * making the following cgroup_update_dfl_csses() properly update
3068 * css associations of all tasks in the subtree.
3070 ret = cgroup_update_dfl_csses(cgrp);
3078 * cgroup_finalize_control - finalize control mask update
3079 * @cgrp: root of the target subtree
3080 * @ret: the result of the update
3082 * Finalize control mask update. See cgroup_apply_control() for more info.
3084 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3087 cgroup_restore_control(cgrp);
3088 cgroup_propagate_control(cgrp);
3091 cgroup_apply_control_disable(cgrp);
3094 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3096 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3098 /* if nothing is getting enabled, nothing to worry about */
3102 /* can @cgrp host any resources? */
3103 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3106 /* mixables don't care */
3107 if (cgroup_is_mixable(cgrp))
3110 if (domain_enable) {
3111 /* can't enable domain controllers inside a thread subtree */
3112 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3116 * Threaded controllers can handle internal competitions
3117 * and are always allowed inside a (prospective) thread
3120 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3125 * Controllers can't be enabled for a cgroup with tasks to avoid
3126 * child cgroups competing against tasks.
3128 if (cgroup_has_tasks(cgrp))
3134 /* change the enabled child controllers for a cgroup in the default hierarchy */
3135 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3136 char *buf, size_t nbytes,
3139 u16 enable = 0, disable = 0;
3140 struct cgroup *cgrp, *child;
3141 struct cgroup_subsys *ss;
3146 * Parse input - space separated list of subsystem names prefixed
3147 * with either + or -.
3149 buf = strstrip(buf);
3150 while ((tok = strsep(&buf, " "))) {
3153 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3154 if (!cgroup_ssid_enabled(ssid) ||
3155 strcmp(tok + 1, ss->name))
3159 enable |= 1 << ssid;
3160 disable &= ~(1 << ssid);
3161 } else if (*tok == '-') {
3162 disable |= 1 << ssid;
3163 enable &= ~(1 << ssid);
3168 } while_each_subsys_mask();
3169 if (ssid == CGROUP_SUBSYS_COUNT)
3173 cgrp = cgroup_kn_lock_live(of->kn, true);
3177 for_each_subsys(ss, ssid) {
3178 if (enable & (1 << ssid)) {
3179 if (cgrp->subtree_control & (1 << ssid)) {
3180 enable &= ~(1 << ssid);
3184 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3188 } else if (disable & (1 << ssid)) {
3189 if (!(cgrp->subtree_control & (1 << ssid))) {
3190 disable &= ~(1 << ssid);
3194 /* a child has it enabled? */
3195 cgroup_for_each_live_child(child, cgrp) {
3196 if (child->subtree_control & (1 << ssid)) {
3204 if (!enable && !disable) {
3209 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3213 /* save and update control masks and prepare csses */
3214 cgroup_save_control(cgrp);
3216 cgrp->subtree_control |= enable;
3217 cgrp->subtree_control &= ~disable;
3219 ret = cgroup_apply_control(cgrp);
3220 cgroup_finalize_control(cgrp, ret);
3224 kernfs_activate(cgrp->kn);
3226 cgroup_kn_unlock(of->kn);
3227 return ret ?: nbytes;
3231 * cgroup_enable_threaded - make @cgrp threaded
3232 * @cgrp: the target cgroup
3234 * Called when "threaded" is written to the cgroup.type interface file and
3235 * tries to make @cgrp threaded and join the parent's resource domain.
3236 * This function is never called on the root cgroup as cgroup.type doesn't
3239 static int cgroup_enable_threaded(struct cgroup *cgrp)
3241 struct cgroup *parent = cgroup_parent(cgrp);
3242 struct cgroup *dom_cgrp = parent->dom_cgrp;
3243 struct cgroup *dsct;
3244 struct cgroup_subsys_state *d_css;
3247 lockdep_assert_held(&cgroup_mutex);
3249 /* noop if already threaded */
3250 if (cgroup_is_threaded(cgrp))
3254 * If @cgroup is populated or has domain controllers enabled, it
3255 * can't be switched. While the below cgroup_can_be_thread_root()
3256 * test can catch the same conditions, that's only when @parent is
3257 * not mixable, so let's check it explicitly.
3259 if (cgroup_is_populated(cgrp) ||
3260 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3263 /* we're joining the parent's domain, ensure its validity */
3264 if (!cgroup_is_valid_domain(dom_cgrp) ||
3265 !cgroup_can_be_thread_root(dom_cgrp))
3269 * The following shouldn't cause actual migrations and should
3272 cgroup_save_control(cgrp);
3274 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3275 if (dsct == cgrp || cgroup_is_threaded(dsct))
3276 dsct->dom_cgrp = dom_cgrp;
3278 ret = cgroup_apply_control(cgrp);
3280 parent->nr_threaded_children++;
3282 cgroup_finalize_control(cgrp, ret);
3286 static int cgroup_type_show(struct seq_file *seq, void *v)
3288 struct cgroup *cgrp = seq_css(seq)->cgroup;
3290 if (cgroup_is_threaded(cgrp))
3291 seq_puts(seq, "threaded\n");
3292 else if (!cgroup_is_valid_domain(cgrp))
3293 seq_puts(seq, "domain invalid\n");
3294 else if (cgroup_is_thread_root(cgrp))
3295 seq_puts(seq, "domain threaded\n");
3297 seq_puts(seq, "domain\n");
3302 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3303 size_t nbytes, loff_t off)
3305 struct cgroup *cgrp;
3308 /* only switching to threaded mode is supported */
3309 if (strcmp(strstrip(buf), "threaded"))
3312 /* drain dying csses before we re-apply (threaded) subtree control */
3313 cgrp = cgroup_kn_lock_live(of->kn, true);
3317 /* threaded can only be enabled */
3318 ret = cgroup_enable_threaded(cgrp);
3320 cgroup_kn_unlock(of->kn);
3321 return ret ?: nbytes;
3324 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3326 struct cgroup *cgrp = seq_css(seq)->cgroup;
3327 int descendants = READ_ONCE(cgrp->max_descendants);
3329 if (descendants == INT_MAX)
3330 seq_puts(seq, "max\n");
3332 seq_printf(seq, "%d\n", descendants);
3337 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3338 char *buf, size_t nbytes, loff_t off)
3340 struct cgroup *cgrp;
3344 buf = strstrip(buf);
3345 if (!strcmp(buf, "max")) {
3346 descendants = INT_MAX;
3348 ret = kstrtoint(buf, 0, &descendants);
3353 if (descendants < 0)
3356 cgrp = cgroup_kn_lock_live(of->kn, false);
3360 cgrp->max_descendants = descendants;
3362 cgroup_kn_unlock(of->kn);
3367 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3369 struct cgroup *cgrp = seq_css(seq)->cgroup;
3370 int depth = READ_ONCE(cgrp->max_depth);
3372 if (depth == INT_MAX)
3373 seq_puts(seq, "max\n");
3375 seq_printf(seq, "%d\n", depth);
3380 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3381 char *buf, size_t nbytes, loff_t off)
3383 struct cgroup *cgrp;
3387 buf = strstrip(buf);
3388 if (!strcmp(buf, "max")) {
3391 ret = kstrtoint(buf, 0, &depth);
3399 cgrp = cgroup_kn_lock_live(of->kn, false);
3403 cgrp->max_depth = depth;
3405 cgroup_kn_unlock(of->kn);
3410 static int cgroup_events_show(struct seq_file *seq, void *v)
3412 seq_printf(seq, "populated %d\n",
3413 cgroup_is_populated(seq_css(seq)->cgroup));
3417 static int cgroup_stat_show(struct seq_file *seq, void *v)
3419 struct cgroup *cgroup = seq_css(seq)->cgroup;
3421 seq_printf(seq, "nr_descendants %d\n",
3422 cgroup->nr_descendants);
3423 seq_printf(seq, "nr_dying_descendants %d\n",
3424 cgroup->nr_dying_descendants);
3429 static int __maybe_unused cgroup_extra_stat_show(struct seq_file *seq,
3430 struct cgroup *cgrp, int ssid)
3432 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3433 struct cgroup_subsys_state *css;
3436 if (!ss->css_extra_stat_show)
3439 css = cgroup_tryget_css(cgrp, ss);
3443 ret = ss->css_extra_stat_show(seq, css);
3448 static int cpu_stat_show(struct seq_file *seq, void *v)
3450 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3453 cgroup_base_stat_cputime_show(seq);
3454 #ifdef CONFIG_CGROUP_SCHED
3455 ret = cgroup_extra_stat_show(seq, cgrp, cpu_cgrp_id);
3460 static int cgroup_file_open(struct kernfs_open_file *of)
3462 struct cftype *cft = of->kn->priv;
3463 struct cgroup_file_ctx *ctx;
3466 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3470 ctx->ns = current->nsproxy->cgroup_ns;
3471 get_cgroup_ns(ctx->ns);
3477 ret = cft->open(of);
3479 put_cgroup_ns(ctx->ns);
3485 static void cgroup_file_release(struct kernfs_open_file *of)
3487 struct cftype *cft = of->kn->priv;
3488 struct cgroup_file_ctx *ctx = of->priv;
3492 put_cgroup_ns(ctx->ns);
3496 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3497 size_t nbytes, loff_t off)
3499 struct cgroup_file_ctx *ctx = of->priv;
3500 struct cgroup *cgrp = of->kn->parent->priv;
3501 struct cftype *cft = of->kn->priv;
3502 struct cgroup_subsys_state *css;
3506 * If namespaces are delegation boundaries, disallow writes to
3507 * files in an non-init namespace root from inside the namespace
3508 * except for the files explicitly marked delegatable -
3509 * cgroup.procs and cgroup.subtree_control.
3511 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3512 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3513 ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
3517 return cft->write(of, buf, nbytes, off);
3520 * kernfs guarantees that a file isn't deleted with operations in
3521 * flight, which means that the matching css is and stays alive and
3522 * doesn't need to be pinned. The RCU locking is not necessary
3523 * either. It's just for the convenience of using cgroup_css().
3526 css = cgroup_css(cgrp, cft->ss);
3529 if (cft->write_u64) {
3530 unsigned long long v;
3531 ret = kstrtoull(buf, 0, &v);
3533 ret = cft->write_u64(css, cft, v);
3534 } else if (cft->write_s64) {
3536 ret = kstrtoll(buf, 0, &v);
3538 ret = cft->write_s64(css, cft, v);
3543 return ret ?: nbytes;
3546 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3548 return seq_cft(seq)->seq_start(seq, ppos);
3551 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3553 return seq_cft(seq)->seq_next(seq, v, ppos);
3556 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3558 if (seq_cft(seq)->seq_stop)
3559 seq_cft(seq)->seq_stop(seq, v);
3562 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3564 struct cftype *cft = seq_cft(m);
3565 struct cgroup_subsys_state *css = seq_css(m);
3568 return cft->seq_show(m, arg);
3571 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3572 else if (cft->read_s64)
3573 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3579 static struct kernfs_ops cgroup_kf_single_ops = {
3580 .atomic_write_len = PAGE_SIZE,
3581 .open = cgroup_file_open,
3582 .release = cgroup_file_release,
3583 .write = cgroup_file_write,
3584 .seq_show = cgroup_seqfile_show,
3587 static struct kernfs_ops cgroup_kf_ops = {
3588 .atomic_write_len = PAGE_SIZE,
3589 .open = cgroup_file_open,
3590 .release = cgroup_file_release,
3591 .write = cgroup_file_write,
3592 .seq_start = cgroup_seqfile_start,
3593 .seq_next = cgroup_seqfile_next,
3594 .seq_stop = cgroup_seqfile_stop,
3595 .seq_show = cgroup_seqfile_show,
3598 /* set uid and gid of cgroup dirs and files to that of the creator */
3599 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3601 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3602 .ia_uid = current_fsuid(),
3603 .ia_gid = current_fsgid(), };
3605 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3606 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3609 return kernfs_setattr(kn, &iattr);
3612 static void cgroup_file_notify_timer(struct timer_list *timer)
3614 cgroup_file_notify(container_of(timer, struct cgroup_file,
3618 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
3621 char name[CGROUP_FILE_NAME_MAX];
3622 struct kernfs_node *kn;
3623 struct lock_class_key *key = NULL;
3626 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3627 key = &cft->lockdep_key;
3629 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3630 cgroup_file_mode(cft),
3631 GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
3632 0, cft->kf_ops, cft,
3637 ret = cgroup_kn_set_ugid(kn);
3643 if (cft->file_offset) {
3644 struct cgroup_file *cfile = (void *)css + cft->file_offset;
3646 timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
3648 spin_lock_irq(&cgroup_file_kn_lock);
3650 spin_unlock_irq(&cgroup_file_kn_lock);
3657 * cgroup_addrm_files - add or remove files to a cgroup directory
3658 * @css: the target css
3659 * @cgrp: the target cgroup (usually css->cgroup)
3660 * @cfts: array of cftypes to be added
3661 * @is_add: whether to add or remove
3663 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3664 * For removals, this function never fails.
3666 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
3667 struct cgroup *cgrp, struct cftype cfts[],
3670 struct cftype *cft, *cft_end = NULL;
3673 lockdep_assert_held(&cgroup_mutex);
3676 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
3677 /* does cft->flags tell us to skip this file on @cgrp? */
3678 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3680 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3682 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3684 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3688 ret = cgroup_add_file(css, cgrp, cft);
3690 pr_warn("%s: failed to add %s, err=%d\n",
3691 __func__, cft->name, ret);
3697 cgroup_rm_file(cgrp, cft);
3703 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3705 struct cgroup_subsys *ss = cfts[0].ss;
3706 struct cgroup *root = &ss->root->cgrp;
3707 struct cgroup_subsys_state *css;
3710 lockdep_assert_held(&cgroup_mutex);
3712 /* add/rm files for all cgroups created before */
3713 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3714 struct cgroup *cgrp = css->cgroup;
3716 if (!(css->flags & CSS_VISIBLE))
3719 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
3725 kernfs_activate(root->kn);
3729 static void cgroup_exit_cftypes(struct cftype *cfts)
3733 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3734 /* free copy for custom atomic_write_len, see init_cftypes() */
3735 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3740 /* revert flags set by cgroup core while adding @cfts */
3741 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3745 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3749 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3750 struct kernfs_ops *kf_ops;
3752 WARN_ON(cft->ss || cft->kf_ops);
3755 kf_ops = &cgroup_kf_ops;
3757 kf_ops = &cgroup_kf_single_ops;
3760 * Ugh... if @cft wants a custom max_write_len, we need to
3761 * make a copy of kf_ops to set its atomic_write_len.
3763 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3764 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3766 cgroup_exit_cftypes(cfts);
3769 kf_ops->atomic_write_len = cft->max_write_len;
3772 cft->kf_ops = kf_ops;
3779 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3781 lockdep_assert_held(&cgroup_mutex);
3783 if (!cfts || !cfts[0].ss)
3786 list_del(&cfts->node);
3787 cgroup_apply_cftypes(cfts, false);
3788 cgroup_exit_cftypes(cfts);
3793 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3794 * @cfts: zero-length name terminated array of cftypes
3796 * Unregister @cfts. Files described by @cfts are removed from all
3797 * existing cgroups and all future cgroups won't have them either. This
3798 * function can be called anytime whether @cfts' subsys is attached or not.
3800 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3803 int cgroup_rm_cftypes(struct cftype *cfts)
3807 mutex_lock(&cgroup_mutex);
3808 ret = cgroup_rm_cftypes_locked(cfts);
3809 mutex_unlock(&cgroup_mutex);
3814 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3815 * @ss: target cgroup subsystem
3816 * @cfts: zero-length name terminated array of cftypes
3818 * Register @cfts to @ss. Files described by @cfts are created for all
3819 * existing cgroups to which @ss is attached and all future cgroups will
3820 * have them too. This function can be called anytime whether @ss is
3823 * Returns 0 on successful registration, -errno on failure. Note that this
3824 * function currently returns 0 as long as @cfts registration is successful
3825 * even if some file creation attempts on existing cgroups fail.
3827 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3831 if (!cgroup_ssid_enabled(ss->id))
3834 if (!cfts || cfts[0].name[0] == '\0')
3837 ret = cgroup_init_cftypes(ss, cfts);
3841 mutex_lock(&cgroup_mutex);
3843 list_add_tail(&cfts->node, &ss->cfts);
3844 ret = cgroup_apply_cftypes(cfts, true);
3846 cgroup_rm_cftypes_locked(cfts);
3848 mutex_unlock(&cgroup_mutex);
3853 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3854 * @ss: target cgroup subsystem
3855 * @cfts: zero-length name terminated array of cftypes
3857 * Similar to cgroup_add_cftypes() but the added files are only used for
3858 * the default hierarchy.
3860 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3864 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3865 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3866 return cgroup_add_cftypes(ss, cfts);
3870 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3871 * @ss: target cgroup subsystem
3872 * @cfts: zero-length name terminated array of cftypes
3874 * Similar to cgroup_add_cftypes() but the added files are only used for
3875 * the legacy hierarchies.
3877 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3881 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3882 cft->flags |= __CFTYPE_NOT_ON_DFL;
3883 return cgroup_add_cftypes(ss, cfts);
3887 * cgroup_file_notify - generate a file modified event for a cgroup_file
3888 * @cfile: target cgroup_file
3890 * @cfile must have been obtained by setting cftype->file_offset.
3892 void cgroup_file_notify(struct cgroup_file *cfile)
3894 unsigned long flags;
3896 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
3898 unsigned long last = cfile->notified_at;
3899 unsigned long next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
3901 if (time_in_range(jiffies, last, next)) {
3902 timer_reduce(&cfile->notify_timer, next);
3904 kernfs_notify(cfile->kn);
3905 cfile->notified_at = jiffies;
3908 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
3912 * css_next_child - find the next child of a given css
3913 * @pos: the current position (%NULL to initiate traversal)
3914 * @parent: css whose children to walk
3916 * This function returns the next child of @parent and should be called
3917 * under either cgroup_mutex or RCU read lock. The only requirement is
3918 * that @parent and @pos are accessible. The next sibling is guaranteed to
3919 * be returned regardless of their states.
3921 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3922 * css which finished ->css_online() is guaranteed to be visible in the
3923 * future iterations and will stay visible until the last reference is put.
3924 * A css which hasn't finished ->css_online() or already finished
3925 * ->css_offline() may show up during traversal. It's each subsystem's
3926 * responsibility to synchronize against on/offlining.
3928 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3929 struct cgroup_subsys_state *parent)
3931 struct cgroup_subsys_state *next;
3933 cgroup_assert_mutex_or_rcu_locked();
3936 * @pos could already have been unlinked from the sibling list.
3937 * Once a cgroup is removed, its ->sibling.next is no longer
3938 * updated when its next sibling changes. CSS_RELEASED is set when
3939 * @pos is taken off list, at which time its next pointer is valid,
3940 * and, as releases are serialized, the one pointed to by the next
3941 * pointer is guaranteed to not have started release yet. This
3942 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3943 * critical section, the one pointed to by its next pointer is
3944 * guaranteed to not have finished its RCU grace period even if we
3945 * have dropped rcu_read_lock() inbetween iterations.
3947 * If @pos has CSS_RELEASED set, its next pointer can't be
3948 * dereferenced; however, as each css is given a monotonically
3949 * increasing unique serial number and always appended to the
3950 * sibling list, the next one can be found by walking the parent's
3951 * children until the first css with higher serial number than
3952 * @pos's. While this path can be slower, it happens iff iteration
3953 * races against release and the race window is very small.
3956 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3957 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3958 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3960 list_for_each_entry_rcu(next, &parent->children, sibling)
3961 if (next->serial_nr > pos->serial_nr)
3966 * @next, if not pointing to the head, can be dereferenced and is
3969 if (&next->sibling != &parent->children)
3975 * css_next_descendant_pre - find the next descendant for pre-order walk
3976 * @pos: the current position (%NULL to initiate traversal)
3977 * @root: css whose descendants to walk
3979 * To be used by css_for_each_descendant_pre(). Find the next descendant
3980 * to visit for pre-order traversal of @root's descendants. @root is
3981 * included in the iteration and the first node to be visited.
3983 * While this function requires cgroup_mutex or RCU read locking, it
3984 * doesn't require the whole traversal to be contained in a single critical
3985 * section. This function will return the correct next descendant as long
3986 * as both @pos and @root are accessible and @pos is a descendant of @root.
3988 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3989 * css which finished ->css_online() is guaranteed to be visible in the
3990 * future iterations and will stay visible until the last reference is put.
3991 * A css which hasn't finished ->css_online() or already finished
3992 * ->css_offline() may show up during traversal. It's each subsystem's
3993 * responsibility to synchronize against on/offlining.
3995 struct cgroup_subsys_state *
3996 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3997 struct cgroup_subsys_state *root)
3999 struct cgroup_subsys_state *next;
4001 cgroup_assert_mutex_or_rcu_locked();
4003 /* if first iteration, visit @root */
4007 /* visit the first child if exists */
4008 next = css_next_child(NULL, pos);
4012 /* no child, visit my or the closest ancestor's next sibling */
4013 while (pos != root) {
4014 next = css_next_child(pos, pos->parent);
4024 * css_rightmost_descendant - return the rightmost descendant of a css
4025 * @pos: css of interest
4027 * Return the rightmost descendant of @pos. If there's no descendant, @pos
4028 * is returned. This can be used during pre-order traversal to skip
4031 * While this function requires cgroup_mutex or RCU read locking, it
4032 * doesn't require the whole traversal to be contained in a single critical
4033 * section. This function will return the correct rightmost descendant as
4034 * long as @pos is accessible.
4036 struct cgroup_subsys_state *
4037 css_rightmost_descendant(struct cgroup_subsys_state *pos)
4039 struct cgroup_subsys_state *last, *tmp;
4041 cgroup_assert_mutex_or_rcu_locked();
4045 /* ->prev isn't RCU safe, walk ->next till the end */
4047 css_for_each_child(tmp, last)
4054 static struct cgroup_subsys_state *
4055 css_leftmost_descendant(struct cgroup_subsys_state *pos)
4057 struct cgroup_subsys_state *last;
4061 pos = css_next_child(NULL, pos);
4068 * css_next_descendant_post - find the next descendant for post-order walk
4069 * @pos: the current position (%NULL to initiate traversal)
4070 * @root: css whose descendants to walk
4072 * To be used by css_for_each_descendant_post(). Find the next descendant
4073 * to visit for post-order traversal of @root's descendants. @root is
4074 * included in the iteration and the last node to be visited.
4076 * While this function requires cgroup_mutex or RCU read locking, it
4077 * doesn't require the whole traversal to be contained in a single critical
4078 * section. This function will return the correct next descendant as long
4079 * as both @pos and @cgroup are accessible and @pos is a descendant of
4082 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4083 * css which finished ->css_online() is guaranteed to be visible in the
4084 * future iterations and will stay visible until the last reference is put.
4085 * A css which hasn't finished ->css_online() or already finished
4086 * ->css_offline() may show up during traversal. It's each subsystem's
4087 * responsibility to synchronize against on/offlining.
4089 struct cgroup_subsys_state *
4090 css_next_descendant_post(struct cgroup_subsys_state *pos,
4091 struct cgroup_subsys_state *root)
4093 struct cgroup_subsys_state *next;
4095 cgroup_assert_mutex_or_rcu_locked();
4097 /* if first iteration, visit leftmost descendant which may be @root */
4099 return css_leftmost_descendant(root);
4101 /* if we visited @root, we're done */
4105 /* if there's an unvisited sibling, visit its leftmost descendant */
4106 next = css_next_child(pos, pos->parent);
4108 return css_leftmost_descendant(next);
4110 /* no sibling left, visit parent */
4115 * css_has_online_children - does a css have online children
4116 * @css: the target css
4118 * Returns %true if @css has any online children; otherwise, %false. This
4119 * function can be called from any context but the caller is responsible
4120 * for synchronizing against on/offlining as necessary.
4122 bool css_has_online_children(struct cgroup_subsys_state *css)
4124 struct cgroup_subsys_state *child;
4128 css_for_each_child(child, css) {
4129 if (child->flags & CSS_ONLINE) {
4138 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4140 struct list_head *l;
4141 struct cgrp_cset_link *link;
4142 struct css_set *cset;
4144 lockdep_assert_held(&css_set_lock);
4146 /* find the next threaded cset */
4147 if (it->tcset_pos) {
4148 l = it->tcset_pos->next;
4150 if (l != it->tcset_head) {
4152 return container_of(l, struct css_set,
4153 threaded_csets_node);
4156 it->tcset_pos = NULL;
4159 /* find the next cset */
4162 if (l == it->cset_head) {
4163 it->cset_pos = NULL;
4168 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4170 link = list_entry(l, struct cgrp_cset_link, cset_link);
4176 /* initialize threaded css_set walking */
4177 if (it->flags & CSS_TASK_ITER_THREADED) {
4179 put_css_set_locked(it->cur_dcset);
4180 it->cur_dcset = cset;
4183 it->tcset_head = &cset->threaded_csets;
4184 it->tcset_pos = &cset->threaded_csets;
4191 * css_task_iter_advance_css_set - advance a task itererator to the next css_set
4192 * @it: the iterator to advance
4194 * Advance @it to the next css_set to walk.
4196 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4198 struct css_set *cset;
4200 lockdep_assert_held(&css_set_lock);
4202 /* Advance to the next non-empty css_set */
4204 cset = css_task_iter_next_css_set(it);
4206 it->task_pos = NULL;
4209 } while (!css_set_populated(cset) && list_empty(&cset->dying_tasks));
4211 if (!list_empty(&cset->tasks)) {
4212 it->task_pos = cset->tasks.next;
4213 it->cur_tasks_head = &cset->tasks;
4214 } else if (!list_empty(&cset->mg_tasks)) {
4215 it->task_pos = cset->mg_tasks.next;
4216 it->cur_tasks_head = &cset->mg_tasks;
4218 it->task_pos = cset->dying_tasks.next;
4219 it->cur_tasks_head = &cset->dying_tasks;
4222 it->tasks_head = &cset->tasks;
4223 it->mg_tasks_head = &cset->mg_tasks;
4224 it->dying_tasks_head = &cset->dying_tasks;
4227 * We don't keep css_sets locked across iteration steps and thus
4228 * need to take steps to ensure that iteration can be resumed after
4229 * the lock is re-acquired. Iteration is performed at two levels -
4230 * css_sets and tasks in them.
4232 * Once created, a css_set never leaves its cgroup lists, so a
4233 * pinned css_set is guaranteed to stay put and we can resume
4234 * iteration afterwards.
4236 * Tasks may leave @cset across iteration steps. This is resolved
4237 * by registering each iterator with the css_set currently being
4238 * walked and making css_set_move_task() advance iterators whose
4239 * next task is leaving.
4242 list_del(&it->iters_node);
4243 put_css_set_locked(it->cur_cset);
4246 it->cur_cset = cset;
4247 list_add(&it->iters_node, &cset->task_iters);
4250 static void css_task_iter_skip(struct css_task_iter *it,
4251 struct task_struct *task)
4253 lockdep_assert_held(&css_set_lock);
4255 if (it->task_pos == &task->cg_list) {
4256 it->task_pos = it->task_pos->next;
4257 it->flags |= CSS_TASK_ITER_SKIPPED;
4261 static void css_task_iter_advance(struct css_task_iter *it)
4263 struct task_struct *task;
4265 lockdep_assert_held(&css_set_lock);
4269 * Advance iterator to find next entry. cset->tasks is
4270 * consumed first and then ->mg_tasks. After ->mg_tasks,
4271 * we move onto the next cset.
4273 if (it->flags & CSS_TASK_ITER_SKIPPED)
4274 it->flags &= ~CSS_TASK_ITER_SKIPPED;
4276 it->task_pos = it->task_pos->next;
4278 if (it->task_pos == it->tasks_head) {
4279 it->task_pos = it->mg_tasks_head->next;
4280 it->cur_tasks_head = it->mg_tasks_head;
4282 if (it->task_pos == it->mg_tasks_head) {
4283 it->task_pos = it->dying_tasks_head->next;
4284 it->cur_tasks_head = it->dying_tasks_head;
4286 if (it->task_pos == it->dying_tasks_head)
4287 css_task_iter_advance_css_set(it);
4289 /* called from start, proceed to the first cset */
4290 css_task_iter_advance_css_set(it);
4296 task = list_entry(it->task_pos, struct task_struct, cg_list);
4298 if (it->flags & CSS_TASK_ITER_PROCS) {
4299 /* if PROCS, skip over tasks which aren't group leaders */
4300 if (!thread_group_leader(task))
4303 /* and dying leaders w/o live member threads */
4304 if (it->cur_tasks_head == it->dying_tasks_head &&
4305 !atomic_read(&task->signal->live))
4308 /* skip all dying ones */
4309 if (it->cur_tasks_head == it->dying_tasks_head)
4315 * css_task_iter_start - initiate task iteration
4316 * @css: the css to walk tasks of
4317 * @flags: CSS_TASK_ITER_* flags
4318 * @it: the task iterator to use
4320 * Initiate iteration through the tasks of @css. The caller can call
4321 * css_task_iter_next() to walk through the tasks until the function
4322 * returns NULL. On completion of iteration, css_task_iter_end() must be
4325 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4326 struct css_task_iter *it)
4328 /* no one should try to iterate before mounting cgroups */
4329 WARN_ON_ONCE(!use_task_css_set_links);
4331 memset(it, 0, sizeof(*it));
4333 spin_lock_irq(&css_set_lock);
4339 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4341 it->cset_pos = &css->cgroup->cset_links;
4343 it->cset_head = it->cset_pos;
4345 css_task_iter_advance(it);
4347 spin_unlock_irq(&css_set_lock);
4351 * css_task_iter_next - return the next task for the iterator
4352 * @it: the task iterator being iterated
4354 * The "next" function for task iteration. @it should have been
4355 * initialized via css_task_iter_start(). Returns NULL when the iteration
4358 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4361 put_task_struct(it->cur_task);
4362 it->cur_task = NULL;
4365 spin_lock_irq(&css_set_lock);
4367 /* @it may be half-advanced by skips, finish advancing */
4368 if (it->flags & CSS_TASK_ITER_SKIPPED)
4369 css_task_iter_advance(it);
4372 it->cur_task = list_entry(it->task_pos, struct task_struct,
4374 get_task_struct(it->cur_task);
4375 css_task_iter_advance(it);
4378 spin_unlock_irq(&css_set_lock);
4380 return it->cur_task;
4384 * css_task_iter_end - finish task iteration
4385 * @it: the task iterator to finish
4387 * Finish task iteration started by css_task_iter_start().
4389 void css_task_iter_end(struct css_task_iter *it)
4392 spin_lock_irq(&css_set_lock);
4393 list_del(&it->iters_node);
4394 put_css_set_locked(it->cur_cset);
4395 spin_unlock_irq(&css_set_lock);
4399 put_css_set(it->cur_dcset);
4402 put_task_struct(it->cur_task);
4405 static void cgroup_procs_release(struct kernfs_open_file *of)
4407 struct cgroup_file_ctx *ctx = of->priv;
4409 if (ctx->procs.started)
4410 css_task_iter_end(&ctx->procs.iter);
4413 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
4415 struct kernfs_open_file *of = s->private;
4416 struct cgroup_file_ctx *ctx = of->priv;
4421 return css_task_iter_next(&ctx->procs.iter);
4424 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
4425 unsigned int iter_flags)
4427 struct kernfs_open_file *of = s->private;
4428 struct cgroup *cgrp = seq_css(s)->cgroup;
4429 struct cgroup_file_ctx *ctx = of->priv;
4430 struct css_task_iter *it = &ctx->procs.iter;
4433 * When a seq_file is seeked, it's always traversed sequentially
4434 * from position 0, so we can simply keep iterating on !0 *pos.
4436 if (!ctx->procs.started) {
4437 if (WARN_ON_ONCE((*pos)))
4438 return ERR_PTR(-EINVAL);
4439 css_task_iter_start(&cgrp->self, iter_flags, it);
4440 ctx->procs.started = true;
4441 } else if (!(*pos)) {
4442 css_task_iter_end(it);
4443 css_task_iter_start(&cgrp->self, iter_flags, it);
4445 return it->cur_task;
4447 return cgroup_procs_next(s, NULL, NULL);
4450 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
4452 struct cgroup *cgrp = seq_css(s)->cgroup;
4455 * All processes of a threaded subtree belong to the domain cgroup
4456 * of the subtree. Only threads can be distributed across the
4457 * subtree. Reject reads on cgroup.procs in the subtree proper.
4458 * They're always empty anyway.
4460 if (cgroup_is_threaded(cgrp))
4461 return ERR_PTR(-EOPNOTSUPP);
4463 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
4464 CSS_TASK_ITER_THREADED);
4467 static int cgroup_procs_show(struct seq_file *s, void *v)
4469 seq_printf(s, "%d\n", task_pid_vnr(v));
4473 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
4474 struct cgroup *dst_cgrp,
4475 struct super_block *sb,
4476 struct cgroup_namespace *ns)
4478 struct cgroup *com_cgrp = src_cgrp;
4479 struct inode *inode;
4482 lockdep_assert_held(&cgroup_mutex);
4484 /* find the common ancestor */
4485 while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
4486 com_cgrp = cgroup_parent(com_cgrp);
4488 /* %current should be authorized to migrate to the common ancestor */
4489 inode = kernfs_get_inode(sb, com_cgrp->procs_file.kn);
4493 ret = inode_permission(inode, MAY_WRITE);
4499 * If namespaces are delegation boundaries, %current must be able
4500 * to see both source and destination cgroups from its namespace.
4502 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
4503 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
4504 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
4510 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
4511 char *buf, size_t nbytes, loff_t off)
4513 struct cgroup_file_ctx *ctx = of->priv;
4514 struct cgroup *src_cgrp, *dst_cgrp;
4515 struct task_struct *task;
4516 const struct cred *saved_cred;
4519 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4523 task = cgroup_procs_write_start(buf, true);
4524 ret = PTR_ERR_OR_ZERO(task);
4528 /* find the source cgroup */
4529 spin_lock_irq(&css_set_lock);
4530 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4531 spin_unlock_irq(&css_set_lock);
4534 * Process and thread migrations follow same delegation rule. Check
4535 * permissions using the credentials from file open to protect against
4536 * inherited fd attacks.
4538 saved_cred = override_creds(of->file->f_cred);
4539 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4540 of->file->f_path.dentry->d_sb,
4542 revert_creds(saved_cred);
4546 ret = cgroup_attach_task(dst_cgrp, task, true);
4549 cgroup_procs_write_finish(task);
4551 cgroup_kn_unlock(of->kn);
4553 return ret ?: nbytes;
4556 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
4558 return __cgroup_procs_start(s, pos, 0);
4561 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
4562 char *buf, size_t nbytes, loff_t off)
4564 struct cgroup_file_ctx *ctx = of->priv;
4565 struct cgroup *src_cgrp, *dst_cgrp;
4566 struct task_struct *task;
4567 const struct cred *saved_cred;
4570 buf = strstrip(buf);
4572 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4576 task = cgroup_procs_write_start(buf, false);
4577 ret = PTR_ERR_OR_ZERO(task);
4581 /* find the source cgroup */
4582 spin_lock_irq(&css_set_lock);
4583 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4584 spin_unlock_irq(&css_set_lock);
4587 * Process and thread migrations follow same delegation rule. Check
4588 * permissions using the credentials from file open to protect against
4589 * inherited fd attacks.
4591 saved_cred = override_creds(of->file->f_cred);
4592 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4593 of->file->f_path.dentry->d_sb,
4595 revert_creds(saved_cred);
4599 /* and must be contained in the same domain */
4601 if (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp)
4604 ret = cgroup_attach_task(dst_cgrp, task, false);
4607 cgroup_procs_write_finish(task);
4609 cgroup_kn_unlock(of->kn);
4611 return ret ?: nbytes;
4614 /* cgroup core interface files for the default hierarchy */
4615 static struct cftype cgroup_base_files[] = {
4617 .name = "cgroup.type",
4618 .flags = CFTYPE_NOT_ON_ROOT,
4619 .seq_show = cgroup_type_show,
4620 .write = cgroup_type_write,
4623 .name = "cgroup.procs",
4624 .flags = CFTYPE_NS_DELEGATABLE,
4625 .file_offset = offsetof(struct cgroup, procs_file),
4626 .release = cgroup_procs_release,
4627 .seq_start = cgroup_procs_start,
4628 .seq_next = cgroup_procs_next,
4629 .seq_show = cgroup_procs_show,
4630 .write = cgroup_procs_write,
4633 .name = "cgroup.threads",
4634 .flags = CFTYPE_NS_DELEGATABLE,
4635 .release = cgroup_procs_release,
4636 .seq_start = cgroup_threads_start,
4637 .seq_next = cgroup_procs_next,
4638 .seq_show = cgroup_procs_show,
4639 .write = cgroup_threads_write,
4642 .name = "cgroup.controllers",
4643 .seq_show = cgroup_controllers_show,
4646 .name = "cgroup.subtree_control",
4647 .flags = CFTYPE_NS_DELEGATABLE,
4648 .seq_show = cgroup_subtree_control_show,
4649 .write = cgroup_subtree_control_write,
4652 .name = "cgroup.events",
4653 .flags = CFTYPE_NOT_ON_ROOT,
4654 .file_offset = offsetof(struct cgroup, events_file),
4655 .seq_show = cgroup_events_show,
4658 .name = "cgroup.max.descendants",
4659 .seq_show = cgroup_max_descendants_show,
4660 .write = cgroup_max_descendants_write,
4663 .name = "cgroup.max.depth",
4664 .seq_show = cgroup_max_depth_show,
4665 .write = cgroup_max_depth_write,
4668 .name = "cgroup.stat",
4669 .seq_show = cgroup_stat_show,
4673 .flags = CFTYPE_NOT_ON_ROOT,
4674 .seq_show = cpu_stat_show,
4680 * css destruction is four-stage process.
4682 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4683 * Implemented in kill_css().
4685 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4686 * and thus css_tryget_online() is guaranteed to fail, the css can be
4687 * offlined by invoking offline_css(). After offlining, the base ref is
4688 * put. Implemented in css_killed_work_fn().
4690 * 3. When the percpu_ref reaches zero, the only possible remaining
4691 * accessors are inside RCU read sections. css_release() schedules the
4694 * 4. After the grace period, the css can be freed. Implemented in
4695 * css_free_work_fn().
4697 * It is actually hairier because both step 2 and 4 require process context
4698 * and thus involve punting to css->destroy_work adding two additional
4699 * steps to the already complex sequence.
4701 static void css_free_rwork_fn(struct work_struct *work)
4703 struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
4704 struct cgroup_subsys_state, destroy_rwork);
4705 struct cgroup_subsys *ss = css->ss;
4706 struct cgroup *cgrp = css->cgroup;
4708 percpu_ref_exit(&css->refcnt);
4712 struct cgroup_subsys_state *parent = css->parent;
4716 cgroup_idr_remove(&ss->css_idr, id);
4722 /* cgroup free path */
4723 atomic_dec(&cgrp->root->nr_cgrps);
4724 cgroup1_pidlist_destroy_all(cgrp);
4725 cancel_work_sync(&cgrp->release_agent_work);
4727 if (cgroup_parent(cgrp)) {
4729 * We get a ref to the parent, and put the ref when
4730 * this cgroup is being freed, so it's guaranteed
4731 * that the parent won't be destroyed before its
4734 cgroup_put(cgroup_parent(cgrp));
4735 kernfs_put(cgrp->kn);
4736 if (cgroup_on_dfl(cgrp))
4737 cgroup_rstat_exit(cgrp);
4741 * This is root cgroup's refcnt reaching zero,
4742 * which indicates that the root should be
4745 cgroup_destroy_root(cgrp->root);
4750 static void css_release_work_fn(struct work_struct *work)
4752 struct cgroup_subsys_state *css =
4753 container_of(work, struct cgroup_subsys_state, destroy_work);
4754 struct cgroup_subsys *ss = css->ss;
4755 struct cgroup *cgrp = css->cgroup;
4757 mutex_lock(&cgroup_mutex);
4759 css->flags |= CSS_RELEASED;
4760 list_del_rcu(&css->sibling);
4763 /* css release path */
4764 if (!list_empty(&css->rstat_css_node)) {
4765 cgroup_rstat_flush(cgrp);
4766 list_del_rcu(&css->rstat_css_node);
4769 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4770 if (ss->css_released)
4771 ss->css_released(css);
4773 struct cgroup *tcgrp;
4775 /* cgroup release path */
4776 TRACE_CGROUP_PATH(release, cgrp);
4778 if (cgroup_on_dfl(cgrp))
4779 cgroup_rstat_flush(cgrp);
4781 spin_lock_irq(&css_set_lock);
4782 for (tcgrp = cgroup_parent(cgrp); tcgrp;
4783 tcgrp = cgroup_parent(tcgrp))
4784 tcgrp->nr_dying_descendants--;
4785 spin_unlock_irq(&css_set_lock);
4787 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4791 * There are two control paths which try to determine
4792 * cgroup from dentry without going through kernfs -
4793 * cgroupstats_build() and css_tryget_online_from_dir().
4794 * Those are supported by RCU protecting clearing of
4795 * cgrp->kn->priv backpointer.
4798 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
4801 cgroup_bpf_put(cgrp);
4804 mutex_unlock(&cgroup_mutex);
4806 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
4807 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
4810 static void css_release(struct percpu_ref *ref)
4812 struct cgroup_subsys_state *css =
4813 container_of(ref, struct cgroup_subsys_state, refcnt);
4815 INIT_WORK(&css->destroy_work, css_release_work_fn);
4816 queue_work(cgroup_destroy_wq, &css->destroy_work);
4819 static void init_and_link_css(struct cgroup_subsys_state *css,
4820 struct cgroup_subsys *ss, struct cgroup *cgrp)
4822 lockdep_assert_held(&cgroup_mutex);
4824 cgroup_get_live(cgrp);
4826 memset(css, 0, sizeof(*css));
4830 INIT_LIST_HEAD(&css->sibling);
4831 INIT_LIST_HEAD(&css->children);
4832 INIT_LIST_HEAD(&css->rstat_css_node);
4833 css->serial_nr = css_serial_nr_next++;
4834 atomic_set(&css->online_cnt, 0);
4836 if (cgroup_parent(cgrp)) {
4837 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4838 css_get(css->parent);
4841 if (cgroup_on_dfl(cgrp) && ss->css_rstat_flush)
4842 list_add_rcu(&css->rstat_css_node, &cgrp->rstat_css_list);
4844 BUG_ON(cgroup_css(cgrp, ss));
4847 /* invoke ->css_online() on a new CSS and mark it online if successful */
4848 static int online_css(struct cgroup_subsys_state *css)
4850 struct cgroup_subsys *ss = css->ss;
4853 lockdep_assert_held(&cgroup_mutex);
4856 ret = ss->css_online(css);
4858 css->flags |= CSS_ONLINE;
4859 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4861 atomic_inc(&css->online_cnt);
4863 atomic_inc(&css->parent->online_cnt);
4868 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4869 static void offline_css(struct cgroup_subsys_state *css)
4871 struct cgroup_subsys *ss = css->ss;
4873 lockdep_assert_held(&cgroup_mutex);
4875 if (!(css->flags & CSS_ONLINE))
4878 if (ss->css_offline)
4879 ss->css_offline(css);
4881 css->flags &= ~CSS_ONLINE;
4882 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4884 wake_up_all(&css->cgroup->offline_waitq);
4888 * css_create - create a cgroup_subsys_state
4889 * @cgrp: the cgroup new css will be associated with
4890 * @ss: the subsys of new css
4892 * Create a new css associated with @cgrp - @ss pair. On success, the new
4893 * css is online and installed in @cgrp. This function doesn't create the
4894 * interface files. Returns 0 on success, -errno on failure.
4896 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
4897 struct cgroup_subsys *ss)
4899 struct cgroup *parent = cgroup_parent(cgrp);
4900 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4901 struct cgroup_subsys_state *css;
4904 lockdep_assert_held(&cgroup_mutex);
4906 css = ss->css_alloc(parent_css);
4908 css = ERR_PTR(-ENOMEM);
4912 init_and_link_css(css, ss, cgrp);
4914 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4918 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
4923 /* @css is ready to be brought online now, make it visible */
4924 list_add_tail_rcu(&css->sibling, &parent_css->children);
4925 cgroup_idr_replace(&ss->css_idr, css, css->id);
4927 err = online_css(css);
4931 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4932 cgroup_parent(parent)) {
4933 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4934 current->comm, current->pid, ss->name);
4935 if (!strcmp(ss->name, "memory"))
4936 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4937 ss->warned_broken_hierarchy = true;
4943 list_del_rcu(&css->sibling);
4945 list_del_rcu(&css->rstat_css_node);
4946 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
4947 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
4948 return ERR_PTR(err);
4952 * The returned cgroup is fully initialized including its control mask, but
4953 * it isn't associated with its kernfs_node and doesn't have the control
4956 static struct cgroup *cgroup_create(struct cgroup *parent)
4958 struct cgroup_root *root = parent->root;
4959 struct cgroup *cgrp, *tcgrp;
4960 int level = parent->level + 1;
4963 /* allocate the cgroup and its ID, 0 is reserved for the root */
4964 cgrp = kzalloc(struct_size(cgrp, ancestor_ids, (level + 1)),
4967 return ERR_PTR(-ENOMEM);
4969 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
4973 if (cgroup_on_dfl(parent)) {
4974 ret = cgroup_rstat_init(cgrp);
4976 goto out_cancel_ref;
4980 * Temporarily set the pointer to NULL, so idr_find() won't return
4981 * a half-baked cgroup.
4983 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
4989 init_cgroup_housekeeping(cgrp);
4991 cgrp->self.parent = &parent->self;
4993 cgrp->level = level;
4994 ret = cgroup_bpf_inherit(cgrp);
4998 spin_lock_irq(&css_set_lock);
4999 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5000 cgrp->ancestor_ids[tcgrp->level] = tcgrp->id;
5003 tcgrp->nr_descendants++;
5005 spin_unlock_irq(&css_set_lock);
5007 if (notify_on_release(parent))
5008 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
5010 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
5011 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
5013 cgrp->self.serial_nr = css_serial_nr_next++;
5015 /* allocation complete, commit to creation */
5016 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
5017 atomic_inc(&root->nr_cgrps);
5018 cgroup_get_live(parent);
5021 * @cgrp is now fully operational. If something fails after this
5022 * point, it'll be released via the normal destruction path.
5024 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
5027 * On the default hierarchy, a child doesn't automatically inherit
5028 * subtree_control from the parent. Each is configured manually.
5030 if (!cgroup_on_dfl(cgrp))
5031 cgrp->subtree_control = cgroup_control(cgrp);
5033 cgroup_propagate_control(cgrp);
5038 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
5040 if (cgroup_on_dfl(parent))
5041 cgroup_rstat_exit(cgrp);
5043 percpu_ref_exit(&cgrp->self.refcnt);
5046 return ERR_PTR(ret);
5049 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
5051 struct cgroup *cgroup;
5055 lockdep_assert_held(&cgroup_mutex);
5057 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
5058 if (cgroup->nr_descendants >= cgroup->max_descendants)
5061 if (level > cgroup->max_depth)
5072 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
5074 struct cgroup *parent, *cgrp;
5075 struct kernfs_node *kn;
5078 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
5079 if (strchr(name, '\n'))
5082 parent = cgroup_kn_lock_live(parent_kn, false);
5086 if (!cgroup_check_hierarchy_limits(parent)) {
5091 cgrp = cgroup_create(parent);
5093 ret = PTR_ERR(cgrp);
5097 /* create the directory */
5098 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
5106 * This extra ref will be put in cgroup_free_fn() and guarantees
5107 * that @cgrp->kn is always accessible.
5111 ret = cgroup_kn_set_ugid(kn);
5115 ret = css_populate_dir(&cgrp->self);
5119 ret = cgroup_apply_control_enable(cgrp);
5123 TRACE_CGROUP_PATH(mkdir, cgrp);
5125 /* let's create and online css's */
5126 kernfs_activate(kn);
5132 cgroup_destroy_locked(cgrp);
5134 cgroup_kn_unlock(parent_kn);
5139 * This is called when the refcnt of a css is confirmed to be killed.
5140 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
5141 * initate destruction and put the css ref from kill_css().
5143 static void css_killed_work_fn(struct work_struct *work)
5145 struct cgroup_subsys_state *css =
5146 container_of(work, struct cgroup_subsys_state, destroy_work);
5148 mutex_lock(&cgroup_mutex);
5153 /* @css can't go away while we're holding cgroup_mutex */
5155 } while (css && atomic_dec_and_test(&css->online_cnt));
5157 mutex_unlock(&cgroup_mutex);
5160 /* css kill confirmation processing requires process context, bounce */
5161 static void css_killed_ref_fn(struct percpu_ref *ref)
5163 struct cgroup_subsys_state *css =
5164 container_of(ref, struct cgroup_subsys_state, refcnt);
5166 if (atomic_dec_and_test(&css->online_cnt)) {
5167 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5168 queue_work(cgroup_destroy_wq, &css->destroy_work);
5173 * kill_css - destroy a css
5174 * @css: css to destroy
5176 * This function initiates destruction of @css by removing cgroup interface
5177 * files and putting its base reference. ->css_offline() will be invoked
5178 * asynchronously once css_tryget_online() is guaranteed to fail and when
5179 * the reference count reaches zero, @css will be released.
5181 static void kill_css(struct cgroup_subsys_state *css)
5183 lockdep_assert_held(&cgroup_mutex);
5185 if (css->flags & CSS_DYING)
5188 css->flags |= CSS_DYING;
5191 * This must happen before css is disassociated with its cgroup.
5192 * See seq_css() for details.
5197 * Killing would put the base ref, but we need to keep it alive
5198 * until after ->css_offline().
5203 * cgroup core guarantees that, by the time ->css_offline() is
5204 * invoked, no new css reference will be given out via
5205 * css_tryget_online(). We can't simply call percpu_ref_kill() and
5206 * proceed to offlining css's because percpu_ref_kill() doesn't
5207 * guarantee that the ref is seen as killed on all CPUs on return.
5209 * Use percpu_ref_kill_and_confirm() to get notifications as each
5210 * css is confirmed to be seen as killed on all CPUs.
5212 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5216 * cgroup_destroy_locked - the first stage of cgroup destruction
5217 * @cgrp: cgroup to be destroyed
5219 * css's make use of percpu refcnts whose killing latency shouldn't be
5220 * exposed to userland and are RCU protected. Also, cgroup core needs to
5221 * guarantee that css_tryget_online() won't succeed by the time
5222 * ->css_offline() is invoked. To satisfy all the requirements,
5223 * destruction is implemented in the following two steps.
5225 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
5226 * userland visible parts and start killing the percpu refcnts of
5227 * css's. Set up so that the next stage will be kicked off once all
5228 * the percpu refcnts are confirmed to be killed.
5230 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5231 * rest of destruction. Once all cgroup references are gone, the
5232 * cgroup is RCU-freed.
5234 * This function implements s1. After this step, @cgrp is gone as far as
5235 * the userland is concerned and a new cgroup with the same name may be
5236 * created. As cgroup doesn't care about the names internally, this
5237 * doesn't cause any problem.
5239 static int cgroup_destroy_locked(struct cgroup *cgrp)
5240 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5242 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5243 struct cgroup_subsys_state *css;
5244 struct cgrp_cset_link *link;
5247 lockdep_assert_held(&cgroup_mutex);
5250 * Only migration can raise populated from zero and we're already
5251 * holding cgroup_mutex.
5253 if (cgroup_is_populated(cgrp))
5257 * Make sure there's no live children. We can't test emptiness of
5258 * ->self.children as dead children linger on it while being
5259 * drained; otherwise, "rmdir parent/child parent" may fail.
5261 if (css_has_online_children(&cgrp->self))
5265 * Mark @cgrp and the associated csets dead. The former prevents
5266 * further task migration and child creation by disabling
5267 * cgroup_lock_live_group(). The latter makes the csets ignored by
5268 * the migration path.
5270 cgrp->self.flags &= ~CSS_ONLINE;
5272 spin_lock_irq(&css_set_lock);
5273 list_for_each_entry(link, &cgrp->cset_links, cset_link)
5274 link->cset->dead = true;
5275 spin_unlock_irq(&css_set_lock);
5277 /* initiate massacre of all css's */
5278 for_each_css(css, ssid, cgrp)
5281 /* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
5282 css_clear_dir(&cgrp->self);
5283 kernfs_remove(cgrp->kn);
5285 if (parent && cgroup_is_threaded(cgrp))
5286 parent->nr_threaded_children--;
5288 spin_lock_irq(&css_set_lock);
5289 for (tcgrp = cgroup_parent(cgrp); tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5290 tcgrp->nr_descendants--;
5291 tcgrp->nr_dying_descendants++;
5293 spin_unlock_irq(&css_set_lock);
5295 cgroup1_check_for_release(parent);
5297 /* put the base reference */
5298 percpu_ref_kill(&cgrp->self.refcnt);
5303 int cgroup_rmdir(struct kernfs_node *kn)
5305 struct cgroup *cgrp;
5308 cgrp = cgroup_kn_lock_live(kn, false);
5312 ret = cgroup_destroy_locked(cgrp);
5314 TRACE_CGROUP_PATH(rmdir, cgrp);
5316 cgroup_kn_unlock(kn);
5320 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5321 .show_options = cgroup_show_options,
5322 .remount_fs = cgroup_remount,
5323 .mkdir = cgroup_mkdir,
5324 .rmdir = cgroup_rmdir,
5325 .show_path = cgroup_show_path,
5328 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5330 struct cgroup_subsys_state *css;
5332 pr_debug("Initializing cgroup subsys %s\n", ss->name);
5334 mutex_lock(&cgroup_mutex);
5336 idr_init(&ss->css_idr);
5337 INIT_LIST_HEAD(&ss->cfts);
5339 /* Create the root cgroup state for this subsystem */
5340 ss->root = &cgrp_dfl_root;
5341 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5342 /* We don't handle early failures gracefully */
5343 BUG_ON(IS_ERR(css));
5344 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5347 * Root csses are never destroyed and we can't initialize
5348 * percpu_ref during early init. Disable refcnting.
5350 css->flags |= CSS_NO_REF;
5353 /* allocation can't be done safely during early init */
5356 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5357 BUG_ON(css->id < 0);
5360 /* Update the init_css_set to contain a subsys
5361 * pointer to this state - since the subsystem is
5362 * newly registered, all tasks and hence the
5363 * init_css_set is in the subsystem's root cgroup. */
5364 init_css_set.subsys[ss->id] = css;
5366 have_fork_callback |= (bool)ss->fork << ss->id;
5367 have_exit_callback |= (bool)ss->exit << ss->id;
5368 have_release_callback |= (bool)ss->release << ss->id;
5369 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5371 /* At system boot, before all subsystems have been
5372 * registered, no tasks have been forked, so we don't
5373 * need to invoke fork callbacks here. */
5374 BUG_ON(!list_empty(&init_task.tasks));
5376 BUG_ON(online_css(css));
5378 mutex_unlock(&cgroup_mutex);
5382 * cgroup_init_early - cgroup initialization at system boot
5384 * Initialize cgroups at system boot, and initialize any
5385 * subsystems that request early init.
5387 int __init cgroup_init_early(void)
5389 static struct cgroup_sb_opts __initdata opts;
5390 struct cgroup_subsys *ss;
5393 init_cgroup_root(&cgrp_dfl_root, &opts);
5394 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5396 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5398 for_each_subsys(ss, i) {
5399 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5400 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
5401 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5403 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5404 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5407 ss->name = cgroup_subsys_name[i];
5408 if (!ss->legacy_name)
5409 ss->legacy_name = cgroup_subsys_name[i];
5412 cgroup_init_subsys(ss, true);
5418 * cgroup_init - cgroup initialization
5420 * Register cgroup filesystem and /proc file, and initialize
5421 * any subsystems that didn't request early init.
5423 int __init cgroup_init(void)
5425 struct cgroup_subsys *ss;
5428 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
5429 BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
5430 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
5431 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
5433 cgroup_rstat_boot();
5436 * The latency of the synchronize_sched() is too high for cgroups,
5437 * avoid it at the cost of forcing all readers into the slow path.
5439 rcu_sync_enter_start(&cgroup_threadgroup_rwsem.rss);
5441 get_user_ns(init_cgroup_ns.user_ns);
5443 mutex_lock(&cgroup_mutex);
5446 * Add init_css_set to the hash table so that dfl_root can link to
5449 hash_add(css_set_table, &init_css_set.hlist,
5450 css_set_hash(init_css_set.subsys));
5452 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0, 0));
5454 mutex_unlock(&cgroup_mutex);
5456 for_each_subsys(ss, ssid) {
5457 if (ss->early_init) {
5458 struct cgroup_subsys_state *css =
5459 init_css_set.subsys[ss->id];
5461 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5463 BUG_ON(css->id < 0);
5465 cgroup_init_subsys(ss, false);
5468 list_add_tail(&init_css_set.e_cset_node[ssid],
5469 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5472 * Setting dfl_root subsys_mask needs to consider the
5473 * disabled flag and cftype registration needs kmalloc,
5474 * both of which aren't available during early_init.
5476 if (!cgroup_ssid_enabled(ssid))
5479 if (cgroup1_ssid_disabled(ssid))
5480 printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
5483 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5485 /* implicit controllers must be threaded too */
5486 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
5488 if (ss->implicit_on_dfl)
5489 cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
5490 else if (!ss->dfl_cftypes)
5491 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
5494 cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
5496 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5497 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5499 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5500 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5504 ss->bind(init_css_set.subsys[ssid]);
5506 mutex_lock(&cgroup_mutex);
5507 css_populate_dir(init_css_set.subsys[ssid]);
5508 mutex_unlock(&cgroup_mutex);
5511 /* init_css_set.subsys[] has been updated, re-hash */
5512 hash_del(&init_css_set.hlist);
5513 hash_add(css_set_table, &init_css_set.hlist,
5514 css_set_hash(init_css_set.subsys));
5516 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
5517 WARN_ON(register_filesystem(&cgroup_fs_type));
5518 WARN_ON(register_filesystem(&cgroup2_fs_type));
5519 WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show));
5524 static int __init cgroup_wq_init(void)
5527 * There isn't much point in executing destruction path in
5528 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5529 * Use 1 for @max_active.
5531 * We would prefer to do this in cgroup_init() above, but that
5532 * is called before init_workqueues(): so leave this until after.
5534 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5535 BUG_ON(!cgroup_destroy_wq);
5538 core_initcall(cgroup_wq_init);
5540 void cgroup_path_from_kernfs_id(const union kernfs_node_id *id,
5541 char *buf, size_t buflen)
5543 struct kernfs_node *kn;
5545 kn = kernfs_get_node_by_id(cgrp_dfl_root.kf_root, id);
5548 kernfs_path(kn, buf, buflen);
5553 * proc_cgroup_show()
5554 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5555 * - Used for /proc/<pid>/cgroup.
5557 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5558 struct pid *pid, struct task_struct *tsk)
5562 struct cgroup_root *root;
5565 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5569 mutex_lock(&cgroup_mutex);
5570 spin_lock_irq(&css_set_lock);
5572 for_each_root(root) {
5573 struct cgroup_subsys *ss;
5574 struct cgroup *cgrp;
5575 int ssid, count = 0;
5577 if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
5580 seq_printf(m, "%d:", root->hierarchy_id);
5581 if (root != &cgrp_dfl_root)
5582 for_each_subsys(ss, ssid)
5583 if (root->subsys_mask & (1 << ssid))
5584 seq_printf(m, "%s%s", count++ ? "," : "",
5586 if (strlen(root->name))
5587 seq_printf(m, "%sname=%s", count ? "," : "",
5591 cgrp = task_cgroup_from_root(tsk, root);
5594 * On traditional hierarchies, all zombie tasks show up as
5595 * belonging to the root cgroup. On the default hierarchy,
5596 * while a zombie doesn't show up in "cgroup.procs" and
5597 * thus can't be migrated, its /proc/PID/cgroup keeps
5598 * reporting the cgroup it belonged to before exiting. If
5599 * the cgroup is removed before the zombie is reaped,
5600 * " (deleted)" is appended to the cgroup path.
5602 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
5603 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
5604 current->nsproxy->cgroup_ns);
5605 if (retval >= PATH_MAX)
5606 retval = -ENAMETOOLONG;
5615 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
5616 seq_puts(m, " (deleted)\n");
5623 spin_unlock_irq(&css_set_lock);
5624 mutex_unlock(&cgroup_mutex);
5631 * cgroup_fork - initialize cgroup related fields during copy_process()
5632 * @child: pointer to task_struct of forking parent process.
5634 * A task is associated with the init_css_set until cgroup_post_fork()
5635 * attaches it to the parent's css_set. Empty cg_list indicates that
5636 * @child isn't holding reference to its css_set.
5638 void cgroup_fork(struct task_struct *child)
5640 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5641 INIT_LIST_HEAD(&child->cg_list);
5645 * cgroup_can_fork - called on a new task before the process is exposed
5646 * @child: the task in question.
5648 * This calls the subsystem can_fork() callbacks. If the can_fork() callback
5649 * returns an error, the fork aborts with that error code. This allows for
5650 * a cgroup subsystem to conditionally allow or deny new forks.
5652 int cgroup_can_fork(struct task_struct *child)
5654 struct cgroup_subsys *ss;
5657 do_each_subsys_mask(ss, i, have_canfork_callback) {
5658 ret = ss->can_fork(child);
5661 } while_each_subsys_mask();
5666 for_each_subsys(ss, j) {
5669 if (ss->cancel_fork)
5670 ss->cancel_fork(child);
5677 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
5678 * @child: the task in question
5680 * This calls the cancel_fork() callbacks if a fork failed *after*
5681 * cgroup_can_fork() succeded.
5683 void cgroup_cancel_fork(struct task_struct *child)
5685 struct cgroup_subsys *ss;
5688 for_each_subsys(ss, i)
5689 if (ss->cancel_fork)
5690 ss->cancel_fork(child);
5694 * cgroup_post_fork - called on a new task after adding it to the task list
5695 * @child: the task in question
5697 * Adds the task to the list running through its css_set if necessary and
5698 * call the subsystem fork() callbacks. Has to be after the task is
5699 * visible on the task list in case we race with the first call to
5700 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5703 void cgroup_post_fork(struct task_struct *child)
5705 struct cgroup_subsys *ss;
5709 * This may race against cgroup_enable_task_cg_lists(). As that
5710 * function sets use_task_css_set_links before grabbing
5711 * tasklist_lock and we just went through tasklist_lock to add
5712 * @child, it's guaranteed that either we see the set
5713 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5714 * @child during its iteration.
5716 * If we won the race, @child is associated with %current's
5717 * css_set. Grabbing css_set_lock guarantees both that the
5718 * association is stable, and, on completion of the parent's
5719 * migration, @child is visible in the source of migration or
5720 * already in the destination cgroup. This guarantee is necessary
5721 * when implementing operations which need to migrate all tasks of
5722 * a cgroup to another.
5724 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5725 * will remain in init_css_set. This is safe because all tasks are
5726 * in the init_css_set before cg_links is enabled and there's no
5727 * operation which transfers all tasks out of init_css_set.
5729 if (use_task_css_set_links) {
5730 struct css_set *cset;
5732 spin_lock_irq(&css_set_lock);
5733 cset = task_css_set(current);
5734 if (list_empty(&child->cg_list)) {
5737 css_set_move_task(child, NULL, cset, false);
5739 spin_unlock_irq(&css_set_lock);
5743 * Call ss->fork(). This must happen after @child is linked on
5744 * css_set; otherwise, @child might change state between ->fork()
5745 * and addition to css_set.
5747 do_each_subsys_mask(ss, i, have_fork_callback) {
5749 } while_each_subsys_mask();
5753 * cgroup_exit - detach cgroup from exiting task
5754 * @tsk: pointer to task_struct of exiting process
5756 * Description: Detach cgroup from @tsk and release it.
5758 * Note that cgroups marked notify_on_release force every task in
5759 * them to take the global cgroup_mutex mutex when exiting.
5760 * This could impact scaling on very large systems. Be reluctant to
5761 * use notify_on_release cgroups where very high task exit scaling
5762 * is required on large systems.
5764 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5765 * call cgroup_exit() while the task is still competent to handle
5766 * notify_on_release(), then leave the task attached to the root cgroup in
5767 * each hierarchy for the remainder of its exit. No need to bother with
5768 * init_css_set refcnting. init_css_set never goes away and we can't race
5769 * with migration path - PF_EXITING is visible to migration path.
5771 void cgroup_exit(struct task_struct *tsk)
5773 struct cgroup_subsys *ss;
5774 struct css_set *cset;
5778 * Unlink from @tsk from its css_set. As migration path can't race
5779 * with us, we can check css_set and cg_list without synchronization.
5781 cset = task_css_set(tsk);
5783 if (!list_empty(&tsk->cg_list)) {
5784 spin_lock_irq(&css_set_lock);
5785 css_set_move_task(tsk, cset, NULL, false);
5786 list_add_tail(&tsk->cg_list, &cset->dying_tasks);
5788 spin_unlock_irq(&css_set_lock);
5793 /* see cgroup_post_fork() for details */
5794 do_each_subsys_mask(ss, i, have_exit_callback) {
5796 } while_each_subsys_mask();
5799 void cgroup_release(struct task_struct *task)
5801 struct cgroup_subsys *ss;
5804 do_each_subsys_mask(ss, ssid, have_release_callback) {
5806 } while_each_subsys_mask();
5808 if (use_task_css_set_links) {
5809 spin_lock_irq(&css_set_lock);
5810 css_set_skip_task_iters(task_css_set(task), task);
5811 list_del_init(&task->cg_list);
5812 spin_unlock_irq(&css_set_lock);
5816 void cgroup_free(struct task_struct *task)
5818 struct css_set *cset = task_css_set(task);
5822 static int __init cgroup_disable(char *str)
5824 struct cgroup_subsys *ss;
5828 while ((token = strsep(&str, ",")) != NULL) {
5832 for_each_subsys(ss, i) {
5833 if (strcmp(token, ss->name) &&
5834 strcmp(token, ss->legacy_name))
5837 static_branch_disable(cgroup_subsys_enabled_key[i]);
5838 pr_info("Disabling %s control group subsystem\n",
5844 __setup("cgroup_disable=", cgroup_disable);
5847 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5848 * @dentry: directory dentry of interest
5849 * @ss: subsystem of interest
5851 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5852 * to get the corresponding css and return it. If such css doesn't exist
5853 * or can't be pinned, an ERR_PTR value is returned.
5855 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5856 struct cgroup_subsys *ss)
5858 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5859 struct file_system_type *s_type = dentry->d_sb->s_type;
5860 struct cgroup_subsys_state *css = NULL;
5861 struct cgroup *cgrp;
5863 /* is @dentry a cgroup dir? */
5864 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
5865 !kn || kernfs_type(kn) != KERNFS_DIR)
5866 return ERR_PTR(-EBADF);
5871 * This path doesn't originate from kernfs and @kn could already
5872 * have been or be removed at any point. @kn->priv is RCU
5873 * protected for this access. See css_release_work_fn() for details.
5875 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
5877 css = cgroup_css(cgrp, ss);
5879 if (!css || !css_tryget_online(css))
5880 css = ERR_PTR(-ENOENT);
5887 * css_from_id - lookup css by id
5888 * @id: the cgroup id
5889 * @ss: cgroup subsys to be looked into
5891 * Returns the css if there's valid one with @id, otherwise returns NULL.
5892 * Should be called under rcu_read_lock().
5894 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5896 WARN_ON_ONCE(!rcu_read_lock_held());
5897 return idr_find(&ss->css_idr, id);
5901 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
5902 * @path: path on the default hierarchy
5904 * Find the cgroup at @path on the default hierarchy, increment its
5905 * reference count and return it. Returns pointer to the found cgroup on
5906 * success, ERR_PTR(-ENOENT) if @path doens't exist and ERR_PTR(-ENOTDIR)
5907 * if @path points to a non-directory.
5909 struct cgroup *cgroup_get_from_path(const char *path)
5911 struct kernfs_node *kn;
5912 struct cgroup *cgrp;
5914 mutex_lock(&cgroup_mutex);
5916 kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
5918 if (kernfs_type(kn) == KERNFS_DIR) {
5920 cgroup_get_live(cgrp);
5922 cgrp = ERR_PTR(-ENOTDIR);
5926 cgrp = ERR_PTR(-ENOENT);
5929 mutex_unlock(&cgroup_mutex);
5932 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
5935 * cgroup_get_from_fd - get a cgroup pointer from a fd
5936 * @fd: fd obtained by open(cgroup2_dir)
5938 * Find the cgroup from a fd which should be obtained
5939 * by opening a cgroup directory. Returns a pointer to the
5940 * cgroup on success. ERR_PTR is returned if the cgroup
5943 struct cgroup *cgroup_get_from_fd(int fd)
5945 struct cgroup_subsys_state *css;
5946 struct cgroup *cgrp;
5951 return ERR_PTR(-EBADF);
5953 css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
5956 return ERR_CAST(css);
5959 if (!cgroup_on_dfl(cgrp)) {
5961 return ERR_PTR(-EBADF);
5966 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
5969 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
5970 * definition in cgroup-defs.h.
5972 #ifdef CONFIG_SOCK_CGROUP_DATA
5974 #if defined(CONFIG_CGROUP_NET_PRIO) || defined(CONFIG_CGROUP_NET_CLASSID)
5976 DEFINE_SPINLOCK(cgroup_sk_update_lock);
5977 static bool cgroup_sk_alloc_disabled __read_mostly;
5979 void cgroup_sk_alloc_disable(void)
5981 if (cgroup_sk_alloc_disabled)
5983 pr_info("cgroup: disabling cgroup2 socket matching due to net_prio or net_cls activation\n");
5984 cgroup_sk_alloc_disabled = true;
5989 #define cgroup_sk_alloc_disabled false
5993 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
5995 if (cgroup_sk_alloc_disabled) {
5996 skcd->no_refcnt = 1;
6000 /* Don't associate the sock with unrelated interrupted task's cgroup. */
6007 struct css_set *cset;
6009 cset = task_css_set(current);
6010 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
6011 skcd->val = (unsigned long)cset->dfl_cgrp;
6020 void cgroup_sk_clone(struct sock_cgroup_data *skcd)
6022 /* Socket clone path */
6024 if (skcd->no_refcnt)
6027 * We might be cloning a socket which is left in an empty
6028 * cgroup and the cgroup might have already been rmdir'd.
6029 * Don't use cgroup_get_live().
6031 cgroup_get(sock_cgroup_ptr(skcd));
6035 void cgroup_sk_free(struct sock_cgroup_data *skcd)
6037 if (skcd->no_refcnt)
6040 cgroup_put(sock_cgroup_ptr(skcd));
6043 #endif /* CONFIG_SOCK_CGROUP_DATA */
6045 #ifdef CONFIG_CGROUP_BPF
6046 int cgroup_bpf_attach(struct cgroup *cgrp, struct bpf_prog *prog,
6047 enum bpf_attach_type type, u32 flags)
6051 mutex_lock(&cgroup_mutex);
6052 ret = __cgroup_bpf_attach(cgrp, prog, type, flags);
6053 mutex_unlock(&cgroup_mutex);
6056 int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
6057 enum bpf_attach_type type, u32 flags)
6061 mutex_lock(&cgroup_mutex);
6062 ret = __cgroup_bpf_detach(cgrp, prog, type, flags);
6063 mutex_unlock(&cgroup_mutex);
6066 int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
6067 union bpf_attr __user *uattr)
6071 mutex_lock(&cgroup_mutex);
6072 ret = __cgroup_bpf_query(cgrp, attr, uattr);
6073 mutex_unlock(&cgroup_mutex);
6076 #endif /* CONFIG_CGROUP_BPF */
6079 static ssize_t show_delegatable_files(struct cftype *files, char *buf,
6080 ssize_t size, const char *prefix)
6085 for (cft = files; cft && cft->name[0] != '\0'; cft++) {
6086 if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
6090 ret += snprintf(buf + ret, size - ret, "%s.", prefix);
6092 ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
6094 if (unlikely(ret >= size)) {
6103 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
6106 struct cgroup_subsys *ss;
6110 ret = show_delegatable_files(cgroup_base_files, buf, PAGE_SIZE - ret,
6113 for_each_subsys(ss, ssid)
6114 ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
6116 cgroup_subsys_name[ssid]);
6120 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
6122 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
6125 return snprintf(buf, PAGE_SIZE, "nsdelegate\n");
6127 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
6129 static struct attribute *cgroup_sysfs_attrs[] = {
6130 &cgroup_delegate_attr.attr,
6131 &cgroup_features_attr.attr,
6135 static const struct attribute_group cgroup_sysfs_attr_group = {
6136 .attrs = cgroup_sysfs_attrs,
6140 static int __init cgroup_sysfs_init(void)
6142 return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
6144 subsys_initcall(cgroup_sysfs_init);
6145 #endif /* CONFIG_SYSFS */