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