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