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_free_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_advance(struct css_task_iter *it);
208 static int cgroup_destroy_locked(struct cgroup *cgrp);
209 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
210 struct cgroup_subsys *ss);
211 static void css_release(struct percpu_ref *ref);
212 static void kill_css(struct cgroup_subsys_state *css);
213 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
214 struct cgroup *cgrp, struct cftype cfts[],
218 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
219 * @ssid: subsys ID of interest
221 * cgroup_subsys_enabled() can only be used with literal subsys names which
222 * is fine for individual subsystems but unsuitable for cgroup core. This
223 * is slower static_key_enabled() based test indexed by @ssid.
225 bool cgroup_ssid_enabled(int ssid)
227 if (CGROUP_SUBSYS_COUNT == 0)
230 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
234 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
235 * @cgrp: the cgroup of interest
237 * The default hierarchy is the v2 interface of cgroup and this function
238 * can be used to test whether a cgroup is on the default hierarchy for
239 * cases where a subsystem should behave differnetly depending on the
242 * The set of behaviors which change on the default hierarchy are still
243 * being determined and the mount option is prefixed with __DEVEL__.
245 * List of changed behaviors:
247 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
248 * and "name" are disallowed.
250 * - When mounting an existing superblock, mount options should match.
252 * - Remount is disallowed.
254 * - rename(2) is disallowed.
256 * - "tasks" is removed. Everything should be at process granularity. Use
257 * "cgroup.procs" instead.
259 * - "cgroup.procs" is not sorted. pids will be unique unless they got
260 * recycled inbetween reads.
262 * - "release_agent" and "notify_on_release" are removed. Replacement
263 * notification mechanism will be implemented.
265 * - "cgroup.clone_children" is removed.
267 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
268 * and its descendants contain no task; otherwise, 1. The file also
269 * generates kernfs notification which can be monitored through poll and
270 * [di]notify when the value of the file changes.
272 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
273 * take masks of ancestors with non-empty cpus/mems, instead of being
274 * moved to an ancestor.
276 * - cpuset: a task can be moved into an empty cpuset, and again it takes
277 * masks of ancestors.
279 * - memcg: use_hierarchy is on by default and the cgroup file for the flag
282 * - blkcg: blk-throttle becomes properly hierarchical.
284 * - debug: disallowed on the default hierarchy.
286 bool cgroup_on_dfl(const struct cgroup *cgrp)
288 return cgrp->root == &cgrp_dfl_root;
291 /* IDR wrappers which synchronize using cgroup_idr_lock */
292 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
297 idr_preload(gfp_mask);
298 spin_lock_bh(&cgroup_idr_lock);
299 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
300 spin_unlock_bh(&cgroup_idr_lock);
305 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
309 spin_lock_bh(&cgroup_idr_lock);
310 ret = idr_replace(idr, ptr, id);
311 spin_unlock_bh(&cgroup_idr_lock);
315 static void cgroup_idr_remove(struct idr *idr, int id)
317 spin_lock_bh(&cgroup_idr_lock);
319 spin_unlock_bh(&cgroup_idr_lock);
322 static bool cgroup_has_tasks(struct cgroup *cgrp)
324 return cgrp->nr_populated_csets;
327 bool cgroup_is_threaded(struct cgroup *cgrp)
329 return cgrp->dom_cgrp != cgrp;
332 /* can @cgrp host both domain and threaded children? */
333 static bool cgroup_is_mixable(struct cgroup *cgrp)
336 * Root isn't under domain level resource control exempting it from
337 * the no-internal-process constraint, so it can serve as a thread
338 * root and a parent of resource domains at the same time.
340 return !cgroup_parent(cgrp);
343 /* can @cgrp become a thread root? should always be true for a thread root */
344 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
346 /* mixables don't care */
347 if (cgroup_is_mixable(cgrp))
350 /* domain roots can't be nested under threaded */
351 if (cgroup_is_threaded(cgrp))
354 /* can only have either domain or threaded children */
355 if (cgrp->nr_populated_domain_children)
358 /* and no domain controllers can be enabled */
359 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
365 /* is @cgrp root of a threaded subtree? */
366 bool cgroup_is_thread_root(struct cgroup *cgrp)
368 /* thread root should be a domain */
369 if (cgroup_is_threaded(cgrp))
372 /* a domain w/ threaded children is a thread root */
373 if (cgrp->nr_threaded_children)
377 * A domain which has tasks and explicit threaded controllers
378 * enabled is a thread root.
380 if (cgroup_has_tasks(cgrp) &&
381 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
387 /* a domain which isn't connected to the root w/o brekage can't be used */
388 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
390 /* the cgroup itself can be a thread root */
391 if (cgroup_is_threaded(cgrp))
394 /* but the ancestors can't be unless mixable */
395 while ((cgrp = cgroup_parent(cgrp))) {
396 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
398 if (cgroup_is_threaded(cgrp))
405 /* subsystems visibly enabled on a cgroup */
406 static u16 cgroup_control(struct cgroup *cgrp)
408 struct cgroup *parent = cgroup_parent(cgrp);
409 u16 root_ss_mask = cgrp->root->subsys_mask;
412 u16 ss_mask = parent->subtree_control;
414 /* threaded cgroups can only have threaded controllers */
415 if (cgroup_is_threaded(cgrp))
416 ss_mask &= cgrp_dfl_threaded_ss_mask;
420 if (cgroup_on_dfl(cgrp))
421 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
422 cgrp_dfl_implicit_ss_mask);
426 /* subsystems enabled on a cgroup */
427 static u16 cgroup_ss_mask(struct cgroup *cgrp)
429 struct cgroup *parent = cgroup_parent(cgrp);
432 u16 ss_mask = parent->subtree_ss_mask;
434 /* threaded cgroups can only have threaded controllers */
435 if (cgroup_is_threaded(cgrp))
436 ss_mask &= cgrp_dfl_threaded_ss_mask;
440 return cgrp->root->subsys_mask;
444 * cgroup_css - obtain a cgroup's css for the specified subsystem
445 * @cgrp: the cgroup of interest
446 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
448 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
449 * function must be called either under cgroup_mutex or rcu_read_lock() and
450 * the caller is responsible for pinning the returned css if it wants to
451 * keep accessing it outside the said locks. This function may return
452 * %NULL if @cgrp doesn't have @subsys_id enabled.
454 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
455 struct cgroup_subsys *ss)
458 return rcu_dereference_check(cgrp->subsys[ss->id],
459 lockdep_is_held(&cgroup_mutex));
465 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
466 * @cgrp: the cgroup of interest
467 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
469 * Similar to cgroup_css() but returns the effective css, which is defined
470 * as the matching css of the nearest ancestor including self which has @ss
471 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
472 * function is guaranteed to return non-NULL css.
474 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
475 struct cgroup_subsys *ss)
477 lockdep_assert_held(&cgroup_mutex);
483 * This function is used while updating css associations and thus
484 * can't test the csses directly. Test ss_mask.
486 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
487 cgrp = cgroup_parent(cgrp);
492 return cgroup_css(cgrp, ss);
496 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
497 * @cgrp: the cgroup of interest
498 * @ss: the subsystem of interest
500 * Find and get the effective css of @cgrp for @ss. The effective css is
501 * defined as the matching css of the nearest ancestor including self which
502 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
503 * the root css is returned, so this function always returns a valid css.
504 * The returned css must be put using css_put().
506 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
507 struct cgroup_subsys *ss)
509 struct cgroup_subsys_state *css;
514 css = cgroup_css(cgrp, ss);
516 if (css && css_tryget_online(css))
518 cgrp = cgroup_parent(cgrp);
521 css = init_css_set.subsys[ss->id];
528 static void cgroup_get_live(struct cgroup *cgrp)
530 WARN_ON_ONCE(cgroup_is_dead(cgrp));
531 css_get(&cgrp->self);
534 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
536 struct cgroup *cgrp = of->kn->parent->priv;
537 struct cftype *cft = of_cft(of);
540 * This is open and unprotected implementation of cgroup_css().
541 * seq_css() is only called from a kernfs file operation which has
542 * an active reference on the file. Because all the subsystem
543 * files are drained before a css is disassociated with a cgroup,
544 * the matching css from the cgroup's subsys table is guaranteed to
545 * be and stay valid until the enclosing operation is complete.
548 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
552 EXPORT_SYMBOL_GPL(of_css);
555 * for_each_css - iterate all css's of a cgroup
556 * @css: the iteration cursor
557 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
558 * @cgrp: the target cgroup to iterate css's of
560 * Should be called under cgroup_[tree_]mutex.
562 #define for_each_css(css, ssid, cgrp) \
563 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
564 if (!((css) = rcu_dereference_check( \
565 (cgrp)->subsys[(ssid)], \
566 lockdep_is_held(&cgroup_mutex)))) { } \
570 * for_each_e_css - iterate all effective css's of a cgroup
571 * @css: the iteration cursor
572 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
573 * @cgrp: the target cgroup to iterate css's of
575 * Should be called under cgroup_[tree_]mutex.
577 #define for_each_e_css(css, ssid, cgrp) \
578 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
579 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
584 * do_each_subsys_mask - filter for_each_subsys with a bitmask
585 * @ss: the iteration cursor
586 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
587 * @ss_mask: the bitmask
589 * The block will only run for cases where the ssid-th bit (1 << ssid) of
592 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
593 unsigned long __ss_mask = (ss_mask); \
594 if (!CGROUP_SUBSYS_COUNT) { /* to avoid spurious gcc warning */ \
598 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
599 (ss) = cgroup_subsys[ssid]; \
602 #define while_each_subsys_mask() \
607 /* iterate over child cgrps, lock should be held throughout iteration */
608 #define cgroup_for_each_live_child(child, cgrp) \
609 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
610 if (({ lockdep_assert_held(&cgroup_mutex); \
611 cgroup_is_dead(child); })) \
615 /* walk live descendants in preorder */
616 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
617 css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
618 if (({ lockdep_assert_held(&cgroup_mutex); \
619 (dsct) = (d_css)->cgroup; \
620 cgroup_is_dead(dsct); })) \
624 /* walk live descendants in postorder */
625 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
626 css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
627 if (({ lockdep_assert_held(&cgroup_mutex); \
628 (dsct) = (d_css)->cgroup; \
629 cgroup_is_dead(dsct); })) \
634 * The default css_set - used by init and its children prior to any
635 * hierarchies being mounted. It contains a pointer to the root state
636 * for each subsystem. Also used to anchor the list of css_sets. Not
637 * reference-counted, to improve performance when child cgroups
638 * haven't been created.
640 struct css_set init_css_set = {
641 .refcount = REFCOUNT_INIT(1),
642 .dom_cset = &init_css_set,
643 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
644 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
645 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
646 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
647 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
648 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
649 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
652 static int css_set_count = 1; /* 1 for init_css_set */
654 static bool css_set_threaded(struct css_set *cset)
656 return cset->dom_cset != cset;
660 * css_set_populated - does a css_set contain any tasks?
661 * @cset: target css_set
663 * css_set_populated() should be the same as !!cset->nr_tasks at steady
664 * state. However, css_set_populated() can be called while a task is being
665 * added to or removed from the linked list before the nr_tasks is
666 * properly updated. Hence, we can't just look at ->nr_tasks here.
668 static bool css_set_populated(struct css_set *cset)
670 lockdep_assert_held(&css_set_lock);
672 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
676 * cgroup_update_populated - update the populated count of a cgroup
677 * @cgrp: the target cgroup
678 * @populated: inc or dec populated count
680 * One of the css_sets associated with @cgrp is either getting its first
681 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
682 * count is propagated towards root so that a given cgroup's
683 * nr_populated_children is zero iff none of its descendants contain any
686 * @cgrp's interface file "cgroup.populated" is zero if both
687 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
688 * 1 otherwise. When the sum changes from or to zero, userland is notified
689 * that the content of the interface file has changed. This can be used to
690 * detect when @cgrp and its descendants become populated or empty.
692 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
694 struct cgroup *child = NULL;
695 int adj = populated ? 1 : -1;
697 lockdep_assert_held(&css_set_lock);
700 bool was_populated = cgroup_is_populated(cgrp);
703 cgrp->nr_populated_csets += adj;
705 if (cgroup_is_threaded(child))
706 cgrp->nr_populated_threaded_children += adj;
708 cgrp->nr_populated_domain_children += adj;
711 if (was_populated == cgroup_is_populated(cgrp))
714 cgroup1_check_for_release(cgrp);
715 cgroup_file_notify(&cgrp->events_file);
718 cgrp = cgroup_parent(cgrp);
723 * css_set_update_populated - update populated state of a css_set
724 * @cset: target css_set
725 * @populated: whether @cset is populated or depopulated
727 * @cset is either getting the first task or losing the last. Update the
728 * populated counters of all associated cgroups accordingly.
730 static void css_set_update_populated(struct css_set *cset, bool populated)
732 struct cgrp_cset_link *link;
734 lockdep_assert_held(&css_set_lock);
736 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
737 cgroup_update_populated(link->cgrp, populated);
741 * css_set_move_task - move a task from one css_set to another
742 * @task: task being moved
743 * @from_cset: css_set @task currently belongs to (may be NULL)
744 * @to_cset: new css_set @task is being moved to (may be NULL)
745 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
747 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
748 * css_set, @from_cset can be NULL. If @task is being disassociated
749 * instead of moved, @to_cset can be NULL.
751 * This function automatically handles populated counter updates and
752 * css_task_iter adjustments but the caller is responsible for managing
753 * @from_cset and @to_cset's reference counts.
755 static void css_set_move_task(struct task_struct *task,
756 struct css_set *from_cset, struct css_set *to_cset,
759 lockdep_assert_held(&css_set_lock);
761 if (to_cset && !css_set_populated(to_cset))
762 css_set_update_populated(to_cset, true);
765 struct css_task_iter *it, *pos;
767 WARN_ON_ONCE(list_empty(&task->cg_list));
770 * @task is leaving, advance task iterators which are
771 * pointing to it so that they can resume at the next
772 * position. Advancing an iterator might remove it from
773 * the list, use safe walk. See css_task_iter_advance*()
776 list_for_each_entry_safe(it, pos, &from_cset->task_iters,
778 if (it->task_pos == &task->cg_list)
779 css_task_iter_advance(it);
781 list_del_init(&task->cg_list);
782 if (!css_set_populated(from_cset))
783 css_set_update_populated(from_cset, false);
785 WARN_ON_ONCE(!list_empty(&task->cg_list));
790 * We are synchronized through cgroup_threadgroup_rwsem
791 * against PF_EXITING setting such that we can't race
792 * against cgroup_exit() changing the css_set to
793 * init_css_set and dropping the old one.
795 WARN_ON_ONCE(task->flags & PF_EXITING);
797 rcu_assign_pointer(task->cgroups, to_cset);
798 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
804 * hash table for cgroup groups. This improves the performance to find
805 * an existing css_set. This hash doesn't (currently) take into
806 * account cgroups in empty hierarchies.
808 #define CSS_SET_HASH_BITS 7
809 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
811 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
813 unsigned long key = 0UL;
814 struct cgroup_subsys *ss;
817 for_each_subsys(ss, i)
818 key += (unsigned long)css[i];
819 key = (key >> 16) ^ key;
824 void put_css_set_locked(struct css_set *cset)
826 struct cgrp_cset_link *link, *tmp_link;
827 struct cgroup_subsys *ss;
830 lockdep_assert_held(&css_set_lock);
832 if (!refcount_dec_and_test(&cset->refcount))
835 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
837 /* This css_set is dead. unlink it and release cgroup and css refs */
838 for_each_subsys(ss, ssid) {
839 list_del(&cset->e_cset_node[ssid]);
840 css_put(cset->subsys[ssid]);
842 hash_del(&cset->hlist);
845 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
846 list_del(&link->cset_link);
847 list_del(&link->cgrp_link);
848 if (cgroup_parent(link->cgrp))
849 cgroup_put(link->cgrp);
853 if (css_set_threaded(cset)) {
854 list_del(&cset->threaded_csets_node);
855 put_css_set_locked(cset->dom_cset);
858 kfree_rcu(cset, rcu_head);
862 * compare_css_sets - helper function for find_existing_css_set().
863 * @cset: candidate css_set being tested
864 * @old_cset: existing css_set for a task
865 * @new_cgrp: cgroup that's being entered by the task
866 * @template: desired set of css pointers in css_set (pre-calculated)
868 * Returns true if "cset" matches "old_cset" except for the hierarchy
869 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
871 static bool compare_css_sets(struct css_set *cset,
872 struct css_set *old_cset,
873 struct cgroup *new_cgrp,
874 struct cgroup_subsys_state *template[])
876 struct cgroup *new_dfl_cgrp;
877 struct list_head *l1, *l2;
880 * On the default hierarchy, there can be csets which are
881 * associated with the same set of cgroups but different csses.
882 * Let's first ensure that csses match.
884 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
888 /* @cset's domain should match the default cgroup's */
889 if (cgroup_on_dfl(new_cgrp))
890 new_dfl_cgrp = new_cgrp;
892 new_dfl_cgrp = old_cset->dfl_cgrp;
894 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
898 * Compare cgroup pointers in order to distinguish between
899 * different cgroups in hierarchies. As different cgroups may
900 * share the same effective css, this comparison is always
903 l1 = &cset->cgrp_links;
904 l2 = &old_cset->cgrp_links;
906 struct cgrp_cset_link *link1, *link2;
907 struct cgroup *cgrp1, *cgrp2;
911 /* See if we reached the end - both lists are equal length. */
912 if (l1 == &cset->cgrp_links) {
913 BUG_ON(l2 != &old_cset->cgrp_links);
916 BUG_ON(l2 == &old_cset->cgrp_links);
918 /* Locate the cgroups associated with these links. */
919 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
920 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
923 /* Hierarchies should be linked in the same order. */
924 BUG_ON(cgrp1->root != cgrp2->root);
927 * If this hierarchy is the hierarchy of the cgroup
928 * that's changing, then we need to check that this
929 * css_set points to the new cgroup; if it's any other
930 * hierarchy, then this css_set should point to the
931 * same cgroup as the old css_set.
933 if (cgrp1->root == new_cgrp->root) {
934 if (cgrp1 != new_cgrp)
945 * find_existing_css_set - init css array and find the matching css_set
946 * @old_cset: the css_set that we're using before the cgroup transition
947 * @cgrp: the cgroup that we're moving into
948 * @template: out param for the new set of csses, should be clear on entry
950 static struct css_set *find_existing_css_set(struct css_set *old_cset,
952 struct cgroup_subsys_state *template[])
954 struct cgroup_root *root = cgrp->root;
955 struct cgroup_subsys *ss;
956 struct css_set *cset;
961 * Build the set of subsystem state objects that we want to see in the
962 * new css_set. while subsystems can change globally, the entries here
963 * won't change, so no need for locking.
965 for_each_subsys(ss, i) {
966 if (root->subsys_mask & (1UL << i)) {
968 * @ss is in this hierarchy, so we want the
969 * effective css from @cgrp.
971 template[i] = cgroup_e_css(cgrp, ss);
974 * @ss is not in this hierarchy, so we don't want
977 template[i] = old_cset->subsys[i];
981 key = css_set_hash(template);
982 hash_for_each_possible(css_set_table, cset, hlist, key) {
983 if (!compare_css_sets(cset, old_cset, cgrp, template))
986 /* This css_set matches what we need */
990 /* No existing cgroup group matched */
994 static void free_cgrp_cset_links(struct list_head *links_to_free)
996 struct cgrp_cset_link *link, *tmp_link;
998 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
999 list_del(&link->cset_link);
1005 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1006 * @count: the number of links to allocate
1007 * @tmp_links: list_head the allocated links are put on
1009 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1010 * through ->cset_link. Returns 0 on success or -errno.
1012 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1014 struct cgrp_cset_link *link;
1017 INIT_LIST_HEAD(tmp_links);
1019 for (i = 0; i < count; i++) {
1020 link = kzalloc(sizeof(*link), GFP_KERNEL);
1022 free_cgrp_cset_links(tmp_links);
1025 list_add(&link->cset_link, tmp_links);
1031 * link_css_set - a helper function to link a css_set to a cgroup
1032 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1033 * @cset: the css_set to be linked
1034 * @cgrp: the destination cgroup
1036 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1037 struct cgroup *cgrp)
1039 struct cgrp_cset_link *link;
1041 BUG_ON(list_empty(tmp_links));
1043 if (cgroup_on_dfl(cgrp))
1044 cset->dfl_cgrp = cgrp;
1046 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1051 * Always add links to the tail of the lists so that the lists are
1052 * in choronological order.
1054 list_move_tail(&link->cset_link, &cgrp->cset_links);
1055 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1057 if (cgroup_parent(cgrp))
1058 cgroup_get_live(cgrp);
1062 * find_css_set - return a new css_set with one cgroup updated
1063 * @old_cset: the baseline css_set
1064 * @cgrp: the cgroup to be updated
1066 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1067 * substituted into the appropriate hierarchy.
1069 static struct css_set *find_css_set(struct css_set *old_cset,
1070 struct cgroup *cgrp)
1072 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1073 struct css_set *cset;
1074 struct list_head tmp_links;
1075 struct cgrp_cset_link *link;
1076 struct cgroup_subsys *ss;
1080 lockdep_assert_held(&cgroup_mutex);
1082 /* First see if we already have a cgroup group that matches
1083 * the desired set */
1084 spin_lock_irq(&css_set_lock);
1085 cset = find_existing_css_set(old_cset, cgrp, template);
1088 spin_unlock_irq(&css_set_lock);
1093 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1097 /* Allocate all the cgrp_cset_link objects that we'll need */
1098 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1103 refcount_set(&cset->refcount, 1);
1104 cset->dom_cset = cset;
1105 INIT_LIST_HEAD(&cset->tasks);
1106 INIT_LIST_HEAD(&cset->mg_tasks);
1107 INIT_LIST_HEAD(&cset->task_iters);
1108 INIT_LIST_HEAD(&cset->threaded_csets);
1109 INIT_HLIST_NODE(&cset->hlist);
1110 INIT_LIST_HEAD(&cset->cgrp_links);
1111 INIT_LIST_HEAD(&cset->mg_preload_node);
1112 INIT_LIST_HEAD(&cset->mg_node);
1114 /* Copy the set of subsystem state objects generated in
1115 * find_existing_css_set() */
1116 memcpy(cset->subsys, template, sizeof(cset->subsys));
1118 spin_lock_irq(&css_set_lock);
1119 /* Add reference counts and links from the new css_set. */
1120 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1121 struct cgroup *c = link->cgrp;
1123 if (c->root == cgrp->root)
1125 link_css_set(&tmp_links, cset, c);
1128 BUG_ON(!list_empty(&tmp_links));
1132 /* Add @cset to the hash table */
1133 key = css_set_hash(cset->subsys);
1134 hash_add(css_set_table, &cset->hlist, key);
1136 for_each_subsys(ss, ssid) {
1137 struct cgroup_subsys_state *css = cset->subsys[ssid];
1139 list_add_tail(&cset->e_cset_node[ssid],
1140 &css->cgroup->e_csets[ssid]);
1144 spin_unlock_irq(&css_set_lock);
1147 * If @cset should be threaded, look up the matching dom_cset and
1148 * link them up. We first fully initialize @cset then look for the
1149 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1150 * to stay empty until we return.
1152 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1153 struct css_set *dcset;
1155 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1161 spin_lock_irq(&css_set_lock);
1162 cset->dom_cset = dcset;
1163 list_add_tail(&cset->threaded_csets_node,
1164 &dcset->threaded_csets);
1165 spin_unlock_irq(&css_set_lock);
1171 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1173 struct cgroup *root_cgrp = kf_root->kn->priv;
1175 return root_cgrp->root;
1178 static int cgroup_init_root_id(struct cgroup_root *root)
1182 lockdep_assert_held(&cgroup_mutex);
1184 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1188 root->hierarchy_id = id;
1192 static void cgroup_exit_root_id(struct cgroup_root *root)
1194 lockdep_assert_held(&cgroup_mutex);
1196 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1199 void cgroup_free_root(struct cgroup_root *root)
1202 idr_destroy(&root->cgroup_idr);
1207 static void cgroup_destroy_root(struct cgroup_root *root)
1209 struct cgroup *cgrp = &root->cgrp;
1210 struct cgrp_cset_link *link, *tmp_link;
1212 trace_cgroup_destroy_root(root);
1214 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1216 BUG_ON(atomic_read(&root->nr_cgrps));
1217 BUG_ON(!list_empty(&cgrp->self.children));
1219 /* Rebind all subsystems back to the default hierarchy */
1220 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1223 * Release all the links from cset_links to this hierarchy's
1226 spin_lock_irq(&css_set_lock);
1228 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1229 list_del(&link->cset_link);
1230 list_del(&link->cgrp_link);
1234 spin_unlock_irq(&css_set_lock);
1236 if (!list_empty(&root->root_list)) {
1237 list_del(&root->root_list);
1238 cgroup_root_count--;
1241 cgroup_exit_root_id(root);
1243 mutex_unlock(&cgroup_mutex);
1245 kernfs_destroy_root(root->kf_root);
1246 cgroup_free_root(root);
1250 * look up cgroup associated with current task's cgroup namespace on the
1251 * specified hierarchy
1253 static struct cgroup *
1254 current_cgns_cgroup_from_root(struct cgroup_root *root)
1256 struct cgroup *res = NULL;
1257 struct css_set *cset;
1259 lockdep_assert_held(&css_set_lock);
1263 cset = current->nsproxy->cgroup_ns->root_cset;
1264 if (cset == &init_css_set) {
1267 struct cgrp_cset_link *link;
1269 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1270 struct cgroup *c = link->cgrp;
1272 if (c->root == root) {
1284 /* look up cgroup associated with given css_set on the specified hierarchy */
1285 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1286 struct cgroup_root *root)
1288 struct cgroup *res = NULL;
1290 lockdep_assert_held(&cgroup_mutex);
1291 lockdep_assert_held(&css_set_lock);
1293 if (cset == &init_css_set) {
1295 } else if (root == &cgrp_dfl_root) {
1296 res = cset->dfl_cgrp;
1298 struct cgrp_cset_link *link;
1300 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1301 struct cgroup *c = link->cgrp;
1303 if (c->root == root) {
1315 * Return the cgroup for "task" from the given hierarchy. Must be
1316 * called with cgroup_mutex and css_set_lock held.
1318 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1319 struct cgroup_root *root)
1322 * No need to lock the task - since we hold cgroup_mutex the
1323 * task can't change groups, so the only thing that can happen
1324 * is that it exits and its css is set back to init_css_set.
1326 return cset_cgroup_from_root(task_css_set(task), root);
1330 * A task must hold cgroup_mutex to modify cgroups.
1332 * Any task can increment and decrement the count field without lock.
1333 * So in general, code holding cgroup_mutex can't rely on the count
1334 * field not changing. However, if the count goes to zero, then only
1335 * cgroup_attach_task() can increment it again. Because a count of zero
1336 * means that no tasks are currently attached, therefore there is no
1337 * way a task attached to that cgroup can fork (the other way to
1338 * increment the count). So code holding cgroup_mutex can safely
1339 * assume that if the count is zero, it will stay zero. Similarly, if
1340 * a task holds cgroup_mutex on a cgroup with zero count, it
1341 * knows that the cgroup won't be removed, as cgroup_rmdir()
1344 * A cgroup can only be deleted if both its 'count' of using tasks
1345 * is zero, and its list of 'children' cgroups is empty. Since all
1346 * tasks in the system use _some_ cgroup, and since there is always at
1347 * least one task in the system (init, pid == 1), therefore, root cgroup
1348 * always has either children cgroups and/or using tasks. So we don't
1349 * need a special hack to ensure that root cgroup cannot be deleted.
1351 * P.S. One more locking exception. RCU is used to guard the
1352 * update of a tasks cgroup pointer by cgroup_attach_task()
1355 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1357 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1360 struct cgroup_subsys *ss = cft->ss;
1362 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1363 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1364 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1365 cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1368 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1373 * cgroup_file_mode - deduce file mode of a control file
1374 * @cft: the control file in question
1376 * S_IRUGO for read, S_IWUSR for write.
1378 static umode_t cgroup_file_mode(const struct cftype *cft)
1382 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1385 if (cft->write_u64 || cft->write_s64 || cft->write) {
1386 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1396 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1397 * @subtree_control: the new subtree_control mask to consider
1398 * @this_ss_mask: available subsystems
1400 * On the default hierarchy, a subsystem may request other subsystems to be
1401 * enabled together through its ->depends_on mask. In such cases, more
1402 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1404 * This function calculates which subsystems need to be enabled if
1405 * @subtree_control is to be applied while restricted to @this_ss_mask.
1407 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1409 u16 cur_ss_mask = subtree_control;
1410 struct cgroup_subsys *ss;
1413 lockdep_assert_held(&cgroup_mutex);
1415 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1418 u16 new_ss_mask = cur_ss_mask;
1420 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1421 new_ss_mask |= ss->depends_on;
1422 } while_each_subsys_mask();
1425 * Mask out subsystems which aren't available. This can
1426 * happen only if some depended-upon subsystems were bound
1427 * to non-default hierarchies.
1429 new_ss_mask &= this_ss_mask;
1431 if (new_ss_mask == cur_ss_mask)
1433 cur_ss_mask = new_ss_mask;
1440 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1441 * @kn: the kernfs_node being serviced
1443 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1444 * the method finishes if locking succeeded. Note that once this function
1445 * returns the cgroup returned by cgroup_kn_lock_live() may become
1446 * inaccessible any time. If the caller intends to continue to access the
1447 * cgroup, it should pin it before invoking this function.
1449 void cgroup_kn_unlock(struct kernfs_node *kn)
1451 struct cgroup *cgrp;
1453 if (kernfs_type(kn) == KERNFS_DIR)
1456 cgrp = kn->parent->priv;
1458 mutex_unlock(&cgroup_mutex);
1460 kernfs_unbreak_active_protection(kn);
1465 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1466 * @kn: the kernfs_node being serviced
1467 * @drain_offline: perform offline draining on the cgroup
1469 * This helper is to be used by a cgroup kernfs method currently servicing
1470 * @kn. It breaks the active protection, performs cgroup locking and
1471 * verifies that the associated cgroup is alive. Returns the cgroup if
1472 * alive; otherwise, %NULL. A successful return should be undone by a
1473 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1474 * cgroup is drained of offlining csses before return.
1476 * Any cgroup kernfs method implementation which requires locking the
1477 * associated cgroup should use this helper. It avoids nesting cgroup
1478 * locking under kernfs active protection and allows all kernfs operations
1479 * including self-removal.
1481 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1483 struct cgroup *cgrp;
1485 if (kernfs_type(kn) == KERNFS_DIR)
1488 cgrp = kn->parent->priv;
1491 * We're gonna grab cgroup_mutex which nests outside kernfs
1492 * active_ref. cgroup liveliness check alone provides enough
1493 * protection against removal. Ensure @cgrp stays accessible and
1494 * break the active_ref protection.
1496 if (!cgroup_tryget(cgrp))
1498 kernfs_break_active_protection(kn);
1501 cgroup_lock_and_drain_offline(cgrp);
1503 mutex_lock(&cgroup_mutex);
1505 if (!cgroup_is_dead(cgrp))
1508 cgroup_kn_unlock(kn);
1512 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1514 char name[CGROUP_FILE_NAME_MAX];
1516 lockdep_assert_held(&cgroup_mutex);
1518 if (cft->file_offset) {
1519 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1520 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1522 spin_lock_irq(&cgroup_file_kn_lock);
1524 spin_unlock_irq(&cgroup_file_kn_lock);
1527 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1531 * css_clear_dir - remove subsys files in a cgroup directory
1534 static void css_clear_dir(struct cgroup_subsys_state *css)
1536 struct cgroup *cgrp = css->cgroup;
1537 struct cftype *cfts;
1539 if (!(css->flags & CSS_VISIBLE))
1542 css->flags &= ~CSS_VISIBLE;
1544 list_for_each_entry(cfts, &css->ss->cfts, node)
1545 cgroup_addrm_files(css, cgrp, cfts, false);
1549 * css_populate_dir - create subsys files in a cgroup directory
1552 * On failure, no file is added.
1554 static int css_populate_dir(struct cgroup_subsys_state *css)
1556 struct cgroup *cgrp = css->cgroup;
1557 struct cftype *cfts, *failed_cfts;
1560 if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
1564 if (cgroup_on_dfl(cgrp))
1565 cfts = cgroup_base_files;
1567 cfts = cgroup1_base_files;
1569 return cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1572 list_for_each_entry(cfts, &css->ss->cfts, node) {
1573 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1580 css->flags |= CSS_VISIBLE;
1584 list_for_each_entry(cfts, &css->ss->cfts, node) {
1585 if (cfts == failed_cfts)
1587 cgroup_addrm_files(css, cgrp, cfts, false);
1592 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1594 struct cgroup *dcgrp = &dst_root->cgrp;
1595 struct cgroup_subsys *ss;
1598 lockdep_assert_held(&cgroup_mutex);
1600 do_each_subsys_mask(ss, ssid, ss_mask) {
1602 * If @ss has non-root csses attached to it, can't move.
1603 * If @ss is an implicit controller, it is exempt from this
1604 * rule and can be stolen.
1606 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1607 !ss->implicit_on_dfl)
1610 /* can't move between two non-dummy roots either */
1611 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1613 } while_each_subsys_mask();
1615 do_each_subsys_mask(ss, ssid, ss_mask) {
1616 struct cgroup_root *src_root = ss->root;
1617 struct cgroup *scgrp = &src_root->cgrp;
1618 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1619 struct css_set *cset;
1621 WARN_ON(!css || cgroup_css(dcgrp, ss));
1623 /* disable from the source */
1624 src_root->subsys_mask &= ~(1 << ssid);
1625 WARN_ON(cgroup_apply_control(scgrp));
1626 cgroup_finalize_control(scgrp, 0);
1629 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1630 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1631 ss->root = dst_root;
1632 css->cgroup = dcgrp;
1634 spin_lock_irq(&css_set_lock);
1635 hash_for_each(css_set_table, i, cset, hlist)
1636 list_move_tail(&cset->e_cset_node[ss->id],
1637 &dcgrp->e_csets[ss->id]);
1638 spin_unlock_irq(&css_set_lock);
1640 /* default hierarchy doesn't enable controllers by default */
1641 dst_root->subsys_mask |= 1 << ssid;
1642 if (dst_root == &cgrp_dfl_root) {
1643 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1645 dcgrp->subtree_control |= 1 << ssid;
1646 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1649 ret = cgroup_apply_control(dcgrp);
1651 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1656 } while_each_subsys_mask();
1658 kernfs_activate(dcgrp->kn);
1662 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1663 struct kernfs_root *kf_root)
1667 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1668 struct cgroup *ns_cgroup;
1670 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1674 spin_lock_irq(&css_set_lock);
1675 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1676 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1677 spin_unlock_irq(&css_set_lock);
1679 if (len >= PATH_MAX)
1682 seq_escape(sf, buf, " \t\n\\");
1689 static int parse_cgroup_root_flags(char *data, unsigned int *root_flags)
1698 while ((token = strsep(&data, ",")) != NULL) {
1699 if (!strcmp(token, "nsdelegate")) {
1700 *root_flags |= CGRP_ROOT_NS_DELEGATE;
1704 pr_err("cgroup2: unknown option \"%s\"\n", token);
1711 static void apply_cgroup_root_flags(unsigned int root_flags)
1713 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1714 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1715 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1717 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1721 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1723 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1724 seq_puts(seq, ",nsdelegate");
1728 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1730 unsigned int root_flags;
1733 ret = parse_cgroup_root_flags(data, &root_flags);
1737 apply_cgroup_root_flags(root_flags);
1742 * To reduce the fork() overhead for systems that are not actually using
1743 * their cgroups capability, we don't maintain the lists running through
1744 * each css_set to its tasks until we see the list actually used - in other
1745 * words after the first mount.
1747 static bool use_task_css_set_links __read_mostly;
1749 static void cgroup_enable_task_cg_lists(void)
1751 struct task_struct *p, *g;
1753 spin_lock_irq(&css_set_lock);
1755 if (use_task_css_set_links)
1758 use_task_css_set_links = true;
1761 * We need tasklist_lock because RCU is not safe against
1762 * while_each_thread(). Besides, a forking task that has passed
1763 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1764 * is not guaranteed to have its child immediately visible in the
1765 * tasklist if we walk through it with RCU.
1767 read_lock(&tasklist_lock);
1768 do_each_thread(g, p) {
1769 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1770 task_css_set(p) != &init_css_set);
1773 * We should check if the process is exiting, otherwise
1774 * it will race with cgroup_exit() in that the list
1775 * entry won't be deleted though the process has exited.
1776 * Do it while holding siglock so that we don't end up
1777 * racing against cgroup_exit().
1779 * Interrupts were already disabled while acquiring
1780 * the css_set_lock, so we do not need to disable it
1781 * again when acquiring the sighand->siglock here.
1783 spin_lock(&p->sighand->siglock);
1784 if (!(p->flags & PF_EXITING)) {
1785 struct css_set *cset = task_css_set(p);
1787 if (!css_set_populated(cset))
1788 css_set_update_populated(cset, true);
1789 list_add_tail(&p->cg_list, &cset->tasks);
1793 spin_unlock(&p->sighand->siglock);
1794 } while_each_thread(g, p);
1795 read_unlock(&tasklist_lock);
1797 spin_unlock_irq(&css_set_lock);
1800 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1802 struct cgroup_subsys *ss;
1805 INIT_LIST_HEAD(&cgrp->self.sibling);
1806 INIT_LIST_HEAD(&cgrp->self.children);
1807 INIT_LIST_HEAD(&cgrp->cset_links);
1808 INIT_LIST_HEAD(&cgrp->pidlists);
1809 mutex_init(&cgrp->pidlist_mutex);
1810 cgrp->self.cgroup = cgrp;
1811 cgrp->self.flags |= CSS_ONLINE;
1812 cgrp->dom_cgrp = cgrp;
1813 cgrp->max_descendants = INT_MAX;
1814 cgrp->max_depth = INT_MAX;
1816 for_each_subsys(ss, ssid)
1817 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1819 init_waitqueue_head(&cgrp->offline_waitq);
1820 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
1823 void init_cgroup_root(struct cgroup_root *root, struct cgroup_sb_opts *opts)
1825 struct cgroup *cgrp = &root->cgrp;
1827 INIT_LIST_HEAD(&root->root_list);
1828 atomic_set(&root->nr_cgrps, 1);
1830 init_cgroup_housekeeping(cgrp);
1831 idr_init(&root->cgroup_idr);
1833 root->flags = opts->flags;
1834 if (opts->release_agent)
1835 strcpy(root->release_agent_path, opts->release_agent);
1837 strcpy(root->name, opts->name);
1838 if (opts->cpuset_clone_children)
1839 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1842 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask, int ref_flags)
1844 LIST_HEAD(tmp_links);
1845 struct cgroup *root_cgrp = &root->cgrp;
1846 struct kernfs_syscall_ops *kf_sops;
1847 struct css_set *cset;
1850 lockdep_assert_held(&cgroup_mutex);
1852 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1855 root_cgrp->id = ret;
1856 root_cgrp->ancestor_ids[0] = ret;
1858 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
1859 ref_flags, GFP_KERNEL);
1864 * We're accessing css_set_count without locking css_set_lock here,
1865 * but that's OK - it can only be increased by someone holding
1866 * cgroup_lock, and that's us. Later rebinding may disable
1867 * controllers on the default hierarchy and thus create new csets,
1868 * which can't be more than the existing ones. Allocate 2x.
1870 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
1874 ret = cgroup_init_root_id(root);
1878 kf_sops = root == &cgrp_dfl_root ?
1879 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
1881 root->kf_root = kernfs_create_root(kf_sops,
1882 KERNFS_ROOT_CREATE_DEACTIVATED,
1884 if (IS_ERR(root->kf_root)) {
1885 ret = PTR_ERR(root->kf_root);
1888 root_cgrp->kn = root->kf_root->kn;
1890 ret = css_populate_dir(&root_cgrp->self);
1894 ret = rebind_subsystems(root, ss_mask);
1898 trace_cgroup_setup_root(root);
1901 * There must be no failure case after here, since rebinding takes
1902 * care of subsystems' refcounts, which are explicitly dropped in
1903 * the failure exit path.
1905 list_add(&root->root_list, &cgroup_roots);
1906 cgroup_root_count++;
1909 * Link the root cgroup in this hierarchy into all the css_set
1912 spin_lock_irq(&css_set_lock);
1913 hash_for_each(css_set_table, i, cset, hlist) {
1914 link_css_set(&tmp_links, cset, root_cgrp);
1915 if (css_set_populated(cset))
1916 cgroup_update_populated(root_cgrp, true);
1918 spin_unlock_irq(&css_set_lock);
1920 BUG_ON(!list_empty(&root_cgrp->self.children));
1921 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1923 kernfs_activate(root_cgrp->kn);
1928 kernfs_destroy_root(root->kf_root);
1929 root->kf_root = NULL;
1931 cgroup_exit_root_id(root);
1933 percpu_ref_exit(&root_cgrp->self.refcnt);
1935 free_cgrp_cset_links(&tmp_links);
1939 struct dentry *cgroup_do_mount(struct file_system_type *fs_type, int flags,
1940 struct cgroup_root *root, unsigned long magic,
1941 struct cgroup_namespace *ns)
1943 struct dentry *dentry;
1946 dentry = kernfs_mount(fs_type, flags, root->kf_root, magic, &new_sb);
1949 * In non-init cgroup namespace, instead of root cgroup's dentry,
1950 * we return the dentry corresponding to the cgroupns->root_cgrp.
1952 if (!IS_ERR(dentry) && ns != &init_cgroup_ns) {
1953 struct dentry *nsdentry;
1954 struct cgroup *cgrp;
1956 mutex_lock(&cgroup_mutex);
1957 spin_lock_irq(&css_set_lock);
1959 cgrp = cset_cgroup_from_root(ns->root_cset, root);
1961 spin_unlock_irq(&css_set_lock);
1962 mutex_unlock(&cgroup_mutex);
1964 nsdentry = kernfs_node_dentry(cgrp->kn, dentry->d_sb);
1969 if (IS_ERR(dentry) || !new_sb)
1970 cgroup_put(&root->cgrp);
1975 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1976 int flags, const char *unused_dev_name,
1979 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
1980 struct dentry *dentry;
1985 /* Check if the caller has permission to mount. */
1986 if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) {
1988 return ERR_PTR(-EPERM);
1992 * The first time anyone tries to mount a cgroup, enable the list
1993 * linking each css_set to its tasks and fix up all existing tasks.
1995 if (!use_task_css_set_links)
1996 cgroup_enable_task_cg_lists();
1998 if (fs_type == &cgroup2_fs_type) {
1999 unsigned int root_flags;
2001 ret = parse_cgroup_root_flags(data, &root_flags);
2004 return ERR_PTR(ret);
2007 cgrp_dfl_visible = true;
2008 cgroup_get_live(&cgrp_dfl_root.cgrp);
2010 dentry = cgroup_do_mount(&cgroup2_fs_type, flags, &cgrp_dfl_root,
2011 CGROUP2_SUPER_MAGIC, ns);
2012 if (!IS_ERR(dentry))
2013 apply_cgroup_root_flags(root_flags);
2015 dentry = cgroup1_mount(&cgroup_fs_type, flags, data,
2016 CGROUP_SUPER_MAGIC, ns);
2023 static void cgroup_kill_sb(struct super_block *sb)
2025 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2026 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2029 * If @root doesn't have any mounts or children, start killing it.
2030 * This prevents new mounts by disabling percpu_ref_tryget_live().
2031 * cgroup_mount() may wait for @root's release.
2033 * And don't kill the default root.
2035 if (!list_empty(&root->cgrp.self.children) ||
2036 root == &cgrp_dfl_root)
2037 cgroup_put(&root->cgrp);
2039 percpu_ref_kill(&root->cgrp.self.refcnt);
2044 struct file_system_type cgroup_fs_type = {
2046 .mount = cgroup_mount,
2047 .kill_sb = cgroup_kill_sb,
2048 .fs_flags = FS_USERNS_MOUNT,
2051 static struct file_system_type cgroup2_fs_type = {
2053 .mount = cgroup_mount,
2054 .kill_sb = cgroup_kill_sb,
2055 .fs_flags = FS_USERNS_MOUNT,
2058 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2059 struct cgroup_namespace *ns)
2061 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2063 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2066 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2067 struct cgroup_namespace *ns)
2071 mutex_lock(&cgroup_mutex);
2072 spin_lock_irq(&css_set_lock);
2074 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2076 spin_unlock_irq(&css_set_lock);
2077 mutex_unlock(&cgroup_mutex);
2081 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2084 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2085 * @task: target task
2086 * @buf: the buffer to write the path into
2087 * @buflen: the length of the buffer
2089 * Determine @task's cgroup on the first (the one with the lowest non-zero
2090 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2091 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2092 * cgroup controller callbacks.
2094 * Return value is the same as kernfs_path().
2096 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2098 struct cgroup_root *root;
2099 struct cgroup *cgrp;
2100 int hierarchy_id = 1;
2103 mutex_lock(&cgroup_mutex);
2104 spin_lock_irq(&css_set_lock);
2106 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2109 cgrp = task_cgroup_from_root(task, root);
2110 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2112 /* if no hierarchy exists, everyone is in "/" */
2113 ret = strlcpy(buf, "/", buflen);
2116 spin_unlock_irq(&css_set_lock);
2117 mutex_unlock(&cgroup_mutex);
2120 EXPORT_SYMBOL_GPL(task_cgroup_path);
2123 * cgroup_migrate_add_task - add a migration target task to a migration context
2124 * @task: target task
2125 * @mgctx: target migration context
2127 * Add @task, which is a migration target, to @mgctx->tset. This function
2128 * becomes noop if @task doesn't need to be migrated. @task's css_set
2129 * should have been added as a migration source and @task->cg_list will be
2130 * moved from the css_set's tasks list to mg_tasks one.
2132 static void cgroup_migrate_add_task(struct task_struct *task,
2133 struct cgroup_mgctx *mgctx)
2135 struct css_set *cset;
2137 lockdep_assert_held(&css_set_lock);
2139 /* @task either already exited or can't exit until the end */
2140 if (task->flags & PF_EXITING)
2143 /* leave @task alone if post_fork() hasn't linked it yet */
2144 if (list_empty(&task->cg_list))
2147 cset = task_css_set(task);
2148 if (!cset->mg_src_cgrp)
2151 list_move_tail(&task->cg_list, &cset->mg_tasks);
2152 if (list_empty(&cset->mg_node))
2153 list_add_tail(&cset->mg_node,
2154 &mgctx->tset.src_csets);
2155 if (list_empty(&cset->mg_dst_cset->mg_node))
2156 list_add_tail(&cset->mg_dst_cset->mg_node,
2157 &mgctx->tset.dst_csets);
2161 * cgroup_taskset_first - reset taskset and return the first task
2162 * @tset: taskset of interest
2163 * @dst_cssp: output variable for the destination css
2165 * @tset iteration is initialized and the first task is returned.
2167 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2168 struct cgroup_subsys_state **dst_cssp)
2170 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2171 tset->cur_task = NULL;
2173 return cgroup_taskset_next(tset, dst_cssp);
2177 * cgroup_taskset_next - iterate to the next task in taskset
2178 * @tset: taskset of interest
2179 * @dst_cssp: output variable for the destination css
2181 * Return the next task in @tset. Iteration must have been initialized
2182 * with cgroup_taskset_first().
2184 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2185 struct cgroup_subsys_state **dst_cssp)
2187 struct css_set *cset = tset->cur_cset;
2188 struct task_struct *task = tset->cur_task;
2190 while (&cset->mg_node != tset->csets) {
2192 task = list_first_entry(&cset->mg_tasks,
2193 struct task_struct, cg_list);
2195 task = list_next_entry(task, cg_list);
2197 if (&task->cg_list != &cset->mg_tasks) {
2198 tset->cur_cset = cset;
2199 tset->cur_task = task;
2202 * This function may be called both before and
2203 * after cgroup_taskset_migrate(). The two cases
2204 * can be distinguished by looking at whether @cset
2205 * has its ->mg_dst_cset set.
2207 if (cset->mg_dst_cset)
2208 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2210 *dst_cssp = cset->subsys[tset->ssid];
2215 cset = list_next_entry(cset, mg_node);
2223 * cgroup_taskset_migrate - migrate a taskset
2224 * @mgctx: migration context
2226 * Migrate tasks in @mgctx as setup by migration preparation functions.
2227 * This function fails iff one of the ->can_attach callbacks fails and
2228 * guarantees that either all or none of the tasks in @mgctx are migrated.
2229 * @mgctx is consumed regardless of success.
2231 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2233 struct cgroup_taskset *tset = &mgctx->tset;
2234 struct cgroup_subsys *ss;
2235 struct task_struct *task, *tmp_task;
2236 struct css_set *cset, *tmp_cset;
2237 int ssid, failed_ssid, ret;
2239 /* methods shouldn't be called if no task is actually migrating */
2240 if (list_empty(&tset->src_csets))
2243 /* check that we can legitimately attach to the cgroup */
2244 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2245 if (ss->can_attach) {
2247 ret = ss->can_attach(tset);
2250 goto out_cancel_attach;
2253 } while_each_subsys_mask();
2256 * Now that we're guaranteed success, proceed to move all tasks to
2257 * the new cgroup. There are no failure cases after here, so this
2258 * is the commit point.
2260 spin_lock_irq(&css_set_lock);
2261 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2262 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2263 struct css_set *from_cset = task_css_set(task);
2264 struct css_set *to_cset = cset->mg_dst_cset;
2266 get_css_set(to_cset);
2267 to_cset->nr_tasks++;
2268 css_set_move_task(task, from_cset, to_cset, true);
2269 put_css_set_locked(from_cset);
2270 from_cset->nr_tasks--;
2273 spin_unlock_irq(&css_set_lock);
2276 * Migration is committed, all target tasks are now on dst_csets.
2277 * Nothing is sensitive to fork() after this point. Notify
2278 * controllers that migration is complete.
2280 tset->csets = &tset->dst_csets;
2282 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2287 } while_each_subsys_mask();
2290 goto out_release_tset;
2293 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2294 if (ssid == failed_ssid)
2296 if (ss->cancel_attach) {
2298 ss->cancel_attach(tset);
2300 } while_each_subsys_mask();
2302 spin_lock_irq(&css_set_lock);
2303 list_splice_init(&tset->dst_csets, &tset->src_csets);
2304 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2305 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2306 list_del_init(&cset->mg_node);
2308 spin_unlock_irq(&css_set_lock);
2313 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2314 * @dst_cgrp: destination cgroup to test
2316 * On the default hierarchy, except for the mixable, (possible) thread root
2317 * and threaded cgroups, subtree_control must be zero for migration
2318 * destination cgroups with tasks so that child cgroups don't compete
2321 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2323 /* v1 doesn't have any restriction */
2324 if (!cgroup_on_dfl(dst_cgrp))
2327 /* verify @dst_cgrp can host resources */
2328 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2331 /* mixables don't care */
2332 if (cgroup_is_mixable(dst_cgrp))
2336 * If @dst_cgrp is already or can become a thread root or is
2337 * threaded, it doesn't matter.
2339 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2342 /* apply no-internal-process constraint */
2343 if (dst_cgrp->subtree_control)
2350 * cgroup_migrate_finish - cleanup after attach
2351 * @mgctx: migration context
2353 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2354 * those functions for details.
2356 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2358 LIST_HEAD(preloaded);
2359 struct css_set *cset, *tmp_cset;
2361 lockdep_assert_held(&cgroup_mutex);
2363 spin_lock_irq(&css_set_lock);
2365 list_splice_tail_init(&mgctx->preloaded_src_csets, &preloaded);
2366 list_splice_tail_init(&mgctx->preloaded_dst_csets, &preloaded);
2368 list_for_each_entry_safe(cset, tmp_cset, &preloaded, mg_preload_node) {
2369 cset->mg_src_cgrp = NULL;
2370 cset->mg_dst_cgrp = NULL;
2371 cset->mg_dst_cset = NULL;
2372 list_del_init(&cset->mg_preload_node);
2373 put_css_set_locked(cset);
2376 spin_unlock_irq(&css_set_lock);
2380 * cgroup_migrate_add_src - add a migration source css_set
2381 * @src_cset: the source css_set to add
2382 * @dst_cgrp: the destination cgroup
2383 * @mgctx: migration context
2385 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2386 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2387 * up by cgroup_migrate_finish().
2389 * This function may be called without holding cgroup_threadgroup_rwsem
2390 * even if the target is a process. Threads may be created and destroyed
2391 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2392 * into play and the preloaded css_sets are guaranteed to cover all
2395 void cgroup_migrate_add_src(struct css_set *src_cset,
2396 struct cgroup *dst_cgrp,
2397 struct cgroup_mgctx *mgctx)
2399 struct cgroup *src_cgrp;
2401 lockdep_assert_held(&cgroup_mutex);
2402 lockdep_assert_held(&css_set_lock);
2405 * If ->dead, @src_set is associated with one or more dead cgroups
2406 * and doesn't contain any migratable tasks. Ignore it early so
2407 * that the rest of migration path doesn't get confused by it.
2412 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2414 if (!list_empty(&src_cset->mg_preload_node))
2417 WARN_ON(src_cset->mg_src_cgrp);
2418 WARN_ON(src_cset->mg_dst_cgrp);
2419 WARN_ON(!list_empty(&src_cset->mg_tasks));
2420 WARN_ON(!list_empty(&src_cset->mg_node));
2422 src_cset->mg_src_cgrp = src_cgrp;
2423 src_cset->mg_dst_cgrp = dst_cgrp;
2424 get_css_set(src_cset);
2425 list_add_tail(&src_cset->mg_preload_node, &mgctx->preloaded_src_csets);
2429 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2430 * @mgctx: migration context
2432 * Tasks are about to be moved and all the source css_sets have been
2433 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2434 * pins all destination css_sets, links each to its source, and append them
2435 * to @mgctx->preloaded_dst_csets.
2437 * This function must be called after cgroup_migrate_add_src() has been
2438 * called on each migration source css_set. After migration is performed
2439 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2442 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2444 struct css_set *src_cset, *tmp_cset;
2446 lockdep_assert_held(&cgroup_mutex);
2448 /* look up the dst cset for each src cset and link it to src */
2449 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2451 struct css_set *dst_cset;
2452 struct cgroup_subsys *ss;
2455 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2459 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2462 * If src cset equals dst, it's noop. Drop the src.
2463 * cgroup_migrate() will skip the cset too. Note that we
2464 * can't handle src == dst as some nodes are used by both.
2466 if (src_cset == dst_cset) {
2467 src_cset->mg_src_cgrp = NULL;
2468 src_cset->mg_dst_cgrp = NULL;
2469 list_del_init(&src_cset->mg_preload_node);
2470 put_css_set(src_cset);
2471 put_css_set(dst_cset);
2475 src_cset->mg_dst_cset = dst_cset;
2477 if (list_empty(&dst_cset->mg_preload_node))
2478 list_add_tail(&dst_cset->mg_preload_node,
2479 &mgctx->preloaded_dst_csets);
2481 put_css_set(dst_cset);
2483 for_each_subsys(ss, ssid)
2484 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2485 mgctx->ss_mask |= 1 << ssid;
2490 cgroup_migrate_finish(mgctx);
2495 * cgroup_migrate - migrate a process or task to a cgroup
2496 * @leader: the leader of the process or the task to migrate
2497 * @threadgroup: whether @leader points to the whole process or a single task
2498 * @mgctx: migration context
2500 * Migrate a process or task denoted by @leader. If migrating a process,
2501 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2502 * responsible for invoking cgroup_migrate_add_src() and
2503 * cgroup_migrate_prepare_dst() on the targets before invoking this
2504 * function and following up with cgroup_migrate_finish().
2506 * As long as a controller's ->can_attach() doesn't fail, this function is
2507 * guaranteed to succeed. This means that, excluding ->can_attach()
2508 * failure, when migrating multiple targets, the success or failure can be
2509 * decided for all targets by invoking group_migrate_prepare_dst() before
2510 * actually starting migrating.
2512 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2513 struct cgroup_mgctx *mgctx)
2515 struct task_struct *task;
2518 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2519 * already PF_EXITING could be freed from underneath us unless we
2520 * take an rcu_read_lock.
2522 spin_lock_irq(&css_set_lock);
2526 cgroup_migrate_add_task(task, mgctx);
2529 } while_each_thread(leader, task);
2531 spin_unlock_irq(&css_set_lock);
2533 return cgroup_migrate_execute(mgctx);
2537 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2538 * @dst_cgrp: the cgroup to attach to
2539 * @leader: the task or the leader of the threadgroup to be attached
2540 * @threadgroup: attach the whole threadgroup?
2542 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2544 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2547 DEFINE_CGROUP_MGCTX(mgctx);
2548 struct task_struct *task;
2551 ret = cgroup_migrate_vet_dst(dst_cgrp);
2555 /* look up all src csets */
2556 spin_lock_irq(&css_set_lock);
2560 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2563 } while_each_thread(leader, task);
2565 spin_unlock_irq(&css_set_lock);
2567 /* prepare dst csets and commit */
2568 ret = cgroup_migrate_prepare_dst(&mgctx);
2570 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2572 cgroup_migrate_finish(&mgctx);
2575 trace_cgroup_attach_task(dst_cgrp, leader, threadgroup);
2580 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup)
2581 __acquires(&cgroup_threadgroup_rwsem)
2583 struct task_struct *tsk;
2586 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2587 return ERR_PTR(-EINVAL);
2589 percpu_down_write(&cgroup_threadgroup_rwsem);
2593 tsk = find_task_by_vpid(pid);
2595 tsk = ERR_PTR(-ESRCH);
2596 goto out_unlock_threadgroup;
2603 tsk = tsk->group_leader;
2606 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2607 * If userland migrates such a kthread to a non-root cgroup, it can
2608 * become trapped in a cpuset, or RT kthread may be born in a
2609 * cgroup with no rt_runtime allocated. Just say no.
2611 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2612 tsk = ERR_PTR(-EINVAL);
2613 goto out_unlock_threadgroup;
2616 get_task_struct(tsk);
2617 goto out_unlock_rcu;
2619 out_unlock_threadgroup:
2620 percpu_up_write(&cgroup_threadgroup_rwsem);
2626 void cgroup_procs_write_finish(struct task_struct *task)
2627 __releases(&cgroup_threadgroup_rwsem)
2629 struct cgroup_subsys *ss;
2632 /* release reference from cgroup_procs_write_start() */
2633 put_task_struct(task);
2635 percpu_up_write(&cgroup_threadgroup_rwsem);
2636 for_each_subsys(ss, ssid)
2637 if (ss->post_attach)
2641 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2643 struct cgroup_subsys *ss;
2644 bool printed = false;
2647 do_each_subsys_mask(ss, ssid, ss_mask) {
2650 seq_printf(seq, "%s", ss->name);
2652 } while_each_subsys_mask();
2654 seq_putc(seq, '\n');
2657 /* show controllers which are enabled from the parent */
2658 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2660 struct cgroup *cgrp = seq_css(seq)->cgroup;
2662 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2666 /* show controllers which are enabled for a given cgroup's children */
2667 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2669 struct cgroup *cgrp = seq_css(seq)->cgroup;
2671 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2676 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2677 * @cgrp: root of the subtree to update csses for
2679 * @cgrp's control masks have changed and its subtree's css associations
2680 * need to be updated accordingly. This function looks up all css_sets
2681 * which are attached to the subtree, creates the matching updated css_sets
2682 * and migrates the tasks to the new ones.
2684 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2686 DEFINE_CGROUP_MGCTX(mgctx);
2687 struct cgroup_subsys_state *d_css;
2688 struct cgroup *dsct;
2689 struct css_set *src_cset;
2692 lockdep_assert_held(&cgroup_mutex);
2694 percpu_down_write(&cgroup_threadgroup_rwsem);
2696 /* look up all csses currently attached to @cgrp's subtree */
2697 spin_lock_irq(&css_set_lock);
2698 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2699 struct cgrp_cset_link *link;
2701 list_for_each_entry(link, &dsct->cset_links, cset_link)
2702 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2704 spin_unlock_irq(&css_set_lock);
2706 /* NULL dst indicates self on default hierarchy */
2707 ret = cgroup_migrate_prepare_dst(&mgctx);
2711 spin_lock_irq(&css_set_lock);
2712 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets, mg_preload_node) {
2713 struct task_struct *task, *ntask;
2715 /* all tasks in src_csets need to be migrated */
2716 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2717 cgroup_migrate_add_task(task, &mgctx);
2719 spin_unlock_irq(&css_set_lock);
2721 ret = cgroup_migrate_execute(&mgctx);
2723 cgroup_migrate_finish(&mgctx);
2724 percpu_up_write(&cgroup_threadgroup_rwsem);
2729 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2730 * @cgrp: root of the target subtree
2732 * Because css offlining is asynchronous, userland may try to re-enable a
2733 * controller while the previous css is still around. This function grabs
2734 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2736 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2737 __acquires(&cgroup_mutex)
2739 struct cgroup *dsct;
2740 struct cgroup_subsys_state *d_css;
2741 struct cgroup_subsys *ss;
2745 mutex_lock(&cgroup_mutex);
2747 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2748 for_each_subsys(ss, ssid) {
2749 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2752 if (!css || !percpu_ref_is_dying(&css->refcnt))
2755 cgroup_get_live(dsct);
2756 prepare_to_wait(&dsct->offline_waitq, &wait,
2757 TASK_UNINTERRUPTIBLE);
2759 mutex_unlock(&cgroup_mutex);
2761 finish_wait(&dsct->offline_waitq, &wait);
2770 * cgroup_save_control - save control masks of a subtree
2771 * @cgrp: root of the target subtree
2773 * Save ->subtree_control and ->subtree_ss_mask to the respective old_
2774 * prefixed fields for @cgrp's subtree including @cgrp itself.
2776 static void cgroup_save_control(struct cgroup *cgrp)
2778 struct cgroup *dsct;
2779 struct cgroup_subsys_state *d_css;
2781 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2782 dsct->old_subtree_control = dsct->subtree_control;
2783 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
2788 * cgroup_propagate_control - refresh control masks of a subtree
2789 * @cgrp: root of the target subtree
2791 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
2792 * ->subtree_control and propagate controller availability through the
2793 * subtree so that descendants don't have unavailable controllers enabled.
2795 static void cgroup_propagate_control(struct cgroup *cgrp)
2797 struct cgroup *dsct;
2798 struct cgroup_subsys_state *d_css;
2800 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2801 dsct->subtree_control &= cgroup_control(dsct);
2802 dsct->subtree_ss_mask =
2803 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
2804 cgroup_ss_mask(dsct));
2809 * cgroup_restore_control - restore control masks of a subtree
2810 * @cgrp: root of the target subtree
2812 * Restore ->subtree_control and ->subtree_ss_mask from the respective old_
2813 * prefixed fields for @cgrp's subtree including @cgrp itself.
2815 static void cgroup_restore_control(struct cgroup *cgrp)
2817 struct cgroup *dsct;
2818 struct cgroup_subsys_state *d_css;
2820 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2821 dsct->subtree_control = dsct->old_subtree_control;
2822 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
2826 static bool css_visible(struct cgroup_subsys_state *css)
2828 struct cgroup_subsys *ss = css->ss;
2829 struct cgroup *cgrp = css->cgroup;
2831 if (cgroup_control(cgrp) & (1 << ss->id))
2833 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
2835 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
2839 * cgroup_apply_control_enable - enable or show csses according to control
2840 * @cgrp: root of the target subtree
2842 * Walk @cgrp's subtree and create new csses or make the existing ones
2843 * visible. A css is created invisible if it's being implicitly enabled
2844 * through dependency. An invisible css is made visible when the userland
2845 * explicitly enables it.
2847 * Returns 0 on success, -errno on failure. On failure, csses which have
2848 * been processed already aren't cleaned up. The caller is responsible for
2849 * cleaning up with cgroup_apply_control_disable().
2851 static int cgroup_apply_control_enable(struct cgroup *cgrp)
2853 struct cgroup *dsct;
2854 struct cgroup_subsys_state *d_css;
2855 struct cgroup_subsys *ss;
2858 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2859 for_each_subsys(ss, ssid) {
2860 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2862 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
2864 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
2868 css = css_create(dsct, ss);
2870 return PTR_ERR(css);
2873 if (css_visible(css)) {
2874 ret = css_populate_dir(css);
2885 * cgroup_apply_control_disable - kill or hide csses according to control
2886 * @cgrp: root of the target subtree
2888 * Walk @cgrp's subtree and kill and hide csses so that they match
2889 * cgroup_ss_mask() and cgroup_visible_mask().
2891 * A css is hidden when the userland requests it to be disabled while other
2892 * subsystems are still depending on it. The css must not actively control
2893 * resources and be in the vanilla state if it's made visible again later.
2894 * Controllers which may be depended upon should provide ->css_reset() for
2897 static void cgroup_apply_control_disable(struct cgroup *cgrp)
2899 struct cgroup *dsct;
2900 struct cgroup_subsys_state *d_css;
2901 struct cgroup_subsys *ss;
2904 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2905 for_each_subsys(ss, ssid) {
2906 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2908 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
2914 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
2916 } else if (!css_visible(css)) {
2926 * cgroup_apply_control - apply control mask updates to the subtree
2927 * @cgrp: root of the target subtree
2929 * subsystems can be enabled and disabled in a subtree using the following
2932 * 1. Call cgroup_save_control() to stash the current state.
2933 * 2. Update ->subtree_control masks in the subtree as desired.
2934 * 3. Call cgroup_apply_control() to apply the changes.
2935 * 4. Optionally perform other related operations.
2936 * 5. Call cgroup_finalize_control() to finish up.
2938 * This function implements step 3 and propagates the mask changes
2939 * throughout @cgrp's subtree, updates csses accordingly and perform
2940 * process migrations.
2942 static int cgroup_apply_control(struct cgroup *cgrp)
2946 cgroup_propagate_control(cgrp);
2948 ret = cgroup_apply_control_enable(cgrp);
2953 * At this point, cgroup_e_css() results reflect the new csses
2954 * making the following cgroup_update_dfl_csses() properly update
2955 * css associations of all tasks in the subtree.
2957 ret = cgroup_update_dfl_csses(cgrp);
2965 * cgroup_finalize_control - finalize control mask update
2966 * @cgrp: root of the target subtree
2967 * @ret: the result of the update
2969 * Finalize control mask update. See cgroup_apply_control() for more info.
2971 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
2974 cgroup_restore_control(cgrp);
2975 cgroup_propagate_control(cgrp);
2978 cgroup_apply_control_disable(cgrp);
2981 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
2983 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
2985 /* if nothing is getting enabled, nothing to worry about */
2989 /* can @cgrp host any resources? */
2990 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
2993 /* mixables don't care */
2994 if (cgroup_is_mixable(cgrp))
2997 if (domain_enable) {
2998 /* can't enable domain controllers inside a thread subtree */
2999 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3003 * Threaded controllers can handle internal competitions
3004 * and are always allowed inside a (prospective) thread
3007 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3012 * Controllers can't be enabled for a cgroup with tasks to avoid
3013 * child cgroups competing against tasks.
3015 if (cgroup_has_tasks(cgrp))
3021 /* change the enabled child controllers for a cgroup in the default hierarchy */
3022 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3023 char *buf, size_t nbytes,
3026 u16 enable = 0, disable = 0;
3027 struct cgroup *cgrp, *child;
3028 struct cgroup_subsys *ss;
3033 * Parse input - space separated list of subsystem names prefixed
3034 * with either + or -.
3036 buf = strstrip(buf);
3037 while ((tok = strsep(&buf, " "))) {
3040 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3041 if (!cgroup_ssid_enabled(ssid) ||
3042 strcmp(tok + 1, ss->name))
3046 enable |= 1 << ssid;
3047 disable &= ~(1 << ssid);
3048 } else if (*tok == '-') {
3049 disable |= 1 << ssid;
3050 enable &= ~(1 << ssid);
3055 } while_each_subsys_mask();
3056 if (ssid == CGROUP_SUBSYS_COUNT)
3060 cgrp = cgroup_kn_lock_live(of->kn, true);
3064 for_each_subsys(ss, ssid) {
3065 if (enable & (1 << ssid)) {
3066 if (cgrp->subtree_control & (1 << ssid)) {
3067 enable &= ~(1 << ssid);
3071 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3075 } else if (disable & (1 << ssid)) {
3076 if (!(cgrp->subtree_control & (1 << ssid))) {
3077 disable &= ~(1 << ssid);
3081 /* a child has it enabled? */
3082 cgroup_for_each_live_child(child, cgrp) {
3083 if (child->subtree_control & (1 << ssid)) {
3091 if (!enable && !disable) {
3096 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3100 /* save and update control masks and prepare csses */
3101 cgroup_save_control(cgrp);
3103 cgrp->subtree_control |= enable;
3104 cgrp->subtree_control &= ~disable;
3106 ret = cgroup_apply_control(cgrp);
3108 cgroup_finalize_control(cgrp, ret);
3110 kernfs_activate(cgrp->kn);
3113 cgroup_kn_unlock(of->kn);
3114 return ret ?: nbytes;
3118 * cgroup_enable_threaded - make @cgrp threaded
3119 * @cgrp: the target cgroup
3121 * Called when "threaded" is written to the cgroup.type interface file and
3122 * tries to make @cgrp threaded and join the parent's resource domain.
3123 * This function is never called on the root cgroup as cgroup.type doesn't
3126 static int cgroup_enable_threaded(struct cgroup *cgrp)
3128 struct cgroup *parent = cgroup_parent(cgrp);
3129 struct cgroup *dom_cgrp = parent->dom_cgrp;
3132 lockdep_assert_held(&cgroup_mutex);
3134 /* noop if already threaded */
3135 if (cgroup_is_threaded(cgrp))
3138 /* we're joining the parent's domain, ensure its validity */
3139 if (!cgroup_is_valid_domain(dom_cgrp) ||
3140 !cgroup_can_be_thread_root(dom_cgrp))
3144 * The following shouldn't cause actual migrations and should
3147 cgroup_save_control(cgrp);
3149 cgrp->dom_cgrp = dom_cgrp;
3150 ret = cgroup_apply_control(cgrp);
3152 parent->nr_threaded_children++;
3154 cgrp->dom_cgrp = cgrp;
3156 cgroup_finalize_control(cgrp, ret);
3160 static int cgroup_type_show(struct seq_file *seq, void *v)
3162 struct cgroup *cgrp = seq_css(seq)->cgroup;
3164 if (cgroup_is_threaded(cgrp))
3165 seq_puts(seq, "threaded\n");
3166 else if (!cgroup_is_valid_domain(cgrp))
3167 seq_puts(seq, "domain invalid\n");
3168 else if (cgroup_is_thread_root(cgrp))
3169 seq_puts(seq, "domain threaded\n");
3171 seq_puts(seq, "domain\n");
3176 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3177 size_t nbytes, loff_t off)
3179 struct cgroup *cgrp;
3182 /* only switching to threaded mode is supported */
3183 if (strcmp(strstrip(buf), "threaded"))
3186 cgrp = cgroup_kn_lock_live(of->kn, false);
3190 /* threaded can only be enabled */
3191 ret = cgroup_enable_threaded(cgrp);
3193 cgroup_kn_unlock(of->kn);
3194 return ret ?: nbytes;
3197 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3199 struct cgroup *cgrp = seq_css(seq)->cgroup;
3200 int descendants = READ_ONCE(cgrp->max_descendants);
3202 if (descendants == INT_MAX)
3203 seq_puts(seq, "max\n");
3205 seq_printf(seq, "%d\n", descendants);
3210 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3211 char *buf, size_t nbytes, loff_t off)
3213 struct cgroup *cgrp;
3217 buf = strstrip(buf);
3218 if (!strcmp(buf, "max")) {
3219 descendants = INT_MAX;
3221 ret = kstrtoint(buf, 0, &descendants);
3226 if (descendants < 0 || descendants > INT_MAX)
3229 cgrp = cgroup_kn_lock_live(of->kn, false);
3233 cgrp->max_descendants = descendants;
3235 cgroup_kn_unlock(of->kn);
3240 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3242 struct cgroup *cgrp = seq_css(seq)->cgroup;
3243 int depth = READ_ONCE(cgrp->max_depth);
3245 if (depth == INT_MAX)
3246 seq_puts(seq, "max\n");
3248 seq_printf(seq, "%d\n", depth);
3253 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3254 char *buf, size_t nbytes, loff_t off)
3256 struct cgroup *cgrp;
3260 buf = strstrip(buf);
3261 if (!strcmp(buf, "max")) {
3264 ret = kstrtoint(buf, 0, &depth);
3269 if (depth < 0 || depth > INT_MAX)
3272 cgrp = cgroup_kn_lock_live(of->kn, false);
3276 cgrp->max_depth = depth;
3278 cgroup_kn_unlock(of->kn);
3283 static int cgroup_events_show(struct seq_file *seq, void *v)
3285 seq_printf(seq, "populated %d\n",
3286 cgroup_is_populated(seq_css(seq)->cgroup));
3290 static int cgroup_stat_show(struct seq_file *seq, void *v)
3292 struct cgroup *cgroup = seq_css(seq)->cgroup;
3294 seq_printf(seq, "nr_descendants %d\n",
3295 cgroup->nr_descendants);
3296 seq_printf(seq, "nr_dying_descendants %d\n",
3297 cgroup->nr_dying_descendants);
3302 static int cgroup_file_open(struct kernfs_open_file *of)
3304 struct cftype *cft = of->kn->priv;
3307 return cft->open(of);
3311 static void cgroup_file_release(struct kernfs_open_file *of)
3313 struct cftype *cft = of->kn->priv;
3319 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3320 size_t nbytes, loff_t off)
3322 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
3323 struct cgroup *cgrp = of->kn->parent->priv;
3324 struct cftype *cft = of->kn->priv;
3325 struct cgroup_subsys_state *css;
3329 * If namespaces are delegation boundaries, disallow writes to
3330 * files in an non-init namespace root from inside the namespace
3331 * except for the files explicitly marked delegatable -
3332 * cgroup.procs and cgroup.subtree_control.
3334 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3335 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3336 ns != &init_cgroup_ns && ns->root_cset->dfl_cgrp == cgrp)
3340 return cft->write(of, buf, nbytes, off);
3343 * kernfs guarantees that a file isn't deleted with operations in
3344 * flight, which means that the matching css is and stays alive and
3345 * doesn't need to be pinned. The RCU locking is not necessary
3346 * either. It's just for the convenience of using cgroup_css().
3349 css = cgroup_css(cgrp, cft->ss);
3352 if (cft->write_u64) {
3353 unsigned long long v;
3354 ret = kstrtoull(buf, 0, &v);
3356 ret = cft->write_u64(css, cft, v);
3357 } else if (cft->write_s64) {
3359 ret = kstrtoll(buf, 0, &v);
3361 ret = cft->write_s64(css, cft, v);
3366 return ret ?: nbytes;
3369 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3371 return seq_cft(seq)->seq_start(seq, ppos);
3374 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3376 return seq_cft(seq)->seq_next(seq, v, ppos);
3379 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3381 if (seq_cft(seq)->seq_stop)
3382 seq_cft(seq)->seq_stop(seq, v);
3385 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3387 struct cftype *cft = seq_cft(m);
3388 struct cgroup_subsys_state *css = seq_css(m);
3391 return cft->seq_show(m, arg);
3394 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3395 else if (cft->read_s64)
3396 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3402 static struct kernfs_ops cgroup_kf_single_ops = {
3403 .atomic_write_len = PAGE_SIZE,
3404 .open = cgroup_file_open,
3405 .release = cgroup_file_release,
3406 .write = cgroup_file_write,
3407 .seq_show = cgroup_seqfile_show,
3410 static struct kernfs_ops cgroup_kf_ops = {
3411 .atomic_write_len = PAGE_SIZE,
3412 .open = cgroup_file_open,
3413 .release = cgroup_file_release,
3414 .write = cgroup_file_write,
3415 .seq_start = cgroup_seqfile_start,
3416 .seq_next = cgroup_seqfile_next,
3417 .seq_stop = cgroup_seqfile_stop,
3418 .seq_show = cgroup_seqfile_show,
3421 /* set uid and gid of cgroup dirs and files to that of the creator */
3422 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3424 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3425 .ia_uid = current_fsuid(),
3426 .ia_gid = current_fsgid(), };
3428 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3429 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3432 return kernfs_setattr(kn, &iattr);
3435 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
3438 char name[CGROUP_FILE_NAME_MAX];
3439 struct kernfs_node *kn;
3440 struct lock_class_key *key = NULL;
3443 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3444 key = &cft->lockdep_key;
3446 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3447 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
3452 ret = cgroup_kn_set_ugid(kn);
3458 if (cft->file_offset) {
3459 struct cgroup_file *cfile = (void *)css + cft->file_offset;
3461 spin_lock_irq(&cgroup_file_kn_lock);
3463 spin_unlock_irq(&cgroup_file_kn_lock);
3470 * cgroup_addrm_files - add or remove files to a cgroup directory
3471 * @css: the target css
3472 * @cgrp: the target cgroup (usually css->cgroup)
3473 * @cfts: array of cftypes to be added
3474 * @is_add: whether to add or remove
3476 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3477 * For removals, this function never fails.
3479 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
3480 struct cgroup *cgrp, struct cftype cfts[],
3483 struct cftype *cft, *cft_end = NULL;
3486 lockdep_assert_held(&cgroup_mutex);
3489 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
3490 /* does cft->flags tell us to skip this file on @cgrp? */
3491 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3493 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3495 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3497 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3501 ret = cgroup_add_file(css, cgrp, cft);
3503 pr_warn("%s: failed to add %s, err=%d\n",
3504 __func__, cft->name, ret);
3510 cgroup_rm_file(cgrp, cft);
3516 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3518 struct cgroup_subsys *ss = cfts[0].ss;
3519 struct cgroup *root = &ss->root->cgrp;
3520 struct cgroup_subsys_state *css;
3523 lockdep_assert_held(&cgroup_mutex);
3525 /* add/rm files for all cgroups created before */
3526 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3527 struct cgroup *cgrp = css->cgroup;
3529 if (!(css->flags & CSS_VISIBLE))
3532 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
3538 kernfs_activate(root->kn);
3542 static void cgroup_exit_cftypes(struct cftype *cfts)
3546 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3547 /* free copy for custom atomic_write_len, see init_cftypes() */
3548 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3553 /* revert flags set by cgroup core while adding @cfts */
3554 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3558 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3562 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3563 struct kernfs_ops *kf_ops;
3565 WARN_ON(cft->ss || cft->kf_ops);
3568 kf_ops = &cgroup_kf_ops;
3570 kf_ops = &cgroup_kf_single_ops;
3573 * Ugh... if @cft wants a custom max_write_len, we need to
3574 * make a copy of kf_ops to set its atomic_write_len.
3576 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3577 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3579 cgroup_exit_cftypes(cfts);
3582 kf_ops->atomic_write_len = cft->max_write_len;
3585 cft->kf_ops = kf_ops;
3592 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3594 lockdep_assert_held(&cgroup_mutex);
3596 if (!cfts || !cfts[0].ss)
3599 list_del(&cfts->node);
3600 cgroup_apply_cftypes(cfts, false);
3601 cgroup_exit_cftypes(cfts);
3606 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3607 * @cfts: zero-length name terminated array of cftypes
3609 * Unregister @cfts. Files described by @cfts are removed from all
3610 * existing cgroups and all future cgroups won't have them either. This
3611 * function can be called anytime whether @cfts' subsys is attached or not.
3613 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3616 int cgroup_rm_cftypes(struct cftype *cfts)
3620 mutex_lock(&cgroup_mutex);
3621 ret = cgroup_rm_cftypes_locked(cfts);
3622 mutex_unlock(&cgroup_mutex);
3627 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3628 * @ss: target cgroup subsystem
3629 * @cfts: zero-length name terminated array of cftypes
3631 * Register @cfts to @ss. Files described by @cfts are created for all
3632 * existing cgroups to which @ss is attached and all future cgroups will
3633 * have them too. This function can be called anytime whether @ss is
3636 * Returns 0 on successful registration, -errno on failure. Note that this
3637 * function currently returns 0 as long as @cfts registration is successful
3638 * even if some file creation attempts on existing cgroups fail.
3640 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3644 if (!cgroup_ssid_enabled(ss->id))
3647 if (!cfts || cfts[0].name[0] == '\0')
3650 ret = cgroup_init_cftypes(ss, cfts);
3654 mutex_lock(&cgroup_mutex);
3656 list_add_tail(&cfts->node, &ss->cfts);
3657 ret = cgroup_apply_cftypes(cfts, true);
3659 cgroup_rm_cftypes_locked(cfts);
3661 mutex_unlock(&cgroup_mutex);
3666 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3667 * @ss: target cgroup subsystem
3668 * @cfts: zero-length name terminated array of cftypes
3670 * Similar to cgroup_add_cftypes() but the added files are only used for
3671 * the default hierarchy.
3673 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3677 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3678 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3679 return cgroup_add_cftypes(ss, cfts);
3683 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3684 * @ss: target cgroup subsystem
3685 * @cfts: zero-length name terminated array of cftypes
3687 * Similar to cgroup_add_cftypes() but the added files are only used for
3688 * the legacy hierarchies.
3690 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3694 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3695 cft->flags |= __CFTYPE_NOT_ON_DFL;
3696 return cgroup_add_cftypes(ss, cfts);
3700 * cgroup_file_notify - generate a file modified event for a cgroup_file
3701 * @cfile: target cgroup_file
3703 * @cfile must have been obtained by setting cftype->file_offset.
3705 void cgroup_file_notify(struct cgroup_file *cfile)
3707 unsigned long flags;
3709 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
3711 kernfs_notify(cfile->kn);
3712 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
3716 * css_next_child - find the next child of a given css
3717 * @pos: the current position (%NULL to initiate traversal)
3718 * @parent: css whose children to walk
3720 * This function returns the next child of @parent and should be called
3721 * under either cgroup_mutex or RCU read lock. The only requirement is
3722 * that @parent and @pos are accessible. The next sibling is guaranteed to
3723 * be returned regardless of their states.
3725 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3726 * css which finished ->css_online() is guaranteed to be visible in the
3727 * future iterations and will stay visible until the last reference is put.
3728 * A css which hasn't finished ->css_online() or already finished
3729 * ->css_offline() may show up during traversal. It's each subsystem's
3730 * responsibility to synchronize against on/offlining.
3732 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3733 struct cgroup_subsys_state *parent)
3735 struct cgroup_subsys_state *next;
3737 cgroup_assert_mutex_or_rcu_locked();
3740 * @pos could already have been unlinked from the sibling list.
3741 * Once a cgroup is removed, its ->sibling.next is no longer
3742 * updated when its next sibling changes. CSS_RELEASED is set when
3743 * @pos is taken off list, at which time its next pointer is valid,
3744 * and, as releases are serialized, the one pointed to by the next
3745 * pointer is guaranteed to not have started release yet. This
3746 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3747 * critical section, the one pointed to by its next pointer is
3748 * guaranteed to not have finished its RCU grace period even if we
3749 * have dropped rcu_read_lock() inbetween iterations.
3751 * If @pos has CSS_RELEASED set, its next pointer can't be
3752 * dereferenced; however, as each css is given a monotonically
3753 * increasing unique serial number and always appended to the
3754 * sibling list, the next one can be found by walking the parent's
3755 * children until the first css with higher serial number than
3756 * @pos's. While this path can be slower, it happens iff iteration
3757 * races against release and the race window is very small.
3760 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3761 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3762 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3764 list_for_each_entry_rcu(next, &parent->children, sibling)
3765 if (next->serial_nr > pos->serial_nr)
3770 * @next, if not pointing to the head, can be dereferenced and is
3773 if (&next->sibling != &parent->children)
3779 * css_next_descendant_pre - find the next descendant for pre-order walk
3780 * @pos: the current position (%NULL to initiate traversal)
3781 * @root: css whose descendants to walk
3783 * To be used by css_for_each_descendant_pre(). Find the next descendant
3784 * to visit for pre-order traversal of @root's descendants. @root is
3785 * included in the iteration and the first node to be visited.
3787 * While this function requires cgroup_mutex or RCU read locking, it
3788 * doesn't require the whole traversal to be contained in a single critical
3789 * section. This function will return the correct next descendant as long
3790 * as both @pos and @root are accessible and @pos is a descendant of @root.
3792 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3793 * css which finished ->css_online() is guaranteed to be visible in the
3794 * future iterations and will stay visible until the last reference is put.
3795 * A css which hasn't finished ->css_online() or already finished
3796 * ->css_offline() may show up during traversal. It's each subsystem's
3797 * responsibility to synchronize against on/offlining.
3799 struct cgroup_subsys_state *
3800 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3801 struct cgroup_subsys_state *root)
3803 struct cgroup_subsys_state *next;
3805 cgroup_assert_mutex_or_rcu_locked();
3807 /* if first iteration, visit @root */
3811 /* visit the first child if exists */
3812 next = css_next_child(NULL, pos);
3816 /* no child, visit my or the closest ancestor's next sibling */
3817 while (pos != root) {
3818 next = css_next_child(pos, pos->parent);
3828 * css_rightmost_descendant - return the rightmost descendant of a css
3829 * @pos: css of interest
3831 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3832 * is returned. This can be used during pre-order traversal to skip
3835 * While this function requires cgroup_mutex or RCU read locking, it
3836 * doesn't require the whole traversal to be contained in a single critical
3837 * section. This function will return the correct rightmost descendant as
3838 * long as @pos is accessible.
3840 struct cgroup_subsys_state *
3841 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3843 struct cgroup_subsys_state *last, *tmp;
3845 cgroup_assert_mutex_or_rcu_locked();
3849 /* ->prev isn't RCU safe, walk ->next till the end */
3851 css_for_each_child(tmp, last)
3858 static struct cgroup_subsys_state *
3859 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3861 struct cgroup_subsys_state *last;
3865 pos = css_next_child(NULL, pos);
3872 * css_next_descendant_post - find the next descendant for post-order walk
3873 * @pos: the current position (%NULL to initiate traversal)
3874 * @root: css whose descendants to walk
3876 * To be used by css_for_each_descendant_post(). Find the next descendant
3877 * to visit for post-order traversal of @root's descendants. @root is
3878 * included in the iteration and the last node to be visited.
3880 * While this function requires cgroup_mutex or RCU read locking, it
3881 * doesn't require the whole traversal to be contained in a single critical
3882 * section. This function will return the correct next descendant as long
3883 * as both @pos and @cgroup are accessible and @pos is a descendant of
3886 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3887 * css which finished ->css_online() is guaranteed to be visible in the
3888 * future iterations and will stay visible until the last reference is put.
3889 * A css which hasn't finished ->css_online() or already finished
3890 * ->css_offline() may show up during traversal. It's each subsystem's
3891 * responsibility to synchronize against on/offlining.
3893 struct cgroup_subsys_state *
3894 css_next_descendant_post(struct cgroup_subsys_state *pos,
3895 struct cgroup_subsys_state *root)
3897 struct cgroup_subsys_state *next;
3899 cgroup_assert_mutex_or_rcu_locked();
3901 /* if first iteration, visit leftmost descendant which may be @root */
3903 return css_leftmost_descendant(root);
3905 /* if we visited @root, we're done */
3909 /* if there's an unvisited sibling, visit its leftmost descendant */
3910 next = css_next_child(pos, pos->parent);
3912 return css_leftmost_descendant(next);
3914 /* no sibling left, visit parent */
3919 * css_has_online_children - does a css have online children
3920 * @css: the target css
3922 * Returns %true if @css has any online children; otherwise, %false. This
3923 * function can be called from any context but the caller is responsible
3924 * for synchronizing against on/offlining as necessary.
3926 bool css_has_online_children(struct cgroup_subsys_state *css)
3928 struct cgroup_subsys_state *child;
3932 css_for_each_child(child, css) {
3933 if (child->flags & CSS_ONLINE) {
3942 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
3944 struct list_head *l;
3945 struct cgrp_cset_link *link;
3946 struct css_set *cset;
3948 lockdep_assert_held(&css_set_lock);
3950 /* find the next threaded cset */
3951 if (it->tcset_pos) {
3952 l = it->tcset_pos->next;
3954 if (l != it->tcset_head) {
3956 return container_of(l, struct css_set,
3957 threaded_csets_node);
3960 it->tcset_pos = NULL;
3963 /* find the next cset */
3966 if (l == it->cset_head) {
3967 it->cset_pos = NULL;
3972 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
3974 link = list_entry(l, struct cgrp_cset_link, cset_link);
3980 /* initialize threaded css_set walking */
3981 if (it->flags & CSS_TASK_ITER_THREADED) {
3983 put_css_set_locked(it->cur_dcset);
3984 it->cur_dcset = cset;
3987 it->tcset_head = &cset->threaded_csets;
3988 it->tcset_pos = &cset->threaded_csets;
3995 * css_task_iter_advance_css_set - advance a task itererator to the next css_set
3996 * @it: the iterator to advance
3998 * Advance @it to the next css_set to walk.
4000 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4002 struct css_set *cset;
4004 lockdep_assert_held(&css_set_lock);
4006 /* Advance to the next non-empty css_set */
4008 cset = css_task_iter_next_css_set(it);
4010 it->task_pos = NULL;
4013 } while (!css_set_populated(cset));
4015 if (!list_empty(&cset->tasks))
4016 it->task_pos = cset->tasks.next;
4018 it->task_pos = cset->mg_tasks.next;
4020 it->tasks_head = &cset->tasks;
4021 it->mg_tasks_head = &cset->mg_tasks;
4024 * We don't keep css_sets locked across iteration steps and thus
4025 * need to take steps to ensure that iteration can be resumed after
4026 * the lock is re-acquired. Iteration is performed at two levels -
4027 * css_sets and tasks in them.
4029 * Once created, a css_set never leaves its cgroup lists, so a
4030 * pinned css_set is guaranteed to stay put and we can resume
4031 * iteration afterwards.
4033 * Tasks may leave @cset across iteration steps. This is resolved
4034 * by registering each iterator with the css_set currently being
4035 * walked and making css_set_move_task() advance iterators whose
4036 * next task is leaving.
4039 list_del(&it->iters_node);
4040 put_css_set_locked(it->cur_cset);
4043 it->cur_cset = cset;
4044 list_add(&it->iters_node, &cset->task_iters);
4047 static void css_task_iter_advance(struct css_task_iter *it)
4049 struct list_head *l = it->task_pos;
4051 lockdep_assert_held(&css_set_lock);
4056 * Advance iterator to find next entry. cset->tasks is consumed
4057 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
4062 if (l == it->tasks_head)
4063 l = it->mg_tasks_head->next;
4065 if (l == it->mg_tasks_head)
4066 css_task_iter_advance_css_set(it);
4070 /* if PROCS, skip over tasks which aren't group leaders */
4071 if ((it->flags & CSS_TASK_ITER_PROCS) && it->task_pos &&
4072 !thread_group_leader(list_entry(it->task_pos, struct task_struct,
4078 * css_task_iter_start - initiate task iteration
4079 * @css: the css to walk tasks of
4080 * @flags: CSS_TASK_ITER_* flags
4081 * @it: the task iterator to use
4083 * Initiate iteration through the tasks of @css. The caller can call
4084 * css_task_iter_next() to walk through the tasks until the function
4085 * returns NULL. On completion of iteration, css_task_iter_end() must be
4088 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4089 struct css_task_iter *it)
4091 /* no one should try to iterate before mounting cgroups */
4092 WARN_ON_ONCE(!use_task_css_set_links);
4094 memset(it, 0, sizeof(*it));
4096 spin_lock_irq(&css_set_lock);
4102 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4104 it->cset_pos = &css->cgroup->cset_links;
4106 it->cset_head = it->cset_pos;
4108 css_task_iter_advance_css_set(it);
4110 spin_unlock_irq(&css_set_lock);
4114 * css_task_iter_next - return the next task for the iterator
4115 * @it: the task iterator being iterated
4117 * The "next" function for task iteration. @it should have been
4118 * initialized via css_task_iter_start(). Returns NULL when the iteration
4121 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4124 put_task_struct(it->cur_task);
4125 it->cur_task = NULL;
4128 spin_lock_irq(&css_set_lock);
4131 it->cur_task = list_entry(it->task_pos, struct task_struct,
4133 get_task_struct(it->cur_task);
4134 css_task_iter_advance(it);
4137 spin_unlock_irq(&css_set_lock);
4139 return it->cur_task;
4143 * css_task_iter_end - finish task iteration
4144 * @it: the task iterator to finish
4146 * Finish task iteration started by css_task_iter_start().
4148 void css_task_iter_end(struct css_task_iter *it)
4151 spin_lock_irq(&css_set_lock);
4152 list_del(&it->iters_node);
4153 put_css_set_locked(it->cur_cset);
4154 spin_unlock_irq(&css_set_lock);
4158 put_css_set(it->cur_dcset);
4161 put_task_struct(it->cur_task);
4164 static void cgroup_procs_release(struct kernfs_open_file *of)
4167 css_task_iter_end(of->priv);
4172 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
4174 struct kernfs_open_file *of = s->private;
4175 struct css_task_iter *it = of->priv;
4177 return css_task_iter_next(it);
4180 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
4181 unsigned int iter_flags)
4183 struct kernfs_open_file *of = s->private;
4184 struct cgroup *cgrp = seq_css(s)->cgroup;
4185 struct css_task_iter *it = of->priv;
4188 * When a seq_file is seeked, it's always traversed sequentially
4189 * from position 0, so we can simply keep iterating on !0 *pos.
4192 if (WARN_ON_ONCE((*pos)++))
4193 return ERR_PTR(-EINVAL);
4195 it = kzalloc(sizeof(*it), GFP_KERNEL);
4197 return ERR_PTR(-ENOMEM);
4199 css_task_iter_start(&cgrp->self, iter_flags, it);
4200 } else if (!(*pos)++) {
4201 css_task_iter_end(it);
4202 css_task_iter_start(&cgrp->self, iter_flags, it);
4205 return cgroup_procs_next(s, NULL, NULL);
4208 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
4210 struct cgroup *cgrp = seq_css(s)->cgroup;
4213 * All processes of a threaded subtree belong to the domain cgroup
4214 * of the subtree. Only threads can be distributed across the
4215 * subtree. Reject reads on cgroup.procs in the subtree proper.
4216 * They're always empty anyway.
4218 if (cgroup_is_threaded(cgrp))
4219 return ERR_PTR(-EOPNOTSUPP);
4221 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
4222 CSS_TASK_ITER_THREADED);
4225 static int cgroup_procs_show(struct seq_file *s, void *v)
4227 seq_printf(s, "%d\n", task_pid_vnr(v));
4231 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
4232 struct cgroup *dst_cgrp,
4233 struct super_block *sb)
4235 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
4236 struct cgroup *com_cgrp = src_cgrp;
4237 struct inode *inode;
4240 lockdep_assert_held(&cgroup_mutex);
4242 /* find the common ancestor */
4243 while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
4244 com_cgrp = cgroup_parent(com_cgrp);
4246 /* %current should be authorized to migrate to the common ancestor */
4247 inode = kernfs_get_inode(sb, com_cgrp->procs_file.kn);
4251 ret = inode_permission(inode, MAY_WRITE);
4257 * If namespaces are delegation boundaries, %current must be able
4258 * to see both source and destination cgroups from its namespace.
4260 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
4261 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
4262 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
4268 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
4269 char *buf, size_t nbytes, loff_t off)
4271 struct cgroup *src_cgrp, *dst_cgrp;
4272 struct task_struct *task;
4275 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4279 task = cgroup_procs_write_start(buf, true);
4280 ret = PTR_ERR_OR_ZERO(task);
4284 /* find the source cgroup */
4285 spin_lock_irq(&css_set_lock);
4286 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4287 spin_unlock_irq(&css_set_lock);
4289 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4290 of->file->f_path.dentry->d_sb);
4294 ret = cgroup_attach_task(dst_cgrp, task, true);
4297 cgroup_procs_write_finish(task);
4299 cgroup_kn_unlock(of->kn);
4301 return ret ?: nbytes;
4304 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
4306 return __cgroup_procs_start(s, pos, 0);
4309 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
4310 char *buf, size_t nbytes, loff_t off)
4312 struct cgroup *src_cgrp, *dst_cgrp;
4313 struct task_struct *task;
4316 buf = strstrip(buf);
4318 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4322 task = cgroup_procs_write_start(buf, false);
4323 ret = PTR_ERR_OR_ZERO(task);
4327 /* find the source cgroup */
4328 spin_lock_irq(&css_set_lock);
4329 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4330 spin_unlock_irq(&css_set_lock);
4332 /* thread migrations follow the cgroup.procs delegation rule */
4333 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4334 of->file->f_path.dentry->d_sb);
4338 /* and must be contained in the same domain */
4340 if (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp)
4343 ret = cgroup_attach_task(dst_cgrp, task, false);
4346 cgroup_procs_write_finish(task);
4348 cgroup_kn_unlock(of->kn);
4350 return ret ?: nbytes;
4353 /* cgroup core interface files for the default hierarchy */
4354 static struct cftype cgroup_base_files[] = {
4356 .name = "cgroup.type",
4357 .flags = CFTYPE_NOT_ON_ROOT,
4358 .seq_show = cgroup_type_show,
4359 .write = cgroup_type_write,
4362 .name = "cgroup.procs",
4363 .flags = CFTYPE_NS_DELEGATABLE,
4364 .file_offset = offsetof(struct cgroup, procs_file),
4365 .release = cgroup_procs_release,
4366 .seq_start = cgroup_procs_start,
4367 .seq_next = cgroup_procs_next,
4368 .seq_show = cgroup_procs_show,
4369 .write = cgroup_procs_write,
4372 .name = "cgroup.threads",
4373 .release = cgroup_procs_release,
4374 .seq_start = cgroup_threads_start,
4375 .seq_next = cgroup_procs_next,
4376 .seq_show = cgroup_procs_show,
4377 .write = cgroup_threads_write,
4380 .name = "cgroup.controllers",
4381 .seq_show = cgroup_controllers_show,
4384 .name = "cgroup.subtree_control",
4385 .flags = CFTYPE_NS_DELEGATABLE,
4386 .seq_show = cgroup_subtree_control_show,
4387 .write = cgroup_subtree_control_write,
4390 .name = "cgroup.events",
4391 .flags = CFTYPE_NOT_ON_ROOT,
4392 .file_offset = offsetof(struct cgroup, events_file),
4393 .seq_show = cgroup_events_show,
4396 .name = "cgroup.max.descendants",
4397 .seq_show = cgroup_max_descendants_show,
4398 .write = cgroup_max_descendants_write,
4401 .name = "cgroup.max.depth",
4402 .seq_show = cgroup_max_depth_show,
4403 .write = cgroup_max_depth_write,
4406 .name = "cgroup.stat",
4407 .seq_show = cgroup_stat_show,
4413 * css destruction is four-stage process.
4415 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4416 * Implemented in kill_css().
4418 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4419 * and thus css_tryget_online() is guaranteed to fail, the css can be
4420 * offlined by invoking offline_css(). After offlining, the base ref is
4421 * put. Implemented in css_killed_work_fn().
4423 * 3. When the percpu_ref reaches zero, the only possible remaining
4424 * accessors are inside RCU read sections. css_release() schedules the
4427 * 4. After the grace period, the css can be freed. Implemented in
4428 * css_free_work_fn().
4430 * It is actually hairier because both step 2 and 4 require process context
4431 * and thus involve punting to css->destroy_work adding two additional
4432 * steps to the already complex sequence.
4434 static void css_free_work_fn(struct work_struct *work)
4436 struct cgroup_subsys_state *css =
4437 container_of(work, struct cgroup_subsys_state, destroy_work);
4438 struct cgroup_subsys *ss = css->ss;
4439 struct cgroup *cgrp = css->cgroup;
4441 percpu_ref_exit(&css->refcnt);
4445 struct cgroup_subsys_state *parent = css->parent;
4449 cgroup_idr_remove(&ss->css_idr, id);
4455 /* cgroup free path */
4456 atomic_dec(&cgrp->root->nr_cgrps);
4457 cgroup1_pidlist_destroy_all(cgrp);
4458 cancel_work_sync(&cgrp->release_agent_work);
4460 if (cgroup_parent(cgrp)) {
4462 * We get a ref to the parent, and put the ref when
4463 * this cgroup is being freed, so it's guaranteed
4464 * that the parent won't be destroyed before its
4467 cgroup_put(cgroup_parent(cgrp));
4468 kernfs_put(cgrp->kn);
4472 * This is root cgroup's refcnt reaching zero,
4473 * which indicates that the root should be
4476 cgroup_destroy_root(cgrp->root);
4481 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4483 struct cgroup_subsys_state *css =
4484 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4486 INIT_WORK(&css->destroy_work, css_free_work_fn);
4487 queue_work(cgroup_destroy_wq, &css->destroy_work);
4490 static void css_release_work_fn(struct work_struct *work)
4492 struct cgroup_subsys_state *css =
4493 container_of(work, struct cgroup_subsys_state, destroy_work);
4494 struct cgroup_subsys *ss = css->ss;
4495 struct cgroup *cgrp = css->cgroup;
4497 mutex_lock(&cgroup_mutex);
4499 css->flags |= CSS_RELEASED;
4500 list_del_rcu(&css->sibling);
4503 /* css release path */
4504 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4505 if (ss->css_released)
4506 ss->css_released(css);
4508 struct cgroup *tcgrp;
4510 /* cgroup release path */
4511 trace_cgroup_release(cgrp);
4513 for (tcgrp = cgroup_parent(cgrp); tcgrp;
4514 tcgrp = cgroup_parent(tcgrp))
4515 tcgrp->nr_dying_descendants--;
4517 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4521 * There are two control paths which try to determine
4522 * cgroup from dentry without going through kernfs -
4523 * cgroupstats_build() and css_tryget_online_from_dir().
4524 * Those are supported by RCU protecting clearing of
4525 * cgrp->kn->priv backpointer.
4528 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
4531 cgroup_bpf_put(cgrp);
4534 mutex_unlock(&cgroup_mutex);
4536 call_rcu(&css->rcu_head, css_free_rcu_fn);
4539 static void css_release(struct percpu_ref *ref)
4541 struct cgroup_subsys_state *css =
4542 container_of(ref, struct cgroup_subsys_state, refcnt);
4544 INIT_WORK(&css->destroy_work, css_release_work_fn);
4545 queue_work(cgroup_destroy_wq, &css->destroy_work);
4548 static void init_and_link_css(struct cgroup_subsys_state *css,
4549 struct cgroup_subsys *ss, struct cgroup *cgrp)
4551 lockdep_assert_held(&cgroup_mutex);
4553 cgroup_get_live(cgrp);
4555 memset(css, 0, sizeof(*css));
4559 INIT_LIST_HEAD(&css->sibling);
4560 INIT_LIST_HEAD(&css->children);
4561 css->serial_nr = css_serial_nr_next++;
4562 atomic_set(&css->online_cnt, 0);
4564 if (cgroup_parent(cgrp)) {
4565 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4566 css_get(css->parent);
4569 BUG_ON(cgroup_css(cgrp, ss));
4572 /* invoke ->css_online() on a new CSS and mark it online if successful */
4573 static int online_css(struct cgroup_subsys_state *css)
4575 struct cgroup_subsys *ss = css->ss;
4578 lockdep_assert_held(&cgroup_mutex);
4581 ret = ss->css_online(css);
4583 css->flags |= CSS_ONLINE;
4584 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4586 atomic_inc(&css->online_cnt);
4588 atomic_inc(&css->parent->online_cnt);
4593 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4594 static void offline_css(struct cgroup_subsys_state *css)
4596 struct cgroup_subsys *ss = css->ss;
4598 lockdep_assert_held(&cgroup_mutex);
4600 if (!(css->flags & CSS_ONLINE))
4606 if (ss->css_offline)
4607 ss->css_offline(css);
4609 css->flags &= ~CSS_ONLINE;
4610 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4612 wake_up_all(&css->cgroup->offline_waitq);
4616 * css_create - create a cgroup_subsys_state
4617 * @cgrp: the cgroup new css will be associated with
4618 * @ss: the subsys of new css
4620 * Create a new css associated with @cgrp - @ss pair. On success, the new
4621 * css is online and installed in @cgrp. This function doesn't create the
4622 * interface files. Returns 0 on success, -errno on failure.
4624 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
4625 struct cgroup_subsys *ss)
4627 struct cgroup *parent = cgroup_parent(cgrp);
4628 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4629 struct cgroup_subsys_state *css;
4632 lockdep_assert_held(&cgroup_mutex);
4634 css = ss->css_alloc(parent_css);
4636 css = ERR_PTR(-ENOMEM);
4640 init_and_link_css(css, ss, cgrp);
4642 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4646 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
4651 /* @css is ready to be brought online now, make it visible */
4652 list_add_tail_rcu(&css->sibling, &parent_css->children);
4653 cgroup_idr_replace(&ss->css_idr, css, css->id);
4655 err = online_css(css);
4659 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4660 cgroup_parent(parent)) {
4661 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4662 current->comm, current->pid, ss->name);
4663 if (!strcmp(ss->name, "memory"))
4664 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4665 ss->warned_broken_hierarchy = true;
4671 list_del_rcu(&css->sibling);
4673 call_rcu(&css->rcu_head, css_free_rcu_fn);
4674 return ERR_PTR(err);
4678 * The returned cgroup is fully initialized including its control mask, but
4679 * it isn't associated with its kernfs_node and doesn't have the control
4682 static struct cgroup *cgroup_create(struct cgroup *parent)
4684 struct cgroup_root *root = parent->root;
4685 struct cgroup *cgrp, *tcgrp;
4686 int level = parent->level + 1;
4689 /* allocate the cgroup and its ID, 0 is reserved for the root */
4690 cgrp = kzalloc(sizeof(*cgrp) +
4691 sizeof(cgrp->ancestor_ids[0]) * (level + 1), GFP_KERNEL);
4693 return ERR_PTR(-ENOMEM);
4695 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
4700 * Temporarily set the pointer to NULL, so idr_find() won't return
4701 * a half-baked cgroup.
4703 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
4706 goto out_cancel_ref;
4709 init_cgroup_housekeeping(cgrp);
4711 cgrp->self.parent = &parent->self;
4713 cgrp->level = level;
4715 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
4716 cgrp->ancestor_ids[tcgrp->level] = tcgrp->id;
4719 tcgrp->nr_descendants++;
4722 if (notify_on_release(parent))
4723 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4725 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4726 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4728 cgrp->self.serial_nr = css_serial_nr_next++;
4730 /* allocation complete, commit to creation */
4731 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4732 atomic_inc(&root->nr_cgrps);
4733 cgroup_get_live(parent);
4736 * @cgrp is now fully operational. If something fails after this
4737 * point, it'll be released via the normal destruction path.
4739 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4742 * On the default hierarchy, a child doesn't automatically inherit
4743 * subtree_control from the parent. Each is configured manually.
4745 if (!cgroup_on_dfl(cgrp))
4746 cgrp->subtree_control = cgroup_control(cgrp);
4749 cgroup_bpf_inherit(cgrp, parent);
4751 cgroup_propagate_control(cgrp);
4756 percpu_ref_exit(&cgrp->self.refcnt);
4759 return ERR_PTR(ret);
4762 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
4764 struct cgroup *cgroup;
4768 lockdep_assert_held(&cgroup_mutex);
4770 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
4771 if (cgroup->nr_descendants >= cgroup->max_descendants)
4774 if (level > cgroup->max_depth)
4785 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
4787 struct cgroup *parent, *cgrp;
4788 struct kernfs_node *kn;
4791 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
4792 if (strchr(name, '\n'))
4795 parent = cgroup_kn_lock_live(parent_kn, false);
4799 if (!cgroup_check_hierarchy_limits(parent)) {
4804 cgrp = cgroup_create(parent);
4806 ret = PTR_ERR(cgrp);
4810 /* create the directory */
4811 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4819 * This extra ref will be put in cgroup_free_fn() and guarantees
4820 * that @cgrp->kn is always accessible.
4824 ret = cgroup_kn_set_ugid(kn);
4828 ret = css_populate_dir(&cgrp->self);
4832 ret = cgroup_apply_control_enable(cgrp);
4836 trace_cgroup_mkdir(cgrp);
4838 /* let's create and online css's */
4839 kernfs_activate(kn);
4845 cgroup_destroy_locked(cgrp);
4847 cgroup_kn_unlock(parent_kn);
4852 * This is called when the refcnt of a css is confirmed to be killed.
4853 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
4854 * initate destruction and put the css ref from kill_css().
4856 static void css_killed_work_fn(struct work_struct *work)
4858 struct cgroup_subsys_state *css =
4859 container_of(work, struct cgroup_subsys_state, destroy_work);
4861 mutex_lock(&cgroup_mutex);
4866 /* @css can't go away while we're holding cgroup_mutex */
4868 } while (css && atomic_dec_and_test(&css->online_cnt));
4870 mutex_unlock(&cgroup_mutex);
4873 /* css kill confirmation processing requires process context, bounce */
4874 static void css_killed_ref_fn(struct percpu_ref *ref)
4876 struct cgroup_subsys_state *css =
4877 container_of(ref, struct cgroup_subsys_state, refcnt);
4879 if (atomic_dec_and_test(&css->online_cnt)) {
4880 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4881 queue_work(cgroup_destroy_wq, &css->destroy_work);
4886 * kill_css - destroy a css
4887 * @css: css to destroy
4889 * This function initiates destruction of @css by removing cgroup interface
4890 * files and putting its base reference. ->css_offline() will be invoked
4891 * asynchronously once css_tryget_online() is guaranteed to fail and when
4892 * the reference count reaches zero, @css will be released.
4894 static void kill_css(struct cgroup_subsys_state *css)
4896 lockdep_assert_held(&cgroup_mutex);
4898 if (css->flags & CSS_DYING)
4901 css->flags |= CSS_DYING;
4904 * This must happen before css is disassociated with its cgroup.
4905 * See seq_css() for details.
4910 * Killing would put the base ref, but we need to keep it alive
4911 * until after ->css_offline().
4916 * cgroup core guarantees that, by the time ->css_offline() is
4917 * invoked, no new css reference will be given out via
4918 * css_tryget_online(). We can't simply call percpu_ref_kill() and
4919 * proceed to offlining css's because percpu_ref_kill() doesn't
4920 * guarantee that the ref is seen as killed on all CPUs on return.
4922 * Use percpu_ref_kill_and_confirm() to get notifications as each
4923 * css is confirmed to be seen as killed on all CPUs.
4925 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4929 * cgroup_destroy_locked - the first stage of cgroup destruction
4930 * @cgrp: cgroup to be destroyed
4932 * css's make use of percpu refcnts whose killing latency shouldn't be
4933 * exposed to userland and are RCU protected. Also, cgroup core needs to
4934 * guarantee that css_tryget_online() won't succeed by the time
4935 * ->css_offline() is invoked. To satisfy all the requirements,
4936 * destruction is implemented in the following two steps.
4938 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4939 * userland visible parts and start killing the percpu refcnts of
4940 * css's. Set up so that the next stage will be kicked off once all
4941 * the percpu refcnts are confirmed to be killed.
4943 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4944 * rest of destruction. Once all cgroup references are gone, the
4945 * cgroup is RCU-freed.
4947 * This function implements s1. After this step, @cgrp is gone as far as
4948 * the userland is concerned and a new cgroup with the same name may be
4949 * created. As cgroup doesn't care about the names internally, this
4950 * doesn't cause any problem.
4952 static int cgroup_destroy_locked(struct cgroup *cgrp)
4953 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4955 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
4956 struct cgroup_subsys_state *css;
4957 struct cgrp_cset_link *link;
4960 lockdep_assert_held(&cgroup_mutex);
4963 * Only migration can raise populated from zero and we're already
4964 * holding cgroup_mutex.
4966 if (cgroup_is_populated(cgrp))
4970 * Make sure there's no live children. We can't test emptiness of
4971 * ->self.children as dead children linger on it while being
4972 * drained; otherwise, "rmdir parent/child parent" may fail.
4974 if (css_has_online_children(&cgrp->self))
4978 * Mark @cgrp and the associated csets dead. The former prevents
4979 * further task migration and child creation by disabling
4980 * cgroup_lock_live_group(). The latter makes the csets ignored by
4981 * the migration path.
4983 cgrp->self.flags &= ~CSS_ONLINE;
4985 spin_lock_irq(&css_set_lock);
4986 list_for_each_entry(link, &cgrp->cset_links, cset_link)
4987 link->cset->dead = true;
4988 spin_unlock_irq(&css_set_lock);
4990 /* initiate massacre of all css's */
4991 for_each_css(css, ssid, cgrp)
4995 * Remove @cgrp directory along with the base files. @cgrp has an
4996 * extra ref on its kn.
4998 kernfs_remove(cgrp->kn);
5000 if (parent && cgroup_is_threaded(cgrp))
5001 parent->nr_threaded_children--;
5003 for (tcgrp = cgroup_parent(cgrp); tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5004 tcgrp->nr_descendants--;
5005 tcgrp->nr_dying_descendants++;
5008 cgroup1_check_for_release(parent);
5010 /* put the base reference */
5011 percpu_ref_kill(&cgrp->self.refcnt);
5016 int cgroup_rmdir(struct kernfs_node *kn)
5018 struct cgroup *cgrp;
5021 cgrp = cgroup_kn_lock_live(kn, false);
5025 ret = cgroup_destroy_locked(cgrp);
5028 trace_cgroup_rmdir(cgrp);
5030 cgroup_kn_unlock(kn);
5034 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5035 .show_options = cgroup_show_options,
5036 .remount_fs = cgroup_remount,
5037 .mkdir = cgroup_mkdir,
5038 .rmdir = cgroup_rmdir,
5039 .show_path = cgroup_show_path,
5042 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5044 struct cgroup_subsys_state *css;
5046 pr_debug("Initializing cgroup subsys %s\n", ss->name);
5048 mutex_lock(&cgroup_mutex);
5050 idr_init(&ss->css_idr);
5051 INIT_LIST_HEAD(&ss->cfts);
5053 /* Create the root cgroup state for this subsystem */
5054 ss->root = &cgrp_dfl_root;
5055 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5056 /* We don't handle early failures gracefully */
5057 BUG_ON(IS_ERR(css));
5058 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5061 * Root csses are never destroyed and we can't initialize
5062 * percpu_ref during early init. Disable refcnting.
5064 css->flags |= CSS_NO_REF;
5067 /* allocation can't be done safely during early init */
5070 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5071 BUG_ON(css->id < 0);
5074 /* Update the init_css_set to contain a subsys
5075 * pointer to this state - since the subsystem is
5076 * newly registered, all tasks and hence the
5077 * init_css_set is in the subsystem's root cgroup. */
5078 init_css_set.subsys[ss->id] = css;
5080 have_fork_callback |= (bool)ss->fork << ss->id;
5081 have_exit_callback |= (bool)ss->exit << ss->id;
5082 have_free_callback |= (bool)ss->free << ss->id;
5083 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5085 /* At system boot, before all subsystems have been
5086 * registered, no tasks have been forked, so we don't
5087 * need to invoke fork callbacks here. */
5088 BUG_ON(!list_empty(&init_task.tasks));
5090 BUG_ON(online_css(css));
5092 mutex_unlock(&cgroup_mutex);
5096 * cgroup_init_early - cgroup initialization at system boot
5098 * Initialize cgroups at system boot, and initialize any
5099 * subsystems that request early init.
5101 int __init cgroup_init_early(void)
5103 static struct cgroup_sb_opts __initdata opts;
5104 struct cgroup_subsys *ss;
5107 init_cgroup_root(&cgrp_dfl_root, &opts);
5108 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5110 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5112 for_each_subsys(ss, i) {
5113 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5114 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
5115 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5117 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5118 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5121 ss->name = cgroup_subsys_name[i];
5122 if (!ss->legacy_name)
5123 ss->legacy_name = cgroup_subsys_name[i];
5126 cgroup_init_subsys(ss, true);
5131 static u16 cgroup_disable_mask __initdata;
5134 * cgroup_init - cgroup initialization
5136 * Register cgroup filesystem and /proc file, and initialize
5137 * any subsystems that didn't request early init.
5139 int __init cgroup_init(void)
5141 struct cgroup_subsys *ss;
5144 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
5145 BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
5146 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
5147 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
5150 * The latency of the synchronize_sched() is too high for cgroups,
5151 * avoid it at the cost of forcing all readers into the slow path.
5153 rcu_sync_enter_start(&cgroup_threadgroup_rwsem.rss);
5155 get_user_ns(init_cgroup_ns.user_ns);
5157 mutex_lock(&cgroup_mutex);
5160 * Add init_css_set to the hash table so that dfl_root can link to
5163 hash_add(css_set_table, &init_css_set.hlist,
5164 css_set_hash(init_css_set.subsys));
5166 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0, 0));
5168 mutex_unlock(&cgroup_mutex);
5170 for_each_subsys(ss, ssid) {
5171 if (ss->early_init) {
5172 struct cgroup_subsys_state *css =
5173 init_css_set.subsys[ss->id];
5175 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5177 BUG_ON(css->id < 0);
5179 cgroup_init_subsys(ss, false);
5182 list_add_tail(&init_css_set.e_cset_node[ssid],
5183 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5186 * Setting dfl_root subsys_mask needs to consider the
5187 * disabled flag and cftype registration needs kmalloc,
5188 * both of which aren't available during early_init.
5190 if (cgroup_disable_mask & (1 << ssid)) {
5191 static_branch_disable(cgroup_subsys_enabled_key[ssid]);
5192 printk(KERN_INFO "Disabling %s control group subsystem\n",
5197 if (cgroup1_ssid_disabled(ssid))
5198 printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
5201 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5203 /* implicit controllers must be threaded too */
5204 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
5206 if (ss->implicit_on_dfl)
5207 cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
5208 else if (!ss->dfl_cftypes)
5209 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
5212 cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
5214 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5215 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5217 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5218 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5222 ss->bind(init_css_set.subsys[ssid]);
5225 /* init_css_set.subsys[] has been updated, re-hash */
5226 hash_del(&init_css_set.hlist);
5227 hash_add(css_set_table, &init_css_set.hlist,
5228 css_set_hash(init_css_set.subsys));
5230 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
5231 WARN_ON(register_filesystem(&cgroup_fs_type));
5232 WARN_ON(register_filesystem(&cgroup2_fs_type));
5233 WARN_ON(!proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations));
5238 static int __init cgroup_wq_init(void)
5241 * There isn't much point in executing destruction path in
5242 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5243 * Use 1 for @max_active.
5245 * We would prefer to do this in cgroup_init() above, but that
5246 * is called before init_workqueues(): so leave this until after.
5248 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5249 BUG_ON(!cgroup_destroy_wq);
5252 core_initcall(cgroup_wq_init);
5255 * proc_cgroup_show()
5256 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5257 * - Used for /proc/<pid>/cgroup.
5259 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5260 struct pid *pid, struct task_struct *tsk)
5264 struct cgroup_root *root;
5267 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5271 mutex_lock(&cgroup_mutex);
5272 spin_lock_irq(&css_set_lock);
5274 for_each_root(root) {
5275 struct cgroup_subsys *ss;
5276 struct cgroup *cgrp;
5277 int ssid, count = 0;
5279 if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
5282 seq_printf(m, "%d:", root->hierarchy_id);
5283 if (root != &cgrp_dfl_root)
5284 for_each_subsys(ss, ssid)
5285 if (root->subsys_mask & (1 << ssid))
5286 seq_printf(m, "%s%s", count++ ? "," : "",
5288 if (strlen(root->name))
5289 seq_printf(m, "%sname=%s", count ? "," : "",
5293 cgrp = task_cgroup_from_root(tsk, root);
5296 * On traditional hierarchies, all zombie tasks show up as
5297 * belonging to the root cgroup. On the default hierarchy,
5298 * while a zombie doesn't show up in "cgroup.procs" and
5299 * thus can't be migrated, its /proc/PID/cgroup keeps
5300 * reporting the cgroup it belonged to before exiting. If
5301 * the cgroup is removed before the zombie is reaped,
5302 * " (deleted)" is appended to the cgroup path.
5304 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
5305 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
5306 current->nsproxy->cgroup_ns);
5307 if (retval >= PATH_MAX)
5308 retval = -ENAMETOOLONG;
5317 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
5318 seq_puts(m, " (deleted)\n");
5325 spin_unlock_irq(&css_set_lock);
5326 mutex_unlock(&cgroup_mutex);
5333 * cgroup_fork - initialize cgroup related fields during copy_process()
5334 * @child: pointer to task_struct of forking parent process.
5336 * A task is associated with the init_css_set until cgroup_post_fork()
5337 * attaches it to the parent's css_set. Empty cg_list indicates that
5338 * @child isn't holding reference to its css_set.
5340 void cgroup_fork(struct task_struct *child)
5342 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5343 INIT_LIST_HEAD(&child->cg_list);
5347 * cgroup_can_fork - called on a new task before the process is exposed
5348 * @child: the task in question.
5350 * This calls the subsystem can_fork() callbacks. If the can_fork() callback
5351 * returns an error, the fork aborts with that error code. This allows for
5352 * a cgroup subsystem to conditionally allow or deny new forks.
5354 int cgroup_can_fork(struct task_struct *child)
5356 struct cgroup_subsys *ss;
5359 do_each_subsys_mask(ss, i, have_canfork_callback) {
5360 ret = ss->can_fork(child);
5363 } while_each_subsys_mask();
5368 for_each_subsys(ss, j) {
5371 if (ss->cancel_fork)
5372 ss->cancel_fork(child);
5379 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
5380 * @child: the task in question
5382 * This calls the cancel_fork() callbacks if a fork failed *after*
5383 * cgroup_can_fork() succeded.
5385 void cgroup_cancel_fork(struct task_struct *child)
5387 struct cgroup_subsys *ss;
5390 for_each_subsys(ss, i)
5391 if (ss->cancel_fork)
5392 ss->cancel_fork(child);
5396 * cgroup_post_fork - called on a new task after adding it to the task list
5397 * @child: the task in question
5399 * Adds the task to the list running through its css_set if necessary and
5400 * call the subsystem fork() callbacks. Has to be after the task is
5401 * visible on the task list in case we race with the first call to
5402 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5405 void cgroup_post_fork(struct task_struct *child)
5407 struct cgroup_subsys *ss;
5411 * This may race against cgroup_enable_task_cg_lists(). As that
5412 * function sets use_task_css_set_links before grabbing
5413 * tasklist_lock and we just went through tasklist_lock to add
5414 * @child, it's guaranteed that either we see the set
5415 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5416 * @child during its iteration.
5418 * If we won the race, @child is associated with %current's
5419 * css_set. Grabbing css_set_lock guarantees both that the
5420 * association is stable, and, on completion of the parent's
5421 * migration, @child is visible in the source of migration or
5422 * already in the destination cgroup. This guarantee is necessary
5423 * when implementing operations which need to migrate all tasks of
5424 * a cgroup to another.
5426 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5427 * will remain in init_css_set. This is safe because all tasks are
5428 * in the init_css_set before cg_links is enabled and there's no
5429 * operation which transfers all tasks out of init_css_set.
5431 if (use_task_css_set_links) {
5432 struct css_set *cset;
5434 spin_lock_irq(&css_set_lock);
5435 cset = task_css_set(current);
5436 if (list_empty(&child->cg_list)) {
5439 css_set_move_task(child, NULL, cset, false);
5441 spin_unlock_irq(&css_set_lock);
5445 * Call ss->fork(). This must happen after @child is linked on
5446 * css_set; otherwise, @child might change state between ->fork()
5447 * and addition to css_set.
5449 do_each_subsys_mask(ss, i, have_fork_callback) {
5451 } while_each_subsys_mask();
5455 * cgroup_exit - detach cgroup from exiting task
5456 * @tsk: pointer to task_struct of exiting process
5458 * Description: Detach cgroup from @tsk and release it.
5460 * Note that cgroups marked notify_on_release force every task in
5461 * them to take the global cgroup_mutex mutex when exiting.
5462 * This could impact scaling on very large systems. Be reluctant to
5463 * use notify_on_release cgroups where very high task exit scaling
5464 * is required on large systems.
5466 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5467 * call cgroup_exit() while the task is still competent to handle
5468 * notify_on_release(), then leave the task attached to the root cgroup in
5469 * each hierarchy for the remainder of its exit. No need to bother with
5470 * init_css_set refcnting. init_css_set never goes away and we can't race
5471 * with migration path - PF_EXITING is visible to migration path.
5473 void cgroup_exit(struct task_struct *tsk)
5475 struct cgroup_subsys *ss;
5476 struct css_set *cset;
5480 * Unlink from @tsk from its css_set. As migration path can't race
5481 * with us, we can check css_set and cg_list without synchronization.
5483 cset = task_css_set(tsk);
5485 if (!list_empty(&tsk->cg_list)) {
5486 spin_lock_irq(&css_set_lock);
5487 css_set_move_task(tsk, cset, NULL, false);
5489 spin_unlock_irq(&css_set_lock);
5494 /* see cgroup_post_fork() for details */
5495 do_each_subsys_mask(ss, i, have_exit_callback) {
5497 } while_each_subsys_mask();
5500 void cgroup_free(struct task_struct *task)
5502 struct css_set *cset = task_css_set(task);
5503 struct cgroup_subsys *ss;
5506 do_each_subsys_mask(ss, ssid, have_free_callback) {
5508 } while_each_subsys_mask();
5513 static int __init cgroup_disable(char *str)
5515 struct cgroup_subsys *ss;
5519 while ((token = strsep(&str, ",")) != NULL) {
5523 for_each_subsys(ss, i) {
5524 if (strcmp(token, ss->name) &&
5525 strcmp(token, ss->legacy_name))
5527 cgroup_disable_mask |= 1 << i;
5532 __setup("cgroup_disable=", cgroup_disable);
5535 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5536 * @dentry: directory dentry of interest
5537 * @ss: subsystem of interest
5539 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5540 * to get the corresponding css and return it. If such css doesn't exist
5541 * or can't be pinned, an ERR_PTR value is returned.
5543 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5544 struct cgroup_subsys *ss)
5546 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5547 struct file_system_type *s_type = dentry->d_sb->s_type;
5548 struct cgroup_subsys_state *css = NULL;
5549 struct cgroup *cgrp;
5551 /* is @dentry a cgroup dir? */
5552 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
5553 !kn || kernfs_type(kn) != KERNFS_DIR)
5554 return ERR_PTR(-EBADF);
5559 * This path doesn't originate from kernfs and @kn could already
5560 * have been or be removed at any point. @kn->priv is RCU
5561 * protected for this access. See css_release_work_fn() for details.
5563 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
5565 css = cgroup_css(cgrp, ss);
5567 if (!css || !css_tryget_online(css))
5568 css = ERR_PTR(-ENOENT);
5575 * css_from_id - lookup css by id
5576 * @id: the cgroup id
5577 * @ss: cgroup subsys to be looked into
5579 * Returns the css if there's valid one with @id, otherwise returns NULL.
5580 * Should be called under rcu_read_lock().
5582 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5584 WARN_ON_ONCE(!rcu_read_lock_held());
5585 return idr_find(&ss->css_idr, id);
5589 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
5590 * @path: path on the default hierarchy
5592 * Find the cgroup at @path on the default hierarchy, increment its
5593 * reference count and return it. Returns pointer to the found cgroup on
5594 * success, ERR_PTR(-ENOENT) if @path doens't exist and ERR_PTR(-ENOTDIR)
5595 * if @path points to a non-directory.
5597 struct cgroup *cgroup_get_from_path(const char *path)
5599 struct kernfs_node *kn;
5600 struct cgroup *cgrp;
5602 mutex_lock(&cgroup_mutex);
5604 kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
5606 if (kernfs_type(kn) == KERNFS_DIR) {
5608 cgroup_get_live(cgrp);
5610 cgrp = ERR_PTR(-ENOTDIR);
5614 cgrp = ERR_PTR(-ENOENT);
5617 mutex_unlock(&cgroup_mutex);
5620 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
5623 * cgroup_get_from_fd - get a cgroup pointer from a fd
5624 * @fd: fd obtained by open(cgroup2_dir)
5626 * Find the cgroup from a fd which should be obtained
5627 * by opening a cgroup directory. Returns a pointer to the
5628 * cgroup on success. ERR_PTR is returned if the cgroup
5631 struct cgroup *cgroup_get_from_fd(int fd)
5633 struct cgroup_subsys_state *css;
5634 struct cgroup *cgrp;
5639 return ERR_PTR(-EBADF);
5641 css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
5644 return ERR_CAST(css);
5647 if (!cgroup_on_dfl(cgrp)) {
5649 return ERR_PTR(-EBADF);
5654 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
5657 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
5658 * definition in cgroup-defs.h.
5660 #ifdef CONFIG_SOCK_CGROUP_DATA
5662 #if defined(CONFIG_CGROUP_NET_PRIO) || defined(CONFIG_CGROUP_NET_CLASSID)
5664 DEFINE_SPINLOCK(cgroup_sk_update_lock);
5665 static bool cgroup_sk_alloc_disabled __read_mostly;
5667 void cgroup_sk_alloc_disable(void)
5669 if (cgroup_sk_alloc_disabled)
5671 pr_info("cgroup: disabling cgroup2 socket matching due to net_prio or net_cls activation\n");
5672 cgroup_sk_alloc_disabled = true;
5677 #define cgroup_sk_alloc_disabled false
5681 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
5683 if (cgroup_sk_alloc_disabled)
5686 /* Socket clone path */
5689 * We might be cloning a socket which is left in an empty
5690 * cgroup and the cgroup might have already been rmdir'd.
5691 * Don't use cgroup_get_live().
5693 cgroup_get(sock_cgroup_ptr(skcd));
5700 struct css_set *cset;
5702 cset = task_css_set(current);
5703 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
5704 skcd->val = (unsigned long)cset->dfl_cgrp;
5713 void cgroup_sk_free(struct sock_cgroup_data *skcd)
5715 cgroup_put(sock_cgroup_ptr(skcd));
5718 #endif /* CONFIG_SOCK_CGROUP_DATA */
5720 #ifdef CONFIG_CGROUP_BPF
5721 int cgroup_bpf_update(struct cgroup *cgrp, struct bpf_prog *prog,
5722 enum bpf_attach_type type, bool overridable)
5724 struct cgroup *parent = cgroup_parent(cgrp);
5727 mutex_lock(&cgroup_mutex);
5728 ret = __cgroup_bpf_update(cgrp, parent, prog, type, overridable);
5729 mutex_unlock(&cgroup_mutex);
5732 #endif /* CONFIG_CGROUP_BPF */