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