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