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