cgroup: Limit event generation frequency
[linux/fpc-iii.git] / kernel / cgroup / cgroup.c
blobfdb7a582f8fcfc5efa8072c040157e84343fa859
1 /*
2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31 #include "cgroup-internal.h"
33 #include <linux/cred.h>
34 #include <linux/errno.h>
35 #include <linux/init_task.h>
36 #include <linux/kernel.h>
37 #include <linux/magic.h>
38 #include <linux/mutex.h>
39 #include <linux/mount.h>
40 #include <linux/pagemap.h>
41 #include <linux/proc_fs.h>
42 #include <linux/rcupdate.h>
43 #include <linux/sched.h>
44 #include <linux/sched/task.h>
45 #include <linux/slab.h>
46 #include <linux/spinlock.h>
47 #include <linux/percpu-rwsem.h>
48 #include <linux/string.h>
49 #include <linux/hashtable.h>
50 #include <linux/idr.h>
51 #include <linux/kthread.h>
52 #include <linux/atomic.h>
53 #include <linux/cpuset.h>
54 #include <linux/proc_ns.h>
55 #include <linux/nsproxy.h>
56 #include <linux/file.h>
57 #include <net/sock.h>
59 #define CREATE_TRACE_POINTS
60 #include <trace/events/cgroup.h>
62 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
63 MAX_CFTYPE_NAME + 2)
64 /* let's not notify more than 100 times per second */
65 #define CGROUP_FILE_NOTIFY_MIN_INTV DIV_ROUND_UP(HZ, 100)
68 * cgroup_mutex is the master lock. Any modification to cgroup or its
69 * hierarchy must be performed while holding it.
71 * css_set_lock protects task->cgroups pointer, the list of css_set
72 * objects, and the chain of tasks off each css_set.
74 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
75 * cgroup.h can use them for lockdep annotations.
77 DEFINE_MUTEX(cgroup_mutex);
78 DEFINE_SPINLOCK(css_set_lock);
80 #ifdef CONFIG_PROVE_RCU
81 EXPORT_SYMBOL_GPL(cgroup_mutex);
82 EXPORT_SYMBOL_GPL(css_set_lock);
83 #endif
86 * Protects cgroup_idr and css_idr so that IDs can be released without
87 * grabbing cgroup_mutex.
89 static DEFINE_SPINLOCK(cgroup_idr_lock);
92 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
93 * against file removal/re-creation across css hiding.
95 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
97 struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
99 #define cgroup_assert_mutex_or_rcu_locked() \
100 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
101 !lockdep_is_held(&cgroup_mutex), \
102 "cgroup_mutex or RCU read lock required");
105 * cgroup destruction makes heavy use of work items and there can be a lot
106 * of concurrent destructions. Use a separate workqueue so that cgroup
107 * destruction work items don't end up filling up max_active of system_wq
108 * which may lead to deadlock.
110 static struct workqueue_struct *cgroup_destroy_wq;
112 /* generate an array of cgroup subsystem pointers */
113 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
114 struct cgroup_subsys *cgroup_subsys[] = {
115 #include <linux/cgroup_subsys.h>
117 #undef SUBSYS
119 /* array of cgroup subsystem names */
120 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
121 static const char *cgroup_subsys_name[] = {
122 #include <linux/cgroup_subsys.h>
124 #undef SUBSYS
126 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
127 #define SUBSYS(_x) \
128 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
129 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
130 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
131 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
132 #include <linux/cgroup_subsys.h>
133 #undef SUBSYS
135 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
136 static struct static_key_true *cgroup_subsys_enabled_key[] = {
137 #include <linux/cgroup_subsys.h>
139 #undef SUBSYS
141 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
142 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
143 #include <linux/cgroup_subsys.h>
145 #undef SUBSYS
147 static DEFINE_PER_CPU(struct cgroup_cpu_stat, cgrp_dfl_root_cpu_stat);
150 * The default hierarchy, reserved for the subsystems that are otherwise
151 * unattached - it never has more than a single cgroup, and all tasks are
152 * part of that cgroup.
154 struct cgroup_root cgrp_dfl_root = { .cgrp.cpu_stat = &cgrp_dfl_root_cpu_stat };
155 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
158 * The default hierarchy always exists but is hidden until mounted for the
159 * first time. This is for backward compatibility.
161 static bool cgrp_dfl_visible;
163 /* some controllers are not supported in the default hierarchy */
164 static u16 cgrp_dfl_inhibit_ss_mask;
166 /* some controllers are implicitly enabled on the default hierarchy */
167 static u16 cgrp_dfl_implicit_ss_mask;
169 /* some controllers can be threaded on the default hierarchy */
170 static u16 cgrp_dfl_threaded_ss_mask;
172 /* The list of hierarchy roots */
173 LIST_HEAD(cgroup_roots);
174 static int cgroup_root_count;
176 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
177 static DEFINE_IDR(cgroup_hierarchy_idr);
180 * Assign a monotonically increasing serial number to csses. It guarantees
181 * cgroups with bigger numbers are newer than those with smaller numbers.
182 * Also, as csses are always appended to the parent's ->children list, it
183 * guarantees that sibling csses are always sorted in the ascending serial
184 * number order on the list. Protected by cgroup_mutex.
186 static u64 css_serial_nr_next = 1;
189 * These bitmasks identify subsystems with specific features to avoid
190 * having to do iterative checks repeatedly.
192 static u16 have_fork_callback __read_mostly;
193 static u16 have_exit_callback __read_mostly;
194 static u16 have_free_callback __read_mostly;
195 static u16 have_canfork_callback __read_mostly;
197 /* cgroup namespace for init task */
198 struct cgroup_namespace init_cgroup_ns = {
199 .count = REFCOUNT_INIT(2),
200 .user_ns = &init_user_ns,
201 .ns.ops = &cgroupns_operations,
202 .ns.inum = PROC_CGROUP_INIT_INO,
203 .root_cset = &init_css_set,
206 static struct file_system_type cgroup2_fs_type;
207 static struct cftype cgroup_base_files[];
209 static int cgroup_apply_control(struct cgroup *cgrp);
210 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
211 static void css_task_iter_advance(struct css_task_iter *it);
212 static int cgroup_destroy_locked(struct cgroup *cgrp);
213 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
214 struct cgroup_subsys *ss);
215 static void css_release(struct percpu_ref *ref);
216 static void kill_css(struct cgroup_subsys_state *css);
217 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
218 struct cgroup *cgrp, struct cftype cfts[],
219 bool is_add);
222 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
223 * @ssid: subsys ID of interest
225 * cgroup_subsys_enabled() can only be used with literal subsys names which
226 * is fine for individual subsystems but unsuitable for cgroup core. This
227 * is slower static_key_enabled() based test indexed by @ssid.
229 bool cgroup_ssid_enabled(int ssid)
231 if (CGROUP_SUBSYS_COUNT == 0)
232 return false;
234 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
238 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
239 * @cgrp: the cgroup of interest
241 * The default hierarchy is the v2 interface of cgroup and this function
242 * can be used to test whether a cgroup is on the default hierarchy for
243 * cases where a subsystem should behave differnetly depending on the
244 * interface version.
246 * The set of behaviors which change on the default hierarchy are still
247 * being determined and the mount option is prefixed with __DEVEL__.
249 * List of changed behaviors:
251 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
252 * and "name" are disallowed.
254 * - When mounting an existing superblock, mount options should match.
256 * - Remount is disallowed.
258 * - rename(2) is disallowed.
260 * - "tasks" is removed. Everything should be at process granularity. Use
261 * "cgroup.procs" instead.
263 * - "cgroup.procs" is not sorted. pids will be unique unless they got
264 * recycled inbetween reads.
266 * - "release_agent" and "notify_on_release" are removed. Replacement
267 * notification mechanism will be implemented.
269 * - "cgroup.clone_children" is removed.
271 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
272 * and its descendants contain no task; otherwise, 1. The file also
273 * generates kernfs notification which can be monitored through poll and
274 * [di]notify when the value of the file changes.
276 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
277 * take masks of ancestors with non-empty cpus/mems, instead of being
278 * moved to an ancestor.
280 * - cpuset: a task can be moved into an empty cpuset, and again it takes
281 * masks of ancestors.
283 * - memcg: use_hierarchy is on by default and the cgroup file for the flag
284 * is not created.
286 * - blkcg: blk-throttle becomes properly hierarchical.
288 * - debug: disallowed on the default hierarchy.
290 bool cgroup_on_dfl(const struct cgroup *cgrp)
292 return cgrp->root == &cgrp_dfl_root;
295 /* IDR wrappers which synchronize using cgroup_idr_lock */
296 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
297 gfp_t gfp_mask)
299 int ret;
301 idr_preload(gfp_mask);
302 spin_lock_bh(&cgroup_idr_lock);
303 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
304 spin_unlock_bh(&cgroup_idr_lock);
305 idr_preload_end();
306 return ret;
309 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
311 void *ret;
313 spin_lock_bh(&cgroup_idr_lock);
314 ret = idr_replace(idr, ptr, id);
315 spin_unlock_bh(&cgroup_idr_lock);
316 return ret;
319 static void cgroup_idr_remove(struct idr *idr, int id)
321 spin_lock_bh(&cgroup_idr_lock);
322 idr_remove(idr, id);
323 spin_unlock_bh(&cgroup_idr_lock);
326 static bool cgroup_has_tasks(struct cgroup *cgrp)
328 return cgrp->nr_populated_csets;
331 bool cgroup_is_threaded(struct cgroup *cgrp)
333 return cgrp->dom_cgrp != cgrp;
336 /* can @cgrp host both domain and threaded children? */
337 static bool cgroup_is_mixable(struct cgroup *cgrp)
340 * Root isn't under domain level resource control exempting it from
341 * the no-internal-process constraint, so it can serve as a thread
342 * root and a parent of resource domains at the same time.
344 return !cgroup_parent(cgrp);
347 /* can @cgrp become a thread root? should always be true for a thread root */
348 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
350 /* mixables don't care */
351 if (cgroup_is_mixable(cgrp))
352 return true;
354 /* domain roots can't be nested under threaded */
355 if (cgroup_is_threaded(cgrp))
356 return false;
358 /* can only have either domain or threaded children */
359 if (cgrp->nr_populated_domain_children)
360 return false;
362 /* and no domain controllers can be enabled */
363 if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
364 return false;
366 return true;
369 /* is @cgrp root of a threaded subtree? */
370 bool cgroup_is_thread_root(struct cgroup *cgrp)
372 /* thread root should be a domain */
373 if (cgroup_is_threaded(cgrp))
374 return false;
376 /* a domain w/ threaded children is a thread root */
377 if (cgrp->nr_threaded_children)
378 return true;
381 * A domain which has tasks and explicit threaded controllers
382 * enabled is a thread root.
384 if (cgroup_has_tasks(cgrp) &&
385 (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
386 return true;
388 return false;
391 /* a domain which isn't connected to the root w/o brekage can't be used */
392 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
394 /* the cgroup itself can be a thread root */
395 if (cgroup_is_threaded(cgrp))
396 return false;
398 /* but the ancestors can't be unless mixable */
399 while ((cgrp = cgroup_parent(cgrp))) {
400 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
401 return false;
402 if (cgroup_is_threaded(cgrp))
403 return false;
406 return true;
409 /* subsystems visibly enabled on a cgroup */
410 static u16 cgroup_control(struct cgroup *cgrp)
412 struct cgroup *parent = cgroup_parent(cgrp);
413 u16 root_ss_mask = cgrp->root->subsys_mask;
415 if (parent) {
416 u16 ss_mask = parent->subtree_control;
418 /* threaded cgroups can only have threaded controllers */
419 if (cgroup_is_threaded(cgrp))
420 ss_mask &= cgrp_dfl_threaded_ss_mask;
421 return ss_mask;
424 if (cgroup_on_dfl(cgrp))
425 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
426 cgrp_dfl_implicit_ss_mask);
427 return root_ss_mask;
430 /* subsystems enabled on a cgroup */
431 static u16 cgroup_ss_mask(struct cgroup *cgrp)
433 struct cgroup *parent = cgroup_parent(cgrp);
435 if (parent) {
436 u16 ss_mask = parent->subtree_ss_mask;
438 /* threaded cgroups can only have threaded controllers */
439 if (cgroup_is_threaded(cgrp))
440 ss_mask &= cgrp_dfl_threaded_ss_mask;
441 return ss_mask;
444 return cgrp->root->subsys_mask;
448 * cgroup_css - obtain a cgroup's css for the specified subsystem
449 * @cgrp: the cgroup of interest
450 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
452 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
453 * function must be called either under cgroup_mutex or rcu_read_lock() and
454 * the caller is responsible for pinning the returned css if it wants to
455 * keep accessing it outside the said locks. This function may return
456 * %NULL if @cgrp doesn't have @subsys_id enabled.
458 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
459 struct cgroup_subsys *ss)
461 if (ss)
462 return rcu_dereference_check(cgrp->subsys[ss->id],
463 lockdep_is_held(&cgroup_mutex));
464 else
465 return &cgrp->self;
469 * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
470 * @cgrp: the cgroup of interest
471 * @ss: the subsystem of interest
473 * Find and get @cgrp's css assocaited with @ss. If the css doesn't exist
474 * or is offline, %NULL is returned.
476 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
477 struct cgroup_subsys *ss)
479 struct cgroup_subsys_state *css;
481 rcu_read_lock();
482 css = cgroup_css(cgrp, ss);
483 if (!css || !css_tryget_online(css))
484 css = NULL;
485 rcu_read_unlock();
487 return css;
491 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
492 * @cgrp: the cgroup of interest
493 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
495 * Similar to cgroup_css() but returns the effective css, which is defined
496 * as the matching css of the nearest ancestor including self which has @ss
497 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
498 * function is guaranteed to return non-NULL css.
500 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
501 struct cgroup_subsys *ss)
503 lockdep_assert_held(&cgroup_mutex);
505 if (!ss)
506 return &cgrp->self;
509 * This function is used while updating css associations and thus
510 * can't test the csses directly. Test ss_mask.
512 while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
513 cgrp = cgroup_parent(cgrp);
514 if (!cgrp)
515 return NULL;
518 return cgroup_css(cgrp, ss);
522 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
523 * @cgrp: the cgroup of interest
524 * @ss: the subsystem of interest
526 * Find and get the effective css of @cgrp for @ss. The effective css is
527 * defined as the matching css of the nearest ancestor including self which
528 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
529 * the root css is returned, so this function always returns a valid css.
530 * The returned css must be put using css_put().
532 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
533 struct cgroup_subsys *ss)
535 struct cgroup_subsys_state *css;
537 rcu_read_lock();
539 do {
540 css = cgroup_css(cgrp, ss);
542 if (css && css_tryget_online(css))
543 goto out_unlock;
544 cgrp = cgroup_parent(cgrp);
545 } while (cgrp);
547 css = init_css_set.subsys[ss->id];
548 css_get(css);
549 out_unlock:
550 rcu_read_unlock();
551 return css;
554 static void cgroup_get_live(struct cgroup *cgrp)
556 WARN_ON_ONCE(cgroup_is_dead(cgrp));
557 css_get(&cgrp->self);
560 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
562 struct cgroup *cgrp = of->kn->parent->priv;
563 struct cftype *cft = of_cft(of);
566 * This is open and unprotected implementation of cgroup_css().
567 * seq_css() is only called from a kernfs file operation which has
568 * an active reference on the file. Because all the subsystem
569 * files are drained before a css is disassociated with a cgroup,
570 * the matching css from the cgroup's subsys table is guaranteed to
571 * be and stay valid until the enclosing operation is complete.
573 if (cft->ss)
574 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
575 else
576 return &cgrp->self;
578 EXPORT_SYMBOL_GPL(of_css);
581 * for_each_css - iterate all css's of a cgroup
582 * @css: the iteration cursor
583 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
584 * @cgrp: the target cgroup to iterate css's of
586 * Should be called under cgroup_[tree_]mutex.
588 #define for_each_css(css, ssid, cgrp) \
589 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
590 if (!((css) = rcu_dereference_check( \
591 (cgrp)->subsys[(ssid)], \
592 lockdep_is_held(&cgroup_mutex)))) { } \
593 else
596 * for_each_e_css - iterate all effective css's of a cgroup
597 * @css: the iteration cursor
598 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
599 * @cgrp: the target cgroup to iterate css's of
601 * Should be called under cgroup_[tree_]mutex.
603 #define for_each_e_css(css, ssid, cgrp) \
604 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
605 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
607 else
610 * do_each_subsys_mask - filter for_each_subsys with a bitmask
611 * @ss: the iteration cursor
612 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
613 * @ss_mask: the bitmask
615 * The block will only run for cases where the ssid-th bit (1 << ssid) of
616 * @ss_mask is set.
618 #define do_each_subsys_mask(ss, ssid, ss_mask) do { \
619 unsigned long __ss_mask = (ss_mask); \
620 if (!CGROUP_SUBSYS_COUNT) { /* to avoid spurious gcc warning */ \
621 (ssid) = 0; \
622 break; \
624 for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) { \
625 (ss) = cgroup_subsys[ssid]; \
628 #define while_each_subsys_mask() \
631 } while (false)
633 /* iterate over child cgrps, lock should be held throughout iteration */
634 #define cgroup_for_each_live_child(child, cgrp) \
635 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
636 if (({ lockdep_assert_held(&cgroup_mutex); \
637 cgroup_is_dead(child); })) \
639 else
641 /* walk live descendants in preorder */
642 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) \
643 css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL)) \
644 if (({ lockdep_assert_held(&cgroup_mutex); \
645 (dsct) = (d_css)->cgroup; \
646 cgroup_is_dead(dsct); })) \
648 else
650 /* walk live descendants in postorder */
651 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) \
652 css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
653 if (({ lockdep_assert_held(&cgroup_mutex); \
654 (dsct) = (d_css)->cgroup; \
655 cgroup_is_dead(dsct); })) \
657 else
660 * The default css_set - used by init and its children prior to any
661 * hierarchies being mounted. It contains a pointer to the root state
662 * for each subsystem. Also used to anchor the list of css_sets. Not
663 * reference-counted, to improve performance when child cgroups
664 * haven't been created.
666 struct css_set init_css_set = {
667 .refcount = REFCOUNT_INIT(1),
668 .dom_cset = &init_css_set,
669 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
670 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
671 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
672 .threaded_csets = LIST_HEAD_INIT(init_css_set.threaded_csets),
673 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
674 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
675 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
678 * The following field is re-initialized when this cset gets linked
679 * in cgroup_init(). However, let's initialize the field
680 * statically too so that the default cgroup can be accessed safely
681 * early during boot.
683 .dfl_cgrp = &cgrp_dfl_root.cgrp,
686 static int css_set_count = 1; /* 1 for init_css_set */
688 static bool css_set_threaded(struct css_set *cset)
690 return cset->dom_cset != cset;
694 * css_set_populated - does a css_set contain any tasks?
695 * @cset: target css_set
697 * css_set_populated() should be the same as !!cset->nr_tasks at steady
698 * state. However, css_set_populated() can be called while a task is being
699 * added to or removed from the linked list before the nr_tasks is
700 * properly updated. Hence, we can't just look at ->nr_tasks here.
702 static bool css_set_populated(struct css_set *cset)
704 lockdep_assert_held(&css_set_lock);
706 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
710 * cgroup_update_populated - update the populated count of a cgroup
711 * @cgrp: the target cgroup
712 * @populated: inc or dec populated count
714 * One of the css_sets associated with @cgrp is either getting its first
715 * task or losing the last. Update @cgrp->nr_populated_* accordingly. The
716 * count is propagated towards root so that a given cgroup's
717 * nr_populated_children is zero iff none of its descendants contain any
718 * tasks.
720 * @cgrp's interface file "cgroup.populated" is zero if both
721 * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
722 * 1 otherwise. When the sum changes from or to zero, userland is notified
723 * that the content of the interface file has changed. This can be used to
724 * detect when @cgrp and its descendants become populated or empty.
726 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
728 struct cgroup *child = NULL;
729 int adj = populated ? 1 : -1;
731 lockdep_assert_held(&css_set_lock);
733 do {
734 bool was_populated = cgroup_is_populated(cgrp);
736 if (!child) {
737 cgrp->nr_populated_csets += adj;
738 } else {
739 if (cgroup_is_threaded(child))
740 cgrp->nr_populated_threaded_children += adj;
741 else
742 cgrp->nr_populated_domain_children += adj;
745 if (was_populated == cgroup_is_populated(cgrp))
746 break;
748 cgroup1_check_for_release(cgrp);
749 cgroup_file_notify(&cgrp->events_file);
751 child = cgrp;
752 cgrp = cgroup_parent(cgrp);
753 } while (cgrp);
757 * css_set_update_populated - update populated state of a css_set
758 * @cset: target css_set
759 * @populated: whether @cset is populated or depopulated
761 * @cset is either getting the first task or losing the last. Update the
762 * populated counters of all associated cgroups accordingly.
764 static void css_set_update_populated(struct css_set *cset, bool populated)
766 struct cgrp_cset_link *link;
768 lockdep_assert_held(&css_set_lock);
770 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
771 cgroup_update_populated(link->cgrp, populated);
775 * css_set_move_task - move a task from one css_set to another
776 * @task: task being moved
777 * @from_cset: css_set @task currently belongs to (may be NULL)
778 * @to_cset: new css_set @task is being moved to (may be NULL)
779 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
781 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
782 * css_set, @from_cset can be NULL. If @task is being disassociated
783 * instead of moved, @to_cset can be NULL.
785 * This function automatically handles populated counter updates and
786 * css_task_iter adjustments but the caller is responsible for managing
787 * @from_cset and @to_cset's reference counts.
789 static void css_set_move_task(struct task_struct *task,
790 struct css_set *from_cset, struct css_set *to_cset,
791 bool use_mg_tasks)
793 lockdep_assert_held(&css_set_lock);
795 if (to_cset && !css_set_populated(to_cset))
796 css_set_update_populated(to_cset, true);
798 if (from_cset) {
799 struct css_task_iter *it, *pos;
801 WARN_ON_ONCE(list_empty(&task->cg_list));
804 * @task is leaving, advance task iterators which are
805 * pointing to it so that they can resume at the next
806 * position. Advancing an iterator might remove it from
807 * the list, use safe walk. See css_task_iter_advance*()
808 * for details.
810 list_for_each_entry_safe(it, pos, &from_cset->task_iters,
811 iters_node)
812 if (it->task_pos == &task->cg_list)
813 css_task_iter_advance(it);
815 list_del_init(&task->cg_list);
816 if (!css_set_populated(from_cset))
817 css_set_update_populated(from_cset, false);
818 } else {
819 WARN_ON_ONCE(!list_empty(&task->cg_list));
822 if (to_cset) {
824 * We are synchronized through cgroup_threadgroup_rwsem
825 * against PF_EXITING setting such that we can't race
826 * against cgroup_exit() changing the css_set to
827 * init_css_set and dropping the old one.
829 WARN_ON_ONCE(task->flags & PF_EXITING);
831 rcu_assign_pointer(task->cgroups, to_cset);
832 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
833 &to_cset->tasks);
838 * hash table for cgroup groups. This improves the performance to find
839 * an existing css_set. This hash doesn't (currently) take into
840 * account cgroups in empty hierarchies.
842 #define CSS_SET_HASH_BITS 7
843 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
845 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
847 unsigned long key = 0UL;
848 struct cgroup_subsys *ss;
849 int i;
851 for_each_subsys(ss, i)
852 key += (unsigned long)css[i];
853 key = (key >> 16) ^ key;
855 return key;
858 void put_css_set_locked(struct css_set *cset)
860 struct cgrp_cset_link *link, *tmp_link;
861 struct cgroup_subsys *ss;
862 int ssid;
864 lockdep_assert_held(&css_set_lock);
866 if (!refcount_dec_and_test(&cset->refcount))
867 return;
869 WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
871 /* This css_set is dead. unlink it and release cgroup and css refs */
872 for_each_subsys(ss, ssid) {
873 list_del(&cset->e_cset_node[ssid]);
874 css_put(cset->subsys[ssid]);
876 hash_del(&cset->hlist);
877 css_set_count--;
879 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
880 list_del(&link->cset_link);
881 list_del(&link->cgrp_link);
882 if (cgroup_parent(link->cgrp))
883 cgroup_put(link->cgrp);
884 kfree(link);
887 if (css_set_threaded(cset)) {
888 list_del(&cset->threaded_csets_node);
889 put_css_set_locked(cset->dom_cset);
892 kfree_rcu(cset, rcu_head);
896 * compare_css_sets - helper function for find_existing_css_set().
897 * @cset: candidate css_set being tested
898 * @old_cset: existing css_set for a task
899 * @new_cgrp: cgroup that's being entered by the task
900 * @template: desired set of css pointers in css_set (pre-calculated)
902 * Returns true if "cset" matches "old_cset" except for the hierarchy
903 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
905 static bool compare_css_sets(struct css_set *cset,
906 struct css_set *old_cset,
907 struct cgroup *new_cgrp,
908 struct cgroup_subsys_state *template[])
910 struct cgroup *new_dfl_cgrp;
911 struct list_head *l1, *l2;
914 * On the default hierarchy, there can be csets which are
915 * associated with the same set of cgroups but different csses.
916 * Let's first ensure that csses match.
918 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
919 return false;
922 /* @cset's domain should match the default cgroup's */
923 if (cgroup_on_dfl(new_cgrp))
924 new_dfl_cgrp = new_cgrp;
925 else
926 new_dfl_cgrp = old_cset->dfl_cgrp;
928 if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
929 return false;
932 * Compare cgroup pointers in order to distinguish between
933 * different cgroups in hierarchies. As different cgroups may
934 * share the same effective css, this comparison is always
935 * necessary.
937 l1 = &cset->cgrp_links;
938 l2 = &old_cset->cgrp_links;
939 while (1) {
940 struct cgrp_cset_link *link1, *link2;
941 struct cgroup *cgrp1, *cgrp2;
943 l1 = l1->next;
944 l2 = l2->next;
945 /* See if we reached the end - both lists are equal length. */
946 if (l1 == &cset->cgrp_links) {
947 BUG_ON(l2 != &old_cset->cgrp_links);
948 break;
949 } else {
950 BUG_ON(l2 == &old_cset->cgrp_links);
952 /* Locate the cgroups associated with these links. */
953 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
954 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
955 cgrp1 = link1->cgrp;
956 cgrp2 = link2->cgrp;
957 /* Hierarchies should be linked in the same order. */
958 BUG_ON(cgrp1->root != cgrp2->root);
961 * If this hierarchy is the hierarchy of the cgroup
962 * that's changing, then we need to check that this
963 * css_set points to the new cgroup; if it's any other
964 * hierarchy, then this css_set should point to the
965 * same cgroup as the old css_set.
967 if (cgrp1->root == new_cgrp->root) {
968 if (cgrp1 != new_cgrp)
969 return false;
970 } else {
971 if (cgrp1 != cgrp2)
972 return false;
975 return true;
979 * find_existing_css_set - init css array and find the matching css_set
980 * @old_cset: the css_set that we're using before the cgroup transition
981 * @cgrp: the cgroup that we're moving into
982 * @template: out param for the new set of csses, should be clear on entry
984 static struct css_set *find_existing_css_set(struct css_set *old_cset,
985 struct cgroup *cgrp,
986 struct cgroup_subsys_state *template[])
988 struct cgroup_root *root = cgrp->root;
989 struct cgroup_subsys *ss;
990 struct css_set *cset;
991 unsigned long key;
992 int i;
995 * Build the set of subsystem state objects that we want to see in the
996 * new css_set. while subsystems can change globally, the entries here
997 * won't change, so no need for locking.
999 for_each_subsys(ss, i) {
1000 if (root->subsys_mask & (1UL << i)) {
1002 * @ss is in this hierarchy, so we want the
1003 * effective css from @cgrp.
1005 template[i] = cgroup_e_css(cgrp, ss);
1006 } else {
1008 * @ss is not in this hierarchy, so we don't want
1009 * to change the css.
1011 template[i] = old_cset->subsys[i];
1015 key = css_set_hash(template);
1016 hash_for_each_possible(css_set_table, cset, hlist, key) {
1017 if (!compare_css_sets(cset, old_cset, cgrp, template))
1018 continue;
1020 /* This css_set matches what we need */
1021 return cset;
1024 /* No existing cgroup group matched */
1025 return NULL;
1028 static void free_cgrp_cset_links(struct list_head *links_to_free)
1030 struct cgrp_cset_link *link, *tmp_link;
1032 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1033 list_del(&link->cset_link);
1034 kfree(link);
1039 * allocate_cgrp_cset_links - allocate cgrp_cset_links
1040 * @count: the number of links to allocate
1041 * @tmp_links: list_head the allocated links are put on
1043 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1044 * through ->cset_link. Returns 0 on success or -errno.
1046 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1048 struct cgrp_cset_link *link;
1049 int i;
1051 INIT_LIST_HEAD(tmp_links);
1053 for (i = 0; i < count; i++) {
1054 link = kzalloc(sizeof(*link), GFP_KERNEL);
1055 if (!link) {
1056 free_cgrp_cset_links(tmp_links);
1057 return -ENOMEM;
1059 list_add(&link->cset_link, tmp_links);
1061 return 0;
1065 * link_css_set - a helper function to link a css_set to a cgroup
1066 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1067 * @cset: the css_set to be linked
1068 * @cgrp: the destination cgroup
1070 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1071 struct cgroup *cgrp)
1073 struct cgrp_cset_link *link;
1075 BUG_ON(list_empty(tmp_links));
1077 if (cgroup_on_dfl(cgrp))
1078 cset->dfl_cgrp = cgrp;
1080 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1081 link->cset = cset;
1082 link->cgrp = cgrp;
1085 * Always add links to the tail of the lists so that the lists are
1086 * in choronological order.
1088 list_move_tail(&link->cset_link, &cgrp->cset_links);
1089 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1091 if (cgroup_parent(cgrp))
1092 cgroup_get_live(cgrp);
1096 * find_css_set - return a new css_set with one cgroup updated
1097 * @old_cset: the baseline css_set
1098 * @cgrp: the cgroup to be updated
1100 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1101 * substituted into the appropriate hierarchy.
1103 static struct css_set *find_css_set(struct css_set *old_cset,
1104 struct cgroup *cgrp)
1106 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1107 struct css_set *cset;
1108 struct list_head tmp_links;
1109 struct cgrp_cset_link *link;
1110 struct cgroup_subsys *ss;
1111 unsigned long key;
1112 int ssid;
1114 lockdep_assert_held(&cgroup_mutex);
1116 /* First see if we already have a cgroup group that matches
1117 * the desired set */
1118 spin_lock_irq(&css_set_lock);
1119 cset = find_existing_css_set(old_cset, cgrp, template);
1120 if (cset)
1121 get_css_set(cset);
1122 spin_unlock_irq(&css_set_lock);
1124 if (cset)
1125 return cset;
1127 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1128 if (!cset)
1129 return NULL;
1131 /* Allocate all the cgrp_cset_link objects that we'll need */
1132 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1133 kfree(cset);
1134 return NULL;
1137 refcount_set(&cset->refcount, 1);
1138 cset->dom_cset = cset;
1139 INIT_LIST_HEAD(&cset->tasks);
1140 INIT_LIST_HEAD(&cset->mg_tasks);
1141 INIT_LIST_HEAD(&cset->task_iters);
1142 INIT_LIST_HEAD(&cset->threaded_csets);
1143 INIT_HLIST_NODE(&cset->hlist);
1144 INIT_LIST_HEAD(&cset->cgrp_links);
1145 INIT_LIST_HEAD(&cset->mg_preload_node);
1146 INIT_LIST_HEAD(&cset->mg_node);
1148 /* Copy the set of subsystem state objects generated in
1149 * find_existing_css_set() */
1150 memcpy(cset->subsys, template, sizeof(cset->subsys));
1152 spin_lock_irq(&css_set_lock);
1153 /* Add reference counts and links from the new css_set. */
1154 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1155 struct cgroup *c = link->cgrp;
1157 if (c->root == cgrp->root)
1158 c = cgrp;
1159 link_css_set(&tmp_links, cset, c);
1162 BUG_ON(!list_empty(&tmp_links));
1164 css_set_count++;
1166 /* Add @cset to the hash table */
1167 key = css_set_hash(cset->subsys);
1168 hash_add(css_set_table, &cset->hlist, key);
1170 for_each_subsys(ss, ssid) {
1171 struct cgroup_subsys_state *css = cset->subsys[ssid];
1173 list_add_tail(&cset->e_cset_node[ssid],
1174 &css->cgroup->e_csets[ssid]);
1175 css_get(css);
1178 spin_unlock_irq(&css_set_lock);
1181 * If @cset should be threaded, look up the matching dom_cset and
1182 * link them up. We first fully initialize @cset then look for the
1183 * dom_cset. It's simpler this way and safe as @cset is guaranteed
1184 * to stay empty until we return.
1186 if (cgroup_is_threaded(cset->dfl_cgrp)) {
1187 struct css_set *dcset;
1189 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1190 if (!dcset) {
1191 put_css_set(cset);
1192 return NULL;
1195 spin_lock_irq(&css_set_lock);
1196 cset->dom_cset = dcset;
1197 list_add_tail(&cset->threaded_csets_node,
1198 &dcset->threaded_csets);
1199 spin_unlock_irq(&css_set_lock);
1202 return cset;
1205 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1207 struct cgroup *root_cgrp = kf_root->kn->priv;
1209 return root_cgrp->root;
1212 static int cgroup_init_root_id(struct cgroup_root *root)
1214 int id;
1216 lockdep_assert_held(&cgroup_mutex);
1218 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1219 if (id < 0)
1220 return id;
1222 root->hierarchy_id = id;
1223 return 0;
1226 static void cgroup_exit_root_id(struct cgroup_root *root)
1228 lockdep_assert_held(&cgroup_mutex);
1230 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1233 void cgroup_free_root(struct cgroup_root *root)
1235 if (root) {
1236 idr_destroy(&root->cgroup_idr);
1237 kfree(root);
1241 static void cgroup_destroy_root(struct cgroup_root *root)
1243 struct cgroup *cgrp = &root->cgrp;
1244 struct cgrp_cset_link *link, *tmp_link;
1246 trace_cgroup_destroy_root(root);
1248 cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1250 BUG_ON(atomic_read(&root->nr_cgrps));
1251 BUG_ON(!list_empty(&cgrp->self.children));
1253 /* Rebind all subsystems back to the default hierarchy */
1254 WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1257 * Release all the links from cset_links to this hierarchy's
1258 * root cgroup
1260 spin_lock_irq(&css_set_lock);
1262 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1263 list_del(&link->cset_link);
1264 list_del(&link->cgrp_link);
1265 kfree(link);
1268 spin_unlock_irq(&css_set_lock);
1270 if (!list_empty(&root->root_list)) {
1271 list_del(&root->root_list);
1272 cgroup_root_count--;
1275 cgroup_exit_root_id(root);
1277 mutex_unlock(&cgroup_mutex);
1279 kernfs_destroy_root(root->kf_root);
1280 cgroup_free_root(root);
1284 * look up cgroup associated with current task's cgroup namespace on the
1285 * specified hierarchy
1287 static struct cgroup *
1288 current_cgns_cgroup_from_root(struct cgroup_root *root)
1290 struct cgroup *res = NULL;
1291 struct css_set *cset;
1293 lockdep_assert_held(&css_set_lock);
1295 rcu_read_lock();
1297 cset = current->nsproxy->cgroup_ns->root_cset;
1298 if (cset == &init_css_set) {
1299 res = &root->cgrp;
1300 } else {
1301 struct cgrp_cset_link *link;
1303 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1304 struct cgroup *c = link->cgrp;
1306 if (c->root == root) {
1307 res = c;
1308 break;
1312 rcu_read_unlock();
1314 BUG_ON(!res);
1315 return res;
1318 /* look up cgroup associated with given css_set on the specified hierarchy */
1319 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1320 struct cgroup_root *root)
1322 struct cgroup *res = NULL;
1324 lockdep_assert_held(&cgroup_mutex);
1325 lockdep_assert_held(&css_set_lock);
1327 if (cset == &init_css_set) {
1328 res = &root->cgrp;
1329 } else if (root == &cgrp_dfl_root) {
1330 res = cset->dfl_cgrp;
1331 } else {
1332 struct cgrp_cset_link *link;
1334 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1335 struct cgroup *c = link->cgrp;
1337 if (c->root == root) {
1338 res = c;
1339 break;
1344 BUG_ON(!res);
1345 return res;
1349 * Return the cgroup for "task" from the given hierarchy. Must be
1350 * called with cgroup_mutex and css_set_lock held.
1352 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1353 struct cgroup_root *root)
1356 * No need to lock the task - since we hold cgroup_mutex the
1357 * task can't change groups, so the only thing that can happen
1358 * is that it exits and its css is set back to init_css_set.
1360 return cset_cgroup_from_root(task_css_set(task), root);
1364 * A task must hold cgroup_mutex to modify cgroups.
1366 * Any task can increment and decrement the count field without lock.
1367 * So in general, code holding cgroup_mutex can't rely on the count
1368 * field not changing. However, if the count goes to zero, then only
1369 * cgroup_attach_task() can increment it again. Because a count of zero
1370 * means that no tasks are currently attached, therefore there is no
1371 * way a task attached to that cgroup can fork (the other way to
1372 * increment the count). So code holding cgroup_mutex can safely
1373 * assume that if the count is zero, it will stay zero. Similarly, if
1374 * a task holds cgroup_mutex on a cgroup with zero count, it
1375 * knows that the cgroup won't be removed, as cgroup_rmdir()
1376 * needs that mutex.
1378 * A cgroup can only be deleted if both its 'count' of using tasks
1379 * is zero, and its list of 'children' cgroups is empty. Since all
1380 * tasks in the system use _some_ cgroup, and since there is always at
1381 * least one task in the system (init, pid == 1), therefore, root cgroup
1382 * always has either children cgroups and/or using tasks. So we don't
1383 * need a special hack to ensure that root cgroup cannot be deleted.
1385 * P.S. One more locking exception. RCU is used to guard the
1386 * update of a tasks cgroup pointer by cgroup_attach_task()
1389 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1391 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1392 char *buf)
1394 struct cgroup_subsys *ss = cft->ss;
1396 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1397 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1398 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1399 cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1400 cft->name);
1401 else
1402 strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1403 return buf;
1407 * cgroup_file_mode - deduce file mode of a control file
1408 * @cft: the control file in question
1410 * S_IRUGO for read, S_IWUSR for write.
1412 static umode_t cgroup_file_mode(const struct cftype *cft)
1414 umode_t mode = 0;
1416 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1417 mode |= S_IRUGO;
1419 if (cft->write_u64 || cft->write_s64 || cft->write) {
1420 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1421 mode |= S_IWUGO;
1422 else
1423 mode |= S_IWUSR;
1426 return mode;
1430 * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1431 * @subtree_control: the new subtree_control mask to consider
1432 * @this_ss_mask: available subsystems
1434 * On the default hierarchy, a subsystem may request other subsystems to be
1435 * enabled together through its ->depends_on mask. In such cases, more
1436 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1438 * This function calculates which subsystems need to be enabled if
1439 * @subtree_control is to be applied while restricted to @this_ss_mask.
1441 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1443 u16 cur_ss_mask = subtree_control;
1444 struct cgroup_subsys *ss;
1445 int ssid;
1447 lockdep_assert_held(&cgroup_mutex);
1449 cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1451 while (true) {
1452 u16 new_ss_mask = cur_ss_mask;
1454 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1455 new_ss_mask |= ss->depends_on;
1456 } while_each_subsys_mask();
1459 * Mask out subsystems which aren't available. This can
1460 * happen only if some depended-upon subsystems were bound
1461 * to non-default hierarchies.
1463 new_ss_mask &= this_ss_mask;
1465 if (new_ss_mask == cur_ss_mask)
1466 break;
1467 cur_ss_mask = new_ss_mask;
1470 return cur_ss_mask;
1474 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1475 * @kn: the kernfs_node being serviced
1477 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1478 * the method finishes if locking succeeded. Note that once this function
1479 * returns the cgroup returned by cgroup_kn_lock_live() may become
1480 * inaccessible any time. If the caller intends to continue to access the
1481 * cgroup, it should pin it before invoking this function.
1483 void cgroup_kn_unlock(struct kernfs_node *kn)
1485 struct cgroup *cgrp;
1487 if (kernfs_type(kn) == KERNFS_DIR)
1488 cgrp = kn->priv;
1489 else
1490 cgrp = kn->parent->priv;
1492 mutex_unlock(&cgroup_mutex);
1494 kernfs_unbreak_active_protection(kn);
1495 cgroup_put(cgrp);
1499 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1500 * @kn: the kernfs_node being serviced
1501 * @drain_offline: perform offline draining on the cgroup
1503 * This helper is to be used by a cgroup kernfs method currently servicing
1504 * @kn. It breaks the active protection, performs cgroup locking and
1505 * verifies that the associated cgroup is alive. Returns the cgroup if
1506 * alive; otherwise, %NULL. A successful return should be undone by a
1507 * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the
1508 * cgroup is drained of offlining csses before return.
1510 * Any cgroup kernfs method implementation which requires locking the
1511 * associated cgroup should use this helper. It avoids nesting cgroup
1512 * locking under kernfs active protection and allows all kernfs operations
1513 * including self-removal.
1515 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1517 struct cgroup *cgrp;
1519 if (kernfs_type(kn) == KERNFS_DIR)
1520 cgrp = kn->priv;
1521 else
1522 cgrp = kn->parent->priv;
1525 * We're gonna grab cgroup_mutex which nests outside kernfs
1526 * active_ref. cgroup liveliness check alone provides enough
1527 * protection against removal. Ensure @cgrp stays accessible and
1528 * break the active_ref protection.
1530 if (!cgroup_tryget(cgrp))
1531 return NULL;
1532 kernfs_break_active_protection(kn);
1534 if (drain_offline)
1535 cgroup_lock_and_drain_offline(cgrp);
1536 else
1537 mutex_lock(&cgroup_mutex);
1539 if (!cgroup_is_dead(cgrp))
1540 return cgrp;
1542 cgroup_kn_unlock(kn);
1543 return NULL;
1546 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1548 char name[CGROUP_FILE_NAME_MAX];
1550 lockdep_assert_held(&cgroup_mutex);
1552 if (cft->file_offset) {
1553 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1554 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1556 spin_lock_irq(&cgroup_file_kn_lock);
1557 cfile->kn = NULL;
1558 spin_unlock_irq(&cgroup_file_kn_lock);
1560 del_timer_sync(&cfile->notify_timer);
1563 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1567 * css_clear_dir - remove subsys files in a cgroup directory
1568 * @css: taget css
1570 static void css_clear_dir(struct cgroup_subsys_state *css)
1572 struct cgroup *cgrp = css->cgroup;
1573 struct cftype *cfts;
1575 if (!(css->flags & CSS_VISIBLE))
1576 return;
1578 css->flags &= ~CSS_VISIBLE;
1580 if (!css->ss) {
1581 if (cgroup_on_dfl(cgrp))
1582 cfts = cgroup_base_files;
1583 else
1584 cfts = cgroup1_base_files;
1586 cgroup_addrm_files(css, cgrp, cfts, false);
1587 } else {
1588 list_for_each_entry(cfts, &css->ss->cfts, node)
1589 cgroup_addrm_files(css, cgrp, cfts, false);
1594 * css_populate_dir - create subsys files in a cgroup directory
1595 * @css: target css
1597 * On failure, no file is added.
1599 static int css_populate_dir(struct cgroup_subsys_state *css)
1601 struct cgroup *cgrp = css->cgroup;
1602 struct cftype *cfts, *failed_cfts;
1603 int ret;
1605 if ((css->flags & CSS_VISIBLE) || !cgrp->kn)
1606 return 0;
1608 if (!css->ss) {
1609 if (cgroup_on_dfl(cgrp))
1610 cfts = cgroup_base_files;
1611 else
1612 cfts = cgroup1_base_files;
1614 ret = cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1615 if (ret < 0)
1616 return ret;
1617 } else {
1618 list_for_each_entry(cfts, &css->ss->cfts, node) {
1619 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1620 if (ret < 0) {
1621 failed_cfts = cfts;
1622 goto err;
1627 css->flags |= CSS_VISIBLE;
1629 return 0;
1630 err:
1631 list_for_each_entry(cfts, &css->ss->cfts, node) {
1632 if (cfts == failed_cfts)
1633 break;
1634 cgroup_addrm_files(css, cgrp, cfts, false);
1636 return ret;
1639 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1641 struct cgroup *dcgrp = &dst_root->cgrp;
1642 struct cgroup_subsys *ss;
1643 int ssid, i, ret;
1645 lockdep_assert_held(&cgroup_mutex);
1647 do_each_subsys_mask(ss, ssid, ss_mask) {
1649 * If @ss has non-root csses attached to it, can't move.
1650 * If @ss is an implicit controller, it is exempt from this
1651 * rule and can be stolen.
1653 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1654 !ss->implicit_on_dfl)
1655 return -EBUSY;
1657 /* can't move between two non-dummy roots either */
1658 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1659 return -EBUSY;
1660 } while_each_subsys_mask();
1662 do_each_subsys_mask(ss, ssid, ss_mask) {
1663 struct cgroup_root *src_root = ss->root;
1664 struct cgroup *scgrp = &src_root->cgrp;
1665 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1666 struct css_set *cset;
1668 WARN_ON(!css || cgroup_css(dcgrp, ss));
1670 /* disable from the source */
1671 src_root->subsys_mask &= ~(1 << ssid);
1672 WARN_ON(cgroup_apply_control(scgrp));
1673 cgroup_finalize_control(scgrp, 0);
1675 /* rebind */
1676 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1677 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1678 ss->root = dst_root;
1679 css->cgroup = dcgrp;
1681 spin_lock_irq(&css_set_lock);
1682 hash_for_each(css_set_table, i, cset, hlist)
1683 list_move_tail(&cset->e_cset_node[ss->id],
1684 &dcgrp->e_csets[ss->id]);
1685 spin_unlock_irq(&css_set_lock);
1687 /* default hierarchy doesn't enable controllers by default */
1688 dst_root->subsys_mask |= 1 << ssid;
1689 if (dst_root == &cgrp_dfl_root) {
1690 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1691 } else {
1692 dcgrp->subtree_control |= 1 << ssid;
1693 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1696 ret = cgroup_apply_control(dcgrp);
1697 if (ret)
1698 pr_warn("partial failure to rebind %s controller (err=%d)\n",
1699 ss->name, ret);
1701 if (ss->bind)
1702 ss->bind(css);
1703 } while_each_subsys_mask();
1705 kernfs_activate(dcgrp->kn);
1706 return 0;
1709 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1710 struct kernfs_root *kf_root)
1712 int len = 0;
1713 char *buf = NULL;
1714 struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1715 struct cgroup *ns_cgroup;
1717 buf = kmalloc(PATH_MAX, GFP_KERNEL);
1718 if (!buf)
1719 return -ENOMEM;
1721 spin_lock_irq(&css_set_lock);
1722 ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1723 len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1724 spin_unlock_irq(&css_set_lock);
1726 if (len >= PATH_MAX)
1727 len = -ERANGE;
1728 else if (len > 0) {
1729 seq_escape(sf, buf, " \t\n\\");
1730 len = 0;
1732 kfree(buf);
1733 return len;
1736 static int parse_cgroup_root_flags(char *data, unsigned int *root_flags)
1738 char *token;
1740 *root_flags = 0;
1742 if (!data)
1743 return 0;
1745 while ((token = strsep(&data, ",")) != NULL) {
1746 if (!strcmp(token, "nsdelegate")) {
1747 *root_flags |= CGRP_ROOT_NS_DELEGATE;
1748 continue;
1751 pr_err("cgroup2: unknown option \"%s\"\n", token);
1752 return -EINVAL;
1755 return 0;
1758 static void apply_cgroup_root_flags(unsigned int root_flags)
1760 if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1761 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1762 cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1763 else
1764 cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1768 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1770 if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1771 seq_puts(seq, ",nsdelegate");
1772 return 0;
1775 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1777 unsigned int root_flags;
1778 int ret;
1780 ret = parse_cgroup_root_flags(data, &root_flags);
1781 if (ret)
1782 return ret;
1784 apply_cgroup_root_flags(root_flags);
1785 return 0;
1789 * To reduce the fork() overhead for systems that are not actually using
1790 * their cgroups capability, we don't maintain the lists running through
1791 * each css_set to its tasks until we see the list actually used - in other
1792 * words after the first mount.
1794 static bool use_task_css_set_links __read_mostly;
1796 static void cgroup_enable_task_cg_lists(void)
1798 struct task_struct *p, *g;
1800 spin_lock_irq(&css_set_lock);
1802 if (use_task_css_set_links)
1803 goto out_unlock;
1805 use_task_css_set_links = true;
1808 * We need tasklist_lock because RCU is not safe against
1809 * while_each_thread(). Besides, a forking task that has passed
1810 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1811 * is not guaranteed to have its child immediately visible in the
1812 * tasklist if we walk through it with RCU.
1814 read_lock(&tasklist_lock);
1815 do_each_thread(g, p) {
1816 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1817 task_css_set(p) != &init_css_set);
1820 * We should check if the process is exiting, otherwise
1821 * it will race with cgroup_exit() in that the list
1822 * entry won't be deleted though the process has exited.
1823 * Do it while holding siglock so that we don't end up
1824 * racing against cgroup_exit().
1826 * Interrupts were already disabled while acquiring
1827 * the css_set_lock, so we do not need to disable it
1828 * again when acquiring the sighand->siglock here.
1830 spin_lock(&p->sighand->siglock);
1831 if (!(p->flags & PF_EXITING)) {
1832 struct css_set *cset = task_css_set(p);
1834 if (!css_set_populated(cset))
1835 css_set_update_populated(cset, true);
1836 list_add_tail(&p->cg_list, &cset->tasks);
1837 get_css_set(cset);
1838 cset->nr_tasks++;
1840 spin_unlock(&p->sighand->siglock);
1841 } while_each_thread(g, p);
1842 read_unlock(&tasklist_lock);
1843 out_unlock:
1844 spin_unlock_irq(&css_set_lock);
1847 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1849 struct cgroup_subsys *ss;
1850 int ssid;
1852 INIT_LIST_HEAD(&cgrp->self.sibling);
1853 INIT_LIST_HEAD(&cgrp->self.children);
1854 INIT_LIST_HEAD(&cgrp->cset_links);
1855 INIT_LIST_HEAD(&cgrp->pidlists);
1856 mutex_init(&cgrp->pidlist_mutex);
1857 cgrp->self.cgroup = cgrp;
1858 cgrp->self.flags |= CSS_ONLINE;
1859 cgrp->dom_cgrp = cgrp;
1860 cgrp->max_descendants = INT_MAX;
1861 cgrp->max_depth = INT_MAX;
1863 for_each_subsys(ss, ssid)
1864 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1866 init_waitqueue_head(&cgrp->offline_waitq);
1867 INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
1870 void init_cgroup_root(struct cgroup_root *root, struct cgroup_sb_opts *opts)
1872 struct cgroup *cgrp = &root->cgrp;
1874 INIT_LIST_HEAD(&root->root_list);
1875 atomic_set(&root->nr_cgrps, 1);
1876 cgrp->root = root;
1877 init_cgroup_housekeeping(cgrp);
1878 idr_init(&root->cgroup_idr);
1880 root->flags = opts->flags;
1881 if (opts->release_agent)
1882 strscpy(root->release_agent_path, opts->release_agent, PATH_MAX);
1883 if (opts->name)
1884 strscpy(root->name, opts->name, MAX_CGROUP_ROOT_NAMELEN);
1885 if (opts->cpuset_clone_children)
1886 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1889 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask, int ref_flags)
1891 LIST_HEAD(tmp_links);
1892 struct cgroup *root_cgrp = &root->cgrp;
1893 struct kernfs_syscall_ops *kf_sops;
1894 struct css_set *cset;
1895 int i, ret;
1897 lockdep_assert_held(&cgroup_mutex);
1899 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1900 if (ret < 0)
1901 goto out;
1902 root_cgrp->id = ret;
1903 root_cgrp->ancestor_ids[0] = ret;
1905 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
1906 ref_flags, GFP_KERNEL);
1907 if (ret)
1908 goto out;
1911 * We're accessing css_set_count without locking css_set_lock here,
1912 * but that's OK - it can only be increased by someone holding
1913 * cgroup_lock, and that's us. Later rebinding may disable
1914 * controllers on the default hierarchy and thus create new csets,
1915 * which can't be more than the existing ones. Allocate 2x.
1917 ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
1918 if (ret)
1919 goto cancel_ref;
1921 ret = cgroup_init_root_id(root);
1922 if (ret)
1923 goto cancel_ref;
1925 kf_sops = root == &cgrp_dfl_root ?
1926 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
1928 root->kf_root = kernfs_create_root(kf_sops,
1929 KERNFS_ROOT_CREATE_DEACTIVATED |
1930 KERNFS_ROOT_SUPPORT_EXPORTOP,
1931 root_cgrp);
1932 if (IS_ERR(root->kf_root)) {
1933 ret = PTR_ERR(root->kf_root);
1934 goto exit_root_id;
1936 root_cgrp->kn = root->kf_root->kn;
1938 ret = css_populate_dir(&root_cgrp->self);
1939 if (ret)
1940 goto destroy_root;
1942 ret = rebind_subsystems(root, ss_mask);
1943 if (ret)
1944 goto destroy_root;
1946 ret = cgroup_bpf_inherit(root_cgrp);
1947 WARN_ON_ONCE(ret);
1949 trace_cgroup_setup_root(root);
1952 * There must be no failure case after here, since rebinding takes
1953 * care of subsystems' refcounts, which are explicitly dropped in
1954 * the failure exit path.
1956 list_add(&root->root_list, &cgroup_roots);
1957 cgroup_root_count++;
1960 * Link the root cgroup in this hierarchy into all the css_set
1961 * objects.
1963 spin_lock_irq(&css_set_lock);
1964 hash_for_each(css_set_table, i, cset, hlist) {
1965 link_css_set(&tmp_links, cset, root_cgrp);
1966 if (css_set_populated(cset))
1967 cgroup_update_populated(root_cgrp, true);
1969 spin_unlock_irq(&css_set_lock);
1971 BUG_ON(!list_empty(&root_cgrp->self.children));
1972 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1974 kernfs_activate(root_cgrp->kn);
1975 ret = 0;
1976 goto out;
1978 destroy_root:
1979 kernfs_destroy_root(root->kf_root);
1980 root->kf_root = NULL;
1981 exit_root_id:
1982 cgroup_exit_root_id(root);
1983 cancel_ref:
1984 percpu_ref_exit(&root_cgrp->self.refcnt);
1985 out:
1986 free_cgrp_cset_links(&tmp_links);
1987 return ret;
1990 struct dentry *cgroup_do_mount(struct file_system_type *fs_type, int flags,
1991 struct cgroup_root *root, unsigned long magic,
1992 struct cgroup_namespace *ns)
1994 struct dentry *dentry;
1995 bool new_sb;
1997 dentry = kernfs_mount(fs_type, flags, root->kf_root, magic, &new_sb);
2000 * In non-init cgroup namespace, instead of root cgroup's dentry,
2001 * we return the dentry corresponding to the cgroupns->root_cgrp.
2003 if (!IS_ERR(dentry) && ns != &init_cgroup_ns) {
2004 struct dentry *nsdentry;
2005 struct cgroup *cgrp;
2007 mutex_lock(&cgroup_mutex);
2008 spin_lock_irq(&css_set_lock);
2010 cgrp = cset_cgroup_from_root(ns->root_cset, root);
2012 spin_unlock_irq(&css_set_lock);
2013 mutex_unlock(&cgroup_mutex);
2015 nsdentry = kernfs_node_dentry(cgrp->kn, dentry->d_sb);
2016 dput(dentry);
2017 dentry = nsdentry;
2020 if (IS_ERR(dentry) || !new_sb)
2021 cgroup_put(&root->cgrp);
2023 return dentry;
2026 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
2027 int flags, const char *unused_dev_name,
2028 void *data)
2030 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
2031 struct dentry *dentry;
2032 int ret;
2034 get_cgroup_ns(ns);
2036 /* Check if the caller has permission to mount. */
2037 if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) {
2038 put_cgroup_ns(ns);
2039 return ERR_PTR(-EPERM);
2043 * The first time anyone tries to mount a cgroup, enable the list
2044 * linking each css_set to its tasks and fix up all existing tasks.
2046 if (!use_task_css_set_links)
2047 cgroup_enable_task_cg_lists();
2049 if (fs_type == &cgroup2_fs_type) {
2050 unsigned int root_flags;
2052 ret = parse_cgroup_root_flags(data, &root_flags);
2053 if (ret) {
2054 put_cgroup_ns(ns);
2055 return ERR_PTR(ret);
2058 cgrp_dfl_visible = true;
2059 cgroup_get_live(&cgrp_dfl_root.cgrp);
2061 dentry = cgroup_do_mount(&cgroup2_fs_type, flags, &cgrp_dfl_root,
2062 CGROUP2_SUPER_MAGIC, ns);
2063 if (!IS_ERR(dentry))
2064 apply_cgroup_root_flags(root_flags);
2065 } else {
2066 dentry = cgroup1_mount(&cgroup_fs_type, flags, data,
2067 CGROUP_SUPER_MAGIC, ns);
2070 put_cgroup_ns(ns);
2071 return dentry;
2074 static void cgroup_kill_sb(struct super_block *sb)
2076 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2077 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2080 * If @root doesn't have any mounts or children, start killing it.
2081 * This prevents new mounts by disabling percpu_ref_tryget_live().
2082 * cgroup_mount() may wait for @root's release.
2084 * And don't kill the default root.
2086 if (!list_empty(&root->cgrp.self.children) ||
2087 root == &cgrp_dfl_root)
2088 cgroup_put(&root->cgrp);
2089 else
2090 percpu_ref_kill(&root->cgrp.self.refcnt);
2092 kernfs_kill_sb(sb);
2095 struct file_system_type cgroup_fs_type = {
2096 .name = "cgroup",
2097 .mount = cgroup_mount,
2098 .kill_sb = cgroup_kill_sb,
2099 .fs_flags = FS_USERNS_MOUNT,
2102 static struct file_system_type cgroup2_fs_type = {
2103 .name = "cgroup2",
2104 .mount = cgroup_mount,
2105 .kill_sb = cgroup_kill_sb,
2106 .fs_flags = FS_USERNS_MOUNT,
2109 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2110 struct cgroup_namespace *ns)
2112 struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2114 return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2117 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2118 struct cgroup_namespace *ns)
2120 int ret;
2122 mutex_lock(&cgroup_mutex);
2123 spin_lock_irq(&css_set_lock);
2125 ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2127 spin_unlock_irq(&css_set_lock);
2128 mutex_unlock(&cgroup_mutex);
2130 return ret;
2132 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2135 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2136 * @task: target task
2137 * @buf: the buffer to write the path into
2138 * @buflen: the length of the buffer
2140 * Determine @task's cgroup on the first (the one with the lowest non-zero
2141 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2142 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2143 * cgroup controller callbacks.
2145 * Return value is the same as kernfs_path().
2147 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2149 struct cgroup_root *root;
2150 struct cgroup *cgrp;
2151 int hierarchy_id = 1;
2152 int ret;
2154 mutex_lock(&cgroup_mutex);
2155 spin_lock_irq(&css_set_lock);
2157 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2159 if (root) {
2160 cgrp = task_cgroup_from_root(task, root);
2161 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2162 } else {
2163 /* if no hierarchy exists, everyone is in "/" */
2164 ret = strlcpy(buf, "/", buflen);
2167 spin_unlock_irq(&css_set_lock);
2168 mutex_unlock(&cgroup_mutex);
2169 return ret;
2171 EXPORT_SYMBOL_GPL(task_cgroup_path);
2174 * cgroup_migrate_add_task - add a migration target task to a migration context
2175 * @task: target task
2176 * @mgctx: target migration context
2178 * Add @task, which is a migration target, to @mgctx->tset. This function
2179 * becomes noop if @task doesn't need to be migrated. @task's css_set
2180 * should have been added as a migration source and @task->cg_list will be
2181 * moved from the css_set's tasks list to mg_tasks one.
2183 static void cgroup_migrate_add_task(struct task_struct *task,
2184 struct cgroup_mgctx *mgctx)
2186 struct css_set *cset;
2188 lockdep_assert_held(&css_set_lock);
2190 /* @task either already exited or can't exit until the end */
2191 if (task->flags & PF_EXITING)
2192 return;
2194 /* leave @task alone if post_fork() hasn't linked it yet */
2195 if (list_empty(&task->cg_list))
2196 return;
2198 cset = task_css_set(task);
2199 if (!cset->mg_src_cgrp)
2200 return;
2202 mgctx->tset.nr_tasks++;
2204 list_move_tail(&task->cg_list, &cset->mg_tasks);
2205 if (list_empty(&cset->mg_node))
2206 list_add_tail(&cset->mg_node,
2207 &mgctx->tset.src_csets);
2208 if (list_empty(&cset->mg_dst_cset->mg_node))
2209 list_add_tail(&cset->mg_dst_cset->mg_node,
2210 &mgctx->tset.dst_csets);
2214 * cgroup_taskset_first - reset taskset and return the first task
2215 * @tset: taskset of interest
2216 * @dst_cssp: output variable for the destination css
2218 * @tset iteration is initialized and the first task is returned.
2220 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2221 struct cgroup_subsys_state **dst_cssp)
2223 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2224 tset->cur_task = NULL;
2226 return cgroup_taskset_next(tset, dst_cssp);
2230 * cgroup_taskset_next - iterate to the next task in taskset
2231 * @tset: taskset of interest
2232 * @dst_cssp: output variable for the destination css
2234 * Return the next task in @tset. Iteration must have been initialized
2235 * with cgroup_taskset_first().
2237 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2238 struct cgroup_subsys_state **dst_cssp)
2240 struct css_set *cset = tset->cur_cset;
2241 struct task_struct *task = tset->cur_task;
2243 while (&cset->mg_node != tset->csets) {
2244 if (!task)
2245 task = list_first_entry(&cset->mg_tasks,
2246 struct task_struct, cg_list);
2247 else
2248 task = list_next_entry(task, cg_list);
2250 if (&task->cg_list != &cset->mg_tasks) {
2251 tset->cur_cset = cset;
2252 tset->cur_task = task;
2255 * This function may be called both before and
2256 * after cgroup_taskset_migrate(). The two cases
2257 * can be distinguished by looking at whether @cset
2258 * has its ->mg_dst_cset set.
2260 if (cset->mg_dst_cset)
2261 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2262 else
2263 *dst_cssp = cset->subsys[tset->ssid];
2265 return task;
2268 cset = list_next_entry(cset, mg_node);
2269 task = NULL;
2272 return NULL;
2276 * cgroup_taskset_migrate - migrate a taskset
2277 * @mgctx: migration context
2279 * Migrate tasks in @mgctx as setup by migration preparation functions.
2280 * This function fails iff one of the ->can_attach callbacks fails and
2281 * guarantees that either all or none of the tasks in @mgctx are migrated.
2282 * @mgctx is consumed regardless of success.
2284 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2286 struct cgroup_taskset *tset = &mgctx->tset;
2287 struct cgroup_subsys *ss;
2288 struct task_struct *task, *tmp_task;
2289 struct css_set *cset, *tmp_cset;
2290 int ssid, failed_ssid, ret;
2292 /* check that we can legitimately attach to the cgroup */
2293 if (tset->nr_tasks) {
2294 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2295 if (ss->can_attach) {
2296 tset->ssid = ssid;
2297 ret = ss->can_attach(tset);
2298 if (ret) {
2299 failed_ssid = ssid;
2300 goto out_cancel_attach;
2303 } while_each_subsys_mask();
2307 * Now that we're guaranteed success, proceed to move all tasks to
2308 * the new cgroup. There are no failure cases after here, so this
2309 * is the commit point.
2311 spin_lock_irq(&css_set_lock);
2312 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2313 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2314 struct css_set *from_cset = task_css_set(task);
2315 struct css_set *to_cset = cset->mg_dst_cset;
2317 get_css_set(to_cset);
2318 to_cset->nr_tasks++;
2319 css_set_move_task(task, from_cset, to_cset, true);
2320 put_css_set_locked(from_cset);
2321 from_cset->nr_tasks--;
2324 spin_unlock_irq(&css_set_lock);
2327 * Migration is committed, all target tasks are now on dst_csets.
2328 * Nothing is sensitive to fork() after this point. Notify
2329 * controllers that migration is complete.
2331 tset->csets = &tset->dst_csets;
2333 if (tset->nr_tasks) {
2334 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2335 if (ss->attach) {
2336 tset->ssid = ssid;
2337 ss->attach(tset);
2339 } while_each_subsys_mask();
2342 ret = 0;
2343 goto out_release_tset;
2345 out_cancel_attach:
2346 if (tset->nr_tasks) {
2347 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2348 if (ssid == failed_ssid)
2349 break;
2350 if (ss->cancel_attach) {
2351 tset->ssid = ssid;
2352 ss->cancel_attach(tset);
2354 } while_each_subsys_mask();
2356 out_release_tset:
2357 spin_lock_irq(&css_set_lock);
2358 list_splice_init(&tset->dst_csets, &tset->src_csets);
2359 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2360 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2361 list_del_init(&cset->mg_node);
2363 spin_unlock_irq(&css_set_lock);
2366 * Re-initialize the cgroup_taskset structure in case it is reused
2367 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2368 * iteration.
2370 tset->nr_tasks = 0;
2371 tset->csets = &tset->src_csets;
2372 return ret;
2376 * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2377 * @dst_cgrp: destination cgroup to test
2379 * On the default hierarchy, except for the mixable, (possible) thread root
2380 * and threaded cgroups, subtree_control must be zero for migration
2381 * destination cgroups with tasks so that child cgroups don't compete
2382 * against tasks.
2384 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2386 /* v1 doesn't have any restriction */
2387 if (!cgroup_on_dfl(dst_cgrp))
2388 return 0;
2390 /* verify @dst_cgrp can host resources */
2391 if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2392 return -EOPNOTSUPP;
2394 /* mixables don't care */
2395 if (cgroup_is_mixable(dst_cgrp))
2396 return 0;
2399 * If @dst_cgrp is already or can become a thread root or is
2400 * threaded, it doesn't matter.
2402 if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2403 return 0;
2405 /* apply no-internal-process constraint */
2406 if (dst_cgrp->subtree_control)
2407 return -EBUSY;
2409 return 0;
2413 * cgroup_migrate_finish - cleanup after attach
2414 * @mgctx: migration context
2416 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2417 * those functions for details.
2419 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2421 LIST_HEAD(preloaded);
2422 struct css_set *cset, *tmp_cset;
2424 lockdep_assert_held(&cgroup_mutex);
2426 spin_lock_irq(&css_set_lock);
2428 list_splice_tail_init(&mgctx->preloaded_src_csets, &preloaded);
2429 list_splice_tail_init(&mgctx->preloaded_dst_csets, &preloaded);
2431 list_for_each_entry_safe(cset, tmp_cset, &preloaded, mg_preload_node) {
2432 cset->mg_src_cgrp = NULL;
2433 cset->mg_dst_cgrp = NULL;
2434 cset->mg_dst_cset = NULL;
2435 list_del_init(&cset->mg_preload_node);
2436 put_css_set_locked(cset);
2439 spin_unlock_irq(&css_set_lock);
2443 * cgroup_migrate_add_src - add a migration source css_set
2444 * @src_cset: the source css_set to add
2445 * @dst_cgrp: the destination cgroup
2446 * @mgctx: migration context
2448 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2449 * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2450 * up by cgroup_migrate_finish().
2452 * This function may be called without holding cgroup_threadgroup_rwsem
2453 * even if the target is a process. Threads may be created and destroyed
2454 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2455 * into play and the preloaded css_sets are guaranteed to cover all
2456 * migrations.
2458 void cgroup_migrate_add_src(struct css_set *src_cset,
2459 struct cgroup *dst_cgrp,
2460 struct cgroup_mgctx *mgctx)
2462 struct cgroup *src_cgrp;
2464 lockdep_assert_held(&cgroup_mutex);
2465 lockdep_assert_held(&css_set_lock);
2468 * If ->dead, @src_set is associated with one or more dead cgroups
2469 * and doesn't contain any migratable tasks. Ignore it early so
2470 * that the rest of migration path doesn't get confused by it.
2472 if (src_cset->dead)
2473 return;
2475 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2477 if (!list_empty(&src_cset->mg_preload_node))
2478 return;
2480 WARN_ON(src_cset->mg_src_cgrp);
2481 WARN_ON(src_cset->mg_dst_cgrp);
2482 WARN_ON(!list_empty(&src_cset->mg_tasks));
2483 WARN_ON(!list_empty(&src_cset->mg_node));
2485 src_cset->mg_src_cgrp = src_cgrp;
2486 src_cset->mg_dst_cgrp = dst_cgrp;
2487 get_css_set(src_cset);
2488 list_add_tail(&src_cset->mg_preload_node, &mgctx->preloaded_src_csets);
2492 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2493 * @mgctx: migration context
2495 * Tasks are about to be moved and all the source css_sets have been
2496 * preloaded to @mgctx->preloaded_src_csets. This function looks up and
2497 * pins all destination css_sets, links each to its source, and append them
2498 * to @mgctx->preloaded_dst_csets.
2500 * This function must be called after cgroup_migrate_add_src() has been
2501 * called on each migration source css_set. After migration is performed
2502 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2503 * @mgctx.
2505 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2507 struct css_set *src_cset, *tmp_cset;
2509 lockdep_assert_held(&cgroup_mutex);
2511 /* look up the dst cset for each src cset and link it to src */
2512 list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2513 mg_preload_node) {
2514 struct css_set *dst_cset;
2515 struct cgroup_subsys *ss;
2516 int ssid;
2518 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2519 if (!dst_cset)
2520 goto err;
2522 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2525 * If src cset equals dst, it's noop. Drop the src.
2526 * cgroup_migrate() will skip the cset too. Note that we
2527 * can't handle src == dst as some nodes are used by both.
2529 if (src_cset == dst_cset) {
2530 src_cset->mg_src_cgrp = NULL;
2531 src_cset->mg_dst_cgrp = NULL;
2532 list_del_init(&src_cset->mg_preload_node);
2533 put_css_set(src_cset);
2534 put_css_set(dst_cset);
2535 continue;
2538 src_cset->mg_dst_cset = dst_cset;
2540 if (list_empty(&dst_cset->mg_preload_node))
2541 list_add_tail(&dst_cset->mg_preload_node,
2542 &mgctx->preloaded_dst_csets);
2543 else
2544 put_css_set(dst_cset);
2546 for_each_subsys(ss, ssid)
2547 if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2548 mgctx->ss_mask |= 1 << ssid;
2551 return 0;
2552 err:
2553 cgroup_migrate_finish(mgctx);
2554 return -ENOMEM;
2558 * cgroup_migrate - migrate a process or task to a cgroup
2559 * @leader: the leader of the process or the task to migrate
2560 * @threadgroup: whether @leader points to the whole process or a single task
2561 * @mgctx: migration context
2563 * Migrate a process or task denoted by @leader. If migrating a process,
2564 * the caller must be holding cgroup_threadgroup_rwsem. The caller is also
2565 * responsible for invoking cgroup_migrate_add_src() and
2566 * cgroup_migrate_prepare_dst() on the targets before invoking this
2567 * function and following up with cgroup_migrate_finish().
2569 * As long as a controller's ->can_attach() doesn't fail, this function is
2570 * guaranteed to succeed. This means that, excluding ->can_attach()
2571 * failure, when migrating multiple targets, the success or failure can be
2572 * decided for all targets by invoking group_migrate_prepare_dst() before
2573 * actually starting migrating.
2575 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2576 struct cgroup_mgctx *mgctx)
2578 struct task_struct *task;
2581 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2582 * already PF_EXITING could be freed from underneath us unless we
2583 * take an rcu_read_lock.
2585 spin_lock_irq(&css_set_lock);
2586 rcu_read_lock();
2587 task = leader;
2588 do {
2589 cgroup_migrate_add_task(task, mgctx);
2590 if (!threadgroup)
2591 break;
2592 } while_each_thread(leader, task);
2593 rcu_read_unlock();
2594 spin_unlock_irq(&css_set_lock);
2596 return cgroup_migrate_execute(mgctx);
2600 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2601 * @dst_cgrp: the cgroup to attach to
2602 * @leader: the task or the leader of the threadgroup to be attached
2603 * @threadgroup: attach the whole threadgroup?
2605 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2607 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2608 bool threadgroup)
2610 DEFINE_CGROUP_MGCTX(mgctx);
2611 struct task_struct *task;
2612 int ret;
2614 ret = cgroup_migrate_vet_dst(dst_cgrp);
2615 if (ret)
2616 return ret;
2618 /* look up all src csets */
2619 spin_lock_irq(&css_set_lock);
2620 rcu_read_lock();
2621 task = leader;
2622 do {
2623 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2624 if (!threadgroup)
2625 break;
2626 } while_each_thread(leader, task);
2627 rcu_read_unlock();
2628 spin_unlock_irq(&css_set_lock);
2630 /* prepare dst csets and commit */
2631 ret = cgroup_migrate_prepare_dst(&mgctx);
2632 if (!ret)
2633 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2635 cgroup_migrate_finish(&mgctx);
2637 if (!ret)
2638 trace_cgroup_attach_task(dst_cgrp, leader, threadgroup);
2640 return ret;
2643 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup)
2644 __acquires(&cgroup_threadgroup_rwsem)
2646 struct task_struct *tsk;
2647 pid_t pid;
2649 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2650 return ERR_PTR(-EINVAL);
2652 percpu_down_write(&cgroup_threadgroup_rwsem);
2654 rcu_read_lock();
2655 if (pid) {
2656 tsk = find_task_by_vpid(pid);
2657 if (!tsk) {
2658 tsk = ERR_PTR(-ESRCH);
2659 goto out_unlock_threadgroup;
2661 } else {
2662 tsk = current;
2665 if (threadgroup)
2666 tsk = tsk->group_leader;
2669 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2670 * If userland migrates such a kthread to a non-root cgroup, it can
2671 * become trapped in a cpuset, or RT kthread may be born in a
2672 * cgroup with no rt_runtime allocated. Just say no.
2674 if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2675 tsk = ERR_PTR(-EINVAL);
2676 goto out_unlock_threadgroup;
2679 get_task_struct(tsk);
2680 goto out_unlock_rcu;
2682 out_unlock_threadgroup:
2683 percpu_up_write(&cgroup_threadgroup_rwsem);
2684 out_unlock_rcu:
2685 rcu_read_unlock();
2686 return tsk;
2689 void cgroup_procs_write_finish(struct task_struct *task)
2690 __releases(&cgroup_threadgroup_rwsem)
2692 struct cgroup_subsys *ss;
2693 int ssid;
2695 /* release reference from cgroup_procs_write_start() */
2696 put_task_struct(task);
2698 percpu_up_write(&cgroup_threadgroup_rwsem);
2699 for_each_subsys(ss, ssid)
2700 if (ss->post_attach)
2701 ss->post_attach();
2704 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2706 struct cgroup_subsys *ss;
2707 bool printed = false;
2708 int ssid;
2710 do_each_subsys_mask(ss, ssid, ss_mask) {
2711 if (printed)
2712 seq_putc(seq, ' ');
2713 seq_printf(seq, "%s", ss->name);
2714 printed = true;
2715 } while_each_subsys_mask();
2716 if (printed)
2717 seq_putc(seq, '\n');
2720 /* show controllers which are enabled from the parent */
2721 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2723 struct cgroup *cgrp = seq_css(seq)->cgroup;
2725 cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2726 return 0;
2729 /* show controllers which are enabled for a given cgroup's children */
2730 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2732 struct cgroup *cgrp = seq_css(seq)->cgroup;
2734 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2735 return 0;
2739 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2740 * @cgrp: root of the subtree to update csses for
2742 * @cgrp's control masks have changed and its subtree's css associations
2743 * need to be updated accordingly. This function looks up all css_sets
2744 * which are attached to the subtree, creates the matching updated css_sets
2745 * and migrates the tasks to the new ones.
2747 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2749 DEFINE_CGROUP_MGCTX(mgctx);
2750 struct cgroup_subsys_state *d_css;
2751 struct cgroup *dsct;
2752 struct css_set *src_cset;
2753 int ret;
2755 lockdep_assert_held(&cgroup_mutex);
2757 percpu_down_write(&cgroup_threadgroup_rwsem);
2759 /* look up all csses currently attached to @cgrp's subtree */
2760 spin_lock_irq(&css_set_lock);
2761 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2762 struct cgrp_cset_link *link;
2764 list_for_each_entry(link, &dsct->cset_links, cset_link)
2765 cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2767 spin_unlock_irq(&css_set_lock);
2769 /* NULL dst indicates self on default hierarchy */
2770 ret = cgroup_migrate_prepare_dst(&mgctx);
2771 if (ret)
2772 goto out_finish;
2774 spin_lock_irq(&css_set_lock);
2775 list_for_each_entry(src_cset, &mgctx.preloaded_src_csets, mg_preload_node) {
2776 struct task_struct *task, *ntask;
2778 /* all tasks in src_csets need to be migrated */
2779 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2780 cgroup_migrate_add_task(task, &mgctx);
2782 spin_unlock_irq(&css_set_lock);
2784 ret = cgroup_migrate_execute(&mgctx);
2785 out_finish:
2786 cgroup_migrate_finish(&mgctx);
2787 percpu_up_write(&cgroup_threadgroup_rwsem);
2788 return ret;
2792 * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2793 * @cgrp: root of the target subtree
2795 * Because css offlining is asynchronous, userland may try to re-enable a
2796 * controller while the previous css is still around. This function grabs
2797 * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2799 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2800 __acquires(&cgroup_mutex)
2802 struct cgroup *dsct;
2803 struct cgroup_subsys_state *d_css;
2804 struct cgroup_subsys *ss;
2805 int ssid;
2807 restart:
2808 mutex_lock(&cgroup_mutex);
2810 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2811 for_each_subsys(ss, ssid) {
2812 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2813 DEFINE_WAIT(wait);
2815 if (!css || !percpu_ref_is_dying(&css->refcnt))
2816 continue;
2818 cgroup_get_live(dsct);
2819 prepare_to_wait(&dsct->offline_waitq, &wait,
2820 TASK_UNINTERRUPTIBLE);
2822 mutex_unlock(&cgroup_mutex);
2823 schedule();
2824 finish_wait(&dsct->offline_waitq, &wait);
2826 cgroup_put(dsct);
2827 goto restart;
2833 * cgroup_save_control - save control masks of a subtree
2834 * @cgrp: root of the target subtree
2836 * Save ->subtree_control and ->subtree_ss_mask to the respective old_
2837 * prefixed fields for @cgrp's subtree including @cgrp itself.
2839 static void cgroup_save_control(struct cgroup *cgrp)
2841 struct cgroup *dsct;
2842 struct cgroup_subsys_state *d_css;
2844 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2845 dsct->old_subtree_control = dsct->subtree_control;
2846 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
2851 * cgroup_propagate_control - refresh control masks of a subtree
2852 * @cgrp: root of the target subtree
2854 * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
2855 * ->subtree_control and propagate controller availability through the
2856 * subtree so that descendants don't have unavailable controllers enabled.
2858 static void cgroup_propagate_control(struct cgroup *cgrp)
2860 struct cgroup *dsct;
2861 struct cgroup_subsys_state *d_css;
2863 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2864 dsct->subtree_control &= cgroup_control(dsct);
2865 dsct->subtree_ss_mask =
2866 cgroup_calc_subtree_ss_mask(dsct->subtree_control,
2867 cgroup_ss_mask(dsct));
2872 * cgroup_restore_control - restore control masks of a subtree
2873 * @cgrp: root of the target subtree
2875 * Restore ->subtree_control and ->subtree_ss_mask from the respective old_
2876 * prefixed fields for @cgrp's subtree including @cgrp itself.
2878 static void cgroup_restore_control(struct cgroup *cgrp)
2880 struct cgroup *dsct;
2881 struct cgroup_subsys_state *d_css;
2883 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2884 dsct->subtree_control = dsct->old_subtree_control;
2885 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
2889 static bool css_visible(struct cgroup_subsys_state *css)
2891 struct cgroup_subsys *ss = css->ss;
2892 struct cgroup *cgrp = css->cgroup;
2894 if (cgroup_control(cgrp) & (1 << ss->id))
2895 return true;
2896 if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
2897 return false;
2898 return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
2902 * cgroup_apply_control_enable - enable or show csses according to control
2903 * @cgrp: root of the target subtree
2905 * Walk @cgrp's subtree and create new csses or make the existing ones
2906 * visible. A css is created invisible if it's being implicitly enabled
2907 * through dependency. An invisible css is made visible when the userland
2908 * explicitly enables it.
2910 * Returns 0 on success, -errno on failure. On failure, csses which have
2911 * been processed already aren't cleaned up. The caller is responsible for
2912 * cleaning up with cgroup_apply_control_disable().
2914 static int cgroup_apply_control_enable(struct cgroup *cgrp)
2916 struct cgroup *dsct;
2917 struct cgroup_subsys_state *d_css;
2918 struct cgroup_subsys *ss;
2919 int ssid, ret;
2921 cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2922 for_each_subsys(ss, ssid) {
2923 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2925 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
2927 if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
2928 continue;
2930 if (!css) {
2931 css = css_create(dsct, ss);
2932 if (IS_ERR(css))
2933 return PTR_ERR(css);
2936 if (css_visible(css)) {
2937 ret = css_populate_dir(css);
2938 if (ret)
2939 return ret;
2944 return 0;
2948 * cgroup_apply_control_disable - kill or hide csses according to control
2949 * @cgrp: root of the target subtree
2951 * Walk @cgrp's subtree and kill and hide csses so that they match
2952 * cgroup_ss_mask() and cgroup_visible_mask().
2954 * A css is hidden when the userland requests it to be disabled while other
2955 * subsystems are still depending on it. The css must not actively control
2956 * resources and be in the vanilla state if it's made visible again later.
2957 * Controllers which may be depended upon should provide ->css_reset() for
2958 * this purpose.
2960 static void cgroup_apply_control_disable(struct cgroup *cgrp)
2962 struct cgroup *dsct;
2963 struct cgroup_subsys_state *d_css;
2964 struct cgroup_subsys *ss;
2965 int ssid;
2967 cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2968 for_each_subsys(ss, ssid) {
2969 struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2971 WARN_ON_ONCE(css && percpu_ref_is_dying(&css->refcnt));
2973 if (!css)
2974 continue;
2976 if (css->parent &&
2977 !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
2978 kill_css(css);
2979 } else if (!css_visible(css)) {
2980 css_clear_dir(css);
2981 if (ss->css_reset)
2982 ss->css_reset(css);
2989 * cgroup_apply_control - apply control mask updates to the subtree
2990 * @cgrp: root of the target subtree
2992 * subsystems can be enabled and disabled in a subtree using the following
2993 * steps.
2995 * 1. Call cgroup_save_control() to stash the current state.
2996 * 2. Update ->subtree_control masks in the subtree as desired.
2997 * 3. Call cgroup_apply_control() to apply the changes.
2998 * 4. Optionally perform other related operations.
2999 * 5. Call cgroup_finalize_control() to finish up.
3001 * This function implements step 3 and propagates the mask changes
3002 * throughout @cgrp's subtree, updates csses accordingly and perform
3003 * process migrations.
3005 static int cgroup_apply_control(struct cgroup *cgrp)
3007 int ret;
3009 cgroup_propagate_control(cgrp);
3011 ret = cgroup_apply_control_enable(cgrp);
3012 if (ret)
3013 return ret;
3016 * At this point, cgroup_e_css() results reflect the new csses
3017 * making the following cgroup_update_dfl_csses() properly update
3018 * css associations of all tasks in the subtree.
3020 ret = cgroup_update_dfl_csses(cgrp);
3021 if (ret)
3022 return ret;
3024 return 0;
3028 * cgroup_finalize_control - finalize control mask update
3029 * @cgrp: root of the target subtree
3030 * @ret: the result of the update
3032 * Finalize control mask update. See cgroup_apply_control() for more info.
3034 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3036 if (ret) {
3037 cgroup_restore_control(cgrp);
3038 cgroup_propagate_control(cgrp);
3041 cgroup_apply_control_disable(cgrp);
3044 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3046 u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3048 /* if nothing is getting enabled, nothing to worry about */
3049 if (!enable)
3050 return 0;
3052 /* can @cgrp host any resources? */
3053 if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3054 return -EOPNOTSUPP;
3056 /* mixables don't care */
3057 if (cgroup_is_mixable(cgrp))
3058 return 0;
3060 if (domain_enable) {
3061 /* can't enable domain controllers inside a thread subtree */
3062 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3063 return -EOPNOTSUPP;
3064 } else {
3066 * Threaded controllers can handle internal competitions
3067 * and are always allowed inside a (prospective) thread
3068 * subtree.
3070 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3071 return 0;
3075 * Controllers can't be enabled for a cgroup with tasks to avoid
3076 * child cgroups competing against tasks.
3078 if (cgroup_has_tasks(cgrp))
3079 return -EBUSY;
3081 return 0;
3084 /* change the enabled child controllers for a cgroup in the default hierarchy */
3085 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3086 char *buf, size_t nbytes,
3087 loff_t off)
3089 u16 enable = 0, disable = 0;
3090 struct cgroup *cgrp, *child;
3091 struct cgroup_subsys *ss;
3092 char *tok;
3093 int ssid, ret;
3096 * Parse input - space separated list of subsystem names prefixed
3097 * with either + or -.
3099 buf = strstrip(buf);
3100 while ((tok = strsep(&buf, " "))) {
3101 if (tok[0] == '\0')
3102 continue;
3103 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3104 if (!cgroup_ssid_enabled(ssid) ||
3105 strcmp(tok + 1, ss->name))
3106 continue;
3108 if (*tok == '+') {
3109 enable |= 1 << ssid;
3110 disable &= ~(1 << ssid);
3111 } else if (*tok == '-') {
3112 disable |= 1 << ssid;
3113 enable &= ~(1 << ssid);
3114 } else {
3115 return -EINVAL;
3117 break;
3118 } while_each_subsys_mask();
3119 if (ssid == CGROUP_SUBSYS_COUNT)
3120 return -EINVAL;
3123 cgrp = cgroup_kn_lock_live(of->kn, true);
3124 if (!cgrp)
3125 return -ENODEV;
3127 for_each_subsys(ss, ssid) {
3128 if (enable & (1 << ssid)) {
3129 if (cgrp->subtree_control & (1 << ssid)) {
3130 enable &= ~(1 << ssid);
3131 continue;
3134 if (!(cgroup_control(cgrp) & (1 << ssid))) {
3135 ret = -ENOENT;
3136 goto out_unlock;
3138 } else if (disable & (1 << ssid)) {
3139 if (!(cgrp->subtree_control & (1 << ssid))) {
3140 disable &= ~(1 << ssid);
3141 continue;
3144 /* a child has it enabled? */
3145 cgroup_for_each_live_child(child, cgrp) {
3146 if (child->subtree_control & (1 << ssid)) {
3147 ret = -EBUSY;
3148 goto out_unlock;
3154 if (!enable && !disable) {
3155 ret = 0;
3156 goto out_unlock;
3159 ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3160 if (ret)
3161 goto out_unlock;
3163 /* save and update control masks and prepare csses */
3164 cgroup_save_control(cgrp);
3166 cgrp->subtree_control |= enable;
3167 cgrp->subtree_control &= ~disable;
3169 ret = cgroup_apply_control(cgrp);
3170 cgroup_finalize_control(cgrp, ret);
3171 if (ret)
3172 goto out_unlock;
3174 kernfs_activate(cgrp->kn);
3175 out_unlock:
3176 cgroup_kn_unlock(of->kn);
3177 return ret ?: nbytes;
3181 * cgroup_enable_threaded - make @cgrp threaded
3182 * @cgrp: the target cgroup
3184 * Called when "threaded" is written to the cgroup.type interface file and
3185 * tries to make @cgrp threaded and join the parent's resource domain.
3186 * This function is never called on the root cgroup as cgroup.type doesn't
3187 * exist on it.
3189 static int cgroup_enable_threaded(struct cgroup *cgrp)
3191 struct cgroup *parent = cgroup_parent(cgrp);
3192 struct cgroup *dom_cgrp = parent->dom_cgrp;
3193 int ret;
3195 lockdep_assert_held(&cgroup_mutex);
3197 /* noop if already threaded */
3198 if (cgroup_is_threaded(cgrp))
3199 return 0;
3202 * If @cgroup is populated or has domain controllers enabled, it
3203 * can't be switched. While the below cgroup_can_be_thread_root()
3204 * test can catch the same conditions, that's only when @parent is
3205 * not mixable, so let's check it explicitly.
3207 if (cgroup_is_populated(cgrp) ||
3208 cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3209 return -EOPNOTSUPP;
3211 /* we're joining the parent's domain, ensure its validity */
3212 if (!cgroup_is_valid_domain(dom_cgrp) ||
3213 !cgroup_can_be_thread_root(dom_cgrp))
3214 return -EOPNOTSUPP;
3217 * The following shouldn't cause actual migrations and should
3218 * always succeed.
3220 cgroup_save_control(cgrp);
3222 cgrp->dom_cgrp = dom_cgrp;
3223 ret = cgroup_apply_control(cgrp);
3224 if (!ret)
3225 parent->nr_threaded_children++;
3226 else
3227 cgrp->dom_cgrp = cgrp;
3229 cgroup_finalize_control(cgrp, ret);
3230 return ret;
3233 static int cgroup_type_show(struct seq_file *seq, void *v)
3235 struct cgroup *cgrp = seq_css(seq)->cgroup;
3237 if (cgroup_is_threaded(cgrp))
3238 seq_puts(seq, "threaded\n");
3239 else if (!cgroup_is_valid_domain(cgrp))
3240 seq_puts(seq, "domain invalid\n");
3241 else if (cgroup_is_thread_root(cgrp))
3242 seq_puts(seq, "domain threaded\n");
3243 else
3244 seq_puts(seq, "domain\n");
3246 return 0;
3249 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3250 size_t nbytes, loff_t off)
3252 struct cgroup *cgrp;
3253 int ret;
3255 /* only switching to threaded mode is supported */
3256 if (strcmp(strstrip(buf), "threaded"))
3257 return -EINVAL;
3259 cgrp = cgroup_kn_lock_live(of->kn, false);
3260 if (!cgrp)
3261 return -ENOENT;
3263 /* threaded can only be enabled */
3264 ret = cgroup_enable_threaded(cgrp);
3266 cgroup_kn_unlock(of->kn);
3267 return ret ?: nbytes;
3270 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3272 struct cgroup *cgrp = seq_css(seq)->cgroup;
3273 int descendants = READ_ONCE(cgrp->max_descendants);
3275 if (descendants == INT_MAX)
3276 seq_puts(seq, "max\n");
3277 else
3278 seq_printf(seq, "%d\n", descendants);
3280 return 0;
3283 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3284 char *buf, size_t nbytes, loff_t off)
3286 struct cgroup *cgrp;
3287 int descendants;
3288 ssize_t ret;
3290 buf = strstrip(buf);
3291 if (!strcmp(buf, "max")) {
3292 descendants = INT_MAX;
3293 } else {
3294 ret = kstrtoint(buf, 0, &descendants);
3295 if (ret)
3296 return ret;
3299 if (descendants < 0)
3300 return -ERANGE;
3302 cgrp = cgroup_kn_lock_live(of->kn, false);
3303 if (!cgrp)
3304 return -ENOENT;
3306 cgrp->max_descendants = descendants;
3308 cgroup_kn_unlock(of->kn);
3310 return nbytes;
3313 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3315 struct cgroup *cgrp = seq_css(seq)->cgroup;
3316 int depth = READ_ONCE(cgrp->max_depth);
3318 if (depth == INT_MAX)
3319 seq_puts(seq, "max\n");
3320 else
3321 seq_printf(seq, "%d\n", depth);
3323 return 0;
3326 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3327 char *buf, size_t nbytes, loff_t off)
3329 struct cgroup *cgrp;
3330 ssize_t ret;
3331 int depth;
3333 buf = strstrip(buf);
3334 if (!strcmp(buf, "max")) {
3335 depth = INT_MAX;
3336 } else {
3337 ret = kstrtoint(buf, 0, &depth);
3338 if (ret)
3339 return ret;
3342 if (depth < 0)
3343 return -ERANGE;
3345 cgrp = cgroup_kn_lock_live(of->kn, false);
3346 if (!cgrp)
3347 return -ENOENT;
3349 cgrp->max_depth = depth;
3351 cgroup_kn_unlock(of->kn);
3353 return nbytes;
3356 static int cgroup_events_show(struct seq_file *seq, void *v)
3358 seq_printf(seq, "populated %d\n",
3359 cgroup_is_populated(seq_css(seq)->cgroup));
3360 return 0;
3363 static int cgroup_stat_show(struct seq_file *seq, void *v)
3365 struct cgroup *cgroup = seq_css(seq)->cgroup;
3367 seq_printf(seq, "nr_descendants %d\n",
3368 cgroup->nr_descendants);
3369 seq_printf(seq, "nr_dying_descendants %d\n",
3370 cgroup->nr_dying_descendants);
3372 return 0;
3375 static int __maybe_unused cgroup_extra_stat_show(struct seq_file *seq,
3376 struct cgroup *cgrp, int ssid)
3378 struct cgroup_subsys *ss = cgroup_subsys[ssid];
3379 struct cgroup_subsys_state *css;
3380 int ret;
3382 if (!ss->css_extra_stat_show)
3383 return 0;
3385 css = cgroup_tryget_css(cgrp, ss);
3386 if (!css)
3387 return 0;
3389 ret = ss->css_extra_stat_show(seq, css);
3390 css_put(css);
3391 return ret;
3394 static int cpu_stat_show(struct seq_file *seq, void *v)
3396 struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3397 int ret = 0;
3399 cgroup_stat_show_cputime(seq);
3400 #ifdef CONFIG_CGROUP_SCHED
3401 ret = cgroup_extra_stat_show(seq, cgrp, cpu_cgrp_id);
3402 #endif
3403 return ret;
3406 static int cgroup_file_open(struct kernfs_open_file *of)
3408 struct cftype *cft = of->kn->priv;
3410 if (cft->open)
3411 return cft->open(of);
3412 return 0;
3415 static void cgroup_file_release(struct kernfs_open_file *of)
3417 struct cftype *cft = of->kn->priv;
3419 if (cft->release)
3420 cft->release(of);
3423 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3424 size_t nbytes, loff_t off)
3426 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
3427 struct cgroup *cgrp = of->kn->parent->priv;
3428 struct cftype *cft = of->kn->priv;
3429 struct cgroup_subsys_state *css;
3430 int ret;
3433 * If namespaces are delegation boundaries, disallow writes to
3434 * files in an non-init namespace root from inside the namespace
3435 * except for the files explicitly marked delegatable -
3436 * cgroup.procs and cgroup.subtree_control.
3438 if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3439 !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3440 ns != &init_cgroup_ns && ns->root_cset->dfl_cgrp == cgrp)
3441 return -EPERM;
3443 if (cft->write)
3444 return cft->write(of, buf, nbytes, off);
3447 * kernfs guarantees that a file isn't deleted with operations in
3448 * flight, which means that the matching css is and stays alive and
3449 * doesn't need to be pinned. The RCU locking is not necessary
3450 * either. It's just for the convenience of using cgroup_css().
3452 rcu_read_lock();
3453 css = cgroup_css(cgrp, cft->ss);
3454 rcu_read_unlock();
3456 if (cft->write_u64) {
3457 unsigned long long v;
3458 ret = kstrtoull(buf, 0, &v);
3459 if (!ret)
3460 ret = cft->write_u64(css, cft, v);
3461 } else if (cft->write_s64) {
3462 long long v;
3463 ret = kstrtoll(buf, 0, &v);
3464 if (!ret)
3465 ret = cft->write_s64(css, cft, v);
3466 } else {
3467 ret = -EINVAL;
3470 return ret ?: nbytes;
3473 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3475 return seq_cft(seq)->seq_start(seq, ppos);
3478 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3480 return seq_cft(seq)->seq_next(seq, v, ppos);
3483 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3485 if (seq_cft(seq)->seq_stop)
3486 seq_cft(seq)->seq_stop(seq, v);
3489 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3491 struct cftype *cft = seq_cft(m);
3492 struct cgroup_subsys_state *css = seq_css(m);
3494 if (cft->seq_show)
3495 return cft->seq_show(m, arg);
3497 if (cft->read_u64)
3498 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3499 else if (cft->read_s64)
3500 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3501 else
3502 return -EINVAL;
3503 return 0;
3506 static struct kernfs_ops cgroup_kf_single_ops = {
3507 .atomic_write_len = PAGE_SIZE,
3508 .open = cgroup_file_open,
3509 .release = cgroup_file_release,
3510 .write = cgroup_file_write,
3511 .seq_show = cgroup_seqfile_show,
3514 static struct kernfs_ops cgroup_kf_ops = {
3515 .atomic_write_len = PAGE_SIZE,
3516 .open = cgroup_file_open,
3517 .release = cgroup_file_release,
3518 .write = cgroup_file_write,
3519 .seq_start = cgroup_seqfile_start,
3520 .seq_next = cgroup_seqfile_next,
3521 .seq_stop = cgroup_seqfile_stop,
3522 .seq_show = cgroup_seqfile_show,
3525 /* set uid and gid of cgroup dirs and files to that of the creator */
3526 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3528 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3529 .ia_uid = current_fsuid(),
3530 .ia_gid = current_fsgid(), };
3532 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3533 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3534 return 0;
3536 return kernfs_setattr(kn, &iattr);
3539 static void cgroup_file_notify_timer(struct timer_list *timer)
3541 cgroup_file_notify(container_of(timer, struct cgroup_file,
3542 notify_timer));
3545 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
3546 struct cftype *cft)
3548 char name[CGROUP_FILE_NAME_MAX];
3549 struct kernfs_node *kn;
3550 struct lock_class_key *key = NULL;
3551 int ret;
3553 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3554 key = &cft->lockdep_key;
3555 #endif
3556 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3557 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
3558 NULL, key);
3559 if (IS_ERR(kn))
3560 return PTR_ERR(kn);
3562 ret = cgroup_kn_set_ugid(kn);
3563 if (ret) {
3564 kernfs_remove(kn);
3565 return ret;
3568 if (cft->file_offset) {
3569 struct cgroup_file *cfile = (void *)css + cft->file_offset;
3571 timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
3573 spin_lock_irq(&cgroup_file_kn_lock);
3574 cfile->kn = kn;
3575 spin_unlock_irq(&cgroup_file_kn_lock);
3578 return 0;
3582 * cgroup_addrm_files - add or remove files to a cgroup directory
3583 * @css: the target css
3584 * @cgrp: the target cgroup (usually css->cgroup)
3585 * @cfts: array of cftypes to be added
3586 * @is_add: whether to add or remove
3588 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3589 * For removals, this function never fails.
3591 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
3592 struct cgroup *cgrp, struct cftype cfts[],
3593 bool is_add)
3595 struct cftype *cft, *cft_end = NULL;
3596 int ret = 0;
3598 lockdep_assert_held(&cgroup_mutex);
3600 restart:
3601 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
3602 /* does cft->flags tell us to skip this file on @cgrp? */
3603 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3604 continue;
3605 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3606 continue;
3607 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3608 continue;
3609 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3610 continue;
3612 if (is_add) {
3613 ret = cgroup_add_file(css, cgrp, cft);
3614 if (ret) {
3615 pr_warn("%s: failed to add %s, err=%d\n",
3616 __func__, cft->name, ret);
3617 cft_end = cft;
3618 is_add = false;
3619 goto restart;
3621 } else {
3622 cgroup_rm_file(cgrp, cft);
3625 return ret;
3628 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3630 struct cgroup_subsys *ss = cfts[0].ss;
3631 struct cgroup *root = &ss->root->cgrp;
3632 struct cgroup_subsys_state *css;
3633 int ret = 0;
3635 lockdep_assert_held(&cgroup_mutex);
3637 /* add/rm files for all cgroups created before */
3638 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3639 struct cgroup *cgrp = css->cgroup;
3641 if (!(css->flags & CSS_VISIBLE))
3642 continue;
3644 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
3645 if (ret)
3646 break;
3649 if (is_add && !ret)
3650 kernfs_activate(root->kn);
3651 return ret;
3654 static void cgroup_exit_cftypes(struct cftype *cfts)
3656 struct cftype *cft;
3658 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3659 /* free copy for custom atomic_write_len, see init_cftypes() */
3660 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3661 kfree(cft->kf_ops);
3662 cft->kf_ops = NULL;
3663 cft->ss = NULL;
3665 /* revert flags set by cgroup core while adding @cfts */
3666 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3670 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3672 struct cftype *cft;
3674 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3675 struct kernfs_ops *kf_ops;
3677 WARN_ON(cft->ss || cft->kf_ops);
3679 if (cft->seq_start)
3680 kf_ops = &cgroup_kf_ops;
3681 else
3682 kf_ops = &cgroup_kf_single_ops;
3685 * Ugh... if @cft wants a custom max_write_len, we need to
3686 * make a copy of kf_ops to set its atomic_write_len.
3688 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3689 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3690 if (!kf_ops) {
3691 cgroup_exit_cftypes(cfts);
3692 return -ENOMEM;
3694 kf_ops->atomic_write_len = cft->max_write_len;
3697 cft->kf_ops = kf_ops;
3698 cft->ss = ss;
3701 return 0;
3704 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3706 lockdep_assert_held(&cgroup_mutex);
3708 if (!cfts || !cfts[0].ss)
3709 return -ENOENT;
3711 list_del(&cfts->node);
3712 cgroup_apply_cftypes(cfts, false);
3713 cgroup_exit_cftypes(cfts);
3714 return 0;
3718 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3719 * @cfts: zero-length name terminated array of cftypes
3721 * Unregister @cfts. Files described by @cfts are removed from all
3722 * existing cgroups and all future cgroups won't have them either. This
3723 * function can be called anytime whether @cfts' subsys is attached or not.
3725 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3726 * registered.
3728 int cgroup_rm_cftypes(struct cftype *cfts)
3730 int ret;
3732 mutex_lock(&cgroup_mutex);
3733 ret = cgroup_rm_cftypes_locked(cfts);
3734 mutex_unlock(&cgroup_mutex);
3735 return ret;
3739 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3740 * @ss: target cgroup subsystem
3741 * @cfts: zero-length name terminated array of cftypes
3743 * Register @cfts to @ss. Files described by @cfts are created for all
3744 * existing cgroups to which @ss is attached and all future cgroups will
3745 * have them too. This function can be called anytime whether @ss is
3746 * attached or not.
3748 * Returns 0 on successful registration, -errno on failure. Note that this
3749 * function currently returns 0 as long as @cfts registration is successful
3750 * even if some file creation attempts on existing cgroups fail.
3752 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3754 int ret;
3756 if (!cgroup_ssid_enabled(ss->id))
3757 return 0;
3759 if (!cfts || cfts[0].name[0] == '\0')
3760 return 0;
3762 ret = cgroup_init_cftypes(ss, cfts);
3763 if (ret)
3764 return ret;
3766 mutex_lock(&cgroup_mutex);
3768 list_add_tail(&cfts->node, &ss->cfts);
3769 ret = cgroup_apply_cftypes(cfts, true);
3770 if (ret)
3771 cgroup_rm_cftypes_locked(cfts);
3773 mutex_unlock(&cgroup_mutex);
3774 return ret;
3778 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3779 * @ss: target cgroup subsystem
3780 * @cfts: zero-length name terminated array of cftypes
3782 * Similar to cgroup_add_cftypes() but the added files are only used for
3783 * the default hierarchy.
3785 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3787 struct cftype *cft;
3789 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3790 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3791 return cgroup_add_cftypes(ss, cfts);
3795 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3796 * @ss: target cgroup subsystem
3797 * @cfts: zero-length name terminated array of cftypes
3799 * Similar to cgroup_add_cftypes() but the added files are only used for
3800 * the legacy hierarchies.
3802 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3804 struct cftype *cft;
3806 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3807 cft->flags |= __CFTYPE_NOT_ON_DFL;
3808 return cgroup_add_cftypes(ss, cfts);
3812 * cgroup_file_notify - generate a file modified event for a cgroup_file
3813 * @cfile: target cgroup_file
3815 * @cfile must have been obtained by setting cftype->file_offset.
3817 void cgroup_file_notify(struct cgroup_file *cfile)
3819 unsigned long flags;
3821 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
3822 if (cfile->kn) {
3823 unsigned long last = cfile->notified_at;
3824 unsigned long next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
3826 if (time_in_range(jiffies, last, next)) {
3827 timer_reduce(&cfile->notify_timer, next);
3828 } else {
3829 kernfs_notify(cfile->kn);
3830 cfile->notified_at = jiffies;
3833 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
3837 * css_next_child - find the next child of a given css
3838 * @pos: the current position (%NULL to initiate traversal)
3839 * @parent: css whose children to walk
3841 * This function returns the next child of @parent and should be called
3842 * under either cgroup_mutex or RCU read lock. The only requirement is
3843 * that @parent and @pos are accessible. The next sibling is guaranteed to
3844 * be returned regardless of their states.
3846 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3847 * css which finished ->css_online() is guaranteed to be visible in the
3848 * future iterations and will stay visible until the last reference is put.
3849 * A css which hasn't finished ->css_online() or already finished
3850 * ->css_offline() may show up during traversal. It's each subsystem's
3851 * responsibility to synchronize against on/offlining.
3853 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3854 struct cgroup_subsys_state *parent)
3856 struct cgroup_subsys_state *next;
3858 cgroup_assert_mutex_or_rcu_locked();
3861 * @pos could already have been unlinked from the sibling list.
3862 * Once a cgroup is removed, its ->sibling.next is no longer
3863 * updated when its next sibling changes. CSS_RELEASED is set when
3864 * @pos is taken off list, at which time its next pointer is valid,
3865 * and, as releases are serialized, the one pointed to by the next
3866 * pointer is guaranteed to not have started release yet. This
3867 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3868 * critical section, the one pointed to by its next pointer is
3869 * guaranteed to not have finished its RCU grace period even if we
3870 * have dropped rcu_read_lock() inbetween iterations.
3872 * If @pos has CSS_RELEASED set, its next pointer can't be
3873 * dereferenced; however, as each css is given a monotonically
3874 * increasing unique serial number and always appended to the
3875 * sibling list, the next one can be found by walking the parent's
3876 * children until the first css with higher serial number than
3877 * @pos's. While this path can be slower, it happens iff iteration
3878 * races against release and the race window is very small.
3880 if (!pos) {
3881 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3882 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3883 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3884 } else {
3885 list_for_each_entry_rcu(next, &parent->children, sibling)
3886 if (next->serial_nr > pos->serial_nr)
3887 break;
3891 * @next, if not pointing to the head, can be dereferenced and is
3892 * the next sibling.
3894 if (&next->sibling != &parent->children)
3895 return next;
3896 return NULL;
3900 * css_next_descendant_pre - find the next descendant for pre-order walk
3901 * @pos: the current position (%NULL to initiate traversal)
3902 * @root: css whose descendants to walk
3904 * To be used by css_for_each_descendant_pre(). Find the next descendant
3905 * to visit for pre-order traversal of @root's descendants. @root is
3906 * included in the iteration and the first node to be visited.
3908 * While this function requires cgroup_mutex or RCU read locking, it
3909 * doesn't require the whole traversal to be contained in a single critical
3910 * section. This function will return the correct next descendant as long
3911 * as both @pos and @root are accessible and @pos is a descendant of @root.
3913 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3914 * css which finished ->css_online() is guaranteed to be visible in the
3915 * future iterations and will stay visible until the last reference is put.
3916 * A css which hasn't finished ->css_online() or already finished
3917 * ->css_offline() may show up during traversal. It's each subsystem's
3918 * responsibility to synchronize against on/offlining.
3920 struct cgroup_subsys_state *
3921 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3922 struct cgroup_subsys_state *root)
3924 struct cgroup_subsys_state *next;
3926 cgroup_assert_mutex_or_rcu_locked();
3928 /* if first iteration, visit @root */
3929 if (!pos)
3930 return root;
3932 /* visit the first child if exists */
3933 next = css_next_child(NULL, pos);
3934 if (next)
3935 return next;
3937 /* no child, visit my or the closest ancestor's next sibling */
3938 while (pos != root) {
3939 next = css_next_child(pos, pos->parent);
3940 if (next)
3941 return next;
3942 pos = pos->parent;
3945 return NULL;
3949 * css_rightmost_descendant - return the rightmost descendant of a css
3950 * @pos: css of interest
3952 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3953 * is returned. This can be used during pre-order traversal to skip
3954 * subtree of @pos.
3956 * While this function requires cgroup_mutex or RCU read locking, it
3957 * doesn't require the whole traversal to be contained in a single critical
3958 * section. This function will return the correct rightmost descendant as
3959 * long as @pos is accessible.
3961 struct cgroup_subsys_state *
3962 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3964 struct cgroup_subsys_state *last, *tmp;
3966 cgroup_assert_mutex_or_rcu_locked();
3968 do {
3969 last = pos;
3970 /* ->prev isn't RCU safe, walk ->next till the end */
3971 pos = NULL;
3972 css_for_each_child(tmp, last)
3973 pos = tmp;
3974 } while (pos);
3976 return last;
3979 static struct cgroup_subsys_state *
3980 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3982 struct cgroup_subsys_state *last;
3984 do {
3985 last = pos;
3986 pos = css_next_child(NULL, pos);
3987 } while (pos);
3989 return last;
3993 * css_next_descendant_post - find the next descendant for post-order walk
3994 * @pos: the current position (%NULL to initiate traversal)
3995 * @root: css whose descendants to walk
3997 * To be used by css_for_each_descendant_post(). Find the next descendant
3998 * to visit for post-order traversal of @root's descendants. @root is
3999 * included in the iteration and the last node to be visited.
4001 * While this function requires cgroup_mutex or RCU read locking, it
4002 * doesn't require the whole traversal to be contained in a single critical
4003 * section. This function will return the correct next descendant as long
4004 * as both @pos and @cgroup are accessible and @pos is a descendant of
4005 * @cgroup.
4007 * If a subsystem synchronizes ->css_online() and the start of iteration, a
4008 * css which finished ->css_online() is guaranteed to be visible in the
4009 * future iterations and will stay visible until the last reference is put.
4010 * A css which hasn't finished ->css_online() or already finished
4011 * ->css_offline() may show up during traversal. It's each subsystem's
4012 * responsibility to synchronize against on/offlining.
4014 struct cgroup_subsys_state *
4015 css_next_descendant_post(struct cgroup_subsys_state *pos,
4016 struct cgroup_subsys_state *root)
4018 struct cgroup_subsys_state *next;
4020 cgroup_assert_mutex_or_rcu_locked();
4022 /* if first iteration, visit leftmost descendant which may be @root */
4023 if (!pos)
4024 return css_leftmost_descendant(root);
4026 /* if we visited @root, we're done */
4027 if (pos == root)
4028 return NULL;
4030 /* if there's an unvisited sibling, visit its leftmost descendant */
4031 next = css_next_child(pos, pos->parent);
4032 if (next)
4033 return css_leftmost_descendant(next);
4035 /* no sibling left, visit parent */
4036 return pos->parent;
4040 * css_has_online_children - does a css have online children
4041 * @css: the target css
4043 * Returns %true if @css has any online children; otherwise, %false. This
4044 * function can be called from any context but the caller is responsible
4045 * for synchronizing against on/offlining as necessary.
4047 bool css_has_online_children(struct cgroup_subsys_state *css)
4049 struct cgroup_subsys_state *child;
4050 bool ret = false;
4052 rcu_read_lock();
4053 css_for_each_child(child, css) {
4054 if (child->flags & CSS_ONLINE) {
4055 ret = true;
4056 break;
4059 rcu_read_unlock();
4060 return ret;
4063 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4065 struct list_head *l;
4066 struct cgrp_cset_link *link;
4067 struct css_set *cset;
4069 lockdep_assert_held(&css_set_lock);
4071 /* find the next threaded cset */
4072 if (it->tcset_pos) {
4073 l = it->tcset_pos->next;
4075 if (l != it->tcset_head) {
4076 it->tcset_pos = l;
4077 return container_of(l, struct css_set,
4078 threaded_csets_node);
4081 it->tcset_pos = NULL;
4084 /* find the next cset */
4085 l = it->cset_pos;
4086 l = l->next;
4087 if (l == it->cset_head) {
4088 it->cset_pos = NULL;
4089 return NULL;
4092 if (it->ss) {
4093 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4094 } else {
4095 link = list_entry(l, struct cgrp_cset_link, cset_link);
4096 cset = link->cset;
4099 it->cset_pos = l;
4101 /* initialize threaded css_set walking */
4102 if (it->flags & CSS_TASK_ITER_THREADED) {
4103 if (it->cur_dcset)
4104 put_css_set_locked(it->cur_dcset);
4105 it->cur_dcset = cset;
4106 get_css_set(cset);
4108 it->tcset_head = &cset->threaded_csets;
4109 it->tcset_pos = &cset->threaded_csets;
4112 return cset;
4116 * css_task_iter_advance_css_set - advance a task itererator to the next css_set
4117 * @it: the iterator to advance
4119 * Advance @it to the next css_set to walk.
4121 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4123 struct css_set *cset;
4125 lockdep_assert_held(&css_set_lock);
4127 /* Advance to the next non-empty css_set */
4128 do {
4129 cset = css_task_iter_next_css_set(it);
4130 if (!cset) {
4131 it->task_pos = NULL;
4132 return;
4134 } while (!css_set_populated(cset));
4136 if (!list_empty(&cset->tasks))
4137 it->task_pos = cset->tasks.next;
4138 else
4139 it->task_pos = cset->mg_tasks.next;
4141 it->tasks_head = &cset->tasks;
4142 it->mg_tasks_head = &cset->mg_tasks;
4145 * We don't keep css_sets locked across iteration steps and thus
4146 * need to take steps to ensure that iteration can be resumed after
4147 * the lock is re-acquired. Iteration is performed at two levels -
4148 * css_sets and tasks in them.
4150 * Once created, a css_set never leaves its cgroup lists, so a
4151 * pinned css_set is guaranteed to stay put and we can resume
4152 * iteration afterwards.
4154 * Tasks may leave @cset across iteration steps. This is resolved
4155 * by registering each iterator with the css_set currently being
4156 * walked and making css_set_move_task() advance iterators whose
4157 * next task is leaving.
4159 if (it->cur_cset) {
4160 list_del(&it->iters_node);
4161 put_css_set_locked(it->cur_cset);
4163 get_css_set(cset);
4164 it->cur_cset = cset;
4165 list_add(&it->iters_node, &cset->task_iters);
4168 static void css_task_iter_advance(struct css_task_iter *it)
4170 struct list_head *next;
4172 lockdep_assert_held(&css_set_lock);
4173 repeat:
4175 * Advance iterator to find next entry. cset->tasks is consumed
4176 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
4177 * next cset.
4179 next = it->task_pos->next;
4181 if (next == it->tasks_head)
4182 next = it->mg_tasks_head->next;
4184 if (next == it->mg_tasks_head)
4185 css_task_iter_advance_css_set(it);
4186 else
4187 it->task_pos = next;
4189 /* if PROCS, skip over tasks which aren't group leaders */
4190 if ((it->flags & CSS_TASK_ITER_PROCS) && it->task_pos &&
4191 !thread_group_leader(list_entry(it->task_pos, struct task_struct,
4192 cg_list)))
4193 goto repeat;
4197 * css_task_iter_start - initiate task iteration
4198 * @css: the css to walk tasks of
4199 * @flags: CSS_TASK_ITER_* flags
4200 * @it: the task iterator to use
4202 * Initiate iteration through the tasks of @css. The caller can call
4203 * css_task_iter_next() to walk through the tasks until the function
4204 * returns NULL. On completion of iteration, css_task_iter_end() must be
4205 * called.
4207 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4208 struct css_task_iter *it)
4210 /* no one should try to iterate before mounting cgroups */
4211 WARN_ON_ONCE(!use_task_css_set_links);
4213 memset(it, 0, sizeof(*it));
4215 spin_lock_irq(&css_set_lock);
4217 it->ss = css->ss;
4218 it->flags = flags;
4220 if (it->ss)
4221 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4222 else
4223 it->cset_pos = &css->cgroup->cset_links;
4225 it->cset_head = it->cset_pos;
4227 css_task_iter_advance_css_set(it);
4229 spin_unlock_irq(&css_set_lock);
4233 * css_task_iter_next - return the next task for the iterator
4234 * @it: the task iterator being iterated
4236 * The "next" function for task iteration. @it should have been
4237 * initialized via css_task_iter_start(). Returns NULL when the iteration
4238 * reaches the end.
4240 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4242 if (it->cur_task) {
4243 put_task_struct(it->cur_task);
4244 it->cur_task = NULL;
4247 spin_lock_irq(&css_set_lock);
4249 if (it->task_pos) {
4250 it->cur_task = list_entry(it->task_pos, struct task_struct,
4251 cg_list);
4252 get_task_struct(it->cur_task);
4253 css_task_iter_advance(it);
4256 spin_unlock_irq(&css_set_lock);
4258 return it->cur_task;
4262 * css_task_iter_end - finish task iteration
4263 * @it: the task iterator to finish
4265 * Finish task iteration started by css_task_iter_start().
4267 void css_task_iter_end(struct css_task_iter *it)
4269 if (it->cur_cset) {
4270 spin_lock_irq(&css_set_lock);
4271 list_del(&it->iters_node);
4272 put_css_set_locked(it->cur_cset);
4273 spin_unlock_irq(&css_set_lock);
4276 if (it->cur_dcset)
4277 put_css_set(it->cur_dcset);
4279 if (it->cur_task)
4280 put_task_struct(it->cur_task);
4283 static void cgroup_procs_release(struct kernfs_open_file *of)
4285 if (of->priv) {
4286 css_task_iter_end(of->priv);
4287 kfree(of->priv);
4291 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
4293 struct kernfs_open_file *of = s->private;
4294 struct css_task_iter *it = of->priv;
4296 return css_task_iter_next(it);
4299 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
4300 unsigned int iter_flags)
4302 struct kernfs_open_file *of = s->private;
4303 struct cgroup *cgrp = seq_css(s)->cgroup;
4304 struct css_task_iter *it = of->priv;
4307 * When a seq_file is seeked, it's always traversed sequentially
4308 * from position 0, so we can simply keep iterating on !0 *pos.
4310 if (!it) {
4311 if (WARN_ON_ONCE((*pos)++))
4312 return ERR_PTR(-EINVAL);
4314 it = kzalloc(sizeof(*it), GFP_KERNEL);
4315 if (!it)
4316 return ERR_PTR(-ENOMEM);
4317 of->priv = it;
4318 css_task_iter_start(&cgrp->self, iter_flags, it);
4319 } else if (!(*pos)++) {
4320 css_task_iter_end(it);
4321 css_task_iter_start(&cgrp->self, iter_flags, it);
4324 return cgroup_procs_next(s, NULL, NULL);
4327 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
4329 struct cgroup *cgrp = seq_css(s)->cgroup;
4332 * All processes of a threaded subtree belong to the domain cgroup
4333 * of the subtree. Only threads can be distributed across the
4334 * subtree. Reject reads on cgroup.procs in the subtree proper.
4335 * They're always empty anyway.
4337 if (cgroup_is_threaded(cgrp))
4338 return ERR_PTR(-EOPNOTSUPP);
4340 return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
4341 CSS_TASK_ITER_THREADED);
4344 static int cgroup_procs_show(struct seq_file *s, void *v)
4346 seq_printf(s, "%d\n", task_pid_vnr(v));
4347 return 0;
4350 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
4351 struct cgroup *dst_cgrp,
4352 struct super_block *sb)
4354 struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
4355 struct cgroup *com_cgrp = src_cgrp;
4356 struct inode *inode;
4357 int ret;
4359 lockdep_assert_held(&cgroup_mutex);
4361 /* find the common ancestor */
4362 while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
4363 com_cgrp = cgroup_parent(com_cgrp);
4365 /* %current should be authorized to migrate to the common ancestor */
4366 inode = kernfs_get_inode(sb, com_cgrp->procs_file.kn);
4367 if (!inode)
4368 return -ENOMEM;
4370 ret = inode_permission(inode, MAY_WRITE);
4371 iput(inode);
4372 if (ret)
4373 return ret;
4376 * If namespaces are delegation boundaries, %current must be able
4377 * to see both source and destination cgroups from its namespace.
4379 if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
4380 (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
4381 !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
4382 return -ENOENT;
4384 return 0;
4387 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
4388 char *buf, size_t nbytes, loff_t off)
4390 struct cgroup *src_cgrp, *dst_cgrp;
4391 struct task_struct *task;
4392 ssize_t ret;
4394 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4395 if (!dst_cgrp)
4396 return -ENODEV;
4398 task = cgroup_procs_write_start(buf, true);
4399 ret = PTR_ERR_OR_ZERO(task);
4400 if (ret)
4401 goto out_unlock;
4403 /* find the source cgroup */
4404 spin_lock_irq(&css_set_lock);
4405 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4406 spin_unlock_irq(&css_set_lock);
4408 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4409 of->file->f_path.dentry->d_sb);
4410 if (ret)
4411 goto out_finish;
4413 ret = cgroup_attach_task(dst_cgrp, task, true);
4415 out_finish:
4416 cgroup_procs_write_finish(task);
4417 out_unlock:
4418 cgroup_kn_unlock(of->kn);
4420 return ret ?: nbytes;
4423 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
4425 return __cgroup_procs_start(s, pos, 0);
4428 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
4429 char *buf, size_t nbytes, loff_t off)
4431 struct cgroup *src_cgrp, *dst_cgrp;
4432 struct task_struct *task;
4433 ssize_t ret;
4435 buf = strstrip(buf);
4437 dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4438 if (!dst_cgrp)
4439 return -ENODEV;
4441 task = cgroup_procs_write_start(buf, false);
4442 ret = PTR_ERR_OR_ZERO(task);
4443 if (ret)
4444 goto out_unlock;
4446 /* find the source cgroup */
4447 spin_lock_irq(&css_set_lock);
4448 src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4449 spin_unlock_irq(&css_set_lock);
4451 /* thread migrations follow the cgroup.procs delegation rule */
4452 ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4453 of->file->f_path.dentry->d_sb);
4454 if (ret)
4455 goto out_finish;
4457 /* and must be contained in the same domain */
4458 ret = -EOPNOTSUPP;
4459 if (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp)
4460 goto out_finish;
4462 ret = cgroup_attach_task(dst_cgrp, task, false);
4464 out_finish:
4465 cgroup_procs_write_finish(task);
4466 out_unlock:
4467 cgroup_kn_unlock(of->kn);
4469 return ret ?: nbytes;
4472 /* cgroup core interface files for the default hierarchy */
4473 static struct cftype cgroup_base_files[] = {
4475 .name = "cgroup.type",
4476 .flags = CFTYPE_NOT_ON_ROOT,
4477 .seq_show = cgroup_type_show,
4478 .write = cgroup_type_write,
4481 .name = "cgroup.procs",
4482 .flags = CFTYPE_NS_DELEGATABLE,
4483 .file_offset = offsetof(struct cgroup, procs_file),
4484 .release = cgroup_procs_release,
4485 .seq_start = cgroup_procs_start,
4486 .seq_next = cgroup_procs_next,
4487 .seq_show = cgroup_procs_show,
4488 .write = cgroup_procs_write,
4491 .name = "cgroup.threads",
4492 .flags = CFTYPE_NS_DELEGATABLE,
4493 .release = cgroup_procs_release,
4494 .seq_start = cgroup_threads_start,
4495 .seq_next = cgroup_procs_next,
4496 .seq_show = cgroup_procs_show,
4497 .write = cgroup_threads_write,
4500 .name = "cgroup.controllers",
4501 .seq_show = cgroup_controllers_show,
4504 .name = "cgroup.subtree_control",
4505 .flags = CFTYPE_NS_DELEGATABLE,
4506 .seq_show = cgroup_subtree_control_show,
4507 .write = cgroup_subtree_control_write,
4510 .name = "cgroup.events",
4511 .flags = CFTYPE_NOT_ON_ROOT,
4512 .file_offset = offsetof(struct cgroup, events_file),
4513 .seq_show = cgroup_events_show,
4516 .name = "cgroup.max.descendants",
4517 .seq_show = cgroup_max_descendants_show,
4518 .write = cgroup_max_descendants_write,
4521 .name = "cgroup.max.depth",
4522 .seq_show = cgroup_max_depth_show,
4523 .write = cgroup_max_depth_write,
4526 .name = "cgroup.stat",
4527 .seq_show = cgroup_stat_show,
4530 .name = "cpu.stat",
4531 .flags = CFTYPE_NOT_ON_ROOT,
4532 .seq_show = cpu_stat_show,
4534 { } /* terminate */
4538 * css destruction is four-stage process.
4540 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4541 * Implemented in kill_css().
4543 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4544 * and thus css_tryget_online() is guaranteed to fail, the css can be
4545 * offlined by invoking offline_css(). After offlining, the base ref is
4546 * put. Implemented in css_killed_work_fn().
4548 * 3. When the percpu_ref reaches zero, the only possible remaining
4549 * accessors are inside RCU read sections. css_release() schedules the
4550 * RCU callback.
4552 * 4. After the grace period, the css can be freed. Implemented in
4553 * css_free_work_fn().
4555 * It is actually hairier because both step 2 and 4 require process context
4556 * and thus involve punting to css->destroy_work adding two additional
4557 * steps to the already complex sequence.
4559 static void css_free_rwork_fn(struct work_struct *work)
4561 struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
4562 struct cgroup_subsys_state, destroy_rwork);
4563 struct cgroup_subsys *ss = css->ss;
4564 struct cgroup *cgrp = css->cgroup;
4566 percpu_ref_exit(&css->refcnt);
4568 if (ss) {
4569 /* css free path */
4570 struct cgroup_subsys_state *parent = css->parent;
4571 int id = css->id;
4573 ss->css_free(css);
4574 cgroup_idr_remove(&ss->css_idr, id);
4575 cgroup_put(cgrp);
4577 if (parent)
4578 css_put(parent);
4579 } else {
4580 /* cgroup free path */
4581 atomic_dec(&cgrp->root->nr_cgrps);
4582 cgroup1_pidlist_destroy_all(cgrp);
4583 cancel_work_sync(&cgrp->release_agent_work);
4585 if (cgroup_parent(cgrp)) {
4587 * We get a ref to the parent, and put the ref when
4588 * this cgroup is being freed, so it's guaranteed
4589 * that the parent won't be destroyed before its
4590 * children.
4592 cgroup_put(cgroup_parent(cgrp));
4593 kernfs_put(cgrp->kn);
4594 if (cgroup_on_dfl(cgrp))
4595 cgroup_stat_exit(cgrp);
4596 kfree(cgrp);
4597 } else {
4599 * This is root cgroup's refcnt reaching zero,
4600 * which indicates that the root should be
4601 * released.
4603 cgroup_destroy_root(cgrp->root);
4608 static void css_release_work_fn(struct work_struct *work)
4610 struct cgroup_subsys_state *css =
4611 container_of(work, struct cgroup_subsys_state, destroy_work);
4612 struct cgroup_subsys *ss = css->ss;
4613 struct cgroup *cgrp = css->cgroup;
4615 mutex_lock(&cgroup_mutex);
4617 css->flags |= CSS_RELEASED;
4618 list_del_rcu(&css->sibling);
4620 if (ss) {
4621 /* css release path */
4622 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4623 if (ss->css_released)
4624 ss->css_released(css);
4625 } else {
4626 struct cgroup *tcgrp;
4628 /* cgroup release path */
4629 trace_cgroup_release(cgrp);
4631 if (cgroup_on_dfl(cgrp))
4632 cgroup_stat_flush(cgrp);
4634 for (tcgrp = cgroup_parent(cgrp); tcgrp;
4635 tcgrp = cgroup_parent(tcgrp))
4636 tcgrp->nr_dying_descendants--;
4638 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4639 cgrp->id = -1;
4642 * There are two control paths which try to determine
4643 * cgroup from dentry without going through kernfs -
4644 * cgroupstats_build() and css_tryget_online_from_dir().
4645 * Those are supported by RCU protecting clearing of
4646 * cgrp->kn->priv backpointer.
4648 if (cgrp->kn)
4649 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
4650 NULL);
4652 cgroup_bpf_put(cgrp);
4655 mutex_unlock(&cgroup_mutex);
4657 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
4658 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
4661 static void css_release(struct percpu_ref *ref)
4663 struct cgroup_subsys_state *css =
4664 container_of(ref, struct cgroup_subsys_state, refcnt);
4666 INIT_WORK(&css->destroy_work, css_release_work_fn);
4667 queue_work(cgroup_destroy_wq, &css->destroy_work);
4670 static void init_and_link_css(struct cgroup_subsys_state *css,
4671 struct cgroup_subsys *ss, struct cgroup *cgrp)
4673 lockdep_assert_held(&cgroup_mutex);
4675 cgroup_get_live(cgrp);
4677 memset(css, 0, sizeof(*css));
4678 css->cgroup = cgrp;
4679 css->ss = ss;
4680 css->id = -1;
4681 INIT_LIST_HEAD(&css->sibling);
4682 INIT_LIST_HEAD(&css->children);
4683 css->serial_nr = css_serial_nr_next++;
4684 atomic_set(&css->online_cnt, 0);
4686 if (cgroup_parent(cgrp)) {
4687 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4688 css_get(css->parent);
4691 BUG_ON(cgroup_css(cgrp, ss));
4694 /* invoke ->css_online() on a new CSS and mark it online if successful */
4695 static int online_css(struct cgroup_subsys_state *css)
4697 struct cgroup_subsys *ss = css->ss;
4698 int ret = 0;
4700 lockdep_assert_held(&cgroup_mutex);
4702 if (ss->css_online)
4703 ret = ss->css_online(css);
4704 if (!ret) {
4705 css->flags |= CSS_ONLINE;
4706 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4708 atomic_inc(&css->online_cnt);
4709 if (css->parent)
4710 atomic_inc(&css->parent->online_cnt);
4712 return ret;
4715 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4716 static void offline_css(struct cgroup_subsys_state *css)
4718 struct cgroup_subsys *ss = css->ss;
4720 lockdep_assert_held(&cgroup_mutex);
4722 if (!(css->flags & CSS_ONLINE))
4723 return;
4725 if (ss->css_offline)
4726 ss->css_offline(css);
4728 css->flags &= ~CSS_ONLINE;
4729 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4731 wake_up_all(&css->cgroup->offline_waitq);
4735 * css_create - create a cgroup_subsys_state
4736 * @cgrp: the cgroup new css will be associated with
4737 * @ss: the subsys of new css
4739 * Create a new css associated with @cgrp - @ss pair. On success, the new
4740 * css is online and installed in @cgrp. This function doesn't create the
4741 * interface files. Returns 0 on success, -errno on failure.
4743 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
4744 struct cgroup_subsys *ss)
4746 struct cgroup *parent = cgroup_parent(cgrp);
4747 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4748 struct cgroup_subsys_state *css;
4749 int err;
4751 lockdep_assert_held(&cgroup_mutex);
4753 css = ss->css_alloc(parent_css);
4754 if (!css)
4755 css = ERR_PTR(-ENOMEM);
4756 if (IS_ERR(css))
4757 return css;
4759 init_and_link_css(css, ss, cgrp);
4761 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4762 if (err)
4763 goto err_free_css;
4765 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
4766 if (err < 0)
4767 goto err_free_css;
4768 css->id = err;
4770 /* @css is ready to be brought online now, make it visible */
4771 list_add_tail_rcu(&css->sibling, &parent_css->children);
4772 cgroup_idr_replace(&ss->css_idr, css, css->id);
4774 err = online_css(css);
4775 if (err)
4776 goto err_list_del;
4778 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4779 cgroup_parent(parent)) {
4780 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4781 current->comm, current->pid, ss->name);
4782 if (!strcmp(ss->name, "memory"))
4783 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4784 ss->warned_broken_hierarchy = true;
4787 return css;
4789 err_list_del:
4790 list_del_rcu(&css->sibling);
4791 err_free_css:
4792 INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
4793 queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
4794 return ERR_PTR(err);
4798 * The returned cgroup is fully initialized including its control mask, but
4799 * it isn't associated with its kernfs_node and doesn't have the control
4800 * mask applied.
4802 static struct cgroup *cgroup_create(struct cgroup *parent)
4804 struct cgroup_root *root = parent->root;
4805 struct cgroup *cgrp, *tcgrp;
4806 int level = parent->level + 1;
4807 int ret;
4809 /* allocate the cgroup and its ID, 0 is reserved for the root */
4810 cgrp = kzalloc(sizeof(*cgrp) +
4811 sizeof(cgrp->ancestor_ids[0]) * (level + 1), GFP_KERNEL);
4812 if (!cgrp)
4813 return ERR_PTR(-ENOMEM);
4815 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
4816 if (ret)
4817 goto out_free_cgrp;
4819 if (cgroup_on_dfl(parent)) {
4820 ret = cgroup_stat_init(cgrp);
4821 if (ret)
4822 goto out_cancel_ref;
4826 * Temporarily set the pointer to NULL, so idr_find() won't return
4827 * a half-baked cgroup.
4829 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
4830 if (cgrp->id < 0) {
4831 ret = -ENOMEM;
4832 goto out_stat_exit;
4835 init_cgroup_housekeeping(cgrp);
4837 cgrp->self.parent = &parent->self;
4838 cgrp->root = root;
4839 cgrp->level = level;
4840 ret = cgroup_bpf_inherit(cgrp);
4841 if (ret)
4842 goto out_idr_free;
4844 for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
4845 cgrp->ancestor_ids[tcgrp->level] = tcgrp->id;
4847 if (tcgrp != cgrp)
4848 tcgrp->nr_descendants++;
4851 if (notify_on_release(parent))
4852 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4854 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4855 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4857 cgrp->self.serial_nr = css_serial_nr_next++;
4859 /* allocation complete, commit to creation */
4860 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4861 atomic_inc(&root->nr_cgrps);
4862 cgroup_get_live(parent);
4865 * @cgrp is now fully operational. If something fails after this
4866 * point, it'll be released via the normal destruction path.
4868 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4871 * On the default hierarchy, a child doesn't automatically inherit
4872 * subtree_control from the parent. Each is configured manually.
4874 if (!cgroup_on_dfl(cgrp))
4875 cgrp->subtree_control = cgroup_control(cgrp);
4877 cgroup_propagate_control(cgrp);
4879 return cgrp;
4881 out_idr_free:
4882 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4883 out_stat_exit:
4884 if (cgroup_on_dfl(parent))
4885 cgroup_stat_exit(cgrp);
4886 out_cancel_ref:
4887 percpu_ref_exit(&cgrp->self.refcnt);
4888 out_free_cgrp:
4889 kfree(cgrp);
4890 return ERR_PTR(ret);
4893 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
4895 struct cgroup *cgroup;
4896 int ret = false;
4897 int level = 1;
4899 lockdep_assert_held(&cgroup_mutex);
4901 for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
4902 if (cgroup->nr_descendants >= cgroup->max_descendants)
4903 goto fail;
4905 if (level > cgroup->max_depth)
4906 goto fail;
4908 level++;
4911 ret = true;
4912 fail:
4913 return ret;
4916 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
4918 struct cgroup *parent, *cgrp;
4919 struct kernfs_node *kn;
4920 int ret;
4922 /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
4923 if (strchr(name, '\n'))
4924 return -EINVAL;
4926 parent = cgroup_kn_lock_live(parent_kn, false);
4927 if (!parent)
4928 return -ENODEV;
4930 if (!cgroup_check_hierarchy_limits(parent)) {
4931 ret = -EAGAIN;
4932 goto out_unlock;
4935 cgrp = cgroup_create(parent);
4936 if (IS_ERR(cgrp)) {
4937 ret = PTR_ERR(cgrp);
4938 goto out_unlock;
4941 /* create the directory */
4942 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4943 if (IS_ERR(kn)) {
4944 ret = PTR_ERR(kn);
4945 goto out_destroy;
4947 cgrp->kn = kn;
4950 * This extra ref will be put in cgroup_free_fn() and guarantees
4951 * that @cgrp->kn is always accessible.
4953 kernfs_get(kn);
4955 ret = cgroup_kn_set_ugid(kn);
4956 if (ret)
4957 goto out_destroy;
4959 ret = css_populate_dir(&cgrp->self);
4960 if (ret)
4961 goto out_destroy;
4963 ret = cgroup_apply_control_enable(cgrp);
4964 if (ret)
4965 goto out_destroy;
4967 trace_cgroup_mkdir(cgrp);
4969 /* let's create and online css's */
4970 kernfs_activate(kn);
4972 ret = 0;
4973 goto out_unlock;
4975 out_destroy:
4976 cgroup_destroy_locked(cgrp);
4977 out_unlock:
4978 cgroup_kn_unlock(parent_kn);
4979 return ret;
4983 * This is called when the refcnt of a css is confirmed to be killed.
4984 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
4985 * initate destruction and put the css ref from kill_css().
4987 static void css_killed_work_fn(struct work_struct *work)
4989 struct cgroup_subsys_state *css =
4990 container_of(work, struct cgroup_subsys_state, destroy_work);
4992 mutex_lock(&cgroup_mutex);
4994 do {
4995 offline_css(css);
4996 css_put(css);
4997 /* @css can't go away while we're holding cgroup_mutex */
4998 css = css->parent;
4999 } while (css && atomic_dec_and_test(&css->online_cnt));
5001 mutex_unlock(&cgroup_mutex);
5004 /* css kill confirmation processing requires process context, bounce */
5005 static void css_killed_ref_fn(struct percpu_ref *ref)
5007 struct cgroup_subsys_state *css =
5008 container_of(ref, struct cgroup_subsys_state, refcnt);
5010 if (atomic_dec_and_test(&css->online_cnt)) {
5011 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5012 queue_work(cgroup_destroy_wq, &css->destroy_work);
5017 * kill_css - destroy a css
5018 * @css: css to destroy
5020 * This function initiates destruction of @css by removing cgroup interface
5021 * files and putting its base reference. ->css_offline() will be invoked
5022 * asynchronously once css_tryget_online() is guaranteed to fail and when
5023 * the reference count reaches zero, @css will be released.
5025 static void kill_css(struct cgroup_subsys_state *css)
5027 lockdep_assert_held(&cgroup_mutex);
5029 if (css->flags & CSS_DYING)
5030 return;
5032 css->flags |= CSS_DYING;
5035 * This must happen before css is disassociated with its cgroup.
5036 * See seq_css() for details.
5038 css_clear_dir(css);
5041 * Killing would put the base ref, but we need to keep it alive
5042 * until after ->css_offline().
5044 css_get(css);
5047 * cgroup core guarantees that, by the time ->css_offline() is
5048 * invoked, no new css reference will be given out via
5049 * css_tryget_online(). We can't simply call percpu_ref_kill() and
5050 * proceed to offlining css's because percpu_ref_kill() doesn't
5051 * guarantee that the ref is seen as killed on all CPUs on return.
5053 * Use percpu_ref_kill_and_confirm() to get notifications as each
5054 * css is confirmed to be seen as killed on all CPUs.
5056 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5060 * cgroup_destroy_locked - the first stage of cgroup destruction
5061 * @cgrp: cgroup to be destroyed
5063 * css's make use of percpu refcnts whose killing latency shouldn't be
5064 * exposed to userland and are RCU protected. Also, cgroup core needs to
5065 * guarantee that css_tryget_online() won't succeed by the time
5066 * ->css_offline() is invoked. To satisfy all the requirements,
5067 * destruction is implemented in the following two steps.
5069 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
5070 * userland visible parts and start killing the percpu refcnts of
5071 * css's. Set up so that the next stage will be kicked off once all
5072 * the percpu refcnts are confirmed to be killed.
5074 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5075 * rest of destruction. Once all cgroup references are gone, the
5076 * cgroup is RCU-freed.
5078 * This function implements s1. After this step, @cgrp is gone as far as
5079 * the userland is concerned and a new cgroup with the same name may be
5080 * created. As cgroup doesn't care about the names internally, this
5081 * doesn't cause any problem.
5083 static int cgroup_destroy_locked(struct cgroup *cgrp)
5084 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5086 struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5087 struct cgroup_subsys_state *css;
5088 struct cgrp_cset_link *link;
5089 int ssid;
5091 lockdep_assert_held(&cgroup_mutex);
5094 * Only migration can raise populated from zero and we're already
5095 * holding cgroup_mutex.
5097 if (cgroup_is_populated(cgrp))
5098 return -EBUSY;
5101 * Make sure there's no live children. We can't test emptiness of
5102 * ->self.children as dead children linger on it while being
5103 * drained; otherwise, "rmdir parent/child parent" may fail.
5105 if (css_has_online_children(&cgrp->self))
5106 return -EBUSY;
5109 * Mark @cgrp and the associated csets dead. The former prevents
5110 * further task migration and child creation by disabling
5111 * cgroup_lock_live_group(). The latter makes the csets ignored by
5112 * the migration path.
5114 cgrp->self.flags &= ~CSS_ONLINE;
5116 spin_lock_irq(&css_set_lock);
5117 list_for_each_entry(link, &cgrp->cset_links, cset_link)
5118 link->cset->dead = true;
5119 spin_unlock_irq(&css_set_lock);
5121 /* initiate massacre of all css's */
5122 for_each_css(css, ssid, cgrp)
5123 kill_css(css);
5125 /* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
5126 css_clear_dir(&cgrp->self);
5127 kernfs_remove(cgrp->kn);
5129 if (parent && cgroup_is_threaded(cgrp))
5130 parent->nr_threaded_children--;
5132 for (tcgrp = cgroup_parent(cgrp); tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5133 tcgrp->nr_descendants--;
5134 tcgrp->nr_dying_descendants++;
5137 cgroup1_check_for_release(parent);
5139 /* put the base reference */
5140 percpu_ref_kill(&cgrp->self.refcnt);
5142 return 0;
5145 int cgroup_rmdir(struct kernfs_node *kn)
5147 struct cgroup *cgrp;
5148 int ret = 0;
5150 cgrp = cgroup_kn_lock_live(kn, false);
5151 if (!cgrp)
5152 return 0;
5154 ret = cgroup_destroy_locked(cgrp);
5156 if (!ret)
5157 trace_cgroup_rmdir(cgrp);
5159 cgroup_kn_unlock(kn);
5160 return ret;
5163 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5164 .show_options = cgroup_show_options,
5165 .remount_fs = cgroup_remount,
5166 .mkdir = cgroup_mkdir,
5167 .rmdir = cgroup_rmdir,
5168 .show_path = cgroup_show_path,
5171 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5173 struct cgroup_subsys_state *css;
5175 pr_debug("Initializing cgroup subsys %s\n", ss->name);
5177 mutex_lock(&cgroup_mutex);
5179 idr_init(&ss->css_idr);
5180 INIT_LIST_HEAD(&ss->cfts);
5182 /* Create the root cgroup state for this subsystem */
5183 ss->root = &cgrp_dfl_root;
5184 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5185 /* We don't handle early failures gracefully */
5186 BUG_ON(IS_ERR(css));
5187 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5190 * Root csses are never destroyed and we can't initialize
5191 * percpu_ref during early init. Disable refcnting.
5193 css->flags |= CSS_NO_REF;
5195 if (early) {
5196 /* allocation can't be done safely during early init */
5197 css->id = 1;
5198 } else {
5199 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5200 BUG_ON(css->id < 0);
5203 /* Update the init_css_set to contain a subsys
5204 * pointer to this state - since the subsystem is
5205 * newly registered, all tasks and hence the
5206 * init_css_set is in the subsystem's root cgroup. */
5207 init_css_set.subsys[ss->id] = css;
5209 have_fork_callback |= (bool)ss->fork << ss->id;
5210 have_exit_callback |= (bool)ss->exit << ss->id;
5211 have_free_callback |= (bool)ss->free << ss->id;
5212 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5214 /* At system boot, before all subsystems have been
5215 * registered, no tasks have been forked, so we don't
5216 * need to invoke fork callbacks here. */
5217 BUG_ON(!list_empty(&init_task.tasks));
5219 BUG_ON(online_css(css));
5221 mutex_unlock(&cgroup_mutex);
5225 * cgroup_init_early - cgroup initialization at system boot
5227 * Initialize cgroups at system boot, and initialize any
5228 * subsystems that request early init.
5230 int __init cgroup_init_early(void)
5232 static struct cgroup_sb_opts __initdata opts;
5233 struct cgroup_subsys *ss;
5234 int i;
5236 init_cgroup_root(&cgrp_dfl_root, &opts);
5237 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5239 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5241 for_each_subsys(ss, i) {
5242 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5243 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
5244 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5245 ss->id, ss->name);
5246 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5247 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5249 ss->id = i;
5250 ss->name = cgroup_subsys_name[i];
5251 if (!ss->legacy_name)
5252 ss->legacy_name = cgroup_subsys_name[i];
5254 if (ss->early_init)
5255 cgroup_init_subsys(ss, true);
5257 return 0;
5260 static u16 cgroup_disable_mask __initdata;
5263 * cgroup_init - cgroup initialization
5265 * Register cgroup filesystem and /proc file, and initialize
5266 * any subsystems that didn't request early init.
5268 int __init cgroup_init(void)
5270 struct cgroup_subsys *ss;
5271 int ssid;
5273 BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
5274 BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
5275 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
5276 BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
5278 cgroup_stat_boot();
5281 * The latency of the synchronize_sched() is too high for cgroups,
5282 * avoid it at the cost of forcing all readers into the slow path.
5284 rcu_sync_enter_start(&cgroup_threadgroup_rwsem.rss);
5286 get_user_ns(init_cgroup_ns.user_ns);
5288 mutex_lock(&cgroup_mutex);
5291 * Add init_css_set to the hash table so that dfl_root can link to
5292 * it during init.
5294 hash_add(css_set_table, &init_css_set.hlist,
5295 css_set_hash(init_css_set.subsys));
5297 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0, 0));
5299 mutex_unlock(&cgroup_mutex);
5301 for_each_subsys(ss, ssid) {
5302 if (ss->early_init) {
5303 struct cgroup_subsys_state *css =
5304 init_css_set.subsys[ss->id];
5306 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5307 GFP_KERNEL);
5308 BUG_ON(css->id < 0);
5309 } else {
5310 cgroup_init_subsys(ss, false);
5313 list_add_tail(&init_css_set.e_cset_node[ssid],
5314 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5317 * Setting dfl_root subsys_mask needs to consider the
5318 * disabled flag and cftype registration needs kmalloc,
5319 * both of which aren't available during early_init.
5321 if (cgroup_disable_mask & (1 << ssid)) {
5322 static_branch_disable(cgroup_subsys_enabled_key[ssid]);
5323 printk(KERN_INFO "Disabling %s control group subsystem\n",
5324 ss->name);
5325 continue;
5328 if (cgroup1_ssid_disabled(ssid))
5329 printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
5330 ss->name);
5332 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5334 /* implicit controllers must be threaded too */
5335 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
5337 if (ss->implicit_on_dfl)
5338 cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
5339 else if (!ss->dfl_cftypes)
5340 cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
5342 if (ss->threaded)
5343 cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
5345 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5346 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5347 } else {
5348 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5349 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5352 if (ss->bind)
5353 ss->bind(init_css_set.subsys[ssid]);
5355 mutex_lock(&cgroup_mutex);
5356 css_populate_dir(init_css_set.subsys[ssid]);
5357 mutex_unlock(&cgroup_mutex);
5360 /* init_css_set.subsys[] has been updated, re-hash */
5361 hash_del(&init_css_set.hlist);
5362 hash_add(css_set_table, &init_css_set.hlist,
5363 css_set_hash(init_css_set.subsys));
5365 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
5366 WARN_ON(register_filesystem(&cgroup_fs_type));
5367 WARN_ON(register_filesystem(&cgroup2_fs_type));
5368 WARN_ON(!proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations));
5370 return 0;
5373 static int __init cgroup_wq_init(void)
5376 * There isn't much point in executing destruction path in
5377 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5378 * Use 1 for @max_active.
5380 * We would prefer to do this in cgroup_init() above, but that
5381 * is called before init_workqueues(): so leave this until after.
5383 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5384 BUG_ON(!cgroup_destroy_wq);
5385 return 0;
5387 core_initcall(cgroup_wq_init);
5389 void cgroup_path_from_kernfs_id(const union kernfs_node_id *id,
5390 char *buf, size_t buflen)
5392 struct kernfs_node *kn;
5394 kn = kernfs_get_node_by_id(cgrp_dfl_root.kf_root, id);
5395 if (!kn)
5396 return;
5397 kernfs_path(kn, buf, buflen);
5398 kernfs_put(kn);
5402 * proc_cgroup_show()
5403 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5404 * - Used for /proc/<pid>/cgroup.
5406 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5407 struct pid *pid, struct task_struct *tsk)
5409 char *buf;
5410 int retval;
5411 struct cgroup_root *root;
5413 retval = -ENOMEM;
5414 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5415 if (!buf)
5416 goto out;
5418 mutex_lock(&cgroup_mutex);
5419 spin_lock_irq(&css_set_lock);
5421 for_each_root(root) {
5422 struct cgroup_subsys *ss;
5423 struct cgroup *cgrp;
5424 int ssid, count = 0;
5426 if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
5427 continue;
5429 seq_printf(m, "%d:", root->hierarchy_id);
5430 if (root != &cgrp_dfl_root)
5431 for_each_subsys(ss, ssid)
5432 if (root->subsys_mask & (1 << ssid))
5433 seq_printf(m, "%s%s", count++ ? "," : "",
5434 ss->legacy_name);
5435 if (strlen(root->name))
5436 seq_printf(m, "%sname=%s", count ? "," : "",
5437 root->name);
5438 seq_putc(m, ':');
5440 cgrp = task_cgroup_from_root(tsk, root);
5443 * On traditional hierarchies, all zombie tasks show up as
5444 * belonging to the root cgroup. On the default hierarchy,
5445 * while a zombie doesn't show up in "cgroup.procs" and
5446 * thus can't be migrated, its /proc/PID/cgroup keeps
5447 * reporting the cgroup it belonged to before exiting. If
5448 * the cgroup is removed before the zombie is reaped,
5449 * " (deleted)" is appended to the cgroup path.
5451 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
5452 retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
5453 current->nsproxy->cgroup_ns);
5454 if (retval >= PATH_MAX)
5455 retval = -ENAMETOOLONG;
5456 if (retval < 0)
5457 goto out_unlock;
5459 seq_puts(m, buf);
5460 } else {
5461 seq_puts(m, "/");
5464 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
5465 seq_puts(m, " (deleted)\n");
5466 else
5467 seq_putc(m, '\n');
5470 retval = 0;
5471 out_unlock:
5472 spin_unlock_irq(&css_set_lock);
5473 mutex_unlock(&cgroup_mutex);
5474 kfree(buf);
5475 out:
5476 return retval;
5480 * cgroup_fork - initialize cgroup related fields during copy_process()
5481 * @child: pointer to task_struct of forking parent process.
5483 * A task is associated with the init_css_set until cgroup_post_fork()
5484 * attaches it to the parent's css_set. Empty cg_list indicates that
5485 * @child isn't holding reference to its css_set.
5487 void cgroup_fork(struct task_struct *child)
5489 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5490 INIT_LIST_HEAD(&child->cg_list);
5494 * cgroup_can_fork - called on a new task before the process is exposed
5495 * @child: the task in question.
5497 * This calls the subsystem can_fork() callbacks. If the can_fork() callback
5498 * returns an error, the fork aborts with that error code. This allows for
5499 * a cgroup subsystem to conditionally allow or deny new forks.
5501 int cgroup_can_fork(struct task_struct *child)
5503 struct cgroup_subsys *ss;
5504 int i, j, ret;
5506 do_each_subsys_mask(ss, i, have_canfork_callback) {
5507 ret = ss->can_fork(child);
5508 if (ret)
5509 goto out_revert;
5510 } while_each_subsys_mask();
5512 return 0;
5514 out_revert:
5515 for_each_subsys(ss, j) {
5516 if (j >= i)
5517 break;
5518 if (ss->cancel_fork)
5519 ss->cancel_fork(child);
5522 return ret;
5526 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
5527 * @child: the task in question
5529 * This calls the cancel_fork() callbacks if a fork failed *after*
5530 * cgroup_can_fork() succeded.
5532 void cgroup_cancel_fork(struct task_struct *child)
5534 struct cgroup_subsys *ss;
5535 int i;
5537 for_each_subsys(ss, i)
5538 if (ss->cancel_fork)
5539 ss->cancel_fork(child);
5543 * cgroup_post_fork - called on a new task after adding it to the task list
5544 * @child: the task in question
5546 * Adds the task to the list running through its css_set if necessary and
5547 * call the subsystem fork() callbacks. Has to be after the task is
5548 * visible on the task list in case we race with the first call to
5549 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5550 * list.
5552 void cgroup_post_fork(struct task_struct *child)
5554 struct cgroup_subsys *ss;
5555 int i;
5558 * This may race against cgroup_enable_task_cg_lists(). As that
5559 * function sets use_task_css_set_links before grabbing
5560 * tasklist_lock and we just went through tasklist_lock to add
5561 * @child, it's guaranteed that either we see the set
5562 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5563 * @child during its iteration.
5565 * If we won the race, @child is associated with %current's
5566 * css_set. Grabbing css_set_lock guarantees both that the
5567 * association is stable, and, on completion of the parent's
5568 * migration, @child is visible in the source of migration or
5569 * already in the destination cgroup. This guarantee is necessary
5570 * when implementing operations which need to migrate all tasks of
5571 * a cgroup to another.
5573 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5574 * will remain in init_css_set. This is safe because all tasks are
5575 * in the init_css_set before cg_links is enabled and there's no
5576 * operation which transfers all tasks out of init_css_set.
5578 if (use_task_css_set_links) {
5579 struct css_set *cset;
5581 spin_lock_irq(&css_set_lock);
5582 cset = task_css_set(current);
5583 if (list_empty(&child->cg_list)) {
5584 get_css_set(cset);
5585 cset->nr_tasks++;
5586 css_set_move_task(child, NULL, cset, false);
5588 spin_unlock_irq(&css_set_lock);
5592 * Call ss->fork(). This must happen after @child is linked on
5593 * css_set; otherwise, @child might change state between ->fork()
5594 * and addition to css_set.
5596 do_each_subsys_mask(ss, i, have_fork_callback) {
5597 ss->fork(child);
5598 } while_each_subsys_mask();
5602 * cgroup_exit - detach cgroup from exiting task
5603 * @tsk: pointer to task_struct of exiting process
5605 * Description: Detach cgroup from @tsk and release it.
5607 * Note that cgroups marked notify_on_release force every task in
5608 * them to take the global cgroup_mutex mutex when exiting.
5609 * This could impact scaling on very large systems. Be reluctant to
5610 * use notify_on_release cgroups where very high task exit scaling
5611 * is required on large systems.
5613 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5614 * call cgroup_exit() while the task is still competent to handle
5615 * notify_on_release(), then leave the task attached to the root cgroup in
5616 * each hierarchy for the remainder of its exit. No need to bother with
5617 * init_css_set refcnting. init_css_set never goes away and we can't race
5618 * with migration path - PF_EXITING is visible to migration path.
5620 void cgroup_exit(struct task_struct *tsk)
5622 struct cgroup_subsys *ss;
5623 struct css_set *cset;
5624 int i;
5627 * Unlink from @tsk from its css_set. As migration path can't race
5628 * with us, we can check css_set and cg_list without synchronization.
5630 cset = task_css_set(tsk);
5632 if (!list_empty(&tsk->cg_list)) {
5633 spin_lock_irq(&css_set_lock);
5634 css_set_move_task(tsk, cset, NULL, false);
5635 cset->nr_tasks--;
5636 spin_unlock_irq(&css_set_lock);
5637 } else {
5638 get_css_set(cset);
5641 /* see cgroup_post_fork() for details */
5642 do_each_subsys_mask(ss, i, have_exit_callback) {
5643 ss->exit(tsk);
5644 } while_each_subsys_mask();
5647 void cgroup_free(struct task_struct *task)
5649 struct css_set *cset = task_css_set(task);
5650 struct cgroup_subsys *ss;
5651 int ssid;
5653 do_each_subsys_mask(ss, ssid, have_free_callback) {
5654 ss->free(task);
5655 } while_each_subsys_mask();
5657 put_css_set(cset);
5660 static int __init cgroup_disable(char *str)
5662 struct cgroup_subsys *ss;
5663 char *token;
5664 int i;
5666 while ((token = strsep(&str, ",")) != NULL) {
5667 if (!*token)
5668 continue;
5670 for_each_subsys(ss, i) {
5671 if (strcmp(token, ss->name) &&
5672 strcmp(token, ss->legacy_name))
5673 continue;
5674 cgroup_disable_mask |= 1 << i;
5677 return 1;
5679 __setup("cgroup_disable=", cgroup_disable);
5682 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5683 * @dentry: directory dentry of interest
5684 * @ss: subsystem of interest
5686 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5687 * to get the corresponding css and return it. If such css doesn't exist
5688 * or can't be pinned, an ERR_PTR value is returned.
5690 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5691 struct cgroup_subsys *ss)
5693 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5694 struct file_system_type *s_type = dentry->d_sb->s_type;
5695 struct cgroup_subsys_state *css = NULL;
5696 struct cgroup *cgrp;
5698 /* is @dentry a cgroup dir? */
5699 if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
5700 !kn || kernfs_type(kn) != KERNFS_DIR)
5701 return ERR_PTR(-EBADF);
5703 rcu_read_lock();
5706 * This path doesn't originate from kernfs and @kn could already
5707 * have been or be removed at any point. @kn->priv is RCU
5708 * protected for this access. See css_release_work_fn() for details.
5710 cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
5711 if (cgrp)
5712 css = cgroup_css(cgrp, ss);
5714 if (!css || !css_tryget_online(css))
5715 css = ERR_PTR(-ENOENT);
5717 rcu_read_unlock();
5718 return css;
5722 * css_from_id - lookup css by id
5723 * @id: the cgroup id
5724 * @ss: cgroup subsys to be looked into
5726 * Returns the css if there's valid one with @id, otherwise returns NULL.
5727 * Should be called under rcu_read_lock().
5729 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5731 WARN_ON_ONCE(!rcu_read_lock_held());
5732 return idr_find(&ss->css_idr, id);
5736 * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
5737 * @path: path on the default hierarchy
5739 * Find the cgroup at @path on the default hierarchy, increment its
5740 * reference count and return it. Returns pointer to the found cgroup on
5741 * success, ERR_PTR(-ENOENT) if @path doens't exist and ERR_PTR(-ENOTDIR)
5742 * if @path points to a non-directory.
5744 struct cgroup *cgroup_get_from_path(const char *path)
5746 struct kernfs_node *kn;
5747 struct cgroup *cgrp;
5749 mutex_lock(&cgroup_mutex);
5751 kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
5752 if (kn) {
5753 if (kernfs_type(kn) == KERNFS_DIR) {
5754 cgrp = kn->priv;
5755 cgroup_get_live(cgrp);
5756 } else {
5757 cgrp = ERR_PTR(-ENOTDIR);
5759 kernfs_put(kn);
5760 } else {
5761 cgrp = ERR_PTR(-ENOENT);
5764 mutex_unlock(&cgroup_mutex);
5765 return cgrp;
5767 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
5770 * cgroup_get_from_fd - get a cgroup pointer from a fd
5771 * @fd: fd obtained by open(cgroup2_dir)
5773 * Find the cgroup from a fd which should be obtained
5774 * by opening a cgroup directory. Returns a pointer to the
5775 * cgroup on success. ERR_PTR is returned if the cgroup
5776 * cannot be found.
5778 struct cgroup *cgroup_get_from_fd(int fd)
5780 struct cgroup_subsys_state *css;
5781 struct cgroup *cgrp;
5782 struct file *f;
5784 f = fget_raw(fd);
5785 if (!f)
5786 return ERR_PTR(-EBADF);
5788 css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
5789 fput(f);
5790 if (IS_ERR(css))
5791 return ERR_CAST(css);
5793 cgrp = css->cgroup;
5794 if (!cgroup_on_dfl(cgrp)) {
5795 cgroup_put(cgrp);
5796 return ERR_PTR(-EBADF);
5799 return cgrp;
5801 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
5804 * sock->sk_cgrp_data handling. For more info, see sock_cgroup_data
5805 * definition in cgroup-defs.h.
5807 #ifdef CONFIG_SOCK_CGROUP_DATA
5809 #if defined(CONFIG_CGROUP_NET_PRIO) || defined(CONFIG_CGROUP_NET_CLASSID)
5811 DEFINE_SPINLOCK(cgroup_sk_update_lock);
5812 static bool cgroup_sk_alloc_disabled __read_mostly;
5814 void cgroup_sk_alloc_disable(void)
5816 if (cgroup_sk_alloc_disabled)
5817 return;
5818 pr_info("cgroup: disabling cgroup2 socket matching due to net_prio or net_cls activation\n");
5819 cgroup_sk_alloc_disabled = true;
5822 #else
5824 #define cgroup_sk_alloc_disabled false
5826 #endif
5828 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
5830 if (cgroup_sk_alloc_disabled)
5831 return;
5833 /* Socket clone path */
5834 if (skcd->val) {
5836 * We might be cloning a socket which is left in an empty
5837 * cgroup and the cgroup might have already been rmdir'd.
5838 * Don't use cgroup_get_live().
5840 cgroup_get(sock_cgroup_ptr(skcd));
5841 return;
5844 rcu_read_lock();
5846 while (true) {
5847 struct css_set *cset;
5849 cset = task_css_set(current);
5850 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
5851 skcd->val = (unsigned long)cset->dfl_cgrp;
5852 break;
5854 cpu_relax();
5857 rcu_read_unlock();
5860 void cgroup_sk_free(struct sock_cgroup_data *skcd)
5862 cgroup_put(sock_cgroup_ptr(skcd));
5865 #endif /* CONFIG_SOCK_CGROUP_DATA */
5867 #ifdef CONFIG_CGROUP_BPF
5868 int cgroup_bpf_attach(struct cgroup *cgrp, struct bpf_prog *prog,
5869 enum bpf_attach_type type, u32 flags)
5871 int ret;
5873 mutex_lock(&cgroup_mutex);
5874 ret = __cgroup_bpf_attach(cgrp, prog, type, flags);
5875 mutex_unlock(&cgroup_mutex);
5876 return ret;
5878 int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
5879 enum bpf_attach_type type, u32 flags)
5881 int ret;
5883 mutex_lock(&cgroup_mutex);
5884 ret = __cgroup_bpf_detach(cgrp, prog, type, flags);
5885 mutex_unlock(&cgroup_mutex);
5886 return ret;
5888 int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
5889 union bpf_attr __user *uattr)
5891 int ret;
5893 mutex_lock(&cgroup_mutex);
5894 ret = __cgroup_bpf_query(cgrp, attr, uattr);
5895 mutex_unlock(&cgroup_mutex);
5896 return ret;
5898 #endif /* CONFIG_CGROUP_BPF */
5900 #ifdef CONFIG_SYSFS
5901 static ssize_t show_delegatable_files(struct cftype *files, char *buf,
5902 ssize_t size, const char *prefix)
5904 struct cftype *cft;
5905 ssize_t ret = 0;
5907 for (cft = files; cft && cft->name[0] != '\0'; cft++) {
5908 if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
5909 continue;
5911 if (prefix)
5912 ret += snprintf(buf + ret, size - ret, "%s.", prefix);
5914 ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
5916 if (unlikely(ret >= size)) {
5917 WARN_ON(1);
5918 break;
5922 return ret;
5925 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
5926 char *buf)
5928 struct cgroup_subsys *ss;
5929 int ssid;
5930 ssize_t ret = 0;
5932 ret = show_delegatable_files(cgroup_base_files, buf, PAGE_SIZE - ret,
5933 NULL);
5935 for_each_subsys(ss, ssid)
5936 ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
5937 PAGE_SIZE - ret,
5938 cgroup_subsys_name[ssid]);
5940 return ret;
5942 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
5944 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
5945 char *buf)
5947 return snprintf(buf, PAGE_SIZE, "nsdelegate\n");
5949 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
5951 static struct attribute *cgroup_sysfs_attrs[] = {
5952 &cgroup_delegate_attr.attr,
5953 &cgroup_features_attr.attr,
5954 NULL,
5957 static const struct attribute_group cgroup_sysfs_attr_group = {
5958 .attrs = cgroup_sysfs_attrs,
5959 .name = "cgroup",
5962 static int __init cgroup_sysfs_init(void)
5964 return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
5966 subsys_initcall(cgroup_sysfs_init);
5967 #endif /* CONFIG_SYSFS */