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