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