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