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