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