xref: /linux/kernel/cgroup/cgroup.c (revision c2dfb2aea8b96884c7b4e1af337106e1cf5f4b5a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  Generic process-grouping system.
4  *
5  *  Based originally on the cpuset system, extracted by Paul Menage
6  *  Copyright (C) 2006 Google, Inc
7  *
8  *  Notifications support
9  *  Copyright (C) 2009 Nokia Corporation
10  *  Author: Kirill A. Shutemov
11  *
12  *  Copyright notices from the original cpuset code:
13  *  --------------------------------------------------
14  *  Copyright (C) 2003 BULL SA.
15  *  Copyright (C) 2004-2006 Silicon Graphics, Inc.
16  *
17  *  Portions derived from Patrick Mochel's sysfs code.
18  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
19  *
20  *  2003-10-10 Written by Simon Derr.
21  *  2003-10-22 Updates by Stephen Hemminger.
22  *  2004 May-July Rework by Paul Jackson.
23  *  ---------------------------------------------------
24  */
25 
26 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
27 
28 #include "cgroup-internal.h"
29 
30 #include <linux/bpf-cgroup.h>
31 #include <linux/cred.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/magic.h>
36 #include <linux/mutex.h>
37 #include <linux/mount.h>
38 #include <linux/pagemap.h>
39 #include <linux/proc_fs.h>
40 #include <linux/rcupdate.h>
41 #include <linux/sched.h>
42 #include <linux/sched/task.h>
43 #include <linux/slab.h>
44 #include <linux/spinlock.h>
45 #include <linux/percpu-rwsem.h>
46 #include <linux/string.h>
47 #include <linux/hashtable.h>
48 #include <linux/idr.h>
49 #include <linux/kthread.h>
50 #include <linux/atomic.h>
51 #include <linux/cpuset.h>
52 #include <linux/proc_ns.h>
53 #include <linux/nsproxy.h>
54 #include <linux/file.h>
55 #include <linux/fs_parser.h>
56 #include <linux/sched/cputime.h>
57 #include <linux/sched/deadline.h>
58 #include <linux/psi.h>
59 #include <linux/nstree.h>
60 #include <linux/irq_work.h>
61 #include <net/sock.h>
62 
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/cgroup.h>
65 
66 #define CGROUP_FILE_NAME_MAX		(MAX_CGROUP_TYPE_NAMELEN +	\
67 					 MAX_CFTYPE_NAME + 2)
68 /* let's not notify more than 100 times per second */
69 #define CGROUP_FILE_NOTIFY_MIN_INTV	DIV_ROUND_UP(HZ, 100)
70 
71 /*
72  * cgroup_mutex is the master lock.  Any modification to cgroup or its
73  * hierarchy must be performed while holding it.
74  *
75  * css_set_lock protects task->cgroups pointer, the list of css_set
76  * objects, and the chain of tasks off each css_set.
77  *
78  * These locks are exported if CONFIG_PROVE_RCU so that accessors in
79  * cgroup.h can use them for lockdep annotations.
80  */
81 DEFINE_MUTEX(cgroup_mutex);
82 DEFINE_SPINLOCK(css_set_lock);
83 
84 #if (defined CONFIG_PROVE_RCU || defined CONFIG_LOCKDEP)
85 EXPORT_SYMBOL_GPL(cgroup_mutex);
86 EXPORT_SYMBOL_GPL(css_set_lock);
87 #endif
88 
89 struct blocking_notifier_head cgroup_lifetime_notifier =
90 	BLOCKING_NOTIFIER_INIT(cgroup_lifetime_notifier);
91 struct blocking_notifier_head cgroup_task_notifier =
92 	BLOCKING_NOTIFIER_INIT(cgroup_task_notifier);
93 
94 DEFINE_SPINLOCK(trace_cgroup_path_lock);
95 char trace_cgroup_path[TRACE_CGROUP_PATH_LEN];
96 static bool cgroup_debug __read_mostly;
97 
98 /*
99  * Protects cgroup_idr and css_idr so that IDs can be released without
100  * grabbing cgroup_mutex.
101  */
102 static DEFINE_SPINLOCK(cgroup_idr_lock);
103 
104 DEFINE_PERCPU_RWSEM(cgroup_threadgroup_rwsem);
105 
106 #define cgroup_assert_mutex_or_rcu_locked()				\
107 	RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&			\
108 			   !lockdep_is_held(&cgroup_mutex),		\
109 			   "cgroup_mutex or RCU read lock required")
110 
111 /*
112  * cgroup destruction makes heavy use of work items and there can be a lot
113  * of concurrent destructions.  Use a separate workqueue so that cgroup
114  * destruction work items don't end up filling up max_active of system_percpu_wq
115  * which may lead to deadlock.
116  *
117  * A cgroup destruction should enqueue work sequentially to:
118  * cgroup_offline_wq: use for css offline work
119  * cgroup_release_wq: use for css release work
120  * cgroup_free_wq: use for free work
121  *
122  * Rationale for using separate workqueues:
123  * The cgroup root free work may depend on completion of other css offline
124  * operations. If all tasks were enqueued to a single workqueue, this could
125  * create a deadlock scenario where:
126  * - Free work waits for other css offline work to complete.
127  * - But other css offline work is queued after free work in the same queue.
128  *
129  * Example deadlock scenario with single workqueue (cgroup_destroy_wq):
130  * 1. umount net_prio
131  * 2. net_prio root destruction enqueues work to cgroup_destroy_wq (CPUx)
132  * 3. perf_event CSS A offline enqueues work to same cgroup_destroy_wq (CPUx)
133  * 4. net_prio cgroup_destroy_root->cgroup_lock_and_drain_offline.
134  * 5. net_prio root destruction blocks waiting for perf_event CSS A offline,
135  *    which can never complete as it's behind in the same queue and
136  *    workqueue's max_active is 1.
137  */
138 static struct workqueue_struct *cgroup_offline_wq;
139 static struct workqueue_struct *cgroup_release_wq;
140 static struct workqueue_struct *cgroup_free_wq;
141 
142 /* generate an array of cgroup subsystem pointers */
143 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
144 struct cgroup_subsys *cgroup_subsys[] = {
145 #include <linux/cgroup_subsys.h>
146 };
147 #undef SUBSYS
148 
149 /* array of cgroup subsystem names */
150 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
151 static const char *cgroup_subsys_name[] = {
152 #include <linux/cgroup_subsys.h>
153 };
154 #undef SUBSYS
155 
156 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
157 #define SUBSYS(_x)								\
158 	DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key);			\
159 	DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key);			\
160 	EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key);			\
161 	EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
162 #include <linux/cgroup_subsys.h>
163 #undef SUBSYS
164 
165 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
166 static struct static_key_true *cgroup_subsys_enabled_key[] = {
167 #include <linux/cgroup_subsys.h>
168 };
169 #undef SUBSYS
170 
171 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
172 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
173 #include <linux/cgroup_subsys.h>
174 };
175 #undef SUBSYS
176 
177 static DEFINE_PER_CPU(struct css_rstat_cpu, root_rstat_cpu);
178 static DEFINE_PER_CPU(struct cgroup_rstat_base_cpu, root_rstat_base_cpu);
179 
180 /* the default hierarchy */
181 struct cgroup_root cgrp_dfl_root = {
182 	.cgrp.self.rstat_cpu = &root_rstat_cpu,
183 	.cgrp.rstat_base_cpu = &root_rstat_base_cpu,
184 };
185 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
186 
187 /*
188  * The default hierarchy always exists but is hidden until mounted for the
189  * first time.  This is for backward compatibility.
190  */
191 bool cgrp_dfl_visible;
192 
193 /* some controllers are not supported in the default hierarchy */
194 static u32 cgrp_dfl_inhibit_ss_mask;
195 
196 /* some controllers are implicitly enabled on the default hierarchy */
197 static u32 cgrp_dfl_implicit_ss_mask;
198 
199 /* some controllers can be threaded on the default hierarchy */
200 static u32 cgrp_dfl_threaded_ss_mask;
201 
202 /*
203  * Set across rebind_subsystems() to the controllers leaving a hierarchy.
204  * Guarded by cgroup_mutex. Makes find_existing_css_set() resolve them to the
205  * root css so the affected tasks are migrated there before
206  * cgroup_apply_control_disable() kills the per-cgroup csses.
207  */
208 static u32 cgroup_rebind_ss_mask;
209 
210 /* The list of hierarchy roots */
211 LIST_HEAD(cgroup_roots);
212 static int cgroup_root_count;
213 
214 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
215 static DEFINE_IDR(cgroup_hierarchy_idr);
216 
217 /*
218  * Assign a monotonically increasing serial number to csses.  It guarantees
219  * cgroups with bigger numbers are newer than those with smaller numbers.
220  * Also, as csses are always appended to the parent's ->children list, it
221  * guarantees that sibling csses are always sorted in the ascending serial
222  * number order on the list.  Protected by cgroup_mutex.
223  */
224 static u64 css_serial_nr_next = 1;
225 
226 /*
227  * These bitmasks identify subsystems with specific features to avoid
228  * having to do iterative checks repeatedly.
229  */
230 static u32 have_fork_callback __read_mostly;
231 static u32 have_exit_callback __read_mostly;
232 static u32 have_release_callback __read_mostly;
233 static u32 have_canfork_callback __read_mostly;
234 
235 static bool have_favordynmods __ro_after_init = IS_ENABLED(CONFIG_CGROUP_FAVOR_DYNMODS);
236 
237 /*
238  * Write protected by cgroup_mutex and write-lock of cgroup_threadgroup_rwsem,
239  * read protected by either.
240  *
241  * Can only be turned on, but not turned off.
242  */
243 bool cgroup_enable_per_threadgroup_rwsem __read_mostly;
244 
245 /* cgroup namespace for init task */
246 struct cgroup_namespace init_cgroup_ns = {
247 	.ns		= NS_COMMON_INIT(init_cgroup_ns),
248 	.user_ns	= &init_user_ns,
249 	.root_cset	= &init_css_set,
250 };
251 
252 static struct file_system_type cgroup2_fs_type;
253 static struct cftype cgroup_base_files[];
254 static struct cftype cgroup_psi_files[];
255 
256 /* cgroup optional features */
257 enum cgroup_opt_features {
258 #ifdef CONFIG_PSI
259 	OPT_FEATURE_PRESSURE,
260 #endif
261 	OPT_FEATURE_COUNT
262 };
263 
264 static const char *cgroup_opt_feature_names[OPT_FEATURE_COUNT] = {
265 #ifdef CONFIG_PSI
266 	"pressure",
267 #endif
268 };
269 
270 static u16 cgroup_feature_disable_mask __read_mostly;
271 
272 static int cgroup_apply_control(struct cgroup *cgrp);
273 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
274 static void css_task_iter_skip(struct css_task_iter *it,
275 			       struct task_struct *task);
276 static int cgroup_destroy_locked(struct cgroup *cgrp);
277 static void kill_css_sync(struct cgroup_subsys_state *css);
278 static void kill_css_finish(struct cgroup_subsys_state *css);
279 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
280 					      struct cgroup_subsys *ss);
281 static void css_release(struct percpu_ref *ref);
282 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
283 			      struct cgroup *cgrp, struct cftype cfts[],
284 			      bool is_add);
285 static void cgroup_rt_init(void);
286 
287 #ifdef CONFIG_DEBUG_CGROUP_REF
288 #define CGROUP_REF_FN_ATTRS	noinline
289 #define CGROUP_REF_EXPORT(fn)	EXPORT_SYMBOL_GPL(fn);
290 #include <linux/cgroup_refcnt.h>
291 #endif
292 
293 /**
294  * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
295  * @ssid: subsys ID of interest
296  *
297  * cgroup_subsys_enabled() can only be used with literal subsys names which
298  * is fine for individual subsystems but unsuitable for cgroup core.  This
299  * is slower static_key_enabled() based test indexed by @ssid.
300  */
301 bool cgroup_ssid_enabled(int ssid)
302 {
303 	if (!CGROUP_HAS_SUBSYS_CONFIG)
304 		return false;
305 
306 	return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
307 }
308 
309 /**
310  * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
311  * @cgrp: the cgroup of interest
312  *
313  * The default hierarchy is the v2 interface of cgroup and this function
314  * can be used to test whether a cgroup is on the default hierarchy for
315  * cases where a subsystem should behave differently depending on the
316  * interface version.
317  *
318  * List of changed behaviors:
319  *
320  * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
321  *   and "name" are disallowed.
322  *
323  * - When mounting an existing superblock, mount options should match.
324  *
325  * - rename(2) is disallowed.
326  *
327  * - "tasks" is removed.  Everything should be at process granularity.  Use
328  *   "cgroup.procs" instead.
329  *
330  * - "cgroup.procs" is not sorted.  pids will be unique unless they got
331  *   recycled in-between reads.
332  *
333  * - "release_agent" and "notify_on_release" are removed.  Replacement
334  *   notification mechanism will be implemented.
335  *
336  * - "cgroup.clone_children" is removed.
337  *
338  * - "cgroup.subtree_populated" is available.  Its value is 0 if the cgroup
339  *   and its descendants contain no task; otherwise, 1.  The file also
340  *   generates kernfs notification which can be monitored through poll and
341  *   [di]notify when the value of the file changes.
342  *
343  * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
344  *   take masks of ancestors with non-empty cpus/mems, instead of being
345  *   moved to an ancestor.
346  *
347  * - cpuset: a task can be moved into an empty cpuset, and again it takes
348  *   masks of ancestors.
349  *
350  * - blkcg: blk-throttle becomes properly hierarchical.
351  */
352 bool cgroup_on_dfl(const struct cgroup *cgrp)
353 {
354 	return cgrp->root == &cgrp_dfl_root;
355 }
356 
357 /* IDR wrappers which synchronize using cgroup_idr_lock */
358 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
359 			    gfp_t gfp_mask)
360 {
361 	int ret;
362 
363 	idr_preload(gfp_mask);
364 	spin_lock_bh(&cgroup_idr_lock);
365 	ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
366 	spin_unlock_bh(&cgroup_idr_lock);
367 	idr_preload_end();
368 	return ret;
369 }
370 
371 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
372 {
373 	void *ret;
374 
375 	spin_lock_bh(&cgroup_idr_lock);
376 	ret = idr_replace(idr, ptr, id);
377 	spin_unlock_bh(&cgroup_idr_lock);
378 	return ret;
379 }
380 
381 static void cgroup_idr_remove(struct idr *idr, int id)
382 {
383 	spin_lock_bh(&cgroup_idr_lock);
384 	idr_remove(idr, id);
385 	spin_unlock_bh(&cgroup_idr_lock);
386 }
387 
388 static bool cgroup_is_threaded(struct cgroup *cgrp)
389 {
390 	return cgrp->dom_cgrp != cgrp;
391 }
392 
393 /* can @cgrp host both domain and threaded children? */
394 static bool cgroup_is_mixable(struct cgroup *cgrp)
395 {
396 	/*
397 	 * Root isn't under domain level resource control exempting it from
398 	 * the no-internal-process constraint, so it can serve as a thread
399 	 * root and a parent of resource domains at the same time.
400 	 */
401 	return !cgroup_parent(cgrp);
402 }
403 
404 /* can @cgrp become a thread root? Should always be true for a thread root */
405 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
406 {
407 	/* mixables don't care */
408 	if (cgroup_is_mixable(cgrp))
409 		return true;
410 
411 	/* domain roots can't be nested under threaded */
412 	if (cgroup_is_threaded(cgrp))
413 		return false;
414 
415 	/* can only have either domain or threaded children */
416 	if (READ_ONCE(cgrp->nr_populated_domain_children))
417 		return false;
418 
419 	/* and no domain controllers can be enabled */
420 	if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
421 		return false;
422 
423 	return true;
424 }
425 
426 /* is @cgrp root of a threaded subtree? */
427 static bool cgroup_is_thread_root(struct cgroup *cgrp)
428 {
429 	/* thread root should be a domain */
430 	if (cgroup_is_threaded(cgrp))
431 		return false;
432 
433 	/* a domain w/ threaded children is a thread root */
434 	if (cgrp->nr_threaded_children)
435 		return true;
436 
437 	/*
438 	 * A domain which has tasks and explicit threaded controllers
439 	 * enabled is a thread root.
440 	 */
441 	if (cgroup_has_tasks(cgrp) &&
442 	    (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
443 		return true;
444 
445 	return false;
446 }
447 
448 /* a domain which isn't connected to the root w/o brekage can't be used */
449 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
450 {
451 	/* the cgroup itself can be a thread root */
452 	if (cgroup_is_threaded(cgrp))
453 		return false;
454 
455 	/* but the ancestors can't be unless mixable */
456 	while ((cgrp = cgroup_parent(cgrp))) {
457 		if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
458 			return false;
459 		if (cgroup_is_threaded(cgrp))
460 			return false;
461 	}
462 
463 	return true;
464 }
465 
466 /* subsystems visibly enabled on a cgroup */
467 static u32 cgroup_control(struct cgroup *cgrp)
468 {
469 	struct cgroup *parent = cgroup_parent(cgrp);
470 	u32 root_ss_mask = cgrp->root->subsys_mask;
471 
472 	if (parent) {
473 		u32 ss_mask = parent->subtree_control;
474 
475 		/* threaded cgroups can only have threaded controllers */
476 		if (cgroup_is_threaded(cgrp))
477 			ss_mask &= cgrp_dfl_threaded_ss_mask;
478 		return ss_mask;
479 	}
480 
481 	if (cgroup_on_dfl(cgrp))
482 		root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
483 				  cgrp_dfl_implicit_ss_mask);
484 	return root_ss_mask;
485 }
486 
487 /* subsystems enabled on a cgroup */
488 static u32 cgroup_ss_mask(struct cgroup *cgrp)
489 {
490 	struct cgroup *parent = cgroup_parent(cgrp);
491 
492 	if (parent) {
493 		u32 ss_mask = parent->subtree_ss_mask;
494 
495 		/* threaded cgroups can only have threaded controllers */
496 		if (cgroup_is_threaded(cgrp))
497 			ss_mask &= cgrp_dfl_threaded_ss_mask;
498 		return ss_mask;
499 	}
500 
501 	return cgrp->root->subsys_mask;
502 }
503 
504 /**
505  * cgroup_e_css_by_mask - obtain a cgroup's effective css for the specified ss
506  * @cgrp: the cgroup of interest
507  * @ss: the subsystem of interest (%NULL returns @cgrp->self)
508  *
509  * Similar to cgroup_css() but returns the effective css, which is defined
510  * as the matching css of the nearest ancestor including self which has @ss
511  * enabled.  If @ss is associated with the hierarchy @cgrp is on, this
512  * function is guaranteed to return non-NULL css.
513  */
514 static struct cgroup_subsys_state *cgroup_e_css_by_mask(struct cgroup *cgrp,
515 							struct cgroup_subsys *ss)
516 {
517 	lockdep_assert_held(&cgroup_mutex);
518 
519 	if (!ss)
520 		return &cgrp->self;
521 
522 	/*
523 	 * This function is used while updating css associations and thus
524 	 * can't test the csses directly.  Test ss_mask.
525 	 */
526 	while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
527 		cgrp = cgroup_parent(cgrp);
528 		if (!cgrp)
529 			return NULL;
530 	}
531 
532 	return cgroup_css(cgrp, ss);
533 }
534 
535 /**
536  * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
537  * @cgrp: the cgroup of interest
538  * @ss: the subsystem of interest
539  *
540  * Find and get the effective css of @cgrp for @ss.  The effective css is
541  * defined as the matching css of the nearest ancestor including self which
542  * has @ss enabled.  If @ss is not mounted on the hierarchy @cgrp is on,
543  * the root css is returned, so this function always returns a valid css.
544  *
545  * The returned css is not guaranteed to be online, and therefore it is the
546  * callers responsibility to try get a reference for it.
547  */
548 struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
549 					 struct cgroup_subsys *ss)
550 {
551 	if (!CGROUP_HAS_SUBSYS_CONFIG)
552 		return NULL;
553 
554 	return rcu_dereference_check(cgrp->e_css[ss->id],
555 				     lockdep_is_held(&cgroup_mutex));
556 }
557 
558 /**
559  * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
560  * @cgrp: the cgroup of interest
561  * @ss: the subsystem of interest
562  *
563  * Find and get the effective css of @cgrp for @ss.  The effective css is
564  * defined as the matching css of the nearest ancestor including self which
565  * has @ss enabled.  If @ss is not mounted on the hierarchy @cgrp is on,
566  * the root css is returned, so this function always returns a valid css.
567  * The returned css must be put using css_put().
568  */
569 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
570 					     struct cgroup_subsys *ss)
571 {
572 	struct cgroup_subsys_state *css;
573 
574 	if (!CGROUP_HAS_SUBSYS_CONFIG)
575 		return NULL;
576 
577 	rcu_read_lock();
578 
579 	css = cgroup_e_css(cgrp, ss);
580 	while (!css_tryget_online(css))
581 		css = cgroup_e_css(cgroup_parent(css->cgroup), ss);
582 
583 	rcu_read_unlock();
584 	return css;
585 }
586 EXPORT_SYMBOL_GPL(cgroup_get_e_css);
587 
588 static void cgroup_get_live(struct cgroup *cgrp)
589 {
590 	WARN_ON_ONCE(cgroup_is_dead(cgrp));
591 	cgroup_get(cgrp);
592 }
593 
594 /**
595  * __cgroup_task_count - count the number of tasks in a cgroup. The caller
596  * is responsible for taking the css_set_lock.
597  * @cgrp: the cgroup in question
598  */
599 int __cgroup_task_count(const struct cgroup *cgrp)
600 {
601 	int count = 0;
602 	struct cgrp_cset_link *link;
603 
604 	lockdep_assert_held(&css_set_lock);
605 
606 	list_for_each_entry(link, &cgrp->cset_links, cset_link)
607 		count += link->cset->nr_tasks;
608 
609 	return count;
610 }
611 
612 /**
613  * cgroup_task_count - count the number of tasks in a cgroup.
614  * @cgrp: the cgroup in question
615  */
616 int cgroup_task_count(const struct cgroup *cgrp)
617 {
618 	int count;
619 
620 	spin_lock_irq(&css_set_lock);
621 	count = __cgroup_task_count(cgrp);
622 	spin_unlock_irq(&css_set_lock);
623 
624 	return count;
625 }
626 
627 static struct cgroup *kn_priv(struct kernfs_node *kn)
628 {
629 	struct kernfs_node *parent;
630 	/*
631 	 * The parent can not be replaced due to KERNFS_ROOT_INVARIANT_PARENT.
632 	 * Therefore it is always safe to dereference this pointer outside of a
633 	 * RCU section.
634 	 */
635 	parent = rcu_dereference_check(kn->__parent,
636 				       kernfs_root_flags(kn) & KERNFS_ROOT_INVARIANT_PARENT);
637 	return parent->priv;
638 }
639 
640 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
641 {
642 	struct cgroup *cgrp = kn_priv(of->kn);
643 	struct cftype *cft = of_cft(of);
644 
645 	/*
646 	 * This is open and unprotected implementation of cgroup_css().
647 	 * seq_css() is only called from a kernfs file operation which has
648 	 * an active reference on the file.  Because all the subsystem
649 	 * files are drained before a css is disassociated with a cgroup,
650 	 * the matching css from the cgroup's subsys table is guaranteed to
651 	 * be and stay valid until the enclosing operation is complete.
652 	 */
653 	if (CGROUP_HAS_SUBSYS_CONFIG && cft->ss)
654 		return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
655 	else
656 		return &cgrp->self;
657 }
658 EXPORT_SYMBOL_GPL(of_css);
659 
660 /**
661  * for_each_css - iterate all css's of a cgroup
662  * @css: the iteration cursor
663  * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
664  * @cgrp: the target cgroup to iterate css's of
665  *
666  * Should be called under cgroup_mutex.
667  */
668 #define for_each_css(css, ssid, cgrp)					\
669 	for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++)	\
670 		if (!((css) = rcu_dereference_check(			\
671 				(cgrp)->subsys[(ssid)],			\
672 				lockdep_is_held(&cgroup_mutex)))) { }	\
673 		else
674 
675 /**
676  * do_each_subsys_mask - filter for_each_subsys with a bitmask
677  * @ss: the iteration cursor
678  * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
679  * @ss_mask: the bitmask
680  *
681  * The block will only run for cases where the ssid-th bit (1 << ssid) of
682  * @ss_mask is set.
683  */
684 #define do_each_subsys_mask(ss, ssid, ss_mask) do {			\
685 	unsigned long __ss_mask = (ss_mask);				\
686 	if (!CGROUP_HAS_SUBSYS_CONFIG) {				\
687 		(ssid) = 0;						\
688 		break;							\
689 	}								\
690 	for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) {	\
691 		(ss) = cgroup_subsys[ssid];				\
692 		{
693 
694 #define while_each_subsys_mask()					\
695 		}							\
696 	}								\
697 } while (false)
698 
699 /*
700  * The default css_set - used by init and its children prior to any
701  * hierarchies being mounted. It contains a pointer to the root state
702  * for each subsystem. Also used to anchor the list of css_sets. Not
703  * reference-counted, to improve performance when child cgroups
704  * haven't been created.
705  */
706 struct css_set init_css_set = {
707 	.refcount		= REFCOUNT_INIT(1),
708 	.dom_cset		= &init_css_set,
709 	.tasks			= LIST_HEAD_INIT(init_css_set.tasks),
710 	.mg_tasks		= LIST_HEAD_INIT(init_css_set.mg_tasks),
711 	.dying_tasks		= LIST_HEAD_INIT(init_css_set.dying_tasks),
712 	.task_iters		= LIST_HEAD_INIT(init_css_set.task_iters),
713 	.threaded_csets		= LIST_HEAD_INIT(init_css_set.threaded_csets),
714 	.cgrp_links		= LIST_HEAD_INIT(init_css_set.cgrp_links),
715 	.mg_src_preload_node	= LIST_HEAD_INIT(init_css_set.mg_src_preload_node),
716 	.mg_dst_preload_node	= LIST_HEAD_INIT(init_css_set.mg_dst_preload_node),
717 	.mg_node		= LIST_HEAD_INIT(init_css_set.mg_node),
718 
719 	/*
720 	 * The following field is re-initialized when this cset gets linked
721 	 * in cgroup_init().  However, let's initialize the field
722 	 * statically too so that the default cgroup can be accessed safely
723 	 * early during boot.
724 	 */
725 	.dfl_cgrp		= &cgrp_dfl_root.cgrp,
726 };
727 
728 static int css_set_count	= 1;	/* 1 for init_css_set */
729 
730 static bool css_set_threaded(struct css_set *cset)
731 {
732 	return cset->dom_cset != cset;
733 }
734 
735 /**
736  * css_set_populated - does a css_set contain any tasks?
737  * @cset: target css_set
738  *
739  * css_set_populated() should be the same as !!cset->nr_tasks at steady
740  * state. However, css_set_populated() can be called while a task is being
741  * added to or removed from the linked list before the nr_tasks is
742  * properly updated. Hence, we can't just look at ->nr_tasks here.
743  */
744 static bool css_set_populated(struct css_set *cset)
745 {
746 	lockdep_assert_held(&css_set_lock);
747 
748 	return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
749 }
750 
751 /**
752  * css_update_populated - update the populated state of a css and ancestors
753  * @css: leaf css whose own populated count is changing
754  * @populated: inc or dec
755  *
756  * One of the css_sets pinned by @css is getting its first task or losing the
757  * last. Propagate the transition up the parent chain so that a css's
758  * nr_populated_children is zero iff none of its descendants contain any tasks.
759  *
760  * For a cgroup->self walk, also runs cgroup-side bookkeeping at each level:
761  * domain/threaded child split, deferred-destroy trigger, and notification via
762  * "cgroup.populated" (zero iff cgrp->self has neither populated csets nor
763  * populated children; userland is notified on transitions).
764  */
765 static void css_update_populated(struct cgroup_subsys_state *css, bool populated)
766 {
767 	struct cgroup_subsys_state *child = NULL;
768 	int adj = populated ? 1 : -1;
769 
770 	lockdep_assert_held(&css_set_lock);
771 
772 	do {
773 		/* non-NULL only on the cgroup->self walk */
774 		struct cgroup *cgrp = css_is_self(css) ? css->cgroup : NULL;
775 		bool was_populated = css_is_populated(css);
776 
777 		if (!child) {
778 			WRITE_ONCE(css->nr_populated_csets,
779 				   css->nr_populated_csets + adj);
780 		} else {
781 			WRITE_ONCE(css->nr_populated_children,
782 				   css->nr_populated_children + adj);
783 			if (cgrp) {
784 				if (cgroup_is_threaded(child->cgroup))
785 					WRITE_ONCE(cgrp->nr_populated_threaded_children,
786 						   cgrp->nr_populated_threaded_children + adj);
787 				else
788 					WRITE_ONCE(cgrp->nr_populated_domain_children,
789 						   cgrp->nr_populated_domain_children + adj);
790 			}
791 		}
792 
793 		if (was_populated == css_is_populated(css))
794 			break;
795 
796 		/*
797 		 * Pair with smp_mb() in kill_css_sync(). Either we observe
798 		 * CSS_DYING and queue, or the caller observes our decrement
799 		 * and fires synchronously.
800 		 */
801 		smp_mb();
802 
803 		/*
804 		 * Subtree just emptied below a dying css. Fire deferred kill.
805 		 * The transition is one-shot for a dying css.
806 		 */
807 		if (was_populated && css_is_dying(css)) {
808 			css_get(css);
809 			WARN_ON_ONCE(!queue_work(cgroup_offline_wq, &css->kill_finish_work));
810 		}
811 
812 		if (cgrp) {
813 			cgroup1_check_for_release(cgrp);
814 			TRACE_CGROUP_PATH(notify_populated, cgrp,
815 					  cgroup_is_populated(cgrp));
816 			cgroup_file_notify(&cgrp->events_file);
817 		}
818 
819 		child = css;
820 		css = css->parent;
821 	} while (css);
822 }
823 
824 /**
825  * css_set_update_populated - update populated state of a css_set
826  * @cset: target css_set
827  * @populated: whether @cset is populated or depopulated
828  *
829  * @cset is either getting the first task or losing the last. Update the
830  * populated counters along each linked cgroup's self chain and each
831  * subsystem css that @cset pins.
832  */
833 static void css_set_update_populated(struct css_set *cset, bool populated)
834 {
835 	struct cgrp_cset_link *link;
836 	struct cgroup_subsys *ss;
837 	int ssid;
838 
839 	lockdep_assert_held(&css_set_lock);
840 
841 	list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
842 		css_update_populated(&link->cgrp->self, populated);
843 
844 	for_each_subsys(ss, ssid) {
845 		struct cgroup_subsys_state *css = cset->subsys[ssid];
846 
847 		if (css)
848 			css_update_populated(css, populated);
849 	}
850 }
851 
852 /*
853  * @task is leaving, advance task iterators which are pointing to it so
854  * that they can resume at the next position.  Advancing an iterator might
855  * remove it from the list, use safe walk.  See css_task_iter_skip() for
856  * details.
857  */
858 static void css_set_skip_task_iters(struct css_set *cset,
859 				    struct task_struct *task)
860 {
861 	struct css_task_iter *it, *pos;
862 
863 	list_for_each_entry_safe(it, pos, &cset->task_iters, iters_node)
864 		css_task_iter_skip(it, task);
865 }
866 
867 /**
868  * css_set_move_task - move a task from one css_set to another
869  * @task: task being moved
870  * @from_cset: css_set @task currently belongs to (may be NULL)
871  * @to_cset: new css_set @task is being moved to (may be NULL)
872  * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
873  *
874  * Move @task from @from_cset to @to_cset.  If @task didn't belong to any
875  * css_set, @from_cset can be NULL.  If @task is being disassociated
876  * instead of moved, @to_cset can be NULL.
877  *
878  * This function automatically handles populated counter updates and
879  * css_task_iter adjustments but the caller is responsible for managing
880  * @from_cset and @to_cset's reference counts.
881  */
882 static void css_set_move_task(struct task_struct *task,
883 			      struct css_set *from_cset, struct css_set *to_cset,
884 			      bool use_mg_tasks)
885 {
886 	lockdep_assert_held(&css_set_lock);
887 
888 	if (to_cset && !css_set_populated(to_cset))
889 		css_set_update_populated(to_cset, true);
890 
891 	if (from_cset) {
892 		WARN_ON_ONCE(list_empty(&task->cg_list));
893 
894 		css_set_skip_task_iters(from_cset, task);
895 		list_del_init(&task->cg_list);
896 		if (!css_set_populated(from_cset))
897 			css_set_update_populated(from_cset, false);
898 	} else {
899 		WARN_ON_ONCE(!list_empty(&task->cg_list));
900 	}
901 
902 	if (to_cset) {
903 		/*
904 		 * We are synchronized through cgroup_threadgroup_rwsem
905 		 * against PF_EXITING setting such that we can't race
906 		 * against cgroup_task_dead()/cgroup_task_free() dropping
907 		 * the css_set.
908 		 */
909 		WARN_ON_ONCE(task->flags & PF_EXITING);
910 
911 		cgroup_move_task(task, to_cset);
912 		list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
913 							     &to_cset->tasks);
914 	}
915 }
916 
917 /*
918  * hash table for cgroup groups. This improves the performance to find
919  * an existing css_set. This hash doesn't (currently) take into
920  * account cgroups in empty hierarchies.
921  */
922 #define CSS_SET_HASH_BITS	7
923 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
924 
925 static unsigned long css_set_hash(struct cgroup_subsys_state **css)
926 {
927 	unsigned long key = 0UL;
928 	struct cgroup_subsys *ss;
929 	int i;
930 
931 	for_each_subsys(ss, i)
932 		key += (unsigned long)css[i];
933 	key = (key >> 16) ^ key;
934 
935 	return key;
936 }
937 
938 void put_css_set_locked(struct css_set *cset)
939 {
940 	struct cgrp_cset_link *link, *tmp_link;
941 	struct cgroup_subsys *ss;
942 	int ssid;
943 
944 	lockdep_assert_held(&css_set_lock);
945 
946 	if (!refcount_dec_and_test(&cset->refcount))
947 		return;
948 
949 	WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
950 
951 	/* This css_set is dead. Unlink it and release cgroup and css refs */
952 	for_each_subsys(ss, ssid) {
953 		list_del(&cset->e_cset_node[ssid]);
954 		css_put(cset->subsys[ssid]);
955 	}
956 	hash_del(&cset->hlist);
957 	css_set_count--;
958 
959 	list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
960 		list_del(&link->cset_link);
961 		list_del(&link->cgrp_link);
962 		if (cgroup_parent(link->cgrp))
963 			cgroup_put(link->cgrp);
964 		kfree(link);
965 	}
966 
967 	if (css_set_threaded(cset)) {
968 		list_del(&cset->threaded_csets_node);
969 		put_css_set_locked(cset->dom_cset);
970 	}
971 
972 	kfree_rcu(cset, rcu_head);
973 }
974 
975 /**
976  * compare_css_sets - helper function for find_existing_css_set().
977  * @cset: candidate css_set being tested
978  * @old_cset: existing css_set for a task
979  * @new_cgrp: cgroup that's being entered by the task
980  * @template: desired set of css pointers in css_set (pre-calculated)
981  *
982  * Returns true if "cset" matches "old_cset" except for the hierarchy
983  * which "new_cgrp" belongs to, for which it should match "new_cgrp".
984  */
985 static bool compare_css_sets(struct css_set *cset,
986 			     struct css_set *old_cset,
987 			     struct cgroup *new_cgrp,
988 			     struct cgroup_subsys_state *template[])
989 {
990 	struct cgroup *new_dfl_cgrp;
991 	struct list_head *l1, *l2;
992 
993 	/*
994 	 * On the default hierarchy, there can be csets which are
995 	 * associated with the same set of cgroups but different csses.
996 	 * Let's first ensure that csses match.
997 	 */
998 	if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
999 		return false;
1000 
1001 
1002 	/* @cset's domain should match the default cgroup's */
1003 	if (cgroup_on_dfl(new_cgrp))
1004 		new_dfl_cgrp = new_cgrp;
1005 	else
1006 		new_dfl_cgrp = old_cset->dfl_cgrp;
1007 
1008 	if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
1009 		return false;
1010 
1011 	/*
1012 	 * Compare cgroup pointers in order to distinguish between
1013 	 * different cgroups in hierarchies.  As different cgroups may
1014 	 * share the same effective css, this comparison is always
1015 	 * necessary.
1016 	 */
1017 	l1 = &cset->cgrp_links;
1018 	l2 = &old_cset->cgrp_links;
1019 	while (1) {
1020 		struct cgrp_cset_link *link1, *link2;
1021 		struct cgroup *cgrp1, *cgrp2;
1022 
1023 		l1 = l1->next;
1024 		l2 = l2->next;
1025 		/* See if we reached the end - both lists are equal length. */
1026 		if (l1 == &cset->cgrp_links) {
1027 			BUG_ON(l2 != &old_cset->cgrp_links);
1028 			break;
1029 		} else {
1030 			BUG_ON(l2 == &old_cset->cgrp_links);
1031 		}
1032 		/* Locate the cgroups associated with these links. */
1033 		link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
1034 		link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
1035 		cgrp1 = link1->cgrp;
1036 		cgrp2 = link2->cgrp;
1037 		/* Hierarchies should be linked in the same order. */
1038 		BUG_ON(cgrp1->root != cgrp2->root);
1039 
1040 		/*
1041 		 * If this hierarchy is the hierarchy of the cgroup
1042 		 * that's changing, then we need to check that this
1043 		 * css_set points to the new cgroup; if it's any other
1044 		 * hierarchy, then this css_set should point to the
1045 		 * same cgroup as the old css_set.
1046 		 */
1047 		if (cgrp1->root == new_cgrp->root) {
1048 			if (cgrp1 != new_cgrp)
1049 				return false;
1050 		} else {
1051 			if (cgrp1 != cgrp2)
1052 				return false;
1053 		}
1054 	}
1055 	return true;
1056 }
1057 
1058 /**
1059  * find_existing_css_set - init css array and find the matching css_set
1060  * @old_cset: the css_set that we're using before the cgroup transition
1061  * @cgrp: the cgroup that we're moving into
1062  * @template: out param for the new set of csses, should be clear on entry
1063  */
1064 static struct css_set *find_existing_css_set(struct css_set *old_cset,
1065 					struct cgroup *cgrp,
1066 					struct cgroup_subsys_state **template)
1067 {
1068 	struct cgroup_root *root = cgrp->root;
1069 	struct cgroup_subsys *ss;
1070 	struct css_set *cset;
1071 	unsigned long key;
1072 	int i;
1073 
1074 	/*
1075 	 * Build the set of subsystem state objects that we want to see in the
1076 	 * new css_set. While subsystems can change globally, the entries here
1077 	 * won't change, so no need for locking.
1078 	 */
1079 	for_each_subsys(ss, i) {
1080 		if (unlikely(cgroup_rebind_ss_mask & (1UL << i))) {
1081 			/*
1082 			 * @ss is leaving this hierarchy and its per-cgroup
1083 			 * csses are about to be killed. Resolve to the
1084 			 * surviving root css so the tasks are migrated there.
1085 			 */
1086 			template[i] = cgroup_css(&root->cgrp, ss);
1087 			WARN_ON_ONCE(!template[i]);
1088 		} else if (root->subsys_mask & (1UL << i)) {
1089 			/*
1090 			 * @ss is in this hierarchy, so we want the
1091 			 * effective css from @cgrp.
1092 			 */
1093 			template[i] = cgroup_e_css_by_mask(cgrp, ss);
1094 		} else {
1095 			/*
1096 			 * @ss is not in this hierarchy, so we don't want
1097 			 * to change the css.
1098 			 */
1099 			template[i] = old_cset->subsys[i];
1100 		}
1101 	}
1102 
1103 	key = css_set_hash(template);
1104 	hash_for_each_possible(css_set_table, cset, hlist, key) {
1105 		if (!compare_css_sets(cset, old_cset, cgrp, template))
1106 			continue;
1107 
1108 		/* This css_set matches what we need */
1109 		return cset;
1110 	}
1111 
1112 	/* No existing cgroup group matched */
1113 	return NULL;
1114 }
1115 
1116 static void free_cgrp_cset_links(struct list_head *links_to_free)
1117 {
1118 	struct cgrp_cset_link *link, *tmp_link;
1119 
1120 	list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1121 		list_del(&link->cset_link);
1122 		kfree(link);
1123 	}
1124 }
1125 
1126 /**
1127  * allocate_cgrp_cset_links - allocate cgrp_cset_links
1128  * @count: the number of links to allocate
1129  * @tmp_links: list_head the allocated links are put on
1130  *
1131  * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1132  * through ->cset_link.  Returns 0 on success or -errno.
1133  */
1134 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1135 {
1136 	struct cgrp_cset_link *link;
1137 	int i;
1138 
1139 	INIT_LIST_HEAD(tmp_links);
1140 
1141 	for (i = 0; i < count; i++) {
1142 		link = kzalloc_obj(*link);
1143 		if (!link) {
1144 			free_cgrp_cset_links(tmp_links);
1145 			return -ENOMEM;
1146 		}
1147 		list_add(&link->cset_link, tmp_links);
1148 	}
1149 	return 0;
1150 }
1151 
1152 /**
1153  * link_css_set - a helper function to link a css_set to a cgroup
1154  * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1155  * @cset: the css_set to be linked
1156  * @cgrp: the destination cgroup
1157  */
1158 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1159 			 struct cgroup *cgrp)
1160 {
1161 	struct cgrp_cset_link *link;
1162 
1163 	BUG_ON(list_empty(tmp_links));
1164 
1165 	if (cgroup_on_dfl(cgrp))
1166 		cset->dfl_cgrp = cgrp;
1167 
1168 	link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1169 	link->cset = cset;
1170 	link->cgrp = cgrp;
1171 
1172 	/*
1173 	 * Always add links to the tail of the lists so that the lists are
1174 	 * in chronological order.
1175 	 */
1176 	list_move_tail(&link->cset_link, &cgrp->cset_links);
1177 	list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1178 
1179 	if (cgroup_parent(cgrp))
1180 		cgroup_get_live(cgrp);
1181 }
1182 
1183 /**
1184  * find_css_set - return a new css_set with one cgroup updated
1185  * @old_cset: the baseline css_set
1186  * @cgrp: the cgroup to be updated
1187  *
1188  * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1189  * substituted into the appropriate hierarchy.
1190  */
1191 static struct css_set *find_css_set(struct css_set *old_cset,
1192 				    struct cgroup *cgrp)
1193 {
1194 	struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1195 	struct css_set *cset;
1196 	struct list_head tmp_links;
1197 	struct cgrp_cset_link *link;
1198 	struct cgroup_subsys *ss;
1199 	unsigned long key;
1200 	int ssid;
1201 
1202 	lockdep_assert_held(&cgroup_mutex);
1203 
1204 	/* First see if we already have a cgroup group that matches
1205 	 * the desired set */
1206 	spin_lock_irq(&css_set_lock);
1207 	cset = find_existing_css_set(old_cset, cgrp, template);
1208 	if (cset)
1209 		get_css_set(cset);
1210 	spin_unlock_irq(&css_set_lock);
1211 
1212 	if (cset)
1213 		return cset;
1214 
1215 	cset = kzalloc_obj(*cset);
1216 	if (!cset)
1217 		return NULL;
1218 
1219 	/* Allocate all the cgrp_cset_link objects that we'll need */
1220 	if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1221 		kfree(cset);
1222 		return NULL;
1223 	}
1224 
1225 	refcount_set(&cset->refcount, 1);
1226 	cset->dom_cset = cset;
1227 	INIT_LIST_HEAD(&cset->tasks);
1228 	INIT_LIST_HEAD(&cset->mg_tasks);
1229 	INIT_LIST_HEAD(&cset->dying_tasks);
1230 	INIT_LIST_HEAD(&cset->task_iters);
1231 	INIT_LIST_HEAD(&cset->threaded_csets);
1232 	INIT_HLIST_NODE(&cset->hlist);
1233 	INIT_LIST_HEAD(&cset->cgrp_links);
1234 	INIT_LIST_HEAD(&cset->mg_src_preload_node);
1235 	INIT_LIST_HEAD(&cset->mg_dst_preload_node);
1236 	INIT_LIST_HEAD(&cset->mg_node);
1237 
1238 	/* Copy the set of subsystem state objects generated in
1239 	 * find_existing_css_set() */
1240 	memcpy(cset->subsys, template, sizeof(cset->subsys));
1241 
1242 	spin_lock_irq(&css_set_lock);
1243 	/* Add reference counts and links from the new css_set. */
1244 	list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1245 		struct cgroup *c = link->cgrp;
1246 
1247 		if (c->root == cgrp->root)
1248 			c = cgrp;
1249 		link_css_set(&tmp_links, cset, c);
1250 	}
1251 
1252 	BUG_ON(!list_empty(&tmp_links));
1253 
1254 	css_set_count++;
1255 
1256 	/* Add @cset to the hash table */
1257 	key = css_set_hash(cset->subsys);
1258 	hash_add(css_set_table, &cset->hlist, key);
1259 
1260 	for_each_subsys(ss, ssid) {
1261 		struct cgroup_subsys_state *css = cset->subsys[ssid];
1262 
1263 		list_add_tail(&cset->e_cset_node[ssid],
1264 			      &css->cgroup->e_csets[ssid]);
1265 		css_get(css);
1266 	}
1267 
1268 	spin_unlock_irq(&css_set_lock);
1269 
1270 	/*
1271 	 * If @cset should be threaded, look up the matching dom_cset and
1272 	 * link them up.  We first fully initialize @cset then look for the
1273 	 * dom_cset.  It's simpler this way and safe as @cset is guaranteed
1274 	 * to stay empty until we return.
1275 	 */
1276 	if (cgroup_is_threaded(cset->dfl_cgrp)) {
1277 		struct css_set *dcset;
1278 
1279 		dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1280 		if (!dcset) {
1281 			put_css_set(cset);
1282 			return NULL;
1283 		}
1284 
1285 		spin_lock_irq(&css_set_lock);
1286 		cset->dom_cset = dcset;
1287 		list_add_tail(&cset->threaded_csets_node,
1288 			      &dcset->threaded_csets);
1289 		spin_unlock_irq(&css_set_lock);
1290 	}
1291 
1292 	return cset;
1293 }
1294 
1295 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1296 {
1297 	struct cgroup *root_cgrp = kernfs_root_to_node(kf_root)->priv;
1298 
1299 	return root_cgrp->root;
1300 }
1301 
1302 void cgroup_favor_dynmods(struct cgroup_root *root, bool favor)
1303 {
1304 	bool favoring = root->flags & CGRP_ROOT_FAVOR_DYNMODS;
1305 
1306 	/*
1307 	 * see the comment above CGRP_ROOT_FAVOR_DYNMODS definition.
1308 	 * favordynmods can flip while task is between
1309 	 * cgroup_threadgroup_change_begin() and end(), so down_write global
1310 	 * cgroup_threadgroup_rwsem to synchronize them.
1311 	 *
1312 	 * Once cgroup_enable_per_threadgroup_rwsem is enabled, holding
1313 	 * cgroup_threadgroup_rwsem doesn't exlude tasks between
1314 	 * cgroup_thread_group_change_begin() and end() and thus it's unsafe to
1315 	 * turn off. As the scenario is unlikely, simply disallow disabling once
1316 	 * enabled and print out a warning.
1317 	 */
1318 	percpu_down_write(&cgroup_threadgroup_rwsem);
1319 	if (favor && !favoring) {
1320 		cgroup_enable_per_threadgroup_rwsem = true;
1321 		rcu_sync_enter(&cgroup_threadgroup_rwsem.rss);
1322 		root->flags |= CGRP_ROOT_FAVOR_DYNMODS;
1323 	} else if (!favor && favoring) {
1324 		if (cgroup_enable_per_threadgroup_rwsem)
1325 			pr_warn_once("cgroup favordynmods: per threadgroup rwsem mechanism can't be disabled\n");
1326 		rcu_sync_exit(&cgroup_threadgroup_rwsem.rss);
1327 		root->flags &= ~CGRP_ROOT_FAVOR_DYNMODS;
1328 	}
1329 	percpu_up_write(&cgroup_threadgroup_rwsem);
1330 }
1331 
1332 static int cgroup_init_root_id(struct cgroup_root *root)
1333 {
1334 	int id;
1335 
1336 	lockdep_assert_held(&cgroup_mutex);
1337 
1338 	id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1339 	if (id < 0)
1340 		return id;
1341 
1342 	root->hierarchy_id = id;
1343 	return 0;
1344 }
1345 
1346 static void cgroup_exit_root_id(struct cgroup_root *root)
1347 {
1348 	lockdep_assert_held(&cgroup_mutex);
1349 
1350 	idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1351 }
1352 
1353 void cgroup_free_root(struct cgroup_root *root)
1354 {
1355 	kfree_rcu(root, rcu);
1356 }
1357 
1358 static void cgroup_destroy_root(struct cgroup_root *root)
1359 {
1360 	struct cgroup *cgrp = &root->cgrp;
1361 	struct cgrp_cset_link *link, *tmp_link;
1362 	int ret;
1363 
1364 	trace_cgroup_destroy_root(root);
1365 
1366 	/* runs off a workqueue, no signal can interrupt the drain */
1367 	ret = cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1368 	if (WARN_ON_ONCE(ret))
1369 		cgroup_lock();
1370 
1371 	BUG_ON(atomic_read(&root->nr_cgrps));
1372 	BUG_ON(!list_empty(&cgrp->self.children));
1373 
1374 	ret = blocking_notifier_call_chain(&cgroup_lifetime_notifier,
1375 					   CGROUP_LIFETIME_OFFLINE, cgrp);
1376 	WARN_ON_ONCE(notifier_to_errno(ret));
1377 
1378 	/* Rebind all subsystems back to the default hierarchy */
1379 	WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1380 
1381 	/*
1382 	 * Release all the links from cset_links to this hierarchy's
1383 	 * root cgroup
1384 	 */
1385 	spin_lock_irq(&css_set_lock);
1386 
1387 	list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1388 		list_del(&link->cset_link);
1389 		list_del(&link->cgrp_link);
1390 		kfree(link);
1391 	}
1392 
1393 	spin_unlock_irq(&css_set_lock);
1394 
1395 	WARN_ON_ONCE(list_empty(&root->root_list));
1396 	list_del_rcu(&root->root_list);
1397 	cgroup_root_count--;
1398 
1399 	if (!have_favordynmods)
1400 		cgroup_favor_dynmods(root, false);
1401 
1402 	cgroup_exit_root_id(root);
1403 
1404 	cgroup_unlock();
1405 
1406 	kernfs_destroy_root(root->kf_root);
1407 	cgroup_free_root(root);
1408 }
1409 
1410 /*
1411  * Returned cgroup is without refcount but it's valid as long as cset pins it.
1412  */
1413 static inline struct cgroup *__cset_cgroup_from_root(struct css_set *cset,
1414 					    struct cgroup_root *root)
1415 {
1416 	struct cgroup *res_cgroup = NULL;
1417 
1418 	if (cset == &init_css_set) {
1419 		res_cgroup = &root->cgrp;
1420 	} else if (root == &cgrp_dfl_root) {
1421 		res_cgroup = cset->dfl_cgrp;
1422 	} else {
1423 		struct cgrp_cset_link *link;
1424 		lockdep_assert_held(&css_set_lock);
1425 
1426 		list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1427 			struct cgroup *c = link->cgrp;
1428 
1429 			if (c->root == root) {
1430 				res_cgroup = c;
1431 				break;
1432 			}
1433 		}
1434 	}
1435 
1436 	/*
1437 	 * If cgroup_mutex is not held, the cgrp_cset_link will be freed
1438 	 * before we remove the cgroup root from the root_list. Consequently,
1439 	 * when accessing a cgroup root, the cset_link may have already been
1440 	 * freed, resulting in a NULL res_cgroup. However, by holding the
1441 	 * cgroup_mutex, we ensure that res_cgroup can't be NULL.
1442 	 * If we don't hold cgroup_mutex in the caller, we must do the NULL
1443 	 * check.
1444 	 */
1445 	return res_cgroup;
1446 }
1447 
1448 /*
1449  * look up cgroup associated with current task's cgroup namespace on the
1450  * specified hierarchy
1451  */
1452 static struct cgroup *
1453 current_cgns_cgroup_from_root(struct cgroup_root *root)
1454 {
1455 	struct cgroup *res = NULL;
1456 	struct css_set *cset;
1457 
1458 	lockdep_assert_held(&css_set_lock);
1459 
1460 	rcu_read_lock();
1461 
1462 	cset = current->nsproxy->cgroup_ns->root_cset;
1463 	res = __cset_cgroup_from_root(cset, root);
1464 
1465 	rcu_read_unlock();
1466 
1467 	/*
1468 	 * The namespace_sem is held by current, so the root cgroup can't
1469 	 * be umounted. Therefore, we can ensure that the res is non-NULL.
1470 	 */
1471 	WARN_ON_ONCE(!res);
1472 	return res;
1473 }
1474 
1475 /*
1476  * Look up cgroup associated with current task's cgroup namespace on the default
1477  * hierarchy.
1478  *
1479  * Unlike current_cgns_cgroup_from_root(), this doesn't need locks:
1480  * - Internal rcu_read_lock is unnecessary because we don't dereference any rcu
1481  *   pointers.
1482  * - css_set_lock is not needed because we just read cset->dfl_cgrp.
1483  * - As a bonus returned cgrp is pinned with the current because it cannot
1484  *   switch cgroup_ns asynchronously.
1485  */
1486 static struct cgroup *current_cgns_cgroup_dfl(void)
1487 {
1488 	struct css_set *cset;
1489 
1490 	if (current->nsproxy) {
1491 		cset = current->nsproxy->cgroup_ns->root_cset;
1492 		return __cset_cgroup_from_root(cset, &cgrp_dfl_root);
1493 	} else {
1494 		/*
1495 		 * NOTE: This function may be called from bpf_cgroup_from_id()
1496 		 * on a task which has already passed exit_nsproxy_namespaces()
1497 		 * and nsproxy == NULL. Fall back to cgrp_dfl_root which will
1498 		 * make all cgroups visible for lookups.
1499 		 */
1500 		return &cgrp_dfl_root.cgrp;
1501 	}
1502 }
1503 
1504 /* look up cgroup associated with given css_set on the specified hierarchy */
1505 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1506 					    struct cgroup_root *root)
1507 {
1508 	lockdep_assert_held(&css_set_lock);
1509 
1510 	return __cset_cgroup_from_root(cset, root);
1511 }
1512 
1513 /*
1514  * Return the cgroup for "task" from the given hierarchy. Must be
1515  * called with css_set_lock held to prevent task's groups from being modified.
1516  * Must be called with either cgroup_mutex or rcu read lock to prevent the
1517  * cgroup root from being destroyed.
1518  */
1519 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1520 				     struct cgroup_root *root)
1521 {
1522 	/*
1523 	 * No need to lock the task - since we hold css_set_lock the
1524 	 * task can't change groups.
1525 	 */
1526 	return cset_cgroup_from_root(task_css_set(task), root);
1527 }
1528 
1529 /*
1530  * A task must hold cgroup_mutex to modify cgroups.
1531  *
1532  * Any task can increment and decrement the count field without lock.
1533  * So in general, code holding cgroup_mutex can't rely on the count
1534  * field not changing.  However, if the count goes to zero, then only
1535  * cgroup_attach_task() can increment it again.  Because a count of zero
1536  * means that no tasks are currently attached, therefore there is no
1537  * way a task attached to that cgroup can fork (the other way to
1538  * increment the count).  So code holding cgroup_mutex can safely
1539  * assume that if the count is zero, it will stay zero. Similarly, if
1540  * a task holds cgroup_mutex on a cgroup with zero count, it
1541  * knows that the cgroup won't be removed, as cgroup_rmdir()
1542  * needs that mutex.
1543  *
1544  * A cgroup can only be deleted if both its 'count' of using tasks
1545  * is zero, and its list of 'children' cgroups is empty.  Since all
1546  * tasks in the system use _some_ cgroup, and since there is always at
1547  * least one task in the system (init, pid == 1), therefore, root cgroup
1548  * always has either children cgroups and/or using tasks.  So we don't
1549  * need a special hack to ensure that root cgroup cannot be deleted.
1550  *
1551  * P.S.  One more locking exception.  RCU is used to guard the
1552  * update of a tasks cgroup pointer by cgroup_attach_task()
1553  */
1554 
1555 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1556 
1557 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1558 			      char *buf)
1559 {
1560 	struct cgroup_subsys *ss = cft->ss;
1561 
1562 	if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1563 	    !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
1564 		const char *dbg = (cft->flags & CFTYPE_DEBUG) ? ".__DEBUG__." : "";
1565 
1566 		snprintf(buf, CGROUP_FILE_NAME_MAX, "%s%s.%s",
1567 			 dbg, cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1568 			 cft->name);
1569 	} else {
1570 		strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1571 	}
1572 	return buf;
1573 }
1574 
1575 /**
1576  * cgroup_file_mode - deduce file mode of a control file
1577  * @cft: the control file in question
1578  *
1579  * S_IRUGO for read, S_IWUSR for write.
1580  */
1581 static umode_t cgroup_file_mode(const struct cftype *cft)
1582 {
1583 	umode_t mode = 0;
1584 
1585 	if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1586 		mode |= S_IRUGO;
1587 
1588 	if (cft->write_u64 || cft->write_s64 || cft->write) {
1589 		if (cft->flags & CFTYPE_WORLD_WRITABLE)
1590 			mode |= S_IWUGO;
1591 		else
1592 			mode |= S_IWUSR;
1593 	}
1594 
1595 	return mode;
1596 }
1597 
1598 /**
1599  * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1600  * @subtree_control: the new subtree_control mask to consider
1601  * @this_ss_mask: available subsystems
1602  *
1603  * On the default hierarchy, a subsystem may request other subsystems to be
1604  * enabled together through its ->depends_on mask.  In such cases, more
1605  * subsystems than specified in "cgroup.subtree_control" may be enabled.
1606  *
1607  * This function calculates which subsystems need to be enabled if
1608  * @subtree_control is to be applied while restricted to @this_ss_mask.
1609  */
1610 static u32 cgroup_calc_subtree_ss_mask(u32 subtree_control, u32 this_ss_mask)
1611 {
1612 	u32 cur_ss_mask = subtree_control;
1613 	struct cgroup_subsys *ss;
1614 	int ssid;
1615 
1616 	lockdep_assert_held(&cgroup_mutex);
1617 
1618 	cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1619 
1620 	while (true) {
1621 		u32 new_ss_mask = cur_ss_mask;
1622 
1623 		do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1624 			new_ss_mask |= ss->depends_on;
1625 		} while_each_subsys_mask();
1626 
1627 		/*
1628 		 * Mask out subsystems which aren't available.  This can
1629 		 * happen only if some depended-upon subsystems were bound
1630 		 * to non-default hierarchies.
1631 		 */
1632 		new_ss_mask &= this_ss_mask;
1633 
1634 		if (new_ss_mask == cur_ss_mask)
1635 			break;
1636 		cur_ss_mask = new_ss_mask;
1637 	}
1638 
1639 	return cur_ss_mask;
1640 }
1641 
1642 /**
1643  * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1644  * @kn: the kernfs_node being serviced
1645  *
1646  * This helper undoes cgroup_kn_lock_live() and should be invoked before
1647  * the method finishes if locking succeeded.  Note that once this function
1648  * returns the cgroup returned by cgroup_kn_lock_live() may become
1649  * inaccessible any time.  If the caller intends to continue to access the
1650  * cgroup, it should pin it before invoking this function.
1651  */
1652 void cgroup_kn_unlock(struct kernfs_node *kn)
1653 {
1654 	struct cgroup *cgrp;
1655 
1656 	if (kernfs_type(kn) == KERNFS_DIR)
1657 		cgrp = kn->priv;
1658 	else
1659 		cgrp = kn_priv(kn);
1660 
1661 	cgroup_unlock();
1662 
1663 	kernfs_unbreak_active_protection(kn);
1664 	cgroup_put(cgrp);
1665 }
1666 
1667 /**
1668  * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1669  * @kn: the kernfs_node being serviced
1670  * @drain_offline: perform offline draining on the cgroup
1671  *
1672  * This helper is to be used by a cgroup kernfs method currently servicing
1673  * @kn.  It breaks the active protection, performs cgroup locking and
1674  * verifies that the associated cgroup is alive.  Returns the cgroup if
1675  * alive; otherwise, an ERR_PTR value.  A successful return should be undone by
1676  * a matching cgroup_kn_unlock() invocation.  If @drain_offline is %true, the
1677  * cgroup is drained of offlining csses before return, and an interrupted drain
1678  * fails with -ERESTARTSYS.
1679  *
1680  * Any cgroup kernfs method implementation which requires locking the
1681  * associated cgroup should use this helper.  It avoids nesting cgroup
1682  * locking under kernfs active protection and allows all kernfs operations
1683  * including self-removal.
1684  */
1685 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1686 {
1687 	struct cgroup *cgrp;
1688 	int ret;
1689 
1690 	if (kernfs_type(kn) == KERNFS_DIR)
1691 		cgrp = kn->priv;
1692 	else
1693 		cgrp = kn_priv(kn);
1694 
1695 	/*
1696 	 * We're gonna grab cgroup_mutex which nests outside kernfs
1697 	 * active_ref.  cgroup liveliness check alone provides enough
1698 	 * protection against removal.  Ensure @cgrp stays accessible and
1699 	 * break the active_ref protection.
1700 	 */
1701 	if (!cgroup_tryget(cgrp))
1702 		return ERR_PTR(-ENODEV);
1703 	kernfs_break_active_protection(kn);
1704 
1705 	if (drain_offline) {
1706 		ret = cgroup_lock_and_drain_offline(cgrp);
1707 		if (unlikely(ret)) {
1708 			kernfs_unbreak_active_protection(kn);
1709 			cgroup_put(cgrp);
1710 			return ERR_PTR(ret);
1711 		}
1712 	} else {
1713 		cgroup_lock();
1714 	}
1715 
1716 	if (!cgroup_is_dead(cgrp))
1717 		return cgrp;
1718 
1719 	cgroup_kn_unlock(kn);
1720 	return ERR_PTR(-ENODEV);
1721 }
1722 
1723 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1724 {
1725 	char name[CGROUP_FILE_NAME_MAX];
1726 
1727 	lockdep_assert_held(&cgroup_mutex);
1728 
1729 	if (cft->file_offset) {
1730 		struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1731 		struct cgroup_file *cfile = (void *)css + cft->file_offset;
1732 
1733 		spin_lock_irq(&cfile->lock);
1734 		WRITE_ONCE(cfile->kn, NULL);
1735 		spin_unlock_irq(&cfile->lock);
1736 
1737 		timer_delete_sync(&cfile->notify_timer);
1738 	}
1739 
1740 	kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1741 }
1742 
1743 /**
1744  * css_clear_dir - remove subsys files in a cgroup directory
1745  * @css: target css
1746  */
1747 static void css_clear_dir(struct cgroup_subsys_state *css)
1748 {
1749 	struct cgroup *cgrp = css->cgroup;
1750 	struct cftype *cfts;
1751 
1752 	if (!(css->flags & CSS_VISIBLE))
1753 		return;
1754 
1755 	css->flags &= ~CSS_VISIBLE;
1756 
1757 	if (css_is_self(css)) {
1758 		if (cgroup_on_dfl(cgrp)) {
1759 			cgroup_addrm_files(css, cgrp,
1760 					   cgroup_base_files, false);
1761 			if (cgroup_psi_enabled())
1762 				cgroup_addrm_files(css, cgrp,
1763 						   cgroup_psi_files, false);
1764 		} else {
1765 			cgroup_addrm_files(css, cgrp,
1766 					   cgroup1_base_files, false);
1767 		}
1768 	} else {
1769 		list_for_each_entry(cfts, &css->ss->cfts, node)
1770 			cgroup_addrm_files(css, cgrp, cfts, false);
1771 	}
1772 }
1773 
1774 /**
1775  * css_populate_dir - create subsys files in a cgroup directory
1776  * @css: target css
1777  *
1778  * On failure, no file is added.
1779  */
1780 static int css_populate_dir(struct cgroup_subsys_state *css)
1781 {
1782 	struct cgroup *cgrp = css->cgroup;
1783 	struct cftype *cfts, *failed_cfts;
1784 	int ret;
1785 
1786 	if (css->flags & CSS_VISIBLE)
1787 		return 0;
1788 
1789 	if (css_is_self(css)) {
1790 		if (cgroup_on_dfl(cgrp)) {
1791 			ret = cgroup_addrm_files(css, cgrp,
1792 						 cgroup_base_files, true);
1793 			if (ret < 0)
1794 				return ret;
1795 
1796 			if (cgroup_psi_enabled()) {
1797 				ret = cgroup_addrm_files(css, cgrp,
1798 							 cgroup_psi_files, true);
1799 				if (ret < 0) {
1800 					cgroup_addrm_files(css, cgrp,
1801 							   cgroup_base_files, false);
1802 					return ret;
1803 				}
1804 			}
1805 		} else {
1806 			ret = cgroup_addrm_files(css, cgrp,
1807 						 cgroup1_base_files, true);
1808 			if (ret < 0)
1809 				return ret;
1810 		}
1811 	} else {
1812 		list_for_each_entry(cfts, &css->ss->cfts, node) {
1813 			ret = cgroup_addrm_files(css, cgrp, cfts, true);
1814 			if (ret < 0) {
1815 				failed_cfts = cfts;
1816 				goto err;
1817 			}
1818 		}
1819 	}
1820 
1821 	css->flags |= CSS_VISIBLE;
1822 
1823 	return 0;
1824 err:
1825 	list_for_each_entry(cfts, &css->ss->cfts, node) {
1826 		if (cfts == failed_cfts)
1827 			break;
1828 		cgroup_addrm_files(css, cgrp, cfts, false);
1829 	}
1830 	return ret;
1831 }
1832 
1833 int rebind_subsystems(struct cgroup_root *dst_root, u32 ss_mask)
1834 {
1835 	struct cgroup *dcgrp = &dst_root->cgrp;
1836 	struct cgroup_subsys *ss;
1837 	int ssid, ret;
1838 	u32 dfl_disable_ss_mask = 0;
1839 
1840 	lockdep_assert_held(&cgroup_mutex);
1841 
1842 	do_each_subsys_mask(ss, ssid, ss_mask) {
1843 		/*
1844 		 * If @ss has non-root csses attached to it, can't move.
1845 		 * If @ss is an implicit controller, it is exempt from this
1846 		 * rule and can be stolen.
1847 		 */
1848 		if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1849 		    !ss->implicit_on_dfl)
1850 			return -EBUSY;
1851 
1852 		/* can't move between two non-dummy roots either */
1853 		if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1854 			return -EBUSY;
1855 
1856 		/*
1857 		 * Collect ssid's that need to be disabled from default
1858 		 * hierarchy.
1859 		 */
1860 		if (ss->root == &cgrp_dfl_root)
1861 			dfl_disable_ss_mask |= 1 << ssid;
1862 
1863 	} while_each_subsys_mask();
1864 
1865 	if (dfl_disable_ss_mask) {
1866 		struct cgroup *scgrp = &cgrp_dfl_root.cgrp;
1867 
1868 		/*
1869 		 * Controllers leaving the default hierarchy are disabled
1870 		 * together. cgroup_rebind_ss_mask makes cgroup_apply_control()
1871 		 * migrate their tasks to the root css, so the per-cgroup csses
1872 		 * are unpopulated when cgroup_finalize_control() kills them.
1873 		 * Clear it before cgroup_finalize_control(), which does no
1874 		 * css_set lookup.
1875 		 */
1876 		cgrp_dfl_root.subsys_mask &= ~dfl_disable_ss_mask;
1877 		cgroup_rebind_ss_mask = dfl_disable_ss_mask;
1878 		WARN_ON(cgroup_apply_control(scgrp));
1879 		cgroup_rebind_ss_mask = 0;
1880 		cgroup_finalize_control(scgrp, 0);
1881 	}
1882 
1883 	do_each_subsys_mask(ss, ssid, ss_mask) {
1884 		struct cgroup_root *src_root = ss->root;
1885 		struct cgroup *scgrp = &src_root->cgrp;
1886 		struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1887 		struct css_set *cset, *cset_pos;
1888 		struct css_task_iter *it;
1889 
1890 		WARN_ON(!css || cgroup_css(dcgrp, ss));
1891 
1892 		if (src_root != &cgrp_dfl_root) {
1893 			/*
1894 			 * Disable from the source, migrating its tasks to the
1895 			 * root css first (see cgroup_rebind_ss_mask).
1896 			 */
1897 			src_root->subsys_mask &= ~(1 << ssid);
1898 			cgroup_rebind_ss_mask = 1 << ssid;
1899 			WARN_ON(cgroup_apply_control(scgrp));
1900 			cgroup_rebind_ss_mask = 0;
1901 			cgroup_finalize_control(scgrp, 0);
1902 		}
1903 
1904 		/* rebind */
1905 		RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1906 		rcu_assign_pointer(dcgrp->subsys[ssid], css);
1907 		ss->root = dst_root;
1908 
1909 		spin_lock_irq(&css_set_lock);
1910 		css->cgroup = dcgrp;
1911 		WARN_ON(!list_empty(&dcgrp->e_csets[ss->id]));
1912 		list_for_each_entry_safe(cset, cset_pos, &scgrp->e_csets[ss->id],
1913 					 e_cset_node[ss->id]) {
1914 			list_move_tail(&cset->e_cset_node[ss->id],
1915 				       &dcgrp->e_csets[ss->id]);
1916 			/*
1917 			 * all css_sets of scgrp together in same order to dcgrp,
1918 			 * patch in-flight iterators to preserve correct iteration.
1919 			 * since the iterator is always advanced right away and
1920 			 * finished when it->cset_pos meets it->cset_head, so only
1921 			 * update it->cset_head is enough here.
1922 			 */
1923 			list_for_each_entry(it, &cset->task_iters, iters_node)
1924 				if (it->cset_head == &scgrp->e_csets[ss->id])
1925 					it->cset_head = &dcgrp->e_csets[ss->id];
1926 		}
1927 		spin_unlock_irq(&css_set_lock);
1928 
1929 		/* default hierarchy doesn't enable controllers by default */
1930 		dst_root->subsys_mask |= 1 << ssid;
1931 		if (dst_root == &cgrp_dfl_root) {
1932 			static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1933 		} else {
1934 			dcgrp->subtree_control |= 1 << ssid;
1935 			static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1936 		}
1937 
1938 		ret = cgroup_apply_control(dcgrp);
1939 		if (ret)
1940 			pr_warn("partial failure to rebind %s controller (err=%d)\n",
1941 				ss->name, ret);
1942 
1943 		if (ss->bind)
1944 			ss->bind(css);
1945 	} while_each_subsys_mask();
1946 
1947 	kernfs_activate(dcgrp->kn);
1948 	return 0;
1949 }
1950 
1951 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1952 		     struct kernfs_root *kf_root)
1953 {
1954 	int len = 0;
1955 	char *buf = NULL;
1956 	struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1957 	struct cgroup *ns_cgroup;
1958 
1959 	buf = kmalloc(PATH_MAX, GFP_KERNEL);
1960 	if (!buf)
1961 		return -ENOMEM;
1962 
1963 	spin_lock_irq(&css_set_lock);
1964 	ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1965 	len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1966 	spin_unlock_irq(&css_set_lock);
1967 
1968 	if (len == -E2BIG)
1969 		len = -ERANGE;
1970 	else if (len > 0) {
1971 		seq_escape(sf, buf, " \t\n\\");
1972 		len = 0;
1973 	}
1974 	kfree(buf);
1975 	return len;
1976 }
1977 
1978 enum cgroup2_param {
1979 	Opt_nsdelegate,
1980 	Opt_favordynmods,
1981 	Opt_memory_localevents,
1982 	Opt_memory_recursiveprot,
1983 	Opt_memory_hugetlb_accounting,
1984 	Opt_pids_localevents,
1985 	nr__cgroup2_params
1986 };
1987 
1988 static const struct fs_parameter_spec cgroup2_fs_parameters[] = {
1989 	fsparam_flag("nsdelegate",		Opt_nsdelegate),
1990 	fsparam_flag("favordynmods",		Opt_favordynmods),
1991 	fsparam_flag("memory_localevents",	Opt_memory_localevents),
1992 	fsparam_flag("memory_recursiveprot",	Opt_memory_recursiveprot),
1993 	fsparam_flag("memory_hugetlb_accounting", Opt_memory_hugetlb_accounting),
1994 	fsparam_flag("pids_localevents",	Opt_pids_localevents),
1995 	{}
1996 };
1997 
1998 static int cgroup2_parse_param(struct fs_context *fc, struct fs_parameter *param)
1999 {
2000 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2001 	struct fs_parse_result result;
2002 	int opt;
2003 
2004 	opt = fs_parse(fc, cgroup2_fs_parameters, param, &result);
2005 	if (opt < 0)
2006 		return opt;
2007 
2008 	switch (opt) {
2009 	case Opt_nsdelegate:
2010 		ctx->flags |= CGRP_ROOT_NS_DELEGATE;
2011 		return 0;
2012 	case Opt_favordynmods:
2013 		ctx->flags |= CGRP_ROOT_FAVOR_DYNMODS;
2014 		return 0;
2015 	case Opt_memory_localevents:
2016 		ctx->flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS;
2017 		return 0;
2018 	case Opt_memory_recursiveprot:
2019 		ctx->flags |= CGRP_ROOT_MEMORY_RECURSIVE_PROT;
2020 		return 0;
2021 	case Opt_memory_hugetlb_accounting:
2022 		ctx->flags |= CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING;
2023 		return 0;
2024 	case Opt_pids_localevents:
2025 		ctx->flags |= CGRP_ROOT_PIDS_LOCAL_EVENTS;
2026 		return 0;
2027 	}
2028 	return -EINVAL;
2029 }
2030 
2031 struct cgroup_of_peak *of_peak(struct kernfs_open_file *of)
2032 {
2033 	struct cgroup_file_ctx *ctx = of->priv;
2034 
2035 	return &ctx->peak;
2036 }
2037 
2038 static void apply_cgroup_root_flags(unsigned int root_flags)
2039 {
2040 	if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
2041 		if (root_flags & CGRP_ROOT_NS_DELEGATE)
2042 			cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
2043 		else
2044 			cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
2045 
2046 		cgroup_favor_dynmods(&cgrp_dfl_root,
2047 				     root_flags & CGRP_ROOT_FAVOR_DYNMODS);
2048 
2049 		if (root_flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
2050 			cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS;
2051 		else
2052 			cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_LOCAL_EVENTS;
2053 
2054 		if (root_flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT)
2055 			cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_RECURSIVE_PROT;
2056 		else
2057 			cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_RECURSIVE_PROT;
2058 
2059 		if (root_flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING)
2060 			cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING;
2061 		else
2062 			cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING;
2063 
2064 		if (root_flags & CGRP_ROOT_PIDS_LOCAL_EVENTS)
2065 			cgrp_dfl_root.flags |= CGRP_ROOT_PIDS_LOCAL_EVENTS;
2066 		else
2067 			cgrp_dfl_root.flags &= ~CGRP_ROOT_PIDS_LOCAL_EVENTS;
2068 	}
2069 }
2070 
2071 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
2072 {
2073 	if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
2074 		seq_puts(seq, ",nsdelegate");
2075 	if (cgrp_dfl_root.flags & CGRP_ROOT_FAVOR_DYNMODS)
2076 		seq_puts(seq, ",favordynmods");
2077 	if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
2078 		seq_puts(seq, ",memory_localevents");
2079 	if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT)
2080 		seq_puts(seq, ",memory_recursiveprot");
2081 	if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_HUGETLB_ACCOUNTING)
2082 		seq_puts(seq, ",memory_hugetlb_accounting");
2083 	if (cgrp_dfl_root.flags & CGRP_ROOT_PIDS_LOCAL_EVENTS)
2084 		seq_puts(seq, ",pids_localevents");
2085 	return 0;
2086 }
2087 
2088 static int cgroup_reconfigure(struct fs_context *fc)
2089 {
2090 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2091 
2092 	apply_cgroup_root_flags(ctx->flags);
2093 	return 0;
2094 }
2095 
2096 static void init_cgroup_housekeeping(struct cgroup *cgrp)
2097 {
2098 	struct cgroup_subsys *ss;
2099 	int ssid;
2100 
2101 	INIT_LIST_HEAD(&cgrp->self.sibling);
2102 	INIT_LIST_HEAD(&cgrp->self.children);
2103 	INIT_LIST_HEAD(&cgrp->cset_links);
2104 	INIT_LIST_HEAD(&cgrp->pidlists);
2105 	mutex_init(&cgrp->pidlist_mutex);
2106 	cgrp->self.cgroup = cgrp;
2107 	cgrp->self.flags |= CSS_ONLINE;
2108 	cgrp->dom_cgrp = cgrp;
2109 	cgrp->max_descendants = INT_MAX;
2110 	cgrp->max_depth = INT_MAX;
2111 	prev_cputime_init(&cgrp->prev_cputime);
2112 
2113 	for_each_subsys(ss, ssid)
2114 		INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
2115 
2116 #ifdef CONFIG_CGROUP_BPF
2117 	for (int i = 0; i < ARRAY_SIZE(cgrp->bpf.revisions); i++)
2118 		cgrp->bpf.revisions[i] = 1;
2119 #endif
2120 
2121 	init_waitqueue_head(&cgrp->offline_waitq);
2122 	INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
2123 }
2124 
2125 void init_cgroup_root(struct cgroup_fs_context *ctx)
2126 {
2127 	struct cgroup_root *root = ctx->root;
2128 	struct cgroup *cgrp = &root->cgrp;
2129 	struct cgroup_subsys *ss;
2130 	int ssid;
2131 
2132 	INIT_LIST_HEAD_RCU(&root->root_list);
2133 	atomic_set(&root->nr_cgrps, 1);
2134 	cgrp->root = root;
2135 	init_cgroup_housekeeping(cgrp);
2136 
2137 	/*
2138 	 * A root cgroup's effective css is always the root css in
2139 	 * init_css_set.subsys[], whichever hierarchy the subsystem is bound
2140 	 * to, so rebind_subsystems() doesn't need to update e_css[]. For
2141 	 * cgrp_dfl_root this runs before the root csses exist, and
2142 	 * online_css() sets the entries when they come online.
2143 	 */
2144 	for_each_subsys(ss, ssid)
2145 		RCU_INIT_POINTER(cgrp->e_css[ssid], init_css_set.subsys[ssid]);
2146 
2147 	/* DYNMODS must be modified through cgroup_favor_dynmods() */
2148 	root->flags = ctx->flags & ~CGRP_ROOT_FAVOR_DYNMODS;
2149 	if (ctx->release_agent)
2150 		strscpy(root->release_agent_path, ctx->release_agent, PATH_MAX);
2151 	if (ctx->name)
2152 		strscpy(root->name, ctx->name, MAX_CGROUP_ROOT_NAMELEN);
2153 	if (ctx->cpuset_clone_children)
2154 		set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
2155 }
2156 
2157 int cgroup_setup_root(struct cgroup_root *root, u32 ss_mask)
2158 {
2159 	LIST_HEAD(tmp_links);
2160 	struct cgroup *root_cgrp = &root->cgrp;
2161 	struct kernfs_syscall_ops *kf_sops;
2162 	struct css_set *cset;
2163 	int i, ret;
2164 
2165 	lockdep_assert_held(&cgroup_mutex);
2166 
2167 	ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
2168 			      0, GFP_KERNEL);
2169 	if (ret)
2170 		goto out;
2171 
2172 	/*
2173 	 * We're accessing css_set_count without locking css_set_lock here,
2174 	 * but that's OK - it can only be increased by someone holding
2175 	 * cgroup_lock, and that's us.  Later rebinding may disable
2176 	 * controllers on the default hierarchy and thus create new csets,
2177 	 * which can't be more than the existing ones.  Allocate 2x.
2178 	 */
2179 	ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
2180 	if (ret)
2181 		goto cancel_ref;
2182 
2183 	ret = cgroup_init_root_id(root);
2184 	if (ret)
2185 		goto cancel_ref;
2186 
2187 	kf_sops = root == &cgrp_dfl_root ?
2188 		&cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
2189 
2190 	root->kf_root = kernfs_create_root(kf_sops,
2191 					   KERNFS_ROOT_CREATE_DEACTIVATED |
2192 					   KERNFS_ROOT_SUPPORT_EXPORTOP |
2193 					   KERNFS_ROOT_SUPPORT_USER_XATTR |
2194 					   KERNFS_ROOT_INVARIANT_PARENT,
2195 					   root_cgrp);
2196 	if (IS_ERR(root->kf_root)) {
2197 		ret = PTR_ERR(root->kf_root);
2198 		goto exit_root_id;
2199 	}
2200 	root_cgrp->kn = kernfs_root_to_node(root->kf_root);
2201 	WARN_ON_ONCE(cgroup_ino(root_cgrp) != 1);
2202 	root_cgrp->ancestors[0] = root_cgrp;
2203 
2204 	ret = css_populate_dir(&root_cgrp->self);
2205 	if (ret)
2206 		goto destroy_root;
2207 
2208 	ret = css_rstat_init(&root_cgrp->self);
2209 	if (ret)
2210 		goto destroy_root;
2211 
2212 	ret = rebind_subsystems(root, ss_mask);
2213 	if (ret)
2214 		goto exit_stats;
2215 
2216 	ret = blocking_notifier_call_chain(&cgroup_lifetime_notifier,
2217 					   CGROUP_LIFETIME_ONLINE, root_cgrp);
2218 	WARN_ON_ONCE(notifier_to_errno(ret));
2219 
2220 	trace_cgroup_setup_root(root);
2221 
2222 	/*
2223 	 * There must be no failure case after here, since rebinding takes
2224 	 * care of subsystems' refcounts, which are explicitly dropped in
2225 	 * the failure exit path.
2226 	 */
2227 	list_add_rcu(&root->root_list, &cgroup_roots);
2228 	cgroup_root_count++;
2229 
2230 	/*
2231 	 * Link the root cgroup in this hierarchy into all the css_set
2232 	 * objects.
2233 	 */
2234 	spin_lock_irq(&css_set_lock);
2235 	hash_for_each(css_set_table, i, cset, hlist) {
2236 		link_css_set(&tmp_links, cset, root_cgrp);
2237 		if (css_set_populated(cset))
2238 			css_update_populated(&root_cgrp->self, true);
2239 	}
2240 	spin_unlock_irq(&css_set_lock);
2241 
2242 	BUG_ON(!list_empty(&root_cgrp->self.children));
2243 	BUG_ON(atomic_read(&root->nr_cgrps) != 1);
2244 
2245 	ret = 0;
2246 	goto out;
2247 
2248 exit_stats:
2249 	css_rstat_exit(&root_cgrp->self);
2250 destroy_root:
2251 	kernfs_destroy_root(root->kf_root);
2252 	root->kf_root = NULL;
2253 exit_root_id:
2254 	cgroup_exit_root_id(root);
2255 cancel_ref:
2256 	percpu_ref_exit(&root_cgrp->self.refcnt);
2257 out:
2258 	free_cgrp_cset_links(&tmp_links);
2259 	return ret;
2260 }
2261 
2262 int cgroup_do_get_tree(struct fs_context *fc)
2263 {
2264 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2265 	int ret;
2266 
2267 	ctx->kfc.root = ctx->root->kf_root;
2268 	if (fc->fs_type == &cgroup2_fs_type)
2269 		ctx->kfc.magic = CGROUP2_SUPER_MAGIC;
2270 	else
2271 		ctx->kfc.magic = CGROUP_SUPER_MAGIC;
2272 	ret = kernfs_get_tree(fc);
2273 
2274 	/*
2275 	 * In non-init cgroup namespace, instead of root cgroup's dentry,
2276 	 * we return the dentry corresponding to the cgroupns->root_cgrp.
2277 	 */
2278 	if (!ret && ctx->ns != &init_cgroup_ns) {
2279 		struct dentry *nsdentry;
2280 		struct super_block *sb = fc->root->d_sb;
2281 		struct cgroup *cgrp;
2282 
2283 		cgroup_lock();
2284 		spin_lock_irq(&css_set_lock);
2285 
2286 		cgrp = cset_cgroup_from_root(ctx->ns->root_cset, ctx->root);
2287 
2288 		spin_unlock_irq(&css_set_lock);
2289 		cgroup_unlock();
2290 
2291 		nsdentry = kernfs_node_dentry(cgrp->kn, sb);
2292 		dput(fc->root);
2293 		if (IS_ERR(nsdentry)) {
2294 			deactivate_locked_super(sb);
2295 			ret = PTR_ERR(nsdentry);
2296 			nsdentry = NULL;
2297 		}
2298 		fc->root = nsdentry;
2299 	}
2300 
2301 	if (!ctx->kfc.new_sb_created)
2302 		cgroup_put(&ctx->root->cgrp);
2303 
2304 	return ret;
2305 }
2306 
2307 /*
2308  * Destroy a cgroup filesystem context.
2309  */
2310 static void cgroup_fs_context_free(struct fs_context *fc)
2311 {
2312 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2313 
2314 	kfree(ctx->name);
2315 	kfree(ctx->release_agent);
2316 	put_cgroup_ns(ctx->ns);
2317 	kernfs_free_fs_context(fc);
2318 	kfree(ctx);
2319 }
2320 
2321 static int cgroup_get_tree(struct fs_context *fc)
2322 {
2323 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2324 	int ret;
2325 
2326 	WRITE_ONCE(cgrp_dfl_visible, true);
2327 	cgroup_get_live(&cgrp_dfl_root.cgrp);
2328 	ctx->root = &cgrp_dfl_root;
2329 
2330 	ret = cgroup_do_get_tree(fc);
2331 	if (!ret)
2332 		apply_cgroup_root_flags(ctx->flags);
2333 	return ret;
2334 }
2335 
2336 static const struct fs_context_operations cgroup_fs_context_ops = {
2337 	.free		= cgroup_fs_context_free,
2338 	.parse_param	= cgroup2_parse_param,
2339 	.get_tree	= cgroup_get_tree,
2340 	.reconfigure	= cgroup_reconfigure,
2341 };
2342 
2343 static const struct fs_context_operations cgroup1_fs_context_ops = {
2344 	.free		= cgroup_fs_context_free,
2345 	.parse_param	= cgroup1_parse_param,
2346 	.get_tree	= cgroup1_get_tree,
2347 	.reconfigure	= cgroup1_reconfigure,
2348 };
2349 
2350 /*
2351  * Initialise the cgroup filesystem creation/reconfiguration context.  Notably,
2352  * we select the namespace we're going to use.
2353  */
2354 static int cgroup_init_fs_context(struct fs_context *fc)
2355 {
2356 	struct cgroup_fs_context *ctx;
2357 
2358 	ctx = kzalloc_obj(struct cgroup_fs_context);
2359 	if (!ctx)
2360 		return -ENOMEM;
2361 
2362 	ctx->ns = current->nsproxy->cgroup_ns;
2363 	get_cgroup_ns(ctx->ns);
2364 	fc->fs_private = &ctx->kfc;
2365 	if (fc->fs_type == &cgroup2_fs_type)
2366 		fc->ops = &cgroup_fs_context_ops;
2367 	else
2368 		fc->ops = &cgroup1_fs_context_ops;
2369 	put_user_ns(fc->user_ns);
2370 	fc->user_ns = get_user_ns(ctx->ns->user_ns);
2371 	fc->global = true;
2372 
2373 	if (have_favordynmods)
2374 		ctx->flags |= CGRP_ROOT_FAVOR_DYNMODS;
2375 
2376 	return 0;
2377 }
2378 
2379 static void cgroup_kill_sb(struct super_block *sb)
2380 {
2381 	struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2382 	struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2383 
2384 	/*
2385 	 * If @root doesn't have any children, start killing it.
2386 	 * This prevents new mounts by disabling percpu_ref_tryget_live().
2387 	 *
2388 	 * And don't kill the default root.
2389 	 */
2390 	if (list_empty(&root->cgrp.self.children) && root != &cgrp_dfl_root &&
2391 	    !percpu_ref_is_dying(&root->cgrp.self.refcnt))
2392 		percpu_ref_kill(&root->cgrp.self.refcnt);
2393 	cgroup_put(&root->cgrp);
2394 	kernfs_kill_sb(sb);
2395 }
2396 
2397 struct file_system_type cgroup_fs_type = {
2398 	.name			= "cgroup",
2399 	.init_fs_context	= cgroup_init_fs_context,
2400 	.parameters		= cgroup1_fs_parameters,
2401 	.kill_sb		= cgroup_kill_sb,
2402 	.fs_flags		= FS_USERNS_MOUNT,
2403 };
2404 
2405 static struct file_system_type cgroup2_fs_type = {
2406 	.name			= "cgroup2",
2407 	.init_fs_context	= cgroup_init_fs_context,
2408 	.parameters		= cgroup2_fs_parameters,
2409 	.kill_sb		= cgroup_kill_sb,
2410 	.fs_flags		= FS_USERNS_MOUNT,
2411 };
2412 
2413 #ifdef CONFIG_CPUSETS_V1
2414 enum cpuset_param {
2415 	Opt_cpuset_v2_mode,
2416 };
2417 
2418 static const struct fs_parameter_spec cpuset_fs_parameters[] = {
2419 	fsparam_flag  ("cpuset_v2_mode", Opt_cpuset_v2_mode),
2420 	{}
2421 };
2422 
2423 static int cpuset_parse_param(struct fs_context *fc, struct fs_parameter *param)
2424 {
2425 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2426 	struct fs_parse_result result;
2427 	int opt;
2428 
2429 	opt = fs_parse(fc, cpuset_fs_parameters, param, &result);
2430 	if (opt < 0)
2431 		return opt;
2432 
2433 	switch (opt) {
2434 	case Opt_cpuset_v2_mode:
2435 		ctx->flags |= CGRP_ROOT_CPUSET_V2_MODE;
2436 		return 0;
2437 	}
2438 	return -EINVAL;
2439 }
2440 
2441 static const struct fs_context_operations cpuset_fs_context_ops = {
2442 	.get_tree	= cgroup1_get_tree,
2443 	.free		= cgroup_fs_context_free,
2444 	.parse_param	= cpuset_parse_param,
2445 };
2446 
2447 /*
2448  * This is ugly, but preserves the userspace API for existing cpuset
2449  * users. If someone tries to mount the "cpuset" filesystem, we
2450  * silently switch it to mount "cgroup" instead
2451  */
2452 static int cpuset_init_fs_context(struct fs_context *fc)
2453 {
2454 	char *agent = kstrdup("/sbin/cpuset_release_agent", GFP_USER);
2455 	struct cgroup_fs_context *ctx;
2456 	int err;
2457 
2458 	err = cgroup_init_fs_context(fc);
2459 	if (err) {
2460 		kfree(agent);
2461 		return err;
2462 	}
2463 
2464 	fc->ops = &cpuset_fs_context_ops;
2465 
2466 	ctx = cgroup_fc2context(fc);
2467 	ctx->subsys_mask = 1 << cpuset_cgrp_id;
2468 	ctx->flags |= CGRP_ROOT_NOPREFIX;
2469 	ctx->release_agent = agent;
2470 
2471 	get_filesystem(&cgroup_fs_type);
2472 	put_filesystem(fc->fs_type);
2473 	fc->fs_type = &cgroup_fs_type;
2474 
2475 	return 0;
2476 }
2477 
2478 static struct file_system_type cpuset_fs_type = {
2479 	.name			= "cpuset",
2480 	.init_fs_context	= cpuset_init_fs_context,
2481 	.parameters		= cpuset_fs_parameters,
2482 	.fs_flags		= FS_USERNS_MOUNT,
2483 };
2484 #endif
2485 
2486 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2487 			  struct cgroup_namespace *ns)
2488 {
2489 	struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2490 
2491 	return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2492 }
2493 
2494 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2495 		   struct cgroup_namespace *ns)
2496 {
2497 	int ret;
2498 
2499 	cgroup_lock();
2500 	spin_lock_irq(&css_set_lock);
2501 
2502 	ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2503 
2504 	spin_unlock_irq(&css_set_lock);
2505 	cgroup_unlock();
2506 
2507 	return ret;
2508 }
2509 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2510 
2511 /**
2512  * cgroup_attach_lock - Lock for ->attach()
2513  * @lock_mode: whether acquire and acquire which rwsem
2514  * @tsk: thread group to lock
2515  *
2516  * cgroup migration sometimes needs to stabilize threadgroups against forks and
2517  * exits by write-locking cgroup_threadgroup_rwsem. However, some ->attach()
2518  * implementations (e.g. cpuset), also need to disable CPU hotplug.
2519  * Unfortunately, letting ->attach() operations acquire cpus_read_lock() can
2520  * lead to deadlocks.
2521  *
2522  * Bringing up a CPU may involve creating and destroying tasks which requires
2523  * read-locking threadgroup_rwsem, so threadgroup_rwsem nests inside
2524  * cpus_read_lock(). If we call an ->attach() which acquires the cpus lock while
2525  * write-locking threadgroup_rwsem, the locking order is reversed and we end up
2526  * waiting for an on-going CPU hotplug operation which in turn is waiting for
2527  * the threadgroup_rwsem to be released to create new tasks. For more details:
2528  *
2529  *   http://lkml.kernel.org/r/20220711174629.uehfmqegcwn2lqzu@wubuntu
2530  *
2531  * Resolve the situation by always acquiring cpus_read_lock() before optionally
2532  * write-locking cgroup_threadgroup_rwsem. This allows ->attach() to assume that
2533  * CPU hotplug is disabled on entry.
2534  *
2535  * When favordynmods is enabled, take per threadgroup rwsem to reduce overhead
2536  * on dynamic cgroup modifications. see the comment above
2537  * CGRP_ROOT_FAVOR_DYNMODS definition.
2538  *
2539  * tsk is not NULL only when writing to cgroup.procs.
2540  */
2541 void cgroup_attach_lock(enum cgroup_attach_lock_mode lock_mode,
2542 			struct task_struct *tsk)
2543 {
2544 	cpus_read_lock();
2545 
2546 	switch (lock_mode) {
2547 	case CGRP_ATTACH_LOCK_NONE:
2548 		break;
2549 	case CGRP_ATTACH_LOCK_GLOBAL:
2550 		percpu_down_write(&cgroup_threadgroup_rwsem);
2551 		break;
2552 	case CGRP_ATTACH_LOCK_PER_THREADGROUP:
2553 		down_write(&tsk->signal->cgroup_threadgroup_rwsem);
2554 		break;
2555 	default:
2556 		pr_warn("cgroup: Unexpected attach lock mode.");
2557 		break;
2558 	}
2559 }
2560 
2561 /**
2562  * cgroup_attach_unlock - Undo cgroup_attach_lock()
2563  * @lock_mode: whether release and release which rwsem
2564  * @tsk: thread group to lock
2565  */
2566 void cgroup_attach_unlock(enum cgroup_attach_lock_mode lock_mode,
2567 			  struct task_struct *tsk)
2568 {
2569 	switch (lock_mode) {
2570 	case CGRP_ATTACH_LOCK_NONE:
2571 		break;
2572 	case CGRP_ATTACH_LOCK_GLOBAL:
2573 		percpu_up_write(&cgroup_threadgroup_rwsem);
2574 		break;
2575 	case CGRP_ATTACH_LOCK_PER_THREADGROUP:
2576 		up_write(&tsk->signal->cgroup_threadgroup_rwsem);
2577 		break;
2578 	default:
2579 		pr_warn("cgroup: Unexpected attach lock mode.");
2580 		break;
2581 	}
2582 
2583 	cpus_read_unlock();
2584 }
2585 
2586 /**
2587  * cgroup_migrate_add_task - add a migration target task to a migration context
2588  * @task: target task
2589  * @mgctx: target migration context
2590  *
2591  * Add @task, which is a migration target, to @mgctx->tset.  This function
2592  * becomes noop if @task doesn't need to be migrated.  @task's css_set
2593  * should have been added as a migration source and @task->cg_list will be
2594  * moved from the css_set's tasks list to mg_tasks one.
2595  */
2596 static void cgroup_migrate_add_task(struct task_struct *task,
2597 				    struct cgroup_mgctx *mgctx)
2598 {
2599 	struct css_set *cset;
2600 
2601 	lockdep_assert_held(&css_set_lock);
2602 
2603 	/* @task either already exited or can't exit until the end */
2604 	if (task->flags & PF_EXITING)
2605 		return;
2606 
2607 	/* cgroup_threadgroup_rwsem protects racing against forks */
2608 	WARN_ON_ONCE(list_empty(&task->cg_list));
2609 
2610 	cset = task_css_set(task);
2611 	if (!cset->mg_src_cgrp)
2612 		return;
2613 
2614 	mgctx->tset.nr_tasks++;
2615 
2616 	css_set_skip_task_iters(cset, task);
2617 	list_move_tail(&task->cg_list, &cset->mg_tasks);
2618 	if (list_empty(&cset->mg_node))
2619 		list_add_tail(&cset->mg_node,
2620 			      &mgctx->tset.src_csets);
2621 	if (list_empty(&cset->mg_dst_cset->mg_node))
2622 		list_add_tail(&cset->mg_dst_cset->mg_node,
2623 			      &mgctx->tset.dst_csets);
2624 }
2625 
2626 /**
2627  * cgroup_taskset_first - reset taskset and return the first task
2628  * @tset: taskset of interest
2629  * @dst_cssp: output variable for the destination css
2630  *
2631  * @tset iteration is initialized and the first task is returned.
2632  */
2633 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2634 					 struct cgroup_subsys_state **dst_cssp)
2635 {
2636 	tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2637 	tset->cur_task = NULL;
2638 
2639 	return cgroup_taskset_next(tset, dst_cssp);
2640 }
2641 
2642 /**
2643  * cgroup_taskset_next - iterate to the next task in taskset
2644  * @tset: taskset of interest
2645  * @dst_cssp: output variable for the destination css
2646  *
2647  * Return the next task in @tset.  Iteration must have been initialized
2648  * with cgroup_taskset_first().
2649  */
2650 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2651 					struct cgroup_subsys_state **dst_cssp)
2652 {
2653 	struct css_set *cset = tset->cur_cset;
2654 	struct task_struct *task = tset->cur_task;
2655 
2656 	while (CGROUP_HAS_SUBSYS_CONFIG && &cset->mg_node != tset->csets) {
2657 		if (!task)
2658 			task = list_first_entry(&cset->mg_tasks,
2659 						struct task_struct, cg_list);
2660 		else
2661 			task = list_next_entry(task, cg_list);
2662 
2663 		if (&task->cg_list != &cset->mg_tasks) {
2664 			tset->cur_cset = cset;
2665 			tset->cur_task = task;
2666 
2667 			/*
2668 			 * This function may be called both before and
2669 			 * after cgroup_migrate_execute().  The two cases
2670 			 * can be distinguished by looking at whether @cset
2671 			 * has its ->mg_dst_cset set.
2672 			 */
2673 			if (cset->mg_dst_cset)
2674 				*dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2675 			else
2676 				*dst_cssp = cset->subsys[tset->ssid];
2677 
2678 			return task;
2679 		}
2680 
2681 		cset = list_next_entry(cset, mg_node);
2682 		task = NULL;
2683 	}
2684 
2685 	return NULL;
2686 }
2687 
2688 static void cgroup_migrate_notify_canceled(struct css_set *src_cset,
2689 					   struct task_struct *task)
2690 {
2691 	struct cgroup_task_migrate_ctx ctx = {
2692 		.task = task,
2693 		.src_dcgrp = src_cset->dfl_cgrp,
2694 		.dst_dcgrp = src_cset->mg_dst_cset->dfl_cgrp,
2695 	};
2696 
2697 	blocking_notifier_call_chain(&cgroup_task_notifier,
2698 				     CGROUP_TASK_MIGRATE_CANCELED, &ctx);
2699 }
2700 
2701 /**
2702  * cgroup_migrate_execute - migrate a taskset
2703  * @mgctx: migration context
2704  *
2705  * Migrate tasks in @mgctx as setup by migration preparation functions. This
2706  * function fails iff one of the ->can_attach callbacks or CGROUP_TASK_MIGRATING
2707  * notifications fails and guarantees that either all or none of the tasks in
2708  * @mgctx are migrated. @mgctx is consumed regardless of success.
2709  */
2710 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2711 {
2712 	struct cgroup_taskset *tset = &mgctx->tset;
2713 	struct cgroup_subsys *ss;
2714 	struct task_struct *task, *tmp_task;
2715 	struct css_set *cset, *tmp_cset;
2716 	bool dfl_migration = false;
2717 	int ssid, failed_ssid, ret;
2718 
2719 	/* check that we can legitimately attach to the cgroup */
2720 	if (tset->nr_tasks) {
2721 		do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2722 			if (ss->can_attach) {
2723 				tset->ssid = ssid;
2724 				ret = ss->can_attach(tset);
2725 				if (ret) {
2726 					failed_ssid = ssid;
2727 					goto out_cancel_attach;
2728 				}
2729 			}
2730 		} while_each_subsys_mask();
2731 	}
2732 
2733 	/*
2734 	 * Notify each task about the impending migration. An error return fails
2735 	 * the migration. Only migrations on the default hierarchy are reported:
2736 	 * a migration modifies either every moved task's dfl cgroup or, on
2737 	 * cgroup1 or for subtree_control writes, none.
2738 	 */
2739 	list_for_each_entry(cset, &tset->src_csets, mg_node) {
2740 		if (cset->dfl_cgrp == cset->mg_dst_cset->dfl_cgrp)
2741 			continue;
2742 		dfl_migration = true;
2743 		list_for_each_entry(task, &cset->mg_tasks, cg_list) {
2744 			struct cgroup_task_migrate_ctx ctx = {
2745 				.task = task,
2746 				.src_dcgrp = cset->dfl_cgrp,
2747 				.dst_dcgrp = cset->mg_dst_cset->dfl_cgrp,
2748 			};
2749 
2750 			ret = blocking_notifier_call_chain_robust(&cgroup_task_notifier,
2751 								  CGROUP_TASK_MIGRATING,
2752 								  CGROUP_TASK_MIGRATE_CANCELED,
2753 								  &ctx);
2754 			ret = notifier_to_errno(ret);
2755 			if (ret)
2756 				goto out_cancel_migrating;
2757 		}
2758 	}
2759 
2760 	/*
2761 	 * Now that we're guaranteed success, proceed to move all tasks to
2762 	 * the new cgroup.  There are no failure cases after here, so this
2763 	 * is the commit point.
2764 	 */
2765 	spin_lock_irq(&css_set_lock);
2766 	list_for_each_entry(cset, &tset->src_csets, mg_node) {
2767 		list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2768 			struct css_set *from_cset = task_css_set(task);
2769 			struct css_set *to_cset = cset->mg_dst_cset;
2770 
2771 			get_css_set(to_cset);
2772 			to_cset->nr_tasks++;
2773 			css_set_move_task(task, from_cset, to_cset, true);
2774 			from_cset->nr_tasks--;
2775 			/*
2776 			 * If the source or destination cgroup is frozen,
2777 			 * the task might require to change its state.
2778 			 */
2779 			cgroup_freezer_migrate_task(task, from_cset->dfl_cgrp,
2780 						    to_cset->dfl_cgrp);
2781 			put_css_set_locked(from_cset);
2782 
2783 		}
2784 	}
2785 	spin_unlock_irq(&css_set_lock);
2786 
2787 	/*
2788 	 * Migration is committed, all target tasks are now on dst_csets.
2789 	 * Nothing is sensitive to fork() after this point.  Notify
2790 	 * controllers that migration is complete.
2791 	 */
2792 	tset->csets = &tset->dst_csets;
2793 
2794 	if (tset->nr_tasks) {
2795 		do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2796 			if (ss->attach) {
2797 				tset->ssid = ssid;
2798 				ss->attach(tset);
2799 			}
2800 		} while_each_subsys_mask();
2801 	}
2802 
2803 	/*
2804 	 * Notify each task after successful migration. The operation can no
2805 	 * longer fail and the return value is ignored. The MIGRATING loop
2806 	 * above explains why only dfl migrations are reported. Per-task
2807 	 * sources are not tracked past the commit point, so src_dcgrp is
2808 	 * NULL.
2809 	 */
2810 	if (dfl_migration) {
2811 		list_for_each_entry(cset, &tset->dst_csets, mg_node) {
2812 			list_for_each_entry(task, &cset->mg_tasks, cg_list) {
2813 				struct cgroup_task_migrate_ctx ctx = {
2814 					.task = task,
2815 					.dst_dcgrp = cset->dfl_cgrp,
2816 				};
2817 
2818 				blocking_notifier_call_chain(
2819 					&cgroup_task_notifier,
2820 					CGROUP_TASK_MIGRATED, &ctx);
2821 			}
2822 		}
2823 	}
2824 
2825 	ret = 0;
2826 	goto out_release_tset;
2827 
2828 out_cancel_migrating:
2829 	list_for_each_entry_continue_reverse(task, &cset->mg_tasks, cg_list)
2830 		cgroup_migrate_notify_canceled(cset, task);
2831 	list_for_each_entry_continue_reverse(cset, &tset->src_csets, mg_node) {
2832 		if (cset->dfl_cgrp == cset->mg_dst_cset->dfl_cgrp)
2833 			continue;
2834 		list_for_each_entry_reverse(task, &cset->mg_tasks, cg_list)
2835 			cgroup_migrate_notify_canceled(cset, task);
2836 	}
2837 	failed_ssid = CGROUP_SUBSYS_COUNT;
2838 out_cancel_attach:
2839 	if (tset->nr_tasks) {
2840 		do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2841 			if (ssid == failed_ssid)
2842 				break;
2843 			if (ss->cancel_attach) {
2844 				tset->ssid = ssid;
2845 				ss->cancel_attach(tset);
2846 			}
2847 		} while_each_subsys_mask();
2848 	}
2849 out_release_tset:
2850 	spin_lock_irq(&css_set_lock);
2851 	list_splice_init(&tset->dst_csets, &tset->src_csets);
2852 	list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2853 		list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2854 		list_del_init(&cset->mg_node);
2855 	}
2856 	spin_unlock_irq(&css_set_lock);
2857 
2858 	/*
2859 	 * Re-initialize the cgroup_taskset structure in case it is reused
2860 	 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2861 	 * iteration.
2862 	 */
2863 	tset->nr_tasks = 0;
2864 	tset->csets    = &tset->src_csets;
2865 	return ret;
2866 }
2867 
2868 /**
2869  * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2870  * @dst_cgrp: destination cgroup to test
2871  *
2872  * On the default hierarchy, except for the mixable, (possible) thread root
2873  * and threaded cgroups, subtree_control must be zero for migration
2874  * destination cgroups with tasks so that child cgroups don't compete
2875  * against tasks.
2876  */
2877 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2878 {
2879 	/* v1 doesn't have any restriction */
2880 	if (!cgroup_on_dfl(dst_cgrp))
2881 		return 0;
2882 
2883 	/* verify @dst_cgrp can host resources */
2884 	if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2885 		return -EOPNOTSUPP;
2886 
2887 	/*
2888 	 * If @dst_cgrp is already or can become a thread root or is
2889 	 * threaded, it doesn't matter.
2890 	 */
2891 	if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2892 		return 0;
2893 
2894 	/* apply no-internal-process constraint */
2895 	if (dst_cgrp->subtree_control)
2896 		return -EBUSY;
2897 
2898 	return 0;
2899 }
2900 
2901 /**
2902  * cgroup_migrate_finish - cleanup after attach
2903  * @mgctx: migration context
2904  *
2905  * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst().  See
2906  * those functions for details.
2907  */
2908 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2909 {
2910 	struct css_set *cset, *tmp_cset;
2911 
2912 	lockdep_assert_held(&cgroup_mutex);
2913 
2914 	spin_lock_irq(&css_set_lock);
2915 
2916 	list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_src_csets,
2917 				 mg_src_preload_node) {
2918 		cset->mg_src_cgrp = NULL;
2919 		cset->mg_dst_cgrp = NULL;
2920 		cset->mg_dst_cset = NULL;
2921 		list_del_init(&cset->mg_src_preload_node);
2922 		put_css_set_locked(cset);
2923 	}
2924 
2925 	list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_dst_csets,
2926 				 mg_dst_preload_node) {
2927 		cset->mg_src_cgrp = NULL;
2928 		cset->mg_dst_cgrp = NULL;
2929 		cset->mg_dst_cset = NULL;
2930 		list_del_init(&cset->mg_dst_preload_node);
2931 		put_css_set_locked(cset);
2932 	}
2933 
2934 	spin_unlock_irq(&css_set_lock);
2935 }
2936 
2937 /**
2938  * cgroup_migrate_add_src - add a migration source css_set
2939  * @src_cset: the source css_set to add
2940  * @dst_cgrp: the destination cgroup
2941  * @mgctx: migration context
2942  *
2943  * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp.  Pin
2944  * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2945  * up by cgroup_migrate_finish().
2946  *
2947  * This function may be called without holding cgroup_threadgroup_rwsem
2948  * even if the target is a process.  Threads may be created and destroyed
2949  * but as long as cgroup_mutex is not dropped, no new css_set can be put
2950  * into play and the preloaded css_sets are guaranteed to cover all
2951  * migrations.
2952  */
2953 void cgroup_migrate_add_src(struct css_set *src_cset,
2954 			    struct cgroup *dst_cgrp,
2955 			    struct cgroup_mgctx *mgctx)
2956 {
2957 	struct cgroup *src_cgrp;
2958 
2959 	lockdep_assert_held(&cgroup_mutex);
2960 	lockdep_assert_held(&css_set_lock);
2961 
2962 	/*
2963 	 * If ->dead, @src_set is associated with one or more dead cgroups
2964 	 * and doesn't contain any migratable tasks.  Ignore it early so
2965 	 * that the rest of migration path doesn't get confused by it.
2966 	 */
2967 	if (src_cset->dead)
2968 		return;
2969 
2970 	if (!list_empty(&src_cset->mg_src_preload_node))
2971 		return;
2972 
2973 	src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2974 
2975 	WARN_ON(src_cset->mg_src_cgrp);
2976 	WARN_ON(src_cset->mg_dst_cgrp);
2977 	WARN_ON(!list_empty(&src_cset->mg_tasks));
2978 	WARN_ON(!list_empty(&src_cset->mg_node));
2979 
2980 	src_cset->mg_src_cgrp = src_cgrp;
2981 	src_cset->mg_dst_cgrp = dst_cgrp;
2982 	get_css_set(src_cset);
2983 	list_add_tail(&src_cset->mg_src_preload_node, &mgctx->preloaded_src_csets);
2984 }
2985 
2986 /**
2987  * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2988  * @mgctx: migration context
2989  *
2990  * Tasks are about to be moved and all the source css_sets have been
2991  * preloaded to @mgctx->preloaded_src_csets.  This function looks up and
2992  * pins all destination css_sets, links each to its source, and append them
2993  * to @mgctx->preloaded_dst_csets.
2994  *
2995  * This function must be called after cgroup_migrate_add_src() has been
2996  * called on each migration source css_set.  After migration is performed
2997  * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2998  * @mgctx.
2999  */
3000 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
3001 {
3002 	struct css_set *src_cset, *tmp_cset;
3003 
3004 	lockdep_assert_held(&cgroup_mutex);
3005 
3006 	/* look up the dst cset for each src cset and link it to src */
3007 	list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
3008 				 mg_src_preload_node) {
3009 		struct css_set *dst_cset;
3010 		struct cgroup_subsys *ss;
3011 		int ssid;
3012 
3013 		dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
3014 		if (!dst_cset)
3015 			return -ENOMEM;
3016 
3017 		WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
3018 
3019 		/*
3020 		 * If src cset equals dst, it's noop.  Drop the src.
3021 		 * cgroup_migrate() will skip the cset too.  Note that we
3022 		 * can't handle src == dst as some nodes are used by both.
3023 		 */
3024 		if (src_cset == dst_cset) {
3025 			src_cset->mg_src_cgrp = NULL;
3026 			src_cset->mg_dst_cgrp = NULL;
3027 			list_del_init(&src_cset->mg_src_preload_node);
3028 			put_css_set(src_cset);
3029 			put_css_set(dst_cset);
3030 			continue;
3031 		}
3032 
3033 		src_cset->mg_dst_cset = dst_cset;
3034 
3035 		if (list_empty(&dst_cset->mg_dst_preload_node))
3036 			list_add_tail(&dst_cset->mg_dst_preload_node,
3037 				      &mgctx->preloaded_dst_csets);
3038 		else
3039 			put_css_set(dst_cset);
3040 
3041 		for_each_subsys(ss, ssid)
3042 			if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
3043 				mgctx->ss_mask |= 1 << ssid;
3044 	}
3045 
3046 	return 0;
3047 }
3048 
3049 /**
3050  * cgroup_migrate - migrate a process or task to a cgroup
3051  * @leader: the leader of the process or the task to migrate
3052  * @threadgroup: whether @leader points to the whole process or a single task
3053  * @mgctx: migration context
3054  *
3055  * Migrate a process or task denoted by @leader.  If migrating a process,
3056  * the caller must be holding cgroup_threadgroup_rwsem.  The caller is also
3057  * responsible for invoking cgroup_migrate_add_src() and
3058  * cgroup_migrate_prepare_dst() on the targets before invoking this
3059  * function and following up with cgroup_migrate_finish().
3060  *
3061  * As long as a controller's ->can_attach() or a CGROUP_TASK_MIGRATING
3062  * notification doesn't fail, this function is guaranteed to succeed.  This
3063  * means that, excluding those failures, when migrating multiple targets,
3064  * the success or failure can be decided for all targets by invoking
3065  * group_migrate_prepare_dst() before actually starting migrating.
3066  */
3067 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
3068 		   struct cgroup_mgctx *mgctx)
3069 {
3070 	struct task_struct *task;
3071 
3072 	/*
3073 	 * The following thread iteration should be inside an RCU critical
3074 	 * section to prevent tasks from being freed while taking the snapshot.
3075 	 * spin_lock_irq() implies RCU critical section here.
3076 	 */
3077 	spin_lock_irq(&css_set_lock);
3078 	task = leader;
3079 	do {
3080 		cgroup_migrate_add_task(task, mgctx);
3081 		if (!threadgroup)
3082 			break;
3083 	} while_each_thread(leader, task);
3084 	spin_unlock_irq(&css_set_lock);
3085 
3086 	return cgroup_migrate_execute(mgctx);
3087 }
3088 
3089 /**
3090  * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
3091  * @dst_cgrp: the cgroup to attach to
3092  * @leader: the task or the leader of the threadgroup to be attached
3093  * @threadgroup: attach the whole threadgroup?
3094  *
3095  * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
3096  */
3097 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
3098 		       bool threadgroup)
3099 {
3100 	DEFINE_CGROUP_MGCTX(mgctx);
3101 	struct task_struct *task;
3102 	int ret = 0;
3103 
3104 	/* look up all src csets */
3105 	spin_lock_irq(&css_set_lock);
3106 	task = leader;
3107 	do {
3108 		cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
3109 		if (!threadgroup)
3110 			break;
3111 	} while_each_thread(leader, task);
3112 	spin_unlock_irq(&css_set_lock);
3113 
3114 	/* prepare dst csets and commit */
3115 	ret = cgroup_migrate_prepare_dst(&mgctx);
3116 	if (!ret)
3117 		ret = cgroup_migrate(leader, threadgroup, &mgctx);
3118 
3119 	cgroup_migrate_finish(&mgctx);
3120 
3121 	if (!ret)
3122 		TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
3123 
3124 	return ret;
3125 }
3126 
3127 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup,
3128 					     enum cgroup_attach_lock_mode *lock_mode)
3129 {
3130 	struct task_struct *tsk;
3131 	pid_t pid;
3132 
3133 	if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
3134 		return ERR_PTR(-EINVAL);
3135 
3136 retry_find_task:
3137 	rcu_read_lock();
3138 	if (pid) {
3139 		tsk = find_task_by_vpid(pid);
3140 		if (!tsk) {
3141 			tsk = ERR_PTR(-ESRCH);
3142 			goto out_unlock_rcu;
3143 		}
3144 	} else {
3145 		tsk = current;
3146 	}
3147 
3148 	if (threadgroup)
3149 		tsk = tsk->group_leader;
3150 
3151 	/*
3152 	 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
3153 	 * If userland migrates such a kthread to a non-root cgroup, it can
3154 	 * become trapped in a cpuset, or RT kthread may be born in a
3155 	 * cgroup with no rt_runtime allocated.  Just say no.
3156 	 */
3157 	if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
3158 		tsk = ERR_PTR(-EINVAL);
3159 		goto out_unlock_rcu;
3160 	}
3161 	get_task_struct(tsk);
3162 	rcu_read_unlock();
3163 
3164 	/*
3165 	 * If we migrate a single thread, we don't care about threadgroup
3166 	 * stability. If the thread is `current`, it won't exit(2) under our
3167 	 * hands or change PID through exec(2). We exclude
3168 	 * cgroup_update_dfl_csses and other cgroup_{proc,thread}s_write callers
3169 	 * by cgroup_mutex. Therefore, we can skip the global lock.
3170 	 */
3171 	lockdep_assert_held(&cgroup_mutex);
3172 
3173 	if (pid || threadgroup) {
3174 		if (cgroup_enable_per_threadgroup_rwsem)
3175 			*lock_mode = CGRP_ATTACH_LOCK_PER_THREADGROUP;
3176 		else
3177 			*lock_mode = CGRP_ATTACH_LOCK_GLOBAL;
3178 	} else {
3179 		*lock_mode = CGRP_ATTACH_LOCK_NONE;
3180 	}
3181 
3182 	cgroup_attach_lock(*lock_mode, tsk);
3183 
3184 	if (threadgroup) {
3185 		if (!thread_group_leader(tsk)) {
3186 			/*
3187 			 * A race with de_thread from another thread's exec()
3188 			 * may strip us of our leadership. If this happens,
3189 			 * throw this task away and try again.
3190 			 */
3191 			cgroup_attach_unlock(*lock_mode, tsk);
3192 			put_task_struct(tsk);
3193 			goto retry_find_task;
3194 		}
3195 	}
3196 
3197 	return tsk;
3198 
3199 out_unlock_rcu:
3200 	rcu_read_unlock();
3201 	return tsk;
3202 }
3203 
3204 void cgroup_procs_write_finish(struct task_struct *task,
3205 			       enum cgroup_attach_lock_mode lock_mode)
3206 {
3207 	cgroup_attach_unlock(lock_mode, task);
3208 
3209 	/* release reference from cgroup_procs_write_start() */
3210 	put_task_struct(task);
3211 }
3212 
3213 static void cgroup_print_ss_mask(struct seq_file *seq, u32 ss_mask)
3214 {
3215 	struct cgroup_subsys *ss;
3216 	bool printed = false;
3217 	int ssid;
3218 
3219 	do_each_subsys_mask(ss, ssid, ss_mask) {
3220 		if (printed)
3221 			seq_putc(seq, ' ');
3222 		seq_puts(seq, ss->name);
3223 		printed = true;
3224 	} while_each_subsys_mask();
3225 	if (printed)
3226 		seq_putc(seq, '\n');
3227 }
3228 
3229 /* show controllers which are enabled from the parent */
3230 static int cgroup_controllers_show(struct seq_file *seq, void *v)
3231 {
3232 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3233 
3234 	cgroup_print_ss_mask(seq, cgroup_control(cgrp));
3235 	return 0;
3236 }
3237 
3238 /* show controllers which are enabled for a given cgroup's children */
3239 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
3240 {
3241 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3242 
3243 	cgroup_print_ss_mask(seq, cgrp->subtree_control);
3244 	return 0;
3245 }
3246 
3247 /**
3248  * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
3249  * @cgrp: root of the subtree to update csses for
3250  *
3251  * @cgrp's control masks have changed and its subtree's css associations
3252  * need to be updated accordingly.  This function looks up all css_sets
3253  * which are attached to the subtree, creates the matching updated css_sets
3254  * and migrates the tasks to the new ones.
3255  */
3256 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
3257 {
3258 	DEFINE_CGROUP_MGCTX(mgctx);
3259 	struct cgroup_subsys_state *d_css;
3260 	struct cgroup *dsct;
3261 	struct css_set *src_cset;
3262 	enum cgroup_attach_lock_mode lock_mode;
3263 	bool has_tasks;
3264 	int ret;
3265 
3266 	lockdep_assert_held(&cgroup_mutex);
3267 
3268 	/* look up all csses currently attached to @cgrp's subtree */
3269 	spin_lock_irq(&css_set_lock);
3270 	cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3271 		struct cgrp_cset_link *link;
3272 
3273 		/*
3274 		 * As cgroup_update_dfl_csses() is only called by
3275 		 * cgroup_apply_control(). The csses associated with the
3276 		 * given cgrp will not be affected by changes made to
3277 		 * its subtree_control file. We can skip them.
3278 		 */
3279 		if (dsct == cgrp)
3280 			continue;
3281 
3282 		list_for_each_entry(link, &dsct->cset_links, cset_link)
3283 			cgroup_migrate_add_src(link->cset, dsct, &mgctx);
3284 	}
3285 	spin_unlock_irq(&css_set_lock);
3286 
3287 	/*
3288 	 * We need to write-lock threadgroup_rwsem while migrating tasks.
3289 	 * However, if there are no source csets for @cgrp, changing its
3290 	 * controllers isn't gonna produce any task migrations and the
3291 	 * write-locking can be skipped safely.
3292 	 */
3293 	has_tasks = !list_empty(&mgctx.preloaded_src_csets);
3294 
3295 	if (has_tasks)
3296 		lock_mode = CGRP_ATTACH_LOCK_GLOBAL;
3297 	else
3298 		lock_mode = CGRP_ATTACH_LOCK_NONE;
3299 
3300 	cgroup_attach_lock(lock_mode, NULL);
3301 
3302 	/* NULL dst indicates self on default hierarchy */
3303 	ret = cgroup_migrate_prepare_dst(&mgctx);
3304 	if (ret)
3305 		goto out_finish;
3306 
3307 	spin_lock_irq(&css_set_lock);
3308 	list_for_each_entry(src_cset, &mgctx.preloaded_src_csets,
3309 			    mg_src_preload_node) {
3310 		struct task_struct *task, *ntask;
3311 
3312 		/* all tasks in src_csets need to be migrated */
3313 		list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
3314 			cgroup_migrate_add_task(task, &mgctx);
3315 	}
3316 	spin_unlock_irq(&css_set_lock);
3317 
3318 	ret = cgroup_migrate_execute(&mgctx);
3319 out_finish:
3320 	cgroup_migrate_finish(&mgctx);
3321 	cgroup_attach_unlock(lock_mode, NULL);
3322 	return ret;
3323 }
3324 
3325 /**
3326  * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
3327  * @cgrp: root of the target subtree
3328  *
3329  * Because css offlining is asynchronous, userland may try to re-enable a
3330  * controller while the previous css is still around. This function grabs
3331  * cgroup_mutex and waits until no css in @cgrp's subtree is dying. A dying css
3332  * offlines only after every task that still pins it has finished exiting, which
3333  * can take arbitrarily long, so the wait is interruptible.
3334  *
3335  * Returns 0 with cgroup_mutex held once the subtree is drained, or -ERESTARTSYS
3336  * without it if interrupted by a signal.
3337  */
3338 int cgroup_lock_and_drain_offline(struct cgroup *cgrp)
3339 {
3340 	struct cgroup *dsct;
3341 	struct cgroup_subsys_state *d_css;
3342 	struct cgroup_subsys *ss;
3343 	int ssid, ret;
3344 
3345 restart:
3346 	cgroup_lock();
3347 
3348 	cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3349 		for_each_subsys(ss, ssid) {
3350 			struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3351 			DEFINE_WAIT(wait);
3352 
3353 			if (!css || !css_is_dying(css))
3354 				continue;
3355 
3356 			cgroup_get_live(dsct);
3357 			ret = prepare_to_wait_event(&dsct->offline_waitq, &wait,
3358 						    TASK_INTERRUPTIBLE);
3359 			cgroup_unlock();
3360 			if (!ret)
3361 				schedule();
3362 			finish_wait(&dsct->offline_waitq, &wait);
3363 			cgroup_put(dsct);
3364 			if (unlikely(ret))
3365 				return ret;
3366 			goto restart;
3367 		}
3368 	}
3369 
3370 	return 0;
3371 }
3372 
3373 /**
3374  * cgroup_save_control - save control masks and dom_cgrp of a subtree
3375  * @cgrp: root of the target subtree
3376  *
3377  * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
3378  * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3379  * itself.
3380  */
3381 static void cgroup_save_control(struct cgroup *cgrp)
3382 {
3383 	struct cgroup *dsct;
3384 	struct cgroup_subsys_state *d_css;
3385 
3386 	cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3387 		dsct->old_subtree_control = dsct->subtree_control;
3388 		dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
3389 		dsct->old_dom_cgrp = dsct->dom_cgrp;
3390 	}
3391 }
3392 
3393 /**
3394  * cgroup_propagate_control - refresh control masks of a subtree
3395  * @cgrp: root of the target subtree
3396  *
3397  * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
3398  * ->subtree_control and propagate controller availability through the
3399  * subtree so that descendants don't have unavailable controllers enabled.
3400  */
3401 static void cgroup_propagate_control(struct cgroup *cgrp)
3402 {
3403 	struct cgroup *dsct;
3404 	struct cgroup_subsys_state *d_css;
3405 
3406 	cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3407 		dsct->subtree_control &= cgroup_control(dsct);
3408 		dsct->subtree_ss_mask =
3409 			cgroup_calc_subtree_ss_mask(dsct->subtree_control,
3410 						    cgroup_ss_mask(dsct));
3411 	}
3412 }
3413 
3414 /**
3415  * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
3416  * @cgrp: root of the target subtree
3417  *
3418  * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
3419  * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3420  * itself.
3421  */
3422 static void cgroup_restore_control(struct cgroup *cgrp)
3423 {
3424 	struct cgroup *dsct;
3425 	struct cgroup_subsys_state *d_css;
3426 
3427 	cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3428 		dsct->subtree_control = dsct->old_subtree_control;
3429 		dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
3430 		dsct->dom_cgrp = dsct->old_dom_cgrp;
3431 	}
3432 }
3433 
3434 static bool css_visible(struct cgroup_subsys_state *css)
3435 {
3436 	struct cgroup_subsys *ss = css->ss;
3437 	struct cgroup *cgrp = css->cgroup;
3438 
3439 	if (cgroup_control(cgrp) & (1 << ss->id))
3440 		return true;
3441 	if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
3442 		return false;
3443 	return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
3444 }
3445 
3446 /**
3447  * cgroup_apply_control_enable - enable or show csses according to control
3448  * @cgrp: root of the target subtree
3449  *
3450  * Walk @cgrp's subtree and create new csses or make the existing ones
3451  * visible.  A css is created invisible if it's being implicitly enabled
3452  * through dependency.  An invisible css is made visible when the userland
3453  * explicitly enables it.
3454  *
3455  * Returns 0 on success, -errno on failure.  On failure, csses which have
3456  * been processed already aren't cleaned up.  The caller is responsible for
3457  * cleaning up with cgroup_apply_control_disable().
3458  */
3459 static int cgroup_apply_control_enable(struct cgroup *cgrp)
3460 {
3461 	struct cgroup *dsct;
3462 	struct cgroup_subsys_state *d_css;
3463 	struct cgroup_subsys *ss;
3464 	int ssid, ret;
3465 
3466 	cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3467 		for_each_subsys(ss, ssid) {
3468 			struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3469 
3470 			if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
3471 				continue;
3472 
3473 			if (!css) {
3474 				css = css_create(dsct, ss);
3475 				if (IS_ERR(css))
3476 					return PTR_ERR(css);
3477 			}
3478 
3479 			WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3480 
3481 			if (css_visible(css)) {
3482 				ret = css_populate_dir(css);
3483 				if (ret)
3484 					return ret;
3485 			}
3486 		}
3487 	}
3488 
3489 	return 0;
3490 }
3491 
3492 /**
3493  * cgroup_apply_control_disable - kill or hide csses according to control
3494  * @cgrp: root of the target subtree
3495  *
3496  * Walk @cgrp's subtree and kill and hide csses so that they match
3497  * cgroup_ss_mask() and cgroup_visible_mask().
3498  *
3499  * A css is hidden when the userland requests it to be disabled while other
3500  * subsystems are still depending on it.  The css must not actively control
3501  * resources and be in the vanilla state if it's made visible again later.
3502  * Controllers which may be depended upon should provide ->css_reset() for
3503  * this purpose.
3504  */
3505 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3506 {
3507 	struct cgroup *dsct;
3508 	struct cgroup_subsys_state *d_css;
3509 	struct cgroup_subsys *ss;
3510 	int ssid;
3511 
3512 	cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3513 		for_each_subsys(ss, ssid) {
3514 			struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3515 
3516 			if (!css)
3517 				continue;
3518 
3519 			WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3520 
3521 			if (css->parent &&
3522 			    !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3523 				kill_css_sync(css);
3524 				if (!css_is_populated(css))
3525 					kill_css_finish(css);
3526 			} else if (!css_visible(css)) {
3527 				css_clear_dir(css);
3528 				if (ss->css_reset)
3529 					ss->css_reset(css);
3530 			}
3531 		}
3532 	}
3533 }
3534 
3535 /**
3536  * cgroup_apply_control - apply control mask updates to the subtree
3537  * @cgrp: root of the target subtree
3538  *
3539  * subsystems can be enabled and disabled in a subtree using the following
3540  * steps.
3541  *
3542  * 1. Call cgroup_save_control() to stash the current state.
3543  * 2. Update ->subtree_control masks in the subtree as desired.
3544  * 3. Call cgroup_apply_control() to apply the changes.
3545  * 4. Optionally perform other related operations.
3546  * 5. Call cgroup_finalize_control() to finish up.
3547  *
3548  * This function implements step 3 and propagates the mask changes
3549  * throughout @cgrp's subtree, updates csses accordingly and perform
3550  * process migrations.
3551  */
3552 static int cgroup_apply_control(struct cgroup *cgrp)
3553 {
3554 	int ret;
3555 
3556 	cgroup_propagate_control(cgrp);
3557 
3558 	ret = cgroup_apply_control_enable(cgrp);
3559 	if (ret)
3560 		return ret;
3561 
3562 	/*
3563 	 * At this point, cgroup_e_css_by_mask() results reflect the new csses
3564 	 * making the following cgroup_update_dfl_csses() properly update
3565 	 * css associations of all tasks in the subtree.
3566 	 */
3567 	return cgroup_update_dfl_csses(cgrp);
3568 }
3569 
3570 /**
3571  * cgroup_finalize_control - finalize control mask update
3572  * @cgrp: root of the target subtree
3573  * @ret: the result of the update
3574  *
3575  * Finalize control mask update.  See cgroup_apply_control() for more info.
3576  */
3577 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3578 {
3579 	if (ret) {
3580 		cgroup_restore_control(cgrp);
3581 		cgroup_propagate_control(cgrp);
3582 	}
3583 
3584 	cgroup_apply_control_disable(cgrp);
3585 }
3586 
3587 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u32 enable)
3588 {
3589 	u32 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3590 
3591 	/* if nothing is getting enabled, nothing to worry about */
3592 	if (!enable)
3593 		return 0;
3594 
3595 	/* can @cgrp host any resources? */
3596 	if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3597 		return -EOPNOTSUPP;
3598 
3599 	/* mixables don't care */
3600 	if (cgroup_is_mixable(cgrp))
3601 		return 0;
3602 
3603 	if (domain_enable) {
3604 		/* can't enable domain controllers inside a thread subtree */
3605 		if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3606 			return -EOPNOTSUPP;
3607 	} else {
3608 		/*
3609 		 * Threaded controllers can handle internal competitions
3610 		 * and are always allowed inside a (prospective) thread
3611 		 * subtree.
3612 		 */
3613 		if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3614 			return 0;
3615 	}
3616 
3617 	/*
3618 	 * Controllers can't be enabled for a cgroup with tasks to avoid
3619 	 * child cgroups competing against tasks.
3620 	 */
3621 	if (cgroup_has_tasks(cgrp))
3622 		return -EBUSY;
3623 
3624 	return 0;
3625 }
3626 
3627 /* change the enabled child controllers for a cgroup in the default hierarchy */
3628 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3629 					    char *buf, size_t nbytes,
3630 					    loff_t off)
3631 {
3632 	u32 enable = 0, disable = 0;
3633 	struct cgroup *cgrp, *child;
3634 	struct cgroup_subsys *ss;
3635 	char *tok;
3636 	int ssid, ret;
3637 
3638 	/*
3639 	 * Parse input - space separated list of subsystem names prefixed
3640 	 * with either + or -.
3641 	 */
3642 	buf = strstrip(buf);
3643 	while ((tok = strsep(&buf, " "))) {
3644 		if (tok[0] == '\0')
3645 			continue;
3646 		do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3647 			if (!cgroup_ssid_enabled(ssid) ||
3648 			    strcmp(tok + 1, ss->name))
3649 				continue;
3650 
3651 			if (*tok == '+') {
3652 				enable |= 1 << ssid;
3653 				disable &= ~(1 << ssid);
3654 			} else if (*tok == '-') {
3655 				disable |= 1 << ssid;
3656 				enable &= ~(1 << ssid);
3657 			} else {
3658 				return -EINVAL;
3659 			}
3660 			break;
3661 		} while_each_subsys_mask();
3662 		if (ssid == CGROUP_SUBSYS_COUNT)
3663 			return -EINVAL;
3664 	}
3665 
3666 	cgrp = cgroup_kn_lock_live(of->kn, true);
3667 	if (IS_ERR(cgrp))
3668 		return PTR_ERR(cgrp);
3669 
3670 	for_each_subsys(ss, ssid) {
3671 		if (enable & (1 << ssid)) {
3672 			if (cgrp->subtree_control & (1 << ssid)) {
3673 				enable &= ~(1 << ssid);
3674 				continue;
3675 			}
3676 
3677 			if (!(cgroup_control(cgrp) & (1 << ssid))) {
3678 				ret = -ENOENT;
3679 				goto out_unlock;
3680 			}
3681 		} else if (disable & (1 << ssid)) {
3682 			if (!(cgrp->subtree_control & (1 << ssid))) {
3683 				disable &= ~(1 << ssid);
3684 				continue;
3685 			}
3686 
3687 			/* a child has it enabled? */
3688 			cgroup_for_each_live_child(child, cgrp) {
3689 				if (child->subtree_control & (1 << ssid)) {
3690 					ret = -EBUSY;
3691 					goto out_unlock;
3692 				}
3693 			}
3694 		}
3695 	}
3696 
3697 	if (!enable && !disable) {
3698 		ret = 0;
3699 		goto out_unlock;
3700 	}
3701 
3702 	ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3703 	if (ret)
3704 		goto out_unlock;
3705 
3706 	/* save and update control masks and prepare csses */
3707 	cgroup_save_control(cgrp);
3708 
3709 	cgrp->subtree_control |= enable;
3710 	cgrp->subtree_control &= ~disable;
3711 
3712 	ret = cgroup_apply_control(cgrp);
3713 	cgroup_finalize_control(cgrp, ret);
3714 	if (ret)
3715 		goto out_unlock;
3716 
3717 	kernfs_activate(cgrp->kn);
3718 out_unlock:
3719 	cgroup_kn_unlock(of->kn);
3720 	return ret ?: nbytes;
3721 }
3722 
3723 /**
3724  * cgroup_enable_threaded - make @cgrp threaded
3725  * @cgrp: the target cgroup
3726  *
3727  * Called when "threaded" is written to the cgroup.type interface file and
3728  * tries to make @cgrp threaded and join the parent's resource domain.
3729  * This function is never called on the root cgroup as cgroup.type doesn't
3730  * exist on it.
3731  */
3732 static int cgroup_enable_threaded(struct cgroup *cgrp)
3733 {
3734 	struct cgroup *parent = cgroup_parent(cgrp);
3735 	struct cgroup *dom_cgrp = parent->dom_cgrp;
3736 	struct cgroup *dsct;
3737 	struct cgroup_subsys_state *d_css;
3738 	int ret;
3739 
3740 	lockdep_assert_held(&cgroup_mutex);
3741 
3742 	/* noop if already threaded */
3743 	if (cgroup_is_threaded(cgrp))
3744 		return 0;
3745 
3746 	/*
3747 	 * If @cgroup is populated or has domain controllers enabled, it
3748 	 * can't be switched.  While the below cgroup_can_be_thread_root()
3749 	 * test can catch the same conditions, that's only when @parent is
3750 	 * not mixable, so let's check it explicitly.
3751 	 */
3752 	if (cgroup_is_populated(cgrp) ||
3753 	    cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3754 		return -EOPNOTSUPP;
3755 
3756 	/* we're joining the parent's domain, ensure its validity */
3757 	if (!cgroup_is_valid_domain(dom_cgrp) ||
3758 	    !cgroup_can_be_thread_root(dom_cgrp))
3759 		return -EOPNOTSUPP;
3760 
3761 	/*
3762 	 * The following shouldn't cause actual migrations and should
3763 	 * always succeed.
3764 	 */
3765 	cgroup_save_control(cgrp);
3766 
3767 	cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3768 		if (dsct == cgrp || cgroup_is_threaded(dsct))
3769 			dsct->dom_cgrp = dom_cgrp;
3770 
3771 	ret = cgroup_apply_control(cgrp);
3772 	if (!ret)
3773 		parent->nr_threaded_children++;
3774 
3775 	cgroup_finalize_control(cgrp, ret);
3776 	return ret;
3777 }
3778 
3779 static int cgroup_type_show(struct seq_file *seq, void *v)
3780 {
3781 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3782 
3783 	if (cgroup_is_threaded(cgrp))
3784 		seq_puts(seq, "threaded\n");
3785 	else if (!cgroup_is_valid_domain(cgrp))
3786 		seq_puts(seq, "domain invalid\n");
3787 	else if (cgroup_is_thread_root(cgrp))
3788 		seq_puts(seq, "domain threaded\n");
3789 	else
3790 		seq_puts(seq, "domain\n");
3791 
3792 	return 0;
3793 }
3794 
3795 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3796 				 size_t nbytes, loff_t off)
3797 {
3798 	struct cgroup *cgrp;
3799 	int ret;
3800 
3801 	/* only switching to threaded mode is supported */
3802 	if (strcmp(strstrip(buf), "threaded"))
3803 		return -EINVAL;
3804 
3805 	/* drain dying csses before we re-apply (threaded) subtree control */
3806 	cgrp = cgroup_kn_lock_live(of->kn, true);
3807 	if (IS_ERR(cgrp))
3808 		return PTR_ERR(cgrp);
3809 
3810 	/* threaded can only be enabled */
3811 	ret = cgroup_enable_threaded(cgrp);
3812 
3813 	cgroup_kn_unlock(of->kn);
3814 	return ret ?: nbytes;
3815 }
3816 
3817 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3818 {
3819 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3820 	int descendants = READ_ONCE(cgrp->max_descendants);
3821 
3822 	if (descendants == INT_MAX)
3823 		seq_puts(seq, "max\n");
3824 	else
3825 		seq_printf(seq, "%d\n", descendants);
3826 
3827 	return 0;
3828 }
3829 
3830 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3831 					   char *buf, size_t nbytes, loff_t off)
3832 {
3833 	struct cgroup *cgrp;
3834 	int descendants;
3835 	ssize_t ret;
3836 
3837 	buf = strstrip(buf);
3838 	if (!strcmp(buf, "max")) {
3839 		descendants = INT_MAX;
3840 	} else {
3841 		ret = kstrtoint(buf, 0, &descendants);
3842 		if (ret)
3843 			return ret;
3844 	}
3845 
3846 	if (descendants < 0)
3847 		return -ERANGE;
3848 
3849 	cgrp = cgroup_kn_lock_live(of->kn, false);
3850 	if (IS_ERR(cgrp))
3851 		return PTR_ERR(cgrp);
3852 
3853 	WRITE_ONCE(cgrp->max_descendants, descendants);
3854 
3855 	cgroup_kn_unlock(of->kn);
3856 
3857 	return nbytes;
3858 }
3859 
3860 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3861 {
3862 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3863 	int depth = READ_ONCE(cgrp->max_depth);
3864 
3865 	if (depth == INT_MAX)
3866 		seq_puts(seq, "max\n");
3867 	else
3868 		seq_printf(seq, "%d\n", depth);
3869 
3870 	return 0;
3871 }
3872 
3873 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3874 				      char *buf, size_t nbytes, loff_t off)
3875 {
3876 	struct cgroup *cgrp;
3877 	ssize_t ret;
3878 	int depth;
3879 
3880 	buf = strstrip(buf);
3881 	if (!strcmp(buf, "max")) {
3882 		depth = INT_MAX;
3883 	} else {
3884 		ret = kstrtoint(buf, 0, &depth);
3885 		if (ret)
3886 			return ret;
3887 	}
3888 
3889 	if (depth < 0)
3890 		return -ERANGE;
3891 
3892 	cgrp = cgroup_kn_lock_live(of->kn, false);
3893 	if (IS_ERR(cgrp))
3894 		return PTR_ERR(cgrp);
3895 
3896 	WRITE_ONCE(cgrp->max_depth, depth);
3897 
3898 	cgroup_kn_unlock(of->kn);
3899 
3900 	return nbytes;
3901 }
3902 
3903 static int cgroup_events_show(struct seq_file *seq, void *v)
3904 {
3905 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3906 
3907 	seq_printf(seq, "populated %d\n", cgroup_is_populated(cgrp));
3908 	seq_printf(seq, "frozen %d\n", test_bit(CGRP_FROZEN, &cgrp->flags));
3909 
3910 	return 0;
3911 }
3912 
3913 static int cgroup_stat_show(struct seq_file *seq, void *v)
3914 {
3915 	struct cgroup *cgroup = seq_css(seq)->cgroup;
3916 	struct cgroup_subsys_state *css;
3917 	int dying_cnt[CGROUP_SUBSYS_COUNT];
3918 	int ssid;
3919 
3920 	seq_printf(seq, "nr_descendants %d\n",
3921 		   cgroup->nr_descendants);
3922 
3923 	/*
3924 	 * Show the number of live and dying csses associated with each of
3925 	 * non-inhibited cgroup subsystems that is bound to cgroup v2.
3926 	 *
3927 	 * Without proper lock protection, racing is possible. So the
3928 	 * numbers may not be consistent when that happens.
3929 	 */
3930 	rcu_read_lock();
3931 	for (ssid = 0; ssid < CGROUP_SUBSYS_COUNT; ssid++) {
3932 		dying_cnt[ssid] = -1;
3933 		if ((BIT(ssid) & cgrp_dfl_inhibit_ss_mask) ||
3934 		    (cgroup_subsys[ssid]->root !=  &cgrp_dfl_root))
3935 			continue;
3936 		css = rcu_dereference_raw(cgroup->subsys[ssid]);
3937 		dying_cnt[ssid] = cgroup->nr_dying_subsys[ssid];
3938 		seq_printf(seq, "nr_subsys_%s %d\n", cgroup_subsys[ssid]->name,
3939 			   css ? (css->nr_descendants + 1) : 0);
3940 	}
3941 
3942 	seq_printf(seq, "nr_dying_descendants %d\n",
3943 		   cgroup->nr_dying_descendants);
3944 	for (ssid = 0; ssid < CGROUP_SUBSYS_COUNT; ssid++) {
3945 		if (dying_cnt[ssid] >= 0)
3946 			seq_printf(seq, "nr_dying_subsys_%s %d\n",
3947 				   cgroup_subsys[ssid]->name, dying_cnt[ssid]);
3948 	}
3949 	rcu_read_unlock();
3950 	return 0;
3951 }
3952 
3953 static int cgroup_core_local_stat_show(struct seq_file *seq, void *v)
3954 {
3955 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3956 	unsigned int sequence;
3957 	u64 freeze_time;
3958 
3959 	do {
3960 		sequence = read_seqcount_begin(&cgrp->freezer.freeze_seq);
3961 		freeze_time = cgrp->freezer.frozen_nsec;
3962 		/* Add in current freezer interval if the cgroup is freezing. */
3963 		if (test_bit(CGRP_FREEZE, &cgrp->flags))
3964 			freeze_time += (ktime_get_ns() -
3965 					cgrp->freezer.freeze_start_nsec);
3966 	} while (read_seqcount_retry(&cgrp->freezer.freeze_seq, sequence));
3967 
3968 	do_div(freeze_time, NSEC_PER_USEC);
3969 	seq_printf(seq, "frozen_usec %llu\n", freeze_time);
3970 
3971 	return 0;
3972 }
3973 
3974 #ifdef CONFIG_CGROUP_SCHED
3975 /**
3976  * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
3977  * @cgrp: the cgroup of interest
3978  * @ss: the subsystem of interest
3979  *
3980  * Find and get @cgrp's css associated with @ss.  If the css doesn't exist
3981  * or is offline, %NULL is returned.
3982  */
3983 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
3984 						     struct cgroup_subsys *ss)
3985 {
3986 	struct cgroup_subsys_state *css;
3987 
3988 	rcu_read_lock();
3989 	css = cgroup_css(cgrp, ss);
3990 	if (css && !css_tryget_online(css))
3991 		css = NULL;
3992 	rcu_read_unlock();
3993 
3994 	return css;
3995 }
3996 
3997 static int cgroup_extra_stat_show(struct seq_file *seq, int ssid)
3998 {
3999 	struct cgroup *cgrp = seq_css(seq)->cgroup;
4000 	struct cgroup_subsys *ss = cgroup_subsys[ssid];
4001 	struct cgroup_subsys_state *css;
4002 	int ret;
4003 
4004 	if (!ss->css_extra_stat_show)
4005 		return 0;
4006 
4007 	css = cgroup_tryget_css(cgrp, ss);
4008 	if (!css)
4009 		return 0;
4010 
4011 	ret = ss->css_extra_stat_show(seq, css);
4012 	css_put(css);
4013 	return ret;
4014 }
4015 
4016 static int cgroup_local_stat_show(struct seq_file *seq,
4017 				  struct cgroup *cgrp, int ssid)
4018 {
4019 	struct cgroup_subsys *ss = cgroup_subsys[ssid];
4020 	struct cgroup_subsys_state *css;
4021 	int ret;
4022 
4023 	if (!ss->css_local_stat_show)
4024 		return 0;
4025 
4026 	css = cgroup_tryget_css(cgrp, ss);
4027 	if (!css)
4028 		return 0;
4029 
4030 	ret = ss->css_local_stat_show(seq, css);
4031 	css_put(css);
4032 	return ret;
4033 }
4034 #endif
4035 
4036 static int cpu_stat_show(struct seq_file *seq, void *v)
4037 {
4038 	int ret = 0;
4039 
4040 	cgroup_base_stat_cputime_show(seq);
4041 #ifdef CONFIG_CGROUP_SCHED
4042 	ret = cgroup_extra_stat_show(seq, cpu_cgrp_id);
4043 #endif
4044 	return ret;
4045 }
4046 
4047 static int cpu_local_stat_show(struct seq_file *seq, void *v)
4048 {
4049 	struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
4050 	int ret = 0;
4051 
4052 #ifdef CONFIG_CGROUP_SCHED
4053 	ret = cgroup_local_stat_show(seq, cgrp, cpu_cgrp_id);
4054 #endif
4055 	return ret;
4056 }
4057 
4058 #ifdef CONFIG_PSI
4059 static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
4060 {
4061 	struct cgroup *cgrp = seq_css(seq)->cgroup;
4062 	struct psi_group *psi = cgroup_psi(cgrp);
4063 
4064 	return psi_show(seq, psi, PSI_IO);
4065 }
4066 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
4067 {
4068 	struct cgroup *cgrp = seq_css(seq)->cgroup;
4069 	struct psi_group *psi = cgroup_psi(cgrp);
4070 
4071 	return psi_show(seq, psi, PSI_MEM);
4072 }
4073 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
4074 {
4075 	struct cgroup *cgrp = seq_css(seq)->cgroup;
4076 	struct psi_group *psi = cgroup_psi(cgrp);
4077 
4078 	return psi_show(seq, psi, PSI_CPU);
4079 }
4080 
4081 static ssize_t pressure_write(struct kernfs_open_file *of, char *buf,
4082 			      size_t nbytes, enum psi_res res)
4083 {
4084 	struct cgroup_file_ctx *ctx;
4085 	struct psi_trigger *new;
4086 	struct cgroup *cgrp;
4087 	struct psi_group *psi;
4088 	bool need_rtpoll_worker;
4089 	ssize_t ret = 0;
4090 
4091 	cgrp = cgroup_kn_lock_live(of->kn, false);
4092 	if (IS_ERR(cgrp))
4093 		return PTR_ERR(cgrp);
4094 
4095 	ctx = of->priv;
4096 	if (!ctx) {
4097 		ret = -ENODEV;
4098 		goto out_unlock;
4099 	}
4100 
4101 	/* Allow only one trigger per file descriptor */
4102 	if (ctx->psi.trigger) {
4103 		ret = -EBUSY;
4104 		goto out_unlock;
4105 	}
4106 
4107 	psi = cgroup_psi(cgrp);
4108 	new = psi_trigger_create(psi, buf, res, of->file, of,
4109 				 &need_rtpoll_worker);
4110 	if (IS_ERR(new)) {
4111 		ret = PTR_ERR(new);
4112 		goto out_unlock;
4113 	}
4114 
4115 	/*
4116 	 * The worker fork must run with neither cgroup_mutex nor the file's
4117 	 * kernfs active reference held. The latter is broken since
4118 	 * cgroup_kn_lock_live(). @of->priv may be released while unlocked, so
4119 	 * recheck before publishing @new.
4120 	 */
4121 	if (need_rtpoll_worker) {
4122 		cgroup_unlock();
4123 		ret = psi_trigger_create_rtpoll_worker(psi);
4124 		cgroup_lock();
4125 
4126 		if (!ret && !of->priv)
4127 			ret = -ENODEV;
4128 		if (ret) {
4129 			psi_trigger_destroy(new);
4130 			goto out_unlock;
4131 		}
4132 	}
4133 
4134 	smp_store_release(&ctx->psi.trigger, new);
4135 
4136 out_unlock:
4137 	cgroup_kn_unlock(of->kn);
4138 	if (ret)
4139 		return ret;
4140 
4141 	return nbytes;
4142 }
4143 
4144 static ssize_t cgroup_io_pressure_write(struct kernfs_open_file *of,
4145 					  char *buf, size_t nbytes,
4146 					  loff_t off)
4147 {
4148 	return pressure_write(of, buf, nbytes, PSI_IO);
4149 }
4150 
4151 static ssize_t cgroup_memory_pressure_write(struct kernfs_open_file *of,
4152 					  char *buf, size_t nbytes,
4153 					  loff_t off)
4154 {
4155 	return pressure_write(of, buf, nbytes, PSI_MEM);
4156 }
4157 
4158 static ssize_t cgroup_cpu_pressure_write(struct kernfs_open_file *of,
4159 					  char *buf, size_t nbytes,
4160 					  loff_t off)
4161 {
4162 	return pressure_write(of, buf, nbytes, PSI_CPU);
4163 }
4164 
4165 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
4166 static int cgroup_irq_pressure_show(struct seq_file *seq, void *v)
4167 {
4168 	struct cgroup *cgrp = seq_css(seq)->cgroup;
4169 	struct psi_group *psi = cgroup_psi(cgrp);
4170 
4171 	return psi_show(seq, psi, PSI_IRQ);
4172 }
4173 
4174 static ssize_t cgroup_irq_pressure_write(struct kernfs_open_file *of,
4175 					 char *buf, size_t nbytes,
4176 					 loff_t off)
4177 {
4178 	return pressure_write(of, buf, nbytes, PSI_IRQ);
4179 }
4180 #endif
4181 
4182 static int cgroup_pressure_show(struct seq_file *seq, void *v)
4183 {
4184 	struct cgroup *cgrp = seq_css(seq)->cgroup;
4185 	struct psi_group *psi = cgroup_psi(cgrp);
4186 
4187 	seq_printf(seq, "%d\n", psi->enabled);
4188 
4189 	return 0;
4190 }
4191 
4192 static ssize_t cgroup_pressure_write(struct kernfs_open_file *of,
4193 				     char *buf, size_t nbytes,
4194 				     loff_t off)
4195 {
4196 	ssize_t ret;
4197 	int enable;
4198 	struct cgroup *cgrp;
4199 	struct psi_group *psi;
4200 
4201 	ret = kstrtoint(strstrip(buf), 0, &enable);
4202 	if (ret)
4203 		return ret;
4204 
4205 	if (enable < 0 || enable > 1)
4206 		return -ERANGE;
4207 
4208 	cgrp = cgroup_kn_lock_live(of->kn, false);
4209 	if (IS_ERR(cgrp))
4210 		return PTR_ERR(cgrp);
4211 
4212 	psi = cgroup_psi(cgrp);
4213 	if (psi->enabled != enable) {
4214 		int i;
4215 
4216 		/* show or hide {cpu,memory,io,irq}.pressure files */
4217 		for (i = 0; i < NR_PSI_RESOURCES; i++)
4218 			cgroup_file_show(&cgrp->psi_files[i], enable);
4219 
4220 		psi->enabled = enable;
4221 		if (enable)
4222 			psi_cgroup_restart(psi);
4223 	}
4224 
4225 	cgroup_kn_unlock(of->kn);
4226 
4227 	return nbytes;
4228 }
4229 
4230 static __poll_t cgroup_pressure_poll(struct kernfs_open_file *of,
4231 					  poll_table *pt)
4232 {
4233 	struct cgroup_file_ctx *ctx = of->priv;
4234 
4235 	return psi_trigger_poll(&ctx->psi.trigger, of->file, pt);
4236 }
4237 
4238 static void cgroup_pressure_release(struct kernfs_open_file *of)
4239 {
4240 	struct cgroup_file_ctx *ctx = of->priv;
4241 
4242 	psi_trigger_destroy(ctx->psi.trigger);
4243 }
4244 
4245 bool cgroup_psi_enabled(void)
4246 {
4247 	if (static_branch_likely(&psi_disabled))
4248 		return false;
4249 
4250 	return (cgroup_feature_disable_mask & (1 << OPT_FEATURE_PRESSURE)) == 0;
4251 }
4252 
4253 #else /* CONFIG_PSI */
4254 bool cgroup_psi_enabled(void)
4255 {
4256 	return false;
4257 }
4258 
4259 #endif /* CONFIG_PSI */
4260 
4261 static int cgroup_freeze_show(struct seq_file *seq, void *v)
4262 {
4263 	struct cgroup *cgrp = seq_css(seq)->cgroup;
4264 
4265 	seq_printf(seq, "%d\n", cgrp->freezer.freeze);
4266 
4267 	return 0;
4268 }
4269 
4270 static ssize_t cgroup_freeze_write(struct kernfs_open_file *of,
4271 				   char *buf, size_t nbytes, loff_t off)
4272 {
4273 	struct cgroup *cgrp;
4274 	ssize_t ret;
4275 	int freeze;
4276 
4277 	ret = kstrtoint(strstrip(buf), 0, &freeze);
4278 	if (ret)
4279 		return ret;
4280 
4281 	if (freeze < 0 || freeze > 1)
4282 		return -ERANGE;
4283 
4284 	cgrp = cgroup_kn_lock_live(of->kn, false);
4285 	if (IS_ERR(cgrp))
4286 		return PTR_ERR(cgrp);
4287 
4288 	cgroup_freeze(cgrp, freeze);
4289 
4290 	cgroup_kn_unlock(of->kn);
4291 
4292 	return nbytes;
4293 }
4294 
4295 static void __cgroup_kill(struct cgroup *cgrp)
4296 {
4297 	struct css_task_iter it;
4298 	struct task_struct *task;
4299 
4300 	lockdep_assert_held(&cgroup_mutex);
4301 
4302 	spin_lock_irq(&css_set_lock);
4303 	cgrp->kill_seq++;
4304 	spin_unlock_irq(&css_set_lock);
4305 
4306 	css_task_iter_start(&cgrp->self, CSS_TASK_ITER_PROCS | CSS_TASK_ITER_THREADED, &it);
4307 	while ((task = css_task_iter_next(&it))) {
4308 		/* Ignore kernel threads here. */
4309 		if (task->flags & PF_KTHREAD)
4310 			continue;
4311 
4312 		/* Skip tasks that are already dying. */
4313 		if (__fatal_signal_pending(task))
4314 			continue;
4315 
4316 		send_sig(SIGKILL, task, 0);
4317 	}
4318 	css_task_iter_end(&it);
4319 }
4320 
4321 static void cgroup_kill(struct cgroup *cgrp)
4322 {
4323 	struct cgroup_subsys_state *css;
4324 	struct cgroup *dsct;
4325 
4326 	lockdep_assert_held(&cgroup_mutex);
4327 
4328 	cgroup_for_each_live_descendant_pre(dsct, css, cgrp)
4329 		__cgroup_kill(dsct);
4330 }
4331 
4332 static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf,
4333 				 size_t nbytes, loff_t off)
4334 {
4335 	ssize_t ret = 0;
4336 	int kill;
4337 	struct cgroup *cgrp;
4338 
4339 	ret = kstrtoint(strstrip(buf), 0, &kill);
4340 	if (ret)
4341 		return ret;
4342 
4343 	if (kill != 1)
4344 		return -ERANGE;
4345 
4346 	cgrp = cgroup_kn_lock_live(of->kn, false);
4347 	if (IS_ERR(cgrp))
4348 		return PTR_ERR(cgrp);
4349 
4350 	/*
4351 	 * Killing is a process directed operation, i.e. the whole thread-group
4352 	 * is taken down so act like we do for cgroup.procs and only make this
4353 	 * writable in non-threaded cgroups.
4354 	 */
4355 	if (cgroup_is_threaded(cgrp))
4356 		ret = -EOPNOTSUPP;
4357 	else
4358 		cgroup_kill(cgrp);
4359 
4360 	cgroup_kn_unlock(of->kn);
4361 
4362 	return ret ?: nbytes;
4363 }
4364 
4365 static int cgroup_file_open(struct kernfs_open_file *of)
4366 {
4367 	struct cftype *cft = of_cft(of);
4368 	struct cgroup_file_ctx *ctx;
4369 	int ret;
4370 
4371 	ctx = kzalloc_obj(*ctx);
4372 	if (!ctx)
4373 		return -ENOMEM;
4374 
4375 	ctx->ns = current->nsproxy->cgroup_ns;
4376 	get_cgroup_ns(ctx->ns);
4377 	of->priv = ctx;
4378 
4379 	if (!cft->open)
4380 		return 0;
4381 
4382 	ret = cft->open(of);
4383 	if (ret) {
4384 		put_cgroup_ns(ctx->ns);
4385 		kfree(ctx);
4386 	}
4387 	return ret;
4388 }
4389 
4390 static void cgroup_file_release(struct kernfs_open_file *of)
4391 {
4392 	struct cftype *cft = of_cft(of);
4393 	struct cgroup_file_ctx *ctx = of->priv;
4394 
4395 	if (cft->release)
4396 		cft->release(of);
4397 	put_cgroup_ns(ctx->ns);
4398 	kfree(ctx);
4399 	of->priv = NULL;
4400 }
4401 
4402 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
4403 				 size_t nbytes, loff_t off)
4404 {
4405 	struct cgroup_file_ctx *ctx = of->priv;
4406 	struct cgroup *cgrp = kn_priv(of->kn);
4407 	struct cftype *cft = of_cft(of);
4408 	struct cgroup_subsys_state *css;
4409 	int ret;
4410 
4411 	if (!nbytes)
4412 		return 0;
4413 
4414 	/*
4415 	 * If namespaces are delegation boundaries, disallow writes to
4416 	 * files in an non-init namespace root from inside the namespace
4417 	 * except for the files explicitly marked delegatable -
4418 	 * eg. cgroup.procs, cgroup.threads and cgroup.subtree_control.
4419 	 */
4420 	if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
4421 	    !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
4422 	    ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
4423 		return -EPERM;
4424 
4425 	if (cft->write)
4426 		return cft->write(of, buf, nbytes, off);
4427 
4428 	/*
4429 	 * kernfs guarantees that a file isn't deleted with operations in
4430 	 * flight, which means that the matching css is and stays alive and
4431 	 * doesn't need to be pinned.  The RCU locking is not necessary
4432 	 * either.  It's just for the convenience of using cgroup_css().
4433 	 */
4434 	rcu_read_lock();
4435 	css = cgroup_css(cgrp, cft->ss);
4436 	rcu_read_unlock();
4437 
4438 	if (cft->write_u64) {
4439 		unsigned long long v;
4440 		ret = kstrtoull(buf, 0, &v);
4441 		if (!ret)
4442 			ret = cft->write_u64(css, cft, v);
4443 	} else if (cft->write_s64) {
4444 		long long v;
4445 		ret = kstrtoll(buf, 0, &v);
4446 		if (!ret)
4447 			ret = cft->write_s64(css, cft, v);
4448 	} else {
4449 		ret = -EINVAL;
4450 	}
4451 
4452 	return ret ?: nbytes;
4453 }
4454 
4455 static __poll_t cgroup_file_poll(struct kernfs_open_file *of, poll_table *pt)
4456 {
4457 	struct cftype *cft = of_cft(of);
4458 
4459 	if (cft->poll)
4460 		return cft->poll(of, pt);
4461 
4462 	return kernfs_generic_poll(of, pt);
4463 }
4464 
4465 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
4466 {
4467 	return seq_cft(seq)->seq_start(seq, ppos);
4468 }
4469 
4470 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
4471 {
4472 	return seq_cft(seq)->seq_next(seq, v, ppos);
4473 }
4474 
4475 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
4476 {
4477 	if (seq_cft(seq)->seq_stop)
4478 		seq_cft(seq)->seq_stop(seq, v);
4479 }
4480 
4481 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
4482 {
4483 	struct cftype *cft = seq_cft(m);
4484 	struct cgroup_subsys_state *css = seq_css(m);
4485 
4486 	if (cft->seq_show)
4487 		return cft->seq_show(m, arg);
4488 
4489 	if (cft->read_u64)
4490 		seq_printf(m, "%llu\n", cft->read_u64(css, cft));
4491 	else if (cft->read_s64)
4492 		seq_printf(m, "%lld\n", cft->read_s64(css, cft));
4493 	else
4494 		return -EINVAL;
4495 	return 0;
4496 }
4497 
4498 static struct kernfs_ops cgroup_kf_single_ops = {
4499 	.atomic_write_len	= PAGE_SIZE,
4500 	.open			= cgroup_file_open,
4501 	.release		= cgroup_file_release,
4502 	.write			= cgroup_file_write,
4503 	.poll			= cgroup_file_poll,
4504 	.seq_show		= cgroup_seqfile_show,
4505 };
4506 
4507 static struct kernfs_ops cgroup_kf_ops = {
4508 	.atomic_write_len	= PAGE_SIZE,
4509 	.open			= cgroup_file_open,
4510 	.release		= cgroup_file_release,
4511 	.write			= cgroup_file_write,
4512 	.poll			= cgroup_file_poll,
4513 	.seq_start		= cgroup_seqfile_start,
4514 	.seq_next		= cgroup_seqfile_next,
4515 	.seq_stop		= cgroup_seqfile_stop,
4516 	.seq_show		= cgroup_seqfile_show,
4517 };
4518 
4519 static void cgroup_file_notify_timer(struct timer_list *timer)
4520 {
4521 	cgroup_file_notify(container_of(timer, struct cgroup_file,
4522 					notify_timer));
4523 }
4524 
4525 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
4526 			   struct cftype *cft)
4527 {
4528 	char name[CGROUP_FILE_NAME_MAX];
4529 	struct kernfs_node *kn;
4530 	struct lock_class_key *key = NULL;
4531 
4532 #ifdef CONFIG_DEBUG_LOCK_ALLOC
4533 	key = &cft->lockdep_key;
4534 #endif
4535 	kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
4536 				  cgroup_file_mode(cft),
4537 				  current_fsuid(), current_fsgid(),
4538 				  0, cft->kf_ops, cft,
4539 				  NULL, key);
4540 	if (IS_ERR(kn))
4541 		return PTR_ERR(kn);
4542 
4543 	if (cft->file_offset) {
4544 		struct cgroup_file *cfile = (void *)css + cft->file_offset;
4545 
4546 		timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
4547 		spin_lock_init(&cfile->lock);
4548 		cfile->kn = kn;
4549 	}
4550 
4551 	return 0;
4552 }
4553 
4554 /**
4555  * cgroup_addrm_files - add or remove files to a cgroup directory
4556  * @css: the target css
4557  * @cgrp: the target cgroup (usually css->cgroup)
4558  * @cfts: array of cftypes to be added
4559  * @is_add: whether to add or remove
4560  *
4561  * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
4562  * For removals, this function never fails.
4563  */
4564 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
4565 			      struct cgroup *cgrp, struct cftype cfts[],
4566 			      bool is_add)
4567 {
4568 	struct cftype *cft, *cft_end = NULL;
4569 	int ret = 0;
4570 
4571 	lockdep_assert_held(&cgroup_mutex);
4572 
4573 restart:
4574 	for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
4575 		/* does cft->flags tell us to skip this file on @cgrp? */
4576 		if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
4577 			continue;
4578 		if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
4579 			continue;
4580 		if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
4581 			continue;
4582 		if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
4583 			continue;
4584 		if ((cft->flags & CFTYPE_DEBUG) && !cgroup_debug)
4585 			continue;
4586 		if (is_add) {
4587 			ret = cgroup_add_file(css, cgrp, cft);
4588 			if (ret) {
4589 				pr_warn("%s: failed to add %s, err=%d\n",
4590 					__func__, cft->name, ret);
4591 				cft_end = cft;
4592 				is_add = false;
4593 				goto restart;
4594 			}
4595 		} else {
4596 			cgroup_rm_file(cgrp, cft);
4597 		}
4598 	}
4599 	return ret;
4600 }
4601 
4602 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
4603 {
4604 	struct cgroup_subsys *ss = cfts[0].ss;
4605 	struct cgroup *root = &ss->root->cgrp;
4606 	struct cgroup_subsys_state *css;
4607 	int ret = 0;
4608 
4609 	lockdep_assert_held(&cgroup_mutex);
4610 
4611 	/* add/rm files for all cgroups created before */
4612 	css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
4613 		struct cgroup *cgrp = css->cgroup;
4614 
4615 		if (!(css->flags & CSS_VISIBLE))
4616 			continue;
4617 
4618 		ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
4619 		if (ret)
4620 			break;
4621 	}
4622 
4623 	if (is_add && !ret)
4624 		kernfs_activate(root->kn);
4625 	return ret;
4626 }
4627 
4628 static void cgroup_exit_cftypes(struct cftype *cfts)
4629 {
4630 	struct cftype *cft;
4631 
4632 	for (cft = cfts; cft->name[0] != '\0'; cft++) {
4633 		/* free copy for custom atomic_write_len, see init_cftypes() */
4634 		if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
4635 			kfree(cft->kf_ops);
4636 		cft->kf_ops = NULL;
4637 		cft->ss = NULL;
4638 
4639 		/* revert flags set by cgroup core while adding @cfts */
4640 		cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL |
4641 				__CFTYPE_ADDED);
4642 	}
4643 }
4644 
4645 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4646 {
4647 	struct cftype *cft;
4648 	int ret = 0;
4649 
4650 	for (cft = cfts; cft->name[0] != '\0'; cft++) {
4651 		struct kernfs_ops *kf_ops;
4652 
4653 		WARN_ON(cft->ss || cft->kf_ops);
4654 
4655 		if (cft->flags & __CFTYPE_ADDED) {
4656 			ret = -EBUSY;
4657 			break;
4658 		}
4659 
4660 		if (cft->seq_start)
4661 			kf_ops = &cgroup_kf_ops;
4662 		else
4663 			kf_ops = &cgroup_kf_single_ops;
4664 
4665 		/*
4666 		 * Ugh... if @cft wants a custom max_write_len, we need to
4667 		 * make a copy of kf_ops to set its atomic_write_len.
4668 		 */
4669 		if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
4670 			kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
4671 			if (!kf_ops) {
4672 				ret = -ENOMEM;
4673 				break;
4674 			}
4675 			kf_ops->atomic_write_len = cft->max_write_len;
4676 		}
4677 
4678 		cft->kf_ops = kf_ops;
4679 		cft->ss = ss;
4680 		cft->flags |= __CFTYPE_ADDED;
4681 	}
4682 
4683 	if (ret)
4684 		cgroup_exit_cftypes(cfts);
4685 	return ret;
4686 }
4687 
4688 static void cgroup_rm_cftypes_locked(struct cftype *cfts)
4689 {
4690 	lockdep_assert_held(&cgroup_mutex);
4691 
4692 	list_del(&cfts->node);
4693 	cgroup_apply_cftypes(cfts, false);
4694 	cgroup_exit_cftypes(cfts);
4695 }
4696 
4697 /**
4698  * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
4699  * @cfts: zero-length name terminated array of cftypes
4700  *
4701  * Unregister @cfts.  Files described by @cfts are removed from all
4702  * existing cgroups and all future cgroups won't have them either.  This
4703  * function can be called anytime whether @cfts' subsys is attached or not.
4704  *
4705  * Returns 0 on successful unregistration, -ENOENT if @cfts is not
4706  * registered.
4707  */
4708 int cgroup_rm_cftypes(struct cftype *cfts)
4709 {
4710 	if (!cfts || cfts[0].name[0] == '\0')
4711 		return 0;
4712 
4713 	if (!(cfts[0].flags & __CFTYPE_ADDED))
4714 		return -ENOENT;
4715 
4716 	cgroup_lock();
4717 	cgroup_rm_cftypes_locked(cfts);
4718 	cgroup_unlock();
4719 	return 0;
4720 }
4721 
4722 /**
4723  * cgroup_add_cftypes - add an array of cftypes to a subsystem
4724  * @ss: target cgroup subsystem
4725  * @cfts: zero-length name terminated array of cftypes
4726  *
4727  * Register @cfts to @ss.  Files described by @cfts are created for all
4728  * existing cgroups to which @ss is attached and all future cgroups will
4729  * have them too.  This function can be called anytime whether @ss is
4730  * attached or not.
4731  *
4732  * Returns 0 on successful registration, -errno on failure.  Note that this
4733  * function currently returns 0 as long as @cfts registration is successful
4734  * even if some file creation attempts on existing cgroups fail.
4735  */
4736 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4737 {
4738 	int ret;
4739 
4740 	if (!cgroup_ssid_enabled(ss->id))
4741 		return 0;
4742 
4743 	if (!cfts || cfts[0].name[0] == '\0')
4744 		return 0;
4745 
4746 	ret = cgroup_init_cftypes(ss, cfts);
4747 	if (ret)
4748 		return ret;
4749 
4750 	cgroup_lock();
4751 
4752 	list_add_tail(&cfts->node, &ss->cfts);
4753 	ret = cgroup_apply_cftypes(cfts, true);
4754 	if (ret)
4755 		cgroup_rm_cftypes_locked(cfts);
4756 
4757 	cgroup_unlock();
4758 	return ret;
4759 }
4760 
4761 /**
4762  * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
4763  * @ss: target cgroup subsystem
4764  * @cfts: zero-length name terminated array of cftypes
4765  *
4766  * Similar to cgroup_add_cftypes() but the added files are only used for
4767  * the default hierarchy.
4768  */
4769 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4770 {
4771 	struct cftype *cft;
4772 
4773 	for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4774 		cft->flags |= __CFTYPE_ONLY_ON_DFL;
4775 	return cgroup_add_cftypes(ss, cfts);
4776 }
4777 
4778 /**
4779  * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
4780  * @ss: target cgroup subsystem
4781  * @cfts: zero-length name terminated array of cftypes
4782  *
4783  * Similar to cgroup_add_cftypes() but the added files are only used for
4784  * the legacy hierarchies.
4785  */
4786 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4787 {
4788 	struct cftype *cft;
4789 
4790 	for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4791 		cft->flags |= __CFTYPE_NOT_ON_DFL;
4792 	return cgroup_add_cftypes(ss, cfts);
4793 }
4794 
4795 /**
4796  * cgroup_file_notify - generate a file modified event for a cgroup_file
4797  * @cfile: target cgroup_file
4798  *
4799  * @cfile must have been obtained by setting cftype->file_offset.
4800  */
4801 void cgroup_file_notify(struct cgroup_file *cfile)
4802 {
4803 	unsigned long flags, last, next;
4804 	struct kernfs_node *kn = NULL;
4805 
4806 	if (!READ_ONCE(cfile->kn))
4807 		return;
4808 
4809 	last = READ_ONCE(cfile->notified_at);
4810 	next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
4811 	if (time_in_range(jiffies, last, next)) {
4812 		timer_reduce(&cfile->notify_timer, next);
4813 		if (timer_pending(&cfile->notify_timer))
4814 			return;
4815 	}
4816 
4817 	spin_lock_irqsave(&cfile->lock, flags);
4818 	if (cfile->kn) {
4819 		kn = cfile->kn;
4820 		kernfs_get(kn);
4821 		WRITE_ONCE(cfile->notified_at, jiffies);
4822 	}
4823 	spin_unlock_irqrestore(&cfile->lock, flags);
4824 
4825 	if (kn) {
4826 		kernfs_notify(kn);
4827 		kernfs_put(kn);
4828 	}
4829 }
4830 EXPORT_SYMBOL_GPL(cgroup_file_notify);
4831 
4832 /**
4833  * cgroup_file_show - show or hide a hidden cgroup file
4834  * @cfile: target cgroup_file obtained by setting cftype->file_offset
4835  * @show: whether to show or hide
4836  */
4837 void cgroup_file_show(struct cgroup_file *cfile, bool show)
4838 {
4839 	struct kernfs_node *kn;
4840 
4841 	spin_lock_irq(&cfile->lock);
4842 	kn = cfile->kn;
4843 	kernfs_get(kn);
4844 	spin_unlock_irq(&cfile->lock);
4845 
4846 	if (kn)
4847 		kernfs_show(kn, show);
4848 
4849 	kernfs_put(kn);
4850 }
4851 
4852 /**
4853  * css_next_child - find the next child of a given css
4854  * @pos: the current position (%NULL to initiate traversal)
4855  * @parent: css whose children to walk
4856  *
4857  * This function returns the next child of @parent and should be called
4858  * under either cgroup_mutex or RCU read lock.  The only requirement is
4859  * that @parent and @pos are accessible.  The next sibling is guaranteed to
4860  * be returned regardless of their states.
4861  *
4862  * If a subsystem synchronizes ->css_online() and the start of iteration, a
4863  * css which finished ->css_online() is guaranteed to be visible in the
4864  * future iterations and will stay visible until the last reference is put.
4865  * A css which hasn't finished ->css_online() or already finished
4866  * ->css_offline() may show up during traversal.  It's each subsystem's
4867  * responsibility to synchronize against on/offlining.
4868  */
4869 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
4870 					   struct cgroup_subsys_state *parent)
4871 {
4872 	struct cgroup_subsys_state *next;
4873 
4874 	cgroup_assert_mutex_or_rcu_locked();
4875 
4876 	/*
4877 	 * @pos could already have been unlinked from the sibling list.
4878 	 * Once a cgroup is removed, its ->sibling.next is no longer
4879 	 * updated when its next sibling changes.  CSS_RELEASED is set when
4880 	 * @pos is taken off list, at which time its next pointer is valid,
4881 	 * and, as releases are serialized, the one pointed to by the next
4882 	 * pointer is guaranteed to not have started release yet.  This
4883 	 * implies that if we observe !CSS_RELEASED on @pos in this RCU
4884 	 * critical section, the one pointed to by its next pointer is
4885 	 * guaranteed to not have finished its RCU grace period even if we
4886 	 * have dropped rcu_read_lock() in-between iterations.
4887 	 *
4888 	 * If @pos has CSS_RELEASED set, its next pointer can't be
4889 	 * dereferenced; however, as each css is given a monotonically
4890 	 * increasing unique serial number and always appended to the
4891 	 * sibling list, the next one can be found by walking the parent's
4892 	 * children until the first css with higher serial number than
4893 	 * @pos's.  While this path can be slower, it happens iff iteration
4894 	 * races against release and the race window is very small.
4895 	 */
4896 	if (!pos) {
4897 		next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
4898 	} else if (likely(!(pos->flags & CSS_RELEASED))) {
4899 		next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
4900 	} else {
4901 		list_for_each_entry_rcu(next, &parent->children, sibling,
4902 					lockdep_is_held(&cgroup_mutex))
4903 			if (next->serial_nr > pos->serial_nr)
4904 				break;
4905 	}
4906 
4907 	/*
4908 	 * @next, if not pointing to the head, can be dereferenced and is
4909 	 * the next sibling.
4910 	 */
4911 	if (&next->sibling != &parent->children)
4912 		return next;
4913 	return NULL;
4914 }
4915 
4916 /**
4917  * css_next_descendant_pre - find the next descendant for pre-order walk
4918  * @pos: the current position (%NULL to initiate traversal)
4919  * @root: css whose descendants to walk
4920  *
4921  * To be used by css_for_each_descendant_pre().  Find the next descendant
4922  * to visit for pre-order traversal of @root's descendants.  @root is
4923  * included in the iteration and the first node to be visited.
4924  *
4925  * While this function requires cgroup_mutex or RCU read locking, it
4926  * doesn't require the whole traversal to be contained in a single critical
4927  * section. Additionally, it isn't necessary to hold onto a reference to @pos.
4928  * This function will return the correct next descendant as long as both @pos
4929  * and @root are accessible and @pos is a descendant of @root.
4930  *
4931  * If a subsystem synchronizes ->css_online() and the start of iteration, a
4932  * css which finished ->css_online() is guaranteed to be visible in the
4933  * future iterations and will stay visible until the last reference is put.
4934  * A css which hasn't finished ->css_online() or already finished
4935  * ->css_offline() may show up during traversal.  It's each subsystem's
4936  * responsibility to synchronize against on/offlining.
4937  */
4938 struct cgroup_subsys_state *
4939 css_next_descendant_pre(struct cgroup_subsys_state *pos,
4940 			struct cgroup_subsys_state *root)
4941 {
4942 	struct cgroup_subsys_state *next;
4943 
4944 	cgroup_assert_mutex_or_rcu_locked();
4945 
4946 	/* if first iteration, visit @root */
4947 	if (!pos)
4948 		return root;
4949 
4950 	/* visit the first child if exists */
4951 	next = css_next_child(NULL, pos);
4952 	if (next)
4953 		return next;
4954 
4955 	/* no child, visit my or the closest ancestor's next sibling */
4956 	while (pos != root) {
4957 		next = css_next_child(pos, pos->parent);
4958 		if (next)
4959 			return next;
4960 		pos = pos->parent;
4961 	}
4962 
4963 	return NULL;
4964 }
4965 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
4966 
4967 /**
4968  * css_rightmost_descendant - return the rightmost descendant of a css
4969  * @pos: css of interest
4970  *
4971  * Return the rightmost descendant of @pos.  If there's no descendant, @pos
4972  * is returned.  This can be used during pre-order traversal to skip
4973  * subtree of @pos.
4974  *
4975  * While this function requires cgroup_mutex or RCU read locking, it
4976  * doesn't require the whole traversal to be contained in a single critical
4977  * section. Additionally, it isn't necessary to hold onto a reference to @pos.
4978  * This function will return the correct rightmost descendant as long as @pos
4979  * is accessible.
4980  */
4981 struct cgroup_subsys_state *
4982 css_rightmost_descendant(struct cgroup_subsys_state *pos)
4983 {
4984 	struct cgroup_subsys_state *last, *tmp;
4985 
4986 	cgroup_assert_mutex_or_rcu_locked();
4987 
4988 	do {
4989 		last = pos;
4990 		/* ->prev isn't RCU safe, walk ->next till the end */
4991 		pos = NULL;
4992 		css_for_each_child(tmp, last)
4993 			pos = tmp;
4994 	} while (pos);
4995 
4996 	return last;
4997 }
4998 
4999 static struct cgroup_subsys_state *
5000 css_leftmost_descendant(struct cgroup_subsys_state *pos)
5001 {
5002 	struct cgroup_subsys_state *last;
5003 
5004 	do {
5005 		last = pos;
5006 		pos = css_next_child(NULL, pos);
5007 	} while (pos);
5008 
5009 	return last;
5010 }
5011 
5012 /**
5013  * css_next_descendant_post - find the next descendant for post-order walk
5014  * @pos: the current position (%NULL to initiate traversal)
5015  * @root: css whose descendants to walk
5016  *
5017  * To be used by css_for_each_descendant_post().  Find the next descendant
5018  * to visit for post-order traversal of @root's descendants.  @root is
5019  * included in the iteration and the last node to be visited.
5020  *
5021  * While this function requires cgroup_mutex or RCU read locking, it
5022  * doesn't require the whole traversal to be contained in a single critical
5023  * section. Additionally, it isn't necessary to hold onto a reference to @pos.
5024  * This function will return the correct next descendant as long as both @pos
5025  * and @cgroup are accessible and @pos is a descendant of @cgroup.
5026  *
5027  * If a subsystem synchronizes ->css_online() and the start of iteration, a
5028  * css which finished ->css_online() is guaranteed to be visible in the
5029  * future iterations and will stay visible until the last reference is put.
5030  * A css which hasn't finished ->css_online() or already finished
5031  * ->css_offline() may show up during traversal.  It's each subsystem's
5032  * responsibility to synchronize against on/offlining.
5033  */
5034 struct cgroup_subsys_state *
5035 css_next_descendant_post(struct cgroup_subsys_state *pos,
5036 			 struct cgroup_subsys_state *root)
5037 {
5038 	struct cgroup_subsys_state *next;
5039 
5040 	cgroup_assert_mutex_or_rcu_locked();
5041 
5042 	/* if first iteration, visit leftmost descendant which may be @root */
5043 	if (!pos)
5044 		return css_leftmost_descendant(root);
5045 
5046 	/* if we visited @root, we're done */
5047 	if (pos == root)
5048 		return NULL;
5049 
5050 	/* if there's an unvisited sibling, visit its leftmost descendant */
5051 	next = css_next_child(pos, pos->parent);
5052 	if (next)
5053 		return css_leftmost_descendant(next);
5054 
5055 	/* no sibling left, visit parent */
5056 	return pos->parent;
5057 }
5058 
5059 /**
5060  * css_has_online_children - does a css have online children
5061  * @css: the target css
5062  *
5063  * Returns %true if @css has any online children; otherwise, %false.  This
5064  * function can be called from any context but the caller is responsible
5065  * for synchronizing against on/offlining as necessary.
5066  */
5067 bool css_has_online_children(struct cgroup_subsys_state *css)
5068 {
5069 	struct cgroup_subsys_state *child;
5070 	bool ret = false;
5071 
5072 	rcu_read_lock();
5073 	css_for_each_child(child, css) {
5074 		if (css_is_online(child)) {
5075 			ret = true;
5076 			break;
5077 		}
5078 	}
5079 	rcu_read_unlock();
5080 	return ret;
5081 }
5082 
5083 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
5084 {
5085 	struct list_head *l;
5086 	struct cgrp_cset_link *link;
5087 	struct css_set *cset;
5088 
5089 	lockdep_assert_held(&css_set_lock);
5090 
5091 	/* find the next threaded cset */
5092 	if (it->tcset_pos) {
5093 		l = it->tcset_pos->next;
5094 
5095 		if (l != it->tcset_head) {
5096 			it->tcset_pos = l;
5097 			return container_of(l, struct css_set,
5098 					    threaded_csets_node);
5099 		}
5100 
5101 		it->tcset_pos = NULL;
5102 	}
5103 
5104 	/* find the next cset */
5105 	l = it->cset_pos;
5106 	l = l->next;
5107 	if (l == it->cset_head) {
5108 		it->cset_pos = NULL;
5109 		return NULL;
5110 	}
5111 
5112 	if (it->ss) {
5113 		cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
5114 	} else {
5115 		link = list_entry(l, struct cgrp_cset_link, cset_link);
5116 		cset = link->cset;
5117 	}
5118 
5119 	it->cset_pos = l;
5120 
5121 	/* initialize threaded css_set walking */
5122 	if (it->flags & CSS_TASK_ITER_THREADED) {
5123 		if (it->cur_dcset)
5124 			put_css_set_locked(it->cur_dcset);
5125 		it->cur_dcset = cset;
5126 		get_css_set(cset);
5127 
5128 		it->tcset_head = &cset->threaded_csets;
5129 		it->tcset_pos = &cset->threaded_csets;
5130 	}
5131 
5132 	return cset;
5133 }
5134 
5135 /**
5136  * css_task_iter_advance_css_set - advance a task iterator to the next css_set
5137  * @it: the iterator to advance
5138  *
5139  * Advance @it to the next css_set to walk.
5140  */
5141 static void css_task_iter_advance_css_set(struct css_task_iter *it)
5142 {
5143 	struct css_set *cset;
5144 
5145 	lockdep_assert_held(&css_set_lock);
5146 
5147 	/* Advance to the next non-empty css_set and find first non-empty tasks list*/
5148 	while ((cset = css_task_iter_next_css_set(it))) {
5149 		if (!list_empty(&cset->tasks)) {
5150 			it->cur_tasks_head = &cset->tasks;
5151 			break;
5152 		} else if (!list_empty(&cset->mg_tasks)) {
5153 			it->cur_tasks_head = &cset->mg_tasks;
5154 			break;
5155 		} else if (!list_empty(&cset->dying_tasks)) {
5156 			it->cur_tasks_head = &cset->dying_tasks;
5157 			break;
5158 		}
5159 	}
5160 	if (!cset) {
5161 		it->task_pos = NULL;
5162 		return;
5163 	}
5164 	it->task_pos = it->cur_tasks_head->next;
5165 
5166 	/*
5167 	 * We don't keep css_sets locked across iteration steps and thus
5168 	 * need to take steps to ensure that iteration can be resumed after
5169 	 * the lock is re-acquired.  Iteration is performed at two levels -
5170 	 * css_sets and tasks in them.
5171 	 *
5172 	 * Once created, a css_set never leaves its cgroup lists, so a
5173 	 * pinned css_set is guaranteed to stay put and we can resume
5174 	 * iteration afterwards.
5175 	 *
5176 	 * Tasks may leave @cset across iteration steps.  This is resolved
5177 	 * by registering each iterator with the css_set currently being
5178 	 * walked and making css_set_move_task() advance iterators whose
5179 	 * next task is leaving.
5180 	 */
5181 	if (it->cur_cset) {
5182 		list_del(&it->iters_node);
5183 		put_css_set_locked(it->cur_cset);
5184 	}
5185 	get_css_set(cset);
5186 	it->cur_cset = cset;
5187 	list_add(&it->iters_node, &cset->task_iters);
5188 }
5189 
5190 static void css_task_iter_skip(struct css_task_iter *it,
5191 			       struct task_struct *task)
5192 {
5193 	lockdep_assert_held(&css_set_lock);
5194 
5195 	if (it->task_pos == &task->cg_list) {
5196 		it->task_pos = it->task_pos->next;
5197 		it->flags |= CSS_TASK_ITER_SKIPPED;
5198 	}
5199 }
5200 
5201 static void css_task_iter_advance(struct css_task_iter *it)
5202 {
5203 	struct task_struct *task;
5204 
5205 	lockdep_assert_held(&css_set_lock);
5206 repeat:
5207 	if (it->task_pos) {
5208 		/*
5209 		 * Advance iterator to find next entry. We go through cset
5210 		 * tasks, mg_tasks and dying_tasks, when consumed we move onto
5211 		 * the next cset.
5212 		 */
5213 		if (it->flags & CSS_TASK_ITER_SKIPPED)
5214 			it->flags &= ~CSS_TASK_ITER_SKIPPED;
5215 		else
5216 			it->task_pos = it->task_pos->next;
5217 
5218 		if (it->task_pos == &it->cur_cset->tasks) {
5219 			it->cur_tasks_head = &it->cur_cset->mg_tasks;
5220 			it->task_pos = it->cur_tasks_head->next;
5221 		}
5222 		if (it->task_pos == &it->cur_cset->mg_tasks) {
5223 			it->cur_tasks_head = &it->cur_cset->dying_tasks;
5224 			it->task_pos = it->cur_tasks_head->next;
5225 		}
5226 		if (it->task_pos == &it->cur_cset->dying_tasks)
5227 			css_task_iter_advance_css_set(it);
5228 	} else {
5229 		/* called from start, proceed to the first cset */
5230 		css_task_iter_advance_css_set(it);
5231 	}
5232 
5233 	if (!it->task_pos)
5234 		return;
5235 
5236 	task = list_entry(it->task_pos, struct task_struct, cg_list);
5237 	/*
5238 	 * Hide tasks that are exiting but not yet removed by default. Keep
5239 	 * zombie leaders with live threads visible. Usages that need to walk
5240 	 * every existing task can opt out via CSS_TASK_ITER_WITH_DEAD.
5241 	 */
5242 	if (!(it->flags & CSS_TASK_ITER_WITH_DEAD) &&
5243 	    (task->flags & PF_EXITING) && !atomic_read(&task->signal->live))
5244 		goto repeat;
5245 
5246 	if (it->flags & CSS_TASK_ITER_PROCS) {
5247 		/* if PROCS, skip over tasks which aren't group leaders */
5248 		if (!thread_group_leader(task))
5249 			goto repeat;
5250 
5251 		/* and dying leaders w/o live member threads */
5252 		if (it->cur_tasks_head == &it->cur_cset->dying_tasks &&
5253 		    !atomic_read(&task->signal->live))
5254 			goto repeat;
5255 	} else {
5256 		/* skip all dying ones */
5257 		if (it->cur_tasks_head == &it->cur_cset->dying_tasks)
5258 			goto repeat;
5259 	}
5260 }
5261 
5262 /**
5263  * css_task_iter_start - initiate task iteration
5264  * @css: the css to walk tasks of
5265  * @flags: CSS_TASK_ITER_* flags
5266  * @it: the task iterator to use
5267  *
5268  * Initiate iteration through the tasks of @css.  The caller can call
5269  * css_task_iter_next() to walk through the tasks until the function
5270  * returns NULL.  On completion of iteration, css_task_iter_end() must be
5271  * called.
5272  */
5273 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
5274 			 struct css_task_iter *it)
5275 {
5276 	unsigned long irqflags;
5277 
5278 	memset(it, 0, sizeof(*it));
5279 
5280 	spin_lock_irqsave(&css_set_lock, irqflags);
5281 
5282 	it->ss = css->ss;
5283 	it->flags = flags;
5284 
5285 	if (CGROUP_HAS_SUBSYS_CONFIG && it->ss)
5286 		it->cset_pos = &css->cgroup->e_csets[css->ss->id];
5287 	else
5288 		it->cset_pos = &css->cgroup->cset_links;
5289 
5290 	it->cset_head = it->cset_pos;
5291 
5292 	css_task_iter_advance(it);
5293 
5294 	spin_unlock_irqrestore(&css_set_lock, irqflags);
5295 }
5296 
5297 /**
5298  * css_task_iter_next - return the next task for the iterator
5299  * @it: the task iterator being iterated
5300  *
5301  * The "next" function for task iteration.  @it should have been
5302  * initialized via css_task_iter_start().  Returns NULL when the iteration
5303  * reaches the end.
5304  */
5305 struct task_struct *css_task_iter_next(struct css_task_iter *it)
5306 {
5307 	unsigned long irqflags;
5308 
5309 	if (it->cur_task) {
5310 		put_task_struct(it->cur_task);
5311 		it->cur_task = NULL;
5312 	}
5313 
5314 	spin_lock_irqsave(&css_set_lock, irqflags);
5315 
5316 	/* @it may be half-advanced by skips, finish advancing */
5317 	if (it->flags & CSS_TASK_ITER_SKIPPED)
5318 		css_task_iter_advance(it);
5319 
5320 	while (it->task_pos && !it->cur_task) {
5321 		it->cur_task = list_entry(it->task_pos, struct task_struct,
5322 					  cg_list);
5323 		/* a task on dying_tasks with zero refcount is only valid for
5324 		 * RCU readers, not even interesting for
5325 		 * CSS_TASK_ITER_WITH_DEAD, find another one */
5326 		it->cur_task = tryget_task_struct(it->cur_task);
5327 		css_task_iter_advance(it);
5328 	}
5329 
5330 	spin_unlock_irqrestore(&css_set_lock, irqflags);
5331 
5332 	return it->cur_task;
5333 }
5334 
5335 /**
5336  * css_task_iter_end - finish task iteration
5337  * @it: the task iterator to finish
5338  *
5339  * Finish task iteration started by css_task_iter_start().
5340  */
5341 void css_task_iter_end(struct css_task_iter *it)
5342 {
5343 	unsigned long irqflags;
5344 
5345 	if (it->cur_cset) {
5346 		spin_lock_irqsave(&css_set_lock, irqflags);
5347 		list_del(&it->iters_node);
5348 		put_css_set_locked(it->cur_cset);
5349 		spin_unlock_irqrestore(&css_set_lock, irqflags);
5350 	}
5351 
5352 	if (it->cur_dcset)
5353 		put_css_set(it->cur_dcset);
5354 
5355 	if (it->cur_task)
5356 		put_task_struct(it->cur_task);
5357 }
5358 
5359 static void cgroup_procs_release(struct kernfs_open_file *of)
5360 {
5361 	struct cgroup_file_ctx *ctx = of->priv;
5362 
5363 	if (ctx->procs.started)
5364 		css_task_iter_end(&ctx->procs.iter);
5365 }
5366 
5367 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
5368 {
5369 	struct kernfs_open_file *of = s->private;
5370 	struct cgroup_file_ctx *ctx = of->priv;
5371 
5372 	if (pos)
5373 		(*pos)++;
5374 
5375 	return css_task_iter_next(&ctx->procs.iter);
5376 }
5377 
5378 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
5379 				  unsigned int iter_flags)
5380 {
5381 	struct kernfs_open_file *of = s->private;
5382 	struct cgroup *cgrp = seq_css(s)->cgroup;
5383 	struct cgroup_file_ctx *ctx = of->priv;
5384 	struct css_task_iter *it = &ctx->procs.iter;
5385 
5386 	/*
5387 	 * When a seq_file is seeked, it's always traversed sequentially
5388 	 * from position 0, so we can simply keep iterating on !0 *pos.
5389 	 */
5390 	if (!ctx->procs.started) {
5391 		if (WARN_ON_ONCE((*pos)))
5392 			return ERR_PTR(-EINVAL);
5393 		css_task_iter_start(&cgrp->self, iter_flags, it);
5394 		ctx->procs.started = true;
5395 	} else if (!(*pos)) {
5396 		css_task_iter_end(it);
5397 		css_task_iter_start(&cgrp->self, iter_flags, it);
5398 	} else
5399 		return it->cur_task;
5400 
5401 	return cgroup_procs_next(s, NULL, NULL);
5402 }
5403 
5404 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
5405 {
5406 	struct cgroup *cgrp = seq_css(s)->cgroup;
5407 
5408 	/*
5409 	 * All processes of a threaded subtree belong to the domain cgroup
5410 	 * of the subtree.  Only threads can be distributed across the
5411 	 * subtree.  Reject reads on cgroup.procs in the subtree proper.
5412 	 * They're always empty anyway.
5413 	 */
5414 	if (cgroup_is_threaded(cgrp))
5415 		return ERR_PTR(-EOPNOTSUPP);
5416 
5417 	return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
5418 					    CSS_TASK_ITER_THREADED);
5419 }
5420 
5421 static int cgroup_procs_show(struct seq_file *s, void *v)
5422 {
5423 	seq_printf(s, "%d\n", task_pid_vnr(v));
5424 	return 0;
5425 }
5426 
5427 static int cgroup_may_write(const struct cgroup *cgrp, struct super_block *sb)
5428 {
5429 	int ret;
5430 	struct inode *inode;
5431 
5432 	lockdep_assert_held(&cgroup_mutex);
5433 
5434 	inode = kernfs_get_inode(sb, cgrp->procs_file.kn);
5435 	if (!inode)
5436 		return -ENOMEM;
5437 
5438 	ret = inode_permission(&nop_mnt_idmap, inode, MAY_WRITE);
5439 	iput(inode);
5440 	return ret;
5441 }
5442 
5443 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
5444 					 struct cgroup *dst_cgrp,
5445 					 struct super_block *sb,
5446 					 struct cgroup_namespace *ns)
5447 {
5448 	struct cgroup *com_cgrp = src_cgrp;
5449 	int ret;
5450 
5451 	lockdep_assert_held(&cgroup_mutex);
5452 
5453 	/* find the common ancestor */
5454 	while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
5455 		com_cgrp = cgroup_parent(com_cgrp);
5456 
5457 	/* %current should be authorized to migrate to the common ancestor */
5458 	ret = cgroup_may_write(com_cgrp, sb);
5459 	if (ret)
5460 		return ret;
5461 
5462 	/*
5463 	 * If namespaces are delegation boundaries, %current must be able
5464 	 * to see both source and destination cgroups from its namespace.
5465 	 */
5466 	if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
5467 	    (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
5468 	     !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
5469 		return -ENOENT;
5470 
5471 	return 0;
5472 }
5473 
5474 static int cgroup_attach_permissions(struct cgroup *src_cgrp,
5475 				     struct cgroup *dst_cgrp,
5476 				     struct super_block *sb, bool threadgroup,
5477 				     struct cgroup_namespace *ns)
5478 {
5479 	int ret = 0;
5480 
5481 	ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp, sb, ns);
5482 	if (ret)
5483 		return ret;
5484 
5485 	ret = cgroup_migrate_vet_dst(dst_cgrp);
5486 	if (ret)
5487 		return ret;
5488 
5489 	if (!threadgroup && (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp))
5490 		ret = -EOPNOTSUPP;
5491 
5492 	return ret;
5493 }
5494 
5495 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
5496 				    bool threadgroup)
5497 {
5498 	struct cgroup_file_ctx *ctx = of->priv;
5499 	struct cgroup *src_cgrp, *dst_cgrp;
5500 	struct task_struct *task;
5501 	ssize_t ret;
5502 	enum cgroup_attach_lock_mode lock_mode;
5503 
5504 	dst_cgrp = cgroup_kn_lock_live(of->kn, false);
5505 	if (IS_ERR(dst_cgrp))
5506 		return PTR_ERR(dst_cgrp);
5507 
5508 	task = cgroup_procs_write_start(buf, threadgroup, &lock_mode);
5509 	ret = PTR_ERR_OR_ZERO(task);
5510 	if (ret)
5511 		goto out_unlock;
5512 
5513 	/* find the source cgroup */
5514 	spin_lock_irq(&css_set_lock);
5515 	src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
5516 	spin_unlock_irq(&css_set_lock);
5517 
5518 	/*
5519 	 * Process and thread migrations follow same delegation rule. Check
5520 	 * permissions using the credentials from file open to protect against
5521 	 * inherited fd attacks.
5522 	 */
5523 	scoped_with_creds(of->file->f_cred)
5524 		ret = cgroup_attach_permissions(src_cgrp, dst_cgrp,
5525 						of->file->f_path.dentry->d_sb,
5526 						threadgroup, ctx->ns);
5527 	if (ret)
5528 		goto out_finish;
5529 
5530 	ret = cgroup_attach_task(dst_cgrp, task, threadgroup);
5531 
5532 out_finish:
5533 	cgroup_procs_write_finish(task, lock_mode);
5534 out_unlock:
5535 	cgroup_kn_unlock(of->kn);
5536 
5537 	return ret;
5538 }
5539 
5540 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
5541 				  char *buf, size_t nbytes, loff_t off)
5542 {
5543 	return __cgroup_procs_write(of, buf, true) ?: nbytes;
5544 }
5545 
5546 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
5547 {
5548 	return __cgroup_procs_start(s, pos, 0);
5549 }
5550 
5551 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
5552 				    char *buf, size_t nbytes, loff_t off)
5553 {
5554 	return __cgroup_procs_write(of, buf, false) ?: nbytes;
5555 }
5556 
5557 /* cgroup core interface files for the default hierarchy */
5558 static struct cftype cgroup_base_files[] = {
5559 	{
5560 		.name = "cgroup.type",
5561 		.flags = CFTYPE_NOT_ON_ROOT,
5562 		.seq_show = cgroup_type_show,
5563 		.write = cgroup_type_write,
5564 	},
5565 	{
5566 		.name = "cgroup.procs",
5567 		.flags = CFTYPE_NS_DELEGATABLE,
5568 		.file_offset = offsetof(struct cgroup, procs_file),
5569 		.release = cgroup_procs_release,
5570 		.seq_start = cgroup_procs_start,
5571 		.seq_next = cgroup_procs_next,
5572 		.seq_show = cgroup_procs_show,
5573 		.write = cgroup_procs_write,
5574 	},
5575 	{
5576 		.name = "cgroup.threads",
5577 		.flags = CFTYPE_NS_DELEGATABLE,
5578 		.release = cgroup_procs_release,
5579 		.seq_start = cgroup_threads_start,
5580 		.seq_next = cgroup_procs_next,
5581 		.seq_show = cgroup_procs_show,
5582 		.write = cgroup_threads_write,
5583 	},
5584 	{
5585 		.name = "cgroup.controllers",
5586 		.seq_show = cgroup_controllers_show,
5587 	},
5588 	{
5589 		.name = "cgroup.subtree_control",
5590 		.flags = CFTYPE_NS_DELEGATABLE,
5591 		.seq_show = cgroup_subtree_control_show,
5592 		.write = cgroup_subtree_control_write,
5593 	},
5594 	{
5595 		.name = "cgroup.events",
5596 		.flags = CFTYPE_NOT_ON_ROOT,
5597 		.file_offset = offsetof(struct cgroup, events_file),
5598 		.seq_show = cgroup_events_show,
5599 	},
5600 	{
5601 		.name = "cgroup.max.descendants",
5602 		.seq_show = cgroup_max_descendants_show,
5603 		.write = cgroup_max_descendants_write,
5604 	},
5605 	{
5606 		.name = "cgroup.max.depth",
5607 		.seq_show = cgroup_max_depth_show,
5608 		.write = cgroup_max_depth_write,
5609 	},
5610 	{
5611 		.name = "cgroup.stat",
5612 		.seq_show = cgroup_stat_show,
5613 	},
5614 	{
5615 		.name = "cgroup.stat.local",
5616 		.flags = CFTYPE_NOT_ON_ROOT,
5617 		.seq_show = cgroup_core_local_stat_show,
5618 	},
5619 	{
5620 		.name = "cgroup.freeze",
5621 		.flags = CFTYPE_NOT_ON_ROOT,
5622 		.seq_show = cgroup_freeze_show,
5623 		.write = cgroup_freeze_write,
5624 	},
5625 	{
5626 		.name = "cgroup.kill",
5627 		.flags = CFTYPE_NOT_ON_ROOT,
5628 		.write = cgroup_kill_write,
5629 	},
5630 	{
5631 		.name = "cpu.stat",
5632 		.seq_show = cpu_stat_show,
5633 	},
5634 	{
5635 		.name = "cpu.stat.local",
5636 		.seq_show = cpu_local_stat_show,
5637 	},
5638 	{ }	/* terminate */
5639 };
5640 
5641 static struct cftype cgroup_psi_files[] = {
5642 #ifdef CONFIG_PSI
5643 	{
5644 		.name = "io.pressure",
5645 		.file_offset = offsetof(struct cgroup, psi_files[PSI_IO]),
5646 		.seq_show = cgroup_io_pressure_show,
5647 		.write = cgroup_io_pressure_write,
5648 		.poll = cgroup_pressure_poll,
5649 		.release = cgroup_pressure_release,
5650 	},
5651 	{
5652 		.name = "memory.pressure",
5653 		.file_offset = offsetof(struct cgroup, psi_files[PSI_MEM]),
5654 		.seq_show = cgroup_memory_pressure_show,
5655 		.write = cgroup_memory_pressure_write,
5656 		.poll = cgroup_pressure_poll,
5657 		.release = cgroup_pressure_release,
5658 	},
5659 	{
5660 		.name = "cpu.pressure",
5661 		.file_offset = offsetof(struct cgroup, psi_files[PSI_CPU]),
5662 		.seq_show = cgroup_cpu_pressure_show,
5663 		.write = cgroup_cpu_pressure_write,
5664 		.poll = cgroup_pressure_poll,
5665 		.release = cgroup_pressure_release,
5666 	},
5667 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
5668 	{
5669 		.name = "irq.pressure",
5670 		.file_offset = offsetof(struct cgroup, psi_files[PSI_IRQ]),
5671 		.seq_show = cgroup_irq_pressure_show,
5672 		.write = cgroup_irq_pressure_write,
5673 		.poll = cgroup_pressure_poll,
5674 		.release = cgroup_pressure_release,
5675 	},
5676 #endif
5677 	{
5678 		.name = "cgroup.pressure",
5679 		.seq_show = cgroup_pressure_show,
5680 		.write = cgroup_pressure_write,
5681 	},
5682 #endif /* CONFIG_PSI */
5683 	{ }	/* terminate */
5684 };
5685 
5686 /*
5687  * css destruction is four-stage process.
5688  *
5689  * 1. Destruction starts.  Killing of the percpu_ref is initiated.
5690  *    Implemented in kill_css_finish().
5691  *
5692  * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
5693  *    and thus css_tryget_online() is guaranteed to fail, the css can be
5694  *    offlined by invoking offline_css().  After offlining, the base ref is
5695  *    put.  Implemented in css_killed_work_fn().
5696  *
5697  * 3. When the percpu_ref reaches zero, the only possible remaining
5698  *    accessors are inside RCU read sections.  css_release() schedules the
5699  *    RCU callback.
5700  *
5701  * 4. After the grace period, the css can be freed.  Implemented in
5702  *    css_free_rwork_fn().
5703  *
5704  * It is actually hairier because both step 2 and 4 require process context
5705  * and thus involve punting to css->destroy_work adding two additional
5706  * steps to the already complex sequence.
5707  */
5708 static void css_free_rwork_fn(struct work_struct *work)
5709 {
5710 	struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
5711 				struct cgroup_subsys_state, destroy_rwork);
5712 	struct cgroup_subsys *ss = css->ss;
5713 	struct cgroup *cgrp = css->cgroup;
5714 
5715 	percpu_ref_exit(&css->refcnt);
5716 	css_rstat_exit(css);
5717 
5718 	if (!css_is_self(css)) {
5719 		/* css free path */
5720 		struct cgroup_subsys_state *parent = css->parent;
5721 		int id = css->id;
5722 
5723 		ss->css_free(css);
5724 		cgroup_idr_remove(&ss->css_idr, id);
5725 		cgroup_put(cgrp);
5726 
5727 		if (parent)
5728 			css_put(parent);
5729 	} else {
5730 		/* cgroup free path */
5731 		atomic_dec(&cgrp->root->nr_cgrps);
5732 		if (!cgroup_on_dfl(cgrp))
5733 			cgroup1_pidlist_destroy_all(cgrp);
5734 		cancel_work_sync(&cgrp->release_agent_work);
5735 		bpf_cgrp_storage_free(cgrp);
5736 
5737 		if (cgroup_parent(cgrp)) {
5738 			/*
5739 			 * We get a ref to the parent, and put the ref when
5740 			 * this cgroup is being freed, so it's guaranteed
5741 			 * that the parent won't be destroyed before its
5742 			 * children.
5743 			 */
5744 			cgroup_put(cgroup_parent(cgrp));
5745 			kernfs_put(cgrp->kn);
5746 			psi_cgroup_free(cgrp);
5747 			kfree(cgrp);
5748 		} else {
5749 			/*
5750 			 * This is root cgroup's refcnt reaching zero,
5751 			 * which indicates that the root should be
5752 			 * released.
5753 			 */
5754 			cgroup_destroy_root(cgrp->root);
5755 		}
5756 	}
5757 }
5758 
5759 static void css_release_work_fn(struct work_struct *work)
5760 {
5761 	struct cgroup_subsys_state *css =
5762 		container_of(work, struct cgroup_subsys_state, destroy_work);
5763 	struct cgroup_subsys *ss = css->ss;
5764 	struct cgroup *cgrp = css->cgroup;
5765 
5766 	cgroup_lock();
5767 
5768 	css->flags |= CSS_RELEASED;
5769 	list_del_rcu(&css->sibling);
5770 
5771 	if (!css_is_self(css)) {
5772 		struct cgroup *parent_cgrp;
5773 
5774 		css_rstat_flush(css);
5775 
5776 		cgroup_idr_replace(&ss->css_idr, NULL, css->id);
5777 		if (ss->css_released)
5778 			ss->css_released(css);
5779 
5780 		cgrp->nr_dying_subsys[ss->id]--;
5781 		/*
5782 		 * When a css is released and ready to be freed, its
5783 		 * nr_descendants must be zero. However, the corresponding
5784 		 * cgrp->nr_dying_subsys[ss->id] may not be 0 if a subsystem
5785 		 * is activated and deactivated multiple times with one or
5786 		 * more of its previous activation leaving behind dying csses.
5787 		 */
5788 		WARN_ON_ONCE(css->nr_descendants);
5789 		parent_cgrp = cgroup_parent(cgrp);
5790 		while (parent_cgrp) {
5791 			parent_cgrp->nr_dying_subsys[ss->id]--;
5792 			parent_cgrp = cgroup_parent(parent_cgrp);
5793 		}
5794 	} else {
5795 		struct cgroup *tcgrp;
5796 
5797 		/* cgroup release path */
5798 		TRACE_CGROUP_PATH(release, cgrp);
5799 
5800 		css_rstat_flush(&cgrp->self);
5801 
5802 		spin_lock_irq(&css_set_lock);
5803 		for (tcgrp = cgroup_parent(cgrp); tcgrp;
5804 		     tcgrp = cgroup_parent(tcgrp))
5805 			tcgrp->nr_dying_descendants--;
5806 		spin_unlock_irq(&css_set_lock);
5807 
5808 		/*
5809 		 * There are two control paths which try to determine
5810 		 * cgroup from dentry without going through kernfs -
5811 		 * cgroupstats_build() and css_tryget_online_from_dir().
5812 		 * Those are supported by RCU protecting clearing of
5813 		 * cgrp->kn->priv backpointer.
5814 		 */
5815 		if (cgrp->kn)
5816 			RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
5817 					 NULL);
5818 	}
5819 
5820 	cgroup_unlock();
5821 
5822 	INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5823 	queue_rcu_work(cgroup_free_wq, &css->destroy_rwork);
5824 }
5825 
5826 static void css_release(struct percpu_ref *ref)
5827 {
5828 	struct cgroup_subsys_state *css =
5829 		container_of(ref, struct cgroup_subsys_state, refcnt);
5830 
5831 	INIT_WORK(&css->destroy_work, css_release_work_fn);
5832 	queue_work(cgroup_release_wq, &css->destroy_work);
5833 }
5834 
5835 /*
5836  * Deferred kill_css_finish() fired from css_update_populated() once a dying
5837  * css's hierarchical populated state drops to zero. Pinned by css_get() at the
5838  * queue site; matched by css_put() here.
5839  */
5840 static void kill_css_finish_work_fn(struct work_struct *work)
5841 {
5842 	struct cgroup_subsys_state *css =
5843 		container_of(work, struct cgroup_subsys_state, kill_finish_work);
5844 
5845 	cgroup_lock();
5846 	kill_css_finish(css);
5847 	cgroup_unlock();
5848 	css_put(css);
5849 }
5850 
5851 static void init_and_link_css(struct cgroup_subsys_state *css,
5852 			      struct cgroup_subsys *ss, struct cgroup *cgrp)
5853 {
5854 	lockdep_assert_held(&cgroup_mutex);
5855 
5856 	cgroup_get_live(cgrp);
5857 
5858 	memset(css, 0, sizeof(*css));
5859 	css->cgroup = cgrp;
5860 	css->ss = ss;
5861 	css->id = -1;
5862 	INIT_LIST_HEAD(&css->sibling);
5863 	INIT_LIST_HEAD(&css->children);
5864 	INIT_WORK(&css->kill_finish_work, kill_css_finish_work_fn);
5865 	css->serial_nr = css_serial_nr_next++;
5866 	atomic_set(&css->online_cnt, 0);
5867 
5868 	if (cgroup_parent(cgrp)) {
5869 		css->parent = cgroup_css(cgroup_parent(cgrp), ss);
5870 		css_get(css->parent);
5871 	}
5872 
5873 	BUG_ON(cgroup_css(cgrp, ss));
5874 }
5875 
5876 static void cgroup_update_e_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
5877 {
5878 	struct cgroup_subsys_state *d_css;
5879 
5880 	lockdep_assert_held(&cgroup_mutex);
5881 
5882 	css_for_each_descendant_pre(d_css, &cgrp->self) {
5883 		struct cgroup *dsct = d_css->cgroup;
5884 		struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
5885 
5886 		if (!css)
5887 			css = cgroup_e_css(cgroup_parent(dsct), ss);
5888 		rcu_assign_pointer(dsct->e_css[ss->id], css);
5889 	}
5890 }
5891 
5892 /* invoke ->css_online() on a new CSS and mark it online if successful */
5893 static int online_css(struct cgroup_subsys_state *css)
5894 {
5895 	struct cgroup_subsys *ss = css->ss;
5896 	int ret = 0;
5897 
5898 	lockdep_assert_held(&cgroup_mutex);
5899 
5900 	if (ss->css_online)
5901 		ret = ss->css_online(css);
5902 	if (!ret) {
5903 		css->flags |= CSS_ONLINE;
5904 		rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
5905 		cgroup_update_e_css(css->cgroup, ss);
5906 
5907 		atomic_inc(&css->online_cnt);
5908 		if (css->parent) {
5909 			atomic_inc(&css->parent->online_cnt);
5910 			while ((css = css->parent))
5911 				css->nr_descendants++;
5912 		}
5913 	}
5914 	return ret;
5915 }
5916 
5917 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
5918 static void offline_css(struct cgroup_subsys_state *css)
5919 {
5920 	struct cgroup_subsys *ss = css->ss;
5921 
5922 	lockdep_assert_held(&cgroup_mutex);
5923 
5924 	if (!css_is_online(css))
5925 		return;
5926 
5927 	if (ss->css_offline)
5928 		ss->css_offline(css);
5929 
5930 	css->flags &= ~CSS_ONLINE;
5931 	RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
5932 	cgroup_update_e_css(css->cgroup, ss);
5933 
5934 	wake_up_all(&css->cgroup->offline_waitq);
5935 }
5936 
5937 /**
5938  * css_create - create a cgroup_subsys_state
5939  * @cgrp: the cgroup new css will be associated with
5940  * @ss: the subsys of new css
5941  *
5942  * Create a new css associated with @cgrp - @ss pair.  On success, the new
5943  * css is online and installed in @cgrp.  This function doesn't create the
5944  * interface files.  Returns 0 on success, -errno on failure.
5945  */
5946 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
5947 					      struct cgroup_subsys *ss)
5948 {
5949 	struct cgroup *parent = cgroup_parent(cgrp);
5950 	struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
5951 	struct cgroup_subsys_state *css;
5952 	int err;
5953 
5954 	lockdep_assert_held(&cgroup_mutex);
5955 
5956 	css = ss->css_alloc(parent_css);
5957 	if (!css)
5958 		css = ERR_PTR(-ENOMEM);
5959 	if (IS_ERR(css))
5960 		return css;
5961 
5962 	init_and_link_css(css, ss, cgrp);
5963 
5964 	err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
5965 	if (err)
5966 		goto err_free_css;
5967 
5968 	err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
5969 	if (err < 0)
5970 		goto err_free_css;
5971 	css->id = err;
5972 
5973 	err = css_rstat_init(css);
5974 	if (err)
5975 		goto err_free_css;
5976 
5977 	/* @css is ready to be brought online now, make it visible */
5978 	list_add_tail_rcu(&css->sibling, &parent_css->children);
5979 	cgroup_idr_replace(&ss->css_idr, css, css->id);
5980 
5981 	err = online_css(css);
5982 	if (err)
5983 		goto err_list_del;
5984 
5985 	return css;
5986 
5987 err_list_del:
5988 	list_del_rcu(&css->sibling);
5989 err_free_css:
5990 	INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5991 	queue_rcu_work(cgroup_free_wq, &css->destroy_rwork);
5992 	return ERR_PTR(err);
5993 }
5994 
5995 /*
5996  * The returned cgroup is fully initialized including its control mask, but
5997  * it doesn't have the control mask applied.
5998  */
5999 static struct cgroup *cgroup_create(struct cgroup *parent, const char *name,
6000 				    umode_t mode)
6001 {
6002 	struct cgroup_root *root = parent->root;
6003 	struct cgroup *cgrp, *tcgrp;
6004 	struct cgroup_subsys *ss;
6005 	struct kernfs_node *kn;
6006 	int i, level = parent->level + 1;
6007 	int ret;
6008 
6009 	/* allocate the cgroup and its ID, 0 is reserved for the root */
6010 	cgrp = kzalloc_flex(*cgrp, _low_ancestors, level);
6011 	if (!cgrp)
6012 		return ERR_PTR(-ENOMEM);
6013 
6014 	ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
6015 	if (ret)
6016 		goto out_free_cgrp;
6017 
6018 	/* create the directory */
6019 	kn = kernfs_create_dir_ns(parent->kn, name, mode,
6020 				  current_fsuid(), current_fsgid(),
6021 				  cgrp, NULL);
6022 	if (IS_ERR(kn)) {
6023 		ret = PTR_ERR(kn);
6024 		goto out_cancel_ref;
6025 	}
6026 	cgrp->kn = kn;
6027 
6028 	init_cgroup_housekeeping(cgrp);
6029 
6030 	cgrp->self.parent = &parent->self;
6031 	cgrp->root = root;
6032 	cgrp->level = level;
6033 
6034 	/*
6035 	 * Now that init_cgroup_housekeeping() has been called and cgrp->self
6036 	 * is setup, it is safe to perform rstat initialization on it.
6037 	 */
6038 	ret = css_rstat_init(&cgrp->self);
6039 	if (ret)
6040 		goto out_kernfs_remove;
6041 
6042 	ret = psi_cgroup_alloc(cgrp);
6043 	if (ret)
6044 		goto out_stat_exit;
6045 
6046 	for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp))
6047 		cgrp->ancestors[tcgrp->level] = tcgrp;
6048 
6049 	for_each_subsys(ss, i)
6050 		RCU_INIT_POINTER(cgrp->e_css[i], cgroup_e_css(parent, ss));
6051 
6052 	/*
6053 	 * New cgroup inherits effective freeze counter, and
6054 	 * if the parent has to be frozen, the child has too.
6055 	 */
6056 	cgrp->freezer.e_freeze = parent->freezer.e_freeze;
6057 	seqcount_spinlock_init(&cgrp->freezer.freeze_seq, &css_set_lock);
6058 	if (cgrp->freezer.e_freeze) {
6059 		/*
6060 		 * Set the CGRP_FREEZE flag, so when a process will be
6061 		 * attached to the child cgroup, it will become frozen.
6062 		 * At this point the new cgroup is unpopulated, so we can
6063 		 * consider it frozen immediately.
6064 		 */
6065 		set_bit(CGRP_FREEZE, &cgrp->flags);
6066 		cgrp->freezer.freeze_start_nsec = ktime_get_ns();
6067 		set_bit(CGRP_FROZEN, &cgrp->flags);
6068 	}
6069 
6070 	if (notify_on_release(parent))
6071 		set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
6072 
6073 	if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
6074 		set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
6075 
6076 	cgrp->self.serial_nr = css_serial_nr_next++;
6077 
6078 	ret = blocking_notifier_call_chain_robust(&cgroup_lifetime_notifier,
6079 						  CGROUP_LIFETIME_ONLINE,
6080 						  CGROUP_LIFETIME_OFFLINE, cgrp);
6081 	ret = notifier_to_errno(ret);
6082 	if (ret)
6083 		goto out_psi_free;
6084 
6085 	/* allocation complete, commit to creation */
6086 	spin_lock_irq(&css_set_lock);
6087 	for (i = 0; i < level; i++) {
6088 		tcgrp = cgrp->ancestors[i];
6089 		tcgrp->nr_descendants++;
6090 
6091 		/*
6092 		 * If the new cgroup is frozen, all ancestor cgroups get a new
6093 		 * frozen descendant, but their state can't change because of
6094 		 * this.
6095 		 */
6096 		if (cgrp->freezer.e_freeze)
6097 			tcgrp->freezer.nr_frozen_descendants++;
6098 	}
6099 	spin_unlock_irq(&css_set_lock);
6100 
6101 	list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
6102 	atomic_inc(&root->nr_cgrps);
6103 	cgroup_get_live(parent);
6104 
6105 	/*
6106 	 * On the default hierarchy, a child doesn't automatically inherit
6107 	 * subtree_control from the parent.  Each is configured manually.
6108 	 */
6109 	if (!cgroup_on_dfl(cgrp))
6110 		cgrp->subtree_control = cgroup_control(cgrp);
6111 
6112 	cgroup_propagate_control(cgrp);
6113 
6114 	return cgrp;
6115 
6116 out_psi_free:
6117 	psi_cgroup_free(cgrp);
6118 out_stat_exit:
6119 	css_rstat_exit(&cgrp->self);
6120 out_kernfs_remove:
6121 	kernfs_remove(cgrp->kn);
6122 out_cancel_ref:
6123 	percpu_ref_exit(&cgrp->self.refcnt);
6124 out_free_cgrp:
6125 	kfree(cgrp);
6126 	return ERR_PTR(ret);
6127 }
6128 
6129 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
6130 {
6131 	struct cgroup *cgroup;
6132 	int ret = false;
6133 	int level = 0;
6134 
6135 	lockdep_assert_held(&cgroup_mutex);
6136 
6137 	for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
6138 		if (cgroup->nr_descendants >= cgroup->max_descendants)
6139 			goto fail;
6140 
6141 		if (level >= cgroup->max_depth)
6142 			goto fail;
6143 
6144 		level++;
6145 	}
6146 
6147 	ret = true;
6148 fail:
6149 	return ret;
6150 }
6151 
6152 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
6153 {
6154 	struct cgroup *parent, *cgrp;
6155 	int ret;
6156 
6157 	/* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
6158 	if (strchr(name, '\n'))
6159 		return -EINVAL;
6160 
6161 	parent = cgroup_kn_lock_live(parent_kn, false);
6162 	if (IS_ERR(parent))
6163 		return PTR_ERR(parent);
6164 
6165 	if (!cgroup_check_hierarchy_limits(parent)) {
6166 		ret = -EAGAIN;
6167 		goto out_unlock;
6168 	}
6169 
6170 	cgrp = cgroup_create(parent, name, mode);
6171 	if (IS_ERR(cgrp)) {
6172 		ret = PTR_ERR(cgrp);
6173 		goto out_unlock;
6174 	}
6175 
6176 	/*
6177 	 * This extra ref will be put in css_free_rwork_fn() and guarantees
6178 	 * that @cgrp->kn is always accessible.
6179 	 */
6180 	kernfs_get(cgrp->kn);
6181 
6182 	ret = css_populate_dir(&cgrp->self);
6183 	if (ret)
6184 		goto out_destroy;
6185 
6186 	ret = cgroup_apply_control_enable(cgrp);
6187 	if (ret)
6188 		goto out_destroy;
6189 
6190 	TRACE_CGROUP_PATH(mkdir, cgrp);
6191 
6192 	/* let's create and online css's */
6193 	kernfs_activate(cgrp->kn);
6194 
6195 	ret = 0;
6196 	goto out_unlock;
6197 
6198 out_destroy:
6199 	cgroup_destroy_locked(cgrp);
6200 out_unlock:
6201 	cgroup_kn_unlock(parent_kn);
6202 	return ret;
6203 }
6204 
6205 /*
6206  * This is called when the refcnt of a css is confirmed to be killed.
6207  * css_tryget_online() is now guaranteed to fail.  Tell the subsystem to
6208  * initiate destruction and put the css ref from kill_css_finish().
6209  */
6210 static void css_killed_work_fn(struct work_struct *work)
6211 {
6212 	struct cgroup_subsys_state *css;
6213 
6214 	css = container_of(to_rcu_work(work), struct cgroup_subsys_state, destroy_rwork);
6215 
6216 	cgroup_lock();
6217 
6218 	do {
6219 		offline_css(css);
6220 		css_put(css);
6221 		/* @css can't go away while we're holding cgroup_mutex */
6222 		css = css->parent;
6223 	} while (css && atomic_dec_and_test(&css->online_cnt));
6224 
6225 	cgroup_unlock();
6226 }
6227 
6228 /* css kill confirmation processing requires process context, bounce */
6229 static void css_killed_ref_fn(struct percpu_ref *ref)
6230 {
6231 	struct cgroup_subsys_state *css =
6232 		container_of(ref, struct cgroup_subsys_state, refcnt);
6233 
6234 	if (atomic_dec_and_test(&css->online_cnt)) {
6235 		INIT_RCU_WORK(&css->destroy_rwork, css_killed_work_fn);
6236 		queue_rcu_work(cgroup_offline_wq, &css->destroy_rwork);
6237 	}
6238 }
6239 
6240 /**
6241  * kill_css_sync - synchronous half of css teardown
6242  * @css: css being killed
6243  *
6244  * See cgroup_destroy_locked().
6245  */
6246 static void kill_css_sync(struct cgroup_subsys_state *css)
6247 {
6248 	struct cgroup_subsys *ss = css->ss;
6249 
6250 	lockdep_assert_held(&cgroup_mutex);
6251 
6252 	if (css->flags & CSS_DYING)
6253 		return;
6254 
6255 	/*
6256 	 * Call css_killed(), if defined, before setting the CSS_DYING flag
6257 	 */
6258 	if (css->ss->css_killed)
6259 		css->ss->css_killed(css);
6260 
6261 	css->flags |= CSS_DYING;
6262 
6263 	/*
6264 	 * Pair with smp_mb() in css_update_populated(). Either our
6265 	 * caller observes the walker's decrement and fires
6266 	 * synchronously, or the walker observes CSS_DYING and queues.
6267 	 */
6268 	smp_mb();
6269 
6270 	/*
6271 	 * This must happen before css is disassociated with its cgroup.
6272 	 * See seq_css() for details.
6273 	 */
6274 	css_clear_dir(css);
6275 
6276 	css->cgroup->nr_dying_subsys[ss->id]++;
6277 	/*
6278 	 * Parent css and cgroup cannot be freed until after the freeing
6279 	 * of child css, see css_free_rwork_fn().
6280 	 */
6281 	while ((css = css->parent)) {
6282 		css->nr_descendants--;
6283 		css->cgroup->nr_dying_subsys[ss->id]++;
6284 	}
6285 }
6286 
6287 /**
6288  * kill_css_finish - deferred half of css teardown
6289  * @css: css being killed
6290  *
6291  * See cgroup_destroy_locked().
6292  */
6293 static void kill_css_finish(struct cgroup_subsys_state *css)
6294 {
6295 	lockdep_assert_held(&cgroup_mutex);
6296 
6297 	/*
6298 	 * Skip on re-entry: cgroup_apply_control_disable() may have killed @css
6299 	 * earlier. cgroup_destroy_locked() can still walk it because
6300 	 * offline_css() (which NULLs cgrp->subsys[ssid]) runs async.
6301 	 */
6302 	if (percpu_ref_is_dying(&css->refcnt))
6303 		return;
6304 
6305 	/*
6306 	 * Killing would put the base ref, but we need to keep it alive until
6307 	 * after ->css_offline().
6308 	 */
6309 	css_get(css);
6310 
6311 	/*
6312 	 * cgroup core guarantees that, by the time ->css_offline() is invoked,
6313 	 * no new css reference will be given out via css_tryget_online(). We
6314 	 * can't simply call percpu_ref_kill() and proceed to offlining css's
6315 	 * because percpu_ref_kill() doesn't guarantee that the ref is seen as
6316 	 * killed on all CPUs on return.
6317 	 *
6318 	 * Use percpu_ref_kill_and_confirm() to get notifications as each css is
6319 	 * confirmed to be seen as killed on all CPUs.
6320 	 */
6321 	percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
6322 }
6323 
6324 /**
6325  * cgroup_destroy_locked - destroy @cgrp (called on rmdir)
6326  * @cgrp: cgroup to be destroyed
6327  *
6328  * Tear down @cgrp on behalf of rmdir. Constraints:
6329  *
6330  * - Userspace: rmdir must succeed when cgroup.procs and friends are empty.
6331  *
6332  * - Kernel: subsystem ->css_offline() must not run while any task in @cgrp's
6333  *   subtree is still doing kernel work. A task hidden from cgroup.procs (past
6334  *   exit_signals() with signal->live cleared) can still schedule, allocate, and
6335  *   consume resources until its final context switch. Dying descendants in the
6336  *   subtree can host such tasks too.
6337  *
6338  * - Kernel: css_tryget_online() must fail by the time ->css_offline() runs.
6339  *
6340  * The destruction runs in three parts:
6341  *
6342  * - This function: synchronous user-visible state teardown plus kill_css_sync()
6343  *   on each subsystem css.
6344  *
6345  * - For each subsys css: fire kill_css_finish() synchronously if the subtree is
6346  *   already drained, otherwise rely on css_update_populated() to queue
6347  *   kill_finish_work when the last populated cset under the css empties.
6348  *
6349  * - The percpu_ref kill chain: css_killed_ref_fn -> css_killed_work_fn ->
6350  *   ->css_offline() -> release/free.
6351  *
6352  * Return 0 on success, -EBUSY if a userspace-visible task or an online child
6353  * remains.
6354  */
6355 static int cgroup_destroy_locked(struct cgroup *cgrp)
6356 {
6357 	struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
6358 	struct cgroup_subsys_state *css;
6359 	struct cgrp_cset_link *link;
6360 	struct css_task_iter it;
6361 	struct task_struct *task;
6362 	int ssid, ret;
6363 
6364 	lockdep_assert_held(&cgroup_mutex);
6365 
6366 	css_task_iter_start(&cgrp->self, 0, &it);
6367 	task = css_task_iter_next(&it);
6368 	css_task_iter_end(&it);
6369 	if (task)
6370 		return -EBUSY;
6371 
6372 	/*
6373 	 * Make sure there's no live children.  We can't test emptiness of
6374 	 * ->self.children as dead children linger on it while being
6375 	 * drained; otherwise, "rmdir parent/child parent" may fail.
6376 	 */
6377 	if (css_has_online_children(&cgrp->self))
6378 		return -EBUSY;
6379 
6380 	/*
6381 	 * Mark @cgrp and the associated csets dead.  The former prevents
6382 	 * further task migration and child creation by disabling
6383 	 * cgroup_kn_lock_live().  The latter makes the csets ignored by
6384 	 * the migration path.
6385 	 */
6386 	cgrp->self.flags &= ~CSS_ONLINE;
6387 
6388 	spin_lock_irq(&css_set_lock);
6389 	list_for_each_entry(link, &cgrp->cset_links, cset_link)
6390 		link->cset->dead = true;
6391 	spin_unlock_irq(&css_set_lock);
6392 
6393 	for_each_css(css, ssid, cgrp)
6394 		kill_css_sync(css);
6395 
6396 	/* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
6397 	css_clear_dir(&cgrp->self);
6398 	kernfs_remove(cgrp->kn);
6399 
6400 	if (cgroup_is_threaded(cgrp))
6401 		parent->nr_threaded_children--;
6402 
6403 	spin_lock_irq(&css_set_lock);
6404 	for (tcgrp = parent; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
6405 		tcgrp->nr_descendants--;
6406 		tcgrp->nr_dying_descendants++;
6407 		/*
6408 		 * If the dying cgroup is frozen, decrease frozen descendants
6409 		 * counters of ancestor cgroups.
6410 		 */
6411 		if (test_bit(CGRP_FROZEN, &cgrp->flags))
6412 			tcgrp->freezer.nr_frozen_descendants--;
6413 	}
6414 	spin_unlock_irq(&css_set_lock);
6415 
6416 	cgroup1_check_for_release(parent);
6417 
6418 	ret = blocking_notifier_call_chain(&cgroup_lifetime_notifier,
6419 					   CGROUP_LIFETIME_OFFLINE, cgrp);
6420 	WARN_ON_ONCE(notifier_to_errno(ret));
6421 
6422 	/* put the base reference */
6423 	percpu_ref_kill(&cgrp->self.refcnt);
6424 
6425 	for_each_css(css, ssid, cgrp) {
6426 		if (!css_is_populated(css))
6427 			kill_css_finish(css);
6428 	}
6429 
6430 	return 0;
6431 };
6432 
6433 int cgroup_rmdir(struct kernfs_node *kn)
6434 {
6435 	struct cgroup *cgrp;
6436 	int ret = 0;
6437 
6438 	cgrp = cgroup_kn_lock_live(kn, false);
6439 	if (IS_ERR(cgrp))
6440 		return 0;
6441 
6442 	ret = cgroup_destroy_locked(cgrp);
6443 	if (!ret)
6444 		TRACE_CGROUP_PATH(rmdir, cgrp);
6445 
6446 	cgroup_kn_unlock(kn);
6447 	return ret;
6448 }
6449 
6450 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
6451 	.show_options		= cgroup_show_options,
6452 	.mkdir			= cgroup_mkdir,
6453 	.rmdir			= cgroup_rmdir,
6454 	.show_path		= cgroup_show_path,
6455 };
6456 
6457 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
6458 {
6459 	struct cgroup_subsys_state *css;
6460 
6461 	pr_debug("Initializing cgroup subsys %s\n", ss->name);
6462 
6463 	cgroup_lock();
6464 
6465 	idr_init(&ss->css_idr);
6466 	INIT_LIST_HEAD(&ss->cfts);
6467 
6468 	/* Create the root cgroup state for this subsystem */
6469 	ss->root = &cgrp_dfl_root;
6470 	css = ss->css_alloc(NULL);
6471 	/* We don't handle early failures gracefully */
6472 	BUG_ON(IS_ERR(css));
6473 	init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
6474 
6475 	/*
6476 	 * Root csses are never destroyed and we can't initialize
6477 	 * percpu_ref during early init.  Disable refcnting.
6478 	 */
6479 	css->flags |= CSS_NO_REF;
6480 
6481 	if (early) {
6482 		/* allocation can't be done safely during early init */
6483 		css->id = 1;
6484 	} else {
6485 		css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
6486 		BUG_ON(css->id < 0);
6487 
6488 		BUG_ON(ss_rstat_init(ss));
6489 		BUG_ON(css_rstat_init(css));
6490 	}
6491 
6492 	/* Update the init_css_set to contain a subsys
6493 	 * pointer to this state - since the subsystem is
6494 	 * newly registered, all tasks and hence the
6495 	 * init_css_set is in the subsystem's root cgroup. */
6496 	init_css_set.subsys[ss->id] = css;
6497 
6498 	have_fork_callback |= (bool)ss->fork << ss->id;
6499 	have_exit_callback |= (bool)ss->exit << ss->id;
6500 	have_release_callback |= (bool)ss->release << ss->id;
6501 	have_canfork_callback |= (bool)ss->can_fork << ss->id;
6502 
6503 	/* At system boot, before all subsystems have been
6504 	 * registered, no tasks have been forked, so we don't
6505 	 * need to invoke fork callbacks here. */
6506 	BUG_ON(!list_empty(&init_task.tasks));
6507 
6508 	BUG_ON(online_css(css));
6509 
6510 	cgroup_unlock();
6511 }
6512 
6513 /**
6514  * cgroup_init_early - cgroup initialization at system boot
6515  *
6516  * Initialize cgroups at system boot, and initialize any
6517  * subsystems that request early init.
6518  */
6519 int __init cgroup_init_early(void)
6520 {
6521 	static struct cgroup_fs_context __initdata ctx;
6522 	struct cgroup_subsys *ss;
6523 	int i;
6524 
6525 	ctx.root = &cgrp_dfl_root;
6526 	init_cgroup_root(&ctx);
6527 	cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
6528 
6529 	RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
6530 
6531 	for_each_subsys(ss, i) {
6532 		WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
6533 		     "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
6534 		     i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
6535 		     ss->id, ss->name);
6536 		WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
6537 		     "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
6538 		WARN(ss->early_init && ss->css_rstat_flush,
6539 		     "cgroup rstat cannot be used with early init subsystem\n");
6540 
6541 		ss->id = i;
6542 		ss->name = cgroup_subsys_name[i];
6543 		if (!ss->legacy_name)
6544 			ss->legacy_name = cgroup_subsys_name[i];
6545 
6546 		if (ss->early_init)
6547 			cgroup_init_subsys(ss, true);
6548 	}
6549 	return 0;
6550 }
6551 
6552 /**
6553  * cgroup_init - cgroup initialization
6554  *
6555  * Register cgroup filesystem and /proc file, and initialize
6556  * any subsystems that didn't request early init.
6557  */
6558 int __init cgroup_init(void)
6559 {
6560 	struct cgroup_subsys *ss;
6561 	int ssid;
6562 
6563 	BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 32);
6564 	BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
6565 	BUG_ON(cgroup_init_cftypes(NULL, cgroup_psi_files));
6566 	BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
6567 
6568 	BUG_ON(ss_rstat_init(NULL));
6569 
6570 	get_user_ns(init_cgroup_ns.user_ns);
6571 	cgroup_rt_init();
6572 
6573 	cgroup_lock();
6574 
6575 	/*
6576 	 * Add init_css_set to the hash table so that dfl_root can link to
6577 	 * it during init.
6578 	 */
6579 	hash_add(css_set_table, &init_css_set.hlist,
6580 		 css_set_hash(init_css_set.subsys));
6581 
6582 	cgroup_bpf_lifetime_notifier_init();
6583 
6584 	BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
6585 
6586 	cgroup_unlock();
6587 
6588 	for_each_subsys(ss, ssid) {
6589 		if (ss->early_init) {
6590 			struct cgroup_subsys_state *css =
6591 				init_css_set.subsys[ss->id];
6592 
6593 			css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
6594 						   GFP_KERNEL);
6595 			BUG_ON(css->id < 0);
6596 		} else {
6597 			cgroup_init_subsys(ss, false);
6598 		}
6599 
6600 		list_add_tail(&init_css_set.e_cset_node[ssid],
6601 			      &cgrp_dfl_root.cgrp.e_csets[ssid]);
6602 
6603 		/*
6604 		 * Setting dfl_root subsys_mask needs to consider the
6605 		 * disabled flag and cftype registration needs kmalloc,
6606 		 * both of which aren't available during early_init.
6607 		 */
6608 		if (!cgroup_ssid_enabled(ssid))
6609 			continue;
6610 
6611 		if (cgroup1_ssid_disabled(ssid))
6612 			pr_info("Disabling %s control group subsystem in v1 mounts\n",
6613 				ss->legacy_name);
6614 
6615 		cgrp_dfl_root.subsys_mask |= 1 << ss->id;
6616 
6617 		/* implicit controllers must be threaded too */
6618 		WARN_ON(ss->implicit_on_dfl && !ss->threaded);
6619 
6620 		if (ss->implicit_on_dfl)
6621 			cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
6622 		else if (!ss->dfl_cftypes)
6623 			cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
6624 
6625 		if (ss->threaded)
6626 			cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
6627 
6628 		if (ss->dfl_cftypes == ss->legacy_cftypes) {
6629 			WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
6630 		} else {
6631 			WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
6632 			WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
6633 		}
6634 
6635 		if (ss->bind)
6636 			ss->bind(init_css_set.subsys[ssid]);
6637 
6638 		cgroup_lock();
6639 		css_populate_dir(init_css_set.subsys[ssid]);
6640 		cgroup_unlock();
6641 	}
6642 
6643 	/* init_css_set.subsys[] has been updated, re-hash */
6644 	hash_del(&init_css_set.hlist);
6645 	hash_add(css_set_table, &init_css_set.hlist,
6646 		 css_set_hash(init_css_set.subsys));
6647 
6648 	WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
6649 	WARN_ON(register_filesystem(&cgroup_fs_type));
6650 	WARN_ON(register_filesystem(&cgroup2_fs_type));
6651 	WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show));
6652 #ifdef CONFIG_CPUSETS_V1
6653 	WARN_ON(register_filesystem(&cpuset_fs_type));
6654 #endif
6655 
6656 	ns_tree_add(&init_cgroup_ns);
6657 	return 0;
6658 }
6659 
6660 static int __init cgroup_wq_init(void)
6661 {
6662 	/*
6663 	 * There isn't much point in executing destruction path in
6664 	 * parallel.  Good chunk is serialized with cgroup_mutex anyway.
6665 	 * Use 1 for @max_active.
6666 	 *
6667 	 * We would prefer to do this in cgroup_init() above, but that
6668 	 * is called before init_workqueues(): so leave this until after.
6669 	 */
6670 	cgroup_offline_wq = alloc_workqueue("cgroup_offline", WQ_PERCPU, 1);
6671 	BUG_ON(!cgroup_offline_wq);
6672 
6673 	cgroup_release_wq = alloc_workqueue("cgroup_release", WQ_PERCPU, 1);
6674 	BUG_ON(!cgroup_release_wq);
6675 
6676 	cgroup_free_wq = alloc_workqueue("cgroup_free", WQ_PERCPU, 1);
6677 	BUG_ON(!cgroup_free_wq);
6678 	return 0;
6679 }
6680 core_initcall(cgroup_wq_init);
6681 
6682 void cgroup_path_from_kernfs_id(u64 id, char *buf, size_t buflen)
6683 {
6684 	struct kernfs_node *kn;
6685 
6686 	kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6687 	if (!kn)
6688 		return;
6689 	kernfs_path(kn, buf, buflen);
6690 	kernfs_put(kn);
6691 }
6692 
6693 /*
6694  * __cgroup_get_from_id : get the cgroup associated with cgroup id
6695  * @id: cgroup id
6696  * On success return the cgrp or ERR_PTR on failure
6697  * There are no cgroup NS restrictions.
6698  */
6699 struct cgroup *__cgroup_get_from_id(u64 id)
6700 {
6701 	struct kernfs_node *kn;
6702 	struct cgroup *cgrp;
6703 
6704 	kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6705 	if (!kn)
6706 		return ERR_PTR(-ENOENT);
6707 
6708 	if (kernfs_type(kn) != KERNFS_DIR) {
6709 		kernfs_put(kn);
6710 		return ERR_PTR(-ENOENT);
6711 	}
6712 
6713 	rcu_read_lock();
6714 
6715 	cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6716 	if (cgrp && !cgroup_tryget(cgrp))
6717 		cgrp = NULL;
6718 
6719 	rcu_read_unlock();
6720 	kernfs_put(kn);
6721 
6722 	if (!cgrp)
6723 		return ERR_PTR(-ENOENT);
6724 	return cgrp;
6725 }
6726 
6727 /*
6728  * cgroup_get_from_id : get the cgroup associated with cgroup id
6729  * @id: cgroup id
6730  * On success return the cgrp or ERR_PTR on failure
6731  * Only cgroups within current task's cgroup NS are valid.
6732  */
6733 struct cgroup *cgroup_get_from_id(u64 id)
6734 {
6735 	struct cgroup *cgrp, *root_cgrp;
6736 
6737 	cgrp = __cgroup_get_from_id(id);
6738 	if (IS_ERR(cgrp))
6739 		return cgrp;
6740 
6741 	root_cgrp = current_cgns_cgroup_dfl();
6742 	if (!cgroup_is_descendant(cgrp, root_cgrp)) {
6743 		cgroup_put(cgrp);
6744 		return ERR_PTR(-ENOENT);
6745 	}
6746 
6747 	return cgrp;
6748 }
6749 EXPORT_SYMBOL_GPL(cgroup_get_from_id);
6750 
6751 /*
6752  * proc_cgroup_show()
6753  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
6754  *  - Used for /proc/<pid>/cgroup.
6755  */
6756 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
6757 		     struct pid *pid, struct task_struct *tsk)
6758 {
6759 	char *buf;
6760 	int retval;
6761 	struct cgroup_root *root;
6762 
6763 	retval = -ENOMEM;
6764 	buf = kmalloc(PATH_MAX, GFP_KERNEL);
6765 	if (!buf)
6766 		goto out;
6767 
6768 	rcu_read_lock();
6769 	spin_lock_irq(&css_set_lock);
6770 
6771 	for_each_root(root) {
6772 		struct cgroup_subsys *ss;
6773 		struct cgroup *cgrp;
6774 		int ssid, count = 0;
6775 
6776 		if (root == &cgrp_dfl_root && !READ_ONCE(cgrp_dfl_visible))
6777 			continue;
6778 
6779 		cgrp = task_cgroup_from_root(tsk, root);
6780 		/* The root has already been unmounted. */
6781 		if (!cgrp)
6782 			continue;
6783 
6784 		seq_printf(m, "%d:", root->hierarchy_id);
6785 		if (root != &cgrp_dfl_root)
6786 			for_each_subsys(ss, ssid)
6787 				if (root->subsys_mask & (1 << ssid))
6788 					seq_printf(m, "%s%s", count++ ? "," : "",
6789 						   ss->legacy_name);
6790 		if (strlen(root->name))
6791 			seq_printf(m, "%sname=%s", count ? "," : "",
6792 				   root->name);
6793 		seq_putc(m, ':');
6794 		/*
6795 		 * On traditional hierarchies, all zombie tasks show up as
6796 		 * belonging to the root cgroup.  On the default hierarchy,
6797 		 * while a zombie doesn't show up in "cgroup.procs" and
6798 		 * thus can't be migrated, its /proc/PID/cgroup keeps
6799 		 * reporting the cgroup it belonged to before exiting.  If
6800 		 * the cgroup is removed before the zombie is reaped,
6801 		 * " (deleted)" is appended to the cgroup path.
6802 		 */
6803 		if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
6804 			retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
6805 						current->nsproxy->cgroup_ns);
6806 			if (retval == -E2BIG)
6807 				retval = -ENAMETOOLONG;
6808 			if (retval < 0)
6809 				goto out_unlock;
6810 
6811 			seq_puts(m, buf);
6812 		} else {
6813 			seq_puts(m, "/");
6814 		}
6815 
6816 		if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
6817 			seq_puts(m, " (deleted)\n");
6818 		else
6819 			seq_putc(m, '\n');
6820 	}
6821 
6822 	retval = 0;
6823 out_unlock:
6824 	spin_unlock_irq(&css_set_lock);
6825 	rcu_read_unlock();
6826 	kfree(buf);
6827 out:
6828 	return retval;
6829 }
6830 
6831 /**
6832  * cgroup_fork - initialize cgroup related fields during copy_process()
6833  * @child: pointer to task_struct of forking parent process.
6834  *
6835  * A task is associated with the init_css_set until cgroup_post_fork()
6836  * attaches it to the target css_set.
6837  */
6838 void cgroup_fork(struct task_struct *child)
6839 {
6840 	RCU_INIT_POINTER(child->cgroups, &init_css_set);
6841 	INIT_LIST_HEAD(&child->cg_list);
6842 }
6843 
6844 /**
6845  * cgroup_v1v2_get_from_file - get a cgroup pointer from a file pointer
6846  * @f: file corresponding to cgroup_dir
6847  *
6848  * Find the cgroup from a file pointer associated with a cgroup directory.
6849  * Returns a pointer to the cgroup on success. ERR_PTR is returned if the
6850  * cgroup cannot be found.
6851  */
6852 static struct cgroup *cgroup_v1v2_get_from_file(struct file *f)
6853 {
6854 	struct cgroup_subsys_state *css;
6855 
6856 	css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
6857 	if (IS_ERR(css))
6858 		return ERR_CAST(css);
6859 
6860 	return css->cgroup;
6861 }
6862 
6863 /**
6864  * cgroup_get_from_file - same as cgroup_v1v2_get_from_file, but only supports
6865  * cgroup2.
6866  * @f: file corresponding to cgroup2_dir
6867  */
6868 static struct cgroup *cgroup_get_from_file(struct file *f)
6869 {
6870 	struct cgroup *cgrp = cgroup_v1v2_get_from_file(f);
6871 
6872 	if (IS_ERR(cgrp))
6873 		return ERR_CAST(cgrp);
6874 
6875 	if (!cgroup_on_dfl(cgrp)) {
6876 		cgroup_put(cgrp);
6877 		return ERR_PTR(-EBADF);
6878 	}
6879 
6880 	return cgrp;
6881 }
6882 
6883 /**
6884  * cgroup_css_set_fork - find or create a css_set for a child process
6885  * @kargs: the arguments passed to create the child process
6886  *
6887  * This functions finds or creates a new css_set which the child
6888  * process will be attached to in cgroup_post_fork(). By default,
6889  * the child process will be given the same css_set as its parent.
6890  *
6891  * If CLONE_INTO_CGROUP is specified this function will try to find an
6892  * existing css_set which includes the requested cgroup and if not create
6893  * a new css_set that the child will be attached to later. If this function
6894  * succeeds it will hold cgroup_threadgroup_rwsem on return. If
6895  * CLONE_INTO_CGROUP is requested this function will grab cgroup mutex
6896  * before grabbing cgroup_threadgroup_rwsem and will hold a reference
6897  * to the target cgroup.
6898  */
6899 static int cgroup_css_set_fork(struct kernel_clone_args *kargs)
6900 	__acquires(&cgroup_mutex) __acquires(&cgroup_threadgroup_rwsem)
6901 {
6902 	int ret;
6903 	struct cgroup *dst_cgrp = NULL;
6904 	struct css_set *cset;
6905 	struct super_block *sb;
6906 
6907 	if (kargs->flags & CLONE_INTO_CGROUP)
6908 		cgroup_lock();
6909 
6910 	cgroup_threadgroup_change_begin(current);
6911 
6912 	spin_lock_irq(&css_set_lock);
6913 	cset = task_css_set(current);
6914 	get_css_set(cset);
6915 	kargs->kill_seq = cset->dfl_cgrp->kill_seq;
6916 	spin_unlock_irq(&css_set_lock);
6917 
6918 	if (!(kargs->flags & CLONE_INTO_CGROUP)) {
6919 		kargs->cset = cset;
6920 		return 0;
6921 	}
6922 
6923 	CLASS(fd_raw, f)(kargs->cgroup);
6924 	if (fd_empty(f)) {
6925 		ret = -EBADF;
6926 		goto err;
6927 	}
6928 	sb = fd_file(f)->f_path.dentry->d_sb;
6929 
6930 	dst_cgrp = cgroup_get_from_file(fd_file(f));
6931 	if (IS_ERR(dst_cgrp)) {
6932 		ret = PTR_ERR(dst_cgrp);
6933 		dst_cgrp = NULL;
6934 		goto err;
6935 	}
6936 
6937 	if (cgroup_is_dead(dst_cgrp)) {
6938 		ret = -ENODEV;
6939 		goto err;
6940 	}
6941 
6942 	/*
6943 	 * Verify that we the target cgroup is writable for us. This is
6944 	 * usually done by the vfs layer but since we're not going through
6945 	 * the vfs layer here we need to do it "manually".
6946 	 */
6947 	ret = cgroup_may_write(dst_cgrp, sb);
6948 	if (ret)
6949 		goto err;
6950 
6951 	/*
6952 	 * Spawning a task directly into a cgroup works by passing a file
6953 	 * descriptor to the target cgroup directory. This can even be an O_PATH
6954 	 * file descriptor. But it can never be a cgroup.procs file descriptor.
6955 	 * This was done on purpose so spawning into a cgroup could be
6956 	 * conceptualized as an atomic
6957 	 *
6958 	 *   fd = openat(dfd_cgroup, "cgroup.procs", ...);
6959 	 *   write(fd, <child-pid>, ...);
6960 	 *
6961 	 * sequence, i.e. it's a shorthand for the caller opening and writing
6962 	 * cgroup.procs of the cgroup indicated by @dfd_cgroup. This allows us
6963 	 * to always use the caller's credentials.
6964 	 */
6965 	ret = cgroup_attach_permissions(cset->dfl_cgrp, dst_cgrp, sb,
6966 					!(kargs->flags & CLONE_THREAD),
6967 					current->nsproxy->cgroup_ns);
6968 	if (ret)
6969 		goto err;
6970 
6971 	kargs->cset = find_css_set(cset, dst_cgrp);
6972 	if (!kargs->cset) {
6973 		ret = -ENOMEM;
6974 		goto err;
6975 	}
6976 
6977 	put_css_set(cset);
6978 	kargs->cgrp = dst_cgrp;
6979 	kargs->kill_seq = dst_cgrp->kill_seq;
6980 	return ret;
6981 
6982 err:
6983 	cgroup_threadgroup_change_end(current);
6984 	cgroup_unlock();
6985 	if (dst_cgrp)
6986 		cgroup_put(dst_cgrp);
6987 	put_css_set(cset);
6988 	if (kargs->cset)
6989 		put_css_set(kargs->cset);
6990 	return ret;
6991 }
6992 
6993 /**
6994  * cgroup_css_set_put_fork - drop references we took during fork
6995  * @kargs: the arguments passed to create the child process
6996  *
6997  * Drop references to the prepared css_set and target cgroup if
6998  * CLONE_INTO_CGROUP was requested.
6999  */
7000 static void cgroup_css_set_put_fork(struct kernel_clone_args *kargs)
7001 	__releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
7002 {
7003 	struct cgroup *cgrp = kargs->cgrp;
7004 	struct css_set *cset = kargs->cset;
7005 
7006 	cgroup_threadgroup_change_end(current);
7007 
7008 	if (cset) {
7009 		put_css_set(cset);
7010 		kargs->cset = NULL;
7011 	}
7012 
7013 	if (kargs->flags & CLONE_INTO_CGROUP) {
7014 		cgroup_unlock();
7015 		if (cgrp) {
7016 			cgroup_put(cgrp);
7017 			kargs->cgrp = NULL;
7018 		}
7019 	}
7020 }
7021 
7022 /**
7023  * cgroup_can_fork - called on a new task before the process is exposed
7024  * @child: the child process
7025  * @kargs: the arguments passed to create the child process
7026  *
7027  * This prepares a new css_set for the child process which the child will
7028  * be attached to in cgroup_post_fork().
7029  * This calls the subsystem can_fork() callbacks. If the cgroup_can_fork()
7030  * callback returns an error, the fork aborts with that error code. This
7031  * allows for a cgroup subsystem to conditionally allow or deny new forks.
7032  */
7033 int cgroup_can_fork(struct task_struct *child, struct kernel_clone_args *kargs)
7034 {
7035 	struct cgroup_subsys *ss;
7036 	int i, j, ret;
7037 
7038 	ret = cgroup_css_set_fork(kargs);
7039 	if (ret)
7040 		return ret;
7041 
7042 	do_each_subsys_mask(ss, i, have_canfork_callback) {
7043 		ret = ss->can_fork(child, kargs->cset);
7044 		if (ret)
7045 			goto out_revert;
7046 	} while_each_subsys_mask();
7047 
7048 	return 0;
7049 
7050 out_revert:
7051 	for_each_subsys(ss, j) {
7052 		if (j >= i)
7053 			break;
7054 		if (ss->cancel_fork)
7055 			ss->cancel_fork(child, kargs->cset);
7056 	}
7057 
7058 	cgroup_css_set_put_fork(kargs);
7059 
7060 	return ret;
7061 }
7062 
7063 /**
7064  * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
7065  * @child: the child process
7066  * @kargs: the arguments passed to create the child process
7067  *
7068  * This calls the cancel_fork() callbacks if a fork failed *after*
7069  * cgroup_can_fork() succeeded and cleans up references we took to
7070  * prepare a new css_set for the child process in cgroup_can_fork().
7071  */
7072 void cgroup_cancel_fork(struct task_struct *child,
7073 			struct kernel_clone_args *kargs)
7074 {
7075 	struct cgroup_subsys *ss;
7076 	int i;
7077 
7078 	for_each_subsys(ss, i)
7079 		if (ss->cancel_fork)
7080 			ss->cancel_fork(child, kargs->cset);
7081 
7082 	cgroup_css_set_put_fork(kargs);
7083 }
7084 
7085 /**
7086  * cgroup_post_fork - finalize cgroup setup for the child process
7087  * @child: the child process
7088  * @kargs: the arguments passed to create the child process
7089  *
7090  * Attach the child process to its css_set calling the subsystem fork()
7091  * callbacks.
7092  */
7093 void cgroup_post_fork(struct task_struct *child,
7094 		      struct kernel_clone_args *kargs)
7095 	__releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
7096 {
7097 	unsigned int cgrp_kill_seq = 0;
7098 	unsigned long cgrp_flags = 0;
7099 	bool kill = false;
7100 	struct cgroup_subsys *ss;
7101 	struct css_set *cset;
7102 	int i;
7103 
7104 	cset = kargs->cset;
7105 	kargs->cset = NULL;
7106 
7107 	spin_lock_irq(&css_set_lock);
7108 
7109 	/* init tasks are special, only link regular threads */
7110 	if (likely(child->pid)) {
7111 		if (kargs->cgrp) {
7112 			cgrp_flags = kargs->cgrp->flags;
7113 			cgrp_kill_seq = kargs->cgrp->kill_seq;
7114 		} else {
7115 			cgrp_flags = cset->dfl_cgrp->flags;
7116 			cgrp_kill_seq = cset->dfl_cgrp->kill_seq;
7117 		}
7118 
7119 		WARN_ON_ONCE(!list_empty(&child->cg_list));
7120 		cset->nr_tasks++;
7121 		css_set_move_task(child, NULL, cset, false);
7122 	} else {
7123 		put_css_set(cset);
7124 		cset = NULL;
7125 	}
7126 
7127 	if (!(child->flags & PF_KTHREAD)) {
7128 		if (unlikely(test_bit(CGRP_FREEZE, &cgrp_flags))) {
7129 			/*
7130 			 * If the cgroup has to be frozen, the new task has
7131 			 * too. Let's set the JOBCTL_TRAP_FREEZE jobctl bit to
7132 			 * get the task into the frozen state.
7133 			 */
7134 			spin_lock(&child->sighand->siglock);
7135 			WARN_ON_ONCE(child->frozen);
7136 			child->jobctl |= JOBCTL_TRAP_FREEZE;
7137 			spin_unlock(&child->sighand->siglock);
7138 
7139 			/*
7140 			 * Calling cgroup_update_frozen() isn't required here,
7141 			 * because it will be called anyway a bit later from
7142 			 * do_freezer_trap(). So we avoid cgroup's transient
7143 			 * switch from the frozen state and back.
7144 			 */
7145 		}
7146 
7147 		/*
7148 		 * If the cgroup is to be killed notice it now and take the
7149 		 * child down right after we finished preparing it for
7150 		 * userspace.
7151 		 */
7152 		kill = kargs->kill_seq != cgrp_kill_seq;
7153 	}
7154 
7155 	spin_unlock_irq(&css_set_lock);
7156 
7157 	/*
7158 	 * Call ss->fork().  This must happen after @child is linked on
7159 	 * css_set; otherwise, @child might change state between ->fork()
7160 	 * and addition to css_set.
7161 	 */
7162 	do_each_subsys_mask(ss, i, have_fork_callback) {
7163 		ss->fork(child);
7164 	} while_each_subsys_mask();
7165 
7166 	/* Make the new cset the root_cset of the new cgroup namespace. */
7167 	if (kargs->flags & CLONE_NEWCGROUP) {
7168 		struct css_set *rcset = child->nsproxy->cgroup_ns->root_cset;
7169 
7170 		get_css_set(cset);
7171 		child->nsproxy->cgroup_ns->root_cset = cset;
7172 		put_css_set(rcset);
7173 	}
7174 
7175 	/* Cgroup has to be killed so take down child immediately. */
7176 	if (unlikely(kill))
7177 		do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, child, PIDTYPE_TGID);
7178 
7179 	cgroup_css_set_put_fork(kargs);
7180 }
7181 
7182 /**
7183  * cgroup_task_exit - detach cgroup from exiting task
7184  * @tsk: pointer to task_struct of exiting process
7185  *
7186  * Description: Detach cgroup from @tsk.
7187  *
7188  */
7189 void cgroup_task_exit(struct task_struct *tsk)
7190 {
7191 	struct cgroup_subsys *ss;
7192 	int i;
7193 
7194 	/* see cgroup_post_fork() for details */
7195 	do_each_subsys_mask(ss, i, have_exit_callback) {
7196 		ss->exit(tsk);
7197 	} while_each_subsys_mask();
7198 }
7199 
7200 static void do_cgroup_task_dead(struct task_struct *tsk)
7201 {
7202 	struct css_set *cset;
7203 	unsigned long flags;
7204 
7205 	spin_lock_irqsave(&css_set_lock, flags);
7206 
7207 	WARN_ON_ONCE(list_empty(&tsk->cg_list));
7208 	cset = task_css_set(tsk);
7209 	css_set_move_task(tsk, cset, NULL, false);
7210 	cset->nr_tasks--;
7211 	/* matches the signal->live check in css_task_iter_advance() */
7212 	if (thread_group_leader(tsk) && atomic_read(&tsk->signal->live))
7213 		list_add_tail(&tsk->cg_list, &cset->dying_tasks);
7214 
7215 	if (dl_task(tsk))
7216 		dec_dl_tasks_cs(tsk);
7217 
7218 	WARN_ON_ONCE(cgroup_task_frozen(tsk));
7219 	if (unlikely(!(tsk->flags & PF_KTHREAD) &&
7220 		     test_bit(CGRP_FREEZE, &task_dfl_cgroup(tsk)->flags)))
7221 		cgroup_update_frozen(task_dfl_cgroup(tsk));
7222 
7223 	spin_unlock_irqrestore(&css_set_lock, flags);
7224 }
7225 
7226 #ifdef CONFIG_PREEMPT_RT
7227 /*
7228  * cgroup_task_dead() is called from finish_task_switch() which doesn't allow
7229  * scheduling even in RT. As the task_dead path requires grabbing css_set_lock,
7230  * this lead to sleeping in the invalid context warning bug. css_set_lock is too
7231  * big to become a raw_spinlock. The task_dead path doesn't need to run
7232  * synchronously but can't be delayed indefinitely either as the dead task pins
7233  * the cgroup and task_struct can be pinned indefinitely. Bounce through lazy
7234  * irq_work to allow batching while ensuring timely completion.
7235  */
7236 struct cgroup_dead {
7237 	struct irq_work		iwork;
7238 	struct llist_head	tasks;
7239 };
7240 static DEFINE_PER_CPU(struct cgroup_dead, cgroup_dead);
7241 
7242 static void cgrp_dead_tasks_iwork_fn(struct irq_work *iwork)
7243 {
7244 	struct cgroup_dead *cgrp_dead = container_of(iwork, struct cgroup_dead, iwork);
7245 	struct llist_node *lnode;
7246 	struct task_struct *task, *next;
7247 
7248 	lnode = llist_del_all(&cgrp_dead->tasks);
7249 	llist_for_each_entry_safe(task, next, lnode, cg_dead_lnode) {
7250 		do_cgroup_task_dead(task);
7251 		put_task_struct(task);
7252 	}
7253 }
7254 
7255 static void __init cgroup_rt_init(void)
7256 {
7257 	int cpu;
7258 
7259 	for_each_possible_cpu(cpu) {
7260 		struct cgroup_dead *cgrp_dead = per_cpu_ptr(&cgroup_dead, cpu);
7261 
7262 		init_llist_head(&cgrp_dead->tasks);
7263 		cgrp_dead->iwork = IRQ_WORK_INIT_LAZY(cgrp_dead_tasks_iwork_fn);
7264 	}
7265 }
7266 
7267 void cgroup_task_dead(struct task_struct *task)
7268 {
7269 	struct cgroup_dead *cgrp_dead = this_cpu_ptr(&cgroup_dead);
7270 
7271 	get_task_struct(task);
7272 	llist_add(&task->cg_dead_lnode, &cgrp_dead->tasks);
7273 	irq_work_queue(&cgrp_dead->iwork);
7274 }
7275 #else	/* CONFIG_PREEMPT_RT */
7276 static void __init cgroup_rt_init(void) {}
7277 
7278 void cgroup_task_dead(struct task_struct *task)
7279 {
7280 	do_cgroup_task_dead(task);
7281 }
7282 #endif	/* CONFIG_PREEMPT_RT */
7283 
7284 void cgroup_task_release(struct task_struct *task)
7285 {
7286 	struct cgroup_subsys *ss;
7287 	int ssid;
7288 
7289 	do_each_subsys_mask(ss, ssid, have_release_callback) {
7290 		ss->release(task);
7291 	} while_each_subsys_mask();
7292 }
7293 
7294 void cgroup_task_free(struct task_struct *task)
7295 {
7296 	struct css_set *cset = task_css_set(task);
7297 
7298 	if (!list_empty(&task->cg_list)) {
7299 		spin_lock_irq(&css_set_lock);
7300 		css_set_skip_task_iters(task_css_set(task), task);
7301 		list_del_init(&task->cg_list);
7302 		spin_unlock_irq(&css_set_lock);
7303 	}
7304 
7305 	put_css_set(cset);
7306 }
7307 
7308 static int __init cgroup_disable(char *str)
7309 {
7310 	struct cgroup_subsys *ss;
7311 	char *token;
7312 	int i;
7313 
7314 	while ((token = strsep(&str, ",")) != NULL) {
7315 		if (!*token)
7316 			continue;
7317 
7318 		for_each_subsys(ss, i) {
7319 			if (strcmp(token, ss->name) &&
7320 			    strcmp(token, ss->legacy_name))
7321 				continue;
7322 
7323 			static_branch_disable(cgroup_subsys_enabled_key[i]);
7324 			pr_info("Disabling %s control group subsystem\n",
7325 				ss->name);
7326 		}
7327 
7328 		for (i = 0; i < OPT_FEATURE_COUNT; i++) {
7329 			if (strcmp(token, cgroup_opt_feature_names[i]))
7330 				continue;
7331 			cgroup_feature_disable_mask |= 1 << i;
7332 			pr_info("Disabling %s control group feature\n",
7333 				cgroup_opt_feature_names[i]);
7334 			break;
7335 		}
7336 	}
7337 	return 1;
7338 }
7339 __setup("cgroup_disable=", cgroup_disable);
7340 
7341 void __init __weak enable_debug_cgroup(void) { }
7342 
7343 static int __init enable_cgroup_debug(char *str)
7344 {
7345 	cgroup_debug = true;
7346 	enable_debug_cgroup();
7347 	return 1;
7348 }
7349 __setup("cgroup_debug", enable_cgroup_debug);
7350 
7351 static int __init cgroup_favordynmods_setup(char *str)
7352 {
7353 	return (kstrtobool(str, &have_favordynmods) == 0);
7354 }
7355 __setup("cgroup_favordynmods=", cgroup_favordynmods_setup);
7356 
7357 /**
7358  * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
7359  * @dentry: directory dentry of interest
7360  * @ss: subsystem of interest
7361  *
7362  * If @dentry is a directory for a cgroup which has @ss enabled on it, try
7363  * to get the corresponding css and return it.  If such css doesn't exist
7364  * or can't be pinned, an ERR_PTR value is returned.
7365  */
7366 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
7367 						       struct cgroup_subsys *ss)
7368 {
7369 	struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
7370 	struct file_system_type *s_type = dentry->d_sb->s_type;
7371 	struct cgroup_subsys_state *css = NULL;
7372 	struct cgroup *cgrp;
7373 
7374 	/* is @dentry a cgroup dir? */
7375 	if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
7376 	    !kn || kernfs_type(kn) != KERNFS_DIR)
7377 		return ERR_PTR(-EBADF);
7378 
7379 	rcu_read_lock();
7380 
7381 	/*
7382 	 * This path doesn't originate from kernfs and @kn could already
7383 	 * have been or be removed at any point.  @kn->priv is RCU
7384 	 * protected for this access.  See css_release_work_fn() for details.
7385 	 */
7386 	cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
7387 	if (cgrp)
7388 		css = cgroup_css(cgrp, ss);
7389 
7390 	if (!css || !css_tryget_online(css))
7391 		css = ERR_PTR(-ENOENT);
7392 
7393 	rcu_read_unlock();
7394 	return css;
7395 }
7396 
7397 /**
7398  * css_from_id - lookup css by id
7399  * @id: the cgroup id
7400  * @ss: cgroup subsys to be looked into
7401  *
7402  * Returns the css if there's valid one with @id, otherwise returns NULL.
7403  * Should be called under rcu_read_lock().
7404  */
7405 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
7406 {
7407 	WARN_ON_ONCE(!rcu_read_lock_held());
7408 	return idr_find(&ss->css_idr, id);
7409 }
7410 
7411 /**
7412  * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
7413  * @path: path on the default hierarchy
7414  *
7415  * Find the cgroup at @path on the default hierarchy, increment its
7416  * reference count and return it.  Returns pointer to the found cgroup on
7417  * success, ERR_PTR(-ENOENT) if @path doesn't exist or if the cgroup has already
7418  * been released and ERR_PTR(-ENOTDIR) if @path points to a non-directory.
7419  */
7420 struct cgroup *cgroup_get_from_path(const char *path)
7421 {
7422 	struct kernfs_node *kn;
7423 	struct cgroup *cgrp = ERR_PTR(-ENOENT);
7424 	struct cgroup *root_cgrp;
7425 
7426 	root_cgrp = current_cgns_cgroup_dfl();
7427 	kn = kernfs_walk_and_get(root_cgrp->kn, path);
7428 	if (!kn)
7429 		goto out;
7430 
7431 	if (kernfs_type(kn) != KERNFS_DIR) {
7432 		cgrp = ERR_PTR(-ENOTDIR);
7433 		goto out_kernfs;
7434 	}
7435 
7436 	rcu_read_lock();
7437 
7438 	cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
7439 	if (!cgrp || !cgroup_tryget(cgrp))
7440 		cgrp = ERR_PTR(-ENOENT);
7441 
7442 	rcu_read_unlock();
7443 
7444 out_kernfs:
7445 	kernfs_put(kn);
7446 out:
7447 	return cgrp;
7448 }
7449 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
7450 
7451 /**
7452  * cgroup_v1v2_get_from_fd - get a cgroup pointer from a fd
7453  * @fd: fd obtained by open(cgroup_dir)
7454  *
7455  * Find the cgroup from a fd which should be obtained
7456  * by opening a cgroup directory.  Returns a pointer to the
7457  * cgroup on success. ERR_PTR is returned if the cgroup
7458  * cannot be found.
7459  */
7460 struct cgroup *cgroup_v1v2_get_from_fd(int fd)
7461 {
7462 	CLASS(fd_raw, f)(fd);
7463 	if (fd_empty(f))
7464 		return ERR_PTR(-EBADF);
7465 
7466 	return cgroup_v1v2_get_from_file(fd_file(f));
7467 }
7468 
7469 /**
7470  * cgroup_get_from_fd - same as cgroup_v1v2_get_from_fd, but only supports
7471  * cgroup2.
7472  * @fd: fd obtained by open(cgroup2_dir)
7473  */
7474 struct cgroup *cgroup_get_from_fd(int fd)
7475 {
7476 	struct cgroup *cgrp = cgroup_v1v2_get_from_fd(fd);
7477 
7478 	if (IS_ERR(cgrp))
7479 		return ERR_CAST(cgrp);
7480 
7481 	if (!cgroup_on_dfl(cgrp)) {
7482 		cgroup_put(cgrp);
7483 		return ERR_PTR(-EBADF);
7484 	}
7485 	return cgrp;
7486 }
7487 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
7488 
7489 static u64 power_of_ten(int power)
7490 {
7491 	u64 v = 1;
7492 	while (power--)
7493 		v *= 10;
7494 	return v;
7495 }
7496 
7497 /**
7498  * cgroup_parse_float - parse a floating number
7499  * @input: input string
7500  * @dec_shift: number of decimal digits to shift
7501  * @v: output
7502  *
7503  * Parse a decimal floating point number in @input and store the result in
7504  * @v with decimal point right shifted @dec_shift times.  For example, if
7505  * @input is "12.3456" and @dec_shift is 3, *@v will be set to 12345.
7506  * Returns 0 on success, -errno otherwise.
7507  *
7508  * There's nothing cgroup specific about this function except that it's
7509  * currently the only user.
7510  */
7511 int cgroup_parse_float(const char *input, unsigned dec_shift, s64 *v)
7512 {
7513 	s64 whole, frac = 0;
7514 	int fstart = 0, fend = 0, flen;
7515 
7516 	if (!sscanf(input, "%lld.%n%lld%n", &whole, &fstart, &frac, &fend))
7517 		return -EINVAL;
7518 	if (frac < 0)
7519 		return -EINVAL;
7520 
7521 	flen = fend > fstart ? fend - fstart : 0;
7522 	if (flen < dec_shift)
7523 		frac *= power_of_ten(dec_shift - flen);
7524 	else
7525 		frac = DIV_ROUND_CLOSEST_ULL(frac, power_of_ten(flen - dec_shift));
7526 
7527 	*v = whole * power_of_ten(dec_shift) + frac;
7528 	return 0;
7529 }
7530 
7531 /*
7532  * sock->sk_cgrp_data handling.  For more info, see sock_cgroup_data
7533  * definition in cgroup-defs.h.
7534  */
7535 #ifdef CONFIG_SOCK_CGROUP_DATA
7536 
7537 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
7538 {
7539 	struct cgroup *cgroup;
7540 
7541 	rcu_read_lock();
7542 	/* Don't associate the sock with unrelated interrupted task's cgroup. */
7543 	if (in_interrupt()) {
7544 		cgroup = &cgrp_dfl_root.cgrp;
7545 		cgroup_get(cgroup);
7546 		goto out;
7547 	}
7548 
7549 	while (true) {
7550 		struct css_set *cset;
7551 
7552 		cset = task_css_set(current);
7553 		if (likely(cgroup_tryget(cset->dfl_cgrp))) {
7554 			cgroup = cset->dfl_cgrp;
7555 			break;
7556 		}
7557 		cpu_relax();
7558 	}
7559 out:
7560 	skcd->cgroup = cgroup;
7561 	cgroup_bpf_get(cgroup);
7562 	rcu_read_unlock();
7563 }
7564 
7565 void cgroup_sk_clone(struct sock_cgroup_data *skcd)
7566 {
7567 	struct cgroup *cgrp = sock_cgroup_ptr(skcd);
7568 
7569 	/*
7570 	 * We might be cloning a socket which is left in an empty
7571 	 * cgroup and the cgroup might have already been rmdir'd.
7572 	 * Don't use cgroup_get_live().
7573 	 */
7574 	cgroup_get(cgrp);
7575 	cgroup_bpf_get(cgrp);
7576 }
7577 
7578 void cgroup_sk_free(struct sock_cgroup_data *skcd)
7579 {
7580 	struct cgroup *cgrp = sock_cgroup_ptr(skcd);
7581 
7582 	cgroup_bpf_put(cgrp);
7583 	cgroup_put(cgrp);
7584 }
7585 
7586 #endif	/* CONFIG_SOCK_CGROUP_DATA */
7587 
7588 #ifdef CONFIG_SYSFS
7589 static ssize_t show_delegatable_files(struct cftype *files, char *buf,
7590 				      ssize_t size, const char *prefix)
7591 {
7592 	struct cftype *cft;
7593 	ssize_t ret = 0;
7594 
7595 	for (cft = files; cft && cft->name[0] != '\0'; cft++) {
7596 		if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
7597 			continue;
7598 
7599 		if (prefix)
7600 			ret += snprintf(buf + ret, size - ret, "%s.", prefix);
7601 
7602 		ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
7603 
7604 		if (WARN_ON(ret >= size))
7605 			break;
7606 	}
7607 
7608 	return ret;
7609 }
7610 
7611 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
7612 			      char *buf)
7613 {
7614 	struct cgroup_subsys *ss;
7615 	int ssid;
7616 	ssize_t ret = 0;
7617 
7618 	ret = show_delegatable_files(cgroup_base_files, buf + ret,
7619 				     PAGE_SIZE - ret, NULL);
7620 	if (cgroup_psi_enabled())
7621 		ret += show_delegatable_files(cgroup_psi_files, buf + ret,
7622 					      PAGE_SIZE - ret, NULL);
7623 
7624 	for_each_subsys(ss, ssid)
7625 		ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
7626 					      PAGE_SIZE - ret,
7627 					      cgroup_subsys_name[ssid]);
7628 
7629 	return ret;
7630 }
7631 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
7632 
7633 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
7634 			     char *buf)
7635 {
7636 	return snprintf(buf, PAGE_SIZE,
7637 			"nsdelegate\n"
7638 			"favordynmods\n"
7639 			"memory_localevents\n"
7640 			"memory_recursiveprot\n"
7641 			"memory_hugetlb_accounting\n"
7642 			"pids_localevents\n");
7643 }
7644 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
7645 
7646 static struct attribute *cgroup_sysfs_attrs[] = {
7647 	&cgroup_delegate_attr.attr,
7648 	&cgroup_features_attr.attr,
7649 	NULL,
7650 };
7651 
7652 static const struct attribute_group cgroup_sysfs_attr_group = {
7653 	.attrs = cgroup_sysfs_attrs,
7654 	.name = "cgroup",
7655 };
7656 
7657 static int __init cgroup_sysfs_init(void)
7658 {
7659 	return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
7660 }
7661 subsys_initcall(cgroup_sysfs_init);
7662 
7663 #endif /* CONFIG_SYSFS */
7664