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