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