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