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