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