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