xref: /linux/kernel/cgroup/cgroup.c (revision 0031c06807cfa8aa51a759ff8aa09e1aa48149af)
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_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
2130 }
2131 
init_cgroup_root(struct cgroup_fs_context * ctx)2132 void init_cgroup_root(struct cgroup_fs_context *ctx)
2133 {
2134 	struct cgroup_root *root = ctx->root;
2135 	struct cgroup *cgrp = &root->cgrp;
2136 
2137 	INIT_LIST_HEAD_RCU(&root->root_list);
2138 	atomic_set(&root->nr_cgrps, 1);
2139 	cgrp->root = root;
2140 	init_cgroup_housekeeping(cgrp);
2141 
2142 	/* DYNMODS must be modified through cgroup_favor_dynmods() */
2143 	root->flags = ctx->flags & ~CGRP_ROOT_FAVOR_DYNMODS;
2144 	if (ctx->release_agent)
2145 		strscpy(root->release_agent_path, ctx->release_agent, PATH_MAX);
2146 	if (ctx->name)
2147 		strscpy(root->name, ctx->name, MAX_CGROUP_ROOT_NAMELEN);
2148 	if (ctx->cpuset_clone_children)
2149 		set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
2150 }
2151 
cgroup_setup_root(struct cgroup_root * root,u32 ss_mask)2152 int cgroup_setup_root(struct cgroup_root *root, u32 ss_mask)
2153 {
2154 	LIST_HEAD(tmp_links);
2155 	struct cgroup *root_cgrp = &root->cgrp;
2156 	struct kernfs_syscall_ops *kf_sops;
2157 	struct css_set *cset;
2158 	int i, ret;
2159 
2160 	lockdep_assert_held(&cgroup_mutex);
2161 
2162 	ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
2163 			      0, GFP_KERNEL);
2164 	if (ret)
2165 		goto out;
2166 
2167 	/*
2168 	 * We're accessing css_set_count without locking css_set_lock here,
2169 	 * but that's OK - it can only be increased by someone holding
2170 	 * cgroup_lock, and that's us.  Later rebinding may disable
2171 	 * controllers on the default hierarchy and thus create new csets,
2172 	 * which can't be more than the existing ones.  Allocate 2x.
2173 	 */
2174 	ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
2175 	if (ret)
2176 		goto cancel_ref;
2177 
2178 	ret = cgroup_init_root_id(root);
2179 	if (ret)
2180 		goto cancel_ref;
2181 
2182 	kf_sops = root == &cgrp_dfl_root ?
2183 		&cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
2184 
2185 	root->kf_root = kernfs_create_root(kf_sops,
2186 					   KERNFS_ROOT_CREATE_DEACTIVATED |
2187 					   KERNFS_ROOT_SUPPORT_EXPORTOP |
2188 					   KERNFS_ROOT_SUPPORT_USER_XATTR |
2189 					   KERNFS_ROOT_INVARIANT_PARENT,
2190 					   root_cgrp);
2191 	if (IS_ERR(root->kf_root)) {
2192 		ret = PTR_ERR(root->kf_root);
2193 		goto exit_root_id;
2194 	}
2195 	root_cgrp->kn = kernfs_root_to_node(root->kf_root);
2196 	WARN_ON_ONCE(cgroup_ino(root_cgrp) != 1);
2197 	root_cgrp->ancestors[0] = root_cgrp;
2198 
2199 	ret = css_populate_dir(&root_cgrp->self);
2200 	if (ret)
2201 		goto destroy_root;
2202 
2203 	ret = css_rstat_init(&root_cgrp->self);
2204 	if (ret)
2205 		goto destroy_root;
2206 
2207 	ret = rebind_subsystems(root, ss_mask);
2208 	if (ret)
2209 		goto exit_stats;
2210 
2211 	ret = blocking_notifier_call_chain(&cgroup_lifetime_notifier,
2212 					   CGROUP_LIFETIME_ONLINE, root_cgrp);
2213 	WARN_ON_ONCE(notifier_to_errno(ret));
2214 
2215 	trace_cgroup_setup_root(root);
2216 
2217 	/*
2218 	 * There must be no failure case after here, since rebinding takes
2219 	 * care of subsystems' refcounts, which are explicitly dropped in
2220 	 * the failure exit path.
2221 	 */
2222 	list_add_rcu(&root->root_list, &cgroup_roots);
2223 	cgroup_root_count++;
2224 
2225 	/*
2226 	 * Link the root cgroup in this hierarchy into all the css_set
2227 	 * objects.
2228 	 */
2229 	spin_lock_irq(&css_set_lock);
2230 	hash_for_each(css_set_table, i, cset, hlist) {
2231 		link_css_set(&tmp_links, cset, root_cgrp);
2232 		if (css_set_populated(cset))
2233 			cgroup_update_populated(root_cgrp, true);
2234 	}
2235 	spin_unlock_irq(&css_set_lock);
2236 
2237 	BUG_ON(!list_empty(&root_cgrp->self.children));
2238 	BUG_ON(atomic_read(&root->nr_cgrps) != 1);
2239 
2240 	ret = 0;
2241 	goto out;
2242 
2243 exit_stats:
2244 	css_rstat_exit(&root_cgrp->self);
2245 destroy_root:
2246 	kernfs_destroy_root(root->kf_root);
2247 	root->kf_root = NULL;
2248 exit_root_id:
2249 	cgroup_exit_root_id(root);
2250 cancel_ref:
2251 	percpu_ref_exit(&root_cgrp->self.refcnt);
2252 out:
2253 	free_cgrp_cset_links(&tmp_links);
2254 	return ret;
2255 }
2256 
cgroup_do_get_tree(struct fs_context * fc)2257 int cgroup_do_get_tree(struct fs_context *fc)
2258 {
2259 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2260 	int ret;
2261 
2262 	ctx->kfc.root = ctx->root->kf_root;
2263 	if (fc->fs_type == &cgroup2_fs_type)
2264 		ctx->kfc.magic = CGROUP2_SUPER_MAGIC;
2265 	else
2266 		ctx->kfc.magic = CGROUP_SUPER_MAGIC;
2267 	ret = kernfs_get_tree(fc);
2268 
2269 	/*
2270 	 * In non-init cgroup namespace, instead of root cgroup's dentry,
2271 	 * we return the dentry corresponding to the cgroupns->root_cgrp.
2272 	 */
2273 	if (!ret && ctx->ns != &init_cgroup_ns) {
2274 		struct dentry *nsdentry;
2275 		struct super_block *sb = fc->root->d_sb;
2276 		struct cgroup *cgrp;
2277 
2278 		cgroup_lock();
2279 		spin_lock_irq(&css_set_lock);
2280 
2281 		cgrp = cset_cgroup_from_root(ctx->ns->root_cset, ctx->root);
2282 
2283 		spin_unlock_irq(&css_set_lock);
2284 		cgroup_unlock();
2285 
2286 		nsdentry = kernfs_node_dentry(cgrp->kn, sb);
2287 		dput(fc->root);
2288 		if (IS_ERR(nsdentry)) {
2289 			deactivate_locked_super(sb);
2290 			ret = PTR_ERR(nsdentry);
2291 			nsdentry = NULL;
2292 		}
2293 		fc->root = nsdentry;
2294 	}
2295 
2296 	if (!ctx->kfc.new_sb_created)
2297 		cgroup_put(&ctx->root->cgrp);
2298 
2299 	return ret;
2300 }
2301 
2302 /*
2303  * Destroy a cgroup filesystem context.
2304  */
cgroup_fs_context_free(struct fs_context * fc)2305 static void cgroup_fs_context_free(struct fs_context *fc)
2306 {
2307 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2308 
2309 	kfree(ctx->name);
2310 	kfree(ctx->release_agent);
2311 	put_cgroup_ns(ctx->ns);
2312 	kernfs_free_fs_context(fc);
2313 	kfree(ctx);
2314 }
2315 
cgroup_get_tree(struct fs_context * fc)2316 static int cgroup_get_tree(struct fs_context *fc)
2317 {
2318 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2319 	int ret;
2320 
2321 	WRITE_ONCE(cgrp_dfl_visible, true);
2322 	cgroup_get_live(&cgrp_dfl_root.cgrp);
2323 	ctx->root = &cgrp_dfl_root;
2324 
2325 	ret = cgroup_do_get_tree(fc);
2326 	if (!ret)
2327 		apply_cgroup_root_flags(ctx->flags);
2328 	return ret;
2329 }
2330 
2331 static const struct fs_context_operations cgroup_fs_context_ops = {
2332 	.free		= cgroup_fs_context_free,
2333 	.parse_param	= cgroup2_parse_param,
2334 	.get_tree	= cgroup_get_tree,
2335 	.reconfigure	= cgroup_reconfigure,
2336 };
2337 
2338 static const struct fs_context_operations cgroup1_fs_context_ops = {
2339 	.free		= cgroup_fs_context_free,
2340 	.parse_param	= cgroup1_parse_param,
2341 	.get_tree	= cgroup1_get_tree,
2342 	.reconfigure	= cgroup1_reconfigure,
2343 };
2344 
2345 /*
2346  * Initialise the cgroup filesystem creation/reconfiguration context.  Notably,
2347  * we select the namespace we're going to use.
2348  */
cgroup_init_fs_context(struct fs_context * fc)2349 static int cgroup_init_fs_context(struct fs_context *fc)
2350 {
2351 	struct cgroup_fs_context *ctx;
2352 
2353 	ctx = kzalloc_obj(struct cgroup_fs_context);
2354 	if (!ctx)
2355 		return -ENOMEM;
2356 
2357 	ctx->ns = current->nsproxy->cgroup_ns;
2358 	get_cgroup_ns(ctx->ns);
2359 	fc->fs_private = &ctx->kfc;
2360 	if (fc->fs_type == &cgroup2_fs_type)
2361 		fc->ops = &cgroup_fs_context_ops;
2362 	else
2363 		fc->ops = &cgroup1_fs_context_ops;
2364 	put_user_ns(fc->user_ns);
2365 	fc->user_ns = get_user_ns(ctx->ns->user_ns);
2366 	fc->global = true;
2367 
2368 	if (have_favordynmods)
2369 		ctx->flags |= CGRP_ROOT_FAVOR_DYNMODS;
2370 
2371 	return 0;
2372 }
2373 
cgroup_kill_sb(struct super_block * sb)2374 static void cgroup_kill_sb(struct super_block *sb)
2375 {
2376 	struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2377 	struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2378 
2379 	/*
2380 	 * If @root doesn't have any children, start killing it.
2381 	 * This prevents new mounts by disabling percpu_ref_tryget_live().
2382 	 *
2383 	 * And don't kill the default root.
2384 	 */
2385 	if (list_empty(&root->cgrp.self.children) && root != &cgrp_dfl_root &&
2386 	    !percpu_ref_is_dying(&root->cgrp.self.refcnt))
2387 		percpu_ref_kill(&root->cgrp.self.refcnt);
2388 	cgroup_put(&root->cgrp);
2389 	kernfs_kill_sb(sb);
2390 }
2391 
2392 struct file_system_type cgroup_fs_type = {
2393 	.name			= "cgroup",
2394 	.init_fs_context	= cgroup_init_fs_context,
2395 	.parameters		= cgroup1_fs_parameters,
2396 	.kill_sb		= cgroup_kill_sb,
2397 	.fs_flags		= FS_USERNS_MOUNT,
2398 };
2399 
2400 static struct file_system_type cgroup2_fs_type = {
2401 	.name			= "cgroup2",
2402 	.init_fs_context	= cgroup_init_fs_context,
2403 	.parameters		= cgroup2_fs_parameters,
2404 	.kill_sb		= cgroup_kill_sb,
2405 	.fs_flags		= FS_USERNS_MOUNT,
2406 };
2407 
2408 #ifdef CONFIG_CPUSETS_V1
2409 enum cpuset_param {
2410 	Opt_cpuset_v2_mode,
2411 };
2412 
2413 static const struct fs_parameter_spec cpuset_fs_parameters[] = {
2414 	fsparam_flag  ("cpuset_v2_mode", Opt_cpuset_v2_mode),
2415 	{}
2416 };
2417 
cpuset_parse_param(struct fs_context * fc,struct fs_parameter * param)2418 static int cpuset_parse_param(struct fs_context *fc, struct fs_parameter *param)
2419 {
2420 	struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2421 	struct fs_parse_result result;
2422 	int opt;
2423 
2424 	opt = fs_parse(fc, cpuset_fs_parameters, param, &result);
2425 	if (opt < 0)
2426 		return opt;
2427 
2428 	switch (opt) {
2429 	case Opt_cpuset_v2_mode:
2430 		ctx->flags |= CGRP_ROOT_CPUSET_V2_MODE;
2431 		return 0;
2432 	}
2433 	return -EINVAL;
2434 }
2435 
2436 static const struct fs_context_operations cpuset_fs_context_ops = {
2437 	.get_tree	= cgroup1_get_tree,
2438 	.free		= cgroup_fs_context_free,
2439 	.parse_param	= cpuset_parse_param,
2440 };
2441 
2442 /*
2443  * This is ugly, but preserves the userspace API for existing cpuset
2444  * users. If someone tries to mount the "cpuset" filesystem, we
2445  * silently switch it to mount "cgroup" instead
2446  */
cpuset_init_fs_context(struct fs_context * fc)2447 static int cpuset_init_fs_context(struct fs_context *fc)
2448 {
2449 	char *agent = kstrdup("/sbin/cpuset_release_agent", GFP_USER);
2450 	struct cgroup_fs_context *ctx;
2451 	int err;
2452 
2453 	err = cgroup_init_fs_context(fc);
2454 	if (err) {
2455 		kfree(agent);
2456 		return err;
2457 	}
2458 
2459 	fc->ops = &cpuset_fs_context_ops;
2460 
2461 	ctx = cgroup_fc2context(fc);
2462 	ctx->subsys_mask = 1 << cpuset_cgrp_id;
2463 	ctx->flags |= CGRP_ROOT_NOPREFIX;
2464 	ctx->release_agent = agent;
2465 
2466 	get_filesystem(&cgroup_fs_type);
2467 	put_filesystem(fc->fs_type);
2468 	fc->fs_type = &cgroup_fs_type;
2469 
2470 	return 0;
2471 }
2472 
2473 static struct file_system_type cpuset_fs_type = {
2474 	.name			= "cpuset",
2475 	.init_fs_context	= cpuset_init_fs_context,
2476 	.parameters		= cpuset_fs_parameters,
2477 	.fs_flags		= FS_USERNS_MOUNT,
2478 };
2479 #endif
2480 
cgroup_path_ns_locked(struct cgroup * cgrp,char * buf,size_t buflen,struct cgroup_namespace * ns)2481 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2482 			  struct cgroup_namespace *ns)
2483 {
2484 	struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2485 
2486 	return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2487 }
2488 
cgroup_path_ns(struct cgroup * cgrp,char * buf,size_t buflen,struct cgroup_namespace * ns)2489 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2490 		   struct cgroup_namespace *ns)
2491 {
2492 	int ret;
2493 
2494 	cgroup_lock();
2495 	spin_lock_irq(&css_set_lock);
2496 
2497 	ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2498 
2499 	spin_unlock_irq(&css_set_lock);
2500 	cgroup_unlock();
2501 
2502 	return ret;
2503 }
2504 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2505 
2506 /**
2507  * cgroup_attach_lock - Lock for ->attach()
2508  * @lock_mode: whether acquire and acquire which rwsem
2509  * @tsk: thread group to lock
2510  *
2511  * cgroup migration sometimes needs to stabilize threadgroups against forks and
2512  * exits by write-locking cgroup_threadgroup_rwsem. However, some ->attach()
2513  * implementations (e.g. cpuset), also need to disable CPU hotplug.
2514  * Unfortunately, letting ->attach() operations acquire cpus_read_lock() can
2515  * lead to deadlocks.
2516  *
2517  * Bringing up a CPU may involve creating and destroying tasks which requires
2518  * read-locking threadgroup_rwsem, so threadgroup_rwsem nests inside
2519  * cpus_read_lock(). If we call an ->attach() which acquires the cpus lock while
2520  * write-locking threadgroup_rwsem, the locking order is reversed and we end up
2521  * waiting for an on-going CPU hotplug operation which in turn is waiting for
2522  * the threadgroup_rwsem to be released to create new tasks. For more details:
2523  *
2524  *   http://lkml.kernel.org/r/20220711174629.uehfmqegcwn2lqzu@wubuntu
2525  *
2526  * Resolve the situation by always acquiring cpus_read_lock() before optionally
2527  * write-locking cgroup_threadgroup_rwsem. This allows ->attach() to assume that
2528  * CPU hotplug is disabled on entry.
2529  *
2530  * When favordynmods is enabled, take per threadgroup rwsem to reduce overhead
2531  * on dynamic cgroup modifications. see the comment above
2532  * CGRP_ROOT_FAVOR_DYNMODS definition.
2533  *
2534  * tsk is not NULL only when writing to cgroup.procs.
2535  */
cgroup_attach_lock(enum cgroup_attach_lock_mode lock_mode,struct task_struct * tsk)2536 void cgroup_attach_lock(enum cgroup_attach_lock_mode lock_mode,
2537 			struct task_struct *tsk)
2538 {
2539 	cpus_read_lock();
2540 
2541 	switch (lock_mode) {
2542 	case CGRP_ATTACH_LOCK_NONE:
2543 		break;
2544 	case CGRP_ATTACH_LOCK_GLOBAL:
2545 		percpu_down_write(&cgroup_threadgroup_rwsem);
2546 		break;
2547 	case CGRP_ATTACH_LOCK_PER_THREADGROUP:
2548 		down_write(&tsk->signal->cgroup_threadgroup_rwsem);
2549 		break;
2550 	default:
2551 		pr_warn("cgroup: Unexpected attach lock mode.");
2552 		break;
2553 	}
2554 }
2555 
2556 /**
2557  * cgroup_attach_unlock - Undo cgroup_attach_lock()
2558  * @lock_mode: whether release and release which rwsem
2559  * @tsk: thread group to lock
2560  */
cgroup_attach_unlock(enum cgroup_attach_lock_mode lock_mode,struct task_struct * tsk)2561 void cgroup_attach_unlock(enum cgroup_attach_lock_mode lock_mode,
2562 			  struct task_struct *tsk)
2563 {
2564 	switch (lock_mode) {
2565 	case CGRP_ATTACH_LOCK_NONE:
2566 		break;
2567 	case CGRP_ATTACH_LOCK_GLOBAL:
2568 		percpu_up_write(&cgroup_threadgroup_rwsem);
2569 		break;
2570 	case CGRP_ATTACH_LOCK_PER_THREADGROUP:
2571 		up_write(&tsk->signal->cgroup_threadgroup_rwsem);
2572 		break;
2573 	default:
2574 		pr_warn("cgroup: Unexpected attach lock mode.");
2575 		break;
2576 	}
2577 
2578 	cpus_read_unlock();
2579 }
2580 
2581 /**
2582  * cgroup_migrate_add_task - add a migration target task to a migration context
2583  * @task: target task
2584  * @mgctx: target migration context
2585  *
2586  * Add @task, which is a migration target, to @mgctx->tset.  This function
2587  * becomes noop if @task doesn't need to be migrated.  @task's css_set
2588  * should have been added as a migration source and @task->cg_list will be
2589  * moved from the css_set's tasks list to mg_tasks one.
2590  */
cgroup_migrate_add_task(struct task_struct * task,struct cgroup_mgctx * mgctx)2591 static void cgroup_migrate_add_task(struct task_struct *task,
2592 				    struct cgroup_mgctx *mgctx)
2593 {
2594 	struct css_set *cset;
2595 
2596 	lockdep_assert_held(&css_set_lock);
2597 
2598 	/* @task either already exited or can't exit until the end */
2599 	if (task->flags & PF_EXITING)
2600 		return;
2601 
2602 	/* cgroup_threadgroup_rwsem protects racing against forks */
2603 	WARN_ON_ONCE(list_empty(&task->cg_list));
2604 
2605 	cset = task_css_set(task);
2606 	if (!cset->mg_src_cgrp)
2607 		return;
2608 
2609 	mgctx->tset.nr_tasks++;
2610 
2611 	css_set_skip_task_iters(cset, task);
2612 	list_move_tail(&task->cg_list, &cset->mg_tasks);
2613 	if (list_empty(&cset->mg_node))
2614 		list_add_tail(&cset->mg_node,
2615 			      &mgctx->tset.src_csets);
2616 	if (list_empty(&cset->mg_dst_cset->mg_node))
2617 		list_add_tail(&cset->mg_dst_cset->mg_node,
2618 			      &mgctx->tset.dst_csets);
2619 }
2620 
2621 /**
2622  * cgroup_taskset_first - reset taskset and return the first task
2623  * @tset: taskset of interest
2624  * @dst_cssp: output variable for the destination css
2625  *
2626  * @tset iteration is initialized and the first task is returned.
2627  */
cgroup_taskset_first(struct cgroup_taskset * tset,struct cgroup_subsys_state ** dst_cssp)2628 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2629 					 struct cgroup_subsys_state **dst_cssp)
2630 {
2631 	tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2632 	tset->cur_task = NULL;
2633 
2634 	return cgroup_taskset_next(tset, dst_cssp);
2635 }
2636 
2637 /**
2638  * cgroup_taskset_next - iterate to the next task in taskset
2639  * @tset: taskset of interest
2640  * @dst_cssp: output variable for the destination css
2641  *
2642  * Return the next task in @tset.  Iteration must have been initialized
2643  * with cgroup_taskset_first().
2644  */
cgroup_taskset_next(struct cgroup_taskset * tset,struct cgroup_subsys_state ** dst_cssp)2645 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2646 					struct cgroup_subsys_state **dst_cssp)
2647 {
2648 	struct css_set *cset = tset->cur_cset;
2649 	struct task_struct *task = tset->cur_task;
2650 
2651 	while (CGROUP_HAS_SUBSYS_CONFIG && &cset->mg_node != tset->csets) {
2652 		if (!task)
2653 			task = list_first_entry(&cset->mg_tasks,
2654 						struct task_struct, cg_list);
2655 		else
2656 			task = list_next_entry(task, cg_list);
2657 
2658 		if (&task->cg_list != &cset->mg_tasks) {
2659 			tset->cur_cset = cset;
2660 			tset->cur_task = task;
2661 
2662 			/*
2663 			 * This function may be called both before and
2664 			 * after cgroup_migrate_execute().  The two cases
2665 			 * can be distinguished by looking at whether @cset
2666 			 * has its ->mg_dst_cset set.
2667 			 */
2668 			if (cset->mg_dst_cset)
2669 				*dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2670 			else
2671 				*dst_cssp = cset->subsys[tset->ssid];
2672 
2673 			return task;
2674 		}
2675 
2676 		cset = list_next_entry(cset, mg_node);
2677 		task = NULL;
2678 	}
2679 
2680 	return NULL;
2681 }
2682 
2683 /**
2684  * cgroup_migrate_execute - migrate a taskset
2685  * @mgctx: migration context
2686  *
2687  * Migrate tasks in @mgctx as setup by migration preparation functions.
2688  * This function fails iff one of the ->can_attach callbacks fails and
2689  * guarantees that either all or none of the tasks in @mgctx are migrated.
2690  * @mgctx is consumed regardless of success.
2691  */
cgroup_migrate_execute(struct cgroup_mgctx * mgctx)2692 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2693 {
2694 	struct cgroup_taskset *tset = &mgctx->tset;
2695 	struct cgroup_subsys *ss;
2696 	struct task_struct *task, *tmp_task;
2697 	struct css_set *cset, *tmp_cset;
2698 	int ssid, failed_ssid, ret;
2699 
2700 	/* check that we can legitimately attach to the cgroup */
2701 	if (tset->nr_tasks) {
2702 		do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2703 			if (ss->can_attach) {
2704 				tset->ssid = ssid;
2705 				ret = ss->can_attach(tset);
2706 				if (ret) {
2707 					failed_ssid = ssid;
2708 					goto out_cancel_attach;
2709 				}
2710 			}
2711 		} while_each_subsys_mask();
2712 	}
2713 
2714 	/*
2715 	 * Now that we're guaranteed success, proceed to move all tasks to
2716 	 * the new cgroup.  There are no failure cases after here, so this
2717 	 * is the commit point.
2718 	 */
2719 	spin_lock_irq(&css_set_lock);
2720 	list_for_each_entry(cset, &tset->src_csets, mg_node) {
2721 		list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2722 			struct css_set *from_cset = task_css_set(task);
2723 			struct css_set *to_cset = cset->mg_dst_cset;
2724 
2725 			get_css_set(to_cset);
2726 			to_cset->nr_tasks++;
2727 			css_set_move_task(task, from_cset, to_cset, true);
2728 			from_cset->nr_tasks--;
2729 			/*
2730 			 * If the source or destination cgroup is frozen,
2731 			 * the task might require to change its state.
2732 			 */
2733 			cgroup_freezer_migrate_task(task, from_cset->dfl_cgrp,
2734 						    to_cset->dfl_cgrp);
2735 			put_css_set_locked(from_cset);
2736 
2737 		}
2738 	}
2739 	spin_unlock_irq(&css_set_lock);
2740 
2741 	/*
2742 	 * Migration is committed, all target tasks are now on dst_csets.
2743 	 * Nothing is sensitive to fork() after this point.  Notify
2744 	 * controllers that migration is complete.
2745 	 */
2746 	tset->csets = &tset->dst_csets;
2747 
2748 	if (tset->nr_tasks) {
2749 		do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2750 			if (ss->attach) {
2751 				tset->ssid = ssid;
2752 				ss->attach(tset);
2753 			}
2754 		} while_each_subsys_mask();
2755 	}
2756 
2757 	ret = 0;
2758 	goto out_release_tset;
2759 
2760 out_cancel_attach:
2761 	if (tset->nr_tasks) {
2762 		do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2763 			if (ssid == failed_ssid)
2764 				break;
2765 			if (ss->cancel_attach) {
2766 				tset->ssid = ssid;
2767 				ss->cancel_attach(tset);
2768 			}
2769 		} while_each_subsys_mask();
2770 	}
2771 out_release_tset:
2772 	spin_lock_irq(&css_set_lock);
2773 	list_splice_init(&tset->dst_csets, &tset->src_csets);
2774 	list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2775 		list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2776 		list_del_init(&cset->mg_node);
2777 	}
2778 	spin_unlock_irq(&css_set_lock);
2779 
2780 	/*
2781 	 * Re-initialize the cgroup_taskset structure in case it is reused
2782 	 * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2783 	 * iteration.
2784 	 */
2785 	tset->nr_tasks = 0;
2786 	tset->csets    = &tset->src_csets;
2787 	return ret;
2788 }
2789 
2790 /**
2791  * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2792  * @dst_cgrp: destination cgroup to test
2793  *
2794  * On the default hierarchy, except for the mixable, (possible) thread root
2795  * and threaded cgroups, subtree_control must be zero for migration
2796  * destination cgroups with tasks so that child cgroups don't compete
2797  * against tasks.
2798  */
cgroup_migrate_vet_dst(struct cgroup * dst_cgrp)2799 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2800 {
2801 	/* v1 doesn't have any restriction */
2802 	if (!cgroup_on_dfl(dst_cgrp))
2803 		return 0;
2804 
2805 	/* verify @dst_cgrp can host resources */
2806 	if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2807 		return -EOPNOTSUPP;
2808 
2809 	/*
2810 	 * If @dst_cgrp is already or can become a thread root or is
2811 	 * threaded, it doesn't matter.
2812 	 */
2813 	if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2814 		return 0;
2815 
2816 	/* apply no-internal-process constraint */
2817 	if (dst_cgrp->subtree_control)
2818 		return -EBUSY;
2819 
2820 	return 0;
2821 }
2822 
2823 /**
2824  * cgroup_migrate_finish - cleanup after attach
2825  * @mgctx: migration context
2826  *
2827  * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst().  See
2828  * those functions for details.
2829  */
cgroup_migrate_finish(struct cgroup_mgctx * mgctx)2830 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2831 {
2832 	struct css_set *cset, *tmp_cset;
2833 
2834 	lockdep_assert_held(&cgroup_mutex);
2835 
2836 	spin_lock_irq(&css_set_lock);
2837 
2838 	list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_src_csets,
2839 				 mg_src_preload_node) {
2840 		cset->mg_src_cgrp = NULL;
2841 		cset->mg_dst_cgrp = NULL;
2842 		cset->mg_dst_cset = NULL;
2843 		list_del_init(&cset->mg_src_preload_node);
2844 		put_css_set_locked(cset);
2845 	}
2846 
2847 	list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_dst_csets,
2848 				 mg_dst_preload_node) {
2849 		cset->mg_src_cgrp = NULL;
2850 		cset->mg_dst_cgrp = NULL;
2851 		cset->mg_dst_cset = NULL;
2852 		list_del_init(&cset->mg_dst_preload_node);
2853 		put_css_set_locked(cset);
2854 	}
2855 
2856 	spin_unlock_irq(&css_set_lock);
2857 }
2858 
2859 /**
2860  * cgroup_migrate_add_src - add a migration source css_set
2861  * @src_cset: the source css_set to add
2862  * @dst_cgrp: the destination cgroup
2863  * @mgctx: migration context
2864  *
2865  * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp.  Pin
2866  * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2867  * up by cgroup_migrate_finish().
2868  *
2869  * This function may be called without holding cgroup_threadgroup_rwsem
2870  * even if the target is a process.  Threads may be created and destroyed
2871  * but as long as cgroup_mutex is not dropped, no new css_set can be put
2872  * into play and the preloaded css_sets are guaranteed to cover all
2873  * migrations.
2874  */
cgroup_migrate_add_src(struct css_set * src_cset,struct cgroup * dst_cgrp,struct cgroup_mgctx * mgctx)2875 void cgroup_migrate_add_src(struct css_set *src_cset,
2876 			    struct cgroup *dst_cgrp,
2877 			    struct cgroup_mgctx *mgctx)
2878 {
2879 	struct cgroup *src_cgrp;
2880 
2881 	lockdep_assert_held(&cgroup_mutex);
2882 	lockdep_assert_held(&css_set_lock);
2883 
2884 	/*
2885 	 * If ->dead, @src_set is associated with one or more dead cgroups
2886 	 * and doesn't contain any migratable tasks.  Ignore it early so
2887 	 * that the rest of migration path doesn't get confused by it.
2888 	 */
2889 	if (src_cset->dead)
2890 		return;
2891 
2892 	if (!list_empty(&src_cset->mg_src_preload_node))
2893 		return;
2894 
2895 	src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2896 
2897 	WARN_ON(src_cset->mg_src_cgrp);
2898 	WARN_ON(src_cset->mg_dst_cgrp);
2899 	WARN_ON(!list_empty(&src_cset->mg_tasks));
2900 	WARN_ON(!list_empty(&src_cset->mg_node));
2901 
2902 	src_cset->mg_src_cgrp = src_cgrp;
2903 	src_cset->mg_dst_cgrp = dst_cgrp;
2904 	get_css_set(src_cset);
2905 	list_add_tail(&src_cset->mg_src_preload_node, &mgctx->preloaded_src_csets);
2906 }
2907 
2908 /**
2909  * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2910  * @mgctx: migration context
2911  *
2912  * Tasks are about to be moved and all the source css_sets have been
2913  * preloaded to @mgctx->preloaded_src_csets.  This function looks up and
2914  * pins all destination css_sets, links each to its source, and append them
2915  * to @mgctx->preloaded_dst_csets.
2916  *
2917  * This function must be called after cgroup_migrate_add_src() has been
2918  * called on each migration source css_set.  After migration is performed
2919  * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2920  * @mgctx.
2921  */
cgroup_migrate_prepare_dst(struct cgroup_mgctx * mgctx)2922 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2923 {
2924 	struct css_set *src_cset, *tmp_cset;
2925 
2926 	lockdep_assert_held(&cgroup_mutex);
2927 
2928 	/* look up the dst cset for each src cset and link it to src */
2929 	list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2930 				 mg_src_preload_node) {
2931 		struct css_set *dst_cset;
2932 		struct cgroup_subsys *ss;
2933 		int ssid;
2934 
2935 		dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2936 		if (!dst_cset)
2937 			return -ENOMEM;
2938 
2939 		WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2940 
2941 		/*
2942 		 * If src cset equals dst, it's noop.  Drop the src.
2943 		 * cgroup_migrate() will skip the cset too.  Note that we
2944 		 * can't handle src == dst as some nodes are used by both.
2945 		 */
2946 		if (src_cset == dst_cset) {
2947 			src_cset->mg_src_cgrp = NULL;
2948 			src_cset->mg_dst_cgrp = NULL;
2949 			list_del_init(&src_cset->mg_src_preload_node);
2950 			put_css_set(src_cset);
2951 			put_css_set(dst_cset);
2952 			continue;
2953 		}
2954 
2955 		src_cset->mg_dst_cset = dst_cset;
2956 
2957 		if (list_empty(&dst_cset->mg_dst_preload_node))
2958 			list_add_tail(&dst_cset->mg_dst_preload_node,
2959 				      &mgctx->preloaded_dst_csets);
2960 		else
2961 			put_css_set(dst_cset);
2962 
2963 		for_each_subsys(ss, ssid)
2964 			if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2965 				mgctx->ss_mask |= 1 << ssid;
2966 	}
2967 
2968 	return 0;
2969 }
2970 
2971 /**
2972  * cgroup_migrate - migrate a process or task to a cgroup
2973  * @leader: the leader of the process or the task to migrate
2974  * @threadgroup: whether @leader points to the whole process or a single task
2975  * @mgctx: migration context
2976  *
2977  * Migrate a process or task denoted by @leader.  If migrating a process,
2978  * the caller must be holding cgroup_threadgroup_rwsem.  The caller is also
2979  * responsible for invoking cgroup_migrate_add_src() and
2980  * cgroup_migrate_prepare_dst() on the targets before invoking this
2981  * function and following up with cgroup_migrate_finish().
2982  *
2983  * As long as a controller's ->can_attach() doesn't fail, this function is
2984  * guaranteed to succeed.  This means that, excluding ->can_attach()
2985  * failure, when migrating multiple targets, the success or failure can be
2986  * decided for all targets by invoking group_migrate_prepare_dst() before
2987  * actually starting migrating.
2988  */
cgroup_migrate(struct task_struct * leader,bool threadgroup,struct cgroup_mgctx * mgctx)2989 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2990 		   struct cgroup_mgctx *mgctx)
2991 {
2992 	struct task_struct *task;
2993 
2994 	/*
2995 	 * The following thread iteration should be inside an RCU critical
2996 	 * section to prevent tasks from being freed while taking the snapshot.
2997 	 * spin_lock_irq() implies RCU critical section here.
2998 	 */
2999 	spin_lock_irq(&css_set_lock);
3000 	task = leader;
3001 	do {
3002 		cgroup_migrate_add_task(task, mgctx);
3003 		if (!threadgroup)
3004 			break;
3005 	} while_each_thread(leader, task);
3006 	spin_unlock_irq(&css_set_lock);
3007 
3008 	return cgroup_migrate_execute(mgctx);
3009 }
3010 
3011 /**
3012  * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
3013  * @dst_cgrp: the cgroup to attach to
3014  * @leader: the task or the leader of the threadgroup to be attached
3015  * @threadgroup: attach the whole threadgroup?
3016  *
3017  * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
3018  */
cgroup_attach_task(struct cgroup * dst_cgrp,struct task_struct * leader,bool threadgroup)3019 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
3020 		       bool threadgroup)
3021 {
3022 	DEFINE_CGROUP_MGCTX(mgctx);
3023 	struct task_struct *task;
3024 	int ret = 0;
3025 
3026 	/* look up all src csets */
3027 	spin_lock_irq(&css_set_lock);
3028 	task = leader;
3029 	do {
3030 		cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
3031 		if (!threadgroup)
3032 			break;
3033 	} while_each_thread(leader, task);
3034 	spin_unlock_irq(&css_set_lock);
3035 
3036 	/* prepare dst csets and commit */
3037 	ret = cgroup_migrate_prepare_dst(&mgctx);
3038 	if (!ret)
3039 		ret = cgroup_migrate(leader, threadgroup, &mgctx);
3040 
3041 	cgroup_migrate_finish(&mgctx);
3042 
3043 	if (!ret)
3044 		TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
3045 
3046 	return ret;
3047 }
3048 
cgroup_procs_write_start(char * buf,bool threadgroup,enum cgroup_attach_lock_mode * lock_mode)3049 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup,
3050 					     enum cgroup_attach_lock_mode *lock_mode)
3051 {
3052 	struct task_struct *tsk;
3053 	pid_t pid;
3054 
3055 	if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
3056 		return ERR_PTR(-EINVAL);
3057 
3058 retry_find_task:
3059 	rcu_read_lock();
3060 	if (pid) {
3061 		tsk = find_task_by_vpid(pid);
3062 		if (!tsk) {
3063 			tsk = ERR_PTR(-ESRCH);
3064 			goto out_unlock_rcu;
3065 		}
3066 	} else {
3067 		tsk = current;
3068 	}
3069 
3070 	if (threadgroup)
3071 		tsk = tsk->group_leader;
3072 
3073 	/*
3074 	 * kthreads may acquire PF_NO_SETAFFINITY during initialization.
3075 	 * If userland migrates such a kthread to a non-root cgroup, it can
3076 	 * become trapped in a cpuset, or RT kthread may be born in a
3077 	 * cgroup with no rt_runtime allocated.  Just say no.
3078 	 */
3079 	if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
3080 		tsk = ERR_PTR(-EINVAL);
3081 		goto out_unlock_rcu;
3082 	}
3083 	get_task_struct(tsk);
3084 	rcu_read_unlock();
3085 
3086 	/*
3087 	 * If we migrate a single thread, we don't care about threadgroup
3088 	 * stability. If the thread is `current`, it won't exit(2) under our
3089 	 * hands or change PID through exec(2). We exclude
3090 	 * cgroup_update_dfl_csses and other cgroup_{proc,thread}s_write callers
3091 	 * by cgroup_mutex. Therefore, we can skip the global lock.
3092 	 */
3093 	lockdep_assert_held(&cgroup_mutex);
3094 
3095 	if (pid || threadgroup) {
3096 		if (cgroup_enable_per_threadgroup_rwsem)
3097 			*lock_mode = CGRP_ATTACH_LOCK_PER_THREADGROUP;
3098 		else
3099 			*lock_mode = CGRP_ATTACH_LOCK_GLOBAL;
3100 	} else {
3101 		*lock_mode = CGRP_ATTACH_LOCK_NONE;
3102 	}
3103 
3104 	cgroup_attach_lock(*lock_mode, tsk);
3105 
3106 	if (threadgroup) {
3107 		if (!thread_group_leader(tsk)) {
3108 			/*
3109 			 * A race with de_thread from another thread's exec()
3110 			 * may strip us of our leadership. If this happens,
3111 			 * throw this task away and try again.
3112 			 */
3113 			cgroup_attach_unlock(*lock_mode, tsk);
3114 			put_task_struct(tsk);
3115 			goto retry_find_task;
3116 		}
3117 	}
3118 
3119 	return tsk;
3120 
3121 out_unlock_rcu:
3122 	rcu_read_unlock();
3123 	return tsk;
3124 }
3125 
cgroup_procs_write_finish(struct task_struct * task,enum cgroup_attach_lock_mode lock_mode)3126 void cgroup_procs_write_finish(struct task_struct *task,
3127 			       enum cgroup_attach_lock_mode lock_mode)
3128 {
3129 	cgroup_attach_unlock(lock_mode, task);
3130 
3131 	/* release reference from cgroup_procs_write_start() */
3132 	put_task_struct(task);
3133 }
3134 
cgroup_print_ss_mask(struct seq_file * seq,u32 ss_mask)3135 static void cgroup_print_ss_mask(struct seq_file *seq, u32 ss_mask)
3136 {
3137 	struct cgroup_subsys *ss;
3138 	bool printed = false;
3139 	int ssid;
3140 
3141 	do_each_subsys_mask(ss, ssid, ss_mask) {
3142 		if (printed)
3143 			seq_putc(seq, ' ');
3144 		seq_puts(seq, ss->name);
3145 		printed = true;
3146 	} while_each_subsys_mask();
3147 	if (printed)
3148 		seq_putc(seq, '\n');
3149 }
3150 
3151 /* show controllers which are enabled from the parent */
cgroup_controllers_show(struct seq_file * seq,void * v)3152 static int cgroup_controllers_show(struct seq_file *seq, void *v)
3153 {
3154 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3155 
3156 	cgroup_print_ss_mask(seq, cgroup_control(cgrp));
3157 	return 0;
3158 }
3159 
3160 /* show controllers which are enabled for a given cgroup's children */
cgroup_subtree_control_show(struct seq_file * seq,void * v)3161 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
3162 {
3163 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3164 
3165 	cgroup_print_ss_mask(seq, cgrp->subtree_control);
3166 	return 0;
3167 }
3168 
3169 /**
3170  * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
3171  * @cgrp: root of the subtree to update csses for
3172  *
3173  * @cgrp's control masks have changed and its subtree's css associations
3174  * need to be updated accordingly.  This function looks up all css_sets
3175  * which are attached to the subtree, creates the matching updated css_sets
3176  * and migrates the tasks to the new ones.
3177  */
cgroup_update_dfl_csses(struct cgroup * cgrp)3178 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
3179 {
3180 	DEFINE_CGROUP_MGCTX(mgctx);
3181 	struct cgroup_subsys_state *d_css;
3182 	struct cgroup *dsct;
3183 	struct css_set *src_cset;
3184 	enum cgroup_attach_lock_mode lock_mode;
3185 	bool has_tasks;
3186 	int ret;
3187 
3188 	lockdep_assert_held(&cgroup_mutex);
3189 
3190 	/* look up all csses currently attached to @cgrp's subtree */
3191 	spin_lock_irq(&css_set_lock);
3192 	cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3193 		struct cgrp_cset_link *link;
3194 
3195 		/*
3196 		 * As cgroup_update_dfl_csses() is only called by
3197 		 * cgroup_apply_control(). The csses associated with the
3198 		 * given cgrp will not be affected by changes made to
3199 		 * its subtree_control file. We can skip them.
3200 		 */
3201 		if (dsct == cgrp)
3202 			continue;
3203 
3204 		list_for_each_entry(link, &dsct->cset_links, cset_link)
3205 			cgroup_migrate_add_src(link->cset, dsct, &mgctx);
3206 	}
3207 	spin_unlock_irq(&css_set_lock);
3208 
3209 	/*
3210 	 * We need to write-lock threadgroup_rwsem while migrating tasks.
3211 	 * However, if there are no source csets for @cgrp, changing its
3212 	 * controllers isn't gonna produce any task migrations and the
3213 	 * write-locking can be skipped safely.
3214 	 */
3215 	has_tasks = !list_empty(&mgctx.preloaded_src_csets);
3216 
3217 	if (has_tasks)
3218 		lock_mode = CGRP_ATTACH_LOCK_GLOBAL;
3219 	else
3220 		lock_mode = CGRP_ATTACH_LOCK_NONE;
3221 
3222 	cgroup_attach_lock(lock_mode, NULL);
3223 
3224 	/* NULL dst indicates self on default hierarchy */
3225 	ret = cgroup_migrate_prepare_dst(&mgctx);
3226 	if (ret)
3227 		goto out_finish;
3228 
3229 	spin_lock_irq(&css_set_lock);
3230 	list_for_each_entry(src_cset, &mgctx.preloaded_src_csets,
3231 			    mg_src_preload_node) {
3232 		struct task_struct *task, *ntask;
3233 
3234 		/* all tasks in src_csets need to be migrated */
3235 		list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
3236 			cgroup_migrate_add_task(task, &mgctx);
3237 	}
3238 	spin_unlock_irq(&css_set_lock);
3239 
3240 	ret = cgroup_migrate_execute(&mgctx);
3241 out_finish:
3242 	cgroup_migrate_finish(&mgctx);
3243 	cgroup_attach_unlock(lock_mode, NULL);
3244 	return ret;
3245 }
3246 
3247 /**
3248  * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
3249  * @cgrp: root of the target subtree
3250  *
3251  * Because css offlining is asynchronous, userland may try to re-enable a
3252  * controller while the previous css is still around.  This function grabs
3253  * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
3254  */
cgroup_lock_and_drain_offline(struct cgroup * cgrp)3255 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
3256 	__acquires(&cgroup_mutex)
3257 {
3258 	struct cgroup *dsct;
3259 	struct cgroup_subsys_state *d_css;
3260 	struct cgroup_subsys *ss;
3261 	int ssid;
3262 
3263 restart:
3264 	cgroup_lock();
3265 
3266 	cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3267 		for_each_subsys(ss, ssid) {
3268 			struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3269 			DEFINE_WAIT(wait);
3270 
3271 			if (!css || !percpu_ref_is_dying(&css->refcnt))
3272 				continue;
3273 
3274 			cgroup_get_live(dsct);
3275 			prepare_to_wait(&dsct->offline_waitq, &wait,
3276 					TASK_UNINTERRUPTIBLE);
3277 
3278 			cgroup_unlock();
3279 			schedule();
3280 			finish_wait(&dsct->offline_waitq, &wait);
3281 
3282 			cgroup_put(dsct);
3283 			goto restart;
3284 		}
3285 	}
3286 }
3287 
3288 /**
3289  * cgroup_save_control - save control masks and dom_cgrp of a subtree
3290  * @cgrp: root of the target subtree
3291  *
3292  * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
3293  * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3294  * itself.
3295  */
cgroup_save_control(struct cgroup * cgrp)3296 static void cgroup_save_control(struct cgroup *cgrp)
3297 {
3298 	struct cgroup *dsct;
3299 	struct cgroup_subsys_state *d_css;
3300 
3301 	cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3302 		dsct->old_subtree_control = dsct->subtree_control;
3303 		dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
3304 		dsct->old_dom_cgrp = dsct->dom_cgrp;
3305 	}
3306 }
3307 
3308 /**
3309  * cgroup_propagate_control - refresh control masks of a subtree
3310  * @cgrp: root of the target subtree
3311  *
3312  * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
3313  * ->subtree_control and propagate controller availability through the
3314  * subtree so that descendants don't have unavailable controllers enabled.
3315  */
cgroup_propagate_control(struct cgroup * cgrp)3316 static void cgroup_propagate_control(struct cgroup *cgrp)
3317 {
3318 	struct cgroup *dsct;
3319 	struct cgroup_subsys_state *d_css;
3320 
3321 	cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3322 		dsct->subtree_control &= cgroup_control(dsct);
3323 		dsct->subtree_ss_mask =
3324 			cgroup_calc_subtree_ss_mask(dsct->subtree_control,
3325 						    cgroup_ss_mask(dsct));
3326 	}
3327 }
3328 
3329 /**
3330  * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
3331  * @cgrp: root of the target subtree
3332  *
3333  * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
3334  * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3335  * itself.
3336  */
cgroup_restore_control(struct cgroup * cgrp)3337 static void cgroup_restore_control(struct cgroup *cgrp)
3338 {
3339 	struct cgroup *dsct;
3340 	struct cgroup_subsys_state *d_css;
3341 
3342 	cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3343 		dsct->subtree_control = dsct->old_subtree_control;
3344 		dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
3345 		dsct->dom_cgrp = dsct->old_dom_cgrp;
3346 	}
3347 }
3348 
css_visible(struct cgroup_subsys_state * css)3349 static bool css_visible(struct cgroup_subsys_state *css)
3350 {
3351 	struct cgroup_subsys *ss = css->ss;
3352 	struct cgroup *cgrp = css->cgroup;
3353 
3354 	if (cgroup_control(cgrp) & (1 << ss->id))
3355 		return true;
3356 	if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
3357 		return false;
3358 	return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
3359 }
3360 
3361 /**
3362  * cgroup_apply_control_enable - enable or show csses according to control
3363  * @cgrp: root of the target subtree
3364  *
3365  * Walk @cgrp's subtree and create new csses or make the existing ones
3366  * visible.  A css is created invisible if it's being implicitly enabled
3367  * through dependency.  An invisible css is made visible when the userland
3368  * explicitly enables it.
3369  *
3370  * Returns 0 on success, -errno on failure.  On failure, csses which have
3371  * been processed already aren't cleaned up.  The caller is responsible for
3372  * cleaning up with cgroup_apply_control_disable().
3373  */
cgroup_apply_control_enable(struct cgroup * cgrp)3374 static int cgroup_apply_control_enable(struct cgroup *cgrp)
3375 {
3376 	struct cgroup *dsct;
3377 	struct cgroup_subsys_state *d_css;
3378 	struct cgroup_subsys *ss;
3379 	int ssid, ret;
3380 
3381 	cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3382 		for_each_subsys(ss, ssid) {
3383 			struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3384 
3385 			if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
3386 				continue;
3387 
3388 			if (!css) {
3389 				css = css_create(dsct, ss);
3390 				if (IS_ERR(css))
3391 					return PTR_ERR(css);
3392 			}
3393 
3394 			WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3395 
3396 			if (css_visible(css)) {
3397 				ret = css_populate_dir(css);
3398 				if (ret)
3399 					return ret;
3400 			}
3401 		}
3402 	}
3403 
3404 	return 0;
3405 }
3406 
3407 /**
3408  * cgroup_apply_control_disable - kill or hide csses according to control
3409  * @cgrp: root of the target subtree
3410  *
3411  * Walk @cgrp's subtree and kill and hide csses so that they match
3412  * cgroup_ss_mask() and cgroup_visible_mask().
3413  *
3414  * A css is hidden when the userland requests it to be disabled while other
3415  * subsystems are still depending on it.  The css must not actively control
3416  * resources and be in the vanilla state if it's made visible again later.
3417  * Controllers which may be depended upon should provide ->css_reset() for
3418  * this purpose.
3419  */
cgroup_apply_control_disable(struct cgroup * cgrp)3420 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3421 {
3422 	struct cgroup *dsct;
3423 	struct cgroup_subsys_state *d_css;
3424 	struct cgroup_subsys *ss;
3425 	int ssid;
3426 
3427 	cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3428 		for_each_subsys(ss, ssid) {
3429 			struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3430 
3431 			if (!css)
3432 				continue;
3433 
3434 			WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3435 
3436 			if (css->parent &&
3437 			    !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3438 				kill_css(css);
3439 			} else if (!css_visible(css)) {
3440 				css_clear_dir(css);
3441 				if (ss->css_reset)
3442 					ss->css_reset(css);
3443 			}
3444 		}
3445 	}
3446 }
3447 
3448 /**
3449  * cgroup_apply_control - apply control mask updates to the subtree
3450  * @cgrp: root of the target subtree
3451  *
3452  * subsystems can be enabled and disabled in a subtree using the following
3453  * steps.
3454  *
3455  * 1. Call cgroup_save_control() to stash the current state.
3456  * 2. Update ->subtree_control masks in the subtree as desired.
3457  * 3. Call cgroup_apply_control() to apply the changes.
3458  * 4. Optionally perform other related operations.
3459  * 5. Call cgroup_finalize_control() to finish up.
3460  *
3461  * This function implements step 3 and propagates the mask changes
3462  * throughout @cgrp's subtree, updates csses accordingly and perform
3463  * process migrations.
3464  */
cgroup_apply_control(struct cgroup * cgrp)3465 static int cgroup_apply_control(struct cgroup *cgrp)
3466 {
3467 	int ret;
3468 
3469 	cgroup_propagate_control(cgrp);
3470 
3471 	ret = cgroup_apply_control_enable(cgrp);
3472 	if (ret)
3473 		return ret;
3474 
3475 	/*
3476 	 * At this point, cgroup_e_css_by_mask() results reflect the new csses
3477 	 * making the following cgroup_update_dfl_csses() properly update
3478 	 * css associations of all tasks in the subtree.
3479 	 */
3480 	return cgroup_update_dfl_csses(cgrp);
3481 }
3482 
3483 /**
3484  * cgroup_finalize_control - finalize control mask update
3485  * @cgrp: root of the target subtree
3486  * @ret: the result of the update
3487  *
3488  * Finalize control mask update.  See cgroup_apply_control() for more info.
3489  */
cgroup_finalize_control(struct cgroup * cgrp,int ret)3490 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3491 {
3492 	if (ret) {
3493 		cgroup_restore_control(cgrp);
3494 		cgroup_propagate_control(cgrp);
3495 	}
3496 
3497 	cgroup_apply_control_disable(cgrp);
3498 }
3499 
cgroup_vet_subtree_control_enable(struct cgroup * cgrp,u32 enable)3500 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u32 enable)
3501 {
3502 	u32 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3503 
3504 	/* if nothing is getting enabled, nothing to worry about */
3505 	if (!enable)
3506 		return 0;
3507 
3508 	/* can @cgrp host any resources? */
3509 	if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3510 		return -EOPNOTSUPP;
3511 
3512 	/* mixables don't care */
3513 	if (cgroup_is_mixable(cgrp))
3514 		return 0;
3515 
3516 	if (domain_enable) {
3517 		/* can't enable domain controllers inside a thread subtree */
3518 		if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3519 			return -EOPNOTSUPP;
3520 	} else {
3521 		/*
3522 		 * Threaded controllers can handle internal competitions
3523 		 * and are always allowed inside a (prospective) thread
3524 		 * subtree.
3525 		 */
3526 		if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3527 			return 0;
3528 	}
3529 
3530 	/*
3531 	 * Controllers can't be enabled for a cgroup with tasks to avoid
3532 	 * child cgroups competing against tasks.
3533 	 */
3534 	if (cgroup_has_tasks(cgrp))
3535 		return -EBUSY;
3536 
3537 	return 0;
3538 }
3539 
3540 /* 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)3541 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3542 					    char *buf, size_t nbytes,
3543 					    loff_t off)
3544 {
3545 	u32 enable = 0, disable = 0;
3546 	struct cgroup *cgrp, *child;
3547 	struct cgroup_subsys *ss;
3548 	char *tok;
3549 	int ssid, ret;
3550 
3551 	/*
3552 	 * Parse input - space separated list of subsystem names prefixed
3553 	 * with either + or -.
3554 	 */
3555 	buf = strstrip(buf);
3556 	while ((tok = strsep(&buf, " "))) {
3557 		if (tok[0] == '\0')
3558 			continue;
3559 		do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3560 			if (!cgroup_ssid_enabled(ssid) ||
3561 			    strcmp(tok + 1, ss->name))
3562 				continue;
3563 
3564 			if (*tok == '+') {
3565 				enable |= 1 << ssid;
3566 				disable &= ~(1 << ssid);
3567 			} else if (*tok == '-') {
3568 				disable |= 1 << ssid;
3569 				enable &= ~(1 << ssid);
3570 			} else {
3571 				return -EINVAL;
3572 			}
3573 			break;
3574 		} while_each_subsys_mask();
3575 		if (ssid == CGROUP_SUBSYS_COUNT)
3576 			return -EINVAL;
3577 	}
3578 
3579 	cgrp = cgroup_kn_lock_live(of->kn, true);
3580 	if (!cgrp)
3581 		return -ENODEV;
3582 
3583 	for_each_subsys(ss, ssid) {
3584 		if (enable & (1 << ssid)) {
3585 			if (cgrp->subtree_control & (1 << ssid)) {
3586 				enable &= ~(1 << ssid);
3587 				continue;
3588 			}
3589 
3590 			if (!(cgroup_control(cgrp) & (1 << ssid))) {
3591 				ret = -ENOENT;
3592 				goto out_unlock;
3593 			}
3594 		} else if (disable & (1 << ssid)) {
3595 			if (!(cgrp->subtree_control & (1 << ssid))) {
3596 				disable &= ~(1 << ssid);
3597 				continue;
3598 			}
3599 
3600 			/* a child has it enabled? */
3601 			cgroup_for_each_live_child(child, cgrp) {
3602 				if (child->subtree_control & (1 << ssid)) {
3603 					ret = -EBUSY;
3604 					goto out_unlock;
3605 				}
3606 			}
3607 		}
3608 	}
3609 
3610 	if (!enable && !disable) {
3611 		ret = 0;
3612 		goto out_unlock;
3613 	}
3614 
3615 	ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3616 	if (ret)
3617 		goto out_unlock;
3618 
3619 	/* save and update control masks and prepare csses */
3620 	cgroup_save_control(cgrp);
3621 
3622 	cgrp->subtree_control |= enable;
3623 	cgrp->subtree_control &= ~disable;
3624 
3625 	ret = cgroup_apply_control(cgrp);
3626 	cgroup_finalize_control(cgrp, ret);
3627 	if (ret)
3628 		goto out_unlock;
3629 
3630 	kernfs_activate(cgrp->kn);
3631 out_unlock:
3632 	cgroup_kn_unlock(of->kn);
3633 	return ret ?: nbytes;
3634 }
3635 
3636 /**
3637  * cgroup_enable_threaded - make @cgrp threaded
3638  * @cgrp: the target cgroup
3639  *
3640  * Called when "threaded" is written to the cgroup.type interface file and
3641  * tries to make @cgrp threaded and join the parent's resource domain.
3642  * This function is never called on the root cgroup as cgroup.type doesn't
3643  * exist on it.
3644  */
cgroup_enable_threaded(struct cgroup * cgrp)3645 static int cgroup_enable_threaded(struct cgroup *cgrp)
3646 {
3647 	struct cgroup *parent = cgroup_parent(cgrp);
3648 	struct cgroup *dom_cgrp = parent->dom_cgrp;
3649 	struct cgroup *dsct;
3650 	struct cgroup_subsys_state *d_css;
3651 	int ret;
3652 
3653 	lockdep_assert_held(&cgroup_mutex);
3654 
3655 	/* noop if already threaded */
3656 	if (cgroup_is_threaded(cgrp))
3657 		return 0;
3658 
3659 	/*
3660 	 * If @cgroup is populated or has domain controllers enabled, it
3661 	 * can't be switched.  While the below cgroup_can_be_thread_root()
3662 	 * test can catch the same conditions, that's only when @parent is
3663 	 * not mixable, so let's check it explicitly.
3664 	 */
3665 	if (cgroup_is_populated(cgrp) ||
3666 	    cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3667 		return -EOPNOTSUPP;
3668 
3669 	/* we're joining the parent's domain, ensure its validity */
3670 	if (!cgroup_is_valid_domain(dom_cgrp) ||
3671 	    !cgroup_can_be_thread_root(dom_cgrp))
3672 		return -EOPNOTSUPP;
3673 
3674 	/*
3675 	 * The following shouldn't cause actual migrations and should
3676 	 * always succeed.
3677 	 */
3678 	cgroup_save_control(cgrp);
3679 
3680 	cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3681 		if (dsct == cgrp || cgroup_is_threaded(dsct))
3682 			dsct->dom_cgrp = dom_cgrp;
3683 
3684 	ret = cgroup_apply_control(cgrp);
3685 	if (!ret)
3686 		parent->nr_threaded_children++;
3687 
3688 	cgroup_finalize_control(cgrp, ret);
3689 	return ret;
3690 }
3691 
cgroup_type_show(struct seq_file * seq,void * v)3692 static int cgroup_type_show(struct seq_file *seq, void *v)
3693 {
3694 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3695 
3696 	if (cgroup_is_threaded(cgrp))
3697 		seq_puts(seq, "threaded\n");
3698 	else if (!cgroup_is_valid_domain(cgrp))
3699 		seq_puts(seq, "domain invalid\n");
3700 	else if (cgroup_is_thread_root(cgrp))
3701 		seq_puts(seq, "domain threaded\n");
3702 	else
3703 		seq_puts(seq, "domain\n");
3704 
3705 	return 0;
3706 }
3707 
cgroup_type_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3708 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3709 				 size_t nbytes, loff_t off)
3710 {
3711 	struct cgroup *cgrp;
3712 	int ret;
3713 
3714 	/* only switching to threaded mode is supported */
3715 	if (strcmp(strstrip(buf), "threaded"))
3716 		return -EINVAL;
3717 
3718 	/* drain dying csses before we re-apply (threaded) subtree control */
3719 	cgrp = cgroup_kn_lock_live(of->kn, true);
3720 	if (!cgrp)
3721 		return -ENOENT;
3722 
3723 	/* threaded can only be enabled */
3724 	ret = cgroup_enable_threaded(cgrp);
3725 
3726 	cgroup_kn_unlock(of->kn);
3727 	return ret ?: nbytes;
3728 }
3729 
cgroup_max_descendants_show(struct seq_file * seq,void * v)3730 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3731 {
3732 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3733 	int descendants = READ_ONCE(cgrp->max_descendants);
3734 
3735 	if (descendants == INT_MAX)
3736 		seq_puts(seq, "max\n");
3737 	else
3738 		seq_printf(seq, "%d\n", descendants);
3739 
3740 	return 0;
3741 }
3742 
cgroup_max_descendants_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3743 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3744 					   char *buf, size_t nbytes, loff_t off)
3745 {
3746 	struct cgroup *cgrp;
3747 	int descendants;
3748 	ssize_t ret;
3749 
3750 	buf = strstrip(buf);
3751 	if (!strcmp(buf, "max")) {
3752 		descendants = INT_MAX;
3753 	} else {
3754 		ret = kstrtoint(buf, 0, &descendants);
3755 		if (ret)
3756 			return ret;
3757 	}
3758 
3759 	if (descendants < 0)
3760 		return -ERANGE;
3761 
3762 	cgrp = cgroup_kn_lock_live(of->kn, false);
3763 	if (!cgrp)
3764 		return -ENOENT;
3765 
3766 	cgrp->max_descendants = descendants;
3767 
3768 	cgroup_kn_unlock(of->kn);
3769 
3770 	return nbytes;
3771 }
3772 
cgroup_max_depth_show(struct seq_file * seq,void * v)3773 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3774 {
3775 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3776 	int depth = READ_ONCE(cgrp->max_depth);
3777 
3778 	if (depth == INT_MAX)
3779 		seq_puts(seq, "max\n");
3780 	else
3781 		seq_printf(seq, "%d\n", depth);
3782 
3783 	return 0;
3784 }
3785 
cgroup_max_depth_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)3786 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3787 				      char *buf, size_t nbytes, loff_t off)
3788 {
3789 	struct cgroup *cgrp;
3790 	ssize_t ret;
3791 	int depth;
3792 
3793 	buf = strstrip(buf);
3794 	if (!strcmp(buf, "max")) {
3795 		depth = INT_MAX;
3796 	} else {
3797 		ret = kstrtoint(buf, 0, &depth);
3798 		if (ret)
3799 			return ret;
3800 	}
3801 
3802 	if (depth < 0)
3803 		return -ERANGE;
3804 
3805 	cgrp = cgroup_kn_lock_live(of->kn, false);
3806 	if (!cgrp)
3807 		return -ENOENT;
3808 
3809 	cgrp->max_depth = depth;
3810 
3811 	cgroup_kn_unlock(of->kn);
3812 
3813 	return nbytes;
3814 }
3815 
cgroup_events_show(struct seq_file * seq,void * v)3816 static int cgroup_events_show(struct seq_file *seq, void *v)
3817 {
3818 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3819 
3820 	seq_printf(seq, "populated %d\n", cgroup_is_populated(cgrp));
3821 	seq_printf(seq, "frozen %d\n", test_bit(CGRP_FROZEN, &cgrp->flags));
3822 
3823 	return 0;
3824 }
3825 
cgroup_stat_show(struct seq_file * seq,void * v)3826 static int cgroup_stat_show(struct seq_file *seq, void *v)
3827 {
3828 	struct cgroup *cgroup = seq_css(seq)->cgroup;
3829 	struct cgroup_subsys_state *css;
3830 	int dying_cnt[CGROUP_SUBSYS_COUNT];
3831 	int ssid;
3832 
3833 	seq_printf(seq, "nr_descendants %d\n",
3834 		   cgroup->nr_descendants);
3835 
3836 	/*
3837 	 * Show the number of live and dying csses associated with each of
3838 	 * non-inhibited cgroup subsystems that is bound to cgroup v2.
3839 	 *
3840 	 * Without proper lock protection, racing is possible. So the
3841 	 * numbers may not be consistent when that happens.
3842 	 */
3843 	rcu_read_lock();
3844 	for (ssid = 0; ssid < CGROUP_SUBSYS_COUNT; ssid++) {
3845 		dying_cnt[ssid] = -1;
3846 		if ((BIT(ssid) & cgrp_dfl_inhibit_ss_mask) ||
3847 		    (cgroup_subsys[ssid]->root !=  &cgrp_dfl_root))
3848 			continue;
3849 		css = rcu_dereference_raw(cgroup->subsys[ssid]);
3850 		dying_cnt[ssid] = cgroup->nr_dying_subsys[ssid];
3851 		seq_printf(seq, "nr_subsys_%s %d\n", cgroup_subsys[ssid]->name,
3852 			   css ? (css->nr_descendants + 1) : 0);
3853 	}
3854 
3855 	seq_printf(seq, "nr_dying_descendants %d\n",
3856 		   cgroup->nr_dying_descendants);
3857 	for (ssid = 0; ssid < CGROUP_SUBSYS_COUNT; ssid++) {
3858 		if (dying_cnt[ssid] >= 0)
3859 			seq_printf(seq, "nr_dying_subsys_%s %d\n",
3860 				   cgroup_subsys[ssid]->name, dying_cnt[ssid]);
3861 	}
3862 	rcu_read_unlock();
3863 	return 0;
3864 }
3865 
cgroup_core_local_stat_show(struct seq_file * seq,void * v)3866 static int cgroup_core_local_stat_show(struct seq_file *seq, void *v)
3867 {
3868 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3869 	unsigned int sequence;
3870 	u64 freeze_time;
3871 
3872 	do {
3873 		sequence = read_seqcount_begin(&cgrp->freezer.freeze_seq);
3874 		freeze_time = cgrp->freezer.frozen_nsec;
3875 		/* Add in current freezer interval if the cgroup is freezing. */
3876 		if (test_bit(CGRP_FREEZE, &cgrp->flags))
3877 			freeze_time += (ktime_get_ns() -
3878 					cgrp->freezer.freeze_start_nsec);
3879 	} while (read_seqcount_retry(&cgrp->freezer.freeze_seq, sequence));
3880 
3881 	do_div(freeze_time, NSEC_PER_USEC);
3882 	seq_printf(seq, "frozen_usec %llu\n", freeze_time);
3883 
3884 	return 0;
3885 }
3886 
3887 #ifdef CONFIG_CGROUP_SCHED
3888 /**
3889  * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
3890  * @cgrp: the cgroup of interest
3891  * @ss: the subsystem of interest
3892  *
3893  * Find and get @cgrp's css associated with @ss.  If the css doesn't exist
3894  * or is offline, %NULL is returned.
3895  */
cgroup_tryget_css(struct cgroup * cgrp,struct cgroup_subsys * ss)3896 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
3897 						     struct cgroup_subsys *ss)
3898 {
3899 	struct cgroup_subsys_state *css;
3900 
3901 	rcu_read_lock();
3902 	css = cgroup_css(cgrp, ss);
3903 	if (css && !css_tryget_online(css))
3904 		css = NULL;
3905 	rcu_read_unlock();
3906 
3907 	return css;
3908 }
3909 
cgroup_extra_stat_show(struct seq_file * seq,int ssid)3910 static int cgroup_extra_stat_show(struct seq_file *seq, int ssid)
3911 {
3912 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3913 	struct cgroup_subsys *ss = cgroup_subsys[ssid];
3914 	struct cgroup_subsys_state *css;
3915 	int ret;
3916 
3917 	if (!ss->css_extra_stat_show)
3918 		return 0;
3919 
3920 	css = cgroup_tryget_css(cgrp, ss);
3921 	if (!css)
3922 		return 0;
3923 
3924 	ret = ss->css_extra_stat_show(seq, css);
3925 	css_put(css);
3926 	return ret;
3927 }
3928 
cgroup_local_stat_show(struct seq_file * seq,struct cgroup * cgrp,int ssid)3929 static int cgroup_local_stat_show(struct seq_file *seq,
3930 				  struct cgroup *cgrp, int ssid)
3931 {
3932 	struct cgroup_subsys *ss = cgroup_subsys[ssid];
3933 	struct cgroup_subsys_state *css;
3934 	int ret;
3935 
3936 	if (!ss->css_local_stat_show)
3937 		return 0;
3938 
3939 	css = cgroup_tryget_css(cgrp, ss);
3940 	if (!css)
3941 		return 0;
3942 
3943 	ret = ss->css_local_stat_show(seq, css);
3944 	css_put(css);
3945 	return ret;
3946 }
3947 #endif
3948 
cpu_stat_show(struct seq_file * seq,void * v)3949 static int cpu_stat_show(struct seq_file *seq, void *v)
3950 {
3951 	int ret = 0;
3952 
3953 	cgroup_base_stat_cputime_show(seq);
3954 #ifdef CONFIG_CGROUP_SCHED
3955 	ret = cgroup_extra_stat_show(seq, cpu_cgrp_id);
3956 #endif
3957 	return ret;
3958 }
3959 
cpu_local_stat_show(struct seq_file * seq,void * v)3960 static int cpu_local_stat_show(struct seq_file *seq, void *v)
3961 {
3962 	struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3963 	int ret = 0;
3964 
3965 #ifdef CONFIG_CGROUP_SCHED
3966 	ret = cgroup_local_stat_show(seq, cgrp, cpu_cgrp_id);
3967 #endif
3968 	return ret;
3969 }
3970 
3971 #ifdef CONFIG_PSI
cgroup_io_pressure_show(struct seq_file * seq,void * v)3972 static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
3973 {
3974 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3975 	struct psi_group *psi = cgroup_psi(cgrp);
3976 
3977 	return psi_show(seq, psi, PSI_IO);
3978 }
cgroup_memory_pressure_show(struct seq_file * seq,void * v)3979 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
3980 {
3981 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3982 	struct psi_group *psi = cgroup_psi(cgrp);
3983 
3984 	return psi_show(seq, psi, PSI_MEM);
3985 }
cgroup_cpu_pressure_show(struct seq_file * seq,void * v)3986 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
3987 {
3988 	struct cgroup *cgrp = seq_css(seq)->cgroup;
3989 	struct psi_group *psi = cgroup_psi(cgrp);
3990 
3991 	return psi_show(seq, psi, PSI_CPU);
3992 }
3993 
pressure_write(struct kernfs_open_file * of,char * buf,size_t nbytes,enum psi_res res)3994 static ssize_t pressure_write(struct kernfs_open_file *of, char *buf,
3995 			      size_t nbytes, enum psi_res res)
3996 {
3997 	struct cgroup_file_ctx *ctx = of->priv;
3998 	struct psi_trigger *new;
3999 	struct cgroup *cgrp;
4000 	struct psi_group *psi;
4001 
4002 	cgrp = cgroup_kn_lock_live(of->kn, false);
4003 	if (!cgrp)
4004 		return -ENODEV;
4005 
4006 	cgroup_get(cgrp);
4007 	cgroup_kn_unlock(of->kn);
4008 
4009 	/* Allow only one trigger per file descriptor */
4010 	if (ctx->psi.trigger) {
4011 		cgroup_put(cgrp);
4012 		return -EBUSY;
4013 	}
4014 
4015 	psi = cgroup_psi(cgrp);
4016 	new = psi_trigger_create(psi, buf, res, of->file, of);
4017 	if (IS_ERR(new)) {
4018 		cgroup_put(cgrp);
4019 		return PTR_ERR(new);
4020 	}
4021 
4022 	smp_store_release(&ctx->psi.trigger, new);
4023 	cgroup_put(cgrp);
4024 
4025 	return nbytes;
4026 }
4027 
cgroup_io_pressure_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4028 static ssize_t cgroup_io_pressure_write(struct kernfs_open_file *of,
4029 					  char *buf, size_t nbytes,
4030 					  loff_t off)
4031 {
4032 	return pressure_write(of, buf, nbytes, PSI_IO);
4033 }
4034 
cgroup_memory_pressure_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4035 static ssize_t cgroup_memory_pressure_write(struct kernfs_open_file *of,
4036 					  char *buf, size_t nbytes,
4037 					  loff_t off)
4038 {
4039 	return pressure_write(of, buf, nbytes, PSI_MEM);
4040 }
4041 
cgroup_cpu_pressure_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4042 static ssize_t cgroup_cpu_pressure_write(struct kernfs_open_file *of,
4043 					  char *buf, size_t nbytes,
4044 					  loff_t off)
4045 {
4046 	return pressure_write(of, buf, nbytes, PSI_CPU);
4047 }
4048 
4049 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
cgroup_irq_pressure_show(struct seq_file * seq,void * v)4050 static int cgroup_irq_pressure_show(struct seq_file *seq, void *v)
4051 {
4052 	struct cgroup *cgrp = seq_css(seq)->cgroup;
4053 	struct psi_group *psi = cgroup_psi(cgrp);
4054 
4055 	return psi_show(seq, psi, PSI_IRQ);
4056 }
4057 
cgroup_irq_pressure_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4058 static ssize_t cgroup_irq_pressure_write(struct kernfs_open_file *of,
4059 					 char *buf, size_t nbytes,
4060 					 loff_t off)
4061 {
4062 	return pressure_write(of, buf, nbytes, PSI_IRQ);
4063 }
4064 #endif
4065 
cgroup_pressure_show(struct seq_file * seq,void * v)4066 static int cgroup_pressure_show(struct seq_file *seq, void *v)
4067 {
4068 	struct cgroup *cgrp = seq_css(seq)->cgroup;
4069 	struct psi_group *psi = cgroup_psi(cgrp);
4070 
4071 	seq_printf(seq, "%d\n", psi->enabled);
4072 
4073 	return 0;
4074 }
4075 
cgroup_pressure_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4076 static ssize_t cgroup_pressure_write(struct kernfs_open_file *of,
4077 				     char *buf, size_t nbytes,
4078 				     loff_t off)
4079 {
4080 	ssize_t ret;
4081 	int enable;
4082 	struct cgroup *cgrp;
4083 	struct psi_group *psi;
4084 
4085 	ret = kstrtoint(strstrip(buf), 0, &enable);
4086 	if (ret)
4087 		return ret;
4088 
4089 	if (enable < 0 || enable > 1)
4090 		return -ERANGE;
4091 
4092 	cgrp = cgroup_kn_lock_live(of->kn, false);
4093 	if (!cgrp)
4094 		return -ENOENT;
4095 
4096 	psi = cgroup_psi(cgrp);
4097 	if (psi->enabled != enable) {
4098 		int i;
4099 
4100 		/* show or hide {cpu,memory,io,irq}.pressure files */
4101 		for (i = 0; i < NR_PSI_RESOURCES; i++)
4102 			cgroup_file_show(&cgrp->psi_files[i], enable);
4103 
4104 		psi->enabled = enable;
4105 		if (enable)
4106 			psi_cgroup_restart(psi);
4107 	}
4108 
4109 	cgroup_kn_unlock(of->kn);
4110 
4111 	return nbytes;
4112 }
4113 
cgroup_pressure_poll(struct kernfs_open_file * of,poll_table * pt)4114 static __poll_t cgroup_pressure_poll(struct kernfs_open_file *of,
4115 					  poll_table *pt)
4116 {
4117 	struct cgroup_file_ctx *ctx = of->priv;
4118 
4119 	return psi_trigger_poll(&ctx->psi.trigger, of->file, pt);
4120 }
4121 
cgroup_pressure_release(struct kernfs_open_file * of)4122 static void cgroup_pressure_release(struct kernfs_open_file *of)
4123 {
4124 	struct cgroup_file_ctx *ctx = of->priv;
4125 
4126 	psi_trigger_destroy(ctx->psi.trigger);
4127 }
4128 
cgroup_psi_enabled(void)4129 bool cgroup_psi_enabled(void)
4130 {
4131 	if (static_branch_likely(&psi_disabled))
4132 		return false;
4133 
4134 	return (cgroup_feature_disable_mask & (1 << OPT_FEATURE_PRESSURE)) == 0;
4135 }
4136 
4137 #else /* CONFIG_PSI */
cgroup_psi_enabled(void)4138 bool cgroup_psi_enabled(void)
4139 {
4140 	return false;
4141 }
4142 
4143 #endif /* CONFIG_PSI */
4144 
cgroup_freeze_show(struct seq_file * seq,void * v)4145 static int cgroup_freeze_show(struct seq_file *seq, void *v)
4146 {
4147 	struct cgroup *cgrp = seq_css(seq)->cgroup;
4148 
4149 	seq_printf(seq, "%d\n", cgrp->freezer.freeze);
4150 
4151 	return 0;
4152 }
4153 
cgroup_freeze_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4154 static ssize_t cgroup_freeze_write(struct kernfs_open_file *of,
4155 				   char *buf, size_t nbytes, loff_t off)
4156 {
4157 	struct cgroup *cgrp;
4158 	ssize_t ret;
4159 	int freeze;
4160 
4161 	ret = kstrtoint(strstrip(buf), 0, &freeze);
4162 	if (ret)
4163 		return ret;
4164 
4165 	if (freeze < 0 || freeze > 1)
4166 		return -ERANGE;
4167 
4168 	cgrp = cgroup_kn_lock_live(of->kn, false);
4169 	if (!cgrp)
4170 		return -ENOENT;
4171 
4172 	cgroup_freeze(cgrp, freeze);
4173 
4174 	cgroup_kn_unlock(of->kn);
4175 
4176 	return nbytes;
4177 }
4178 
__cgroup_kill(struct cgroup * cgrp)4179 static void __cgroup_kill(struct cgroup *cgrp)
4180 {
4181 	struct css_task_iter it;
4182 	struct task_struct *task;
4183 
4184 	lockdep_assert_held(&cgroup_mutex);
4185 
4186 	spin_lock_irq(&css_set_lock);
4187 	cgrp->kill_seq++;
4188 	spin_unlock_irq(&css_set_lock);
4189 
4190 	css_task_iter_start(&cgrp->self, CSS_TASK_ITER_PROCS | CSS_TASK_ITER_THREADED, &it);
4191 	while ((task = css_task_iter_next(&it))) {
4192 		/* Ignore kernel threads here. */
4193 		if (task->flags & PF_KTHREAD)
4194 			continue;
4195 
4196 		/* Skip tasks that are already dying. */
4197 		if (__fatal_signal_pending(task))
4198 			continue;
4199 
4200 		send_sig(SIGKILL, task, 0);
4201 	}
4202 	css_task_iter_end(&it);
4203 }
4204 
cgroup_kill(struct cgroup * cgrp)4205 static void cgroup_kill(struct cgroup *cgrp)
4206 {
4207 	struct cgroup_subsys_state *css;
4208 	struct cgroup *dsct;
4209 
4210 	lockdep_assert_held(&cgroup_mutex);
4211 
4212 	cgroup_for_each_live_descendant_pre(dsct, css, cgrp)
4213 		__cgroup_kill(dsct);
4214 }
4215 
cgroup_kill_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4216 static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf,
4217 				 size_t nbytes, loff_t off)
4218 {
4219 	ssize_t ret = 0;
4220 	int kill;
4221 	struct cgroup *cgrp;
4222 
4223 	ret = kstrtoint(strstrip(buf), 0, &kill);
4224 	if (ret)
4225 		return ret;
4226 
4227 	if (kill != 1)
4228 		return -ERANGE;
4229 
4230 	cgrp = cgroup_kn_lock_live(of->kn, false);
4231 	if (!cgrp)
4232 		return -ENOENT;
4233 
4234 	/*
4235 	 * Killing is a process directed operation, i.e. the whole thread-group
4236 	 * is taken down so act like we do for cgroup.procs and only make this
4237 	 * writable in non-threaded cgroups.
4238 	 */
4239 	if (cgroup_is_threaded(cgrp))
4240 		ret = -EOPNOTSUPP;
4241 	else
4242 		cgroup_kill(cgrp);
4243 
4244 	cgroup_kn_unlock(of->kn);
4245 
4246 	return ret ?: nbytes;
4247 }
4248 
cgroup_file_open(struct kernfs_open_file * of)4249 static int cgroup_file_open(struct kernfs_open_file *of)
4250 {
4251 	struct cftype *cft = of_cft(of);
4252 	struct cgroup_file_ctx *ctx;
4253 	int ret;
4254 
4255 	ctx = kzalloc_obj(*ctx);
4256 	if (!ctx)
4257 		return -ENOMEM;
4258 
4259 	ctx->ns = current->nsproxy->cgroup_ns;
4260 	get_cgroup_ns(ctx->ns);
4261 	of->priv = ctx;
4262 
4263 	if (!cft->open)
4264 		return 0;
4265 
4266 	ret = cft->open(of);
4267 	if (ret) {
4268 		put_cgroup_ns(ctx->ns);
4269 		kfree(ctx);
4270 	}
4271 	return ret;
4272 }
4273 
cgroup_file_release(struct kernfs_open_file * of)4274 static void cgroup_file_release(struct kernfs_open_file *of)
4275 {
4276 	struct cftype *cft = of_cft(of);
4277 	struct cgroup_file_ctx *ctx = of->priv;
4278 
4279 	if (cft->release)
4280 		cft->release(of);
4281 	put_cgroup_ns(ctx->ns);
4282 	kfree(ctx);
4283 	of->priv = NULL;
4284 }
4285 
cgroup_file_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)4286 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
4287 				 size_t nbytes, loff_t off)
4288 {
4289 	struct cgroup_file_ctx *ctx = of->priv;
4290 	struct cgroup *cgrp = kn_priv(of->kn);
4291 	struct cftype *cft = of_cft(of);
4292 	struct cgroup_subsys_state *css;
4293 	int ret;
4294 
4295 	if (!nbytes)
4296 		return 0;
4297 
4298 	/*
4299 	 * If namespaces are delegation boundaries, disallow writes to
4300 	 * files in an non-init namespace root from inside the namespace
4301 	 * except for the files explicitly marked delegatable -
4302 	 * eg. cgroup.procs, cgroup.threads and cgroup.subtree_control.
4303 	 */
4304 	if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
4305 	    !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
4306 	    ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
4307 		return -EPERM;
4308 
4309 	if (cft->write)
4310 		return cft->write(of, buf, nbytes, off);
4311 
4312 	/*
4313 	 * kernfs guarantees that a file isn't deleted with operations in
4314 	 * flight, which means that the matching css is and stays alive and
4315 	 * doesn't need to be pinned.  The RCU locking is not necessary
4316 	 * either.  It's just for the convenience of using cgroup_css().
4317 	 */
4318 	rcu_read_lock();
4319 	css = cgroup_css(cgrp, cft->ss);
4320 	rcu_read_unlock();
4321 
4322 	if (cft->write_u64) {
4323 		unsigned long long v;
4324 		ret = kstrtoull(buf, 0, &v);
4325 		if (!ret)
4326 			ret = cft->write_u64(css, cft, v);
4327 	} else if (cft->write_s64) {
4328 		long long v;
4329 		ret = kstrtoll(buf, 0, &v);
4330 		if (!ret)
4331 			ret = cft->write_s64(css, cft, v);
4332 	} else {
4333 		ret = -EINVAL;
4334 	}
4335 
4336 	return ret ?: nbytes;
4337 }
4338 
cgroup_file_poll(struct kernfs_open_file * of,poll_table * pt)4339 static __poll_t cgroup_file_poll(struct kernfs_open_file *of, poll_table *pt)
4340 {
4341 	struct cftype *cft = of_cft(of);
4342 
4343 	if (cft->poll)
4344 		return cft->poll(of, pt);
4345 
4346 	return kernfs_generic_poll(of, pt);
4347 }
4348 
cgroup_seqfile_start(struct seq_file * seq,loff_t * ppos)4349 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
4350 {
4351 	return seq_cft(seq)->seq_start(seq, ppos);
4352 }
4353 
cgroup_seqfile_next(struct seq_file * seq,void * v,loff_t * ppos)4354 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
4355 {
4356 	return seq_cft(seq)->seq_next(seq, v, ppos);
4357 }
4358 
cgroup_seqfile_stop(struct seq_file * seq,void * v)4359 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
4360 {
4361 	if (seq_cft(seq)->seq_stop)
4362 		seq_cft(seq)->seq_stop(seq, v);
4363 }
4364 
cgroup_seqfile_show(struct seq_file * m,void * arg)4365 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
4366 {
4367 	struct cftype *cft = seq_cft(m);
4368 	struct cgroup_subsys_state *css = seq_css(m);
4369 
4370 	if (cft->seq_show)
4371 		return cft->seq_show(m, arg);
4372 
4373 	if (cft->read_u64)
4374 		seq_printf(m, "%llu\n", cft->read_u64(css, cft));
4375 	else if (cft->read_s64)
4376 		seq_printf(m, "%lld\n", cft->read_s64(css, cft));
4377 	else
4378 		return -EINVAL;
4379 	return 0;
4380 }
4381 
4382 static struct kernfs_ops cgroup_kf_single_ops = {
4383 	.atomic_write_len	= PAGE_SIZE,
4384 	.open			= cgroup_file_open,
4385 	.release		= cgroup_file_release,
4386 	.write			= cgroup_file_write,
4387 	.poll			= cgroup_file_poll,
4388 	.seq_show		= cgroup_seqfile_show,
4389 };
4390 
4391 static struct kernfs_ops cgroup_kf_ops = {
4392 	.atomic_write_len	= PAGE_SIZE,
4393 	.open			= cgroup_file_open,
4394 	.release		= cgroup_file_release,
4395 	.write			= cgroup_file_write,
4396 	.poll			= cgroup_file_poll,
4397 	.seq_start		= cgroup_seqfile_start,
4398 	.seq_next		= cgroup_seqfile_next,
4399 	.seq_stop		= cgroup_seqfile_stop,
4400 	.seq_show		= cgroup_seqfile_show,
4401 };
4402 
cgroup_file_notify_timer(struct timer_list * timer)4403 static void cgroup_file_notify_timer(struct timer_list *timer)
4404 {
4405 	cgroup_file_notify(container_of(timer, struct cgroup_file,
4406 					notify_timer));
4407 }
4408 
cgroup_add_file(struct cgroup_subsys_state * css,struct cgroup * cgrp,struct cftype * cft)4409 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
4410 			   struct cftype *cft)
4411 {
4412 	char name[CGROUP_FILE_NAME_MAX];
4413 	struct kernfs_node *kn;
4414 	struct lock_class_key *key = NULL;
4415 
4416 #ifdef CONFIG_DEBUG_LOCK_ALLOC
4417 	key = &cft->lockdep_key;
4418 #endif
4419 	kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
4420 				  cgroup_file_mode(cft),
4421 				  current_fsuid(), current_fsgid(),
4422 				  0, cft->kf_ops, cft,
4423 				  NULL, key);
4424 	if (IS_ERR(kn))
4425 		return PTR_ERR(kn);
4426 
4427 	if (cft->file_offset) {
4428 		struct cgroup_file *cfile = (void *)css + cft->file_offset;
4429 
4430 		timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
4431 
4432 		spin_lock_irq(&cgroup_file_kn_lock);
4433 		cfile->kn = kn;
4434 		spin_unlock_irq(&cgroup_file_kn_lock);
4435 	}
4436 
4437 	return 0;
4438 }
4439 
4440 /**
4441  * cgroup_addrm_files - add or remove files to a cgroup directory
4442  * @css: the target css
4443  * @cgrp: the target cgroup (usually css->cgroup)
4444  * @cfts: array of cftypes to be added
4445  * @is_add: whether to add or remove
4446  *
4447  * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
4448  * For removals, this function never fails.
4449  */
cgroup_addrm_files(struct cgroup_subsys_state * css,struct cgroup * cgrp,struct cftype cfts[],bool is_add)4450 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
4451 			      struct cgroup *cgrp, struct cftype cfts[],
4452 			      bool is_add)
4453 {
4454 	struct cftype *cft, *cft_end = NULL;
4455 	int ret = 0;
4456 
4457 	lockdep_assert_held(&cgroup_mutex);
4458 
4459 restart:
4460 	for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
4461 		/* does cft->flags tell us to skip this file on @cgrp? */
4462 		if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
4463 			continue;
4464 		if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
4465 			continue;
4466 		if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
4467 			continue;
4468 		if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
4469 			continue;
4470 		if ((cft->flags & CFTYPE_DEBUG) && !cgroup_debug)
4471 			continue;
4472 		if (is_add) {
4473 			ret = cgroup_add_file(css, cgrp, cft);
4474 			if (ret) {
4475 				pr_warn("%s: failed to add %s, err=%d\n",
4476 					__func__, cft->name, ret);
4477 				cft_end = cft;
4478 				is_add = false;
4479 				goto restart;
4480 			}
4481 		} else {
4482 			cgroup_rm_file(cgrp, cft);
4483 		}
4484 	}
4485 	return ret;
4486 }
4487 
cgroup_apply_cftypes(struct cftype * cfts,bool is_add)4488 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
4489 {
4490 	struct cgroup_subsys *ss = cfts[0].ss;
4491 	struct cgroup *root = &ss->root->cgrp;
4492 	struct cgroup_subsys_state *css;
4493 	int ret = 0;
4494 
4495 	lockdep_assert_held(&cgroup_mutex);
4496 
4497 	/* add/rm files for all cgroups created before */
4498 	css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
4499 		struct cgroup *cgrp = css->cgroup;
4500 
4501 		if (!(css->flags & CSS_VISIBLE))
4502 			continue;
4503 
4504 		ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
4505 		if (ret)
4506 			break;
4507 	}
4508 
4509 	if (is_add && !ret)
4510 		kernfs_activate(root->kn);
4511 	return ret;
4512 }
4513 
cgroup_exit_cftypes(struct cftype * cfts)4514 static void cgroup_exit_cftypes(struct cftype *cfts)
4515 {
4516 	struct cftype *cft;
4517 
4518 	for (cft = cfts; cft->name[0] != '\0'; cft++) {
4519 		/* free copy for custom atomic_write_len, see init_cftypes() */
4520 		if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
4521 			kfree(cft->kf_ops);
4522 		cft->kf_ops = NULL;
4523 		cft->ss = NULL;
4524 
4525 		/* revert flags set by cgroup core while adding @cfts */
4526 		cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL |
4527 				__CFTYPE_ADDED);
4528 	}
4529 }
4530 
cgroup_init_cftypes(struct cgroup_subsys * ss,struct cftype * cfts)4531 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4532 {
4533 	struct cftype *cft;
4534 	int ret = 0;
4535 
4536 	for (cft = cfts; cft->name[0] != '\0'; cft++) {
4537 		struct kernfs_ops *kf_ops;
4538 
4539 		WARN_ON(cft->ss || cft->kf_ops);
4540 
4541 		if (cft->flags & __CFTYPE_ADDED) {
4542 			ret = -EBUSY;
4543 			break;
4544 		}
4545 
4546 		if (cft->seq_start)
4547 			kf_ops = &cgroup_kf_ops;
4548 		else
4549 			kf_ops = &cgroup_kf_single_ops;
4550 
4551 		/*
4552 		 * Ugh... if @cft wants a custom max_write_len, we need to
4553 		 * make a copy of kf_ops to set its atomic_write_len.
4554 		 */
4555 		if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
4556 			kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
4557 			if (!kf_ops) {
4558 				ret = -ENOMEM;
4559 				break;
4560 			}
4561 			kf_ops->atomic_write_len = cft->max_write_len;
4562 		}
4563 
4564 		cft->kf_ops = kf_ops;
4565 		cft->ss = ss;
4566 		cft->flags |= __CFTYPE_ADDED;
4567 	}
4568 
4569 	if (ret)
4570 		cgroup_exit_cftypes(cfts);
4571 	return ret;
4572 }
4573 
cgroup_rm_cftypes_locked(struct cftype * cfts)4574 static void cgroup_rm_cftypes_locked(struct cftype *cfts)
4575 {
4576 	lockdep_assert_held(&cgroup_mutex);
4577 
4578 	list_del(&cfts->node);
4579 	cgroup_apply_cftypes(cfts, false);
4580 	cgroup_exit_cftypes(cfts);
4581 }
4582 
4583 /**
4584  * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
4585  * @cfts: zero-length name terminated array of cftypes
4586  *
4587  * Unregister @cfts.  Files described by @cfts are removed from all
4588  * existing cgroups and all future cgroups won't have them either.  This
4589  * function can be called anytime whether @cfts' subsys is attached or not.
4590  *
4591  * Returns 0 on successful unregistration, -ENOENT if @cfts is not
4592  * registered.
4593  */
cgroup_rm_cftypes(struct cftype * cfts)4594 int cgroup_rm_cftypes(struct cftype *cfts)
4595 {
4596 	if (!cfts || cfts[0].name[0] == '\0')
4597 		return 0;
4598 
4599 	if (!(cfts[0].flags & __CFTYPE_ADDED))
4600 		return -ENOENT;
4601 
4602 	cgroup_lock();
4603 	cgroup_rm_cftypes_locked(cfts);
4604 	cgroup_unlock();
4605 	return 0;
4606 }
4607 
4608 /**
4609  * cgroup_add_cftypes - add an array of cftypes to a subsystem
4610  * @ss: target cgroup subsystem
4611  * @cfts: zero-length name terminated array of cftypes
4612  *
4613  * Register @cfts to @ss.  Files described by @cfts are created for all
4614  * existing cgroups to which @ss is attached and all future cgroups will
4615  * have them too.  This function can be called anytime whether @ss is
4616  * attached or not.
4617  *
4618  * Returns 0 on successful registration, -errno on failure.  Note that this
4619  * function currently returns 0 as long as @cfts registration is successful
4620  * even if some file creation attempts on existing cgroups fail.
4621  */
cgroup_add_cftypes(struct cgroup_subsys * ss,struct cftype * cfts)4622 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4623 {
4624 	int ret;
4625 
4626 	if (!cgroup_ssid_enabled(ss->id))
4627 		return 0;
4628 
4629 	if (!cfts || cfts[0].name[0] == '\0')
4630 		return 0;
4631 
4632 	ret = cgroup_init_cftypes(ss, cfts);
4633 	if (ret)
4634 		return ret;
4635 
4636 	cgroup_lock();
4637 
4638 	list_add_tail(&cfts->node, &ss->cfts);
4639 	ret = cgroup_apply_cftypes(cfts, true);
4640 	if (ret)
4641 		cgroup_rm_cftypes_locked(cfts);
4642 
4643 	cgroup_unlock();
4644 	return ret;
4645 }
4646 
4647 /**
4648  * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
4649  * @ss: target cgroup subsystem
4650  * @cfts: zero-length name terminated array of cftypes
4651  *
4652  * Similar to cgroup_add_cftypes() but the added files are only used for
4653  * the default hierarchy.
4654  */
cgroup_add_dfl_cftypes(struct cgroup_subsys * ss,struct cftype * cfts)4655 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4656 {
4657 	struct cftype *cft;
4658 
4659 	for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4660 		cft->flags |= __CFTYPE_ONLY_ON_DFL;
4661 	return cgroup_add_cftypes(ss, cfts);
4662 }
4663 
4664 /**
4665  * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
4666  * @ss: target cgroup subsystem
4667  * @cfts: zero-length name terminated array of cftypes
4668  *
4669  * Similar to cgroup_add_cftypes() but the added files are only used for
4670  * the legacy hierarchies.
4671  */
cgroup_add_legacy_cftypes(struct cgroup_subsys * ss,struct cftype * cfts)4672 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4673 {
4674 	struct cftype *cft;
4675 
4676 	for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4677 		cft->flags |= __CFTYPE_NOT_ON_DFL;
4678 	return cgroup_add_cftypes(ss, cfts);
4679 }
4680 
4681 /**
4682  * cgroup_file_notify - generate a file modified event for a cgroup_file
4683  * @cfile: target cgroup_file
4684  *
4685  * @cfile must have been obtained by setting cftype->file_offset.
4686  */
cgroup_file_notify(struct cgroup_file * cfile)4687 void cgroup_file_notify(struct cgroup_file *cfile)
4688 {
4689 	unsigned long flags;
4690 
4691 	spin_lock_irqsave(&cgroup_file_kn_lock, flags);
4692 	if (cfile->kn) {
4693 		unsigned long last = cfile->notified_at;
4694 		unsigned long next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
4695 
4696 		if (time_in_range(jiffies, last, next)) {
4697 			timer_reduce(&cfile->notify_timer, next);
4698 		} else {
4699 			kernfs_notify(cfile->kn);
4700 			cfile->notified_at = jiffies;
4701 		}
4702 	}
4703 	spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
4704 }
4705 EXPORT_SYMBOL_GPL(cgroup_file_notify);
4706 
4707 /**
4708  * cgroup_file_show - show or hide a hidden cgroup file
4709  * @cfile: target cgroup_file obtained by setting cftype->file_offset
4710  * @show: whether to show or hide
4711  */
cgroup_file_show(struct cgroup_file * cfile,bool show)4712 void cgroup_file_show(struct cgroup_file *cfile, bool show)
4713 {
4714 	struct kernfs_node *kn;
4715 
4716 	spin_lock_irq(&cgroup_file_kn_lock);
4717 	kn = cfile->kn;
4718 	kernfs_get(kn);
4719 	spin_unlock_irq(&cgroup_file_kn_lock);
4720 
4721 	if (kn)
4722 		kernfs_show(kn, show);
4723 
4724 	kernfs_put(kn);
4725 }
4726 
4727 /**
4728  * css_next_child - find the next child of a given css
4729  * @pos: the current position (%NULL to initiate traversal)
4730  * @parent: css whose children to walk
4731  *
4732  * This function returns the next child of @parent and should be called
4733  * under either cgroup_mutex or RCU read lock.  The only requirement is
4734  * that @parent and @pos are accessible.  The next sibling is guaranteed to
4735  * be returned regardless of their states.
4736  *
4737  * If a subsystem synchronizes ->css_online() and the start of iteration, a
4738  * css which finished ->css_online() is guaranteed to be visible in the
4739  * future iterations and will stay visible until the last reference is put.
4740  * A css which hasn't finished ->css_online() or already finished
4741  * ->css_offline() may show up during traversal.  It's each subsystem's
4742  * responsibility to synchronize against on/offlining.
4743  */
css_next_child(struct cgroup_subsys_state * pos,struct cgroup_subsys_state * parent)4744 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
4745 					   struct cgroup_subsys_state *parent)
4746 {
4747 	struct cgroup_subsys_state *next;
4748 
4749 	cgroup_assert_mutex_or_rcu_locked();
4750 
4751 	/*
4752 	 * @pos could already have been unlinked from the sibling list.
4753 	 * Once a cgroup is removed, its ->sibling.next is no longer
4754 	 * updated when its next sibling changes.  CSS_RELEASED is set when
4755 	 * @pos is taken off list, at which time its next pointer is valid,
4756 	 * and, as releases are serialized, the one pointed to by the next
4757 	 * pointer is guaranteed to not have started release yet.  This
4758 	 * implies that if we observe !CSS_RELEASED on @pos in this RCU
4759 	 * critical section, the one pointed to by its next pointer is
4760 	 * guaranteed to not have finished its RCU grace period even if we
4761 	 * have dropped rcu_read_lock() in-between iterations.
4762 	 *
4763 	 * If @pos has CSS_RELEASED set, its next pointer can't be
4764 	 * dereferenced; however, as each css is given a monotonically
4765 	 * increasing unique serial number and always appended to the
4766 	 * sibling list, the next one can be found by walking the parent's
4767 	 * children until the first css with higher serial number than
4768 	 * @pos's.  While this path can be slower, it happens iff iteration
4769 	 * races against release and the race window is very small.
4770 	 */
4771 	if (!pos) {
4772 		next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
4773 	} else if (likely(!(pos->flags & CSS_RELEASED))) {
4774 		next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
4775 	} else {
4776 		list_for_each_entry_rcu(next, &parent->children, sibling,
4777 					lockdep_is_held(&cgroup_mutex))
4778 			if (next->serial_nr > pos->serial_nr)
4779 				break;
4780 	}
4781 
4782 	/*
4783 	 * @next, if not pointing to the head, can be dereferenced and is
4784 	 * the next sibling.
4785 	 */
4786 	if (&next->sibling != &parent->children)
4787 		return next;
4788 	return NULL;
4789 }
4790 
4791 /**
4792  * css_next_descendant_pre - find the next descendant for pre-order walk
4793  * @pos: the current position (%NULL to initiate traversal)
4794  * @root: css whose descendants to walk
4795  *
4796  * To be used by css_for_each_descendant_pre().  Find the next descendant
4797  * to visit for pre-order traversal of @root's descendants.  @root is
4798  * included in the iteration and the first node to be visited.
4799  *
4800  * While this function requires cgroup_mutex or RCU read locking, it
4801  * doesn't require the whole traversal to be contained in a single critical
4802  * section. Additionally, it isn't necessary to hold onto a reference to @pos.
4803  * This function will return the correct next descendant as long as both @pos
4804  * and @root are accessible and @pos is a descendant of @root.
4805  *
4806  * If a subsystem synchronizes ->css_online() and the start of iteration, a
4807  * css which finished ->css_online() is guaranteed to be visible in the
4808  * future iterations and will stay visible until the last reference is put.
4809  * A css which hasn't finished ->css_online() or already finished
4810  * ->css_offline() may show up during traversal.  It's each subsystem's
4811  * responsibility to synchronize against on/offlining.
4812  */
4813 struct cgroup_subsys_state *
css_next_descendant_pre(struct cgroup_subsys_state * pos,struct cgroup_subsys_state * root)4814 css_next_descendant_pre(struct cgroup_subsys_state *pos,
4815 			struct cgroup_subsys_state *root)
4816 {
4817 	struct cgroup_subsys_state *next;
4818 
4819 	cgroup_assert_mutex_or_rcu_locked();
4820 
4821 	/* if first iteration, visit @root */
4822 	if (!pos)
4823 		return root;
4824 
4825 	/* visit the first child if exists */
4826 	next = css_next_child(NULL, pos);
4827 	if (next)
4828 		return next;
4829 
4830 	/* no child, visit my or the closest ancestor's next sibling */
4831 	while (pos != root) {
4832 		next = css_next_child(pos, pos->parent);
4833 		if (next)
4834 			return next;
4835 		pos = pos->parent;
4836 	}
4837 
4838 	return NULL;
4839 }
4840 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
4841 
4842 /**
4843  * css_rightmost_descendant - return the rightmost descendant of a css
4844  * @pos: css of interest
4845  *
4846  * Return the rightmost descendant of @pos.  If there's no descendant, @pos
4847  * is returned.  This can be used during pre-order traversal to skip
4848  * subtree of @pos.
4849  *
4850  * While this function requires cgroup_mutex or RCU read locking, it
4851  * doesn't require the whole traversal to be contained in a single critical
4852  * section. Additionally, it isn't necessary to hold onto a reference to @pos.
4853  * This function will return the correct rightmost descendant as long as @pos
4854  * is accessible.
4855  */
4856 struct cgroup_subsys_state *
css_rightmost_descendant(struct cgroup_subsys_state * pos)4857 css_rightmost_descendant(struct cgroup_subsys_state *pos)
4858 {
4859 	struct cgroup_subsys_state *last, *tmp;
4860 
4861 	cgroup_assert_mutex_or_rcu_locked();
4862 
4863 	do {
4864 		last = pos;
4865 		/* ->prev isn't RCU safe, walk ->next till the end */
4866 		pos = NULL;
4867 		css_for_each_child(tmp, last)
4868 			pos = tmp;
4869 	} while (pos);
4870 
4871 	return last;
4872 }
4873 
4874 static struct cgroup_subsys_state *
css_leftmost_descendant(struct cgroup_subsys_state * pos)4875 css_leftmost_descendant(struct cgroup_subsys_state *pos)
4876 {
4877 	struct cgroup_subsys_state *last;
4878 
4879 	do {
4880 		last = pos;
4881 		pos = css_next_child(NULL, pos);
4882 	} while (pos);
4883 
4884 	return last;
4885 }
4886 
4887 /**
4888  * css_next_descendant_post - find the next descendant for post-order walk
4889  * @pos: the current position (%NULL to initiate traversal)
4890  * @root: css whose descendants to walk
4891  *
4892  * To be used by css_for_each_descendant_post().  Find the next descendant
4893  * to visit for post-order traversal of @root's descendants.  @root is
4894  * included in the iteration and the last node to be visited.
4895  *
4896  * While this function requires cgroup_mutex or RCU read locking, it
4897  * doesn't require the whole traversal to be contained in a single critical
4898  * section. Additionally, it isn't necessary to hold onto a reference to @pos.
4899  * This function will return the correct next descendant as long as both @pos
4900  * and @cgroup are accessible and @pos is a descendant of @cgroup.
4901  *
4902  * If a subsystem synchronizes ->css_online() and the start of iteration, a
4903  * css which finished ->css_online() is guaranteed to be visible in the
4904  * future iterations and will stay visible until the last reference is put.
4905  * A css which hasn't finished ->css_online() or already finished
4906  * ->css_offline() may show up during traversal.  It's each subsystem's
4907  * responsibility to synchronize against on/offlining.
4908  */
4909 struct cgroup_subsys_state *
css_next_descendant_post(struct cgroup_subsys_state * pos,struct cgroup_subsys_state * root)4910 css_next_descendant_post(struct cgroup_subsys_state *pos,
4911 			 struct cgroup_subsys_state *root)
4912 {
4913 	struct cgroup_subsys_state *next;
4914 
4915 	cgroup_assert_mutex_or_rcu_locked();
4916 
4917 	/* if first iteration, visit leftmost descendant which may be @root */
4918 	if (!pos)
4919 		return css_leftmost_descendant(root);
4920 
4921 	/* if we visited @root, we're done */
4922 	if (pos == root)
4923 		return NULL;
4924 
4925 	/* if there's an unvisited sibling, visit its leftmost descendant */
4926 	next = css_next_child(pos, pos->parent);
4927 	if (next)
4928 		return css_leftmost_descendant(next);
4929 
4930 	/* no sibling left, visit parent */
4931 	return pos->parent;
4932 }
4933 
4934 /**
4935  * css_has_online_children - does a css have online children
4936  * @css: the target css
4937  *
4938  * Returns %true if @css has any online children; otherwise, %false.  This
4939  * function can be called from any context but the caller is responsible
4940  * for synchronizing against on/offlining as necessary.
4941  */
css_has_online_children(struct cgroup_subsys_state * css)4942 bool css_has_online_children(struct cgroup_subsys_state *css)
4943 {
4944 	struct cgroup_subsys_state *child;
4945 	bool ret = false;
4946 
4947 	rcu_read_lock();
4948 	css_for_each_child(child, css) {
4949 		if (css_is_online(child)) {
4950 			ret = true;
4951 			break;
4952 		}
4953 	}
4954 	rcu_read_unlock();
4955 	return ret;
4956 }
4957 
css_task_iter_next_css_set(struct css_task_iter * it)4958 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4959 {
4960 	struct list_head *l;
4961 	struct cgrp_cset_link *link;
4962 	struct css_set *cset;
4963 
4964 	lockdep_assert_held(&css_set_lock);
4965 
4966 	/* find the next threaded cset */
4967 	if (it->tcset_pos) {
4968 		l = it->tcset_pos->next;
4969 
4970 		if (l != it->tcset_head) {
4971 			it->tcset_pos = l;
4972 			return container_of(l, struct css_set,
4973 					    threaded_csets_node);
4974 		}
4975 
4976 		it->tcset_pos = NULL;
4977 	}
4978 
4979 	/* find the next cset */
4980 	l = it->cset_pos;
4981 	l = l->next;
4982 	if (l == it->cset_head) {
4983 		it->cset_pos = NULL;
4984 		return NULL;
4985 	}
4986 
4987 	if (it->ss) {
4988 		cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4989 	} else {
4990 		link = list_entry(l, struct cgrp_cset_link, cset_link);
4991 		cset = link->cset;
4992 	}
4993 
4994 	it->cset_pos = l;
4995 
4996 	/* initialize threaded css_set walking */
4997 	if (it->flags & CSS_TASK_ITER_THREADED) {
4998 		if (it->cur_dcset)
4999 			put_css_set_locked(it->cur_dcset);
5000 		it->cur_dcset = cset;
5001 		get_css_set(cset);
5002 
5003 		it->tcset_head = &cset->threaded_csets;
5004 		it->tcset_pos = &cset->threaded_csets;
5005 	}
5006 
5007 	return cset;
5008 }
5009 
5010 /**
5011  * css_task_iter_advance_css_set - advance a task iterator to the next css_set
5012  * @it: the iterator to advance
5013  *
5014  * Advance @it to the next css_set to walk.
5015  */
css_task_iter_advance_css_set(struct css_task_iter * it)5016 static void css_task_iter_advance_css_set(struct css_task_iter *it)
5017 {
5018 	struct css_set *cset;
5019 
5020 	lockdep_assert_held(&css_set_lock);
5021 
5022 	/* Advance to the next non-empty css_set and find first non-empty tasks list*/
5023 	while ((cset = css_task_iter_next_css_set(it))) {
5024 		if (!list_empty(&cset->tasks)) {
5025 			it->cur_tasks_head = &cset->tasks;
5026 			break;
5027 		} else if (!list_empty(&cset->mg_tasks)) {
5028 			it->cur_tasks_head = &cset->mg_tasks;
5029 			break;
5030 		} else if (!list_empty(&cset->dying_tasks)) {
5031 			it->cur_tasks_head = &cset->dying_tasks;
5032 			break;
5033 		}
5034 	}
5035 	if (!cset) {
5036 		it->task_pos = NULL;
5037 		return;
5038 	}
5039 	it->task_pos = it->cur_tasks_head->next;
5040 
5041 	/*
5042 	 * We don't keep css_sets locked across iteration steps and thus
5043 	 * need to take steps to ensure that iteration can be resumed after
5044 	 * the lock is re-acquired.  Iteration is performed at two levels -
5045 	 * css_sets and tasks in them.
5046 	 *
5047 	 * Once created, a css_set never leaves its cgroup lists, so a
5048 	 * pinned css_set is guaranteed to stay put and we can resume
5049 	 * iteration afterwards.
5050 	 *
5051 	 * Tasks may leave @cset across iteration steps.  This is resolved
5052 	 * by registering each iterator with the css_set currently being
5053 	 * walked and making css_set_move_task() advance iterators whose
5054 	 * next task is leaving.
5055 	 */
5056 	if (it->cur_cset) {
5057 		list_del(&it->iters_node);
5058 		put_css_set_locked(it->cur_cset);
5059 	}
5060 	get_css_set(cset);
5061 	it->cur_cset = cset;
5062 	list_add(&it->iters_node, &cset->task_iters);
5063 }
5064 
css_task_iter_skip(struct css_task_iter * it,struct task_struct * task)5065 static void css_task_iter_skip(struct css_task_iter *it,
5066 			       struct task_struct *task)
5067 {
5068 	lockdep_assert_held(&css_set_lock);
5069 
5070 	if (it->task_pos == &task->cg_list) {
5071 		it->task_pos = it->task_pos->next;
5072 		it->flags |= CSS_TASK_ITER_SKIPPED;
5073 	}
5074 }
5075 
css_task_iter_advance(struct css_task_iter * it)5076 static void css_task_iter_advance(struct css_task_iter *it)
5077 {
5078 	struct task_struct *task;
5079 
5080 	lockdep_assert_held(&css_set_lock);
5081 repeat:
5082 	if (it->task_pos) {
5083 		/*
5084 		 * Advance iterator to find next entry. We go through cset
5085 		 * tasks, mg_tasks and dying_tasks, when consumed we move onto
5086 		 * the next cset.
5087 		 */
5088 		if (it->flags & CSS_TASK_ITER_SKIPPED)
5089 			it->flags &= ~CSS_TASK_ITER_SKIPPED;
5090 		else
5091 			it->task_pos = it->task_pos->next;
5092 
5093 		if (it->task_pos == &it->cur_cset->tasks) {
5094 			it->cur_tasks_head = &it->cur_cset->mg_tasks;
5095 			it->task_pos = it->cur_tasks_head->next;
5096 		}
5097 		if (it->task_pos == &it->cur_cset->mg_tasks) {
5098 			it->cur_tasks_head = &it->cur_cset->dying_tasks;
5099 			it->task_pos = it->cur_tasks_head->next;
5100 		}
5101 		if (it->task_pos == &it->cur_cset->dying_tasks)
5102 			css_task_iter_advance_css_set(it);
5103 	} else {
5104 		/* called from start, proceed to the first cset */
5105 		css_task_iter_advance_css_set(it);
5106 	}
5107 
5108 	if (!it->task_pos)
5109 		return;
5110 
5111 	task = list_entry(it->task_pos, struct task_struct, cg_list);
5112 
5113 	if (it->flags & CSS_TASK_ITER_PROCS) {
5114 		/* if PROCS, skip over tasks which aren't group leaders */
5115 		if (!thread_group_leader(task))
5116 			goto repeat;
5117 
5118 		/* and dying leaders w/o live member threads */
5119 		if (it->cur_tasks_head == &it->cur_cset->dying_tasks &&
5120 		    !atomic_read(&task->signal->live))
5121 			goto repeat;
5122 	} else {
5123 		/* skip all dying ones */
5124 		if (it->cur_tasks_head == &it->cur_cset->dying_tasks)
5125 			goto repeat;
5126 	}
5127 }
5128 
5129 /**
5130  * css_task_iter_start - initiate task iteration
5131  * @css: the css to walk tasks of
5132  * @flags: CSS_TASK_ITER_* flags
5133  * @it: the task iterator to use
5134  *
5135  * Initiate iteration through the tasks of @css.  The caller can call
5136  * css_task_iter_next() to walk through the tasks until the function
5137  * returns NULL.  On completion of iteration, css_task_iter_end() must be
5138  * called.
5139  */
css_task_iter_start(struct cgroup_subsys_state * css,unsigned int flags,struct css_task_iter * it)5140 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
5141 			 struct css_task_iter *it)
5142 {
5143 	unsigned long irqflags;
5144 
5145 	memset(it, 0, sizeof(*it));
5146 
5147 	spin_lock_irqsave(&css_set_lock, irqflags);
5148 
5149 	it->ss = css->ss;
5150 	it->flags = flags;
5151 
5152 	if (CGROUP_HAS_SUBSYS_CONFIG && it->ss)
5153 		it->cset_pos = &css->cgroup->e_csets[css->ss->id];
5154 	else
5155 		it->cset_pos = &css->cgroup->cset_links;
5156 
5157 	it->cset_head = it->cset_pos;
5158 
5159 	css_task_iter_advance(it);
5160 
5161 	spin_unlock_irqrestore(&css_set_lock, irqflags);
5162 }
5163 
5164 /**
5165  * css_task_iter_next - return the next task for the iterator
5166  * @it: the task iterator being iterated
5167  *
5168  * The "next" function for task iteration.  @it should have been
5169  * initialized via css_task_iter_start().  Returns NULL when the iteration
5170  * reaches the end.
5171  */
css_task_iter_next(struct css_task_iter * it)5172 struct task_struct *css_task_iter_next(struct css_task_iter *it)
5173 {
5174 	unsigned long irqflags;
5175 
5176 	if (it->cur_task) {
5177 		put_task_struct(it->cur_task);
5178 		it->cur_task = NULL;
5179 	}
5180 
5181 	spin_lock_irqsave(&css_set_lock, irqflags);
5182 
5183 	/* @it may be half-advanced by skips, finish advancing */
5184 	if (it->flags & CSS_TASK_ITER_SKIPPED)
5185 		css_task_iter_advance(it);
5186 
5187 	if (it->task_pos) {
5188 		it->cur_task = list_entry(it->task_pos, struct task_struct,
5189 					  cg_list);
5190 		get_task_struct(it->cur_task);
5191 		css_task_iter_advance(it);
5192 	}
5193 
5194 	spin_unlock_irqrestore(&css_set_lock, irqflags);
5195 
5196 	return it->cur_task;
5197 }
5198 
5199 /**
5200  * css_task_iter_end - finish task iteration
5201  * @it: the task iterator to finish
5202  *
5203  * Finish task iteration started by css_task_iter_start().
5204  */
css_task_iter_end(struct css_task_iter * it)5205 void css_task_iter_end(struct css_task_iter *it)
5206 {
5207 	unsigned long irqflags;
5208 
5209 	if (it->cur_cset) {
5210 		spin_lock_irqsave(&css_set_lock, irqflags);
5211 		list_del(&it->iters_node);
5212 		put_css_set_locked(it->cur_cset);
5213 		spin_unlock_irqrestore(&css_set_lock, irqflags);
5214 	}
5215 
5216 	if (it->cur_dcset)
5217 		put_css_set(it->cur_dcset);
5218 
5219 	if (it->cur_task)
5220 		put_task_struct(it->cur_task);
5221 }
5222 
cgroup_procs_release(struct kernfs_open_file * of)5223 static void cgroup_procs_release(struct kernfs_open_file *of)
5224 {
5225 	struct cgroup_file_ctx *ctx = of->priv;
5226 
5227 	if (ctx->procs.started)
5228 		css_task_iter_end(&ctx->procs.iter);
5229 }
5230 
cgroup_procs_next(struct seq_file * s,void * v,loff_t * pos)5231 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
5232 {
5233 	struct kernfs_open_file *of = s->private;
5234 	struct cgroup_file_ctx *ctx = of->priv;
5235 
5236 	if (pos)
5237 		(*pos)++;
5238 
5239 	return css_task_iter_next(&ctx->procs.iter);
5240 }
5241 
__cgroup_procs_start(struct seq_file * s,loff_t * pos,unsigned int iter_flags)5242 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
5243 				  unsigned int iter_flags)
5244 {
5245 	struct kernfs_open_file *of = s->private;
5246 	struct cgroup *cgrp = seq_css(s)->cgroup;
5247 	struct cgroup_file_ctx *ctx = of->priv;
5248 	struct css_task_iter *it = &ctx->procs.iter;
5249 
5250 	/*
5251 	 * When a seq_file is seeked, it's always traversed sequentially
5252 	 * from position 0, so we can simply keep iterating on !0 *pos.
5253 	 */
5254 	if (!ctx->procs.started) {
5255 		if (WARN_ON_ONCE((*pos)))
5256 			return ERR_PTR(-EINVAL);
5257 		css_task_iter_start(&cgrp->self, iter_flags, it);
5258 		ctx->procs.started = true;
5259 	} else if (!(*pos)) {
5260 		css_task_iter_end(it);
5261 		css_task_iter_start(&cgrp->self, iter_flags, it);
5262 	} else
5263 		return it->cur_task;
5264 
5265 	return cgroup_procs_next(s, NULL, NULL);
5266 }
5267 
cgroup_procs_start(struct seq_file * s,loff_t * pos)5268 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
5269 {
5270 	struct cgroup *cgrp = seq_css(s)->cgroup;
5271 
5272 	/*
5273 	 * All processes of a threaded subtree belong to the domain cgroup
5274 	 * of the subtree.  Only threads can be distributed across the
5275 	 * subtree.  Reject reads on cgroup.procs in the subtree proper.
5276 	 * They're always empty anyway.
5277 	 */
5278 	if (cgroup_is_threaded(cgrp))
5279 		return ERR_PTR(-EOPNOTSUPP);
5280 
5281 	return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
5282 					    CSS_TASK_ITER_THREADED);
5283 }
5284 
cgroup_procs_show(struct seq_file * s,void * v)5285 static int cgroup_procs_show(struct seq_file *s, void *v)
5286 {
5287 	seq_printf(s, "%d\n", task_pid_vnr(v));
5288 	return 0;
5289 }
5290 
cgroup_may_write(const struct cgroup * cgrp,struct super_block * sb)5291 static int cgroup_may_write(const struct cgroup *cgrp, struct super_block *sb)
5292 {
5293 	int ret;
5294 	struct inode *inode;
5295 
5296 	lockdep_assert_held(&cgroup_mutex);
5297 
5298 	inode = kernfs_get_inode(sb, cgrp->procs_file.kn);
5299 	if (!inode)
5300 		return -ENOMEM;
5301 
5302 	ret = inode_permission(&nop_mnt_idmap, inode, MAY_WRITE);
5303 	iput(inode);
5304 	return ret;
5305 }
5306 
cgroup_procs_write_permission(struct cgroup * src_cgrp,struct cgroup * dst_cgrp,struct super_block * sb,struct cgroup_namespace * ns)5307 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
5308 					 struct cgroup *dst_cgrp,
5309 					 struct super_block *sb,
5310 					 struct cgroup_namespace *ns)
5311 {
5312 	struct cgroup *com_cgrp = src_cgrp;
5313 	int ret;
5314 
5315 	lockdep_assert_held(&cgroup_mutex);
5316 
5317 	/* find the common ancestor */
5318 	while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
5319 		com_cgrp = cgroup_parent(com_cgrp);
5320 
5321 	/* %current should be authorized to migrate to the common ancestor */
5322 	ret = cgroup_may_write(com_cgrp, sb);
5323 	if (ret)
5324 		return ret;
5325 
5326 	/*
5327 	 * If namespaces are delegation boundaries, %current must be able
5328 	 * to see both source and destination cgroups from its namespace.
5329 	 */
5330 	if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
5331 	    (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
5332 	     !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
5333 		return -ENOENT;
5334 
5335 	return 0;
5336 }
5337 
cgroup_attach_permissions(struct cgroup * src_cgrp,struct cgroup * dst_cgrp,struct super_block * sb,bool threadgroup,struct cgroup_namespace * ns)5338 static int cgroup_attach_permissions(struct cgroup *src_cgrp,
5339 				     struct cgroup *dst_cgrp,
5340 				     struct super_block *sb, bool threadgroup,
5341 				     struct cgroup_namespace *ns)
5342 {
5343 	int ret = 0;
5344 
5345 	ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp, sb, ns);
5346 	if (ret)
5347 		return ret;
5348 
5349 	ret = cgroup_migrate_vet_dst(dst_cgrp);
5350 	if (ret)
5351 		return ret;
5352 
5353 	if (!threadgroup && (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp))
5354 		ret = -EOPNOTSUPP;
5355 
5356 	return ret;
5357 }
5358 
__cgroup_procs_write(struct kernfs_open_file * of,char * buf,bool threadgroup)5359 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
5360 				    bool threadgroup)
5361 {
5362 	struct cgroup_file_ctx *ctx = of->priv;
5363 	struct cgroup *src_cgrp, *dst_cgrp;
5364 	struct task_struct *task;
5365 	ssize_t ret;
5366 	enum cgroup_attach_lock_mode lock_mode;
5367 
5368 	dst_cgrp = cgroup_kn_lock_live(of->kn, false);
5369 	if (!dst_cgrp)
5370 		return -ENODEV;
5371 
5372 	task = cgroup_procs_write_start(buf, threadgroup, &lock_mode);
5373 	ret = PTR_ERR_OR_ZERO(task);
5374 	if (ret)
5375 		goto out_unlock;
5376 
5377 	/* find the source cgroup */
5378 	spin_lock_irq(&css_set_lock);
5379 	src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
5380 	spin_unlock_irq(&css_set_lock);
5381 
5382 	/*
5383 	 * Process and thread migrations follow same delegation rule. Check
5384 	 * permissions using the credentials from file open to protect against
5385 	 * inherited fd attacks.
5386 	 */
5387 	scoped_with_creds(of->file->f_cred)
5388 		ret = cgroup_attach_permissions(src_cgrp, dst_cgrp,
5389 						of->file->f_path.dentry->d_sb,
5390 						threadgroup, ctx->ns);
5391 	if (ret)
5392 		goto out_finish;
5393 
5394 	ret = cgroup_attach_task(dst_cgrp, task, threadgroup);
5395 
5396 out_finish:
5397 	cgroup_procs_write_finish(task, lock_mode);
5398 out_unlock:
5399 	cgroup_kn_unlock(of->kn);
5400 
5401 	return ret;
5402 }
5403 
cgroup_procs_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)5404 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
5405 				  char *buf, size_t nbytes, loff_t off)
5406 {
5407 	return __cgroup_procs_write(of, buf, true) ?: nbytes;
5408 }
5409 
cgroup_threads_start(struct seq_file * s,loff_t * pos)5410 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
5411 {
5412 	return __cgroup_procs_start(s, pos, 0);
5413 }
5414 
cgroup_threads_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)5415 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
5416 				    char *buf, size_t nbytes, loff_t off)
5417 {
5418 	return __cgroup_procs_write(of, buf, false) ?: nbytes;
5419 }
5420 
5421 /* cgroup core interface files for the default hierarchy */
5422 static struct cftype cgroup_base_files[] = {
5423 	{
5424 		.name = "cgroup.type",
5425 		.flags = CFTYPE_NOT_ON_ROOT,
5426 		.seq_show = cgroup_type_show,
5427 		.write = cgroup_type_write,
5428 	},
5429 	{
5430 		.name = "cgroup.procs",
5431 		.flags = CFTYPE_NS_DELEGATABLE,
5432 		.file_offset = offsetof(struct cgroup, procs_file),
5433 		.release = cgroup_procs_release,
5434 		.seq_start = cgroup_procs_start,
5435 		.seq_next = cgroup_procs_next,
5436 		.seq_show = cgroup_procs_show,
5437 		.write = cgroup_procs_write,
5438 	},
5439 	{
5440 		.name = "cgroup.threads",
5441 		.flags = CFTYPE_NS_DELEGATABLE,
5442 		.release = cgroup_procs_release,
5443 		.seq_start = cgroup_threads_start,
5444 		.seq_next = cgroup_procs_next,
5445 		.seq_show = cgroup_procs_show,
5446 		.write = cgroup_threads_write,
5447 	},
5448 	{
5449 		.name = "cgroup.controllers",
5450 		.seq_show = cgroup_controllers_show,
5451 	},
5452 	{
5453 		.name = "cgroup.subtree_control",
5454 		.flags = CFTYPE_NS_DELEGATABLE,
5455 		.seq_show = cgroup_subtree_control_show,
5456 		.write = cgroup_subtree_control_write,
5457 	},
5458 	{
5459 		.name = "cgroup.events",
5460 		.flags = CFTYPE_NOT_ON_ROOT,
5461 		.file_offset = offsetof(struct cgroup, events_file),
5462 		.seq_show = cgroup_events_show,
5463 	},
5464 	{
5465 		.name = "cgroup.max.descendants",
5466 		.seq_show = cgroup_max_descendants_show,
5467 		.write = cgroup_max_descendants_write,
5468 	},
5469 	{
5470 		.name = "cgroup.max.depth",
5471 		.seq_show = cgroup_max_depth_show,
5472 		.write = cgroup_max_depth_write,
5473 	},
5474 	{
5475 		.name = "cgroup.stat",
5476 		.seq_show = cgroup_stat_show,
5477 	},
5478 	{
5479 		.name = "cgroup.stat.local",
5480 		.flags = CFTYPE_NOT_ON_ROOT,
5481 		.seq_show = cgroup_core_local_stat_show,
5482 	},
5483 	{
5484 		.name = "cgroup.freeze",
5485 		.flags = CFTYPE_NOT_ON_ROOT,
5486 		.seq_show = cgroup_freeze_show,
5487 		.write = cgroup_freeze_write,
5488 	},
5489 	{
5490 		.name = "cgroup.kill",
5491 		.flags = CFTYPE_NOT_ON_ROOT,
5492 		.write = cgroup_kill_write,
5493 	},
5494 	{
5495 		.name = "cpu.stat",
5496 		.seq_show = cpu_stat_show,
5497 	},
5498 	{
5499 		.name = "cpu.stat.local",
5500 		.seq_show = cpu_local_stat_show,
5501 	},
5502 	{ }	/* terminate */
5503 };
5504 
5505 static struct cftype cgroup_psi_files[] = {
5506 #ifdef CONFIG_PSI
5507 	{
5508 		.name = "io.pressure",
5509 		.file_offset = offsetof(struct cgroup, psi_files[PSI_IO]),
5510 		.seq_show = cgroup_io_pressure_show,
5511 		.write = cgroup_io_pressure_write,
5512 		.poll = cgroup_pressure_poll,
5513 		.release = cgroup_pressure_release,
5514 	},
5515 	{
5516 		.name = "memory.pressure",
5517 		.file_offset = offsetof(struct cgroup, psi_files[PSI_MEM]),
5518 		.seq_show = cgroup_memory_pressure_show,
5519 		.write = cgroup_memory_pressure_write,
5520 		.poll = cgroup_pressure_poll,
5521 		.release = cgroup_pressure_release,
5522 	},
5523 	{
5524 		.name = "cpu.pressure",
5525 		.file_offset = offsetof(struct cgroup, psi_files[PSI_CPU]),
5526 		.seq_show = cgroup_cpu_pressure_show,
5527 		.write = cgroup_cpu_pressure_write,
5528 		.poll = cgroup_pressure_poll,
5529 		.release = cgroup_pressure_release,
5530 	},
5531 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
5532 	{
5533 		.name = "irq.pressure",
5534 		.file_offset = offsetof(struct cgroup, psi_files[PSI_IRQ]),
5535 		.seq_show = cgroup_irq_pressure_show,
5536 		.write = cgroup_irq_pressure_write,
5537 		.poll = cgroup_pressure_poll,
5538 		.release = cgroup_pressure_release,
5539 	},
5540 #endif
5541 	{
5542 		.name = "cgroup.pressure",
5543 		.seq_show = cgroup_pressure_show,
5544 		.write = cgroup_pressure_write,
5545 	},
5546 #endif /* CONFIG_PSI */
5547 	{ }	/* terminate */
5548 };
5549 
5550 /*
5551  * css destruction is four-stage process.
5552  *
5553  * 1. Destruction starts.  Killing of the percpu_ref is initiated.
5554  *    Implemented in kill_css().
5555  *
5556  * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
5557  *    and thus css_tryget_online() is guaranteed to fail, the css can be
5558  *    offlined by invoking offline_css().  After offlining, the base ref is
5559  *    put.  Implemented in css_killed_work_fn().
5560  *
5561  * 3. When the percpu_ref reaches zero, the only possible remaining
5562  *    accessors are inside RCU read sections.  css_release() schedules the
5563  *    RCU callback.
5564  *
5565  * 4. After the grace period, the css can be freed.  Implemented in
5566  *    css_free_rwork_fn().
5567  *
5568  * It is actually hairier because both step 2 and 4 require process context
5569  * and thus involve punting to css->destroy_work adding two additional
5570  * steps to the already complex sequence.
5571  */
css_free_rwork_fn(struct work_struct * work)5572 static void css_free_rwork_fn(struct work_struct *work)
5573 {
5574 	struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
5575 				struct cgroup_subsys_state, destroy_rwork);
5576 	struct cgroup_subsys *ss = css->ss;
5577 	struct cgroup *cgrp = css->cgroup;
5578 
5579 	percpu_ref_exit(&css->refcnt);
5580 	css_rstat_exit(css);
5581 
5582 	if (!css_is_self(css)) {
5583 		/* css free path */
5584 		struct cgroup_subsys_state *parent = css->parent;
5585 		int id = css->id;
5586 
5587 		ss->css_free(css);
5588 		cgroup_idr_remove(&ss->css_idr, id);
5589 		cgroup_put(cgrp);
5590 
5591 		if (parent)
5592 			css_put(parent);
5593 	} else {
5594 		/* cgroup free path */
5595 		atomic_dec(&cgrp->root->nr_cgrps);
5596 		if (!cgroup_on_dfl(cgrp))
5597 			cgroup1_pidlist_destroy_all(cgrp);
5598 		cancel_work_sync(&cgrp->release_agent_work);
5599 		bpf_cgrp_storage_free(cgrp);
5600 
5601 		if (cgroup_parent(cgrp)) {
5602 			/*
5603 			 * We get a ref to the parent, and put the ref when
5604 			 * this cgroup is being freed, so it's guaranteed
5605 			 * that the parent won't be destroyed before its
5606 			 * children.
5607 			 */
5608 			cgroup_put(cgroup_parent(cgrp));
5609 			kernfs_put(cgrp->kn);
5610 			psi_cgroup_free(cgrp);
5611 			kfree(cgrp);
5612 		} else {
5613 			/*
5614 			 * This is root cgroup's refcnt reaching zero,
5615 			 * which indicates that the root should be
5616 			 * released.
5617 			 */
5618 			cgroup_destroy_root(cgrp->root);
5619 		}
5620 	}
5621 }
5622 
css_release_work_fn(struct work_struct * work)5623 static void css_release_work_fn(struct work_struct *work)
5624 {
5625 	struct cgroup_subsys_state *css =
5626 		container_of(work, struct cgroup_subsys_state, destroy_work);
5627 	struct cgroup_subsys *ss = css->ss;
5628 	struct cgroup *cgrp = css->cgroup;
5629 
5630 	cgroup_lock();
5631 
5632 	css->flags |= CSS_RELEASED;
5633 	list_del_rcu(&css->sibling);
5634 
5635 	if (!css_is_self(css)) {
5636 		struct cgroup *parent_cgrp;
5637 
5638 		css_rstat_flush(css);
5639 
5640 		cgroup_idr_replace(&ss->css_idr, NULL, css->id);
5641 		if (ss->css_released)
5642 			ss->css_released(css);
5643 
5644 		cgrp->nr_dying_subsys[ss->id]--;
5645 		/*
5646 		 * When a css is released and ready to be freed, its
5647 		 * nr_descendants must be zero. However, the corresponding
5648 		 * cgrp->nr_dying_subsys[ss->id] may not be 0 if a subsystem
5649 		 * is activated and deactivated multiple times with one or
5650 		 * more of its previous activation leaving behind dying csses.
5651 		 */
5652 		WARN_ON_ONCE(css->nr_descendants);
5653 		parent_cgrp = cgroup_parent(cgrp);
5654 		while (parent_cgrp) {
5655 			parent_cgrp->nr_dying_subsys[ss->id]--;
5656 			parent_cgrp = cgroup_parent(parent_cgrp);
5657 		}
5658 	} else {
5659 		struct cgroup *tcgrp;
5660 
5661 		/* cgroup release path */
5662 		TRACE_CGROUP_PATH(release, cgrp);
5663 
5664 		css_rstat_flush(&cgrp->self);
5665 
5666 		spin_lock_irq(&css_set_lock);
5667 		for (tcgrp = cgroup_parent(cgrp); tcgrp;
5668 		     tcgrp = cgroup_parent(tcgrp))
5669 			tcgrp->nr_dying_descendants--;
5670 		spin_unlock_irq(&css_set_lock);
5671 
5672 		/*
5673 		 * There are two control paths which try to determine
5674 		 * cgroup from dentry without going through kernfs -
5675 		 * cgroupstats_build() and css_tryget_online_from_dir().
5676 		 * Those are supported by RCU protecting clearing of
5677 		 * cgrp->kn->priv backpointer.
5678 		 */
5679 		if (cgrp->kn)
5680 			RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
5681 					 NULL);
5682 	}
5683 
5684 	cgroup_unlock();
5685 
5686 	INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5687 	queue_rcu_work(cgroup_free_wq, &css->destroy_rwork);
5688 }
5689 
css_release(struct percpu_ref * ref)5690 static void css_release(struct percpu_ref *ref)
5691 {
5692 	struct cgroup_subsys_state *css =
5693 		container_of(ref, struct cgroup_subsys_state, refcnt);
5694 
5695 	INIT_WORK(&css->destroy_work, css_release_work_fn);
5696 	queue_work(cgroup_release_wq, &css->destroy_work);
5697 }
5698 
init_and_link_css(struct cgroup_subsys_state * css,struct cgroup_subsys * ss,struct cgroup * cgrp)5699 static void init_and_link_css(struct cgroup_subsys_state *css,
5700 			      struct cgroup_subsys *ss, struct cgroup *cgrp)
5701 {
5702 	lockdep_assert_held(&cgroup_mutex);
5703 
5704 	cgroup_get_live(cgrp);
5705 
5706 	memset(css, 0, sizeof(*css));
5707 	css->cgroup = cgrp;
5708 	css->ss = ss;
5709 	css->id = -1;
5710 	INIT_LIST_HEAD(&css->sibling);
5711 	INIT_LIST_HEAD(&css->children);
5712 	css->serial_nr = css_serial_nr_next++;
5713 	atomic_set(&css->online_cnt, 0);
5714 
5715 	if (cgroup_parent(cgrp)) {
5716 		css->parent = cgroup_css(cgroup_parent(cgrp), ss);
5717 		css_get(css->parent);
5718 	}
5719 
5720 	BUG_ON(cgroup_css(cgrp, ss));
5721 }
5722 
5723 /* invoke ->css_online() on a new CSS and mark it online if successful */
online_css(struct cgroup_subsys_state * css)5724 static int online_css(struct cgroup_subsys_state *css)
5725 {
5726 	struct cgroup_subsys *ss = css->ss;
5727 	int ret = 0;
5728 
5729 	lockdep_assert_held(&cgroup_mutex);
5730 
5731 	if (ss->css_online)
5732 		ret = ss->css_online(css);
5733 	if (!ret) {
5734 		css->flags |= CSS_ONLINE;
5735 		rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
5736 
5737 		atomic_inc(&css->online_cnt);
5738 		if (css->parent) {
5739 			atomic_inc(&css->parent->online_cnt);
5740 			while ((css = css->parent))
5741 				css->nr_descendants++;
5742 		}
5743 	}
5744 	return ret;
5745 }
5746 
5747 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
offline_css(struct cgroup_subsys_state * css)5748 static void offline_css(struct cgroup_subsys_state *css)
5749 {
5750 	struct cgroup_subsys *ss = css->ss;
5751 
5752 	lockdep_assert_held(&cgroup_mutex);
5753 
5754 	if (!css_is_online(css))
5755 		return;
5756 
5757 	if (ss->css_offline)
5758 		ss->css_offline(css);
5759 
5760 	css->flags &= ~CSS_ONLINE;
5761 	RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
5762 
5763 	wake_up_all(&css->cgroup->offline_waitq);
5764 
5765 	css->cgroup->nr_dying_subsys[ss->id]++;
5766 	/*
5767 	 * Parent css and cgroup cannot be freed until after the freeing
5768 	 * of child css, see css_free_rwork_fn().
5769 	 */
5770 	while ((css = css->parent)) {
5771 		css->nr_descendants--;
5772 		css->cgroup->nr_dying_subsys[ss->id]++;
5773 	}
5774 }
5775 
5776 /**
5777  * css_create - create a cgroup_subsys_state
5778  * @cgrp: the cgroup new css will be associated with
5779  * @ss: the subsys of new css
5780  *
5781  * Create a new css associated with @cgrp - @ss pair.  On success, the new
5782  * css is online and installed in @cgrp.  This function doesn't create the
5783  * interface files.  Returns 0 on success, -errno on failure.
5784  */
css_create(struct cgroup * cgrp,struct cgroup_subsys * ss)5785 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
5786 					      struct cgroup_subsys *ss)
5787 {
5788 	struct cgroup *parent = cgroup_parent(cgrp);
5789 	struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
5790 	struct cgroup_subsys_state *css;
5791 	int err;
5792 
5793 	lockdep_assert_held(&cgroup_mutex);
5794 
5795 	css = ss->css_alloc(parent_css);
5796 	if (!css)
5797 		css = ERR_PTR(-ENOMEM);
5798 	if (IS_ERR(css))
5799 		return css;
5800 
5801 	init_and_link_css(css, ss, cgrp);
5802 
5803 	err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
5804 	if (err)
5805 		goto err_free_css;
5806 
5807 	err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
5808 	if (err < 0)
5809 		goto err_free_css;
5810 	css->id = err;
5811 
5812 	err = css_rstat_init(css);
5813 	if (err)
5814 		goto err_free_css;
5815 
5816 	/* @css is ready to be brought online now, make it visible */
5817 	list_add_tail_rcu(&css->sibling, &parent_css->children);
5818 	cgroup_idr_replace(&ss->css_idr, css, css->id);
5819 
5820 	err = online_css(css);
5821 	if (err)
5822 		goto err_list_del;
5823 
5824 	return css;
5825 
5826 err_list_del:
5827 	list_del_rcu(&css->sibling);
5828 err_free_css:
5829 	INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5830 	queue_rcu_work(cgroup_free_wq, &css->destroy_rwork);
5831 	return ERR_PTR(err);
5832 }
5833 
5834 /*
5835  * The returned cgroup is fully initialized including its control mask, but
5836  * it doesn't have the control mask applied.
5837  */
cgroup_create(struct cgroup * parent,const char * name,umode_t mode)5838 static struct cgroup *cgroup_create(struct cgroup *parent, const char *name,
5839 				    umode_t mode)
5840 {
5841 	struct cgroup_root *root = parent->root;
5842 	struct cgroup *cgrp, *tcgrp;
5843 	struct kernfs_node *kn;
5844 	int i, level = parent->level + 1;
5845 	int ret;
5846 
5847 	/* allocate the cgroup and its ID, 0 is reserved for the root */
5848 	cgrp = kzalloc_flex(*cgrp, _low_ancestors, level);
5849 	if (!cgrp)
5850 		return ERR_PTR(-ENOMEM);
5851 
5852 	ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
5853 	if (ret)
5854 		goto out_free_cgrp;
5855 
5856 	/* create the directory */
5857 	kn = kernfs_create_dir_ns(parent->kn, name, mode,
5858 				  current_fsuid(), current_fsgid(),
5859 				  cgrp, NULL);
5860 	if (IS_ERR(kn)) {
5861 		ret = PTR_ERR(kn);
5862 		goto out_cancel_ref;
5863 	}
5864 	cgrp->kn = kn;
5865 
5866 	init_cgroup_housekeeping(cgrp);
5867 
5868 	cgrp->self.parent = &parent->self;
5869 	cgrp->root = root;
5870 	cgrp->level = level;
5871 
5872 	/*
5873 	 * Now that init_cgroup_housekeeping() has been called and cgrp->self
5874 	 * is setup, it is safe to perform rstat initialization on it.
5875 	 */
5876 	ret = css_rstat_init(&cgrp->self);
5877 	if (ret)
5878 		goto out_kernfs_remove;
5879 
5880 	ret = psi_cgroup_alloc(cgrp);
5881 	if (ret)
5882 		goto out_stat_exit;
5883 
5884 	for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp))
5885 		cgrp->ancestors[tcgrp->level] = tcgrp;
5886 
5887 	/*
5888 	 * New cgroup inherits effective freeze counter, and
5889 	 * if the parent has to be frozen, the child has too.
5890 	 */
5891 	cgrp->freezer.e_freeze = parent->freezer.e_freeze;
5892 	seqcount_spinlock_init(&cgrp->freezer.freeze_seq, &css_set_lock);
5893 	if (cgrp->freezer.e_freeze) {
5894 		/*
5895 		 * Set the CGRP_FREEZE flag, so when a process will be
5896 		 * attached to the child cgroup, it will become frozen.
5897 		 * At this point the new cgroup is unpopulated, so we can
5898 		 * consider it frozen immediately.
5899 		 */
5900 		set_bit(CGRP_FREEZE, &cgrp->flags);
5901 		cgrp->freezer.freeze_start_nsec = ktime_get_ns();
5902 		set_bit(CGRP_FROZEN, &cgrp->flags);
5903 	}
5904 
5905 	if (notify_on_release(parent))
5906 		set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
5907 
5908 	if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
5909 		set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
5910 
5911 	cgrp->self.serial_nr = css_serial_nr_next++;
5912 
5913 	ret = blocking_notifier_call_chain_robust(&cgroup_lifetime_notifier,
5914 						  CGROUP_LIFETIME_ONLINE,
5915 						  CGROUP_LIFETIME_OFFLINE, cgrp);
5916 	ret = notifier_to_errno(ret);
5917 	if (ret)
5918 		goto out_psi_free;
5919 
5920 	/* allocation complete, commit to creation */
5921 	spin_lock_irq(&css_set_lock);
5922 	for (i = 0; i < level; i++) {
5923 		tcgrp = cgrp->ancestors[i];
5924 		tcgrp->nr_descendants++;
5925 
5926 		/*
5927 		 * If the new cgroup is frozen, all ancestor cgroups get a new
5928 		 * frozen descendant, but their state can't change because of
5929 		 * this.
5930 		 */
5931 		if (cgrp->freezer.e_freeze)
5932 			tcgrp->freezer.nr_frozen_descendants++;
5933 	}
5934 	spin_unlock_irq(&css_set_lock);
5935 
5936 	list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
5937 	atomic_inc(&root->nr_cgrps);
5938 	cgroup_get_live(parent);
5939 
5940 	/*
5941 	 * On the default hierarchy, a child doesn't automatically inherit
5942 	 * subtree_control from the parent.  Each is configured manually.
5943 	 */
5944 	if (!cgroup_on_dfl(cgrp))
5945 		cgrp->subtree_control = cgroup_control(cgrp);
5946 
5947 	cgroup_propagate_control(cgrp);
5948 
5949 	return cgrp;
5950 
5951 out_psi_free:
5952 	psi_cgroup_free(cgrp);
5953 out_stat_exit:
5954 	css_rstat_exit(&cgrp->self);
5955 out_kernfs_remove:
5956 	kernfs_remove(cgrp->kn);
5957 out_cancel_ref:
5958 	percpu_ref_exit(&cgrp->self.refcnt);
5959 out_free_cgrp:
5960 	kfree(cgrp);
5961 	return ERR_PTR(ret);
5962 }
5963 
cgroup_check_hierarchy_limits(struct cgroup * parent)5964 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
5965 {
5966 	struct cgroup *cgroup;
5967 	int ret = false;
5968 	int level = 0;
5969 
5970 	lockdep_assert_held(&cgroup_mutex);
5971 
5972 	for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
5973 		if (cgroup->nr_descendants >= cgroup->max_descendants)
5974 			goto fail;
5975 
5976 		if (level >= cgroup->max_depth)
5977 			goto fail;
5978 
5979 		level++;
5980 	}
5981 
5982 	ret = true;
5983 fail:
5984 	return ret;
5985 }
5986 
cgroup_mkdir(struct kernfs_node * parent_kn,const char * name,umode_t mode)5987 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
5988 {
5989 	struct cgroup *parent, *cgrp;
5990 	int ret;
5991 
5992 	/* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
5993 	if (strchr(name, '\n'))
5994 		return -EINVAL;
5995 
5996 	parent = cgroup_kn_lock_live(parent_kn, false);
5997 	if (!parent)
5998 		return -ENODEV;
5999 
6000 	if (!cgroup_check_hierarchy_limits(parent)) {
6001 		ret = -EAGAIN;
6002 		goto out_unlock;
6003 	}
6004 
6005 	cgrp = cgroup_create(parent, name, mode);
6006 	if (IS_ERR(cgrp)) {
6007 		ret = PTR_ERR(cgrp);
6008 		goto out_unlock;
6009 	}
6010 
6011 	/*
6012 	 * This extra ref will be put in css_free_rwork_fn() and guarantees
6013 	 * that @cgrp->kn is always accessible.
6014 	 */
6015 	kernfs_get(cgrp->kn);
6016 
6017 	ret = css_populate_dir(&cgrp->self);
6018 	if (ret)
6019 		goto out_destroy;
6020 
6021 	ret = cgroup_apply_control_enable(cgrp);
6022 	if (ret)
6023 		goto out_destroy;
6024 
6025 	TRACE_CGROUP_PATH(mkdir, cgrp);
6026 
6027 	/* let's create and online css's */
6028 	kernfs_activate(cgrp->kn);
6029 
6030 	ret = 0;
6031 	goto out_unlock;
6032 
6033 out_destroy:
6034 	cgroup_destroy_locked(cgrp);
6035 out_unlock:
6036 	cgroup_kn_unlock(parent_kn);
6037 	return ret;
6038 }
6039 
6040 /*
6041  * This is called when the refcnt of a css is confirmed to be killed.
6042  * css_tryget_online() is now guaranteed to fail.  Tell the subsystem to
6043  * initiate destruction and put the css ref from kill_css().
6044  */
css_killed_work_fn(struct work_struct * work)6045 static void css_killed_work_fn(struct work_struct *work)
6046 {
6047 	struct cgroup_subsys_state *css =
6048 		container_of(work, struct cgroup_subsys_state, destroy_work);
6049 
6050 	cgroup_lock();
6051 
6052 	do {
6053 		offline_css(css);
6054 		css_put(css);
6055 		/* @css can't go away while we're holding cgroup_mutex */
6056 		css = css->parent;
6057 	} while (css && atomic_dec_and_test(&css->online_cnt));
6058 
6059 	cgroup_unlock();
6060 }
6061 
6062 /* css kill confirmation processing requires process context, bounce */
css_killed_ref_fn(struct percpu_ref * ref)6063 static void css_killed_ref_fn(struct percpu_ref *ref)
6064 {
6065 	struct cgroup_subsys_state *css =
6066 		container_of(ref, struct cgroup_subsys_state, refcnt);
6067 
6068 	if (atomic_dec_and_test(&css->online_cnt)) {
6069 		INIT_WORK(&css->destroy_work, css_killed_work_fn);
6070 		queue_work(cgroup_offline_wq, &css->destroy_work);
6071 	}
6072 }
6073 
6074 /**
6075  * kill_css - destroy a css
6076  * @css: css to destroy
6077  *
6078  * This function initiates destruction of @css by removing cgroup interface
6079  * files and putting its base reference.  ->css_offline() will be invoked
6080  * asynchronously once css_tryget_online() is guaranteed to fail and when
6081  * the reference count reaches zero, @css will be released.
6082  */
kill_css(struct cgroup_subsys_state * css)6083 static void kill_css(struct cgroup_subsys_state *css)
6084 {
6085 	lockdep_assert_held(&cgroup_mutex);
6086 
6087 	if (css->flags & CSS_DYING)
6088 		return;
6089 
6090 	/*
6091 	 * Call css_killed(), if defined, before setting the CSS_DYING flag
6092 	 */
6093 	if (css->ss->css_killed)
6094 		css->ss->css_killed(css);
6095 
6096 	css->flags |= CSS_DYING;
6097 
6098 	/*
6099 	 * This must happen before css is disassociated with its cgroup.
6100 	 * See seq_css() for details.
6101 	 */
6102 	css_clear_dir(css);
6103 
6104 	/*
6105 	 * Killing would put the base ref, but we need to keep it alive
6106 	 * until after ->css_offline().
6107 	 */
6108 	css_get(css);
6109 
6110 	/*
6111 	 * cgroup core guarantees that, by the time ->css_offline() is
6112 	 * invoked, no new css reference will be given out via
6113 	 * css_tryget_online().  We can't simply call percpu_ref_kill() and
6114 	 * proceed to offlining css's because percpu_ref_kill() doesn't
6115 	 * guarantee that the ref is seen as killed on all CPUs on return.
6116 	 *
6117 	 * Use percpu_ref_kill_and_confirm() to get notifications as each
6118 	 * css is confirmed to be seen as killed on all CPUs.
6119 	 */
6120 	percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
6121 }
6122 
6123 /**
6124  * cgroup_destroy_locked - the first stage of cgroup destruction
6125  * @cgrp: cgroup to be destroyed
6126  *
6127  * css's make use of percpu refcnts whose killing latency shouldn't be
6128  * exposed to userland and are RCU protected.  Also, cgroup core needs to
6129  * guarantee that css_tryget_online() won't succeed by the time
6130  * ->css_offline() is invoked.  To satisfy all the requirements,
6131  * destruction is implemented in the following two steps.
6132  *
6133  * s1. Verify @cgrp can be destroyed and mark it dying.  Remove all
6134  *     userland visible parts and start killing the percpu refcnts of
6135  *     css's.  Set up so that the next stage will be kicked off once all
6136  *     the percpu refcnts are confirmed to be killed.
6137  *
6138  * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
6139  *     rest of destruction.  Once all cgroup references are gone, the
6140  *     cgroup is RCU-freed.
6141  *
6142  * This function implements s1.  After this step, @cgrp is gone as far as
6143  * the userland is concerned and a new cgroup with the same name may be
6144  * created.  As cgroup doesn't care about the names internally, this
6145  * doesn't cause any problem.
6146  */
cgroup_destroy_locked(struct cgroup * cgrp)6147 static int cgroup_destroy_locked(struct cgroup *cgrp)
6148 	__releases(&cgroup_mutex) __acquires(&cgroup_mutex)
6149 {
6150 	struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
6151 	struct cgroup_subsys_state *css;
6152 	struct cgrp_cset_link *link;
6153 	int ssid, ret;
6154 
6155 	lockdep_assert_held(&cgroup_mutex);
6156 
6157 	/*
6158 	 * Only migration can raise populated from zero and we're already
6159 	 * holding cgroup_mutex.
6160 	 */
6161 	if (cgroup_is_populated(cgrp))
6162 		return -EBUSY;
6163 
6164 	/*
6165 	 * Make sure there's no live children.  We can't test emptiness of
6166 	 * ->self.children as dead children linger on it while being
6167 	 * drained; otherwise, "rmdir parent/child parent" may fail.
6168 	 */
6169 	if (css_has_online_children(&cgrp->self))
6170 		return -EBUSY;
6171 
6172 	/*
6173 	 * Mark @cgrp and the associated csets dead.  The former prevents
6174 	 * further task migration and child creation by disabling
6175 	 * cgroup_kn_lock_live().  The latter makes the csets ignored by
6176 	 * the migration path.
6177 	 */
6178 	cgrp->self.flags &= ~CSS_ONLINE;
6179 
6180 	spin_lock_irq(&css_set_lock);
6181 	list_for_each_entry(link, &cgrp->cset_links, cset_link)
6182 		link->cset->dead = true;
6183 	spin_unlock_irq(&css_set_lock);
6184 
6185 	/* initiate massacre of all css's */
6186 	for_each_css(css, ssid, cgrp)
6187 		kill_css(css);
6188 
6189 	/* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
6190 	css_clear_dir(&cgrp->self);
6191 	kernfs_remove(cgrp->kn);
6192 
6193 	if (cgroup_is_threaded(cgrp))
6194 		parent->nr_threaded_children--;
6195 
6196 	spin_lock_irq(&css_set_lock);
6197 	for (tcgrp = parent; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
6198 		tcgrp->nr_descendants--;
6199 		tcgrp->nr_dying_descendants++;
6200 		/*
6201 		 * If the dying cgroup is frozen, decrease frozen descendants
6202 		 * counters of ancestor cgroups.
6203 		 */
6204 		if (test_bit(CGRP_FROZEN, &cgrp->flags))
6205 			tcgrp->freezer.nr_frozen_descendants--;
6206 	}
6207 	spin_unlock_irq(&css_set_lock);
6208 
6209 	cgroup1_check_for_release(parent);
6210 
6211 	ret = blocking_notifier_call_chain(&cgroup_lifetime_notifier,
6212 					   CGROUP_LIFETIME_OFFLINE, cgrp);
6213 	WARN_ON_ONCE(notifier_to_errno(ret));
6214 
6215 	/* put the base reference */
6216 	percpu_ref_kill(&cgrp->self.refcnt);
6217 
6218 	return 0;
6219 };
6220 
cgroup_rmdir(struct kernfs_node * kn)6221 int cgroup_rmdir(struct kernfs_node *kn)
6222 {
6223 	struct cgroup *cgrp;
6224 	int ret = 0;
6225 
6226 	cgrp = cgroup_kn_lock_live(kn, false);
6227 	if (!cgrp)
6228 		return 0;
6229 
6230 	ret = cgroup_destroy_locked(cgrp);
6231 	if (!ret)
6232 		TRACE_CGROUP_PATH(rmdir, cgrp);
6233 
6234 	cgroup_kn_unlock(kn);
6235 	return ret;
6236 }
6237 
6238 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
6239 	.show_options		= cgroup_show_options,
6240 	.mkdir			= cgroup_mkdir,
6241 	.rmdir			= cgroup_rmdir,
6242 	.show_path		= cgroup_show_path,
6243 };
6244 
cgroup_init_subsys(struct cgroup_subsys * ss,bool early)6245 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
6246 {
6247 	struct cgroup_subsys_state *css;
6248 
6249 	pr_debug("Initializing cgroup subsys %s\n", ss->name);
6250 
6251 	cgroup_lock();
6252 
6253 	idr_init(&ss->css_idr);
6254 	INIT_LIST_HEAD(&ss->cfts);
6255 
6256 	/* Create the root cgroup state for this subsystem */
6257 	ss->root = &cgrp_dfl_root;
6258 	css = ss->css_alloc(NULL);
6259 	/* We don't handle early failures gracefully */
6260 	BUG_ON(IS_ERR(css));
6261 	init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
6262 
6263 	/*
6264 	 * Root csses are never destroyed and we can't initialize
6265 	 * percpu_ref during early init.  Disable refcnting.
6266 	 */
6267 	css->flags |= CSS_NO_REF;
6268 
6269 	if (early) {
6270 		/* allocation can't be done safely during early init */
6271 		css->id = 1;
6272 	} else {
6273 		css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
6274 		BUG_ON(css->id < 0);
6275 
6276 		BUG_ON(ss_rstat_init(ss));
6277 		BUG_ON(css_rstat_init(css));
6278 	}
6279 
6280 	/* Update the init_css_set to contain a subsys
6281 	 * pointer to this state - since the subsystem is
6282 	 * newly registered, all tasks and hence the
6283 	 * init_css_set is in the subsystem's root cgroup. */
6284 	init_css_set.subsys[ss->id] = css;
6285 
6286 	have_fork_callback |= (bool)ss->fork << ss->id;
6287 	have_exit_callback |= (bool)ss->exit << ss->id;
6288 	have_release_callback |= (bool)ss->release << ss->id;
6289 	have_canfork_callback |= (bool)ss->can_fork << ss->id;
6290 
6291 	/* At system boot, before all subsystems have been
6292 	 * registered, no tasks have been forked, so we don't
6293 	 * need to invoke fork callbacks here. */
6294 	BUG_ON(!list_empty(&init_task.tasks));
6295 
6296 	BUG_ON(online_css(css));
6297 
6298 	cgroup_unlock();
6299 }
6300 
6301 /**
6302  * cgroup_init_early - cgroup initialization at system boot
6303  *
6304  * Initialize cgroups at system boot, and initialize any
6305  * subsystems that request early init.
6306  */
cgroup_init_early(void)6307 int __init cgroup_init_early(void)
6308 {
6309 	static struct cgroup_fs_context __initdata ctx;
6310 	struct cgroup_subsys *ss;
6311 	int i;
6312 
6313 	ctx.root = &cgrp_dfl_root;
6314 	init_cgroup_root(&ctx);
6315 	cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
6316 
6317 	RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
6318 
6319 	for_each_subsys(ss, i) {
6320 		WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
6321 		     "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
6322 		     i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
6323 		     ss->id, ss->name);
6324 		WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
6325 		     "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
6326 		WARN(ss->early_init && ss->css_rstat_flush,
6327 		     "cgroup rstat cannot be used with early init subsystem\n");
6328 
6329 		ss->id = i;
6330 		ss->name = cgroup_subsys_name[i];
6331 		if (!ss->legacy_name)
6332 			ss->legacy_name = cgroup_subsys_name[i];
6333 
6334 		if (ss->early_init)
6335 			cgroup_init_subsys(ss, true);
6336 	}
6337 	return 0;
6338 }
6339 
6340 /**
6341  * cgroup_init - cgroup initialization
6342  *
6343  * Register cgroup filesystem and /proc file, and initialize
6344  * any subsystems that didn't request early init.
6345  */
cgroup_init(void)6346 int __init cgroup_init(void)
6347 {
6348 	struct cgroup_subsys *ss;
6349 	int ssid;
6350 
6351 	BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 32);
6352 	BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
6353 	BUG_ON(cgroup_init_cftypes(NULL, cgroup_psi_files));
6354 	BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
6355 
6356 	BUG_ON(ss_rstat_init(NULL));
6357 
6358 	get_user_ns(init_cgroup_ns.user_ns);
6359 	cgroup_rt_init();
6360 
6361 	cgroup_lock();
6362 
6363 	/*
6364 	 * Add init_css_set to the hash table so that dfl_root can link to
6365 	 * it during init.
6366 	 */
6367 	hash_add(css_set_table, &init_css_set.hlist,
6368 		 css_set_hash(init_css_set.subsys));
6369 
6370 	cgroup_bpf_lifetime_notifier_init();
6371 
6372 	BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
6373 
6374 	cgroup_unlock();
6375 
6376 	for_each_subsys(ss, ssid) {
6377 		if (ss->early_init) {
6378 			struct cgroup_subsys_state *css =
6379 				init_css_set.subsys[ss->id];
6380 
6381 			css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
6382 						   GFP_KERNEL);
6383 			BUG_ON(css->id < 0);
6384 		} else {
6385 			cgroup_init_subsys(ss, false);
6386 		}
6387 
6388 		list_add_tail(&init_css_set.e_cset_node[ssid],
6389 			      &cgrp_dfl_root.cgrp.e_csets[ssid]);
6390 
6391 		/*
6392 		 * Setting dfl_root subsys_mask needs to consider the
6393 		 * disabled flag and cftype registration needs kmalloc,
6394 		 * both of which aren't available during early_init.
6395 		 */
6396 		if (!cgroup_ssid_enabled(ssid))
6397 			continue;
6398 
6399 		if (cgroup1_ssid_disabled(ssid))
6400 			pr_info("Disabling %s control group subsystem in v1 mounts\n",
6401 				ss->legacy_name);
6402 
6403 		cgrp_dfl_root.subsys_mask |= 1 << ss->id;
6404 
6405 		/* implicit controllers must be threaded too */
6406 		WARN_ON(ss->implicit_on_dfl && !ss->threaded);
6407 
6408 		if (ss->implicit_on_dfl)
6409 			cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
6410 		else if (!ss->dfl_cftypes)
6411 			cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
6412 
6413 		if (ss->threaded)
6414 			cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
6415 
6416 		if (ss->dfl_cftypes == ss->legacy_cftypes) {
6417 			WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
6418 		} else {
6419 			WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
6420 			WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
6421 		}
6422 
6423 		if (ss->bind)
6424 			ss->bind(init_css_set.subsys[ssid]);
6425 
6426 		cgroup_lock();
6427 		css_populate_dir(init_css_set.subsys[ssid]);
6428 		cgroup_unlock();
6429 	}
6430 
6431 	/* init_css_set.subsys[] has been updated, re-hash */
6432 	hash_del(&init_css_set.hlist);
6433 	hash_add(css_set_table, &init_css_set.hlist,
6434 		 css_set_hash(init_css_set.subsys));
6435 
6436 	WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
6437 	WARN_ON(register_filesystem(&cgroup_fs_type));
6438 	WARN_ON(register_filesystem(&cgroup2_fs_type));
6439 	WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show));
6440 #ifdef CONFIG_CPUSETS_V1
6441 	WARN_ON(register_filesystem(&cpuset_fs_type));
6442 #endif
6443 
6444 	ns_tree_add(&init_cgroup_ns);
6445 	return 0;
6446 }
6447 
cgroup_wq_init(void)6448 static int __init cgroup_wq_init(void)
6449 {
6450 	/*
6451 	 * There isn't much point in executing destruction path in
6452 	 * parallel.  Good chunk is serialized with cgroup_mutex anyway.
6453 	 * Use 1 for @max_active.
6454 	 *
6455 	 * We would prefer to do this in cgroup_init() above, but that
6456 	 * is called before init_workqueues(): so leave this until after.
6457 	 */
6458 	cgroup_offline_wq = alloc_workqueue("cgroup_offline", WQ_PERCPU, 1);
6459 	BUG_ON(!cgroup_offline_wq);
6460 
6461 	cgroup_release_wq = alloc_workqueue("cgroup_release", WQ_PERCPU, 1);
6462 	BUG_ON(!cgroup_release_wq);
6463 
6464 	cgroup_free_wq = alloc_workqueue("cgroup_free", WQ_PERCPU, 1);
6465 	BUG_ON(!cgroup_free_wq);
6466 	return 0;
6467 }
6468 core_initcall(cgroup_wq_init);
6469 
cgroup_path_from_kernfs_id(u64 id,char * buf,size_t buflen)6470 void cgroup_path_from_kernfs_id(u64 id, char *buf, size_t buflen)
6471 {
6472 	struct kernfs_node *kn;
6473 
6474 	kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6475 	if (!kn)
6476 		return;
6477 	kernfs_path(kn, buf, buflen);
6478 	kernfs_put(kn);
6479 }
6480 
6481 /*
6482  * __cgroup_get_from_id : get the cgroup associated with cgroup id
6483  * @id: cgroup id
6484  * On success return the cgrp or ERR_PTR on failure
6485  * There are no cgroup NS restrictions.
6486  */
__cgroup_get_from_id(u64 id)6487 struct cgroup *__cgroup_get_from_id(u64 id)
6488 {
6489 	struct kernfs_node *kn;
6490 	struct cgroup *cgrp;
6491 
6492 	kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6493 	if (!kn)
6494 		return ERR_PTR(-ENOENT);
6495 
6496 	if (kernfs_type(kn) != KERNFS_DIR) {
6497 		kernfs_put(kn);
6498 		return ERR_PTR(-ENOENT);
6499 	}
6500 
6501 	rcu_read_lock();
6502 
6503 	cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6504 	if (cgrp && !cgroup_tryget(cgrp))
6505 		cgrp = NULL;
6506 
6507 	rcu_read_unlock();
6508 	kernfs_put(kn);
6509 
6510 	if (!cgrp)
6511 		return ERR_PTR(-ENOENT);
6512 	return cgrp;
6513 }
6514 
6515 /*
6516  * cgroup_get_from_id : get the cgroup associated with cgroup id
6517  * @id: cgroup id
6518  * On success return the cgrp or ERR_PTR on failure
6519  * Only cgroups within current task's cgroup NS are valid.
6520  */
cgroup_get_from_id(u64 id)6521 struct cgroup *cgroup_get_from_id(u64 id)
6522 {
6523 	struct cgroup *cgrp, *root_cgrp;
6524 
6525 	cgrp = __cgroup_get_from_id(id);
6526 	if (IS_ERR(cgrp))
6527 		return cgrp;
6528 
6529 	root_cgrp = current_cgns_cgroup_dfl();
6530 	if (!cgroup_is_descendant(cgrp, root_cgrp)) {
6531 		cgroup_put(cgrp);
6532 		return ERR_PTR(-ENOENT);
6533 	}
6534 
6535 	return cgrp;
6536 }
6537 EXPORT_SYMBOL_GPL(cgroup_get_from_id);
6538 
6539 /*
6540  * proc_cgroup_show()
6541  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
6542  *  - Used for /proc/<pid>/cgroup.
6543  */
proc_cgroup_show(struct seq_file * m,struct pid_namespace * ns,struct pid * pid,struct task_struct * tsk)6544 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
6545 		     struct pid *pid, struct task_struct *tsk)
6546 {
6547 	char *buf;
6548 	int retval;
6549 	struct cgroup_root *root;
6550 
6551 	retval = -ENOMEM;
6552 	buf = kmalloc(PATH_MAX, GFP_KERNEL);
6553 	if (!buf)
6554 		goto out;
6555 
6556 	rcu_read_lock();
6557 	spin_lock_irq(&css_set_lock);
6558 
6559 	for_each_root(root) {
6560 		struct cgroup_subsys *ss;
6561 		struct cgroup *cgrp;
6562 		int ssid, count = 0;
6563 
6564 		if (root == &cgrp_dfl_root && !READ_ONCE(cgrp_dfl_visible))
6565 			continue;
6566 
6567 		cgrp = task_cgroup_from_root(tsk, root);
6568 		/* The root has already been unmounted. */
6569 		if (!cgrp)
6570 			continue;
6571 
6572 		seq_printf(m, "%d:", root->hierarchy_id);
6573 		if (root != &cgrp_dfl_root)
6574 			for_each_subsys(ss, ssid)
6575 				if (root->subsys_mask & (1 << ssid))
6576 					seq_printf(m, "%s%s", count++ ? "," : "",
6577 						   ss->legacy_name);
6578 		if (strlen(root->name))
6579 			seq_printf(m, "%sname=%s", count ? "," : "",
6580 				   root->name);
6581 		seq_putc(m, ':');
6582 		/*
6583 		 * On traditional hierarchies, all zombie tasks show up as
6584 		 * belonging to the root cgroup.  On the default hierarchy,
6585 		 * while a zombie doesn't show up in "cgroup.procs" and
6586 		 * thus can't be migrated, its /proc/PID/cgroup keeps
6587 		 * reporting the cgroup it belonged to before exiting.  If
6588 		 * the cgroup is removed before the zombie is reaped,
6589 		 * " (deleted)" is appended to the cgroup path.
6590 		 */
6591 		if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
6592 			retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
6593 						current->nsproxy->cgroup_ns);
6594 			if (retval == -E2BIG)
6595 				retval = -ENAMETOOLONG;
6596 			if (retval < 0)
6597 				goto out_unlock;
6598 
6599 			seq_puts(m, buf);
6600 		} else {
6601 			seq_puts(m, "/");
6602 		}
6603 
6604 		if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
6605 			seq_puts(m, " (deleted)\n");
6606 		else
6607 			seq_putc(m, '\n');
6608 	}
6609 
6610 	retval = 0;
6611 out_unlock:
6612 	spin_unlock_irq(&css_set_lock);
6613 	rcu_read_unlock();
6614 	kfree(buf);
6615 out:
6616 	return retval;
6617 }
6618 
6619 /**
6620  * cgroup_fork - initialize cgroup related fields during copy_process()
6621  * @child: pointer to task_struct of forking parent process.
6622  *
6623  * A task is associated with the init_css_set until cgroup_post_fork()
6624  * attaches it to the target css_set.
6625  */
cgroup_fork(struct task_struct * child)6626 void cgroup_fork(struct task_struct *child)
6627 {
6628 	RCU_INIT_POINTER(child->cgroups, &init_css_set);
6629 	INIT_LIST_HEAD(&child->cg_list);
6630 }
6631 
6632 /**
6633  * cgroup_v1v2_get_from_file - get a cgroup pointer from a file pointer
6634  * @f: file corresponding to cgroup_dir
6635  *
6636  * Find the cgroup from a file pointer associated with a cgroup directory.
6637  * Returns a pointer to the cgroup on success. ERR_PTR is returned if the
6638  * cgroup cannot be found.
6639  */
cgroup_v1v2_get_from_file(struct file * f)6640 static struct cgroup *cgroup_v1v2_get_from_file(struct file *f)
6641 {
6642 	struct cgroup_subsys_state *css;
6643 
6644 	css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
6645 	if (IS_ERR(css))
6646 		return ERR_CAST(css);
6647 
6648 	return css->cgroup;
6649 }
6650 
6651 /**
6652  * cgroup_get_from_file - same as cgroup_v1v2_get_from_file, but only supports
6653  * cgroup2.
6654  * @f: file corresponding to cgroup2_dir
6655  */
cgroup_get_from_file(struct file * f)6656 static struct cgroup *cgroup_get_from_file(struct file *f)
6657 {
6658 	struct cgroup *cgrp = cgroup_v1v2_get_from_file(f);
6659 
6660 	if (IS_ERR(cgrp))
6661 		return ERR_CAST(cgrp);
6662 
6663 	if (!cgroup_on_dfl(cgrp)) {
6664 		cgroup_put(cgrp);
6665 		return ERR_PTR(-EBADF);
6666 	}
6667 
6668 	return cgrp;
6669 }
6670 
6671 /**
6672  * cgroup_css_set_fork - find or create a css_set for a child process
6673  * @kargs: the arguments passed to create the child process
6674  *
6675  * This functions finds or creates a new css_set which the child
6676  * process will be attached to in cgroup_post_fork(). By default,
6677  * the child process will be given the same css_set as its parent.
6678  *
6679  * If CLONE_INTO_CGROUP is specified this function will try to find an
6680  * existing css_set which includes the requested cgroup and if not create
6681  * a new css_set that the child will be attached to later. If this function
6682  * succeeds it will hold cgroup_threadgroup_rwsem on return. If
6683  * CLONE_INTO_CGROUP is requested this function will grab cgroup mutex
6684  * before grabbing cgroup_threadgroup_rwsem and will hold a reference
6685  * to the target cgroup.
6686  */
cgroup_css_set_fork(struct kernel_clone_args * kargs)6687 static int cgroup_css_set_fork(struct kernel_clone_args *kargs)
6688 	__acquires(&cgroup_mutex) __acquires(&cgroup_threadgroup_rwsem)
6689 {
6690 	int ret;
6691 	struct cgroup *dst_cgrp = NULL;
6692 	struct css_set *cset;
6693 	struct super_block *sb;
6694 
6695 	if (kargs->flags & CLONE_INTO_CGROUP)
6696 		cgroup_lock();
6697 
6698 	cgroup_threadgroup_change_begin(current);
6699 
6700 	spin_lock_irq(&css_set_lock);
6701 	cset = task_css_set(current);
6702 	get_css_set(cset);
6703 	if (kargs->cgrp)
6704 		kargs->kill_seq = kargs->cgrp->kill_seq;
6705 	else
6706 		kargs->kill_seq = cset->dfl_cgrp->kill_seq;
6707 	spin_unlock_irq(&css_set_lock);
6708 
6709 	if (!(kargs->flags & CLONE_INTO_CGROUP)) {
6710 		kargs->cset = cset;
6711 		return 0;
6712 	}
6713 
6714 	CLASS(fd_raw, f)(kargs->cgroup);
6715 	if (fd_empty(f)) {
6716 		ret = -EBADF;
6717 		goto err;
6718 	}
6719 	sb = fd_file(f)->f_path.dentry->d_sb;
6720 
6721 	dst_cgrp = cgroup_get_from_file(fd_file(f));
6722 	if (IS_ERR(dst_cgrp)) {
6723 		ret = PTR_ERR(dst_cgrp);
6724 		dst_cgrp = NULL;
6725 		goto err;
6726 	}
6727 
6728 	if (cgroup_is_dead(dst_cgrp)) {
6729 		ret = -ENODEV;
6730 		goto err;
6731 	}
6732 
6733 	/*
6734 	 * Verify that we the target cgroup is writable for us. This is
6735 	 * usually done by the vfs layer but since we're not going through
6736 	 * the vfs layer here we need to do it "manually".
6737 	 */
6738 	ret = cgroup_may_write(dst_cgrp, sb);
6739 	if (ret)
6740 		goto err;
6741 
6742 	/*
6743 	 * Spawning a task directly into a cgroup works by passing a file
6744 	 * descriptor to the target cgroup directory. This can even be an O_PATH
6745 	 * file descriptor. But it can never be a cgroup.procs file descriptor.
6746 	 * This was done on purpose so spawning into a cgroup could be
6747 	 * conceptualized as an atomic
6748 	 *
6749 	 *   fd = openat(dfd_cgroup, "cgroup.procs", ...);
6750 	 *   write(fd, <child-pid>, ...);
6751 	 *
6752 	 * sequence, i.e. it's a shorthand for the caller opening and writing
6753 	 * cgroup.procs of the cgroup indicated by @dfd_cgroup. This allows us
6754 	 * to always use the caller's credentials.
6755 	 */
6756 	ret = cgroup_attach_permissions(cset->dfl_cgrp, dst_cgrp, sb,
6757 					!(kargs->flags & CLONE_THREAD),
6758 					current->nsproxy->cgroup_ns);
6759 	if (ret)
6760 		goto err;
6761 
6762 	kargs->cset = find_css_set(cset, dst_cgrp);
6763 	if (!kargs->cset) {
6764 		ret = -ENOMEM;
6765 		goto err;
6766 	}
6767 
6768 	put_css_set(cset);
6769 	kargs->cgrp = dst_cgrp;
6770 	return ret;
6771 
6772 err:
6773 	cgroup_threadgroup_change_end(current);
6774 	cgroup_unlock();
6775 	if (dst_cgrp)
6776 		cgroup_put(dst_cgrp);
6777 	put_css_set(cset);
6778 	if (kargs->cset)
6779 		put_css_set(kargs->cset);
6780 	return ret;
6781 }
6782 
6783 /**
6784  * cgroup_css_set_put_fork - drop references we took during fork
6785  * @kargs: the arguments passed to create the child process
6786  *
6787  * Drop references to the prepared css_set and target cgroup if
6788  * CLONE_INTO_CGROUP was requested.
6789  */
cgroup_css_set_put_fork(struct kernel_clone_args * kargs)6790 static void cgroup_css_set_put_fork(struct kernel_clone_args *kargs)
6791 	__releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6792 {
6793 	struct cgroup *cgrp = kargs->cgrp;
6794 	struct css_set *cset = kargs->cset;
6795 
6796 	cgroup_threadgroup_change_end(current);
6797 
6798 	if (cset) {
6799 		put_css_set(cset);
6800 		kargs->cset = NULL;
6801 	}
6802 
6803 	if (kargs->flags & CLONE_INTO_CGROUP) {
6804 		cgroup_unlock();
6805 		if (cgrp) {
6806 			cgroup_put(cgrp);
6807 			kargs->cgrp = NULL;
6808 		}
6809 	}
6810 }
6811 
6812 /**
6813  * cgroup_can_fork - called on a new task before the process is exposed
6814  * @child: the child process
6815  * @kargs: the arguments passed to create the child process
6816  *
6817  * This prepares a new css_set for the child process which the child will
6818  * be attached to in cgroup_post_fork().
6819  * This calls the subsystem can_fork() callbacks. If the cgroup_can_fork()
6820  * callback returns an error, the fork aborts with that error code. This
6821  * allows for a cgroup subsystem to conditionally allow or deny new forks.
6822  */
cgroup_can_fork(struct task_struct * child,struct kernel_clone_args * kargs)6823 int cgroup_can_fork(struct task_struct *child, struct kernel_clone_args *kargs)
6824 {
6825 	struct cgroup_subsys *ss;
6826 	int i, j, ret;
6827 
6828 	ret = cgroup_css_set_fork(kargs);
6829 	if (ret)
6830 		return ret;
6831 
6832 	do_each_subsys_mask(ss, i, have_canfork_callback) {
6833 		ret = ss->can_fork(child, kargs->cset);
6834 		if (ret)
6835 			goto out_revert;
6836 	} while_each_subsys_mask();
6837 
6838 	return 0;
6839 
6840 out_revert:
6841 	for_each_subsys(ss, j) {
6842 		if (j >= i)
6843 			break;
6844 		if (ss->cancel_fork)
6845 			ss->cancel_fork(child, kargs->cset);
6846 	}
6847 
6848 	cgroup_css_set_put_fork(kargs);
6849 
6850 	return ret;
6851 }
6852 
6853 /**
6854  * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
6855  * @child: the child process
6856  * @kargs: the arguments passed to create the child process
6857  *
6858  * This calls the cancel_fork() callbacks if a fork failed *after*
6859  * cgroup_can_fork() succeeded and cleans up references we took to
6860  * prepare a new css_set for the child process in cgroup_can_fork().
6861  */
cgroup_cancel_fork(struct task_struct * child,struct kernel_clone_args * kargs)6862 void cgroup_cancel_fork(struct task_struct *child,
6863 			struct kernel_clone_args *kargs)
6864 {
6865 	struct cgroup_subsys *ss;
6866 	int i;
6867 
6868 	for_each_subsys(ss, i)
6869 		if (ss->cancel_fork)
6870 			ss->cancel_fork(child, kargs->cset);
6871 
6872 	cgroup_css_set_put_fork(kargs);
6873 }
6874 
6875 /**
6876  * cgroup_post_fork - finalize cgroup setup for the child process
6877  * @child: the child process
6878  * @kargs: the arguments passed to create the child process
6879  *
6880  * Attach the child process to its css_set calling the subsystem fork()
6881  * callbacks.
6882  */
cgroup_post_fork(struct task_struct * child,struct kernel_clone_args * kargs)6883 void cgroup_post_fork(struct task_struct *child,
6884 		      struct kernel_clone_args *kargs)
6885 	__releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6886 {
6887 	unsigned int cgrp_kill_seq = 0;
6888 	unsigned long cgrp_flags = 0;
6889 	bool kill = false;
6890 	struct cgroup_subsys *ss;
6891 	struct css_set *cset;
6892 	int i;
6893 
6894 	cset = kargs->cset;
6895 	kargs->cset = NULL;
6896 
6897 	spin_lock_irq(&css_set_lock);
6898 
6899 	/* init tasks are special, only link regular threads */
6900 	if (likely(child->pid)) {
6901 		if (kargs->cgrp) {
6902 			cgrp_flags = kargs->cgrp->flags;
6903 			cgrp_kill_seq = kargs->cgrp->kill_seq;
6904 		} else {
6905 			cgrp_flags = cset->dfl_cgrp->flags;
6906 			cgrp_kill_seq = cset->dfl_cgrp->kill_seq;
6907 		}
6908 
6909 		WARN_ON_ONCE(!list_empty(&child->cg_list));
6910 		cset->nr_tasks++;
6911 		css_set_move_task(child, NULL, cset, false);
6912 	} else {
6913 		put_css_set(cset);
6914 		cset = NULL;
6915 	}
6916 
6917 	if (!(child->flags & PF_KTHREAD)) {
6918 		if (unlikely(test_bit(CGRP_FREEZE, &cgrp_flags))) {
6919 			/*
6920 			 * If the cgroup has to be frozen, the new task has
6921 			 * too. Let's set the JOBCTL_TRAP_FREEZE jobctl bit to
6922 			 * get the task into the frozen state.
6923 			 */
6924 			spin_lock(&child->sighand->siglock);
6925 			WARN_ON_ONCE(child->frozen);
6926 			child->jobctl |= JOBCTL_TRAP_FREEZE;
6927 			spin_unlock(&child->sighand->siglock);
6928 
6929 			/*
6930 			 * Calling cgroup_update_frozen() isn't required here,
6931 			 * because it will be called anyway a bit later from
6932 			 * do_freezer_trap(). So we avoid cgroup's transient
6933 			 * switch from the frozen state and back.
6934 			 */
6935 		}
6936 
6937 		/*
6938 		 * If the cgroup is to be killed notice it now and take the
6939 		 * child down right after we finished preparing it for
6940 		 * userspace.
6941 		 */
6942 		kill = kargs->kill_seq != cgrp_kill_seq;
6943 	}
6944 
6945 	spin_unlock_irq(&css_set_lock);
6946 
6947 	/*
6948 	 * Call ss->fork().  This must happen after @child is linked on
6949 	 * css_set; otherwise, @child might change state between ->fork()
6950 	 * and addition to css_set.
6951 	 */
6952 	do_each_subsys_mask(ss, i, have_fork_callback) {
6953 		ss->fork(child);
6954 	} while_each_subsys_mask();
6955 
6956 	/* Make the new cset the root_cset of the new cgroup namespace. */
6957 	if (kargs->flags & CLONE_NEWCGROUP) {
6958 		struct css_set *rcset = child->nsproxy->cgroup_ns->root_cset;
6959 
6960 		get_css_set(cset);
6961 		child->nsproxy->cgroup_ns->root_cset = cset;
6962 		put_css_set(rcset);
6963 	}
6964 
6965 	/* Cgroup has to be killed so take down child immediately. */
6966 	if (unlikely(kill))
6967 		do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, child, PIDTYPE_TGID);
6968 
6969 	cgroup_css_set_put_fork(kargs);
6970 }
6971 
6972 /**
6973  * cgroup_task_exit - detach cgroup from exiting task
6974  * @tsk: pointer to task_struct of exiting process
6975  *
6976  * Description: Detach cgroup from @tsk.
6977  *
6978  */
cgroup_task_exit(struct task_struct * tsk)6979 void cgroup_task_exit(struct task_struct *tsk)
6980 {
6981 	struct cgroup_subsys *ss;
6982 	int i;
6983 
6984 	/* see cgroup_post_fork() for details */
6985 	do_each_subsys_mask(ss, i, have_exit_callback) {
6986 		ss->exit(tsk);
6987 	} while_each_subsys_mask();
6988 }
6989 
do_cgroup_task_dead(struct task_struct * tsk)6990 static void do_cgroup_task_dead(struct task_struct *tsk)
6991 {
6992 	struct css_set *cset;
6993 	unsigned long flags;
6994 
6995 	spin_lock_irqsave(&css_set_lock, flags);
6996 
6997 	WARN_ON_ONCE(list_empty(&tsk->cg_list));
6998 	cset = task_css_set(tsk);
6999 	css_set_move_task(tsk, cset, NULL, false);
7000 	cset->nr_tasks--;
7001 	/* matches the signal->live check in css_task_iter_advance() */
7002 	if (thread_group_leader(tsk) && atomic_read(&tsk->signal->live))
7003 		list_add_tail(&tsk->cg_list, &cset->dying_tasks);
7004 
7005 	if (dl_task(tsk))
7006 		dec_dl_tasks_cs(tsk);
7007 
7008 	WARN_ON_ONCE(cgroup_task_frozen(tsk));
7009 	if (unlikely(!(tsk->flags & PF_KTHREAD) &&
7010 		     test_bit(CGRP_FREEZE, &task_dfl_cgroup(tsk)->flags)))
7011 		cgroup_update_frozen(task_dfl_cgroup(tsk));
7012 
7013 	spin_unlock_irqrestore(&css_set_lock, flags);
7014 }
7015 
7016 #ifdef CONFIG_PREEMPT_RT
7017 /*
7018  * cgroup_task_dead() is called from finish_task_switch() which doesn't allow
7019  * scheduling even in RT. As the task_dead path requires grabbing css_set_lock,
7020  * this lead to sleeping in the invalid context warning bug. css_set_lock is too
7021  * big to become a raw_spinlock. The task_dead path doesn't need to run
7022  * synchronously but can't be delayed indefinitely either as the dead task pins
7023  * the cgroup and task_struct can be pinned indefinitely. Bounce through lazy
7024  * irq_work to allow batching while ensuring timely completion.
7025  */
7026 static DEFINE_PER_CPU(struct llist_head, cgrp_dead_tasks);
7027 static DEFINE_PER_CPU(struct irq_work, cgrp_dead_tasks_iwork);
7028 
cgrp_dead_tasks_iwork_fn(struct irq_work * iwork)7029 static void cgrp_dead_tasks_iwork_fn(struct irq_work *iwork)
7030 {
7031 	struct llist_node *lnode;
7032 	struct task_struct *task, *next;
7033 
7034 	lnode = llist_del_all(this_cpu_ptr(&cgrp_dead_tasks));
7035 	llist_for_each_entry_safe(task, next, lnode, cg_dead_lnode) {
7036 		do_cgroup_task_dead(task);
7037 		put_task_struct(task);
7038 	}
7039 }
7040 
cgroup_rt_init(void)7041 static void __init cgroup_rt_init(void)
7042 {
7043 	int cpu;
7044 
7045 	for_each_possible_cpu(cpu) {
7046 		init_llist_head(per_cpu_ptr(&cgrp_dead_tasks, cpu));
7047 		per_cpu(cgrp_dead_tasks_iwork, cpu) =
7048 			IRQ_WORK_INIT_LAZY(cgrp_dead_tasks_iwork_fn);
7049 	}
7050 }
7051 
cgroup_task_dead(struct task_struct * task)7052 void cgroup_task_dead(struct task_struct *task)
7053 {
7054 	get_task_struct(task);
7055 	llist_add(&task->cg_dead_lnode, this_cpu_ptr(&cgrp_dead_tasks));
7056 	irq_work_queue(this_cpu_ptr(&cgrp_dead_tasks_iwork));
7057 }
7058 #else	/* CONFIG_PREEMPT_RT */
cgroup_rt_init(void)7059 static void __init cgroup_rt_init(void) {}
7060 
cgroup_task_dead(struct task_struct * task)7061 void cgroup_task_dead(struct task_struct *task)
7062 {
7063 	do_cgroup_task_dead(task);
7064 }
7065 #endif	/* CONFIG_PREEMPT_RT */
7066 
cgroup_task_release(struct task_struct * task)7067 void cgroup_task_release(struct task_struct *task)
7068 {
7069 	struct cgroup_subsys *ss;
7070 	int ssid;
7071 
7072 	do_each_subsys_mask(ss, ssid, have_release_callback) {
7073 		ss->release(task);
7074 	} while_each_subsys_mask();
7075 }
7076 
cgroup_task_free(struct task_struct * task)7077 void cgroup_task_free(struct task_struct *task)
7078 {
7079 	struct css_set *cset = task_css_set(task);
7080 
7081 	if (!list_empty(&task->cg_list)) {
7082 		spin_lock_irq(&css_set_lock);
7083 		css_set_skip_task_iters(task_css_set(task), task);
7084 		list_del_init(&task->cg_list);
7085 		spin_unlock_irq(&css_set_lock);
7086 	}
7087 
7088 	put_css_set(cset);
7089 }
7090 
cgroup_disable(char * str)7091 static int __init cgroup_disable(char *str)
7092 {
7093 	struct cgroup_subsys *ss;
7094 	char *token;
7095 	int i;
7096 
7097 	while ((token = strsep(&str, ",")) != NULL) {
7098 		if (!*token)
7099 			continue;
7100 
7101 		for_each_subsys(ss, i) {
7102 			if (strcmp(token, ss->name) &&
7103 			    strcmp(token, ss->legacy_name))
7104 				continue;
7105 
7106 			static_branch_disable(cgroup_subsys_enabled_key[i]);
7107 			pr_info("Disabling %s control group subsystem\n",
7108 				ss->name);
7109 		}
7110 
7111 		for (i = 0; i < OPT_FEATURE_COUNT; i++) {
7112 			if (strcmp(token, cgroup_opt_feature_names[i]))
7113 				continue;
7114 			cgroup_feature_disable_mask |= 1 << i;
7115 			pr_info("Disabling %s control group feature\n",
7116 				cgroup_opt_feature_names[i]);
7117 			break;
7118 		}
7119 	}
7120 	return 1;
7121 }
7122 __setup("cgroup_disable=", cgroup_disable);
7123 
enable_debug_cgroup(void)7124 void __init __weak enable_debug_cgroup(void) { }
7125 
enable_cgroup_debug(char * str)7126 static int __init enable_cgroup_debug(char *str)
7127 {
7128 	cgroup_debug = true;
7129 	enable_debug_cgroup();
7130 	return 1;
7131 }
7132 __setup("cgroup_debug", enable_cgroup_debug);
7133 
cgroup_favordynmods_setup(char * str)7134 static int __init cgroup_favordynmods_setup(char *str)
7135 {
7136 	return (kstrtobool(str, &have_favordynmods) == 0);
7137 }
7138 __setup("cgroup_favordynmods=", cgroup_favordynmods_setup);
7139 
7140 /**
7141  * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
7142  * @dentry: directory dentry of interest
7143  * @ss: subsystem of interest
7144  *
7145  * If @dentry is a directory for a cgroup which has @ss enabled on it, try
7146  * to get the corresponding css and return it.  If such css doesn't exist
7147  * or can't be pinned, an ERR_PTR value is returned.
7148  */
css_tryget_online_from_dir(struct dentry * dentry,struct cgroup_subsys * ss)7149 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
7150 						       struct cgroup_subsys *ss)
7151 {
7152 	struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
7153 	struct file_system_type *s_type = dentry->d_sb->s_type;
7154 	struct cgroup_subsys_state *css = NULL;
7155 	struct cgroup *cgrp;
7156 
7157 	/* is @dentry a cgroup dir? */
7158 	if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
7159 	    !kn || kernfs_type(kn) != KERNFS_DIR)
7160 		return ERR_PTR(-EBADF);
7161 
7162 	rcu_read_lock();
7163 
7164 	/*
7165 	 * This path doesn't originate from kernfs and @kn could already
7166 	 * have been or be removed at any point.  @kn->priv is RCU
7167 	 * protected for this access.  See css_release_work_fn() for details.
7168 	 */
7169 	cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
7170 	if (cgrp)
7171 		css = cgroup_css(cgrp, ss);
7172 
7173 	if (!css || !css_tryget_online(css))
7174 		css = ERR_PTR(-ENOENT);
7175 
7176 	rcu_read_unlock();
7177 	return css;
7178 }
7179 
7180 /**
7181  * css_from_id - lookup css by id
7182  * @id: the cgroup id
7183  * @ss: cgroup subsys to be looked into
7184  *
7185  * Returns the css if there's valid one with @id, otherwise returns NULL.
7186  * Should be called under rcu_read_lock().
7187  */
css_from_id(int id,struct cgroup_subsys * ss)7188 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
7189 {
7190 	WARN_ON_ONCE(!rcu_read_lock_held());
7191 	return idr_find(&ss->css_idr, id);
7192 }
7193 
7194 /**
7195  * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
7196  * @path: path on the default hierarchy
7197  *
7198  * Find the cgroup at @path on the default hierarchy, increment its
7199  * reference count and return it.  Returns pointer to the found cgroup on
7200  * success, ERR_PTR(-ENOENT) if @path doesn't exist or if the cgroup has already
7201  * been released and ERR_PTR(-ENOTDIR) if @path points to a non-directory.
7202  */
cgroup_get_from_path(const char * path)7203 struct cgroup *cgroup_get_from_path(const char *path)
7204 {
7205 	struct kernfs_node *kn;
7206 	struct cgroup *cgrp = ERR_PTR(-ENOENT);
7207 	struct cgroup *root_cgrp;
7208 
7209 	root_cgrp = current_cgns_cgroup_dfl();
7210 	kn = kernfs_walk_and_get(root_cgrp->kn, path);
7211 	if (!kn)
7212 		goto out;
7213 
7214 	if (kernfs_type(kn) != KERNFS_DIR) {
7215 		cgrp = ERR_PTR(-ENOTDIR);
7216 		goto out_kernfs;
7217 	}
7218 
7219 	rcu_read_lock();
7220 
7221 	cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
7222 	if (!cgrp || !cgroup_tryget(cgrp))
7223 		cgrp = ERR_PTR(-ENOENT);
7224 
7225 	rcu_read_unlock();
7226 
7227 out_kernfs:
7228 	kernfs_put(kn);
7229 out:
7230 	return cgrp;
7231 }
7232 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
7233 
7234 /**
7235  * cgroup_v1v2_get_from_fd - get a cgroup pointer from a fd
7236  * @fd: fd obtained by open(cgroup_dir)
7237  *
7238  * Find the cgroup from a fd which should be obtained
7239  * by opening a cgroup directory.  Returns a pointer to the
7240  * cgroup on success. ERR_PTR is returned if the cgroup
7241  * cannot be found.
7242  */
cgroup_v1v2_get_from_fd(int fd)7243 struct cgroup *cgroup_v1v2_get_from_fd(int fd)
7244 {
7245 	CLASS(fd_raw, f)(fd);
7246 	if (fd_empty(f))
7247 		return ERR_PTR(-EBADF);
7248 
7249 	return cgroup_v1v2_get_from_file(fd_file(f));
7250 }
7251 
7252 /**
7253  * cgroup_get_from_fd - same as cgroup_v1v2_get_from_fd, but only supports
7254  * cgroup2.
7255  * @fd: fd obtained by open(cgroup2_dir)
7256  */
cgroup_get_from_fd(int fd)7257 struct cgroup *cgroup_get_from_fd(int fd)
7258 {
7259 	struct cgroup *cgrp = cgroup_v1v2_get_from_fd(fd);
7260 
7261 	if (IS_ERR(cgrp))
7262 		return ERR_CAST(cgrp);
7263 
7264 	if (!cgroup_on_dfl(cgrp)) {
7265 		cgroup_put(cgrp);
7266 		return ERR_PTR(-EBADF);
7267 	}
7268 	return cgrp;
7269 }
7270 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
7271 
power_of_ten(int power)7272 static u64 power_of_ten(int power)
7273 {
7274 	u64 v = 1;
7275 	while (power--)
7276 		v *= 10;
7277 	return v;
7278 }
7279 
7280 /**
7281  * cgroup_parse_float - parse a floating number
7282  * @input: input string
7283  * @dec_shift: number of decimal digits to shift
7284  * @v: output
7285  *
7286  * Parse a decimal floating point number in @input and store the result in
7287  * @v with decimal point right shifted @dec_shift times.  For example, if
7288  * @input is "12.3456" and @dec_shift is 3, *@v will be set to 12345.
7289  * Returns 0 on success, -errno otherwise.
7290  *
7291  * There's nothing cgroup specific about this function except that it's
7292  * currently the only user.
7293  */
cgroup_parse_float(const char * input,unsigned dec_shift,s64 * v)7294 int cgroup_parse_float(const char *input, unsigned dec_shift, s64 *v)
7295 {
7296 	s64 whole, frac = 0;
7297 	int fstart = 0, fend = 0, flen;
7298 
7299 	if (!sscanf(input, "%lld.%n%lld%n", &whole, &fstart, &frac, &fend))
7300 		return -EINVAL;
7301 	if (frac < 0)
7302 		return -EINVAL;
7303 
7304 	flen = fend > fstart ? fend - fstart : 0;
7305 	if (flen < dec_shift)
7306 		frac *= power_of_ten(dec_shift - flen);
7307 	else
7308 		frac = DIV_ROUND_CLOSEST_ULL(frac, power_of_ten(flen - dec_shift));
7309 
7310 	*v = whole * power_of_ten(dec_shift) + frac;
7311 	return 0;
7312 }
7313 
7314 /*
7315  * sock->sk_cgrp_data handling.  For more info, see sock_cgroup_data
7316  * definition in cgroup-defs.h.
7317  */
7318 #ifdef CONFIG_SOCK_CGROUP_DATA
7319 
cgroup_sk_alloc(struct sock_cgroup_data * skcd)7320 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
7321 {
7322 	struct cgroup *cgroup;
7323 
7324 	rcu_read_lock();
7325 	/* Don't associate the sock with unrelated interrupted task's cgroup. */
7326 	if (in_interrupt()) {
7327 		cgroup = &cgrp_dfl_root.cgrp;
7328 		cgroup_get(cgroup);
7329 		goto out;
7330 	}
7331 
7332 	while (true) {
7333 		struct css_set *cset;
7334 
7335 		cset = task_css_set(current);
7336 		if (likely(cgroup_tryget(cset->dfl_cgrp))) {
7337 			cgroup = cset->dfl_cgrp;
7338 			break;
7339 		}
7340 		cpu_relax();
7341 	}
7342 out:
7343 	skcd->cgroup = cgroup;
7344 	cgroup_bpf_get(cgroup);
7345 	rcu_read_unlock();
7346 }
7347 
cgroup_sk_clone(struct sock_cgroup_data * skcd)7348 void cgroup_sk_clone(struct sock_cgroup_data *skcd)
7349 {
7350 	struct cgroup *cgrp = sock_cgroup_ptr(skcd);
7351 
7352 	/*
7353 	 * We might be cloning a socket which is left in an empty
7354 	 * cgroup and the cgroup might have already been rmdir'd.
7355 	 * Don't use cgroup_get_live().
7356 	 */
7357 	cgroup_get(cgrp);
7358 	cgroup_bpf_get(cgrp);
7359 }
7360 
cgroup_sk_free(struct sock_cgroup_data * skcd)7361 void cgroup_sk_free(struct sock_cgroup_data *skcd)
7362 {
7363 	struct cgroup *cgrp = sock_cgroup_ptr(skcd);
7364 
7365 	cgroup_bpf_put(cgrp);
7366 	cgroup_put(cgrp);
7367 }
7368 
7369 #endif	/* CONFIG_SOCK_CGROUP_DATA */
7370 
7371 #ifdef CONFIG_SYSFS
show_delegatable_files(struct cftype * files,char * buf,ssize_t size,const char * prefix)7372 static ssize_t show_delegatable_files(struct cftype *files, char *buf,
7373 				      ssize_t size, const char *prefix)
7374 {
7375 	struct cftype *cft;
7376 	ssize_t ret = 0;
7377 
7378 	for (cft = files; cft && cft->name[0] != '\0'; cft++) {
7379 		if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
7380 			continue;
7381 
7382 		if (prefix)
7383 			ret += snprintf(buf + ret, size - ret, "%s.", prefix);
7384 
7385 		ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
7386 
7387 		if (WARN_ON(ret >= size))
7388 			break;
7389 	}
7390 
7391 	return ret;
7392 }
7393 
delegate_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)7394 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
7395 			      char *buf)
7396 {
7397 	struct cgroup_subsys *ss;
7398 	int ssid;
7399 	ssize_t ret = 0;
7400 
7401 	ret = show_delegatable_files(cgroup_base_files, buf + ret,
7402 				     PAGE_SIZE - ret, NULL);
7403 	if (cgroup_psi_enabled())
7404 		ret += show_delegatable_files(cgroup_psi_files, buf + ret,
7405 					      PAGE_SIZE - ret, NULL);
7406 
7407 	for_each_subsys(ss, ssid)
7408 		ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
7409 					      PAGE_SIZE - ret,
7410 					      cgroup_subsys_name[ssid]);
7411 
7412 	return ret;
7413 }
7414 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
7415 
features_show(struct kobject * kobj,struct kobj_attribute * attr,char * buf)7416 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
7417 			     char *buf)
7418 {
7419 	return snprintf(buf, PAGE_SIZE,
7420 			"nsdelegate\n"
7421 			"favordynmods\n"
7422 			"memory_localevents\n"
7423 			"memory_recursiveprot\n"
7424 			"memory_hugetlb_accounting\n"
7425 			"pids_localevents\n");
7426 }
7427 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
7428 
7429 static struct attribute *cgroup_sysfs_attrs[] = {
7430 	&cgroup_delegate_attr.attr,
7431 	&cgroup_features_attr.attr,
7432 	NULL,
7433 };
7434 
7435 static const struct attribute_group cgroup_sysfs_attr_group = {
7436 	.attrs = cgroup_sysfs_attrs,
7437 	.name = "cgroup",
7438 };
7439 
cgroup_sysfs_init(void)7440 static int __init cgroup_sysfs_init(void)
7441 {
7442 	return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
7443 }
7444 subsys_initcall(cgroup_sysfs_init);
7445 
7446 #endif /* CONFIG_SYSFS */
7447