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