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