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