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