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