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>
59 #define CREATE_TRACE_POINTS
60 #include <trace/events/cgroup.h>
62 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
66 * cgroup_mutex is the master lock. Any modification to cgroup or its
67 * hierarchy must be performed while holding it.
69 * css_set_lock protects task->cgroups pointer, the list of css_set
70 * objects, and the chain of tasks off each css_set.
72 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
73 * cgroup.h can use them for lockdep annotations.
75 DEFINE_MUTEX(cgroup_mutex);
76 DEFINE_SPINLOCK(css_set_lock);
78 #ifdef CONFIG_PROVE_RCU
79 EXPORT_SYMBOL_GPL(cgroup_mutex);
80 EXPORT_SYMBOL_GPL(css_set_lock);
84 * Protects cgroup_idr and css_idr so that IDs can be released without
85 * grabbing cgroup_mutex.
87 static DEFINE_SPINLOCK(cgroup_idr_lock);
90 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
91 * against file removal/re-creation across css hiding.
93 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
95 struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
97 #define cgroup_assert_mutex_or_rcu_locked() \
98 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
99 !lockdep_is_held(&cgroup_mutex), \
100 "cgroup_mutex or RCU read lock required");
103 * cgroup destruction makes heavy use of work items and there can be a lot
104 * of concurrent destructions. Use a separate workqueue so that cgroup
105 * destruction work items don't end up filling up max_active of system_wq
106 * which may lead to deadlock.
108 static struct workqueue_struct *cgroup_destroy_wq;
110 /* generate an array of cgroup subsystem pointers */
111 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
112 struct cgroup_subsys *cgroup_subsys[] = {
113 #include <linux/cgroup_subsys.h>
117 /* array of cgroup subsystem names */
118 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
119 static const char *cgroup_subsys_name[] = {
120 #include <linux/cgroup_subsys.h>
124 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
126 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
127 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
128 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
129 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
130 #include <linux/cgroup_subsys.h>
133 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
134 static struct static_key_true *cgroup_subsys_enabled_key[] = {
135 #include <linux/cgroup_subsys.h>
139 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
140 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
141 #include <linux/cgroup_subsys.h>
146 * The default hierarchy, reserved for the subsystems that are otherwise
147 * unattached - it never has more than a single cgroup, and all tasks are
148 * part of that cgroup.
150 struct cgroup_root cgrp_dfl_root;
151 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
154 * The default hierarchy always exists but is hidden until mounted for the
155 * first time. This is for backward compatibility.
157 static bool cgrp_dfl_visible;
159 /* some controllers are not supported in the default hierarchy */
160 static u16 cgrp_dfl_inhibit_ss_mask;
162 /* some controllers are implicitly enabled on the default hierarchy */
163 static u16 cgrp_dfl_implicit_ss_mask;
165 /* some controllers can be threaded on the default hierarchy */
166 static u16 cgrp_dfl_threaded_ss_mask;
168 /* The list of hierarchy roots */
169 LIST_HEAD(cgroup_roots);
170 static int cgroup_root_count;
172 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
173 static DEFINE_IDR(cgroup_hierarchy_idr);
176 * Assign a monotonically increasing serial number to csses. It guarantees
177 * cgroups with bigger numbers are newer than those with smaller numbers.
178 * Also, as csses are always appended to the parent's ->children list, it
179 * guarantees that sibling csses are always sorted in the ascending serial
180 * number order on the list. Protected by cgroup_mutex.
182 static u64 css_serial_nr_next = 1;
185 * These bitmasks identify subsystems with specific features to avoid
186 * having to do iterative checks repeatedly.
188 static u16 have_fork_callback __read_mostly;
189 static u16 have_exit_callback __read_mostly;
190 static u16 have_release_callback __read_mostly;
191 static u16 have_canfork_callback __read_mostly;
193 /* cgroup namespace for init task */
194 struct cgroup_namespace init_cgroup_ns = {
195 .count = REFCOUNT_INIT(2),
196 .user_ns = &init_user_ns,
197 .ns.ops = &cgroupns_operations,
198 .ns.inum = PROC_CGROUP_INIT_INO,
199 .root_cset = &init_css_set,
202 static struct file_system_type cgroup2_fs_type;
203 static struct cftype cgroup_base_files[];
205 static int cgroup_apply_control(struct cgroup *cgrp);
206 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
207 static void css_task_iter_skip(struct css_task_iter *it,
208 struct task_struct *task);
209 static int cgroup_destroy_locked(struct cgroup *cgrp);
210 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
211 struct cgroup_subsys *ss);
212 static void css_release(struct percpu_ref *ref);
213 static void kill_css(struct cgroup_subsys_state *css);
214 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
215 struct cgroup *cgrp, struct cftype cfts[],
219 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
220 * @ssid: subsys ID of interest
222 * cgroup_subsys_enabled() can only be used with literal subsys names which
223 * is fine for individual subsystems but unsuitable for cgroup core. This
224 * is slower static_key_enabled() based test indexed by @ssid.
226 bool cgroup_ssid_enabled(int ssid)
228 if (CGROUP_SUBSYS_COUNT == 0)
231 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
235 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
236 * @cgrp: the cgroup of interest
238 * The default hierarchy is the v2 interface of cgroup and this function
239 * can be used to test whether a cgroup is on the default hierarchy for
240 * cases where a subsystem should behave differnetly depending on the
243 * The set of behaviors which change on the default hierarchy are still
244 * being determined and the mount option is prefixed with __DEVEL__.
246 * List of changed behaviors:
248 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
249 * and "name" are disallowed.
251 * - When mounting an existing superblock, mount options should match.
253 * - Remount is disallowed.
255 * - rename(2) is disallowed.
257 * - "tasks" is removed. Everything should be at process granularity. Use
258 * "cgroup.procs" instead.
260 * - "cgroup.procs" is not sorted. pids will be unique unless they got
261 * recycled inbetween reads.
263 * - "release_agent" and "notify_on_release" are removed. Replacement
264 * notification mechanism will be implemented.
266 * - "cgroup.clone_children" is removed.
268 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
269 * and its descendants contain no task; otherwise, 1. The file also
270 * generates kernfs notification which can be monitored through poll and
271 * [di]notify when the value of the file changes.
273 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
274 * take masks of ancestors with non-empty cpus/mems, instead of being
275 * moved to an ancestor.
277 * - cpuset: a task can be moved into an empty cpuset, and again it takes
278 * masks of ancestors.
280 * - memcg: use_hierarchy is on by default and the cgroup file for the flag
283 * - blkcg: blk-throttle becomes properly hierarchical.
285 * - debug: disallowed on the default hierarchy.
287 bool cgroup_on_dfl(const struct cgroup *cgrp)
289 return cgrp->root == &cgrp_dfl_root;
292 /* IDR wrappers which synchronize using cgroup_idr_lock */
293 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
298 idr_preload(gfp_mask);
299 spin_lock_bh(&cgroup_idr_lock);
300 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
301 spin_unlock_bh(&cgroup_idr_lock);
306 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
310 spin_lock_bh(&cgroup_idr_lock);
311 ret = idr_replace(idr, ptr, id);
312 spin_unlock_bh(&cgroup_idr_lock);
316 static void cgroup_idr_remove(struct idr *idr, int id)
318 spin_lock_bh(&cgroup_idr_lock);
320 spin_unlock_bh(&cgroup_idr_lock);
323 static bool cgroup_has_tasks(struct cgroup *cgrp)
325 return cgrp->nr_populated_csets;
328 bool cgroup_is_threaded(struct cgroup *cgrp)
330 return cgrp->dom_cgrp != cgrp;
333 /* can @cgrp host both domain and threaded children? */
334 static bool cgroup_is_mixable(struct cgroup *cgrp)
337 * Root isn't under domain level resource control exempting it from
338 * the no-internal-process constraint, so it can serve as a thread
339 * root and a parent of resource domains at the same time.
341 return !cgroup_parent(cgrp);
344 /* can @cgrp become a thread root? should always be true for a thread root */
345 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
347 /* mixables don't care */
348 if (cgroup_is_mixable(cgrp))
351 /* domain roots can't be nested under threaded */
352 if (cgroup_is_threaded(cgrp))
355 /* can only have either domain or threaded children */
356 if (cgrp->nr_populated_domain_children)
359 /* and no domain controllers can be enabled */
360 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
366 /* is @cgrp root of a threaded subtree? */
367 bool cgroup_is_thread_root(struct cgroup *cgrp)
369 /* thread root should be a domain */
370 if (cgroup_is_threaded(cgrp))
373 /* a domain w/ threaded children is a thread root */
374 if (cgrp->nr_threaded_children)
378 * A domain which has tasks and explicit threaded controllers
379 * enabled is a thread root.
381 if (cgroup_has_tasks(cgrp) &&
382 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
388 /* a domain which isn't connected to the root w/o brekage can't be used */
389 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
391 /* the cgroup itself can be a thread root */
392 if (cgroup_is_threaded(cgrp))
395 /* but the ancestors can't be unless mixable */
396 while ((cgrp = cgroup_parent(cgrp))) {
397 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
399 if (cgroup_is_threaded(cgrp))
406 /* subsystems visibly enabled on a cgroup */
407 static u16 cgroup_control(struct cgroup *cgrp)
409 struct cgroup *parent = cgroup_parent(cgrp);
410 u16 root_ss_mask = cgrp->root->subsys_mask;
413 u16 ss_mask = parent->subtree_control;
415 /* threaded cgroups can only have threaded controllers */
416 if (cgroup_is_threaded(cgrp))
417 ss_mask &= cgrp_dfl_threaded_ss_mask;
421 if (cgroup_on_dfl(cgrp))
422 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
423 cgrp_dfl_implicit_ss_mask);
427 /* subsystems enabled on a cgroup */
428 static u16 cgroup_ss_mask(struct cgroup *cgrp)
430 struct cgroup *parent = cgroup_parent(cgrp);
433 u16 ss_mask = parent->subtree_ss_mask;
435 /* threaded cgroups can only have threaded controllers */
436 if (cgroup_is_threaded(cgrp))
437 ss_mask &= cgrp_dfl_threaded_ss_mask;
441 return cgrp->root->subsys_mask;
445 * cgroup_css - obtain a cgroup's css for the specified subsystem
446 * @cgrp: the cgroup of interest
447 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
449 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
450 * function must be called either under cgroup_mutex or rcu_read_lock() and
451 * the caller is responsible for pinning the returned css if it wants to
452 * keep accessing it outside the said locks. This function may return
453 * %NULL if @cgrp doesn't have @subsys_id enabled.
455 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
456 struct cgroup_subsys *ss)
459 return rcu_dereference_check(cgrp->subsys[ss->id],
460 lockdep_is_held(&cgroup_mutex));
466 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
467 * @cgrp: the cgroup of interest
468 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
470 * Similar to cgroup_css() but returns the effective css, which is defined
471 * as the matching css of the nearest ancestor including self which has @ss
472 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
473 * function is guaranteed to return non-NULL css.
475 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
476 struct cgroup_subsys *ss)
478 lockdep_assert_held(&cgroup_mutex);
484 * This function is used while updating css associations and thus
485 * can't test the csses directly. Test ss_mask.
487 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
488 cgrp = cgroup_parent(cgrp);
493 return cgroup_css(cgrp, ss);
497 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
498 * @cgrp: the cgroup of interest
499 * @ss: the subsystem of interest
501 * Find and get the effective css of @cgrp for @ss. The effective css is
502 * defined as the matching css of the nearest ancestor including self which
503 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
504 * the root css is returned, so this function always returns a valid css.
505 * The returned css must be put using css_put().
507 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
508 struct cgroup_subsys *ss)
510 struct cgroup_subsys_state *css;
515 css = cgroup_css(cgrp, ss);
517 if (css && css_tryget_online(css))
519 cgrp = cgroup_parent(cgrp);
522 css = init_css_set.subsys[ss->id];
529 static void cgroup_get_live(struct cgroup *cgrp)
531 WARN_ON_ONCE(cgroup_is_dead(cgrp));
532 css_get(&cgrp->self);
535 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
537 struct cgroup *cgrp = of->kn->parent->priv;
538 struct cftype *cft = of_cft(of);
541 * This is open and unprotected implementation of cgroup_css().
542 * seq_css() is only called from a kernfs file operation which has
543 * an active reference on the file. Because all the subsystem
544 * files are drained before a css is disassociated with a cgroup,
545 * the matching css from the cgroup's subsys table is guaranteed to
546 * be and stay valid until the enclosing operation is complete.
549 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
553 EXPORT_SYMBOL_GPL(of_css);
556 * for_each_css - iterate all css's of a cgroup
557 * @css: the iteration cursor
558 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
559 * @cgrp: the target cgroup to iterate css's of
561 * Should be called under cgroup_[tree_]mutex.
563 #define for_each_css(css, ssid, cgrp) \
564 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
565 if (!((css) = rcu_dereference_check( \
566 (cgrp)->subsys[(ssid)], \
567 lockdep_is_held(&cgroup_mutex)))) { } \
571 * for_each_e_css - iterate all effective css's of a cgroup
572 * @css: the iteration cursor
573 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
574 * @cgrp: the target cgroup to iterate css's of
576 * Should be called under cgroup_[tree_]mutex.
578 #define for_each_e_css(css, ssid, cgrp) \
579 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
580 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
585 * do_each_subsys_mask - filter for_each_subsys with a bitmask
586 * @ss: the iteration cursor
587 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
588 * @ss_mask: the bitmask
590 * The block will only run for cases where the ssid-th bit (1 << ssid) of
593 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
594 unsigned long __ss_mask = (ss_mask); \
595 if (!CGROUP_SUBSYS_COUNT) { /* to avoid spurious gcc warning */ \
599 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
600 (ss) = cgroup_subsys[ssid]; \
603 #define while_each_subsys_mask() \
608 /* iterate over child cgrps, lock should be held throughout iteration */
609 #define cgroup_for_each_live_child(child, cgrp) \
610 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
611 if (({ lockdep_assert_held(&cgroup_mutex); \
612 cgroup_is_dead(child); })) \
616 /* walk live descendants in preorder */
617 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
618 css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
619 if (({ lockdep_assert_held(&cgroup_mutex); \
620 (dsct) = (d_css)->cgroup; \
621 cgroup_is_dead(dsct); })) \
625 /* walk live descendants in postorder */
626 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
627 css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
628 if (({ lockdep_assert_held(&cgroup_mutex); \
629 (dsct) = (d_css)->cgroup; \
630 cgroup_is_dead(dsct); })) \
635 * The default css_set - used by init and its children prior to any
636 * hierarchies being mounted. It contains a pointer to the root state
637 * for each subsystem. Also used to anchor the list of css_sets. Not
638 * reference-counted, to improve performance when child cgroups
639 * haven't been created.
641 struct css_set init_css_set = {
642 .refcount = REFCOUNT_INIT(1),
643 .dom_cset = &init_css_set,
644 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
645 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
646 .dying_tasks = LIST_HEAD_INIT(init_css_set.dying_tasks),
647 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
648 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
649 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
650 .mg_src_preload_node = LIST_HEAD_INIT(init_css_set.mg_src_preload_node),
651 .mg_dst_preload_node = LIST_HEAD_INIT(init_css_set.mg_dst_preload_node),
652 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
655 static int css_set_count = 1; /* 1 for init_css_set */
657 static bool css_set_threaded(struct css_set *cset)
659 return cset->dom_cset != cset;
663 * css_set_populated - does a css_set contain any tasks?
664 * @cset: target css_set
666 * css_set_populated() should be the same as !!cset->nr_tasks at steady
667 * state. However, css_set_populated() can be called while a task is being
668 * added to or removed from the linked list before the nr_tasks is
669 * properly updated. Hence, we can't just look at ->nr_tasks here.
671 static bool css_set_populated(struct css_set *cset)
673 lockdep_assert_held(&css_set_lock);
675 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
679 * cgroup_update_populated - update the populated count of a cgroup
680 * @cgrp: the target cgroup
681 * @populated: inc or dec populated count
683 * One of the css_sets associated with @cgrp is either getting its first
684 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
685 * count is propagated towards root so that a given cgroup's
686 * nr_populated_children is zero iff none of its descendants contain any
689 * @cgrp's interface file "cgroup.populated" is zero if both
690 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
691 * 1 otherwise. When the sum changes from or to zero, userland is notified
692 * that the content of the interface file has changed. This can be used to
693 * detect when @cgrp and its descendants become populated or empty.
695 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
697 struct cgroup *child = NULL;
698 int adj = populated ? 1 : -1;
700 lockdep_assert_held(&css_set_lock);
703 bool was_populated = cgroup_is_populated(cgrp);
706 cgrp->nr_populated_csets += adj;
708 if (cgroup_is_threaded(child))
709 cgrp->nr_populated_threaded_children += adj;
711 cgrp->nr_populated_domain_children += adj;
714 if (was_populated == cgroup_is_populated(cgrp))
717 cgroup1_check_for_release(cgrp);
718 cgroup_file_notify(&cgrp->events_file);
721 cgrp = cgroup_parent(cgrp);
726 * css_set_update_populated - update populated state of a css_set
727 * @cset: target css_set
728 * @populated: whether @cset is populated or depopulated
730 * @cset is either getting the first task or losing the last. Update the
731 * populated counters of all associated cgroups accordingly.
733 static void css_set_update_populated(struct css_set *cset, bool populated)
735 struct cgrp_cset_link *link;
737 lockdep_assert_held(&css_set_lock);
739 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
740 cgroup_update_populated(link->cgrp, populated);
744 * @task is leaving, advance task iterators which are pointing to it so
745 * that they can resume at the next position. Advancing an iterator might
746 * remove it from the list, use safe walk. See css_task_iter_skip() for
749 static void css_set_skip_task_iters(struct css_set *cset,
750 struct task_struct *task)
752 struct css_task_iter *it, *pos;
754 list_for_each_entry_safe(it, pos, &cset->task_iters, iters_node)
755 css_task_iter_skip(it, task);
759 * css_set_move_task - move a task from one css_set to another
760 * @task: task being moved
761 * @from_cset: css_set @task currently belongs to (may be NULL)
762 * @to_cset: new css_set @task is being moved to (may be NULL)
763 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
765 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
766 * css_set, @from_cset can be NULL. If @task is being disassociated
767 * instead of moved, @to_cset can be NULL.
769 * This function automatically handles populated counter updates and
770 * css_task_iter adjustments but the caller is responsible for managing
771 * @from_cset and @to_cset's reference counts.
773 static void css_set_move_task(struct task_struct *task,
774 struct css_set *from_cset, struct css_set *to_cset,
777 lockdep_assert_held(&css_set_lock);
779 if (to_cset && !css_set_populated(to_cset))
780 css_set_update_populated(to_cset, true);
783 WARN_ON_ONCE(list_empty(&task->cg_list));
785 css_set_skip_task_iters(from_cset, task);
786 list_del_init(&task->cg_list);
787 if (!css_set_populated(from_cset))
788 css_set_update_populated(from_cset, false);
790 WARN_ON_ONCE(!list_empty(&task->cg_list));
795 * We are synchronized through cgroup_threadgroup_rwsem
796 * against PF_EXITING setting such that we can't race
797 * against cgroup_exit() changing the css_set to
798 * init_css_set and dropping the old one.
800 WARN_ON_ONCE(task->flags & PF_EXITING);
802 rcu_assign_pointer(task->cgroups, to_cset);
803 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
809 * hash table for cgroup groups. This improves the performance to find
810 * an existing css_set. This hash doesn't (currently) take into
811 * account cgroups in empty hierarchies.
813 #define CSS_SET_HASH_BITS 7
814 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
816 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
818 unsigned long key = 0UL;
819 struct cgroup_subsys *ss;
822 for_each_subsys(ss, i)
823 key += (unsigned long)css[i];
824 key = (key >> 16) ^ key;
829 void put_css_set_locked(struct css_set *cset)
831 struct cgrp_cset_link *link, *tmp_link;
832 struct cgroup_subsys *ss;
835 lockdep_assert_held(&css_set_lock);
837 if (!refcount_dec_and_test(&cset->refcount))
840 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
842 /* This css_set is dead. unlink it and release cgroup and css refs */
843 for_each_subsys(ss, ssid) {
844 list_del(&cset->e_cset_node[ssid]);
845 css_put(cset->subsys[ssid]);
847 hash_del(&cset->hlist);
850 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
851 list_del(&link->cset_link);
852 list_del(&link->cgrp_link);
853 if (cgroup_parent(link->cgrp))
854 cgroup_put(link->cgrp);
858 if (css_set_threaded(cset)) {
859 list_del(&cset->threaded_csets_node);
860 put_css_set_locked(cset->dom_cset);
863 kfree_rcu(cset, rcu_head);
867 * compare_css_sets - helper function for find_existing_css_set().
868 * @cset: candidate css_set being tested
869 * @old_cset: existing css_set for a task
870 * @new_cgrp: cgroup that's being entered by the task
871 * @template: desired set of css pointers in css_set (pre-calculated)
873 * Returns true if "cset" matches "old_cset" except for the hierarchy
874 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
876 static bool compare_css_sets(struct css_set *cset,
877 struct css_set *old_cset,
878 struct cgroup *new_cgrp,
879 struct cgroup_subsys_state *template[])
881 struct cgroup *new_dfl_cgrp;
882 struct list_head *l1, *l2;
885 * On the default hierarchy, there can be csets which are
886 * associated with the same set of cgroups but different csses.
887 * Let's first ensure that csses match.
889 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
893 /* @cset's domain should match the default cgroup's */
894 if (cgroup_on_dfl(new_cgrp))
895 new_dfl_cgrp = new_cgrp;
897 new_dfl_cgrp = old_cset->dfl_cgrp;
899 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
903 * Compare cgroup pointers in order to distinguish between
904 * different cgroups in hierarchies. As different cgroups may
905 * share the same effective css, this comparison is always
908 l1 = &cset->cgrp_links;
909 l2 = &old_cset->cgrp_links;
911 struct cgrp_cset_link *link1, *link2;
912 struct cgroup *cgrp1, *cgrp2;
916 /* See if we reached the end - both lists are equal length. */
917 if (l1 == &cset->cgrp_links) {
918 BUG_ON(l2 != &old_cset->cgrp_links);
921 BUG_ON(l2 == &old_cset->cgrp_links);
923 /* Locate the cgroups associated with these links. */
924 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
925 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
928 /* Hierarchies should be linked in the same order. */
929 BUG_ON(cgrp1->root != cgrp2->root);
932 * If this hierarchy is the hierarchy of the cgroup
933 * that's changing, then we need to check that this
934 * css_set points to the new cgroup; if it's any other
935 * hierarchy, then this css_set should point to the
936 * same cgroup as the old css_set.
938 if (cgrp1->root == new_cgrp->root) {
939 if (cgrp1 != new_cgrp)
950 * find_existing_css_set - init css array and find the matching css_set
951 * @old_cset: the css_set that we're using before the cgroup transition
952 * @cgrp: the cgroup that we're moving into
953 * @template: out param for the new set of csses, should be clear on entry
955 static struct css_set *find_existing_css_set(struct css_set *old_cset,
957 struct cgroup_subsys_state *template[])
959 struct cgroup_root *root = cgrp->root;
960 struct cgroup_subsys *ss;
961 struct css_set *cset;
966 * Build the set of subsystem state objects that we want to see in the
967 * new css_set. while subsystems can change globally, the entries here
968 * won't change, so no need for locking.
970 for_each_subsys(ss, i) {
971 if (root->subsys_mask & (1UL << i)) {
973 * @ss is in this hierarchy, so we want the
974 * effective css from @cgrp.
976 template[i] = cgroup_e_css(cgrp, ss);
979 * @ss is not in this hierarchy, so we don't want
982 template[i] = old_cset->subsys[i];
986 key = css_set_hash(template);
987 hash_for_each_possible(css_set_table, cset, hlist, key) {
988 if (!compare_css_sets(cset, old_cset, cgrp, template))
991 /* This css_set matches what we need */
995 /* No existing cgroup group matched */
999 static void free_cgrp_cset_links(struct list_head *links_to_free)
1001 struct cgrp_cset_link *link, *tmp_link;
1003 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1004 list_del(&link->cset_link);
1010 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1011 * @count: the number of links to allocate
1012 * @tmp_links: list_head the allocated links are put on
1014 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1015 * through ->cset_link. Returns 0 on success or -errno.
1017 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1019 struct cgrp_cset_link *link;
1022 INIT_LIST_HEAD(tmp_links);
1024 for (i = 0; i < count; i++) {
1025 link = kzalloc(sizeof(*link), GFP_KERNEL);
1027 free_cgrp_cset_links(tmp_links);
1030 list_add(&link->cset_link, tmp_links);
1036 * link_css_set - a helper function to link a css_set to a cgroup
1037 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1038 * @cset: the css_set to be linked
1039 * @cgrp: the destination cgroup
1041 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1042 struct cgroup *cgrp)
1044 struct cgrp_cset_link *link;
1046 BUG_ON(list_empty(tmp_links));
1048 if (cgroup_on_dfl(cgrp))
1049 cset->dfl_cgrp = cgrp;
1051 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1056 * Always add links to the tail of the lists so that the lists are
1057 * in choronological order.
1059 list_move_tail(&link->cset_link, &cgrp->cset_links);
1060 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1062 if (cgroup_parent(cgrp))
1063 cgroup_get_live(cgrp);
1067 * find_css_set - return a new css_set with one cgroup updated
1068 * @old_cset: the baseline css_set
1069 * @cgrp: the cgroup to be updated
1071 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1072 * substituted into the appropriate hierarchy.
1074 static struct css_set *find_css_set(struct css_set *old_cset,
1075 struct cgroup *cgrp)
1077 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1078 struct css_set *cset;
1079 struct list_head tmp_links;
1080 struct cgrp_cset_link *link;
1081 struct cgroup_subsys *ss;
1085 lockdep_assert_held(&cgroup_mutex);
1087 /* First see if we already have a cgroup group that matches
1088 * the desired set */
1089 spin_lock_irq(&css_set_lock);
1090 cset = find_existing_css_set(old_cset, cgrp, template);
1093 spin_unlock_irq(&css_set_lock);
1098 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1102 /* Allocate all the cgrp_cset_link objects that we'll need */
1103 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1108 refcount_set(&cset->refcount, 1);
1109 cset->dom_cset = cset;
1110 INIT_LIST_HEAD(&cset->tasks);
1111 INIT_LIST_HEAD(&cset->mg_tasks);
1112 INIT_LIST_HEAD(&cset->dying_tasks);
1113 INIT_LIST_HEAD(&cset->task_iters);
1114 INIT_LIST_HEAD(&cset->threaded_csets);
1115 INIT_HLIST_NODE(&cset->hlist);
1116 INIT_LIST_HEAD(&cset->cgrp_links);
1117 INIT_LIST_HEAD(&cset->mg_src_preload_node);
1118 INIT_LIST_HEAD(&cset->mg_dst_preload_node);
1119 INIT_LIST_HEAD(&cset->mg_node);
1121 /* Copy the set of subsystem state objects generated in
1122 * find_existing_css_set() */
1123 memcpy(cset->subsys, template, sizeof(cset->subsys));
1125 spin_lock_irq(&css_set_lock);
1126 /* Add reference counts and links from the new css_set. */
1127 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1128 struct cgroup *c = link->cgrp;
1130 if (c->root == cgrp->root)
1132 link_css_set(&tmp_links, cset, c);
1135 BUG_ON(!list_empty(&tmp_links));
1139 /* Add @cset to the hash table */
1140 key = css_set_hash(cset->subsys);
1141 hash_add(css_set_table, &cset->hlist, key);
1143 for_each_subsys(ss, ssid) {
1144 struct cgroup_subsys_state *css = cset->subsys[ssid];
1146 list_add_tail(&cset->e_cset_node[ssid],
1147 &css->cgroup->e_csets[ssid]);
1151 spin_unlock_irq(&css_set_lock);
1154 * If @cset should be threaded, look up the matching dom_cset and
1155 * link them up. We first fully initialize @cset then look for the
1156 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1157 * to stay empty until we return.
1159 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1160 struct css_set *dcset;
1162 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1168 spin_lock_irq(&css_set_lock);
1169 cset->dom_cset = dcset;
1170 list_add_tail(&cset->threaded_csets_node,
1171 &dcset->threaded_csets);
1172 spin_unlock_irq(&css_set_lock);
1178 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1180 struct cgroup *root_cgrp = kf_root->kn->priv;
1182 return root_cgrp->root;
1185 static int cgroup_init_root_id(struct cgroup_root *root)
1189 lockdep_assert_held(&cgroup_mutex);
1191 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1195 root->hierarchy_id = id;
1199 static void cgroup_exit_root_id(struct cgroup_root *root)
1201 lockdep_assert_held(&cgroup_mutex);
1203 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1206 void cgroup_free_root(struct cgroup_root *root)
1209 idr_destroy(&root->cgroup_idr);
1214 static void cgroup_destroy_root(struct cgroup_root *root)
1216 struct cgroup *cgrp = &root->cgrp;
1217 struct cgrp_cset_link *link, *tmp_link;
1219 trace_cgroup_destroy_root(root);
1221 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1223 BUG_ON(atomic_read(&root->nr_cgrps));
1224 BUG_ON(!list_empty(&cgrp->self.children));
1226 /* Rebind all subsystems back to the default hierarchy */
1227 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1230 * Release all the links from cset_links to this hierarchy's
1233 spin_lock_irq(&css_set_lock);
1235 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1236 list_del(&link->cset_link);
1237 list_del(&link->cgrp_link);
1241 spin_unlock_irq(&css_set_lock);
1243 if (!list_empty(&root->root_list)) {
1244 list_del(&root->root_list);
1245 cgroup_root_count--;
1248 cgroup_exit_root_id(root);
1250 mutex_unlock(&cgroup_mutex);
1252 kernfs_destroy_root(root->kf_root);
1253 cgroup_free_root(root);
1257 * look up cgroup associated with current task's cgroup namespace on the
1258 * specified hierarchy
1260 static struct cgroup *
1261 current_cgns_cgroup_from_root(struct cgroup_root *root)
1263 struct cgroup *res = NULL;
1264 struct css_set *cset;
1266 lockdep_assert_held(&css_set_lock);
1270 cset = current->nsproxy->cgroup_ns->root_cset;
1271 if (cset == &init_css_set) {
1274 struct cgrp_cset_link *link;
1276 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1277 struct cgroup *c = link->cgrp;
1279 if (c->root == root) {
1291 /* look up cgroup associated with given css_set on the specified hierarchy */
1292 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1293 struct cgroup_root *root)
1295 struct cgroup *res = NULL;
1297 lockdep_assert_held(&cgroup_mutex);
1298 lockdep_assert_held(&css_set_lock);
1300 if (cset == &init_css_set) {
1302 } else if (root == &cgrp_dfl_root) {
1303 res = cset->dfl_cgrp;
1305 struct cgrp_cset_link *link;
1307 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1308 struct cgroup *c = link->cgrp;
1310 if (c->root == root) {
1322 * Return the cgroup for "task" from the given hierarchy. Must be
1323 * called with cgroup_mutex and css_set_lock held.
1325 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1326 struct cgroup_root *root)
1329 * No need to lock the task - since we hold cgroup_mutex the
1330 * task can't change groups, so the only thing that can happen
1331 * is that it exits and its css is set back to init_css_set.
1333 return cset_cgroup_from_root(task_css_set(task), root);
1337 * A task must hold cgroup_mutex to modify cgroups.
1339 * Any task can increment and decrement the count field without lock.
1340 * So in general, code holding cgroup_mutex can't rely on the count
1341 * field not changing. However, if the count goes to zero, then only
1342 * cgroup_attach_task() can increment it again. Because a count of zero
1343 * means that no tasks are currently attached, therefore there is no
1344 * way a task attached to that cgroup can fork (the other way to
1345 * increment the count). So code holding cgroup_mutex can safely
1346 * assume that if the count is zero, it will stay zero. Similarly, if
1347 * a task holds cgroup_mutex on a cgroup with zero count, it
1348 * knows that the cgroup won't be removed, as cgroup_rmdir()
1351 * A cgroup can only be deleted if both its 'count' of using tasks
1352 * is zero, and its list of 'children' cgroups is empty. Since all
1353 * tasks in the system use _some_ cgroup, and since there is always at
1354 * least one task in the system (init, pid == 1), therefore, root cgroup
1355 * always has either children cgroups and/or using tasks. So we don't
1356 * need a special hack to ensure that root cgroup cannot be deleted.
1358 * P.S. One more locking exception. RCU is used to guard the
1359 * update of a tasks cgroup pointer by cgroup_attach_task()
1362 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1364 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1367 struct cgroup_subsys *ss = cft->ss;
1369 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1370 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1371 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1372 cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1375 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1380 * cgroup_file_mode - deduce file mode of a control file
1381 * @cft: the control file in question
1383 * S_IRUGO for read, S_IWUSR for write.
1385 static umode_t cgroup_file_mode(const struct cftype *cft)
1389 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1392 if (cft->write_u64 || cft->write_s64 || cft->write) {
1393 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1403 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1404 * @subtree_control: the new subtree_control mask to consider
1405 * @this_ss_mask: available subsystems
1407 * On the default hierarchy, a subsystem may request other subsystems to be
1408 * enabled together through its ->depends_on mask. In such cases, more
1409 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1411 * This function calculates which subsystems need to be enabled if
1412 * @subtree_control is to be applied while restricted to @this_ss_mask.
1414 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1416 u16 cur_ss_mask = subtree_control;
1417 struct cgroup_subsys *ss;
1420 lockdep_assert_held(&cgroup_mutex);
1422 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1425 u16 new_ss_mask = cur_ss_mask;
1427 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1428 new_ss_mask |= ss->depends_on;
1429 } while_each_subsys_mask();
1432 * Mask out subsystems which aren't available. This can
1433 * happen only if some depended-upon subsystems were bound
1434 * to non-default hierarchies.
1436 new_ss_mask &= this_ss_mask;
1438 if (new_ss_mask == cur_ss_mask)
1440 cur_ss_mask = new_ss_mask;
1447 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1448 * @kn: the kernfs_node being serviced
1450 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1451 * the method finishes if locking succeeded. Note that once this function
1452 * returns the cgroup returned by cgroup_kn_lock_live() may become
1453 * inaccessible any time. If the caller intends to continue to access the
1454 * cgroup, it should pin it before invoking this function.
1456 void cgroup_kn_unlock(struct kernfs_node *kn)
1458 struct cgroup *cgrp;
1460 if (kernfs_type(kn) == KERNFS_DIR)
1463 cgrp = kn->parent->priv;
1465 mutex_unlock(&cgroup_mutex);
1467 kernfs_unbreak_active_protection(kn);
1472 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1473 * @kn: the kernfs_node being serviced
1474 * @drain_offline: perform offline draining on the cgroup
1476 * This helper is to be used by a cgroup kernfs method currently servicing
1477 * @kn. It breaks the active protection, performs cgroup locking and
1478 * verifies that the associated cgroup is alive. Returns the cgroup if
1479 * alive; otherwise, %NULL. A successful return should be undone by a
1480 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1481 * cgroup is drained of offlining csses before return.
1483 * Any cgroup kernfs method implementation which requires locking the
1484 * associated cgroup should use this helper. It avoids nesting cgroup
1485 * locking under kernfs active protection and allows all kernfs operations
1486 * including self-removal.
1488 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1490 struct cgroup *cgrp;
1492 if (kernfs_type(kn) == KERNFS_DIR)
1495 cgrp = kn->parent->priv;
1498 * We're gonna grab cgroup_mutex which nests outside kernfs
1499 * active_ref. cgroup liveliness check alone provides enough
1500 * protection against removal. Ensure @cgrp stays accessible and
1501 * break the active_ref protection.
1503 if (!cgroup_tryget(cgrp))
1505 kernfs_break_active_protection(kn);
1508 cgroup_lock_and_drain_offline(cgrp);
1510 mutex_lock(&cgroup_mutex);
1512 if (!cgroup_is_dead(cgrp))
1515 cgroup_kn_unlock(kn);
1519 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1521 char name[CGROUP_FILE_NAME_MAX];
1523 lockdep_assert_held(&cgroup_mutex);
1525 if (cft->file_offset) {
1526 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1527 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1529 spin_lock_irq(&cgroup_file_kn_lock);
1531 spin_unlock_irq(&cgroup_file_kn_lock);
1534 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1538 * css_clear_dir - remove subsys files in a cgroup directory
1541 static void css_clear_dir(struct cgroup_subsys_state *css)
1543 struct cgroup *cgrp = css->cgroup;
1544 struct cftype *cfts;
1546 if (!(css->flags & CSS_VISIBLE))
1549 css->flags &= ~CSS_VISIBLE;
1551 list_for_each_entry(cfts, &css->ss->cfts, node)
1552 cgroup_addrm_files(css, cgrp, cfts, false);
1556 * css_populate_dir - create subsys files in a cgroup directory
1559 * On failure, no file is added.
1561 static int css_populate_dir(struct cgroup_subsys_state *css)
1563 struct cgroup *cgrp = css->cgroup;
1564 struct cftype *cfts, *failed_cfts;
1567 if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
1571 if (cgroup_on_dfl(cgrp))
1572 cfts = cgroup_base_files;
1574 cfts = cgroup1_base_files;
1576 return cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1579 list_for_each_entry(cfts, &css->ss->cfts, node) {
1580 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1587 css->flags |= CSS_VISIBLE;
1591 list_for_each_entry(cfts, &css->ss->cfts, node) {
1592 if (cfts == failed_cfts)
1594 cgroup_addrm_files(css, cgrp, cfts, false);
1599 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1601 struct cgroup *dcgrp = &dst_root->cgrp;
1602 struct cgroup_subsys *ss;
1604 u16 dfl_disable_ss_mask = 0;
1606 lockdep_assert_held(&cgroup_mutex);
1608 do_each_subsys_mask(ss, ssid, ss_mask) {
1610 * If @ss has non-root csses attached to it, can't move.
1611 * If @ss is an implicit controller, it is exempt from this
1612 * rule and can be stolen.
1614 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1615 !ss->implicit_on_dfl)
1618 /* can't move between two non-dummy roots either */
1619 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1623 * Collect ssid's that need to be disabled from default
1626 if (ss->root == &cgrp_dfl_root)
1627 dfl_disable_ss_mask |= 1 << ssid;
1629 } while_each_subsys_mask();
1631 if (dfl_disable_ss_mask) {
1632 struct cgroup *scgrp = &cgrp_dfl_root.cgrp;
1635 * Controllers from default hierarchy that need to be rebound
1636 * are all disabled together in one go.
1638 cgrp_dfl_root.subsys_mask &= ~dfl_disable_ss_mask;
1639 WARN_ON(cgroup_apply_control(scgrp));
1640 cgroup_finalize_control(scgrp, 0);
1643 do_each_subsys_mask(ss, ssid, ss_mask) {
1644 struct cgroup_root *src_root = ss->root;
1645 struct cgroup *scgrp = &src_root->cgrp;
1646 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1647 struct css_set *cset;
1649 WARN_ON(!css || cgroup_css(dcgrp, ss));
1651 if (src_root != &cgrp_dfl_root) {
1652 /* disable from the source */
1653 src_root->subsys_mask &= ~(1 << ssid);
1654 WARN_ON(cgroup_apply_control(scgrp));
1655 cgroup_finalize_control(scgrp, 0);
1659 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1660 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1661 ss->root = dst_root;
1662 css->cgroup = dcgrp;
1664 spin_lock_irq(&css_set_lock);
1665 hash_for_each(css_set_table, i, cset, hlist)
1666 list_move_tail(&cset->e_cset_node[ss->id],
1667 &dcgrp->e_csets[ss->id]);
1668 spin_unlock_irq(&css_set_lock);
1670 /* default hierarchy doesn't enable controllers by default */
1671 dst_root->subsys_mask |= 1 << ssid;
1672 if (dst_root == &cgrp_dfl_root) {
1673 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1675 dcgrp->subtree_control |= 1 << ssid;
1676 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1679 ret = cgroup_apply_control(dcgrp);
1681 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1686 } while_each_subsys_mask();
1688 kernfs_activate(dcgrp->kn);
1692 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1693 struct kernfs_root *kf_root)
1697 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1698 struct cgroup *ns_cgroup;
1700 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1704 spin_lock_irq(&css_set_lock);
1705 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1706 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1707 spin_unlock_irq(&css_set_lock);
1709 if (len >= PATH_MAX)
1712 seq_escape(sf, buf, " \t\n\\");
1719 static int parse_cgroup_root_flags(char *data, unsigned int *root_flags)
1725 if (!data || *data == '\0')
1728 while ((token = strsep(&data, ",")) != NULL) {
1729 if (!strcmp(token, "nsdelegate")) {
1730 *root_flags |= CGRP_ROOT_NS_DELEGATE;
1734 pr_err("cgroup2: unknown option \"%s\"\n", token);
1741 static void apply_cgroup_root_flags(unsigned int root_flags)
1743 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1744 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1745 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1747 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1751 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1753 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1754 seq_puts(seq, ",nsdelegate");
1758 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1760 unsigned int root_flags;
1763 ret = parse_cgroup_root_flags(data, &root_flags);
1767 apply_cgroup_root_flags(root_flags);
1772 * To reduce the fork() overhead for systems that are not actually using
1773 * their cgroups capability, we don't maintain the lists running through
1774 * each css_set to its tasks until we see the list actually used - in other
1775 * words after the first mount.
1777 static bool use_task_css_set_links __read_mostly;
1779 static void cgroup_enable_task_cg_lists(void)
1781 struct task_struct *p, *g;
1783 spin_lock_irq(&css_set_lock);
1785 if (use_task_css_set_links)
1788 use_task_css_set_links = true;
1791 * We need tasklist_lock because RCU is not safe against
1792 * while_each_thread(). Besides, a forking task that has passed
1793 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1794 * is not guaranteed to have its child immediately visible in the
1795 * tasklist if we walk through it with RCU.
1797 read_lock(&tasklist_lock);
1798 do_each_thread(g, p) {
1799 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1800 task_css_set(p) != &init_css_set);
1803 * We should check if the process is exiting, otherwise
1804 * it will race with cgroup_exit() in that the list
1805 * entry won't be deleted though the process has exited.
1806 * Do it while holding siglock so that we don't end up
1807 * racing against cgroup_exit().
1809 * Interrupts were already disabled while acquiring
1810 * the css_set_lock, so we do not need to disable it
1811 * again when acquiring the sighand->siglock here.
1813 spin_lock(&p->sighand->siglock);
1814 if (!(p->flags & PF_EXITING)) {
1815 struct css_set *cset = task_css_set(p);
1817 if (!css_set_populated(cset))
1818 css_set_update_populated(cset, true);
1819 list_add_tail(&p->cg_list, &cset->tasks);
1823 spin_unlock(&p->sighand->siglock);
1824 } while_each_thread(g, p);
1825 read_unlock(&tasklist_lock);
1827 spin_unlock_irq(&css_set_lock);
1830 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1832 struct cgroup_subsys *ss;
1835 INIT_LIST_HEAD(&cgrp->self.sibling);
1836 INIT_LIST_HEAD(&cgrp->self.children);
1837 INIT_LIST_HEAD(&cgrp->cset_links);
1838 INIT_LIST_HEAD(&cgrp->pidlists);
1839 mutex_init(&cgrp->pidlist_mutex);
1840 cgrp->self.cgroup = cgrp;
1841 cgrp->self.flags |= CSS_ONLINE;
1842 cgrp->dom_cgrp = cgrp;
1843 cgrp->max_descendants = INT_MAX;
1844 cgrp->max_depth = INT_MAX;
1846 for_each_subsys(ss, ssid)
1847 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1849 init_waitqueue_head(&cgrp->offline_waitq);
1850 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
1853 void init_cgroup_root(struct cgroup_root *root, struct cgroup_sb_opts *opts)
1855 struct cgroup *cgrp = &root->cgrp;
1857 INIT_LIST_HEAD(&root->root_list);
1858 atomic_set(&root->nr_cgrps, 1);
1860 init_cgroup_housekeeping(cgrp);
1861 idr_init(&root->cgroup_idr);
1863 root->flags = opts->flags;
1864 if (opts->release_agent)
1865 strcpy(root->release_agent_path, opts->release_agent);
1867 strcpy(root->name, opts->name);
1868 if (opts->cpuset_clone_children)
1869 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1872 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask, int ref_flags)
1874 LIST_HEAD(tmp_links);
1875 struct cgroup *root_cgrp = &root->cgrp;
1876 struct kernfs_syscall_ops *kf_sops;
1877 struct css_set *cset;
1880 lockdep_assert_held(&cgroup_mutex);
1882 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1885 root_cgrp->id = ret;
1886 root_cgrp->ancestor_ids[0] = ret;
1888 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
1889 ref_flags, GFP_KERNEL);
1894 * We're accessing css_set_count without locking css_set_lock here,
1895 * but that's OK - it can only be increased by someone holding
1896 * cgroup_lock, and that's us. Later rebinding may disable
1897 * controllers on the default hierarchy and thus create new csets,
1898 * which can't be more than the existing ones. Allocate 2x.
1900 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
1904 ret = cgroup_init_root_id(root);
1908 kf_sops = root == &cgrp_dfl_root ?
1909 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
1911 root->kf_root = kernfs_create_root(kf_sops,
1912 KERNFS_ROOT_CREATE_DEACTIVATED |
1913 KERNFS_ROOT_SUPPORT_EXPORTOP,
1915 if (IS_ERR(root->kf_root)) {
1916 ret = PTR_ERR(root->kf_root);
1919 root_cgrp->kn = root->kf_root->kn;
1921 ret = css_populate_dir(&root_cgrp->self);
1925 ret = rebind_subsystems(root, ss_mask);
1929 trace_cgroup_setup_root(root);
1932 * There must be no failure case after here, since rebinding takes
1933 * care of subsystems' refcounts, which are explicitly dropped in
1934 * the failure exit path.
1936 list_add(&root->root_list, &cgroup_roots);
1937 cgroup_root_count++;
1940 * Link the root cgroup in this hierarchy into all the css_set
1943 spin_lock_irq(&css_set_lock);
1944 hash_for_each(css_set_table, i, cset, hlist) {
1945 link_css_set(&tmp_links, cset, root_cgrp);
1946 if (css_set_populated(cset))
1947 cgroup_update_populated(root_cgrp, true);
1949 spin_unlock_irq(&css_set_lock);
1951 BUG_ON(!list_empty(&root_cgrp->self.children));
1952 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1954 kernfs_activate(root_cgrp->kn);
1959 kernfs_destroy_root(root->kf_root);
1960 root->kf_root = NULL;
1962 cgroup_exit_root_id(root);
1964 percpu_ref_exit(&root_cgrp->self.refcnt);
1966 free_cgrp_cset_links(&tmp_links);
1970 struct dentry *cgroup_do_mount(struct file_system_type *fs_type, int flags,
1971 struct cgroup_root *root, unsigned long magic,
1972 struct cgroup_namespace *ns)
1974 struct dentry *dentry;
1975 bool new_sb = false;
1977 dentry = kernfs_mount(fs_type, flags, root->kf_root, magic, &new_sb);
1980 * In non-init cgroup namespace, instead of root cgroup's dentry,
1981 * we return the dentry corresponding to the cgroupns->root_cgrp.
1983 if (!IS_ERR(dentry) && ns != &init_cgroup_ns) {
1984 struct dentry *nsdentry;
1985 struct super_block *sb = dentry->d_sb;
1986 struct cgroup *cgrp;
1988 mutex_lock(&cgroup_mutex);
1989 spin_lock_irq(&css_set_lock);
1991 cgrp = cset_cgroup_from_root(ns->root_cset, root);
1993 spin_unlock_irq(&css_set_lock);
1994 mutex_unlock(&cgroup_mutex);
1996 nsdentry = kernfs_node_dentry(cgrp->kn, sb);
1998 if (IS_ERR(nsdentry))
1999 deactivate_locked_super(sb);
2004 cgroup_put(&root->cgrp);
2009 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
2010 int flags, const char *unused_dev_name,
2013 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
2014 struct dentry *dentry;
2019 /* Check if the caller has permission to mount. */
2020 if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) {
2022 return ERR_PTR(-EPERM);
2026 * The first time anyone tries to mount a cgroup, enable the list
2027 * linking each css_set to its tasks and fix up all existing tasks.
2029 if (!use_task_css_set_links)
2030 cgroup_enable_task_cg_lists();
2032 if (fs_type == &cgroup2_fs_type) {
2033 unsigned int root_flags;
2035 ret = parse_cgroup_root_flags(data, &root_flags);
2038 return ERR_PTR(ret);
2041 cgrp_dfl_visible = true;
2042 cgroup_get_live(&cgrp_dfl_root.cgrp);
2044 dentry = cgroup_do_mount(&cgroup2_fs_type, flags, &cgrp_dfl_root,
2045 CGROUP2_SUPER_MAGIC, ns);
2046 if (!IS_ERR(dentry))
2047 apply_cgroup_root_flags(root_flags);
2049 dentry = cgroup1_mount(&cgroup_fs_type, flags, data,
2050 CGROUP_SUPER_MAGIC, ns);
2057 static void cgroup_kill_sb(struct super_block *sb)
2059 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2060 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2063 * If @root doesn't have any mounts or children, start killing it.
2064 * This prevents new mounts by disabling percpu_ref_tryget_live().
2065 * cgroup_mount() may wait for @root's release.
2067 * And don't kill the default root.
2069 if (!list_empty(&root->cgrp.self.children) ||
2070 root == &cgrp_dfl_root)
2071 cgroup_put(&root->cgrp);
2073 percpu_ref_kill(&root->cgrp.self.refcnt);
2078 struct file_system_type cgroup_fs_type = {
2080 .mount = cgroup_mount,
2081 .kill_sb = cgroup_kill_sb,
2082 .fs_flags = FS_USERNS_MOUNT,
2085 static struct file_system_type cgroup2_fs_type = {
2087 .mount = cgroup_mount,
2088 .kill_sb = cgroup_kill_sb,
2089 .fs_flags = FS_USERNS_MOUNT,
2092 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2093 struct cgroup_namespace *ns)
2095 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2097 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2100 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2101 struct cgroup_namespace *ns)
2105 mutex_lock(&cgroup_mutex);
2106 spin_lock_irq(&css_set_lock);
2108 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2110 spin_unlock_irq(&css_set_lock);
2111 mutex_unlock(&cgroup_mutex);
2115 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2118 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2119 * @task: target task
2120 * @buf: the buffer to write the path into
2121 * @buflen: the length of the buffer
2123 * Determine @task's cgroup on the first (the one with the lowest non-zero
2124 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2125 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2126 * cgroup controller callbacks.
2128 * Return value is the same as kernfs_path().
2130 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2132 struct cgroup_root *root;
2133 struct cgroup *cgrp;
2134 int hierarchy_id = 1;
2137 mutex_lock(&cgroup_mutex);
2138 spin_lock_irq(&css_set_lock);
2140 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2143 cgrp = task_cgroup_from_root(task, root);
2144 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2146 /* if no hierarchy exists, everyone is in "/" */
2147 ret = strlcpy(buf, "/", buflen);
2150 spin_unlock_irq(&css_set_lock);
2151 mutex_unlock(&cgroup_mutex);
2154 EXPORT_SYMBOL_GPL(task_cgroup_path);
2157 * cgroup_migrate_add_task - add a migration target task to a migration context
2158 * @task: target task
2159 * @mgctx: target migration context
2161 * Add @task, which is a migration target, to @mgctx->tset. This function
2162 * becomes noop if @task doesn't need to be migrated. @task's css_set
2163 * should have been added as a migration source and @task->cg_list will be
2164 * moved from the css_set's tasks list to mg_tasks one.
2166 static void cgroup_migrate_add_task(struct task_struct *task,
2167 struct cgroup_mgctx *mgctx)
2169 struct css_set *cset;
2171 lockdep_assert_held(&css_set_lock);
2173 /* @task either already exited or can't exit until the end */
2174 if (task->flags & PF_EXITING)
2177 /* leave @task alone if post_fork() hasn't linked it yet */
2178 if (list_empty(&task->cg_list))
2181 cset = task_css_set(task);
2182 if (!cset->mg_src_cgrp)
2185 mgctx->tset.nr_tasks++;
2187 list_move_tail(&task->cg_list, &cset->mg_tasks);
2188 if (list_empty(&cset->mg_node))
2189 list_add_tail(&cset->mg_node,
2190 &mgctx->tset.src_csets);
2191 if (list_empty(&cset->mg_dst_cset->mg_node))
2192 list_add_tail(&cset->mg_dst_cset->mg_node,
2193 &mgctx->tset.dst_csets);
2197 * cgroup_taskset_first - reset taskset and return the first task
2198 * @tset: taskset of interest
2199 * @dst_cssp: output variable for the destination css
2201 * @tset iteration is initialized and the first task is returned.
2203 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2204 struct cgroup_subsys_state **dst_cssp)
2206 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2207 tset->cur_task = NULL;
2209 return cgroup_taskset_next(tset, dst_cssp);
2213 * cgroup_taskset_next - iterate to the next task in taskset
2214 * @tset: taskset of interest
2215 * @dst_cssp: output variable for the destination css
2217 * Return the next task in @tset. Iteration must have been initialized
2218 * with cgroup_taskset_first().
2220 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2221 struct cgroup_subsys_state **dst_cssp)
2223 struct css_set *cset = tset->cur_cset;
2224 struct task_struct *task = tset->cur_task;
2226 while (&cset->mg_node != tset->csets) {
2228 task = list_first_entry(&cset->mg_tasks,
2229 struct task_struct, cg_list);
2231 task = list_next_entry(task, cg_list);
2233 if (&task->cg_list != &cset->mg_tasks) {
2234 tset->cur_cset = cset;
2235 tset->cur_task = task;
2238 * This function may be called both before and
2239 * after cgroup_taskset_migrate(). The two cases
2240 * can be distinguished by looking at whether @cset
2241 * has its ->mg_dst_cset set.
2243 if (cset->mg_dst_cset)
2244 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2246 *dst_cssp = cset->subsys[tset->ssid];
2251 cset = list_next_entry(cset, mg_node);
2259 * cgroup_taskset_migrate - migrate a taskset
2260 * @mgctx: migration context
2262 * Migrate tasks in @mgctx as setup by migration preparation functions.
2263 * This function fails iff one of the ->can_attach callbacks fails and
2264 * guarantees that either all or none of the tasks in @mgctx are migrated.
2265 * @mgctx is consumed regardless of success.
2267 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2269 struct cgroup_taskset *tset = &mgctx->tset;
2270 struct cgroup_subsys *ss;
2271 struct task_struct *task, *tmp_task;
2272 struct css_set *cset, *tmp_cset;
2273 int ssid, failed_ssid, ret;
2275 /* check that we can legitimately attach to the cgroup */
2276 if (tset->nr_tasks) {
2277 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2278 if (ss->can_attach) {
2280 ret = ss->can_attach(tset);
2283 goto out_cancel_attach;
2286 } while_each_subsys_mask();
2290 * Now that we're guaranteed success, proceed to move all tasks to
2291 * the new cgroup. There are no failure cases after here, so this
2292 * is the commit point.
2294 spin_lock_irq(&css_set_lock);
2295 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2296 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2297 struct css_set *from_cset = task_css_set(task);
2298 struct css_set *to_cset = cset->mg_dst_cset;
2300 get_css_set(to_cset);
2301 to_cset->nr_tasks++;
2302 css_set_move_task(task, from_cset, to_cset, true);
2303 put_css_set_locked(from_cset);
2304 from_cset->nr_tasks--;
2307 spin_unlock_irq(&css_set_lock);
2310 * Migration is committed, all target tasks are now on dst_csets.
2311 * Nothing is sensitive to fork() after this point. Notify
2312 * controllers that migration is complete.
2314 tset->csets = &tset->dst_csets;
2316 if (tset->nr_tasks) {
2317 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2322 } while_each_subsys_mask();
2326 goto out_release_tset;
2329 if (tset->nr_tasks) {
2330 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2331 if (ssid == failed_ssid)
2333 if (ss->cancel_attach) {
2335 ss->cancel_attach(tset);
2337 } while_each_subsys_mask();
2340 spin_lock_irq(&css_set_lock);
2341 list_splice_init(&tset->dst_csets, &tset->src_csets);
2342 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2343 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2344 list_del_init(&cset->mg_node);
2346 spin_unlock_irq(&css_set_lock);
2349 * Re-initialize the cgroup_taskset structure in case it is reused
2350 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2354 tset->csets = &tset->src_csets;
2359 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2360 * @dst_cgrp: destination cgroup to test
2362 * On the default hierarchy, except for the mixable, (possible) thread root
2363 * and threaded cgroups, subtree_control must be zero for migration
2364 * destination cgroups with tasks so that child cgroups don't compete
2367 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2369 /* v1 doesn't have any restriction */
2370 if (!cgroup_on_dfl(dst_cgrp))
2373 /* verify @dst_cgrp can host resources */
2374 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2377 /* mixables don't care */
2378 if (cgroup_is_mixable(dst_cgrp))
2382 * If @dst_cgrp is already or can become a thread root or is
2383 * threaded, it doesn't matter.
2385 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2388 /* apply no-internal-process constraint */
2389 if (dst_cgrp->subtree_control)
2396 * cgroup_migrate_finish - cleanup after attach
2397 * @mgctx: migration context
2399 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2400 * those functions for details.
2402 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2404 struct css_set *cset, *tmp_cset;
2406 lockdep_assert_held(&cgroup_mutex);
2408 spin_lock_irq(&css_set_lock);
2410 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_src_csets,
2411 mg_src_preload_node) {
2412 cset->mg_src_cgrp = NULL;
2413 cset->mg_dst_cgrp = NULL;
2414 cset->mg_dst_cset = NULL;
2415 list_del_init(&cset->mg_src_preload_node);
2416 put_css_set_locked(cset);
2419 list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_dst_csets,
2420 mg_dst_preload_node) {
2421 cset->mg_src_cgrp = NULL;
2422 cset->mg_dst_cgrp = NULL;
2423 cset->mg_dst_cset = NULL;
2424 list_del_init(&cset->mg_dst_preload_node);
2425 put_css_set_locked(cset);
2428 spin_unlock_irq(&css_set_lock);
2432 * cgroup_migrate_add_src - add a migration source css_set
2433 * @src_cset: the source css_set to add
2434 * @dst_cgrp: the destination cgroup
2435 * @mgctx: migration context
2437 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2438 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2439 * up by cgroup_migrate_finish().
2441 * This function may be called without holding cgroup_threadgroup_rwsem
2442 * even if the target is a process. Threads may be created and destroyed
2443 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2444 * into play and the preloaded css_sets are guaranteed to cover all
2447 void cgroup_migrate_add_src(struct css_set *src_cset,
2448 struct cgroup *dst_cgrp,
2449 struct cgroup_mgctx *mgctx)
2451 struct cgroup *src_cgrp;
2453 lockdep_assert_held(&cgroup_mutex);
2454 lockdep_assert_held(&css_set_lock);
2457 * If ->dead, @src_set is associated with one or more dead cgroups
2458 * and doesn't contain any migratable tasks. Ignore it early so
2459 * that the rest of migration path doesn't get confused by it.
2464 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2466 if (!list_empty(&src_cset->mg_src_preload_node))
2469 WARN_ON(src_cset->mg_src_cgrp);
2470 WARN_ON(src_cset->mg_dst_cgrp);
2471 WARN_ON(!list_empty(&src_cset->mg_tasks));
2472 WARN_ON(!list_empty(&src_cset->mg_node));
2474 src_cset->mg_src_cgrp = src_cgrp;
2475 src_cset->mg_dst_cgrp = dst_cgrp;
2476 get_css_set(src_cset);
2477 list_add_tail(&src_cset->mg_src_preload_node, &mgctx->preloaded_src_csets);
2481 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2482 * @mgctx: migration context
2484 * Tasks are about to be moved and all the source css_sets have been
2485 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2486 * pins all destination css_sets, links each to its source, and append them
2487 * to @mgctx->preloaded_dst_csets.
2489 * This function must be called after cgroup_migrate_add_src() has been
2490 * called on each migration source css_set. After migration is performed
2491 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2494 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2496 struct css_set *src_cset, *tmp_cset;
2498 lockdep_assert_held(&cgroup_mutex);
2500 /* look up the dst cset for each src cset and link it to src */
2501 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2502 mg_src_preload_node) {
2503 struct css_set *dst_cset;
2504 struct cgroup_subsys *ss;
2507 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2511 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2514 * If src cset equals dst, it's noop. Drop the src.
2515 * cgroup_migrate() will skip the cset too. Note that we
2516 * can't handle src == dst as some nodes are used by both.
2518 if (src_cset == dst_cset) {
2519 src_cset->mg_src_cgrp = NULL;
2520 src_cset->mg_dst_cgrp = NULL;
2521 list_del_init(&src_cset->mg_src_preload_node);
2522 put_css_set(src_cset);
2523 put_css_set(dst_cset);
2527 src_cset->mg_dst_cset = dst_cset;
2529 if (list_empty(&dst_cset->mg_dst_preload_node))
2530 list_add_tail(&dst_cset->mg_dst_preload_node,
2531 &mgctx->preloaded_dst_csets);
2533 put_css_set(dst_cset);
2535 for_each_subsys(ss, ssid)
2536 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2537 mgctx->ss_mask |= 1 << ssid;
2542 cgroup_migrate_finish(mgctx);
2547 * cgroup_migrate - migrate a process or task to a cgroup
2548 * @leader: the leader of the process or the task to migrate
2549 * @threadgroup: whether @leader points to the whole process or a single task
2550 * @mgctx: migration context
2552 * Migrate a process or task denoted by @leader. If migrating a process,
2553 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2554 * responsible for invoking cgroup_migrate_add_src() and
2555 * cgroup_migrate_prepare_dst() on the targets before invoking this
2556 * function and following up with cgroup_migrate_finish().
2558 * As long as a controller's ->can_attach() doesn't fail, this function is
2559 * guaranteed to succeed. This means that, excluding ->can_attach()
2560 * failure, when migrating multiple targets, the success or failure can be
2561 * decided for all targets by invoking group_migrate_prepare_dst() before
2562 * actually starting migrating.
2564 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2565 struct cgroup_mgctx *mgctx)
2567 struct task_struct *task;
2570 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2571 * already PF_EXITING could be freed from underneath us unless we
2572 * take an rcu_read_lock.
2574 spin_lock_irq(&css_set_lock);
2578 cgroup_migrate_add_task(task, mgctx);
2581 } while_each_thread(leader, task);
2583 spin_unlock_irq(&css_set_lock);
2585 return cgroup_migrate_execute(mgctx);
2589 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2590 * @dst_cgrp: the cgroup to attach to
2591 * @leader: the task or the leader of the threadgroup to be attached
2592 * @threadgroup: attach the whole threadgroup?
2594 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2596 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2599 DEFINE_CGROUP_MGCTX(mgctx);
2600 struct task_struct *task;
2603 ret = cgroup_migrate_vet_dst(dst_cgrp);
2607 /* look up all src csets */
2608 spin_lock_irq(&css_set_lock);
2612 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2615 } while_each_thread(leader, task);
2617 spin_unlock_irq(&css_set_lock);
2619 /* prepare dst csets and commit */
2620 ret = cgroup_migrate_prepare_dst(&mgctx);
2622 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2624 cgroup_migrate_finish(&mgctx);
2627 trace_cgroup_attach_task(dst_cgrp, leader, threadgroup);
2632 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup)
2633 __acquires(&cgroup_threadgroup_rwsem)
2635 struct task_struct *tsk;
2638 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2639 return ERR_PTR(-EINVAL);
2641 percpu_down_write(&cgroup_threadgroup_rwsem);
2645 tsk = find_task_by_vpid(pid);
2647 tsk = ERR_PTR(-ESRCH);
2648 goto out_unlock_threadgroup;
2655 tsk = tsk->group_leader;
2658 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2659 * If userland migrates such a kthread to a non-root cgroup, it can
2660 * become trapped in a cpuset, or RT kthread may be born in a
2661 * cgroup with no rt_runtime allocated. Just say no.
2663 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2664 tsk = ERR_PTR(-EINVAL);
2665 goto out_unlock_threadgroup;
2668 get_task_struct(tsk);
2669 goto out_unlock_rcu;
2671 out_unlock_threadgroup:
2672 percpu_up_write(&cgroup_threadgroup_rwsem);
2678 void cgroup_procs_write_finish(struct task_struct *task)
2679 __releases(&cgroup_threadgroup_rwsem)
2681 struct cgroup_subsys *ss;
2684 /* release reference from cgroup_procs_write_start() */
2685 put_task_struct(task);
2687 percpu_up_write(&cgroup_threadgroup_rwsem);
2688 for_each_subsys(ss, ssid)
2689 if (ss->post_attach)
2693 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2695 struct cgroup_subsys *ss;
2696 bool printed = false;
2699 do_each_subsys_mask(ss, ssid, ss_mask) {
2702 seq_printf(seq, "%s", ss->name);
2704 } while_each_subsys_mask();
2706 seq_putc(seq, '\n');
2709 /* show controllers which are enabled from the parent */
2710 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2712 struct cgroup *cgrp = seq_css(seq)->cgroup;
2714 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2718 /* show controllers which are enabled for a given cgroup's children */
2719 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2721 struct cgroup *cgrp = seq_css(seq)->cgroup;
2723 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2728 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2729 * @cgrp: root of the subtree to update csses for
2731 * @cgrp's control masks have changed and its subtree's css associations
2732 * need to be updated accordingly. This function looks up all css_sets
2733 * which are attached to the subtree, creates the matching updated css_sets
2734 * and migrates the tasks to the new ones.
2736 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2738 DEFINE_CGROUP_MGCTX(mgctx);
2739 struct cgroup_subsys_state *d_css;
2740 struct cgroup *dsct;
2741 struct css_set *src_cset;
2744 lockdep_assert_held(&cgroup_mutex);
2746 percpu_down_write(&cgroup_threadgroup_rwsem);
2748 /* look up all csses currently attached to @cgrp's subtree */
2749 spin_lock_irq(&css_set_lock);
2750 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2751 struct cgrp_cset_link *link;
2753 list_for_each_entry(link, &dsct->cset_links, cset_link)
2754 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2756 spin_unlock_irq(&css_set_lock);
2758 /* NULL dst indicates self on default hierarchy */
2759 ret = cgroup_migrate_prepare_dst(&mgctx);
2763 spin_lock_irq(&css_set_lock);
2764 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets,
2765 mg_src_preload_node) {
2766 struct task_struct *task, *ntask;
2768 /* all tasks in src_csets need to be migrated */
2769 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2770 cgroup_migrate_add_task(task, &mgctx);
2772 spin_unlock_irq(&css_set_lock);
2774 ret = cgroup_migrate_execute(&mgctx);
2776 cgroup_migrate_finish(&mgctx);
2777 percpu_up_write(&cgroup_threadgroup_rwsem);
2782 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2783 * @cgrp: root of the target subtree
2785 * Because css offlining is asynchronous, userland may try to re-enable a
2786 * controller while the previous css is still around. This function grabs
2787 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2789 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2790 __acquires(&cgroup_mutex)
2792 struct cgroup *dsct;
2793 struct cgroup_subsys_state *d_css;
2794 struct cgroup_subsys *ss;
2798 mutex_lock(&cgroup_mutex);
2800 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2801 for_each_subsys(ss, ssid) {
2802 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2805 if (!css || !percpu_ref_is_dying(&css->refcnt))
2808 cgroup_get_live(dsct);
2809 prepare_to_wait(&dsct->offline_waitq, &wait,
2810 TASK_UNINTERRUPTIBLE);
2812 mutex_unlock(&cgroup_mutex);
2814 finish_wait(&dsct->offline_waitq, &wait);
2823 * cgroup_save_control - save control masks and dom_cgrp of a subtree
2824 * @cgrp: root of the target subtree
2826 * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
2827 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2830 static void cgroup_save_control(struct cgroup *cgrp)
2832 struct cgroup *dsct;
2833 struct cgroup_subsys_state *d_css;
2835 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2836 dsct->old_subtree_control = dsct->subtree_control;
2837 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
2838 dsct->old_dom_cgrp = dsct->dom_cgrp;
2843 * cgroup_propagate_control - refresh control masks of a subtree
2844 * @cgrp: root of the target subtree
2846 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
2847 * ->subtree_control and propagate controller availability through the
2848 * subtree so that descendants don't have unavailable controllers enabled.
2850 static void cgroup_propagate_control(struct cgroup *cgrp)
2852 struct cgroup *dsct;
2853 struct cgroup_subsys_state *d_css;
2855 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2856 dsct->subtree_control &= cgroup_control(dsct);
2857 dsct->subtree_ss_mask =
2858 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
2859 cgroup_ss_mask(dsct));
2864 * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
2865 * @cgrp: root of the target subtree
2867 * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
2868 * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2871 static void cgroup_restore_control(struct cgroup *cgrp)
2873 struct cgroup *dsct;
2874 struct cgroup_subsys_state *d_css;
2876 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2877 dsct->subtree_control = dsct->old_subtree_control;
2878 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
2879 dsct->dom_cgrp = dsct->old_dom_cgrp;
2883 static bool css_visible(struct cgroup_subsys_state *css)
2885 struct cgroup_subsys *ss = css->ss;
2886 struct cgroup *cgrp = css->cgroup;
2888 if (cgroup_control(cgrp) & (1 << ss->id))
2890 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
2892 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
2896 * cgroup_apply_control_enable - enable or show csses according to control
2897 * @cgrp: root of the target subtree
2899 * Walk @cgrp's subtree and create new csses or make the existing ones
2900 * visible. A css is created invisible if it's being implicitly enabled
2901 * through dependency. An invisible css is made visible when the userland
2902 * explicitly enables it.
2904 * Returns 0 on success, -errno on failure. On failure, csses which have
2905 * been processed already aren't cleaned up. The caller is responsible for
2906 * cleaning up with cgroup_apply_control_disable().
2908 static int cgroup_apply_control_enable(struct cgroup *cgrp)
2910 struct cgroup *dsct;
2911 struct cgroup_subsys_state *d_css;
2912 struct cgroup_subsys *ss;
2915 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2916 for_each_subsys(ss, ssid) {
2917 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2919 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
2923 css = css_create(dsct, ss);
2925 return PTR_ERR(css);
2928 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
2930 if (css_visible(css)) {
2931 ret = css_populate_dir(css);
2942 * cgroup_apply_control_disable - kill or hide csses according to control
2943 * @cgrp: root of the target subtree
2945 * Walk @cgrp's subtree and kill and hide csses so that they match
2946 * cgroup_ss_mask() and cgroup_visible_mask().
2948 * A css is hidden when the userland requests it to be disabled while other
2949 * subsystems are still depending on it. The css must not actively control
2950 * resources and be in the vanilla state if it's made visible again later.
2951 * Controllers which may be depended upon should provide ->css_reset() for
2954 static void cgroup_apply_control_disable(struct cgroup *cgrp)
2956 struct cgroup *dsct;
2957 struct cgroup_subsys_state *d_css;
2958 struct cgroup_subsys *ss;
2961 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2962 for_each_subsys(ss, ssid) {
2963 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2968 WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
2971 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
2973 } else if (!css_visible(css)) {
2983 * cgroup_apply_control - apply control mask updates to the subtree
2984 * @cgrp: root of the target subtree
2986 * subsystems can be enabled and disabled in a subtree using the following
2989 * 1. Call cgroup_save_control() to stash the current state.
2990 * 2. Update ->subtree_control masks in the subtree as desired.
2991 * 3. Call cgroup_apply_control() to apply the changes.
2992 * 4. Optionally perform other related operations.
2993 * 5. Call cgroup_finalize_control() to finish up.
2995 * This function implements step 3 and propagates the mask changes
2996 * throughout @cgrp's subtree, updates csses accordingly and perform
2997 * process migrations.
2999 static int cgroup_apply_control(struct cgroup *cgrp)
3003 cgroup_propagate_control(cgrp);
3005 ret = cgroup_apply_control_enable(cgrp);
3010 * At this point, cgroup_e_css() results reflect the new csses
3011 * making the following cgroup_update_dfl_csses() properly update
3012 * css associations of all tasks in the subtree.
3014 ret = cgroup_update_dfl_csses(cgrp);
3022 * cgroup_finalize_control - finalize control mask update
3023 * @cgrp: root of the target subtree
3024 * @ret: the result of the update
3026 * Finalize control mask update. See cgroup_apply_control() for more info.
3028 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3031 cgroup_restore_control(cgrp);
3032 cgroup_propagate_control(cgrp);
3035 cgroup_apply_control_disable(cgrp);
3038 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3040 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3042 /* if nothing is getting enabled, nothing to worry about */
3046 /* can @cgrp host any resources? */
3047 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3050 /* mixables don't care */
3051 if (cgroup_is_mixable(cgrp))
3054 if (domain_enable) {
3055 /* can't enable domain controllers inside a thread subtree */
3056 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3060 * Threaded controllers can handle internal competitions
3061 * and are always allowed inside a (prospective) thread
3064 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3069 * Controllers can't be enabled for a cgroup with tasks to avoid
3070 * child cgroups competing against tasks.
3072 if (cgroup_has_tasks(cgrp))
3078 /* change the enabled child controllers for a cgroup in the default hierarchy */
3079 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3080 char *buf, size_t nbytes,
3083 u16 enable = 0, disable = 0;
3084 struct cgroup *cgrp, *child;
3085 struct cgroup_subsys *ss;
3090 * Parse input - space separated list of subsystem names prefixed
3091 * with either + or -.
3093 buf = strstrip(buf);
3094 while ((tok = strsep(&buf, " "))) {
3097 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3098 if (!cgroup_ssid_enabled(ssid) ||
3099 strcmp(tok + 1, ss->name))
3103 enable |= 1 << ssid;
3104 disable &= ~(1 << ssid);
3105 } else if (*tok == '-') {
3106 disable |= 1 << ssid;
3107 enable &= ~(1 << ssid);
3112 } while_each_subsys_mask();
3113 if (ssid == CGROUP_SUBSYS_COUNT)
3117 cgrp = cgroup_kn_lock_live(of->kn, true);
3121 for_each_subsys(ss, ssid) {
3122 if (enable & (1 << ssid)) {
3123 if (cgrp->subtree_control & (1 << ssid)) {
3124 enable &= ~(1 << ssid);
3128 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3132 } else if (disable & (1 << ssid)) {
3133 if (!(cgrp->subtree_control & (1 << ssid))) {
3134 disable &= ~(1 << ssid);
3138 /* a child has it enabled? */
3139 cgroup_for_each_live_child(child, cgrp) {
3140 if (child->subtree_control & (1 << ssid)) {
3148 if (!enable && !disable) {
3153 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3157 /* save and update control masks and prepare csses */
3158 cgroup_save_control(cgrp);
3160 cgrp->subtree_control |= enable;
3161 cgrp->subtree_control &= ~disable;
3163 ret = cgroup_apply_control(cgrp);
3164 cgroup_finalize_control(cgrp, ret);
3168 kernfs_activate(cgrp->kn);
3170 cgroup_kn_unlock(of->kn);
3171 return ret ?: nbytes;
3175 * cgroup_enable_threaded - make @cgrp threaded
3176 * @cgrp: the target cgroup
3178 * Called when "threaded" is written to the cgroup.type interface file and
3179 * tries to make @cgrp threaded and join the parent's resource domain.
3180 * This function is never called on the root cgroup as cgroup.type doesn't
3183 static int cgroup_enable_threaded(struct cgroup *cgrp)
3185 struct cgroup *parent = cgroup_parent(cgrp);
3186 struct cgroup *dom_cgrp = parent->dom_cgrp;
3187 struct cgroup *dsct;
3188 struct cgroup_subsys_state *d_css;
3191 lockdep_assert_held(&cgroup_mutex);
3193 /* noop if already threaded */
3194 if (cgroup_is_threaded(cgrp))
3198 * If @cgroup is populated or has domain controllers enabled, it
3199 * can't be switched. While the below cgroup_can_be_thread_root()
3200 * test can catch the same conditions, that's only when @parent is
3201 * not mixable, so let's check it explicitly.
3203 if (cgroup_is_populated(cgrp) ||
3204 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3207 /* we're joining the parent's domain, ensure its validity */
3208 if (!cgroup_is_valid_domain(dom_cgrp) ||
3209 !cgroup_can_be_thread_root(dom_cgrp))
3213 * The following shouldn't cause actual migrations and should
3216 cgroup_save_control(cgrp);
3218 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3219 if (dsct == cgrp || cgroup_is_threaded(dsct))
3220 dsct->dom_cgrp = dom_cgrp;
3222 ret = cgroup_apply_control(cgrp);
3224 parent->nr_threaded_children++;
3226 cgroup_finalize_control(cgrp, ret);
3230 static int cgroup_type_show(struct seq_file *seq, void *v)
3232 struct cgroup *cgrp = seq_css(seq)->cgroup;
3234 if (cgroup_is_threaded(cgrp))
3235 seq_puts(seq, "threaded\n");
3236 else if (!cgroup_is_valid_domain(cgrp))
3237 seq_puts(seq, "domain invalid\n");
3238 else if (cgroup_is_thread_root(cgrp))
3239 seq_puts(seq, "domain threaded\n");
3241 seq_puts(seq, "domain\n");
3246 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3247 size_t nbytes, loff_t off)
3249 struct cgroup *cgrp;
3252 /* only switching to threaded mode is supported */
3253 if (strcmp(strstrip(buf), "threaded"))
3256 /* drain dying csses before we re-apply (threaded) subtree control */
3257 cgrp = cgroup_kn_lock_live(of->kn, true);
3261 /* threaded can only be enabled */
3262 ret = cgroup_enable_threaded(cgrp);
3264 cgroup_kn_unlock(of->kn);
3265 return ret ?: nbytes;
3268 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3270 struct cgroup *cgrp = seq_css(seq)->cgroup;
3271 int descendants = READ_ONCE(cgrp->max_descendants);
3273 if (descendants == INT_MAX)
3274 seq_puts(seq, "max\n");
3276 seq_printf(seq, "%d\n", descendants);
3281 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3282 char *buf, size_t nbytes, loff_t off)
3284 struct cgroup *cgrp;
3288 buf = strstrip(buf);
3289 if (!strcmp(buf, "max")) {
3290 descendants = INT_MAX;
3292 ret = kstrtoint(buf, 0, &descendants);
3297 if (descendants < 0)
3300 cgrp = cgroup_kn_lock_live(of->kn, false);
3304 cgrp->max_descendants = descendants;
3306 cgroup_kn_unlock(of->kn);
3311 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3313 struct cgroup *cgrp = seq_css(seq)->cgroup;
3314 int depth = READ_ONCE(cgrp->max_depth);
3316 if (depth == INT_MAX)
3317 seq_puts(seq, "max\n");
3319 seq_printf(seq, "%d\n", depth);
3324 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3325 char *buf, size_t nbytes, loff_t off)
3327 struct cgroup *cgrp;
3331 buf = strstrip(buf);
3332 if (!strcmp(buf, "max")) {
3335 ret = kstrtoint(buf, 0, &depth);
3343 cgrp = cgroup_kn_lock_live(of->kn, false);
3347 cgrp->max_depth = depth;
3349 cgroup_kn_unlock(of->kn);
3354 static int cgroup_events_show(struct seq_file *seq, void *v)
3356 seq_printf(seq, "populated %d\n",
3357 cgroup_is_populated(seq_css(seq)->cgroup));
3361 static int cgroup_stat_show(struct seq_file *seq, void *v)
3363 struct cgroup *cgroup = seq_css(seq)->cgroup;
3365 seq_printf(seq, "nr_descendants %d\n",
3366 cgroup->nr_descendants);
3367 seq_printf(seq, "nr_dying_descendants %d\n",
3368 cgroup->nr_dying_descendants);
3373 static int cgroup_file_open(struct kernfs_open_file *of)
3375 struct cftype *cft = of->kn->priv;
3376 struct cgroup_file_ctx *ctx;
3379 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3383 ctx->ns = current->nsproxy->cgroup_ns;
3384 get_cgroup_ns(ctx->ns);
3390 ret = cft->open(of);
3392 put_cgroup_ns(ctx->ns);
3398 static void cgroup_file_release(struct kernfs_open_file *of)
3400 struct cftype *cft = of->kn->priv;
3401 struct cgroup_file_ctx *ctx = of->priv;
3405 put_cgroup_ns(ctx->ns);
3409 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3410 size_t nbytes, loff_t off)
3412 struct cgroup_file_ctx *ctx = of->priv;
3413 struct cgroup *cgrp = of->kn->parent->priv;
3414 struct cftype *cft = of->kn->priv;
3415 struct cgroup_subsys_state *css;
3419 * If namespaces are delegation boundaries, disallow writes to
3420 * files in an non-init namespace root from inside the namespace
3421 * except for the files explicitly marked delegatable -
3422 * cgroup.procs and cgroup.subtree_control.
3424 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3425 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3426 ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
3430 return cft->write(of, buf, nbytes, off);
3433 * kernfs guarantees that a file isn't deleted with operations in
3434 * flight, which means that the matching css is and stays alive and
3435 * doesn't need to be pinned. The RCU locking is not necessary
3436 * either. It's just for the convenience of using cgroup_css().
3439 css = cgroup_css(cgrp, cft->ss);
3442 if (cft->write_u64) {
3443 unsigned long long v;
3444 ret = kstrtoull(buf, 0, &v);
3446 ret = cft->write_u64(css, cft, v);
3447 } else if (cft->write_s64) {
3449 ret = kstrtoll(buf, 0, &v);
3451 ret = cft->write_s64(css, cft, v);
3456 return ret ?: nbytes;
3459 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3461 return seq_cft(seq)->seq_start(seq, ppos);
3464 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3466 return seq_cft(seq)->seq_next(seq, v, ppos);
3469 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3471 if (seq_cft(seq)->seq_stop)
3472 seq_cft(seq)->seq_stop(seq, v);
3475 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3477 struct cftype *cft = seq_cft(m);
3478 struct cgroup_subsys_state *css = seq_css(m);
3481 return cft->seq_show(m, arg);
3484 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3485 else if (cft->read_s64)
3486 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3492 static struct kernfs_ops cgroup_kf_single_ops = {
3493 .atomic_write_len = PAGE_SIZE,
3494 .open = cgroup_file_open,
3495 .release = cgroup_file_release,
3496 .write = cgroup_file_write,
3497 .seq_show = cgroup_seqfile_show,
3500 static struct kernfs_ops cgroup_kf_ops = {
3501 .atomic_write_len = PAGE_SIZE,
3502 .open = cgroup_file_open,
3503 .release = cgroup_file_release,
3504 .write = cgroup_file_write,
3505 .seq_start = cgroup_seqfile_start,
3506 .seq_next = cgroup_seqfile_next,
3507 .seq_stop = cgroup_seqfile_stop,
3508 .seq_show = cgroup_seqfile_show,
3511 /* set uid and gid of cgroup dirs and files to that of the creator */
3512 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3514 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3515 .ia_uid = current_fsuid(),
3516 .ia_gid = current_fsgid(), };
3518 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3519 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3522 return kernfs_setattr(kn, &iattr);
3525 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
3528 char name[CGROUP_FILE_NAME_MAX];
3529 struct kernfs_node *kn;
3530 struct lock_class_key *key = NULL;
3533 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3534 key = &cft->lockdep_key;
3536 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3537 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
3542 ret = cgroup_kn_set_ugid(kn);
3548 if (cft->file_offset) {
3549 struct cgroup_file *cfile = (void *)css + cft->file_offset;
3551 spin_lock_irq(&cgroup_file_kn_lock);
3553 spin_unlock_irq(&cgroup_file_kn_lock);
3560 * cgroup_addrm_files - add or remove files to a cgroup directory
3561 * @css: the target css
3562 * @cgrp: the target cgroup (usually css->cgroup)
3563 * @cfts: array of cftypes to be added
3564 * @is_add: whether to add or remove
3566 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3567 * For removals, this function never fails.
3569 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
3570 struct cgroup *cgrp, struct cftype cfts[],
3573 struct cftype *cft, *cft_end = NULL;
3576 lockdep_assert_held(&cgroup_mutex);
3579 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
3580 /* does cft->flags tell us to skip this file on @cgrp? */
3581 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3583 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3585 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3587 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3591 ret = cgroup_add_file(css, cgrp, cft);
3593 pr_warn("%s: failed to add %s, err=%d\n",
3594 __func__, cft->name, ret);
3600 cgroup_rm_file(cgrp, cft);
3606 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3608 struct cgroup_subsys *ss = cfts[0].ss;
3609 struct cgroup *root = &ss->root->cgrp;
3610 struct cgroup_subsys_state *css;
3613 lockdep_assert_held(&cgroup_mutex);
3615 /* add/rm files for all cgroups created before */
3616 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3617 struct cgroup *cgrp = css->cgroup;
3619 if (!(css->flags & CSS_VISIBLE))
3622 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
3628 kernfs_activate(root->kn);
3632 static void cgroup_exit_cftypes(struct cftype *cfts)
3636 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3637 /* free copy for custom atomic_write_len, see init_cftypes() */
3638 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3643 /* revert flags set by cgroup core while adding @cfts */
3644 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3648 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3652 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3653 struct kernfs_ops *kf_ops;
3655 WARN_ON(cft->ss || cft->kf_ops);
3658 kf_ops = &cgroup_kf_ops;
3660 kf_ops = &cgroup_kf_single_ops;
3663 * Ugh... if @cft wants a custom max_write_len, we need to
3664 * make a copy of kf_ops to set its atomic_write_len.
3666 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3667 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3669 cgroup_exit_cftypes(cfts);
3672 kf_ops->atomic_write_len = cft->max_write_len;
3675 cft->kf_ops = kf_ops;
3682 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3684 lockdep_assert_held(&cgroup_mutex);
3686 if (!cfts || !cfts[0].ss)
3689 list_del(&cfts->node);
3690 cgroup_apply_cftypes(cfts, false);
3691 cgroup_exit_cftypes(cfts);
3696 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3697 * @cfts: zero-length name terminated array of cftypes
3699 * Unregister @cfts. Files described by @cfts are removed from all
3700 * existing cgroups and all future cgroups won't have them either. This
3701 * function can be called anytime whether @cfts' subsys is attached or not.
3703 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3706 int cgroup_rm_cftypes(struct cftype *cfts)
3710 mutex_lock(&cgroup_mutex);
3711 ret = cgroup_rm_cftypes_locked(cfts);
3712 mutex_unlock(&cgroup_mutex);
3717 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3718 * @ss: target cgroup subsystem
3719 * @cfts: zero-length name terminated array of cftypes
3721 * Register @cfts to @ss. Files described by @cfts are created for all
3722 * existing cgroups to which @ss is attached and all future cgroups will
3723 * have them too. This function can be called anytime whether @ss is
3726 * Returns 0 on successful registration, -errno on failure. Note that this
3727 * function currently returns 0 as long as @cfts registration is successful
3728 * even if some file creation attempts on existing cgroups fail.
3730 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3734 if (!cgroup_ssid_enabled(ss->id))
3737 if (!cfts || cfts[0].name[0] == '\0')
3740 ret = cgroup_init_cftypes(ss, cfts);
3744 mutex_lock(&cgroup_mutex);
3746 list_add_tail(&cfts->node, &ss->cfts);
3747 ret = cgroup_apply_cftypes(cfts, true);
3749 cgroup_rm_cftypes_locked(cfts);
3751 mutex_unlock(&cgroup_mutex);
3756 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3757 * @ss: target cgroup subsystem
3758 * @cfts: zero-length name terminated array of cftypes
3760 * Similar to cgroup_add_cftypes() but the added files are only used for
3761 * the default hierarchy.
3763 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3767 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3768 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3769 return cgroup_add_cftypes(ss, cfts);
3773 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3774 * @ss: target cgroup subsystem
3775 * @cfts: zero-length name terminated array of cftypes
3777 * Similar to cgroup_add_cftypes() but the added files are only used for
3778 * the legacy hierarchies.
3780 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3784 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3785 cft->flags |= __CFTYPE_NOT_ON_DFL;
3786 return cgroup_add_cftypes(ss, cfts);
3790 * cgroup_file_notify - generate a file modified event for a cgroup_file
3791 * @cfile: target cgroup_file
3793 * @cfile must have been obtained by setting cftype->file_offset.
3795 void cgroup_file_notify(struct cgroup_file *cfile)
3797 unsigned long flags;
3799 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
3801 kernfs_notify(cfile->kn);
3802 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
3806 * css_next_child - find the next child of a given css
3807 * @pos: the current position (%NULL to initiate traversal)
3808 * @parent: css whose children to walk
3810 * This function returns the next child of @parent and should be called
3811 * under either cgroup_mutex or RCU read lock. The only requirement is
3812 * that @parent and @pos are accessible. The next sibling is guaranteed to
3813 * be returned regardless of their states.
3815 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3816 * css which finished ->css_online() is guaranteed to be visible in the
3817 * future iterations and will stay visible until the last reference is put.
3818 * A css which hasn't finished ->css_online() or already finished
3819 * ->css_offline() may show up during traversal. It's each subsystem's
3820 * responsibility to synchronize against on/offlining.
3822 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3823 struct cgroup_subsys_state *parent)
3825 struct cgroup_subsys_state *next;
3827 cgroup_assert_mutex_or_rcu_locked();
3830 * @pos could already have been unlinked from the sibling list.
3831 * Once a cgroup is removed, its ->sibling.next is no longer
3832 * updated when its next sibling changes. CSS_RELEASED is set when
3833 * @pos is taken off list, at which time its next pointer is valid,
3834 * and, as releases are serialized, the one pointed to by the next
3835 * pointer is guaranteed to not have started release yet. This
3836 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3837 * critical section, the one pointed to by its next pointer is
3838 * guaranteed to not have finished its RCU grace period even if we
3839 * have dropped rcu_read_lock() inbetween iterations.
3841 * If @pos has CSS_RELEASED set, its next pointer can't be
3842 * dereferenced; however, as each css is given a monotonically
3843 * increasing unique serial number and always appended to the
3844 * sibling list, the next one can be found by walking the parent's
3845 * children until the first css with higher serial number than
3846 * @pos's. While this path can be slower, it happens iff iteration
3847 * races against release and the race window is very small.
3850 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3851 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3852 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3854 list_for_each_entry_rcu(next, &parent->children, sibling)
3855 if (next->serial_nr > pos->serial_nr)
3860 * @next, if not pointing to the head, can be dereferenced and is
3863 if (&next->sibling != &parent->children)
3869 * css_next_descendant_pre - find the next descendant for pre-order walk
3870 * @pos: the current position (%NULL to initiate traversal)
3871 * @root: css whose descendants to walk
3873 * To be used by css_for_each_descendant_pre(). Find the next descendant
3874 * to visit for pre-order traversal of @root's descendants. @root is
3875 * included in the iteration and the first node to be visited.
3877 * While this function requires cgroup_mutex or RCU read locking, it
3878 * doesn't require the whole traversal to be contained in a single critical
3879 * section. This function will return the correct next descendant as long
3880 * as both @pos and @root are accessible and @pos is a descendant of @root.
3882 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3883 * css which finished ->css_online() is guaranteed to be visible in the
3884 * future iterations and will stay visible until the last reference is put.
3885 * A css which hasn't finished ->css_online() or already finished
3886 * ->css_offline() may show up during traversal. It's each subsystem's
3887 * responsibility to synchronize against on/offlining.
3889 struct cgroup_subsys_state *
3890 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3891 struct cgroup_subsys_state *root)
3893 struct cgroup_subsys_state *next;
3895 cgroup_assert_mutex_or_rcu_locked();
3897 /* if first iteration, visit @root */
3901 /* visit the first child if exists */
3902 next = css_next_child(NULL, pos);
3906 /* no child, visit my or the closest ancestor's next sibling */
3907 while (pos != root) {
3908 next = css_next_child(pos, pos->parent);
3918 * css_rightmost_descendant - return the rightmost descendant of a css
3919 * @pos: css of interest
3921 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3922 * is returned. This can be used during pre-order traversal to skip
3925 * While this function requires cgroup_mutex or RCU read locking, it
3926 * doesn't require the whole traversal to be contained in a single critical
3927 * section. This function will return the correct rightmost descendant as
3928 * long as @pos is accessible.
3930 struct cgroup_subsys_state *
3931 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3933 struct cgroup_subsys_state *last, *tmp;
3935 cgroup_assert_mutex_or_rcu_locked();
3939 /* ->prev isn't RCU safe, walk ->next till the end */
3941 css_for_each_child(tmp, last)
3948 static struct cgroup_subsys_state *
3949 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3951 struct cgroup_subsys_state *last;
3955 pos = css_next_child(NULL, pos);
3962 * css_next_descendant_post - find the next descendant for post-order walk
3963 * @pos: the current position (%NULL to initiate traversal)
3964 * @root: css whose descendants to walk
3966 * To be used by css_for_each_descendant_post(). Find the next descendant
3967 * to visit for post-order traversal of @root's descendants. @root is
3968 * included in the iteration and the last node to be visited.
3970 * While this function requires cgroup_mutex or RCU read locking, it
3971 * doesn't require the whole traversal to be contained in a single critical
3972 * section. This function will return the correct next descendant as long
3973 * as both @pos and @cgroup are accessible and @pos is a descendant of
3976 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3977 * css which finished ->css_online() is guaranteed to be visible in the
3978 * future iterations and will stay visible until the last reference is put.
3979 * A css which hasn't finished ->css_online() or already finished
3980 * ->css_offline() may show up during traversal. It's each subsystem's
3981 * responsibility to synchronize against on/offlining.
3983 struct cgroup_subsys_state *
3984 css_next_descendant_post(struct cgroup_subsys_state *pos,
3985 struct cgroup_subsys_state *root)
3987 struct cgroup_subsys_state *next;
3989 cgroup_assert_mutex_or_rcu_locked();
3991 /* if first iteration, visit leftmost descendant which may be @root */
3993 return css_leftmost_descendant(root);
3995 /* if we visited @root, we're done */
3999 /* if there's an unvisited sibling, visit its leftmost descendant */
4000 next = css_next_child(pos, pos->parent);
4002 return css_leftmost_descendant(next);
4004 /* no sibling left, visit parent */
4009 * css_has_online_children - does a css have online children
4010 * @css: the target css
4012 * Returns %true if @css has any online children; otherwise, %false. This
4013 * function can be called from any context but the caller is responsible
4014 * for synchronizing against on/offlining as necessary.
4016 bool css_has_online_children(struct cgroup_subsys_state *css)
4018 struct cgroup_subsys_state *child;
4022 css_for_each_child(child, css) {
4023 if (child->flags & CSS_ONLINE) {
4032 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4034 struct list_head *l;
4035 struct cgrp_cset_link *link;
4036 struct css_set *cset;
4038 lockdep_assert_held(&css_set_lock);
4040 /* find the next threaded cset */
4041 if (it->tcset_pos) {
4042 l = it->tcset_pos->next;
4044 if (l != it->tcset_head) {
4046 return container_of(l, struct css_set,
4047 threaded_csets_node);
4050 it->tcset_pos = NULL;
4053 /* find the next cset */
4056 if (l == it->cset_head) {
4057 it->cset_pos = NULL;
4062 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4064 link = list_entry(l, struct cgrp_cset_link, cset_link);
4070 /* initialize threaded css_set walking */
4071 if (it->flags & CSS_TASK_ITER_THREADED) {
4073 put_css_set_locked(it->cur_dcset);
4074 it->cur_dcset = cset;
4077 it->tcset_head = &cset->threaded_csets;
4078 it->tcset_pos = &cset->threaded_csets;
4085 * css_task_iter_advance_css_set - advance a task itererator to the next css_set
4086 * @it: the iterator to advance
4088 * Advance @it to the next css_set to walk.
4090 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4092 struct css_set *cset;
4094 lockdep_assert_held(&css_set_lock);
4096 /* Advance to the next non-empty css_set */
4098 cset = css_task_iter_next_css_set(it);
4100 it->task_pos = NULL;
4103 } while (!css_set_populated(cset) && list_empty(&cset->dying_tasks));
4105 if (!list_empty(&cset->tasks)) {
4106 it->task_pos = cset->tasks.next;
4107 it->cur_tasks_head = &cset->tasks;
4108 } else if (!list_empty(&cset->mg_tasks)) {
4109 it->task_pos = cset->mg_tasks.next;
4110 it->cur_tasks_head = &cset->mg_tasks;
4112 it->task_pos = cset->dying_tasks.next;
4113 it->cur_tasks_head = &cset->dying_tasks;
4116 it->tasks_head = &cset->tasks;
4117 it->mg_tasks_head = &cset->mg_tasks;
4118 it->dying_tasks_head = &cset->dying_tasks;
4121 * We don't keep css_sets locked across iteration steps and thus
4122 * need to take steps to ensure that iteration can be resumed after
4123 * the lock is re-acquired. Iteration is performed at two levels -
4124 * css_sets and tasks in them.
4126 * Once created, a css_set never leaves its cgroup lists, so a
4127 * pinned css_set is guaranteed to stay put and we can resume
4128 * iteration afterwards.
4130 * Tasks may leave @cset across iteration steps. This is resolved
4131 * by registering each iterator with the css_set currently being
4132 * walked and making css_set_move_task() advance iterators whose
4133 * next task is leaving.
4136 list_del(&it->iters_node);
4137 put_css_set_locked(it->cur_cset);
4140 it->cur_cset = cset;
4141 list_add(&it->iters_node, &cset->task_iters);
4144 static void css_task_iter_skip(struct css_task_iter *it,
4145 struct task_struct *task)
4147 lockdep_assert_held(&css_set_lock);
4149 if (it->task_pos == &task->cg_list) {
4150 it->task_pos = it->task_pos->next;
4151 it->flags |= CSS_TASK_ITER_SKIPPED;
4155 static void css_task_iter_advance(struct css_task_iter *it)
4157 struct task_struct *task;
4159 lockdep_assert_held(&css_set_lock);
4163 * Advance iterator to find next entry. cset->tasks is
4164 * consumed first and then ->mg_tasks. After ->mg_tasks,
4165 * we move onto the next cset.
4167 if (it->flags & CSS_TASK_ITER_SKIPPED)
4168 it->flags &= ~CSS_TASK_ITER_SKIPPED;
4170 it->task_pos = it->task_pos->next;
4172 if (it->task_pos == it->tasks_head) {
4173 it->task_pos = it->mg_tasks_head->next;
4174 it->cur_tasks_head = it->mg_tasks_head;
4176 if (it->task_pos == it->mg_tasks_head) {
4177 it->task_pos = it->dying_tasks_head->next;
4178 it->cur_tasks_head = it->dying_tasks_head;
4180 if (it->task_pos == it->dying_tasks_head)
4181 css_task_iter_advance_css_set(it);
4183 /* called from start, proceed to the first cset */
4184 css_task_iter_advance_css_set(it);
4190 task = list_entry(it->task_pos, struct task_struct, cg_list);
4192 if (it->flags & CSS_TASK_ITER_PROCS) {
4193 /* if PROCS, skip over tasks which aren't group leaders */
4194 if (!thread_group_leader(task))
4197 /* and dying leaders w/o live member threads */
4198 if (it->cur_tasks_head == it->dying_tasks_head &&
4199 !atomic_read(&task->signal->live))
4202 /* skip all dying ones */
4203 if (it->cur_tasks_head == it->dying_tasks_head)
4209 * css_task_iter_start - initiate task iteration
4210 * @css: the css to walk tasks of
4211 * @flags: CSS_TASK_ITER_* flags
4212 * @it: the task iterator to use
4214 * Initiate iteration through the tasks of @css. The caller can call
4215 * css_task_iter_next() to walk through the tasks until the function
4216 * returns NULL. On completion of iteration, css_task_iter_end() must be
4219 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4220 struct css_task_iter *it)
4222 /* no one should try to iterate before mounting cgroups */
4223 WARN_ON_ONCE(!use_task_css_set_links);
4225 memset(it, 0, sizeof(*it));
4227 spin_lock_irq(&css_set_lock);
4233 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4235 it->cset_pos = &css->cgroup->cset_links;
4237 it->cset_head = it->cset_pos;
4239 css_task_iter_advance(it);
4241 spin_unlock_irq(&css_set_lock);
4245 * css_task_iter_next - return the next task for the iterator
4246 * @it: the task iterator being iterated
4248 * The "next" function for task iteration. @it should have been
4249 * initialized via css_task_iter_start(). Returns NULL when the iteration
4252 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4255 put_task_struct(it->cur_task);
4256 it->cur_task = NULL;
4259 spin_lock_irq(&css_set_lock);
4261 /* @it may be half-advanced by skips, finish advancing */
4262 if (it->flags & CSS_TASK_ITER_SKIPPED)
4263 css_task_iter_advance(it);
4266 it->cur_task = list_entry(it->task_pos, struct task_struct,
4268 get_task_struct(it->cur_task);
4269 css_task_iter_advance(it);
4272 spin_unlock_irq(&css_set_lock);
4274 return it->cur_task;
4278 * css_task_iter_end - finish task iteration
4279 * @it: the task iterator to finish
4281 * Finish task iteration started by css_task_iter_start().
4283 void css_task_iter_end(struct css_task_iter *it)
4286 spin_lock_irq(&css_set_lock);
4287 list_del(&it->iters_node);
4288 put_css_set_locked(it->cur_cset);
4289 spin_unlock_irq(&css_set_lock);
4293 put_css_set(it->cur_dcset);
4296 put_task_struct(it->cur_task);
4299 static void cgroup_procs_release(struct kernfs_open_file *of)
4301 struct cgroup_file_ctx *ctx = of->priv;
4303 if (ctx->procs.started)
4304 css_task_iter_end(&ctx->procs.iter);
4307 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
4309 struct kernfs_open_file *of = s->private;
4310 struct cgroup_file_ctx *ctx = of->priv;
4315 return css_task_iter_next(&ctx->procs.iter);
4318 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
4319 unsigned int iter_flags)
4321 struct kernfs_open_file *of = s->private;
4322 struct cgroup *cgrp = seq_css(s)->cgroup;
4323 struct cgroup_file_ctx *ctx = of->priv;
4324 struct css_task_iter *it = &ctx->procs.iter;
4327 * When a seq_file is seeked, it's always traversed sequentially
4328 * from position 0, so we can simply keep iterating on !0 *pos.
4330 if (!ctx->procs.started) {
4331 if (WARN_ON_ONCE((*pos)))
4332 return ERR_PTR(-EINVAL);
4333 css_task_iter_start(&cgrp->self, iter_flags, it);
4334 ctx->procs.started = true;
4335 } else if (!(*pos)) {
4336 css_task_iter_end(it);
4337 css_task_iter_start(&cgrp->self, iter_flags, it);
4339 return it->cur_task;
4341 return cgroup_procs_next(s, NULL, NULL);
4344 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
4346 struct cgroup *cgrp = seq_css(s)->cgroup;
4349 * All processes of a threaded subtree belong to the domain cgroup
4350 * of the subtree. Only threads can be distributed across the
4351 * subtree. Reject reads on cgroup.procs in the subtree proper.
4352 * They're always empty anyway.
4354 if (cgroup_is_threaded(cgrp))
4355 return ERR_PTR(-EOPNOTSUPP);
4357 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
4358 CSS_TASK_ITER_THREADED);
4361 static int cgroup_procs_show(struct seq_file *s, void *v)
4363 seq_printf(s, "%d\n", task_pid_vnr(v));
4367 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
4368 struct cgroup *dst_cgrp,
4369 struct super_block *sb,
4370 struct cgroup_namespace *ns)
4372 struct cgroup *com_cgrp = src_cgrp;
4373 struct inode *inode;
4376 lockdep_assert_held(&cgroup_mutex);
4378 /* find the common ancestor */
4379 while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
4380 com_cgrp = cgroup_parent(com_cgrp);
4382 /* %current should be authorized to migrate to the common ancestor */
4383 inode = kernfs_get_inode(sb, com_cgrp->procs_file.kn);
4387 ret = inode_permission(inode, MAY_WRITE);
4393 * If namespaces are delegation boundaries, %current must be able
4394 * to see both source and destination cgroups from its namespace.
4396 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
4397 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
4398 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
4404 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
4405 char *buf, size_t nbytes, loff_t off)
4407 struct cgroup_file_ctx *ctx = of->priv;
4408 struct cgroup *src_cgrp, *dst_cgrp;
4409 struct task_struct *task;
4410 const struct cred *saved_cred;
4413 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4417 task = cgroup_procs_write_start(buf, true);
4418 ret = PTR_ERR_OR_ZERO(task);
4422 /* find the source cgroup */
4423 spin_lock_irq(&css_set_lock);
4424 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4425 spin_unlock_irq(&css_set_lock);
4428 * Process and thread migrations follow same delegation rule. Check
4429 * permissions using the credentials from file open to protect against
4430 * inherited fd attacks.
4432 saved_cred = override_creds(of->file->f_cred);
4433 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4434 of->file->f_path.dentry->d_sb,
4436 revert_creds(saved_cred);
4440 ret = cgroup_attach_task(dst_cgrp, task, true);
4443 cgroup_procs_write_finish(task);
4445 cgroup_kn_unlock(of->kn);
4447 return ret ?: nbytes;
4450 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
4452 return __cgroup_procs_start(s, pos, 0);
4455 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
4456 char *buf, size_t nbytes, loff_t off)
4458 struct cgroup_file_ctx *ctx = of->priv;
4459 struct cgroup *src_cgrp, *dst_cgrp;
4460 struct task_struct *task;
4461 const struct cred *saved_cred;
4464 buf = strstrip(buf);
4466 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4470 task = cgroup_procs_write_start(buf, false);
4471 ret = PTR_ERR_OR_ZERO(task);
4475 /* find the source cgroup */
4476 spin_lock_irq(&css_set_lock);
4477 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4478 spin_unlock_irq(&css_set_lock);
4481 * Process and thread migrations follow same delegation rule. Check
4482 * permissions using the credentials from file open to protect against
4483 * inherited fd attacks.
4485 saved_cred = override_creds(of->file->f_cred);
4486 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4487 of->file->f_path.dentry->d_sb,
4489 revert_creds(saved_cred);
4493 /* and must be contained in the same domain */
4495 if (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp)
4498 ret = cgroup_attach_task(dst_cgrp, task, false);
4501 cgroup_procs_write_finish(task);
4503 cgroup_kn_unlock(of->kn);
4505 return ret ?: nbytes;
4508 /* cgroup core interface files for the default hierarchy */
4509 static struct cftype cgroup_base_files[] = {
4511 .name = "cgroup.type",
4512 .flags = CFTYPE_NOT_ON_ROOT,
4513 .seq_show = cgroup_type_show,
4514 .write = cgroup_type_write,
4517 .name = "cgroup.procs",
4518 .flags = CFTYPE_NS_DELEGATABLE,
4519 .file_offset = offsetof(struct cgroup, procs_file),
4520 .release = cgroup_procs_release,
4521 .seq_start = cgroup_procs_start,
4522 .seq_next = cgroup_procs_next,
4523 .seq_show = cgroup_procs_show,
4524 .write = cgroup_procs_write,
4527 .name = "cgroup.threads",
4528 .release = cgroup_procs_release,
4529 .seq_start = cgroup_threads_start,
4530 .seq_next = cgroup_procs_next,
4531 .seq_show = cgroup_procs_show,
4532 .write = cgroup_threads_write,
4535 .name = "cgroup.controllers",
4536 .seq_show = cgroup_controllers_show,
4539 .name = "cgroup.subtree_control",
4540 .flags = CFTYPE_NS_DELEGATABLE,
4541 .seq_show = cgroup_subtree_control_show,
4542 .write = cgroup_subtree_control_write,
4545 .name = "cgroup.events",
4546 .flags = CFTYPE_NOT_ON_ROOT,
4547 .file_offset = offsetof(struct cgroup, events_file),
4548 .seq_show = cgroup_events_show,
4551 .name = "cgroup.max.descendants",
4552 .seq_show = cgroup_max_descendants_show,
4553 .write = cgroup_max_descendants_write,
4556 .name = "cgroup.max.depth",
4557 .seq_show = cgroup_max_depth_show,
4558 .write = cgroup_max_depth_write,
4561 .name = "cgroup.stat",
4562 .seq_show = cgroup_stat_show,
4568 * css destruction is four-stage process.
4570 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4571 * Implemented in kill_css().
4573 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4574 * and thus css_tryget_online() is guaranteed to fail, the css can be
4575 * offlined by invoking offline_css(). After offlining, the base ref is
4576 * put. Implemented in css_killed_work_fn().
4578 * 3. When the percpu_ref reaches zero, the only possible remaining
4579 * accessors are inside RCU read sections. css_release() schedules the
4582 * 4. After the grace period, the css can be freed. Implemented in
4583 * css_free_work_fn().
4585 * It is actually hairier because both step 2 and 4 require process context
4586 * and thus involve punting to css->destroy_work adding two additional
4587 * steps to the already complex sequence.
4589 static void css_free_work_fn(struct work_struct *work)
4591 struct cgroup_subsys_state *css =
4592 container_of(work, struct cgroup_subsys_state, destroy_work);
4593 struct cgroup_subsys *ss = css->ss;
4594 struct cgroup *cgrp = css->cgroup;
4596 percpu_ref_exit(&css->refcnt);
4600 struct cgroup_subsys_state *parent = css->parent;
4604 cgroup_idr_remove(&ss->css_idr, id);
4610 /* cgroup free path */
4611 atomic_dec(&cgrp->root->nr_cgrps);
4612 cgroup1_pidlist_destroy_all(cgrp);
4613 cancel_work_sync(&cgrp->release_agent_work);
4615 if (cgroup_parent(cgrp)) {
4617 * We get a ref to the parent, and put the ref when
4618 * this cgroup is being freed, so it's guaranteed
4619 * that the parent won't be destroyed before its
4622 cgroup_put(cgroup_parent(cgrp));
4623 kernfs_put(cgrp->kn);
4627 * This is root cgroup's refcnt reaching zero,
4628 * which indicates that the root should be
4631 cgroup_destroy_root(cgrp->root);
4636 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4638 struct cgroup_subsys_state *css =
4639 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4641 INIT_WORK(&css->destroy_work, css_free_work_fn);
4642 queue_work(cgroup_destroy_wq, &css->destroy_work);
4645 static void css_release_work_fn(struct work_struct *work)
4647 struct cgroup_subsys_state *css =
4648 container_of(work, struct cgroup_subsys_state, destroy_work);
4649 struct cgroup_subsys *ss = css->ss;
4650 struct cgroup *cgrp = css->cgroup;
4652 mutex_lock(&cgroup_mutex);
4654 css->flags |= CSS_RELEASED;
4655 list_del_rcu(&css->sibling);
4658 /* css release path */
4659 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4660 if (ss->css_released)
4661 ss->css_released(css);
4663 struct cgroup *tcgrp;
4665 /* cgroup release path */
4666 trace_cgroup_release(cgrp);
4668 spin_lock_irq(&css_set_lock);
4669 for (tcgrp = cgroup_parent(cgrp); tcgrp;
4670 tcgrp = cgroup_parent(tcgrp))
4671 tcgrp->nr_dying_descendants--;
4672 spin_unlock_irq(&css_set_lock);
4674 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4678 * There are two control paths which try to determine
4679 * cgroup from dentry without going through kernfs -
4680 * cgroupstats_build() and css_tryget_online_from_dir().
4681 * Those are supported by RCU protecting clearing of
4682 * cgrp->kn->priv backpointer.
4685 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
4688 cgroup_bpf_put(cgrp);
4691 mutex_unlock(&cgroup_mutex);
4693 call_rcu(&css->rcu_head, css_free_rcu_fn);
4696 static void css_release(struct percpu_ref *ref)
4698 struct cgroup_subsys_state *css =
4699 container_of(ref, struct cgroup_subsys_state, refcnt);
4701 INIT_WORK(&css->destroy_work, css_release_work_fn);
4702 queue_work(cgroup_destroy_wq, &css->destroy_work);
4705 static void init_and_link_css(struct cgroup_subsys_state *css,
4706 struct cgroup_subsys *ss, struct cgroup *cgrp)
4708 lockdep_assert_held(&cgroup_mutex);
4710 cgroup_get_live(cgrp);
4712 memset(css, 0, sizeof(*css));
4716 INIT_LIST_HEAD(&css->sibling);
4717 INIT_LIST_HEAD(&css->children);
4718 css->serial_nr = css_serial_nr_next++;
4719 atomic_set(&css->online_cnt, 0);
4721 if (cgroup_parent(cgrp)) {
4722 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4723 css_get(css->parent);
4726 BUG_ON(cgroup_css(cgrp, ss));
4729 /* invoke ->css_online() on a new CSS and mark it online if successful */
4730 static int online_css(struct cgroup_subsys_state *css)
4732 struct cgroup_subsys *ss = css->ss;
4735 lockdep_assert_held(&cgroup_mutex);
4738 ret = ss->css_online(css);
4740 css->flags |= CSS_ONLINE;
4741 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4743 atomic_inc(&css->online_cnt);
4745 atomic_inc(&css->parent->online_cnt);
4750 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4751 static void offline_css(struct cgroup_subsys_state *css)
4753 struct cgroup_subsys *ss = css->ss;
4755 lockdep_assert_held(&cgroup_mutex);
4757 if (!(css->flags & CSS_ONLINE))
4760 if (ss->css_offline)
4761 ss->css_offline(css);
4763 css->flags &= ~CSS_ONLINE;
4764 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4766 wake_up_all(&css->cgroup->offline_waitq);
4770 * css_create - create a cgroup_subsys_state
4771 * @cgrp: the cgroup new css will be associated with
4772 * @ss: the subsys of new css
4774 * Create a new css associated with @cgrp - @ss pair. On success, the new
4775 * css is online and installed in @cgrp. This function doesn't create the
4776 * interface files. Returns 0 on success, -errno on failure.
4778 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
4779 struct cgroup_subsys *ss)
4781 struct cgroup *parent = cgroup_parent(cgrp);
4782 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4783 struct cgroup_subsys_state *css;
4786 lockdep_assert_held(&cgroup_mutex);
4788 css = ss->css_alloc(parent_css);
4790 css = ERR_PTR(-ENOMEM);
4794 init_and_link_css(css, ss, cgrp);
4796 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4800 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
4805 /* @css is ready to be brought online now, make it visible */
4806 list_add_tail_rcu(&css->sibling, &parent_css->children);
4807 cgroup_idr_replace(&ss->css_idr, css, css->id);
4809 err = online_css(css);
4813 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4814 cgroup_parent(parent)) {
4815 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4816 current->comm, current->pid, ss->name);
4817 if (!strcmp(ss->name, "memory"))
4818 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4819 ss->warned_broken_hierarchy = true;
4825 list_del_rcu(&css->sibling);
4827 call_rcu(&css->rcu_head, css_free_rcu_fn);
4828 return ERR_PTR(err);
4832 * The returned cgroup is fully initialized including its control mask, but
4833 * it isn't associated with its kernfs_node and doesn't have the control
4836 static struct cgroup *cgroup_create(struct cgroup *parent)
4838 struct cgroup_root *root = parent->root;
4839 struct cgroup *cgrp, *tcgrp;
4840 int level = parent->level + 1;
4843 /* allocate the cgroup and its ID, 0 is reserved for the root */
4844 cgrp = kzalloc(sizeof(*cgrp) +
4845 sizeof(cgrp->ancestor_ids[0]) * (level + 1), GFP_KERNEL);
4847 return ERR_PTR(-ENOMEM);
4849 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
4854 * Temporarily set the pointer to NULL, so idr_find() won't return
4855 * a half-baked cgroup.
4857 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
4860 goto out_cancel_ref;
4863 init_cgroup_housekeeping(cgrp);
4865 cgrp->self.parent = &parent->self;
4867 cgrp->level = level;
4869 spin_lock_irq(&css_set_lock);
4870 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
4871 cgrp->ancestor_ids[tcgrp->level] = tcgrp->id;
4874 tcgrp->nr_descendants++;
4876 spin_unlock_irq(&css_set_lock);
4878 if (notify_on_release(parent))
4879 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4881 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4882 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4884 cgrp->self.serial_nr = css_serial_nr_next++;
4886 /* allocation complete, commit to creation */
4887 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4888 atomic_inc(&root->nr_cgrps);
4889 cgroup_get_live(parent);
4892 * @cgrp is now fully operational. If something fails after this
4893 * point, it'll be released via the normal destruction path.
4895 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4898 * On the default hierarchy, a child doesn't automatically inherit
4899 * subtree_control from the parent. Each is configured manually.
4901 if (!cgroup_on_dfl(cgrp))
4902 cgrp->subtree_control = cgroup_control(cgrp);
4905 cgroup_bpf_inherit(cgrp, parent);
4907 cgroup_propagate_control(cgrp);
4912 percpu_ref_exit(&cgrp->self.refcnt);
4915 return ERR_PTR(ret);
4918 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
4920 struct cgroup *cgroup;
4924 lockdep_assert_held(&cgroup_mutex);
4926 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
4927 if (cgroup->nr_descendants >= cgroup->max_descendants)
4930 if (level > cgroup->max_depth)
4941 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
4943 struct cgroup *parent, *cgrp;
4944 struct kernfs_node *kn;
4947 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
4948 if (strchr(name, '\n'))
4951 parent = cgroup_kn_lock_live(parent_kn, false);
4955 if (!cgroup_check_hierarchy_limits(parent)) {
4960 cgrp = cgroup_create(parent);
4962 ret = PTR_ERR(cgrp);
4966 /* create the directory */
4967 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4975 * This extra ref will be put in cgroup_free_fn() and guarantees
4976 * that @cgrp->kn is always accessible.
4980 ret = cgroup_kn_set_ugid(kn);
4984 ret = css_populate_dir(&cgrp->self);
4988 ret = cgroup_apply_control_enable(cgrp);
4992 trace_cgroup_mkdir(cgrp);
4994 /* let's create and online css's */
4995 kernfs_activate(kn);
5001 cgroup_destroy_locked(cgrp);
5003 cgroup_kn_unlock(parent_kn);
5008 * This is called when the refcnt of a css is confirmed to be killed.
5009 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
5010 * initate destruction and put the css ref from kill_css().
5012 static void css_killed_work_fn(struct work_struct *work)
5014 struct cgroup_subsys_state *css =
5015 container_of(work, struct cgroup_subsys_state, destroy_work);
5017 mutex_lock(&cgroup_mutex);
5022 /* @css can't go away while we're holding cgroup_mutex */
5024 } while (css && atomic_dec_and_test(&css->online_cnt));
5026 mutex_unlock(&cgroup_mutex);
5029 /* css kill confirmation processing requires process context, bounce */
5030 static void css_killed_ref_fn(struct percpu_ref *ref)
5032 struct cgroup_subsys_state *css =
5033 container_of(ref, struct cgroup_subsys_state, refcnt);
5035 if (atomic_dec_and_test(&css->online_cnt)) {
5036 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5037 queue_work(cgroup_destroy_wq, &css->destroy_work);
5042 * kill_css - destroy a css
5043 * @css: css to destroy
5045 * This function initiates destruction of @css by removing cgroup interface
5046 * files and putting its base reference. ->css_offline() will be invoked
5047 * asynchronously once css_tryget_online() is guaranteed to fail and when
5048 * the reference count reaches zero, @css will be released.
5050 static void kill_css(struct cgroup_subsys_state *css)
5052 lockdep_assert_held(&cgroup_mutex);
5054 if (css->flags & CSS_DYING)
5057 css->flags |= CSS_DYING;
5060 * This must happen before css is disassociated with its cgroup.
5061 * See seq_css() for details.
5066 * Killing would put the base ref, but we need to keep it alive
5067 * until after ->css_offline().
5072 * cgroup core guarantees that, by the time ->css_offline() is
5073 * invoked, no new css reference will be given out via
5074 * css_tryget_online(). We can't simply call percpu_ref_kill() and
5075 * proceed to offlining css's because percpu_ref_kill() doesn't
5076 * guarantee that the ref is seen as killed on all CPUs on return.
5078 * Use percpu_ref_kill_and_confirm() to get notifications as each
5079 * css is confirmed to be seen as killed on all CPUs.
5081 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5085 * cgroup_destroy_locked - the first stage of cgroup destruction
5086 * @cgrp: cgroup to be destroyed
5088 * css's make use of percpu refcnts whose killing latency shouldn't be
5089 * exposed to userland and are RCU protected. Also, cgroup core needs to
5090 * guarantee that css_tryget_online() won't succeed by the time
5091 * ->css_offline() is invoked. To satisfy all the requirements,
5092 * destruction is implemented in the following two steps.
5094 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
5095 * userland visible parts and start killing the percpu refcnts of
5096 * css's. Set up so that the next stage will be kicked off once all
5097 * the percpu refcnts are confirmed to be killed.
5099 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5100 * rest of destruction. Once all cgroup references are gone, the
5101 * cgroup is RCU-freed.
5103 * This function implements s1. After this step, @cgrp is gone as far as
5104 * the userland is concerned and a new cgroup with the same name may be
5105 * created. As cgroup doesn't care about the names internally, this
5106 * doesn't cause any problem.
5108 static int cgroup_destroy_locked(struct cgroup *cgrp)
5109 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5111 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5112 struct cgroup_subsys_state *css;
5113 struct cgrp_cset_link *link;
5116 lockdep_assert_held(&cgroup_mutex);
5119 * Only migration can raise populated from zero and we're already
5120 * holding cgroup_mutex.
5122 if (cgroup_is_populated(cgrp))
5126 * Make sure there's no live children. We can't test emptiness of
5127 * ->self.children as dead children linger on it while being
5128 * drained; otherwise, "rmdir parent/child parent" may fail.
5130 if (css_has_online_children(&cgrp->self))
5134 * Mark @cgrp and the associated csets dead. The former prevents
5135 * further task migration and child creation by disabling
5136 * cgroup_lock_live_group(). The latter makes the csets ignored by
5137 * the migration path.
5139 cgrp->self.flags &= ~CSS_ONLINE;
5141 spin_lock_irq(&css_set_lock);
5142 list_for_each_entry(link, &cgrp->cset_links, cset_link)
5143 link->cset->dead = true;
5144 spin_unlock_irq(&css_set_lock);
5146 /* initiate massacre of all css's */
5147 for_each_css(css, ssid, cgrp)
5151 * Remove @cgrp directory along with the base files. @cgrp has an
5152 * extra ref on its kn.
5154 kernfs_remove(cgrp->kn);
5156 if (parent && cgroup_is_threaded(cgrp))
5157 parent->nr_threaded_children--;
5159 spin_lock_irq(&css_set_lock);
5160 for (tcgrp = cgroup_parent(cgrp); tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5161 tcgrp->nr_descendants--;
5162 tcgrp->nr_dying_descendants++;
5164 spin_unlock_irq(&css_set_lock);
5166 cgroup1_check_for_release(parent);
5168 /* put the base reference */
5169 percpu_ref_kill(&cgrp->self.refcnt);
5174 int cgroup_rmdir(struct kernfs_node *kn)
5176 struct cgroup *cgrp;
5179 cgrp = cgroup_kn_lock_live(kn, false);
5183 ret = cgroup_destroy_locked(cgrp);
5186 trace_cgroup_rmdir(cgrp);
5188 cgroup_kn_unlock(kn);
5192 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5193 .show_options = cgroup_show_options,
5194 .remount_fs = cgroup_remount,
5195 .mkdir = cgroup_mkdir,
5196 .rmdir = cgroup_rmdir,
5197 .show_path = cgroup_show_path,
5200 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5202 struct cgroup_subsys_state *css;
5204 pr_debug("Initializing cgroup subsys %s\n", ss->name);
5206 mutex_lock(&cgroup_mutex);
5208 idr_init(&ss->css_idr);
5209 INIT_LIST_HEAD(&ss->cfts);
5211 /* Create the root cgroup state for this subsystem */
5212 ss->root = &cgrp_dfl_root;
5213 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5214 /* We don't handle early failures gracefully */
5215 BUG_ON(IS_ERR(css));
5216 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5219 * Root csses are never destroyed and we can't initialize
5220 * percpu_ref during early init. Disable refcnting.
5222 css->flags |= CSS_NO_REF;
5225 /* allocation can't be done safely during early init */
5228 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5229 BUG_ON(css->id < 0);
5232 /* Update the init_css_set to contain a subsys
5233 * pointer to this state - since the subsystem is
5234 * newly registered, all tasks and hence the
5235 * init_css_set is in the subsystem's root cgroup. */
5236 init_css_set.subsys[ss->id] = css;
5238 have_fork_callback |= (bool)ss->fork << ss->id;
5239 have_exit_callback |= (bool)ss->exit << ss->id;
5240 have_release_callback |= (bool)ss->release << ss->id;
5241 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5243 /* At system boot, before all subsystems have been
5244 * registered, no tasks have been forked, so we don't
5245 * need to invoke fork callbacks here. */
5246 BUG_ON(!list_empty(&init_task.tasks));
5248 BUG_ON(online_css(css));
5250 mutex_unlock(&cgroup_mutex);
5254 * cgroup_init_early - cgroup initialization at system boot
5256 * Initialize cgroups at system boot, and initialize any
5257 * subsystems that request early init.
5259 int __init cgroup_init_early(void)
5261 static struct cgroup_sb_opts __initdata opts;
5262 struct cgroup_subsys *ss;
5265 init_cgroup_root(&cgrp_dfl_root, &opts);
5266 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5268 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5270 for_each_subsys(ss, i) {
5271 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5272 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
5273 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5275 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5276 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5279 ss->name = cgroup_subsys_name[i];
5280 if (!ss->legacy_name)
5281 ss->legacy_name = cgroup_subsys_name[i];
5284 cgroup_init_subsys(ss, true);
5290 * cgroup_init - cgroup initialization
5292 * Register cgroup filesystem and /proc file, and initialize
5293 * any subsystems that didn't request early init.
5295 int __init cgroup_init(void)
5297 struct cgroup_subsys *ss;
5300 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
5301 BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
5302 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
5303 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
5306 * The latency of the synchronize_sched() is too high for cgroups,
5307 * avoid it at the cost of forcing all readers into the slow path.
5309 rcu_sync_enter_start(&cgroup_threadgroup_rwsem.rss);
5311 get_user_ns(init_cgroup_ns.user_ns);
5313 mutex_lock(&cgroup_mutex);
5316 * Add init_css_set to the hash table so that dfl_root can link to
5319 hash_add(css_set_table, &init_css_set.hlist,
5320 css_set_hash(init_css_set.subsys));
5322 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0, 0));
5324 mutex_unlock(&cgroup_mutex);
5326 for_each_subsys(ss, ssid) {
5327 if (ss->early_init) {
5328 struct cgroup_subsys_state *css =
5329 init_css_set.subsys[ss->id];
5331 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5333 BUG_ON(css->id < 0);
5335 cgroup_init_subsys(ss, false);
5338 list_add_tail(&init_css_set.e_cset_node[ssid],
5339 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5342 * Setting dfl_root subsys_mask needs to consider the
5343 * disabled flag and cftype registration needs kmalloc,
5344 * both of which aren't available during early_init.
5346 if (!cgroup_ssid_enabled(ssid))
5349 if (cgroup1_ssid_disabled(ssid))
5350 printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
5353 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5355 /* implicit controllers must be threaded too */
5356 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
5358 if (ss->implicit_on_dfl)
5359 cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
5360 else if (!ss->dfl_cftypes)
5361 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
5364 cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
5366 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5367 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5369 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5370 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5374 ss->bind(init_css_set.subsys[ssid]);
5376 mutex_lock(&cgroup_mutex);
5377 css_populate_dir(init_css_set.subsys[ssid]);
5378 mutex_unlock(&cgroup_mutex);
5381 /* init_css_set.subsys[] has been updated, re-hash */
5382 hash_del(&init_css_set.hlist);
5383 hash_add(css_set_table, &init_css_set.hlist,
5384 css_set_hash(init_css_set.subsys));
5386 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
5387 WARN_ON(register_filesystem(&cgroup_fs_type));
5388 WARN_ON(register_filesystem(&cgroup2_fs_type));
5389 WARN_ON(!proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations));
5394 static int __init cgroup_wq_init(void)
5397 * There isn't much point in executing destruction path in
5398 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5399 * Use 1 for @max_active.
5401 * We would prefer to do this in cgroup_init() above, but that
5402 * is called before init_workqueues(): so leave this until after.
5404 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5405 BUG_ON(!cgroup_destroy_wq);
5408 core_initcall(cgroup_wq_init);
5410 void cgroup_path_from_kernfs_id(const union kernfs_node_id *id,
5411 char *buf, size_t buflen)
5413 struct kernfs_node *kn;
5415 kn = kernfs_get_node_by_id(cgrp_dfl_root.kf_root, id);
5418 kernfs_path(kn, buf, buflen);
5423 * proc_cgroup_show()
5424 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5425 * - Used for /proc/<pid>/cgroup.
5427 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5428 struct pid *pid, struct task_struct *tsk)
5432 struct cgroup_root *root;
5435 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5439 mutex_lock(&cgroup_mutex);
5440 spin_lock_irq(&css_set_lock);
5442 for_each_root(root) {
5443 struct cgroup_subsys *ss;
5444 struct cgroup *cgrp;
5445 int ssid, count = 0;
5447 if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
5450 seq_printf(m, "%d:", root->hierarchy_id);
5451 if (root != &cgrp_dfl_root)
5452 for_each_subsys(ss, ssid)
5453 if (root->subsys_mask & (1 << ssid))
5454 seq_printf(m, "%s%s", count++ ? "," : "",
5456 if (strlen(root->name))
5457 seq_printf(m, "%sname=%s", count ? "," : "",
5461 cgrp = task_cgroup_from_root(tsk, root);
5464 * On traditional hierarchies, all zombie tasks show up as
5465 * belonging to the root cgroup. On the default hierarchy,
5466 * while a zombie doesn't show up in "cgroup.procs" and
5467 * thus can't be migrated, its /proc/PID/cgroup keeps
5468 * reporting the cgroup it belonged to before exiting. If
5469 * the cgroup is removed before the zombie is reaped,
5470 * " (deleted)" is appended to the cgroup path.
5472 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
5473 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
5474 current->nsproxy->cgroup_ns);
5475 if (retval >= PATH_MAX)
5476 retval = -ENAMETOOLONG;
5485 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
5486 seq_puts(m, " (deleted)\n");
5493 spin_unlock_irq(&css_set_lock);
5494 mutex_unlock(&cgroup_mutex);
5501 * cgroup_fork - initialize cgroup related fields during copy_process()
5502 * @child: pointer to task_struct of forking parent process.
5504 * A task is associated with the init_css_set until cgroup_post_fork()
5505 * attaches it to the parent's css_set. Empty cg_list indicates that
5506 * @child isn't holding reference to its css_set.
5508 void cgroup_fork(struct task_struct *child)
5510 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5511 INIT_LIST_HEAD(&child->cg_list);
5515 * cgroup_can_fork - called on a new task before the process is exposed
5516 * @child: the task in question.
5518 * This calls the subsystem can_fork() callbacks. If the can_fork() callback
5519 * returns an error, the fork aborts with that error code. This allows for
5520 * a cgroup subsystem to conditionally allow or deny new forks.
5522 int cgroup_can_fork(struct task_struct *child)
5524 struct cgroup_subsys *ss;
5527 do_each_subsys_mask(ss, i, have_canfork_callback) {
5528 ret = ss->can_fork(child);
5531 } while_each_subsys_mask();
5536 for_each_subsys(ss, j) {
5539 if (ss->cancel_fork)
5540 ss->cancel_fork(child);
5547 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
5548 * @child: the task in question
5550 * This calls the cancel_fork() callbacks if a fork failed *after*
5551 * cgroup_can_fork() succeded.
5553 void cgroup_cancel_fork(struct task_struct *child)
5555 struct cgroup_subsys *ss;
5558 for_each_subsys(ss, i)
5559 if (ss->cancel_fork)
5560 ss->cancel_fork(child);
5564 * cgroup_post_fork - called on a new task after adding it to the task list
5565 * @child: the task in question
5567 * Adds the task to the list running through its css_set if necessary and
5568 * call the subsystem fork() callbacks. Has to be after the task is
5569 * visible on the task list in case we race with the first call to
5570 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5573 void cgroup_post_fork(struct task_struct *child)
5575 struct cgroup_subsys *ss;
5579 * This may race against cgroup_enable_task_cg_lists(). As that
5580 * function sets use_task_css_set_links before grabbing
5581 * tasklist_lock and we just went through tasklist_lock to add
5582 * @child, it's guaranteed that either we see the set
5583 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5584 * @child during its iteration.
5586 * If we won the race, @child is associated with %current's
5587 * css_set. Grabbing css_set_lock guarantees both that the
5588 * association is stable, and, on completion of the parent's
5589 * migration, @child is visible in the source of migration or
5590 * already in the destination cgroup. This guarantee is necessary
5591 * when implementing operations which need to migrate all tasks of
5592 * a cgroup to another.
5594 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5595 * will remain in init_css_set. This is safe because all tasks are
5596 * in the init_css_set before cg_links is enabled and there's no
5597 * operation which transfers all tasks out of init_css_set.
5599 if (use_task_css_set_links) {
5600 struct css_set *cset;
5602 spin_lock_irq(&css_set_lock);
5603 cset = task_css_set(current);
5604 if (list_empty(&child->cg_list)) {
5607 css_set_move_task(child, NULL, cset, false);
5609 spin_unlock_irq(&css_set_lock);
5613 * Call ss->fork(). This must happen after @child is linked on
5614 * css_set; otherwise, @child might change state between ->fork()
5615 * and addition to css_set.
5617 do_each_subsys_mask(ss, i, have_fork_callback) {
5619 } while_each_subsys_mask();
5623 * cgroup_exit - detach cgroup from exiting task
5624 * @tsk: pointer to task_struct of exiting process
5626 * Description: Detach cgroup from @tsk and release it.
5628 * Note that cgroups marked notify_on_release force every task in
5629 * them to take the global cgroup_mutex mutex when exiting.
5630 * This could impact scaling on very large systems. Be reluctant to
5631 * use notify_on_release cgroups where very high task exit scaling
5632 * is required on large systems.
5634 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5635 * call cgroup_exit() while the task is still competent to handle
5636 * notify_on_release(), then leave the task attached to the root cgroup in
5637 * each hierarchy for the remainder of its exit. No need to bother with
5638 * init_css_set refcnting. init_css_set never goes away and we can't race
5639 * with migration path - PF_EXITING is visible to migration path.
5641 void cgroup_exit(struct task_struct *tsk)
5643 struct cgroup_subsys *ss;
5644 struct css_set *cset;
5648 * Unlink from @tsk from its css_set. As migration path can't race
5649 * with us, we can check css_set and cg_list without synchronization.
5651 cset = task_css_set(tsk);
5653 if (!list_empty(&tsk->cg_list)) {
5654 spin_lock_irq(&css_set_lock);
5655 css_set_move_task(tsk, cset, NULL, false);
5656 list_add_tail(&tsk->cg_list, &cset->dying_tasks);
5658 spin_unlock_irq(&css_set_lock);
5663 /* see cgroup_post_fork() for details */
5664 do_each_subsys_mask(ss, i, have_exit_callback) {
5666 } while_each_subsys_mask();
5669 void cgroup_release(struct task_struct *task)
5671 struct cgroup_subsys *ss;
5674 do_each_subsys_mask(ss, ssid, have_release_callback) {
5676 } while_each_subsys_mask();
5678 if (use_task_css_set_links) {
5679 spin_lock_irq(&css_set_lock);
5680 css_set_skip_task_iters(task_css_set(task), task);
5681 list_del_init(&task->cg_list);
5682 spin_unlock_irq(&css_set_lock);
5686 void cgroup_free(struct task_struct *task)
5688 struct css_set *cset = task_css_set(task);
5692 static int __init cgroup_disable(char *str)
5694 struct cgroup_subsys *ss;
5698 while ((token = strsep(&str, ",")) != NULL) {
5702 for_each_subsys(ss, i) {
5703 if (strcmp(token, ss->name) &&
5704 strcmp(token, ss->legacy_name))
5707 static_branch_disable(cgroup_subsys_enabled_key[i]);
5708 pr_info("Disabling %s control group subsystem\n",
5714 __setup("cgroup_disable=", cgroup_disable);
5717 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5718 * @dentry: directory dentry of interest
5719 * @ss: subsystem of interest
5721 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5722 * to get the corresponding css and return it. If such css doesn't exist
5723 * or can't be pinned, an ERR_PTR value is returned.
5725 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5726 struct cgroup_subsys *ss)
5728 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5729 struct file_system_type *s_type = dentry->d_sb->s_type;
5730 struct cgroup_subsys_state *css = NULL;
5731 struct cgroup *cgrp;
5733 /* is @dentry a cgroup dir? */
5734 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
5735 !kn || kernfs_type(kn) != KERNFS_DIR)
5736 return ERR_PTR(-EBADF);
5741 * This path doesn't originate from kernfs and @kn could already
5742 * have been or be removed at any point. @kn->priv is RCU
5743 * protected for this access. See css_release_work_fn() for details.
5745 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
5747 css = cgroup_css(cgrp, ss);
5749 if (!css || !css_tryget_online(css))
5750 css = ERR_PTR(-ENOENT);
5757 * css_from_id - lookup css by id
5758 * @id: the cgroup id
5759 * @ss: cgroup subsys to be looked into
5761 * Returns the css if there's valid one with @id, otherwise returns NULL.
5762 * Should be called under rcu_read_lock().
5764 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5766 WARN_ON_ONCE(!rcu_read_lock_held());
5767 return idr_find(&ss->css_idr, id);
5771 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
5772 * @path: path on the default hierarchy
5774 * Find the cgroup at @path on the default hierarchy, increment its
5775 * reference count and return it. Returns pointer to the found cgroup on
5776 * success, ERR_PTR(-ENOENT) if @path doens't exist and ERR_PTR(-ENOTDIR)
5777 * if @path points to a non-directory.
5779 struct cgroup *cgroup_get_from_path(const char *path)
5781 struct kernfs_node *kn;
5782 struct cgroup *cgrp;
5784 mutex_lock(&cgroup_mutex);
5786 kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
5788 if (kernfs_type(kn) == KERNFS_DIR) {
5790 cgroup_get_live(cgrp);
5792 cgrp = ERR_PTR(-ENOTDIR);
5796 cgrp = ERR_PTR(-ENOENT);
5799 mutex_unlock(&cgroup_mutex);
5802 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
5805 * cgroup_get_from_fd - get a cgroup pointer from a fd
5806 * @fd: fd obtained by open(cgroup2_dir)
5808 * Find the cgroup from a fd which should be obtained
5809 * by opening a cgroup directory. Returns a pointer to the
5810 * cgroup on success. ERR_PTR is returned if the cgroup
5813 struct cgroup *cgroup_get_from_fd(int fd)
5815 struct cgroup_subsys_state *css;
5816 struct cgroup *cgrp;
5821 return ERR_PTR(-EBADF);
5823 css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
5826 return ERR_CAST(css);
5829 if (!cgroup_on_dfl(cgrp)) {
5831 return ERR_PTR(-EBADF);
5836 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
5839 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
5840 * definition in cgroup-defs.h.
5842 #ifdef CONFIG_SOCK_CGROUP_DATA
5844 #if defined(CONFIG_CGROUP_NET_PRIO) || defined(CONFIG_CGROUP_NET_CLASSID)
5846 DEFINE_SPINLOCK(cgroup_sk_update_lock);
5847 static bool cgroup_sk_alloc_disabled __read_mostly;
5849 void cgroup_sk_alloc_disable(void)
5851 if (cgroup_sk_alloc_disabled)
5853 pr_info("cgroup: disabling cgroup2 socket matching due to net_prio or net_cls activation\n");
5854 cgroup_sk_alloc_disabled = true;
5859 #define cgroup_sk_alloc_disabled false
5863 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
5865 if (cgroup_sk_alloc_disabled) {
5866 skcd->no_refcnt = 1;
5870 /* Don't associate the sock with unrelated interrupted task's cgroup. */
5877 struct css_set *cset;
5879 cset = task_css_set(current);
5880 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
5881 skcd->val = (unsigned long)cset->dfl_cgrp;
5890 void cgroup_sk_clone(struct sock_cgroup_data *skcd)
5892 /* Socket clone path */
5894 if (skcd->no_refcnt)
5897 * We might be cloning a socket which is left in an empty
5898 * cgroup and the cgroup might have already been rmdir'd.
5899 * Don't use cgroup_get_live().
5901 cgroup_get(sock_cgroup_ptr(skcd));
5905 void cgroup_sk_free(struct sock_cgroup_data *skcd)
5907 if (skcd->no_refcnt)
5910 cgroup_put(sock_cgroup_ptr(skcd));
5913 #endif /* CONFIG_SOCK_CGROUP_DATA */
5915 #ifdef CONFIG_CGROUP_BPF
5916 int cgroup_bpf_update(struct cgroup *cgrp, struct bpf_prog *prog,
5917 enum bpf_attach_type type, bool overridable)
5919 struct cgroup *parent = cgroup_parent(cgrp);
5922 mutex_lock(&cgroup_mutex);
5923 ret = __cgroup_bpf_update(cgrp, parent, prog, type, overridable);
5924 mutex_unlock(&cgroup_mutex);
5927 #endif /* CONFIG_CGROUP_BPF */