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