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