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