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