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