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