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