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