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