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