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