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