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