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