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