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