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