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