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