memcg: update threshold and softlimit at commit
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / kernel / cgroup.c
blobea94984a389532fdc7585b52c3c781dee08e84e8
1 /*
2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
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 * ---------------------------------------------------
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.
29 #include <linux/cgroup.h>
30 #include <linux/module.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/fs.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
36 #include <linux/mm.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/backing-dev.h>
44 #include <linux/seq_file.h>
45 #include <linux/slab.h>
46 #include <linux/magic.h>
47 #include <linux/spinlock.h>
48 #include <linux/string.h>
49 #include <linux/sort.h>
50 #include <linux/kmod.h>
51 #include <linux/module.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hash.h>
55 #include <linux/namei.h>
56 #include <linux/smp_lock.h>
57 #include <linux/pid_namespace.h>
58 #include <linux/idr.h>
59 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
60 #include <linux/eventfd.h>
61 #include <linux/poll.h>
63 #include <asm/atomic.h>
65 static DEFINE_MUTEX(cgroup_mutex);
68 * Generate an array of cgroup subsystem pointers. At boot time, this is
69 * populated up to CGROUP_BUILTIN_SUBSYS_COUNT, and modular subsystems are
70 * registered after that. The mutable section of this array is protected by
71 * cgroup_mutex.
73 #define SUBSYS(_x) &_x ## _subsys,
74 static struct cgroup_subsys *subsys[CGROUP_SUBSYS_COUNT] = {
75 #include <linux/cgroup_subsys.h>
78 #define MAX_CGROUP_ROOT_NAMELEN 64
81 * A cgroupfs_root represents the root of a cgroup hierarchy,
82 * and may be associated with a superblock to form an active
83 * hierarchy
85 struct cgroupfs_root {
86 struct super_block *sb;
89 * The bitmask of subsystems intended to be attached to this
90 * hierarchy
92 unsigned long subsys_bits;
94 /* Unique id for this hierarchy. */
95 int hierarchy_id;
97 /* The bitmask of subsystems currently attached to this hierarchy */
98 unsigned long actual_subsys_bits;
100 /* A list running through the attached subsystems */
101 struct list_head subsys_list;
103 /* The root cgroup for this hierarchy */
104 struct cgroup top_cgroup;
106 /* Tracks how many cgroups are currently defined in hierarchy.*/
107 int number_of_cgroups;
109 /* A list running through the active hierarchies */
110 struct list_head root_list;
112 /* Hierarchy-specific flags */
113 unsigned long flags;
115 /* The path to use for release notifications. */
116 char release_agent_path[PATH_MAX];
118 /* The name for this hierarchy - may be empty */
119 char name[MAX_CGROUP_ROOT_NAMELEN];
123 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
124 * subsystems that are otherwise unattached - it never has more than a
125 * single cgroup, and all tasks are part of that cgroup.
127 static struct cgroupfs_root rootnode;
130 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
131 * cgroup_subsys->use_id != 0.
133 #define CSS_ID_MAX (65535)
134 struct css_id {
136 * The css to which this ID points. This pointer is set to valid value
137 * after cgroup is populated. If cgroup is removed, this will be NULL.
138 * This pointer is expected to be RCU-safe because destroy()
139 * is called after synchronize_rcu(). But for safe use, css_is_removed()
140 * css_tryget() should be used for avoiding race.
142 struct cgroup_subsys_state *css;
144 * ID of this css.
146 unsigned short id;
148 * Depth in hierarchy which this ID belongs to.
150 unsigned short depth;
152 * ID is freed by RCU. (and lookup routine is RCU safe.)
154 struct rcu_head rcu_head;
156 * Hierarchy of CSS ID belongs to.
158 unsigned short stack[0]; /* Array of Length (depth+1) */
162 * cgroup_event represents events which userspace want to recieve.
164 struct cgroup_event {
166 * Cgroup which the event belongs to.
168 struct cgroup *cgrp;
170 * Control file which the event associated.
172 struct cftype *cft;
174 * eventfd to signal userspace about the event.
176 struct eventfd_ctx *eventfd;
178 * Each of these stored in a list by the cgroup.
180 struct list_head list;
182 * All fields below needed to unregister event when
183 * userspace closes eventfd.
185 poll_table pt;
186 wait_queue_head_t *wqh;
187 wait_queue_t wait;
188 struct work_struct remove;
191 /* The list of hierarchy roots */
193 static LIST_HEAD(roots);
194 static int root_count;
196 static DEFINE_IDA(hierarchy_ida);
197 static int next_hierarchy_id;
198 static DEFINE_SPINLOCK(hierarchy_id_lock);
200 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
201 #define dummytop (&rootnode.top_cgroup)
203 /* This flag indicates whether tasks in the fork and exit paths should
204 * check for fork/exit handlers to call. This avoids us having to do
205 * extra work in the fork/exit path if none of the subsystems need to
206 * be called.
208 static int need_forkexit_callback __read_mostly;
210 #ifdef CONFIG_PROVE_LOCKING
211 int cgroup_lock_is_held(void)
213 return lockdep_is_held(&cgroup_mutex);
215 #else /* #ifdef CONFIG_PROVE_LOCKING */
216 int cgroup_lock_is_held(void)
218 return mutex_is_locked(&cgroup_mutex);
220 #endif /* #else #ifdef CONFIG_PROVE_LOCKING */
222 EXPORT_SYMBOL_GPL(cgroup_lock_is_held);
224 /* convenient tests for these bits */
225 inline int cgroup_is_removed(const struct cgroup *cgrp)
227 return test_bit(CGRP_REMOVED, &cgrp->flags);
230 /* bits in struct cgroupfs_root flags field */
231 enum {
232 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
235 static int cgroup_is_releasable(const struct cgroup *cgrp)
237 const int bits =
238 (1 << CGRP_RELEASABLE) |
239 (1 << CGRP_NOTIFY_ON_RELEASE);
240 return (cgrp->flags & bits) == bits;
243 static int notify_on_release(const struct cgroup *cgrp)
245 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
249 * for_each_subsys() allows you to iterate on each subsystem attached to
250 * an active hierarchy
252 #define for_each_subsys(_root, _ss) \
253 list_for_each_entry(_ss, &_root->subsys_list, sibling)
255 /* for_each_active_root() allows you to iterate across the active hierarchies */
256 #define for_each_active_root(_root) \
257 list_for_each_entry(_root, &roots, root_list)
259 /* the list of cgroups eligible for automatic release. Protected by
260 * release_list_lock */
261 static LIST_HEAD(release_list);
262 static DEFINE_SPINLOCK(release_list_lock);
263 static void cgroup_release_agent(struct work_struct *work);
264 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
265 static void check_for_release(struct cgroup *cgrp);
267 /* Link structure for associating css_set objects with cgroups */
268 struct cg_cgroup_link {
270 * List running through cg_cgroup_links associated with a
271 * cgroup, anchored on cgroup->css_sets
273 struct list_head cgrp_link_list;
274 struct cgroup *cgrp;
276 * List running through cg_cgroup_links pointing at a
277 * single css_set object, anchored on css_set->cg_links
279 struct list_head cg_link_list;
280 struct css_set *cg;
283 /* The default css_set - used by init and its children prior to any
284 * hierarchies being mounted. It contains a pointer to the root state
285 * for each subsystem. Also used to anchor the list of css_sets. Not
286 * reference-counted, to improve performance when child cgroups
287 * haven't been created.
290 static struct css_set init_css_set;
291 static struct cg_cgroup_link init_css_set_link;
293 static int cgroup_init_idr(struct cgroup_subsys *ss,
294 struct cgroup_subsys_state *css);
296 /* css_set_lock protects the list of css_set objects, and the
297 * chain of tasks off each css_set. Nests outside task->alloc_lock
298 * due to cgroup_iter_start() */
299 static DEFINE_RWLOCK(css_set_lock);
300 static int css_set_count;
303 * hash table for cgroup groups. This improves the performance to find
304 * an existing css_set. This hash doesn't (currently) take into
305 * account cgroups in empty hierarchies.
307 #define CSS_SET_HASH_BITS 7
308 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
309 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
311 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
313 int i;
314 int index;
315 unsigned long tmp = 0UL;
317 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
318 tmp += (unsigned long)css[i];
319 tmp = (tmp >> 16) ^ tmp;
321 index = hash_long(tmp, CSS_SET_HASH_BITS);
323 return &css_set_table[index];
326 static void free_css_set_rcu(struct rcu_head *obj)
328 struct css_set *cg = container_of(obj, struct css_set, rcu_head);
329 kfree(cg);
332 /* We don't maintain the lists running through each css_set to its
333 * task until after the first call to cgroup_iter_start(). This
334 * reduces the fork()/exit() overhead for people who have cgroups
335 * compiled into their kernel but not actually in use */
336 static int use_task_css_set_links __read_mostly;
338 static void __put_css_set(struct css_set *cg, int taskexit)
340 struct cg_cgroup_link *link;
341 struct cg_cgroup_link *saved_link;
343 * Ensure that the refcount doesn't hit zero while any readers
344 * can see it. Similar to atomic_dec_and_lock(), but for an
345 * rwlock
347 if (atomic_add_unless(&cg->refcount, -1, 1))
348 return;
349 write_lock(&css_set_lock);
350 if (!atomic_dec_and_test(&cg->refcount)) {
351 write_unlock(&css_set_lock);
352 return;
355 /* This css_set is dead. unlink it and release cgroup refcounts */
356 hlist_del(&cg->hlist);
357 css_set_count--;
359 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
360 cg_link_list) {
361 struct cgroup *cgrp = link->cgrp;
362 list_del(&link->cg_link_list);
363 list_del(&link->cgrp_link_list);
364 if (atomic_dec_and_test(&cgrp->count) &&
365 notify_on_release(cgrp)) {
366 if (taskexit)
367 set_bit(CGRP_RELEASABLE, &cgrp->flags);
368 check_for_release(cgrp);
371 kfree(link);
374 write_unlock(&css_set_lock);
375 call_rcu(&cg->rcu_head, free_css_set_rcu);
379 * refcounted get/put for css_set objects
381 static inline void get_css_set(struct css_set *cg)
383 atomic_inc(&cg->refcount);
386 static inline void put_css_set(struct css_set *cg)
388 __put_css_set(cg, 0);
391 static inline void put_css_set_taskexit(struct css_set *cg)
393 __put_css_set(cg, 1);
397 * compare_css_sets - helper function for find_existing_css_set().
398 * @cg: candidate css_set being tested
399 * @old_cg: existing css_set for a task
400 * @new_cgrp: cgroup that's being entered by the task
401 * @template: desired set of css pointers in css_set (pre-calculated)
403 * Returns true if "cg" matches "old_cg" except for the hierarchy
404 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
406 static bool compare_css_sets(struct css_set *cg,
407 struct css_set *old_cg,
408 struct cgroup *new_cgrp,
409 struct cgroup_subsys_state *template[])
411 struct list_head *l1, *l2;
413 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
414 /* Not all subsystems matched */
415 return false;
419 * Compare cgroup pointers in order to distinguish between
420 * different cgroups in heirarchies with no subsystems. We
421 * could get by with just this check alone (and skip the
422 * memcmp above) but on most setups the memcmp check will
423 * avoid the need for this more expensive check on almost all
424 * candidates.
427 l1 = &cg->cg_links;
428 l2 = &old_cg->cg_links;
429 while (1) {
430 struct cg_cgroup_link *cgl1, *cgl2;
431 struct cgroup *cg1, *cg2;
433 l1 = l1->next;
434 l2 = l2->next;
435 /* See if we reached the end - both lists are equal length. */
436 if (l1 == &cg->cg_links) {
437 BUG_ON(l2 != &old_cg->cg_links);
438 break;
439 } else {
440 BUG_ON(l2 == &old_cg->cg_links);
442 /* Locate the cgroups associated with these links. */
443 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
444 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
445 cg1 = cgl1->cgrp;
446 cg2 = cgl2->cgrp;
447 /* Hierarchies should be linked in the same order. */
448 BUG_ON(cg1->root != cg2->root);
451 * If this hierarchy is the hierarchy of the cgroup
452 * that's changing, then we need to check that this
453 * css_set points to the new cgroup; if it's any other
454 * hierarchy, then this css_set should point to the
455 * same cgroup as the old css_set.
457 if (cg1->root == new_cgrp->root) {
458 if (cg1 != new_cgrp)
459 return false;
460 } else {
461 if (cg1 != cg2)
462 return false;
465 return true;
469 * find_existing_css_set() is a helper for
470 * find_css_set(), and checks to see whether an existing
471 * css_set is suitable.
473 * oldcg: the cgroup group that we're using before the cgroup
474 * transition
476 * cgrp: the cgroup that we're moving into
478 * template: location in which to build the desired set of subsystem
479 * state objects for the new cgroup group
481 static struct css_set *find_existing_css_set(
482 struct css_set *oldcg,
483 struct cgroup *cgrp,
484 struct cgroup_subsys_state *template[])
486 int i;
487 struct cgroupfs_root *root = cgrp->root;
488 struct hlist_head *hhead;
489 struct hlist_node *node;
490 struct css_set *cg;
493 * Build the set of subsystem state objects that we want to see in the
494 * new css_set. while subsystems can change globally, the entries here
495 * won't change, so no need for locking.
497 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
498 if (root->subsys_bits & (1UL << i)) {
499 /* Subsystem is in this hierarchy. So we want
500 * the subsystem state from the new
501 * cgroup */
502 template[i] = cgrp->subsys[i];
503 } else {
504 /* Subsystem is not in this hierarchy, so we
505 * don't want to change the subsystem state */
506 template[i] = oldcg->subsys[i];
510 hhead = css_set_hash(template);
511 hlist_for_each_entry(cg, node, hhead, hlist) {
512 if (!compare_css_sets(cg, oldcg, cgrp, template))
513 continue;
515 /* This css_set matches what we need */
516 return cg;
519 /* No existing cgroup group matched */
520 return NULL;
523 static void free_cg_links(struct list_head *tmp)
525 struct cg_cgroup_link *link;
526 struct cg_cgroup_link *saved_link;
528 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
529 list_del(&link->cgrp_link_list);
530 kfree(link);
535 * allocate_cg_links() allocates "count" cg_cgroup_link structures
536 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
537 * success or a negative error
539 static int allocate_cg_links(int count, struct list_head *tmp)
541 struct cg_cgroup_link *link;
542 int i;
543 INIT_LIST_HEAD(tmp);
544 for (i = 0; i < count; i++) {
545 link = kmalloc(sizeof(*link), GFP_KERNEL);
546 if (!link) {
547 free_cg_links(tmp);
548 return -ENOMEM;
550 list_add(&link->cgrp_link_list, tmp);
552 return 0;
556 * link_css_set - a helper function to link a css_set to a cgroup
557 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
558 * @cg: the css_set to be linked
559 * @cgrp: the destination cgroup
561 static void link_css_set(struct list_head *tmp_cg_links,
562 struct css_set *cg, struct cgroup *cgrp)
564 struct cg_cgroup_link *link;
566 BUG_ON(list_empty(tmp_cg_links));
567 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
568 cgrp_link_list);
569 link->cg = cg;
570 link->cgrp = cgrp;
571 atomic_inc(&cgrp->count);
572 list_move(&link->cgrp_link_list, &cgrp->css_sets);
574 * Always add links to the tail of the list so that the list
575 * is sorted by order of hierarchy creation
577 list_add_tail(&link->cg_link_list, &cg->cg_links);
581 * find_css_set() takes an existing cgroup group and a
582 * cgroup object, and returns a css_set object that's
583 * equivalent to the old group, but with the given cgroup
584 * substituted into the appropriate hierarchy. Must be called with
585 * cgroup_mutex held
587 static struct css_set *find_css_set(
588 struct css_set *oldcg, struct cgroup *cgrp)
590 struct css_set *res;
591 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
593 struct list_head tmp_cg_links;
595 struct hlist_head *hhead;
596 struct cg_cgroup_link *link;
598 /* First see if we already have a cgroup group that matches
599 * the desired set */
600 read_lock(&css_set_lock);
601 res = find_existing_css_set(oldcg, cgrp, template);
602 if (res)
603 get_css_set(res);
604 read_unlock(&css_set_lock);
606 if (res)
607 return res;
609 res = kmalloc(sizeof(*res), GFP_KERNEL);
610 if (!res)
611 return NULL;
613 /* Allocate all the cg_cgroup_link objects that we'll need */
614 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
615 kfree(res);
616 return NULL;
619 atomic_set(&res->refcount, 1);
620 INIT_LIST_HEAD(&res->cg_links);
621 INIT_LIST_HEAD(&res->tasks);
622 INIT_HLIST_NODE(&res->hlist);
624 /* Copy the set of subsystem state objects generated in
625 * find_existing_css_set() */
626 memcpy(res->subsys, template, sizeof(res->subsys));
628 write_lock(&css_set_lock);
629 /* Add reference counts and links from the new css_set. */
630 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
631 struct cgroup *c = link->cgrp;
632 if (c->root == cgrp->root)
633 c = cgrp;
634 link_css_set(&tmp_cg_links, res, c);
637 BUG_ON(!list_empty(&tmp_cg_links));
639 css_set_count++;
641 /* Add this cgroup group to the hash table */
642 hhead = css_set_hash(res->subsys);
643 hlist_add_head(&res->hlist, hhead);
645 write_unlock(&css_set_lock);
647 return res;
651 * Return the cgroup for "task" from the given hierarchy. Must be
652 * called with cgroup_mutex held.
654 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
655 struct cgroupfs_root *root)
657 struct css_set *css;
658 struct cgroup *res = NULL;
660 BUG_ON(!mutex_is_locked(&cgroup_mutex));
661 read_lock(&css_set_lock);
663 * No need to lock the task - since we hold cgroup_mutex the
664 * task can't change groups, so the only thing that can happen
665 * is that it exits and its css is set back to init_css_set.
667 css = task->cgroups;
668 if (css == &init_css_set) {
669 res = &root->top_cgroup;
670 } else {
671 struct cg_cgroup_link *link;
672 list_for_each_entry(link, &css->cg_links, cg_link_list) {
673 struct cgroup *c = link->cgrp;
674 if (c->root == root) {
675 res = c;
676 break;
680 read_unlock(&css_set_lock);
681 BUG_ON(!res);
682 return res;
686 * There is one global cgroup mutex. We also require taking
687 * task_lock() when dereferencing a task's cgroup subsys pointers.
688 * See "The task_lock() exception", at the end of this comment.
690 * A task must hold cgroup_mutex to modify cgroups.
692 * Any task can increment and decrement the count field without lock.
693 * So in general, code holding cgroup_mutex can't rely on the count
694 * field not changing. However, if the count goes to zero, then only
695 * cgroup_attach_task() can increment it again. Because a count of zero
696 * means that no tasks are currently attached, therefore there is no
697 * way a task attached to that cgroup can fork (the other way to
698 * increment the count). So code holding cgroup_mutex can safely
699 * assume that if the count is zero, it will stay zero. Similarly, if
700 * a task holds cgroup_mutex on a cgroup with zero count, it
701 * knows that the cgroup won't be removed, as cgroup_rmdir()
702 * needs that mutex.
704 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
705 * (usually) take cgroup_mutex. These are the two most performance
706 * critical pieces of code here. The exception occurs on cgroup_exit(),
707 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
708 * is taken, and if the cgroup count is zero, a usermode call made
709 * to the release agent with the name of the cgroup (path relative to
710 * the root of cgroup file system) as the argument.
712 * A cgroup can only be deleted if both its 'count' of using tasks
713 * is zero, and its list of 'children' cgroups is empty. Since all
714 * tasks in the system use _some_ cgroup, and since there is always at
715 * least one task in the system (init, pid == 1), therefore, top_cgroup
716 * always has either children cgroups and/or using tasks. So we don't
717 * need a special hack to ensure that top_cgroup cannot be deleted.
719 * The task_lock() exception
721 * The need for this exception arises from the action of
722 * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
723 * another. It does so using cgroup_mutex, however there are
724 * several performance critical places that need to reference
725 * task->cgroup without the expense of grabbing a system global
726 * mutex. Therefore except as noted below, when dereferencing or, as
727 * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
728 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
729 * the task_struct routinely used for such matters.
731 * P.S. One more locking exception. RCU is used to guard the
732 * update of a tasks cgroup pointer by cgroup_attach_task()
736 * cgroup_lock - lock out any changes to cgroup structures
739 void cgroup_lock(void)
741 mutex_lock(&cgroup_mutex);
743 EXPORT_SYMBOL_GPL(cgroup_lock);
746 * cgroup_unlock - release lock on cgroup changes
748 * Undo the lock taken in a previous cgroup_lock() call.
750 void cgroup_unlock(void)
752 mutex_unlock(&cgroup_mutex);
754 EXPORT_SYMBOL_GPL(cgroup_unlock);
757 * A couple of forward declarations required, due to cyclic reference loop:
758 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
759 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
760 * -> cgroup_mkdir.
763 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
764 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
765 static int cgroup_populate_dir(struct cgroup *cgrp);
766 static const struct inode_operations cgroup_dir_inode_operations;
767 static const struct file_operations proc_cgroupstats_operations;
769 static struct backing_dev_info cgroup_backing_dev_info = {
770 .name = "cgroup",
771 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
774 static int alloc_css_id(struct cgroup_subsys *ss,
775 struct cgroup *parent, struct cgroup *child);
777 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
779 struct inode *inode = new_inode(sb);
781 if (inode) {
782 inode->i_mode = mode;
783 inode->i_uid = current_fsuid();
784 inode->i_gid = current_fsgid();
785 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
786 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
788 return inode;
792 * Call subsys's pre_destroy handler.
793 * This is called before css refcnt check.
795 static int cgroup_call_pre_destroy(struct cgroup *cgrp)
797 struct cgroup_subsys *ss;
798 struct cgroup_event *event, *tmp;
799 int ret = 0;
801 for_each_subsys(cgrp->root, ss)
802 if (ss->pre_destroy) {
803 ret = ss->pre_destroy(ss, cgrp);
804 if (ret)
805 goto out;
809 * Unregister events and notify userspace.
811 spin_lock(&cgrp->event_list_lock);
812 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
813 list_del(&event->list);
814 eventfd_signal(event->eventfd, 1);
815 schedule_work(&event->remove);
817 spin_unlock(&cgrp->event_list_lock);
819 out:
820 return ret;
823 static void free_cgroup_rcu(struct rcu_head *obj)
825 struct cgroup *cgrp = container_of(obj, struct cgroup, rcu_head);
827 kfree(cgrp);
830 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
832 /* is dentry a directory ? if so, kfree() associated cgroup */
833 if (S_ISDIR(inode->i_mode)) {
834 struct cgroup *cgrp = dentry->d_fsdata;
835 struct cgroup_subsys *ss;
836 BUG_ON(!(cgroup_is_removed(cgrp)));
837 /* It's possible for external users to be holding css
838 * reference counts on a cgroup; css_put() needs to
839 * be able to access the cgroup after decrementing
840 * the reference count in order to know if it needs to
841 * queue the cgroup to be handled by the release
842 * agent */
843 synchronize_rcu();
845 mutex_lock(&cgroup_mutex);
847 * Release the subsystem state objects.
849 for_each_subsys(cgrp->root, ss)
850 ss->destroy(ss, cgrp);
852 cgrp->root->number_of_cgroups--;
853 mutex_unlock(&cgroup_mutex);
856 * Drop the active superblock reference that we took when we
857 * created the cgroup
859 deactivate_super(cgrp->root->sb);
862 * if we're getting rid of the cgroup, refcount should ensure
863 * that there are no pidlists left.
865 BUG_ON(!list_empty(&cgrp->pidlists));
867 call_rcu(&cgrp->rcu_head, free_cgroup_rcu);
869 iput(inode);
872 static void remove_dir(struct dentry *d)
874 struct dentry *parent = dget(d->d_parent);
876 d_delete(d);
877 simple_rmdir(parent->d_inode, d);
878 dput(parent);
881 static void cgroup_clear_directory(struct dentry *dentry)
883 struct list_head *node;
885 BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
886 spin_lock(&dcache_lock);
887 node = dentry->d_subdirs.next;
888 while (node != &dentry->d_subdirs) {
889 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
890 list_del_init(node);
891 if (d->d_inode) {
892 /* This should never be called on a cgroup
893 * directory with child cgroups */
894 BUG_ON(d->d_inode->i_mode & S_IFDIR);
895 d = dget_locked(d);
896 spin_unlock(&dcache_lock);
897 d_delete(d);
898 simple_unlink(dentry->d_inode, d);
899 dput(d);
900 spin_lock(&dcache_lock);
902 node = dentry->d_subdirs.next;
904 spin_unlock(&dcache_lock);
908 * NOTE : the dentry must have been dget()'ed
910 static void cgroup_d_remove_dir(struct dentry *dentry)
912 cgroup_clear_directory(dentry);
914 spin_lock(&dcache_lock);
915 list_del_init(&dentry->d_u.d_child);
916 spin_unlock(&dcache_lock);
917 remove_dir(dentry);
921 * A queue for waiters to do rmdir() cgroup. A tasks will sleep when
922 * cgroup->count == 0 && list_empty(&cgroup->children) && subsys has some
923 * reference to css->refcnt. In general, this refcnt is expected to goes down
924 * to zero, soon.
926 * CGRP_WAIT_ON_RMDIR flag is set under cgroup's inode->i_mutex;
928 DECLARE_WAIT_QUEUE_HEAD(cgroup_rmdir_waitq);
930 static void cgroup_wakeup_rmdir_waiter(struct cgroup *cgrp)
932 if (unlikely(test_and_clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags)))
933 wake_up_all(&cgroup_rmdir_waitq);
936 void cgroup_exclude_rmdir(struct cgroup_subsys_state *css)
938 css_get(css);
941 void cgroup_release_and_wakeup_rmdir(struct cgroup_subsys_state *css)
943 cgroup_wakeup_rmdir_waiter(css->cgroup);
944 css_put(css);
948 * Call with cgroup_mutex held. Drops reference counts on modules, including
949 * any duplicate ones that parse_cgroupfs_options took. If this function
950 * returns an error, no reference counts are touched.
952 static int rebind_subsystems(struct cgroupfs_root *root,
953 unsigned long final_bits)
955 unsigned long added_bits, removed_bits;
956 struct cgroup *cgrp = &root->top_cgroup;
957 int i;
959 BUG_ON(!mutex_is_locked(&cgroup_mutex));
961 removed_bits = root->actual_subsys_bits & ~final_bits;
962 added_bits = final_bits & ~root->actual_subsys_bits;
963 /* Check that any added subsystems are currently free */
964 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
965 unsigned long bit = 1UL << i;
966 struct cgroup_subsys *ss = subsys[i];
967 if (!(bit & added_bits))
968 continue;
970 * Nobody should tell us to do a subsys that doesn't exist:
971 * parse_cgroupfs_options should catch that case and refcounts
972 * ensure that subsystems won't disappear once selected.
974 BUG_ON(ss == NULL);
975 if (ss->root != &rootnode) {
976 /* Subsystem isn't free */
977 return -EBUSY;
981 /* Currently we don't handle adding/removing subsystems when
982 * any child cgroups exist. This is theoretically supportable
983 * but involves complex error handling, so it's being left until
984 * later */
985 if (root->number_of_cgroups > 1)
986 return -EBUSY;
988 /* Process each subsystem */
989 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
990 struct cgroup_subsys *ss = subsys[i];
991 unsigned long bit = 1UL << i;
992 if (bit & added_bits) {
993 /* We're binding this subsystem to this hierarchy */
994 BUG_ON(ss == NULL);
995 BUG_ON(cgrp->subsys[i]);
996 BUG_ON(!dummytop->subsys[i]);
997 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
998 mutex_lock(&ss->hierarchy_mutex);
999 cgrp->subsys[i] = dummytop->subsys[i];
1000 cgrp->subsys[i]->cgroup = cgrp;
1001 list_move(&ss->sibling, &root->subsys_list);
1002 ss->root = root;
1003 if (ss->bind)
1004 ss->bind(ss, cgrp);
1005 mutex_unlock(&ss->hierarchy_mutex);
1006 /* refcount was already taken, and we're keeping it */
1007 } else if (bit & removed_bits) {
1008 /* We're removing this subsystem */
1009 BUG_ON(ss == NULL);
1010 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1011 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1012 mutex_lock(&ss->hierarchy_mutex);
1013 if (ss->bind)
1014 ss->bind(ss, dummytop);
1015 dummytop->subsys[i]->cgroup = dummytop;
1016 cgrp->subsys[i] = NULL;
1017 subsys[i]->root = &rootnode;
1018 list_move(&ss->sibling, &rootnode.subsys_list);
1019 mutex_unlock(&ss->hierarchy_mutex);
1020 /* subsystem is now free - drop reference on module */
1021 module_put(ss->module);
1022 } else if (bit & final_bits) {
1023 /* Subsystem state should already exist */
1024 BUG_ON(ss == NULL);
1025 BUG_ON(!cgrp->subsys[i]);
1027 * a refcount was taken, but we already had one, so
1028 * drop the extra reference.
1030 module_put(ss->module);
1031 #ifdef CONFIG_MODULE_UNLOAD
1032 BUG_ON(ss->module && !module_refcount(ss->module));
1033 #endif
1034 } else {
1035 /* Subsystem state shouldn't exist */
1036 BUG_ON(cgrp->subsys[i]);
1039 root->subsys_bits = root->actual_subsys_bits = final_bits;
1040 synchronize_rcu();
1042 return 0;
1045 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
1047 struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
1048 struct cgroup_subsys *ss;
1050 mutex_lock(&cgroup_mutex);
1051 for_each_subsys(root, ss)
1052 seq_printf(seq, ",%s", ss->name);
1053 if (test_bit(ROOT_NOPREFIX, &root->flags))
1054 seq_puts(seq, ",noprefix");
1055 if (strlen(root->release_agent_path))
1056 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1057 if (strlen(root->name))
1058 seq_printf(seq, ",name=%s", root->name);
1059 mutex_unlock(&cgroup_mutex);
1060 return 0;
1063 struct cgroup_sb_opts {
1064 unsigned long subsys_bits;
1065 unsigned long flags;
1066 char *release_agent;
1067 char *name;
1068 /* User explicitly requested empty subsystem */
1069 bool none;
1071 struct cgroupfs_root *new_root;
1076 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1077 * with cgroup_mutex held to protect the subsys[] array. This function takes
1078 * refcounts on subsystems to be used, unless it returns error, in which case
1079 * no refcounts are taken.
1081 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1083 char *token, *o = data ?: "all";
1084 unsigned long mask = (unsigned long)-1;
1085 int i;
1086 bool module_pin_failed = false;
1088 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1090 #ifdef CONFIG_CPUSETS
1091 mask = ~(1UL << cpuset_subsys_id);
1092 #endif
1094 memset(opts, 0, sizeof(*opts));
1096 while ((token = strsep(&o, ",")) != NULL) {
1097 if (!*token)
1098 return -EINVAL;
1099 if (!strcmp(token, "all")) {
1100 /* Add all non-disabled subsystems */
1101 opts->subsys_bits = 0;
1102 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1103 struct cgroup_subsys *ss = subsys[i];
1104 if (ss == NULL)
1105 continue;
1106 if (!ss->disabled)
1107 opts->subsys_bits |= 1ul << i;
1109 } else if (!strcmp(token, "none")) {
1110 /* Explicitly have no subsystems */
1111 opts->none = true;
1112 } else if (!strcmp(token, "noprefix")) {
1113 set_bit(ROOT_NOPREFIX, &opts->flags);
1114 } else if (!strncmp(token, "release_agent=", 14)) {
1115 /* Specifying two release agents is forbidden */
1116 if (opts->release_agent)
1117 return -EINVAL;
1118 opts->release_agent =
1119 kstrndup(token + 14, PATH_MAX, GFP_KERNEL);
1120 if (!opts->release_agent)
1121 return -ENOMEM;
1122 } else if (!strncmp(token, "name=", 5)) {
1123 const char *name = token + 5;
1124 /* Can't specify an empty name */
1125 if (!strlen(name))
1126 return -EINVAL;
1127 /* Must match [\w.-]+ */
1128 for (i = 0; i < strlen(name); i++) {
1129 char c = name[i];
1130 if (isalnum(c))
1131 continue;
1132 if ((c == '.') || (c == '-') || (c == '_'))
1133 continue;
1134 return -EINVAL;
1136 /* Specifying two names is forbidden */
1137 if (opts->name)
1138 return -EINVAL;
1139 opts->name = kstrndup(name,
1140 MAX_CGROUP_ROOT_NAMELEN,
1141 GFP_KERNEL);
1142 if (!opts->name)
1143 return -ENOMEM;
1144 } else {
1145 struct cgroup_subsys *ss;
1146 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1147 ss = subsys[i];
1148 if (ss == NULL)
1149 continue;
1150 if (!strcmp(token, ss->name)) {
1151 if (!ss->disabled)
1152 set_bit(i, &opts->subsys_bits);
1153 break;
1156 if (i == CGROUP_SUBSYS_COUNT)
1157 return -ENOENT;
1161 /* Consistency checks */
1164 * Option noprefix was introduced just for backward compatibility
1165 * with the old cpuset, so we allow noprefix only if mounting just
1166 * the cpuset subsystem.
1168 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1169 (opts->subsys_bits & mask))
1170 return -EINVAL;
1173 /* Can't specify "none" and some subsystems */
1174 if (opts->subsys_bits && opts->none)
1175 return -EINVAL;
1178 * We either have to specify by name or by subsystems. (So all
1179 * empty hierarchies must have a name).
1181 if (!opts->subsys_bits && !opts->name)
1182 return -EINVAL;
1185 * Grab references on all the modules we'll need, so the subsystems
1186 * don't dance around before rebind_subsystems attaches them. This may
1187 * take duplicate reference counts on a subsystem that's already used,
1188 * but rebind_subsystems handles this case.
1190 for (i = CGROUP_BUILTIN_SUBSYS_COUNT; i < CGROUP_SUBSYS_COUNT; i++) {
1191 unsigned long bit = 1UL << i;
1193 if (!(bit & opts->subsys_bits))
1194 continue;
1195 if (!try_module_get(subsys[i]->module)) {
1196 module_pin_failed = true;
1197 break;
1200 if (module_pin_failed) {
1202 * oops, one of the modules was going away. this means that we
1203 * raced with a module_delete call, and to the user this is
1204 * essentially a "subsystem doesn't exist" case.
1206 for (i--; i >= CGROUP_BUILTIN_SUBSYS_COUNT; i--) {
1207 /* drop refcounts only on the ones we took */
1208 unsigned long bit = 1UL << i;
1210 if (!(bit & opts->subsys_bits))
1211 continue;
1212 module_put(subsys[i]->module);
1214 return -ENOENT;
1217 return 0;
1220 static void drop_parsed_module_refcounts(unsigned long subsys_bits)
1222 int i;
1223 for (i = CGROUP_BUILTIN_SUBSYS_COUNT; i < CGROUP_SUBSYS_COUNT; i++) {
1224 unsigned long bit = 1UL << i;
1226 if (!(bit & subsys_bits))
1227 continue;
1228 module_put(subsys[i]->module);
1232 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1234 int ret = 0;
1235 struct cgroupfs_root *root = sb->s_fs_info;
1236 struct cgroup *cgrp = &root->top_cgroup;
1237 struct cgroup_sb_opts opts;
1239 lock_kernel();
1240 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1241 mutex_lock(&cgroup_mutex);
1243 /* See what subsystems are wanted */
1244 ret = parse_cgroupfs_options(data, &opts);
1245 if (ret)
1246 goto out_unlock;
1248 /* Don't allow flags or name to change at remount */
1249 if (opts.flags != root->flags ||
1250 (opts.name && strcmp(opts.name, root->name))) {
1251 ret = -EINVAL;
1252 drop_parsed_module_refcounts(opts.subsys_bits);
1253 goto out_unlock;
1256 ret = rebind_subsystems(root, opts.subsys_bits);
1257 if (ret) {
1258 drop_parsed_module_refcounts(opts.subsys_bits);
1259 goto out_unlock;
1262 /* (re)populate subsystem files */
1263 cgroup_populate_dir(cgrp);
1265 if (opts.release_agent)
1266 strcpy(root->release_agent_path, opts.release_agent);
1267 out_unlock:
1268 kfree(opts.release_agent);
1269 kfree(opts.name);
1270 mutex_unlock(&cgroup_mutex);
1271 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1272 unlock_kernel();
1273 return ret;
1276 static const struct super_operations cgroup_ops = {
1277 .statfs = simple_statfs,
1278 .drop_inode = generic_delete_inode,
1279 .show_options = cgroup_show_options,
1280 .remount_fs = cgroup_remount,
1283 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1285 INIT_LIST_HEAD(&cgrp->sibling);
1286 INIT_LIST_HEAD(&cgrp->children);
1287 INIT_LIST_HEAD(&cgrp->css_sets);
1288 INIT_LIST_HEAD(&cgrp->release_list);
1289 INIT_LIST_HEAD(&cgrp->pidlists);
1290 mutex_init(&cgrp->pidlist_mutex);
1291 INIT_LIST_HEAD(&cgrp->event_list);
1292 spin_lock_init(&cgrp->event_list_lock);
1295 static void init_cgroup_root(struct cgroupfs_root *root)
1297 struct cgroup *cgrp = &root->top_cgroup;
1298 INIT_LIST_HEAD(&root->subsys_list);
1299 INIT_LIST_HEAD(&root->root_list);
1300 root->number_of_cgroups = 1;
1301 cgrp->root = root;
1302 cgrp->top_cgroup = cgrp;
1303 init_cgroup_housekeeping(cgrp);
1306 static bool init_root_id(struct cgroupfs_root *root)
1308 int ret = 0;
1310 do {
1311 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1312 return false;
1313 spin_lock(&hierarchy_id_lock);
1314 /* Try to allocate the next unused ID */
1315 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1316 &root->hierarchy_id);
1317 if (ret == -ENOSPC)
1318 /* Try again starting from 0 */
1319 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1320 if (!ret) {
1321 next_hierarchy_id = root->hierarchy_id + 1;
1322 } else if (ret != -EAGAIN) {
1323 /* Can only get here if the 31-bit IDR is full ... */
1324 BUG_ON(ret);
1326 spin_unlock(&hierarchy_id_lock);
1327 } while (ret);
1328 return true;
1331 static int cgroup_test_super(struct super_block *sb, void *data)
1333 struct cgroup_sb_opts *opts = data;
1334 struct cgroupfs_root *root = sb->s_fs_info;
1336 /* If we asked for a name then it must match */
1337 if (opts->name && strcmp(opts->name, root->name))
1338 return 0;
1341 * If we asked for subsystems (or explicitly for no
1342 * subsystems) then they must match
1344 if ((opts->subsys_bits || opts->none)
1345 && (opts->subsys_bits != root->subsys_bits))
1346 return 0;
1348 return 1;
1351 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1353 struct cgroupfs_root *root;
1355 if (!opts->subsys_bits && !opts->none)
1356 return NULL;
1358 root = kzalloc(sizeof(*root), GFP_KERNEL);
1359 if (!root)
1360 return ERR_PTR(-ENOMEM);
1362 if (!init_root_id(root)) {
1363 kfree(root);
1364 return ERR_PTR(-ENOMEM);
1366 init_cgroup_root(root);
1368 root->subsys_bits = opts->subsys_bits;
1369 root->flags = opts->flags;
1370 if (opts->release_agent)
1371 strcpy(root->release_agent_path, opts->release_agent);
1372 if (opts->name)
1373 strcpy(root->name, opts->name);
1374 return root;
1377 static void cgroup_drop_root(struct cgroupfs_root *root)
1379 if (!root)
1380 return;
1382 BUG_ON(!root->hierarchy_id);
1383 spin_lock(&hierarchy_id_lock);
1384 ida_remove(&hierarchy_ida, root->hierarchy_id);
1385 spin_unlock(&hierarchy_id_lock);
1386 kfree(root);
1389 static int cgroup_set_super(struct super_block *sb, void *data)
1391 int ret;
1392 struct cgroup_sb_opts *opts = data;
1394 /* If we don't have a new root, we can't set up a new sb */
1395 if (!opts->new_root)
1396 return -EINVAL;
1398 BUG_ON(!opts->subsys_bits && !opts->none);
1400 ret = set_anon_super(sb, NULL);
1401 if (ret)
1402 return ret;
1404 sb->s_fs_info = opts->new_root;
1405 opts->new_root->sb = sb;
1407 sb->s_blocksize = PAGE_CACHE_SIZE;
1408 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1409 sb->s_magic = CGROUP_SUPER_MAGIC;
1410 sb->s_op = &cgroup_ops;
1412 return 0;
1415 static int cgroup_get_rootdir(struct super_block *sb)
1417 struct inode *inode =
1418 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1419 struct dentry *dentry;
1421 if (!inode)
1422 return -ENOMEM;
1424 inode->i_fop = &simple_dir_operations;
1425 inode->i_op = &cgroup_dir_inode_operations;
1426 /* directories start off with i_nlink == 2 (for "." entry) */
1427 inc_nlink(inode);
1428 dentry = d_alloc_root(inode);
1429 if (!dentry) {
1430 iput(inode);
1431 return -ENOMEM;
1433 sb->s_root = dentry;
1434 return 0;
1437 static int cgroup_get_sb(struct file_system_type *fs_type,
1438 int flags, const char *unused_dev_name,
1439 void *data, struct vfsmount *mnt)
1441 struct cgroup_sb_opts opts;
1442 struct cgroupfs_root *root;
1443 int ret = 0;
1444 struct super_block *sb;
1445 struct cgroupfs_root *new_root;
1447 /* First find the desired set of subsystems */
1448 mutex_lock(&cgroup_mutex);
1449 ret = parse_cgroupfs_options(data, &opts);
1450 mutex_unlock(&cgroup_mutex);
1451 if (ret)
1452 goto out_err;
1455 * Allocate a new cgroup root. We may not need it if we're
1456 * reusing an existing hierarchy.
1458 new_root = cgroup_root_from_opts(&opts);
1459 if (IS_ERR(new_root)) {
1460 ret = PTR_ERR(new_root);
1461 goto drop_modules;
1463 opts.new_root = new_root;
1465 /* Locate an existing or new sb for this hierarchy */
1466 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, &opts);
1467 if (IS_ERR(sb)) {
1468 ret = PTR_ERR(sb);
1469 cgroup_drop_root(opts.new_root);
1470 goto drop_modules;
1473 root = sb->s_fs_info;
1474 BUG_ON(!root);
1475 if (root == opts.new_root) {
1476 /* We used the new root structure, so this is a new hierarchy */
1477 struct list_head tmp_cg_links;
1478 struct cgroup *root_cgrp = &root->top_cgroup;
1479 struct inode *inode;
1480 struct cgroupfs_root *existing_root;
1481 int i;
1483 BUG_ON(sb->s_root != NULL);
1485 ret = cgroup_get_rootdir(sb);
1486 if (ret)
1487 goto drop_new_super;
1488 inode = sb->s_root->d_inode;
1490 mutex_lock(&inode->i_mutex);
1491 mutex_lock(&cgroup_mutex);
1493 if (strlen(root->name)) {
1494 /* Check for name clashes with existing mounts */
1495 for_each_active_root(existing_root) {
1496 if (!strcmp(existing_root->name, root->name)) {
1497 ret = -EBUSY;
1498 mutex_unlock(&cgroup_mutex);
1499 mutex_unlock(&inode->i_mutex);
1500 goto drop_new_super;
1506 * We're accessing css_set_count without locking
1507 * css_set_lock here, but that's OK - it can only be
1508 * increased by someone holding cgroup_lock, and
1509 * that's us. The worst that can happen is that we
1510 * have some link structures left over
1512 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1513 if (ret) {
1514 mutex_unlock(&cgroup_mutex);
1515 mutex_unlock(&inode->i_mutex);
1516 goto drop_new_super;
1519 ret = rebind_subsystems(root, root->subsys_bits);
1520 if (ret == -EBUSY) {
1521 mutex_unlock(&cgroup_mutex);
1522 mutex_unlock(&inode->i_mutex);
1523 free_cg_links(&tmp_cg_links);
1524 goto drop_new_super;
1527 * There must be no failure case after here, since rebinding
1528 * takes care of subsystems' refcounts, which are explicitly
1529 * dropped in the failure exit path.
1532 /* EBUSY should be the only error here */
1533 BUG_ON(ret);
1535 list_add(&root->root_list, &roots);
1536 root_count++;
1538 sb->s_root->d_fsdata = root_cgrp;
1539 root->top_cgroup.dentry = sb->s_root;
1541 /* Link the top cgroup in this hierarchy into all
1542 * the css_set objects */
1543 write_lock(&css_set_lock);
1544 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1545 struct hlist_head *hhead = &css_set_table[i];
1546 struct hlist_node *node;
1547 struct css_set *cg;
1549 hlist_for_each_entry(cg, node, hhead, hlist)
1550 link_css_set(&tmp_cg_links, cg, root_cgrp);
1552 write_unlock(&css_set_lock);
1554 free_cg_links(&tmp_cg_links);
1556 BUG_ON(!list_empty(&root_cgrp->sibling));
1557 BUG_ON(!list_empty(&root_cgrp->children));
1558 BUG_ON(root->number_of_cgroups != 1);
1560 cgroup_populate_dir(root_cgrp);
1561 mutex_unlock(&cgroup_mutex);
1562 mutex_unlock(&inode->i_mutex);
1563 } else {
1565 * We re-used an existing hierarchy - the new root (if
1566 * any) is not needed
1568 cgroup_drop_root(opts.new_root);
1569 /* no subsys rebinding, so refcounts don't change */
1570 drop_parsed_module_refcounts(opts.subsys_bits);
1573 simple_set_mnt(mnt, sb);
1574 kfree(opts.release_agent);
1575 kfree(opts.name);
1576 return 0;
1578 drop_new_super:
1579 deactivate_locked_super(sb);
1580 drop_modules:
1581 drop_parsed_module_refcounts(opts.subsys_bits);
1582 out_err:
1583 kfree(opts.release_agent);
1584 kfree(opts.name);
1586 return ret;
1589 static void cgroup_kill_sb(struct super_block *sb) {
1590 struct cgroupfs_root *root = sb->s_fs_info;
1591 struct cgroup *cgrp = &root->top_cgroup;
1592 int ret;
1593 struct cg_cgroup_link *link;
1594 struct cg_cgroup_link *saved_link;
1596 BUG_ON(!root);
1598 BUG_ON(root->number_of_cgroups != 1);
1599 BUG_ON(!list_empty(&cgrp->children));
1600 BUG_ON(!list_empty(&cgrp->sibling));
1602 mutex_lock(&cgroup_mutex);
1604 /* Rebind all subsystems back to the default hierarchy */
1605 ret = rebind_subsystems(root, 0);
1606 /* Shouldn't be able to fail ... */
1607 BUG_ON(ret);
1610 * Release all the links from css_sets to this hierarchy's
1611 * root cgroup
1613 write_lock(&css_set_lock);
1615 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1616 cgrp_link_list) {
1617 list_del(&link->cg_link_list);
1618 list_del(&link->cgrp_link_list);
1619 kfree(link);
1621 write_unlock(&css_set_lock);
1623 if (!list_empty(&root->root_list)) {
1624 list_del(&root->root_list);
1625 root_count--;
1628 mutex_unlock(&cgroup_mutex);
1630 kill_litter_super(sb);
1631 cgroup_drop_root(root);
1634 static struct file_system_type cgroup_fs_type = {
1635 .name = "cgroup",
1636 .get_sb = cgroup_get_sb,
1637 .kill_sb = cgroup_kill_sb,
1640 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1642 return dentry->d_fsdata;
1645 static inline struct cftype *__d_cft(struct dentry *dentry)
1647 return dentry->d_fsdata;
1651 * cgroup_path - generate the path of a cgroup
1652 * @cgrp: the cgroup in question
1653 * @buf: the buffer to write the path into
1654 * @buflen: the length of the buffer
1656 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1657 * reference. Writes path of cgroup into buf. Returns 0 on success,
1658 * -errno on error.
1660 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1662 char *start;
1663 struct dentry *dentry = rcu_dereference(cgrp->dentry);
1665 if (!dentry || cgrp == dummytop) {
1667 * Inactive subsystems have no dentry for their root
1668 * cgroup
1670 strcpy(buf, "/");
1671 return 0;
1674 start = buf + buflen;
1676 *--start = '\0';
1677 for (;;) {
1678 int len = dentry->d_name.len;
1679 if ((start -= len) < buf)
1680 return -ENAMETOOLONG;
1681 memcpy(start, cgrp->dentry->d_name.name, len);
1682 cgrp = cgrp->parent;
1683 if (!cgrp)
1684 break;
1685 dentry = rcu_dereference(cgrp->dentry);
1686 if (!cgrp->parent)
1687 continue;
1688 if (--start < buf)
1689 return -ENAMETOOLONG;
1690 *start = '/';
1692 memmove(buf, start, buf + buflen - start);
1693 return 0;
1695 EXPORT_SYMBOL_GPL(cgroup_path);
1698 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1699 * @cgrp: the cgroup the task is attaching to
1700 * @tsk: the task to be attached
1702 * Call holding cgroup_mutex. May take task_lock of
1703 * the task 'tsk' during call.
1705 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1707 int retval = 0;
1708 struct cgroup_subsys *ss, *failed_ss = NULL;
1709 struct cgroup *oldcgrp;
1710 struct css_set *cg;
1711 struct css_set *newcg;
1712 struct cgroupfs_root *root = cgrp->root;
1714 /* Nothing to do if the task is already in that cgroup */
1715 oldcgrp = task_cgroup_from_root(tsk, root);
1716 if (cgrp == oldcgrp)
1717 return 0;
1719 for_each_subsys(root, ss) {
1720 if (ss->can_attach) {
1721 retval = ss->can_attach(ss, cgrp, tsk, false);
1722 if (retval) {
1724 * Remember on which subsystem the can_attach()
1725 * failed, so that we only call cancel_attach()
1726 * against the subsystems whose can_attach()
1727 * succeeded. (See below)
1729 failed_ss = ss;
1730 goto out;
1735 task_lock(tsk);
1736 cg = tsk->cgroups;
1737 get_css_set(cg);
1738 task_unlock(tsk);
1740 * Locate or allocate a new css_set for this task,
1741 * based on its final set of cgroups
1743 newcg = find_css_set(cg, cgrp);
1744 put_css_set(cg);
1745 if (!newcg) {
1746 retval = -ENOMEM;
1747 goto out;
1750 task_lock(tsk);
1751 if (tsk->flags & PF_EXITING) {
1752 task_unlock(tsk);
1753 put_css_set(newcg);
1754 retval = -ESRCH;
1755 goto out;
1757 rcu_assign_pointer(tsk->cgroups, newcg);
1758 task_unlock(tsk);
1760 /* Update the css_set linked lists if we're using them */
1761 write_lock(&css_set_lock);
1762 if (!list_empty(&tsk->cg_list)) {
1763 list_del(&tsk->cg_list);
1764 list_add(&tsk->cg_list, &newcg->tasks);
1766 write_unlock(&css_set_lock);
1768 for_each_subsys(root, ss) {
1769 if (ss->attach)
1770 ss->attach(ss, cgrp, oldcgrp, tsk, false);
1772 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1773 synchronize_rcu();
1774 put_css_set(cg);
1777 * wake up rmdir() waiter. the rmdir should fail since the cgroup
1778 * is no longer empty.
1780 cgroup_wakeup_rmdir_waiter(cgrp);
1781 out:
1782 if (retval) {
1783 for_each_subsys(root, ss) {
1784 if (ss == failed_ss)
1786 * This subsystem was the one that failed the
1787 * can_attach() check earlier, so we don't need
1788 * to call cancel_attach() against it or any
1789 * remaining subsystems.
1791 break;
1792 if (ss->cancel_attach)
1793 ss->cancel_attach(ss, cgrp, tsk, false);
1796 return retval;
1800 * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
1801 * held. May take task_lock of task
1803 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
1805 struct task_struct *tsk;
1806 const struct cred *cred = current_cred(), *tcred;
1807 int ret;
1809 if (pid) {
1810 rcu_read_lock();
1811 tsk = find_task_by_vpid(pid);
1812 if (!tsk || tsk->flags & PF_EXITING) {
1813 rcu_read_unlock();
1814 return -ESRCH;
1817 tcred = __task_cred(tsk);
1818 if (cred->euid &&
1819 cred->euid != tcred->uid &&
1820 cred->euid != tcred->suid) {
1821 rcu_read_unlock();
1822 return -EACCES;
1824 get_task_struct(tsk);
1825 rcu_read_unlock();
1826 } else {
1827 tsk = current;
1828 get_task_struct(tsk);
1831 ret = cgroup_attach_task(cgrp, tsk);
1832 put_task_struct(tsk);
1833 return ret;
1836 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
1838 int ret;
1839 if (!cgroup_lock_live_group(cgrp))
1840 return -ENODEV;
1841 ret = attach_task_by_pid(cgrp, pid);
1842 cgroup_unlock();
1843 return ret;
1847 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1848 * @cgrp: the cgroup to be checked for liveness
1850 * On success, returns true; the lock should be later released with
1851 * cgroup_unlock(). On failure returns false with no lock held.
1853 bool cgroup_lock_live_group(struct cgroup *cgrp)
1855 mutex_lock(&cgroup_mutex);
1856 if (cgroup_is_removed(cgrp)) {
1857 mutex_unlock(&cgroup_mutex);
1858 return false;
1860 return true;
1862 EXPORT_SYMBOL_GPL(cgroup_lock_live_group);
1864 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1865 const char *buffer)
1867 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1868 if (!cgroup_lock_live_group(cgrp))
1869 return -ENODEV;
1870 strcpy(cgrp->root->release_agent_path, buffer);
1871 cgroup_unlock();
1872 return 0;
1875 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1876 struct seq_file *seq)
1878 if (!cgroup_lock_live_group(cgrp))
1879 return -ENODEV;
1880 seq_puts(seq, cgrp->root->release_agent_path);
1881 seq_putc(seq, '\n');
1882 cgroup_unlock();
1883 return 0;
1886 /* A buffer size big enough for numbers or short strings */
1887 #define CGROUP_LOCAL_BUFFER_SIZE 64
1889 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1890 struct file *file,
1891 const char __user *userbuf,
1892 size_t nbytes, loff_t *unused_ppos)
1894 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1895 int retval = 0;
1896 char *end;
1898 if (!nbytes)
1899 return -EINVAL;
1900 if (nbytes >= sizeof(buffer))
1901 return -E2BIG;
1902 if (copy_from_user(buffer, userbuf, nbytes))
1903 return -EFAULT;
1905 buffer[nbytes] = 0; /* nul-terminate */
1906 if (cft->write_u64) {
1907 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
1908 if (*end)
1909 return -EINVAL;
1910 retval = cft->write_u64(cgrp, cft, val);
1911 } else {
1912 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
1913 if (*end)
1914 return -EINVAL;
1915 retval = cft->write_s64(cgrp, cft, val);
1917 if (!retval)
1918 retval = nbytes;
1919 return retval;
1922 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1923 struct file *file,
1924 const char __user *userbuf,
1925 size_t nbytes, loff_t *unused_ppos)
1927 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1928 int retval = 0;
1929 size_t max_bytes = cft->max_write_len;
1930 char *buffer = local_buffer;
1932 if (!max_bytes)
1933 max_bytes = sizeof(local_buffer) - 1;
1934 if (nbytes >= max_bytes)
1935 return -E2BIG;
1936 /* Allocate a dynamic buffer if we need one */
1937 if (nbytes >= sizeof(local_buffer)) {
1938 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1939 if (buffer == NULL)
1940 return -ENOMEM;
1942 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
1943 retval = -EFAULT;
1944 goto out;
1947 buffer[nbytes] = 0; /* nul-terminate */
1948 retval = cft->write_string(cgrp, cft, strstrip(buffer));
1949 if (!retval)
1950 retval = nbytes;
1951 out:
1952 if (buffer != local_buffer)
1953 kfree(buffer);
1954 return retval;
1957 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1958 size_t nbytes, loff_t *ppos)
1960 struct cftype *cft = __d_cft(file->f_dentry);
1961 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1963 if (cgroup_is_removed(cgrp))
1964 return -ENODEV;
1965 if (cft->write)
1966 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1967 if (cft->write_u64 || cft->write_s64)
1968 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1969 if (cft->write_string)
1970 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1971 if (cft->trigger) {
1972 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1973 return ret ? ret : nbytes;
1975 return -EINVAL;
1978 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1979 struct file *file,
1980 char __user *buf, size_t nbytes,
1981 loff_t *ppos)
1983 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1984 u64 val = cft->read_u64(cgrp, cft);
1985 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1987 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1990 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1991 struct file *file,
1992 char __user *buf, size_t nbytes,
1993 loff_t *ppos)
1995 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1996 s64 val = cft->read_s64(cgrp, cft);
1997 int len = sprintf(tmp, "%lld\n", (long long) val);
1999 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2002 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2003 size_t nbytes, loff_t *ppos)
2005 struct cftype *cft = __d_cft(file->f_dentry);
2006 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2008 if (cgroup_is_removed(cgrp))
2009 return -ENODEV;
2011 if (cft->read)
2012 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2013 if (cft->read_u64)
2014 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2015 if (cft->read_s64)
2016 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2017 return -EINVAL;
2021 * seqfile ops/methods for returning structured data. Currently just
2022 * supports string->u64 maps, but can be extended in future.
2025 struct cgroup_seqfile_state {
2026 struct cftype *cft;
2027 struct cgroup *cgroup;
2030 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2032 struct seq_file *sf = cb->state;
2033 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2036 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2038 struct cgroup_seqfile_state *state = m->private;
2039 struct cftype *cft = state->cft;
2040 if (cft->read_map) {
2041 struct cgroup_map_cb cb = {
2042 .fill = cgroup_map_add,
2043 .state = m,
2045 return cft->read_map(state->cgroup, cft, &cb);
2047 return cft->read_seq_string(state->cgroup, cft, m);
2050 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2052 struct seq_file *seq = file->private_data;
2053 kfree(seq->private);
2054 return single_release(inode, file);
2057 static const struct file_operations cgroup_seqfile_operations = {
2058 .read = seq_read,
2059 .write = cgroup_file_write,
2060 .llseek = seq_lseek,
2061 .release = cgroup_seqfile_release,
2064 static int cgroup_file_open(struct inode *inode, struct file *file)
2066 int err;
2067 struct cftype *cft;
2069 err = generic_file_open(inode, file);
2070 if (err)
2071 return err;
2072 cft = __d_cft(file->f_dentry);
2074 if (cft->read_map || cft->read_seq_string) {
2075 struct cgroup_seqfile_state *state =
2076 kzalloc(sizeof(*state), GFP_USER);
2077 if (!state)
2078 return -ENOMEM;
2079 state->cft = cft;
2080 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2081 file->f_op = &cgroup_seqfile_operations;
2082 err = single_open(file, cgroup_seqfile_show, state);
2083 if (err < 0)
2084 kfree(state);
2085 } else if (cft->open)
2086 err = cft->open(inode, file);
2087 else
2088 err = 0;
2090 return err;
2093 static int cgroup_file_release(struct inode *inode, struct file *file)
2095 struct cftype *cft = __d_cft(file->f_dentry);
2096 if (cft->release)
2097 return cft->release(inode, file);
2098 return 0;
2102 * cgroup_rename - Only allow simple rename of directories in place.
2104 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2105 struct inode *new_dir, struct dentry *new_dentry)
2107 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2108 return -ENOTDIR;
2109 if (new_dentry->d_inode)
2110 return -EEXIST;
2111 if (old_dir != new_dir)
2112 return -EIO;
2113 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2116 static const struct file_operations cgroup_file_operations = {
2117 .read = cgroup_file_read,
2118 .write = cgroup_file_write,
2119 .llseek = generic_file_llseek,
2120 .open = cgroup_file_open,
2121 .release = cgroup_file_release,
2124 static const struct inode_operations cgroup_dir_inode_operations = {
2125 .lookup = simple_lookup,
2126 .mkdir = cgroup_mkdir,
2127 .rmdir = cgroup_rmdir,
2128 .rename = cgroup_rename,
2132 * Check if a file is a control file
2134 static inline struct cftype *__file_cft(struct file *file)
2136 if (file->f_dentry->d_inode->i_fop != &cgroup_file_operations)
2137 return ERR_PTR(-EINVAL);
2138 return __d_cft(file->f_dentry);
2141 static int cgroup_create_file(struct dentry *dentry, mode_t mode,
2142 struct super_block *sb)
2144 static const struct dentry_operations cgroup_dops = {
2145 .d_iput = cgroup_diput,
2148 struct inode *inode;
2150 if (!dentry)
2151 return -ENOENT;
2152 if (dentry->d_inode)
2153 return -EEXIST;
2155 inode = cgroup_new_inode(mode, sb);
2156 if (!inode)
2157 return -ENOMEM;
2159 if (S_ISDIR(mode)) {
2160 inode->i_op = &cgroup_dir_inode_operations;
2161 inode->i_fop = &simple_dir_operations;
2163 /* start off with i_nlink == 2 (for "." entry) */
2164 inc_nlink(inode);
2166 /* start with the directory inode held, so that we can
2167 * populate it without racing with another mkdir */
2168 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
2169 } else if (S_ISREG(mode)) {
2170 inode->i_size = 0;
2171 inode->i_fop = &cgroup_file_operations;
2173 dentry->d_op = &cgroup_dops;
2174 d_instantiate(dentry, inode);
2175 dget(dentry); /* Extra count - pin the dentry in core */
2176 return 0;
2180 * cgroup_create_dir - create a directory for an object.
2181 * @cgrp: the cgroup we create the directory for. It must have a valid
2182 * ->parent field. And we are going to fill its ->dentry field.
2183 * @dentry: dentry of the new cgroup
2184 * @mode: mode to set on new directory.
2186 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
2187 mode_t mode)
2189 struct dentry *parent;
2190 int error = 0;
2192 parent = cgrp->parent->dentry;
2193 error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
2194 if (!error) {
2195 dentry->d_fsdata = cgrp;
2196 inc_nlink(parent->d_inode);
2197 rcu_assign_pointer(cgrp->dentry, dentry);
2198 dget(dentry);
2200 dput(dentry);
2202 return error;
2206 * cgroup_file_mode - deduce file mode of a control file
2207 * @cft: the control file in question
2209 * returns cft->mode if ->mode is not 0
2210 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2211 * returns S_IRUGO if it has only a read handler
2212 * returns S_IWUSR if it has only a write hander
2214 static mode_t cgroup_file_mode(const struct cftype *cft)
2216 mode_t mode = 0;
2218 if (cft->mode)
2219 return cft->mode;
2221 if (cft->read || cft->read_u64 || cft->read_s64 ||
2222 cft->read_map || cft->read_seq_string)
2223 mode |= S_IRUGO;
2225 if (cft->write || cft->write_u64 || cft->write_s64 ||
2226 cft->write_string || cft->trigger)
2227 mode |= S_IWUSR;
2229 return mode;
2232 int cgroup_add_file(struct cgroup *cgrp,
2233 struct cgroup_subsys *subsys,
2234 const struct cftype *cft)
2236 struct dentry *dir = cgrp->dentry;
2237 struct dentry *dentry;
2238 int error;
2239 mode_t mode;
2241 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2242 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2243 strcpy(name, subsys->name);
2244 strcat(name, ".");
2246 strcat(name, cft->name);
2247 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2248 dentry = lookup_one_len(name, dir, strlen(name));
2249 if (!IS_ERR(dentry)) {
2250 mode = cgroup_file_mode(cft);
2251 error = cgroup_create_file(dentry, mode | S_IFREG,
2252 cgrp->root->sb);
2253 if (!error)
2254 dentry->d_fsdata = (void *)cft;
2255 dput(dentry);
2256 } else
2257 error = PTR_ERR(dentry);
2258 return error;
2260 EXPORT_SYMBOL_GPL(cgroup_add_file);
2262 int cgroup_add_files(struct cgroup *cgrp,
2263 struct cgroup_subsys *subsys,
2264 const struct cftype cft[],
2265 int count)
2267 int i, err;
2268 for (i = 0; i < count; i++) {
2269 err = cgroup_add_file(cgrp, subsys, &cft[i]);
2270 if (err)
2271 return err;
2273 return 0;
2275 EXPORT_SYMBOL_GPL(cgroup_add_files);
2278 * cgroup_task_count - count the number of tasks in a cgroup.
2279 * @cgrp: the cgroup in question
2281 * Return the number of tasks in the cgroup.
2283 int cgroup_task_count(const struct cgroup *cgrp)
2285 int count = 0;
2286 struct cg_cgroup_link *link;
2288 read_lock(&css_set_lock);
2289 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2290 count += atomic_read(&link->cg->refcount);
2292 read_unlock(&css_set_lock);
2293 return count;
2297 * Advance a list_head iterator. The iterator should be positioned at
2298 * the start of a css_set
2300 static void cgroup_advance_iter(struct cgroup *cgrp,
2301 struct cgroup_iter *it)
2303 struct list_head *l = it->cg_link;
2304 struct cg_cgroup_link *link;
2305 struct css_set *cg;
2307 /* Advance to the next non-empty css_set */
2308 do {
2309 l = l->next;
2310 if (l == &cgrp->css_sets) {
2311 it->cg_link = NULL;
2312 return;
2314 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2315 cg = link->cg;
2316 } while (list_empty(&cg->tasks));
2317 it->cg_link = l;
2318 it->task = cg->tasks.next;
2322 * To reduce the fork() overhead for systems that are not actually
2323 * using their cgroups capability, we don't maintain the lists running
2324 * through each css_set to its tasks until we see the list actually
2325 * used - in other words after the first call to cgroup_iter_start().
2327 * The tasklist_lock is not held here, as do_each_thread() and
2328 * while_each_thread() are protected by RCU.
2330 static void cgroup_enable_task_cg_lists(void)
2332 struct task_struct *p, *g;
2333 write_lock(&css_set_lock);
2334 use_task_css_set_links = 1;
2335 do_each_thread(g, p) {
2336 task_lock(p);
2338 * We should check if the process is exiting, otherwise
2339 * it will race with cgroup_exit() in that the list
2340 * entry won't be deleted though the process has exited.
2342 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2343 list_add(&p->cg_list, &p->cgroups->tasks);
2344 task_unlock(p);
2345 } while_each_thread(g, p);
2346 write_unlock(&css_set_lock);
2349 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
2352 * The first time anyone tries to iterate across a cgroup,
2353 * we need to enable the list linking each css_set to its
2354 * tasks, and fix up all existing tasks.
2356 if (!use_task_css_set_links)
2357 cgroup_enable_task_cg_lists();
2359 read_lock(&css_set_lock);
2360 it->cg_link = &cgrp->css_sets;
2361 cgroup_advance_iter(cgrp, it);
2364 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
2365 struct cgroup_iter *it)
2367 struct task_struct *res;
2368 struct list_head *l = it->task;
2369 struct cg_cgroup_link *link;
2371 /* If the iterator cg is NULL, we have no tasks */
2372 if (!it->cg_link)
2373 return NULL;
2374 res = list_entry(l, struct task_struct, cg_list);
2375 /* Advance iterator to find next entry */
2376 l = l->next;
2377 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
2378 if (l == &link->cg->tasks) {
2379 /* We reached the end of this task list - move on to
2380 * the next cg_cgroup_link */
2381 cgroup_advance_iter(cgrp, it);
2382 } else {
2383 it->task = l;
2385 return res;
2388 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
2390 read_unlock(&css_set_lock);
2393 static inline int started_after_time(struct task_struct *t1,
2394 struct timespec *time,
2395 struct task_struct *t2)
2397 int start_diff = timespec_compare(&t1->start_time, time);
2398 if (start_diff > 0) {
2399 return 1;
2400 } else if (start_diff < 0) {
2401 return 0;
2402 } else {
2404 * Arbitrarily, if two processes started at the same
2405 * time, we'll say that the lower pointer value
2406 * started first. Note that t2 may have exited by now
2407 * so this may not be a valid pointer any longer, but
2408 * that's fine - it still serves to distinguish
2409 * between two tasks started (effectively) simultaneously.
2411 return t1 > t2;
2416 * This function is a callback from heap_insert() and is used to order
2417 * the heap.
2418 * In this case we order the heap in descending task start time.
2420 static inline int started_after(void *p1, void *p2)
2422 struct task_struct *t1 = p1;
2423 struct task_struct *t2 = p2;
2424 return started_after_time(t1, &t2->start_time, t2);
2428 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
2429 * @scan: struct cgroup_scanner containing arguments for the scan
2431 * Arguments include pointers to callback functions test_task() and
2432 * process_task().
2433 * Iterate through all the tasks in a cgroup, calling test_task() for each,
2434 * and if it returns true, call process_task() for it also.
2435 * The test_task pointer may be NULL, meaning always true (select all tasks).
2436 * Effectively duplicates cgroup_iter_{start,next,end}()
2437 * but does not lock css_set_lock for the call to process_task().
2438 * The struct cgroup_scanner may be embedded in any structure of the caller's
2439 * creation.
2440 * It is guaranteed that process_task() will act on every task that
2441 * is a member of the cgroup for the duration of this call. This
2442 * function may or may not call process_task() for tasks that exit
2443 * or move to a different cgroup during the call, or are forked or
2444 * move into the cgroup during the call.
2446 * Note that test_task() may be called with locks held, and may in some
2447 * situations be called multiple times for the same task, so it should
2448 * be cheap.
2449 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
2450 * pre-allocated and will be used for heap operations (and its "gt" member will
2451 * be overwritten), else a temporary heap will be used (allocation of which
2452 * may cause this function to fail).
2454 int cgroup_scan_tasks(struct cgroup_scanner *scan)
2456 int retval, i;
2457 struct cgroup_iter it;
2458 struct task_struct *p, *dropped;
2459 /* Never dereference latest_task, since it's not refcounted */
2460 struct task_struct *latest_task = NULL;
2461 struct ptr_heap tmp_heap;
2462 struct ptr_heap *heap;
2463 struct timespec latest_time = { 0, 0 };
2465 if (scan->heap) {
2466 /* The caller supplied our heap and pre-allocated its memory */
2467 heap = scan->heap;
2468 heap->gt = &started_after;
2469 } else {
2470 /* We need to allocate our own heap memory */
2471 heap = &tmp_heap;
2472 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2473 if (retval)
2474 /* cannot allocate the heap */
2475 return retval;
2478 again:
2480 * Scan tasks in the cgroup, using the scanner's "test_task" callback
2481 * to determine which are of interest, and using the scanner's
2482 * "process_task" callback to process any of them that need an update.
2483 * Since we don't want to hold any locks during the task updates,
2484 * gather tasks to be processed in a heap structure.
2485 * The heap is sorted by descending task start time.
2486 * If the statically-sized heap fills up, we overflow tasks that
2487 * started later, and in future iterations only consider tasks that
2488 * started after the latest task in the previous pass. This
2489 * guarantees forward progress and that we don't miss any tasks.
2491 heap->size = 0;
2492 cgroup_iter_start(scan->cg, &it);
2493 while ((p = cgroup_iter_next(scan->cg, &it))) {
2495 * Only affect tasks that qualify per the caller's callback,
2496 * if he provided one
2498 if (scan->test_task && !scan->test_task(p, scan))
2499 continue;
2501 * Only process tasks that started after the last task
2502 * we processed
2504 if (!started_after_time(p, &latest_time, latest_task))
2505 continue;
2506 dropped = heap_insert(heap, p);
2507 if (dropped == NULL) {
2509 * The new task was inserted; the heap wasn't
2510 * previously full
2512 get_task_struct(p);
2513 } else if (dropped != p) {
2515 * The new task was inserted, and pushed out a
2516 * different task
2518 get_task_struct(p);
2519 put_task_struct(dropped);
2522 * Else the new task was newer than anything already in
2523 * the heap and wasn't inserted
2526 cgroup_iter_end(scan->cg, &it);
2528 if (heap->size) {
2529 for (i = 0; i < heap->size; i++) {
2530 struct task_struct *q = heap->ptrs[i];
2531 if (i == 0) {
2532 latest_time = q->start_time;
2533 latest_task = q;
2535 /* Process the task per the caller's callback */
2536 scan->process_task(q, scan);
2537 put_task_struct(q);
2540 * If we had to process any tasks at all, scan again
2541 * in case some of them were in the middle of forking
2542 * children that didn't get processed.
2543 * Not the most efficient way to do it, but it avoids
2544 * having to take callback_mutex in the fork path
2546 goto again;
2548 if (heap == &tmp_heap)
2549 heap_free(&tmp_heap);
2550 return 0;
2554 * Stuff for reading the 'tasks'/'procs' files.
2556 * Reading this file can return large amounts of data if a cgroup has
2557 * *lots* of attached tasks. So it may need several calls to read(),
2558 * but we cannot guarantee that the information we produce is correct
2559 * unless we produce it entirely atomically.
2564 * The following two functions "fix" the issue where there are more pids
2565 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
2566 * TODO: replace with a kernel-wide solution to this problem
2568 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
2569 static void *pidlist_allocate(int count)
2571 if (PIDLIST_TOO_LARGE(count))
2572 return vmalloc(count * sizeof(pid_t));
2573 else
2574 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
2576 static void pidlist_free(void *p)
2578 if (is_vmalloc_addr(p))
2579 vfree(p);
2580 else
2581 kfree(p);
2583 static void *pidlist_resize(void *p, int newcount)
2585 void *newlist;
2586 /* note: if new alloc fails, old p will still be valid either way */
2587 if (is_vmalloc_addr(p)) {
2588 newlist = vmalloc(newcount * sizeof(pid_t));
2589 if (!newlist)
2590 return NULL;
2591 memcpy(newlist, p, newcount * sizeof(pid_t));
2592 vfree(p);
2593 } else {
2594 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
2596 return newlist;
2600 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
2601 * If the new stripped list is sufficiently smaller and there's enough memory
2602 * to allocate a new buffer, will let go of the unneeded memory. Returns the
2603 * number of unique elements.
2605 /* is the size difference enough that we should re-allocate the array? */
2606 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
2607 static int pidlist_uniq(pid_t **p, int length)
2609 int src, dest = 1;
2610 pid_t *list = *p;
2611 pid_t *newlist;
2614 * we presume the 0th element is unique, so i starts at 1. trivial
2615 * edge cases first; no work needs to be done for either
2617 if (length == 0 || length == 1)
2618 return length;
2619 /* src and dest walk down the list; dest counts unique elements */
2620 for (src = 1; src < length; src++) {
2621 /* find next unique element */
2622 while (list[src] == list[src-1]) {
2623 src++;
2624 if (src == length)
2625 goto after;
2627 /* dest always points to where the next unique element goes */
2628 list[dest] = list[src];
2629 dest++;
2631 after:
2633 * if the length difference is large enough, we want to allocate a
2634 * smaller buffer to save memory. if this fails due to out of memory,
2635 * we'll just stay with what we've got.
2637 if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
2638 newlist = pidlist_resize(list, dest);
2639 if (newlist)
2640 *p = newlist;
2642 return dest;
2645 static int cmppid(const void *a, const void *b)
2647 return *(pid_t *)a - *(pid_t *)b;
2651 * find the appropriate pidlist for our purpose (given procs vs tasks)
2652 * returns with the lock on that pidlist already held, and takes care
2653 * of the use count, or returns NULL with no locks held if we're out of
2654 * memory.
2656 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
2657 enum cgroup_filetype type)
2659 struct cgroup_pidlist *l;
2660 /* don't need task_nsproxy() if we're looking at ourself */
2661 struct pid_namespace *ns = current->nsproxy->pid_ns;
2664 * We can't drop the pidlist_mutex before taking the l->mutex in case
2665 * the last ref-holder is trying to remove l from the list at the same
2666 * time. Holding the pidlist_mutex precludes somebody taking whichever
2667 * list we find out from under us - compare release_pid_array().
2669 mutex_lock(&cgrp->pidlist_mutex);
2670 list_for_each_entry(l, &cgrp->pidlists, links) {
2671 if (l->key.type == type && l->key.ns == ns) {
2672 /* make sure l doesn't vanish out from under us */
2673 down_write(&l->mutex);
2674 mutex_unlock(&cgrp->pidlist_mutex);
2675 return l;
2678 /* entry not found; create a new one */
2679 l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
2680 if (!l) {
2681 mutex_unlock(&cgrp->pidlist_mutex);
2682 return l;
2684 init_rwsem(&l->mutex);
2685 down_write(&l->mutex);
2686 l->key.type = type;
2687 l->key.ns = get_pid_ns(ns);
2688 l->use_count = 0; /* don't increment here */
2689 l->list = NULL;
2690 l->owner = cgrp;
2691 list_add(&l->links, &cgrp->pidlists);
2692 mutex_unlock(&cgrp->pidlist_mutex);
2693 return l;
2697 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
2699 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
2700 struct cgroup_pidlist **lp)
2702 pid_t *array;
2703 int length;
2704 int pid, n = 0; /* used for populating the array */
2705 struct cgroup_iter it;
2706 struct task_struct *tsk;
2707 struct cgroup_pidlist *l;
2710 * If cgroup gets more users after we read count, we won't have
2711 * enough space - tough. This race is indistinguishable to the
2712 * caller from the case that the additional cgroup users didn't
2713 * show up until sometime later on.
2715 length = cgroup_task_count(cgrp);
2716 array = pidlist_allocate(length);
2717 if (!array)
2718 return -ENOMEM;
2719 /* now, populate the array */
2720 cgroup_iter_start(cgrp, &it);
2721 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2722 if (unlikely(n == length))
2723 break;
2724 /* get tgid or pid for procs or tasks file respectively */
2725 if (type == CGROUP_FILE_PROCS)
2726 pid = task_tgid_vnr(tsk);
2727 else
2728 pid = task_pid_vnr(tsk);
2729 if (pid > 0) /* make sure to only use valid results */
2730 array[n++] = pid;
2732 cgroup_iter_end(cgrp, &it);
2733 length = n;
2734 /* now sort & (if procs) strip out duplicates */
2735 sort(array, length, sizeof(pid_t), cmppid, NULL);
2736 if (type == CGROUP_FILE_PROCS)
2737 length = pidlist_uniq(&array, length);
2738 l = cgroup_pidlist_find(cgrp, type);
2739 if (!l) {
2740 pidlist_free(array);
2741 return -ENOMEM;
2743 /* store array, freeing old if necessary - lock already held */
2744 pidlist_free(l->list);
2745 l->list = array;
2746 l->length = length;
2747 l->use_count++;
2748 up_write(&l->mutex);
2749 *lp = l;
2750 return 0;
2754 * cgroupstats_build - build and fill cgroupstats
2755 * @stats: cgroupstats to fill information into
2756 * @dentry: A dentry entry belonging to the cgroup for which stats have
2757 * been requested.
2759 * Build and fill cgroupstats so that taskstats can export it to user
2760 * space.
2762 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2764 int ret = -EINVAL;
2765 struct cgroup *cgrp;
2766 struct cgroup_iter it;
2767 struct task_struct *tsk;
2770 * Validate dentry by checking the superblock operations,
2771 * and make sure it's a directory.
2773 if (dentry->d_sb->s_op != &cgroup_ops ||
2774 !S_ISDIR(dentry->d_inode->i_mode))
2775 goto err;
2777 ret = 0;
2778 cgrp = dentry->d_fsdata;
2780 cgroup_iter_start(cgrp, &it);
2781 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2782 switch (tsk->state) {
2783 case TASK_RUNNING:
2784 stats->nr_running++;
2785 break;
2786 case TASK_INTERRUPTIBLE:
2787 stats->nr_sleeping++;
2788 break;
2789 case TASK_UNINTERRUPTIBLE:
2790 stats->nr_uninterruptible++;
2791 break;
2792 case TASK_STOPPED:
2793 stats->nr_stopped++;
2794 break;
2795 default:
2796 if (delayacct_is_task_waiting_on_io(tsk))
2797 stats->nr_io_wait++;
2798 break;
2801 cgroup_iter_end(cgrp, &it);
2803 err:
2804 return ret;
2809 * seq_file methods for the tasks/procs files. The seq_file position is the
2810 * next pid to display; the seq_file iterator is a pointer to the pid
2811 * in the cgroup->l->list array.
2814 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
2817 * Initially we receive a position value that corresponds to
2818 * one more than the last pid shown (or 0 on the first call or
2819 * after a seek to the start). Use a binary-search to find the
2820 * next pid to display, if any
2822 struct cgroup_pidlist *l = s->private;
2823 int index = 0, pid = *pos;
2824 int *iter;
2826 down_read(&l->mutex);
2827 if (pid) {
2828 int end = l->length;
2830 while (index < end) {
2831 int mid = (index + end) / 2;
2832 if (l->list[mid] == pid) {
2833 index = mid;
2834 break;
2835 } else if (l->list[mid] <= pid)
2836 index = mid + 1;
2837 else
2838 end = mid;
2841 /* If we're off the end of the array, we're done */
2842 if (index >= l->length)
2843 return NULL;
2844 /* Update the abstract position to be the actual pid that we found */
2845 iter = l->list + index;
2846 *pos = *iter;
2847 return iter;
2850 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
2852 struct cgroup_pidlist *l = s->private;
2853 up_read(&l->mutex);
2856 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
2858 struct cgroup_pidlist *l = s->private;
2859 pid_t *p = v;
2860 pid_t *end = l->list + l->length;
2862 * Advance to the next pid in the array. If this goes off the
2863 * end, we're done
2865 p++;
2866 if (p >= end) {
2867 return NULL;
2868 } else {
2869 *pos = *p;
2870 return p;
2874 static int cgroup_pidlist_show(struct seq_file *s, void *v)
2876 return seq_printf(s, "%d\n", *(int *)v);
2880 * seq_operations functions for iterating on pidlists through seq_file -
2881 * independent of whether it's tasks or procs
2883 static const struct seq_operations cgroup_pidlist_seq_operations = {
2884 .start = cgroup_pidlist_start,
2885 .stop = cgroup_pidlist_stop,
2886 .next = cgroup_pidlist_next,
2887 .show = cgroup_pidlist_show,
2890 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
2893 * the case where we're the last user of this particular pidlist will
2894 * have us remove it from the cgroup's list, which entails taking the
2895 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
2896 * pidlist_mutex, we have to take pidlist_mutex first.
2898 mutex_lock(&l->owner->pidlist_mutex);
2899 down_write(&l->mutex);
2900 BUG_ON(!l->use_count);
2901 if (!--l->use_count) {
2902 /* we're the last user if refcount is 0; remove and free */
2903 list_del(&l->links);
2904 mutex_unlock(&l->owner->pidlist_mutex);
2905 pidlist_free(l->list);
2906 put_pid_ns(l->key.ns);
2907 up_write(&l->mutex);
2908 kfree(l);
2909 return;
2911 mutex_unlock(&l->owner->pidlist_mutex);
2912 up_write(&l->mutex);
2915 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
2917 struct cgroup_pidlist *l;
2918 if (!(file->f_mode & FMODE_READ))
2919 return 0;
2921 * the seq_file will only be initialized if the file was opened for
2922 * reading; hence we check if it's not null only in that case.
2924 l = ((struct seq_file *)file->private_data)->private;
2925 cgroup_release_pid_array(l);
2926 return seq_release(inode, file);
2929 static const struct file_operations cgroup_pidlist_operations = {
2930 .read = seq_read,
2931 .llseek = seq_lseek,
2932 .write = cgroup_file_write,
2933 .release = cgroup_pidlist_release,
2937 * The following functions handle opens on a file that displays a pidlist
2938 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
2939 * in the cgroup.
2941 /* helper function for the two below it */
2942 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
2944 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2945 struct cgroup_pidlist *l;
2946 int retval;
2948 /* Nothing to do for write-only files */
2949 if (!(file->f_mode & FMODE_READ))
2950 return 0;
2952 /* have the array populated */
2953 retval = pidlist_array_load(cgrp, type, &l);
2954 if (retval)
2955 return retval;
2956 /* configure file information */
2957 file->f_op = &cgroup_pidlist_operations;
2959 retval = seq_open(file, &cgroup_pidlist_seq_operations);
2960 if (retval) {
2961 cgroup_release_pid_array(l);
2962 return retval;
2964 ((struct seq_file *)file->private_data)->private = l;
2965 return 0;
2967 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2969 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
2971 static int cgroup_procs_open(struct inode *unused, struct file *file)
2973 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
2976 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2977 struct cftype *cft)
2979 return notify_on_release(cgrp);
2982 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2983 struct cftype *cft,
2984 u64 val)
2986 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2987 if (val)
2988 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2989 else
2990 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2991 return 0;
2995 * Unregister event and free resources.
2997 * Gets called from workqueue.
2999 static void cgroup_event_remove(struct work_struct *work)
3001 struct cgroup_event *event = container_of(work, struct cgroup_event,
3002 remove);
3003 struct cgroup *cgrp = event->cgrp;
3005 /* TODO: check return code */
3006 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3008 eventfd_ctx_put(event->eventfd);
3009 remove_wait_queue(event->wqh, &event->wait);
3010 kfree(event);
3014 * Gets called on POLLHUP on eventfd when user closes it.
3016 * Called with wqh->lock held and interrupts disabled.
3018 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3019 int sync, void *key)
3021 struct cgroup_event *event = container_of(wait,
3022 struct cgroup_event, wait);
3023 struct cgroup *cgrp = event->cgrp;
3024 unsigned long flags = (unsigned long)key;
3026 if (flags & POLLHUP) {
3027 spin_lock(&cgrp->event_list_lock);
3028 list_del(&event->list);
3029 spin_unlock(&cgrp->event_list_lock);
3031 * We are in atomic context, but cgroup_event_remove() may
3032 * sleep, so we have to call it in workqueue.
3034 schedule_work(&event->remove);
3037 return 0;
3040 static void cgroup_event_ptable_queue_proc(struct file *file,
3041 wait_queue_head_t *wqh, poll_table *pt)
3043 struct cgroup_event *event = container_of(pt,
3044 struct cgroup_event, pt);
3046 event->wqh = wqh;
3047 add_wait_queue(wqh, &event->wait);
3051 * Parse input and register new cgroup event handler.
3053 * Input must be in format '<event_fd> <control_fd> <args>'.
3054 * Interpretation of args is defined by control file implementation.
3056 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3057 const char *buffer)
3059 struct cgroup_event *event = NULL;
3060 unsigned int efd, cfd;
3061 struct file *efile = NULL;
3062 struct file *cfile = NULL;
3063 char *endp;
3064 int ret;
3066 efd = simple_strtoul(buffer, &endp, 10);
3067 if (*endp != ' ')
3068 return -EINVAL;
3069 buffer = endp + 1;
3071 cfd = simple_strtoul(buffer, &endp, 10);
3072 if ((*endp != ' ') && (*endp != '\0'))
3073 return -EINVAL;
3074 buffer = endp + 1;
3076 event = kzalloc(sizeof(*event), GFP_KERNEL);
3077 if (!event)
3078 return -ENOMEM;
3079 event->cgrp = cgrp;
3080 INIT_LIST_HEAD(&event->list);
3081 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3082 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3083 INIT_WORK(&event->remove, cgroup_event_remove);
3085 efile = eventfd_fget(efd);
3086 if (IS_ERR(efile)) {
3087 ret = PTR_ERR(efile);
3088 goto fail;
3091 event->eventfd = eventfd_ctx_fileget(efile);
3092 if (IS_ERR(event->eventfd)) {
3093 ret = PTR_ERR(event->eventfd);
3094 goto fail;
3097 cfile = fget(cfd);
3098 if (!cfile) {
3099 ret = -EBADF;
3100 goto fail;
3103 /* the process need read permission on control file */
3104 ret = file_permission(cfile, MAY_READ);
3105 if (ret < 0)
3106 goto fail;
3108 event->cft = __file_cft(cfile);
3109 if (IS_ERR(event->cft)) {
3110 ret = PTR_ERR(event->cft);
3111 goto fail;
3114 if (!event->cft->register_event || !event->cft->unregister_event) {
3115 ret = -EINVAL;
3116 goto fail;
3119 ret = event->cft->register_event(cgrp, event->cft,
3120 event->eventfd, buffer);
3121 if (ret)
3122 goto fail;
3124 if (efile->f_op->poll(efile, &event->pt) & POLLHUP) {
3125 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3126 ret = 0;
3127 goto fail;
3130 spin_lock(&cgrp->event_list_lock);
3131 list_add(&event->list, &cgrp->event_list);
3132 spin_unlock(&cgrp->event_list_lock);
3134 fput(cfile);
3135 fput(efile);
3137 return 0;
3139 fail:
3140 if (cfile)
3141 fput(cfile);
3143 if (event && event->eventfd && !IS_ERR(event->eventfd))
3144 eventfd_ctx_put(event->eventfd);
3146 if (!IS_ERR_OR_NULL(efile))
3147 fput(efile);
3149 kfree(event);
3151 return ret;
3155 * for the common functions, 'private' gives the type of file
3157 /* for hysterical raisins, we can't put this on the older files */
3158 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3159 static struct cftype files[] = {
3161 .name = "tasks",
3162 .open = cgroup_tasks_open,
3163 .write_u64 = cgroup_tasks_write,
3164 .release = cgroup_pidlist_release,
3165 .mode = S_IRUGO | S_IWUSR,
3168 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
3169 .open = cgroup_procs_open,
3170 /* .write_u64 = cgroup_procs_write, TODO */
3171 .release = cgroup_pidlist_release,
3172 .mode = S_IRUGO,
3175 .name = "notify_on_release",
3176 .read_u64 = cgroup_read_notify_on_release,
3177 .write_u64 = cgroup_write_notify_on_release,
3180 .name = CGROUP_FILE_GENERIC_PREFIX "event_control",
3181 .write_string = cgroup_write_event_control,
3182 .mode = S_IWUGO,
3186 static struct cftype cft_release_agent = {
3187 .name = "release_agent",
3188 .read_seq_string = cgroup_release_agent_show,
3189 .write_string = cgroup_release_agent_write,
3190 .max_write_len = PATH_MAX,
3193 static int cgroup_populate_dir(struct cgroup *cgrp)
3195 int err;
3196 struct cgroup_subsys *ss;
3198 /* First clear out any existing files */
3199 cgroup_clear_directory(cgrp->dentry);
3201 err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
3202 if (err < 0)
3203 return err;
3205 if (cgrp == cgrp->top_cgroup) {
3206 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
3207 return err;
3210 for_each_subsys(cgrp->root, ss) {
3211 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
3212 return err;
3214 /* This cgroup is ready now */
3215 for_each_subsys(cgrp->root, ss) {
3216 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3218 * Update id->css pointer and make this css visible from
3219 * CSS ID functions. This pointer will be dereferened
3220 * from RCU-read-side without locks.
3222 if (css->id)
3223 rcu_assign_pointer(css->id->css, css);
3226 return 0;
3229 static void init_cgroup_css(struct cgroup_subsys_state *css,
3230 struct cgroup_subsys *ss,
3231 struct cgroup *cgrp)
3233 css->cgroup = cgrp;
3234 atomic_set(&css->refcnt, 1);
3235 css->flags = 0;
3236 css->id = NULL;
3237 if (cgrp == dummytop)
3238 set_bit(CSS_ROOT, &css->flags);
3239 BUG_ON(cgrp->subsys[ss->subsys_id]);
3240 cgrp->subsys[ss->subsys_id] = css;
3243 static void cgroup_lock_hierarchy(struct cgroupfs_root *root)
3245 /* We need to take each hierarchy_mutex in a consistent order */
3246 int i;
3249 * No worry about a race with rebind_subsystems that might mess up the
3250 * locking order, since both parties are under cgroup_mutex.
3252 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3253 struct cgroup_subsys *ss = subsys[i];
3254 if (ss == NULL)
3255 continue;
3256 if (ss->root == root)
3257 mutex_lock(&ss->hierarchy_mutex);
3261 static void cgroup_unlock_hierarchy(struct cgroupfs_root *root)
3263 int i;
3265 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3266 struct cgroup_subsys *ss = subsys[i];
3267 if (ss == NULL)
3268 continue;
3269 if (ss->root == root)
3270 mutex_unlock(&ss->hierarchy_mutex);
3275 * cgroup_create - create a cgroup
3276 * @parent: cgroup that will be parent of the new cgroup
3277 * @dentry: dentry of the new cgroup
3278 * @mode: mode to set on new inode
3280 * Must be called with the mutex on the parent inode held
3282 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
3283 mode_t mode)
3285 struct cgroup *cgrp;
3286 struct cgroupfs_root *root = parent->root;
3287 int err = 0;
3288 struct cgroup_subsys *ss;
3289 struct super_block *sb = root->sb;
3291 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
3292 if (!cgrp)
3293 return -ENOMEM;
3295 /* Grab a reference on the superblock so the hierarchy doesn't
3296 * get deleted on unmount if there are child cgroups. This
3297 * can be done outside cgroup_mutex, since the sb can't
3298 * disappear while someone has an open control file on the
3299 * fs */
3300 atomic_inc(&sb->s_active);
3302 mutex_lock(&cgroup_mutex);
3304 init_cgroup_housekeeping(cgrp);
3306 cgrp->parent = parent;
3307 cgrp->root = parent->root;
3308 cgrp->top_cgroup = parent->top_cgroup;
3310 if (notify_on_release(parent))
3311 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3313 for_each_subsys(root, ss) {
3314 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
3316 if (IS_ERR(css)) {
3317 err = PTR_ERR(css);
3318 goto err_destroy;
3320 init_cgroup_css(css, ss, cgrp);
3321 if (ss->use_id) {
3322 err = alloc_css_id(ss, parent, cgrp);
3323 if (err)
3324 goto err_destroy;
3326 /* At error, ->destroy() callback has to free assigned ID. */
3329 cgroup_lock_hierarchy(root);
3330 list_add(&cgrp->sibling, &cgrp->parent->children);
3331 cgroup_unlock_hierarchy(root);
3332 root->number_of_cgroups++;
3334 err = cgroup_create_dir(cgrp, dentry, mode);
3335 if (err < 0)
3336 goto err_remove;
3338 /* The cgroup directory was pre-locked for us */
3339 BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
3341 err = cgroup_populate_dir(cgrp);
3342 /* If err < 0, we have a half-filled directory - oh well ;) */
3344 mutex_unlock(&cgroup_mutex);
3345 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
3347 return 0;
3349 err_remove:
3351 cgroup_lock_hierarchy(root);
3352 list_del(&cgrp->sibling);
3353 cgroup_unlock_hierarchy(root);
3354 root->number_of_cgroups--;
3356 err_destroy:
3358 for_each_subsys(root, ss) {
3359 if (cgrp->subsys[ss->subsys_id])
3360 ss->destroy(ss, cgrp);
3363 mutex_unlock(&cgroup_mutex);
3365 /* Release the reference count that we took on the superblock */
3366 deactivate_super(sb);
3368 kfree(cgrp);
3369 return err;
3372 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
3374 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
3376 /* the vfs holds inode->i_mutex already */
3377 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
3380 static int cgroup_has_css_refs(struct cgroup *cgrp)
3382 /* Check the reference count on each subsystem. Since we
3383 * already established that there are no tasks in the
3384 * cgroup, if the css refcount is also 1, then there should
3385 * be no outstanding references, so the subsystem is safe to
3386 * destroy. We scan across all subsystems rather than using
3387 * the per-hierarchy linked list of mounted subsystems since
3388 * we can be called via check_for_release() with no
3389 * synchronization other than RCU, and the subsystem linked
3390 * list isn't RCU-safe */
3391 int i;
3393 * We won't need to lock the subsys array, because the subsystems
3394 * we're concerned about aren't going anywhere since our cgroup root
3395 * has a reference on them.
3397 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3398 struct cgroup_subsys *ss = subsys[i];
3399 struct cgroup_subsys_state *css;
3400 /* Skip subsystems not present or not in this hierarchy */
3401 if (ss == NULL || ss->root != cgrp->root)
3402 continue;
3403 css = cgrp->subsys[ss->subsys_id];
3404 /* When called from check_for_release() it's possible
3405 * that by this point the cgroup has been removed
3406 * and the css deleted. But a false-positive doesn't
3407 * matter, since it can only happen if the cgroup
3408 * has been deleted and hence no longer needs the
3409 * release agent to be called anyway. */
3410 if (css && (atomic_read(&css->refcnt) > 1))
3411 return 1;
3413 return 0;
3417 * Atomically mark all (or else none) of the cgroup's CSS objects as
3418 * CSS_REMOVED. Return true on success, or false if the cgroup has
3419 * busy subsystems. Call with cgroup_mutex held
3422 static int cgroup_clear_css_refs(struct cgroup *cgrp)
3424 struct cgroup_subsys *ss;
3425 unsigned long flags;
3426 bool failed = false;
3427 local_irq_save(flags);
3428 for_each_subsys(cgrp->root, ss) {
3429 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3430 int refcnt;
3431 while (1) {
3432 /* We can only remove a CSS with a refcnt==1 */
3433 refcnt = atomic_read(&css->refcnt);
3434 if (refcnt > 1) {
3435 failed = true;
3436 goto done;
3438 BUG_ON(!refcnt);
3440 * Drop the refcnt to 0 while we check other
3441 * subsystems. This will cause any racing
3442 * css_tryget() to spin until we set the
3443 * CSS_REMOVED bits or abort
3445 if (atomic_cmpxchg(&css->refcnt, refcnt, 0) == refcnt)
3446 break;
3447 cpu_relax();
3450 done:
3451 for_each_subsys(cgrp->root, ss) {
3452 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3453 if (failed) {
3455 * Restore old refcnt if we previously managed
3456 * to clear it from 1 to 0
3458 if (!atomic_read(&css->refcnt))
3459 atomic_set(&css->refcnt, 1);
3460 } else {
3461 /* Commit the fact that the CSS is removed */
3462 set_bit(CSS_REMOVED, &css->flags);
3465 local_irq_restore(flags);
3466 return !failed;
3469 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
3471 struct cgroup *cgrp = dentry->d_fsdata;
3472 struct dentry *d;
3473 struct cgroup *parent;
3474 DEFINE_WAIT(wait);
3475 int ret;
3477 /* the vfs holds both inode->i_mutex already */
3478 again:
3479 mutex_lock(&cgroup_mutex);
3480 if (atomic_read(&cgrp->count) != 0) {
3481 mutex_unlock(&cgroup_mutex);
3482 return -EBUSY;
3484 if (!list_empty(&cgrp->children)) {
3485 mutex_unlock(&cgroup_mutex);
3486 return -EBUSY;
3488 mutex_unlock(&cgroup_mutex);
3491 * In general, subsystem has no css->refcnt after pre_destroy(). But
3492 * in racy cases, subsystem may have to get css->refcnt after
3493 * pre_destroy() and it makes rmdir return with -EBUSY. This sometimes
3494 * make rmdir return -EBUSY too often. To avoid that, we use waitqueue
3495 * for cgroup's rmdir. CGRP_WAIT_ON_RMDIR is for synchronizing rmdir
3496 * and subsystem's reference count handling. Please see css_get/put
3497 * and css_tryget() and cgroup_wakeup_rmdir_waiter() implementation.
3499 set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3502 * Call pre_destroy handlers of subsys. Notify subsystems
3503 * that rmdir() request comes.
3505 ret = cgroup_call_pre_destroy(cgrp);
3506 if (ret) {
3507 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3508 return ret;
3511 mutex_lock(&cgroup_mutex);
3512 parent = cgrp->parent;
3513 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
3514 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3515 mutex_unlock(&cgroup_mutex);
3516 return -EBUSY;
3518 prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
3519 if (!cgroup_clear_css_refs(cgrp)) {
3520 mutex_unlock(&cgroup_mutex);
3522 * Because someone may call cgroup_wakeup_rmdir_waiter() before
3523 * prepare_to_wait(), we need to check this flag.
3525 if (test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))
3526 schedule();
3527 finish_wait(&cgroup_rmdir_waitq, &wait);
3528 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3529 if (signal_pending(current))
3530 return -EINTR;
3531 goto again;
3533 /* NO css_tryget() can success after here. */
3534 finish_wait(&cgroup_rmdir_waitq, &wait);
3535 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3537 spin_lock(&release_list_lock);
3538 set_bit(CGRP_REMOVED, &cgrp->flags);
3539 if (!list_empty(&cgrp->release_list))
3540 list_del(&cgrp->release_list);
3541 spin_unlock(&release_list_lock);
3543 cgroup_lock_hierarchy(cgrp->root);
3544 /* delete this cgroup from parent->children */
3545 list_del(&cgrp->sibling);
3546 cgroup_unlock_hierarchy(cgrp->root);
3548 spin_lock(&cgrp->dentry->d_lock);
3549 d = dget(cgrp->dentry);
3550 spin_unlock(&d->d_lock);
3552 cgroup_d_remove_dir(d);
3553 dput(d);
3555 set_bit(CGRP_RELEASABLE, &parent->flags);
3556 check_for_release(parent);
3558 mutex_unlock(&cgroup_mutex);
3559 return 0;
3562 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
3564 struct cgroup_subsys_state *css;
3566 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
3568 /* Create the top cgroup state for this subsystem */
3569 list_add(&ss->sibling, &rootnode.subsys_list);
3570 ss->root = &rootnode;
3571 css = ss->create(ss, dummytop);
3572 /* We don't handle early failures gracefully */
3573 BUG_ON(IS_ERR(css));
3574 init_cgroup_css(css, ss, dummytop);
3576 /* Update the init_css_set to contain a subsys
3577 * pointer to this state - since the subsystem is
3578 * newly registered, all tasks and hence the
3579 * init_css_set is in the subsystem's top cgroup. */
3580 init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
3582 need_forkexit_callback |= ss->fork || ss->exit;
3584 /* At system boot, before all subsystems have been
3585 * registered, no tasks have been forked, so we don't
3586 * need to invoke fork callbacks here. */
3587 BUG_ON(!list_empty(&init_task.tasks));
3589 mutex_init(&ss->hierarchy_mutex);
3590 lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
3591 ss->active = 1;
3593 /* this function shouldn't be used with modular subsystems, since they
3594 * need to register a subsys_id, among other things */
3595 BUG_ON(ss->module);
3599 * cgroup_load_subsys: load and register a modular subsystem at runtime
3600 * @ss: the subsystem to load
3602 * This function should be called in a modular subsystem's initcall. If the
3603 * subsytem is built as a module, it will be assigned a new subsys_id and set
3604 * up for use. If the subsystem is built-in anyway, work is delegated to the
3605 * simpler cgroup_init_subsys.
3607 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
3609 int i;
3610 struct cgroup_subsys_state *css;
3612 /* check name and function validity */
3613 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
3614 ss->create == NULL || ss->destroy == NULL)
3615 return -EINVAL;
3618 * we don't support callbacks in modular subsystems. this check is
3619 * before the ss->module check for consistency; a subsystem that could
3620 * be a module should still have no callbacks even if the user isn't
3621 * compiling it as one.
3623 if (ss->fork || ss->exit)
3624 return -EINVAL;
3627 * an optionally modular subsystem is built-in: we want to do nothing,
3628 * since cgroup_init_subsys will have already taken care of it.
3630 if (ss->module == NULL) {
3631 /* a few sanity checks */
3632 BUG_ON(ss->subsys_id >= CGROUP_BUILTIN_SUBSYS_COUNT);
3633 BUG_ON(subsys[ss->subsys_id] != ss);
3634 return 0;
3638 * need to register a subsys id before anything else - for example,
3639 * init_cgroup_css needs it.
3641 mutex_lock(&cgroup_mutex);
3642 /* find the first empty slot in the array */
3643 for (i = CGROUP_BUILTIN_SUBSYS_COUNT; i < CGROUP_SUBSYS_COUNT; i++) {
3644 if (subsys[i] == NULL)
3645 break;
3647 if (i == CGROUP_SUBSYS_COUNT) {
3648 /* maximum number of subsystems already registered! */
3649 mutex_unlock(&cgroup_mutex);
3650 return -EBUSY;
3652 /* assign ourselves the subsys_id */
3653 ss->subsys_id = i;
3654 subsys[i] = ss;
3657 * no ss->create seems to need anything important in the ss struct, so
3658 * this can happen first (i.e. before the rootnode attachment).
3660 css = ss->create(ss, dummytop);
3661 if (IS_ERR(css)) {
3662 /* failure case - need to deassign the subsys[] slot. */
3663 subsys[i] = NULL;
3664 mutex_unlock(&cgroup_mutex);
3665 return PTR_ERR(css);
3668 list_add(&ss->sibling, &rootnode.subsys_list);
3669 ss->root = &rootnode;
3671 /* our new subsystem will be attached to the dummy hierarchy. */
3672 init_cgroup_css(css, ss, dummytop);
3673 /* init_idr must be after init_cgroup_css because it sets css->id. */
3674 if (ss->use_id) {
3675 int ret = cgroup_init_idr(ss, css);
3676 if (ret) {
3677 dummytop->subsys[ss->subsys_id] = NULL;
3678 ss->destroy(ss, dummytop);
3679 subsys[i] = NULL;
3680 mutex_unlock(&cgroup_mutex);
3681 return ret;
3686 * Now we need to entangle the css into the existing css_sets. unlike
3687 * in cgroup_init_subsys, there are now multiple css_sets, so each one
3688 * will need a new pointer to it; done by iterating the css_set_table.
3689 * furthermore, modifying the existing css_sets will corrupt the hash
3690 * table state, so each changed css_set will need its hash recomputed.
3691 * this is all done under the css_set_lock.
3693 write_lock(&css_set_lock);
3694 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
3695 struct css_set *cg;
3696 struct hlist_node *node, *tmp;
3697 struct hlist_head *bucket = &css_set_table[i], *new_bucket;
3699 hlist_for_each_entry_safe(cg, node, tmp, bucket, hlist) {
3700 /* skip entries that we already rehashed */
3701 if (cg->subsys[ss->subsys_id])
3702 continue;
3703 /* remove existing entry */
3704 hlist_del(&cg->hlist);
3705 /* set new value */
3706 cg->subsys[ss->subsys_id] = css;
3707 /* recompute hash and restore entry */
3708 new_bucket = css_set_hash(cg->subsys);
3709 hlist_add_head(&cg->hlist, new_bucket);
3712 write_unlock(&css_set_lock);
3714 mutex_init(&ss->hierarchy_mutex);
3715 lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
3716 ss->active = 1;
3718 /* success! */
3719 mutex_unlock(&cgroup_mutex);
3720 return 0;
3722 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
3725 * cgroup_unload_subsys: unload a modular subsystem
3726 * @ss: the subsystem to unload
3728 * This function should be called in a modular subsystem's exitcall. When this
3729 * function is invoked, the refcount on the subsystem's module will be 0, so
3730 * the subsystem will not be attached to any hierarchy.
3732 void cgroup_unload_subsys(struct cgroup_subsys *ss)
3734 struct cg_cgroup_link *link;
3735 struct hlist_head *hhead;
3737 BUG_ON(ss->module == NULL);
3740 * we shouldn't be called if the subsystem is in use, and the use of
3741 * try_module_get in parse_cgroupfs_options should ensure that it
3742 * doesn't start being used while we're killing it off.
3744 BUG_ON(ss->root != &rootnode);
3746 mutex_lock(&cgroup_mutex);
3747 /* deassign the subsys_id */
3748 BUG_ON(ss->subsys_id < CGROUP_BUILTIN_SUBSYS_COUNT);
3749 subsys[ss->subsys_id] = NULL;
3751 /* remove subsystem from rootnode's list of subsystems */
3752 list_del(&ss->sibling);
3755 * disentangle the css from all css_sets attached to the dummytop. as
3756 * in loading, we need to pay our respects to the hashtable gods.
3758 write_lock(&css_set_lock);
3759 list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
3760 struct css_set *cg = link->cg;
3762 hlist_del(&cg->hlist);
3763 BUG_ON(!cg->subsys[ss->subsys_id]);
3764 cg->subsys[ss->subsys_id] = NULL;
3765 hhead = css_set_hash(cg->subsys);
3766 hlist_add_head(&cg->hlist, hhead);
3768 write_unlock(&css_set_lock);
3771 * remove subsystem's css from the dummytop and free it - need to free
3772 * before marking as null because ss->destroy needs the cgrp->subsys
3773 * pointer to find their state. note that this also takes care of
3774 * freeing the css_id.
3776 ss->destroy(ss, dummytop);
3777 dummytop->subsys[ss->subsys_id] = NULL;
3779 mutex_unlock(&cgroup_mutex);
3781 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
3784 * cgroup_init_early - cgroup initialization at system boot
3786 * Initialize cgroups at system boot, and initialize any
3787 * subsystems that request early init.
3789 int __init cgroup_init_early(void)
3791 int i;
3792 atomic_set(&init_css_set.refcount, 1);
3793 INIT_LIST_HEAD(&init_css_set.cg_links);
3794 INIT_LIST_HEAD(&init_css_set.tasks);
3795 INIT_HLIST_NODE(&init_css_set.hlist);
3796 css_set_count = 1;
3797 init_cgroup_root(&rootnode);
3798 root_count = 1;
3799 init_task.cgroups = &init_css_set;
3801 init_css_set_link.cg = &init_css_set;
3802 init_css_set_link.cgrp = dummytop;
3803 list_add(&init_css_set_link.cgrp_link_list,
3804 &rootnode.top_cgroup.css_sets);
3805 list_add(&init_css_set_link.cg_link_list,
3806 &init_css_set.cg_links);
3808 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
3809 INIT_HLIST_HEAD(&css_set_table[i]);
3811 /* at bootup time, we don't worry about modular subsystems */
3812 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3813 struct cgroup_subsys *ss = subsys[i];
3815 BUG_ON(!ss->name);
3816 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
3817 BUG_ON(!ss->create);
3818 BUG_ON(!ss->destroy);
3819 if (ss->subsys_id != i) {
3820 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
3821 ss->name, ss->subsys_id);
3822 BUG();
3825 if (ss->early_init)
3826 cgroup_init_subsys(ss);
3828 return 0;
3832 * cgroup_init - cgroup initialization
3834 * Register cgroup filesystem and /proc file, and initialize
3835 * any subsystems that didn't request early init.
3837 int __init cgroup_init(void)
3839 int err;
3840 int i;
3841 struct hlist_head *hhead;
3843 err = bdi_init(&cgroup_backing_dev_info);
3844 if (err)
3845 return err;
3847 /* at bootup time, we don't worry about modular subsystems */
3848 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3849 struct cgroup_subsys *ss = subsys[i];
3850 if (!ss->early_init)
3851 cgroup_init_subsys(ss);
3852 if (ss->use_id)
3853 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
3856 /* Add init_css_set to the hash table */
3857 hhead = css_set_hash(init_css_set.subsys);
3858 hlist_add_head(&init_css_set.hlist, hhead);
3859 BUG_ON(!init_root_id(&rootnode));
3860 err = register_filesystem(&cgroup_fs_type);
3861 if (err < 0)
3862 goto out;
3864 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
3866 out:
3867 if (err)
3868 bdi_destroy(&cgroup_backing_dev_info);
3870 return err;
3874 * proc_cgroup_show()
3875 * - Print task's cgroup paths into seq_file, one line for each hierarchy
3876 * - Used for /proc/<pid>/cgroup.
3877 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
3878 * doesn't really matter if tsk->cgroup changes after we read it,
3879 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
3880 * anyway. No need to check that tsk->cgroup != NULL, thanks to
3881 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
3882 * cgroup to top_cgroup.
3885 /* TODO: Use a proper seq_file iterator */
3886 static int proc_cgroup_show(struct seq_file *m, void *v)
3888 struct pid *pid;
3889 struct task_struct *tsk;
3890 char *buf;
3891 int retval;
3892 struct cgroupfs_root *root;
3894 retval = -ENOMEM;
3895 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3896 if (!buf)
3897 goto out;
3899 retval = -ESRCH;
3900 pid = m->private;
3901 tsk = get_pid_task(pid, PIDTYPE_PID);
3902 if (!tsk)
3903 goto out_free;
3905 retval = 0;
3907 mutex_lock(&cgroup_mutex);
3909 for_each_active_root(root) {
3910 struct cgroup_subsys *ss;
3911 struct cgroup *cgrp;
3912 int count = 0;
3914 seq_printf(m, "%d:", root->hierarchy_id);
3915 for_each_subsys(root, ss)
3916 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
3917 if (strlen(root->name))
3918 seq_printf(m, "%sname=%s", count ? "," : "",
3919 root->name);
3920 seq_putc(m, ':');
3921 cgrp = task_cgroup_from_root(tsk, root);
3922 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
3923 if (retval < 0)
3924 goto out_unlock;
3925 seq_puts(m, buf);
3926 seq_putc(m, '\n');
3929 out_unlock:
3930 mutex_unlock(&cgroup_mutex);
3931 put_task_struct(tsk);
3932 out_free:
3933 kfree(buf);
3934 out:
3935 return retval;
3938 static int cgroup_open(struct inode *inode, struct file *file)
3940 struct pid *pid = PROC_I(inode)->pid;
3941 return single_open(file, proc_cgroup_show, pid);
3944 const struct file_operations proc_cgroup_operations = {
3945 .open = cgroup_open,
3946 .read = seq_read,
3947 .llseek = seq_lseek,
3948 .release = single_release,
3951 /* Display information about each subsystem and each hierarchy */
3952 static int proc_cgroupstats_show(struct seq_file *m, void *v)
3954 int i;
3956 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
3958 * ideally we don't want subsystems moving around while we do this.
3959 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
3960 * subsys/hierarchy state.
3962 mutex_lock(&cgroup_mutex);
3963 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3964 struct cgroup_subsys *ss = subsys[i];
3965 if (ss == NULL)
3966 continue;
3967 seq_printf(m, "%s\t%d\t%d\t%d\n",
3968 ss->name, ss->root->hierarchy_id,
3969 ss->root->number_of_cgroups, !ss->disabled);
3971 mutex_unlock(&cgroup_mutex);
3972 return 0;
3975 static int cgroupstats_open(struct inode *inode, struct file *file)
3977 return single_open(file, proc_cgroupstats_show, NULL);
3980 static const struct file_operations proc_cgroupstats_operations = {
3981 .open = cgroupstats_open,
3982 .read = seq_read,
3983 .llseek = seq_lseek,
3984 .release = single_release,
3988 * cgroup_fork - attach newly forked task to its parents cgroup.
3989 * @child: pointer to task_struct of forking parent process.
3991 * Description: A task inherits its parent's cgroup at fork().
3993 * A pointer to the shared css_set was automatically copied in
3994 * fork.c by dup_task_struct(). However, we ignore that copy, since
3995 * it was not made under the protection of RCU or cgroup_mutex, so
3996 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
3997 * have already changed current->cgroups, allowing the previously
3998 * referenced cgroup group to be removed and freed.
4000 * At the point that cgroup_fork() is called, 'current' is the parent
4001 * task, and the passed argument 'child' points to the child task.
4003 void cgroup_fork(struct task_struct *child)
4005 task_lock(current);
4006 child->cgroups = current->cgroups;
4007 get_css_set(child->cgroups);
4008 task_unlock(current);
4009 INIT_LIST_HEAD(&child->cg_list);
4013 * cgroup_fork_callbacks - run fork callbacks
4014 * @child: the new task
4016 * Called on a new task very soon before adding it to the
4017 * tasklist. No need to take any locks since no-one can
4018 * be operating on this task.
4020 void cgroup_fork_callbacks(struct task_struct *child)
4022 if (need_forkexit_callback) {
4023 int i;
4025 * forkexit callbacks are only supported for builtin
4026 * subsystems, and the builtin section of the subsys array is
4027 * immutable, so we don't need to lock the subsys array here.
4029 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4030 struct cgroup_subsys *ss = subsys[i];
4031 if (ss->fork)
4032 ss->fork(ss, child);
4038 * cgroup_post_fork - called on a new task after adding it to the task list
4039 * @child: the task in question
4041 * Adds the task to the list running through its css_set if necessary.
4042 * Has to be after the task is visible on the task list in case we race
4043 * with the first call to cgroup_iter_start() - to guarantee that the
4044 * new task ends up on its list.
4046 void cgroup_post_fork(struct task_struct *child)
4048 if (use_task_css_set_links) {
4049 write_lock(&css_set_lock);
4050 task_lock(child);
4051 if (list_empty(&child->cg_list))
4052 list_add(&child->cg_list, &child->cgroups->tasks);
4053 task_unlock(child);
4054 write_unlock(&css_set_lock);
4058 * cgroup_exit - detach cgroup from exiting task
4059 * @tsk: pointer to task_struct of exiting process
4060 * @run_callback: run exit callbacks?
4062 * Description: Detach cgroup from @tsk and release it.
4064 * Note that cgroups marked notify_on_release force every task in
4065 * them to take the global cgroup_mutex mutex when exiting.
4066 * This could impact scaling on very large systems. Be reluctant to
4067 * use notify_on_release cgroups where very high task exit scaling
4068 * is required on large systems.
4070 * the_top_cgroup_hack:
4072 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4074 * We call cgroup_exit() while the task is still competent to
4075 * handle notify_on_release(), then leave the task attached to the
4076 * root cgroup in each hierarchy for the remainder of its exit.
4078 * To do this properly, we would increment the reference count on
4079 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4080 * code we would add a second cgroup function call, to drop that
4081 * reference. This would just create an unnecessary hot spot on
4082 * the top_cgroup reference count, to no avail.
4084 * Normally, holding a reference to a cgroup without bumping its
4085 * count is unsafe. The cgroup could go away, or someone could
4086 * attach us to a different cgroup, decrementing the count on
4087 * the first cgroup that we never incremented. But in this case,
4088 * top_cgroup isn't going away, and either task has PF_EXITING set,
4089 * which wards off any cgroup_attach_task() attempts, or task is a failed
4090 * fork, never visible to cgroup_attach_task.
4092 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4094 int i;
4095 struct css_set *cg;
4097 if (run_callbacks && need_forkexit_callback) {
4099 * modular subsystems can't use callbacks, so no need to lock
4100 * the subsys array
4102 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4103 struct cgroup_subsys *ss = subsys[i];
4104 if (ss->exit)
4105 ss->exit(ss, tsk);
4110 * Unlink from the css_set task list if necessary.
4111 * Optimistically check cg_list before taking
4112 * css_set_lock
4114 if (!list_empty(&tsk->cg_list)) {
4115 write_lock(&css_set_lock);
4116 if (!list_empty(&tsk->cg_list))
4117 list_del(&tsk->cg_list);
4118 write_unlock(&css_set_lock);
4121 /* Reassign the task to the init_css_set. */
4122 task_lock(tsk);
4123 cg = tsk->cgroups;
4124 tsk->cgroups = &init_css_set;
4125 task_unlock(tsk);
4126 if (cg)
4127 put_css_set_taskexit(cg);
4131 * cgroup_clone - clone the cgroup the given subsystem is attached to
4132 * @tsk: the task to be moved
4133 * @subsys: the given subsystem
4134 * @nodename: the name for the new cgroup
4136 * Duplicate the current cgroup in the hierarchy that the given
4137 * subsystem is attached to, and move this task into the new
4138 * child.
4140 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
4141 char *nodename)
4143 struct dentry *dentry;
4144 int ret = 0;
4145 struct cgroup *parent, *child;
4146 struct inode *inode;
4147 struct css_set *cg;
4148 struct cgroupfs_root *root;
4149 struct cgroup_subsys *ss;
4151 /* We shouldn't be called by an unregistered subsystem */
4152 BUG_ON(!subsys->active);
4154 /* First figure out what hierarchy and cgroup we're dealing
4155 * with, and pin them so we can drop cgroup_mutex */
4156 mutex_lock(&cgroup_mutex);
4157 again:
4158 root = subsys->root;
4159 if (root == &rootnode) {
4160 mutex_unlock(&cgroup_mutex);
4161 return 0;
4164 /* Pin the hierarchy */
4165 if (!atomic_inc_not_zero(&root->sb->s_active)) {
4166 /* We race with the final deactivate_super() */
4167 mutex_unlock(&cgroup_mutex);
4168 return 0;
4171 /* Keep the cgroup alive */
4172 task_lock(tsk);
4173 parent = task_cgroup(tsk, subsys->subsys_id);
4174 cg = tsk->cgroups;
4175 get_css_set(cg);
4176 task_unlock(tsk);
4178 mutex_unlock(&cgroup_mutex);
4180 /* Now do the VFS work to create a cgroup */
4181 inode = parent->dentry->d_inode;
4183 /* Hold the parent directory mutex across this operation to
4184 * stop anyone else deleting the new cgroup */
4185 mutex_lock(&inode->i_mutex);
4186 dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
4187 if (IS_ERR(dentry)) {
4188 printk(KERN_INFO
4189 "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
4190 PTR_ERR(dentry));
4191 ret = PTR_ERR(dentry);
4192 goto out_release;
4195 /* Create the cgroup directory, which also creates the cgroup */
4196 ret = vfs_mkdir(inode, dentry, 0755);
4197 child = __d_cgrp(dentry);
4198 dput(dentry);
4199 if (ret) {
4200 printk(KERN_INFO
4201 "Failed to create cgroup %s: %d\n", nodename,
4202 ret);
4203 goto out_release;
4206 /* The cgroup now exists. Retake cgroup_mutex and check
4207 * that we're still in the same state that we thought we
4208 * were. */
4209 mutex_lock(&cgroup_mutex);
4210 if ((root != subsys->root) ||
4211 (parent != task_cgroup(tsk, subsys->subsys_id))) {
4212 /* Aargh, we raced ... */
4213 mutex_unlock(&inode->i_mutex);
4214 put_css_set(cg);
4216 deactivate_super(root->sb);
4217 /* The cgroup is still accessible in the VFS, but
4218 * we're not going to try to rmdir() it at this
4219 * point. */
4220 printk(KERN_INFO
4221 "Race in cgroup_clone() - leaking cgroup %s\n",
4222 nodename);
4223 goto again;
4226 /* do any required auto-setup */
4227 for_each_subsys(root, ss) {
4228 if (ss->post_clone)
4229 ss->post_clone(ss, child);
4232 /* All seems fine. Finish by moving the task into the new cgroup */
4233 ret = cgroup_attach_task(child, tsk);
4234 mutex_unlock(&cgroup_mutex);
4236 out_release:
4237 mutex_unlock(&inode->i_mutex);
4239 mutex_lock(&cgroup_mutex);
4240 put_css_set(cg);
4241 mutex_unlock(&cgroup_mutex);
4242 deactivate_super(root->sb);
4243 return ret;
4247 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
4248 * @cgrp: the cgroup in question
4249 * @task: the task in question
4251 * See if @cgrp is a descendant of @task's cgroup in the appropriate
4252 * hierarchy.
4254 * If we are sending in dummytop, then presumably we are creating
4255 * the top cgroup in the subsystem.
4257 * Called only by the ns (nsproxy) cgroup.
4259 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
4261 int ret;
4262 struct cgroup *target;
4264 if (cgrp == dummytop)
4265 return 1;
4267 target = task_cgroup_from_root(task, cgrp->root);
4268 while (cgrp != target && cgrp!= cgrp->top_cgroup)
4269 cgrp = cgrp->parent;
4270 ret = (cgrp == target);
4271 return ret;
4274 static void check_for_release(struct cgroup *cgrp)
4276 /* All of these checks rely on RCU to keep the cgroup
4277 * structure alive */
4278 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
4279 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
4280 /* Control Group is currently removeable. If it's not
4281 * already queued for a userspace notification, queue
4282 * it now */
4283 int need_schedule_work = 0;
4284 spin_lock(&release_list_lock);
4285 if (!cgroup_is_removed(cgrp) &&
4286 list_empty(&cgrp->release_list)) {
4287 list_add(&cgrp->release_list, &release_list);
4288 need_schedule_work = 1;
4290 spin_unlock(&release_list_lock);
4291 if (need_schedule_work)
4292 schedule_work(&release_agent_work);
4296 /* Caller must verify that the css is not for root cgroup */
4297 void __css_put(struct cgroup_subsys_state *css, int count)
4299 struct cgroup *cgrp = css->cgroup;
4300 int val;
4301 rcu_read_lock();
4302 val = atomic_sub_return(count, &css->refcnt);
4303 if (val == 1) {
4304 if (notify_on_release(cgrp)) {
4305 set_bit(CGRP_RELEASABLE, &cgrp->flags);
4306 check_for_release(cgrp);
4308 cgroup_wakeup_rmdir_waiter(cgrp);
4310 rcu_read_unlock();
4311 WARN_ON_ONCE(val < 1);
4313 EXPORT_SYMBOL_GPL(__css_put);
4316 * Notify userspace when a cgroup is released, by running the
4317 * configured release agent with the name of the cgroup (path
4318 * relative to the root of cgroup file system) as the argument.
4320 * Most likely, this user command will try to rmdir this cgroup.
4322 * This races with the possibility that some other task will be
4323 * attached to this cgroup before it is removed, or that some other
4324 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4325 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4326 * unused, and this cgroup will be reprieved from its death sentence,
4327 * to continue to serve a useful existence. Next time it's released,
4328 * we will get notified again, if it still has 'notify_on_release' set.
4330 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4331 * means only wait until the task is successfully execve()'d. The
4332 * separate release agent task is forked by call_usermodehelper(),
4333 * then control in this thread returns here, without waiting for the
4334 * release agent task. We don't bother to wait because the caller of
4335 * this routine has no use for the exit status of the release agent
4336 * task, so no sense holding our caller up for that.
4338 static void cgroup_release_agent(struct work_struct *work)
4340 BUG_ON(work != &release_agent_work);
4341 mutex_lock(&cgroup_mutex);
4342 spin_lock(&release_list_lock);
4343 while (!list_empty(&release_list)) {
4344 char *argv[3], *envp[3];
4345 int i;
4346 char *pathbuf = NULL, *agentbuf = NULL;
4347 struct cgroup *cgrp = list_entry(release_list.next,
4348 struct cgroup,
4349 release_list);
4350 list_del_init(&cgrp->release_list);
4351 spin_unlock(&release_list_lock);
4352 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4353 if (!pathbuf)
4354 goto continue_free;
4355 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
4356 goto continue_free;
4357 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4358 if (!agentbuf)
4359 goto continue_free;
4361 i = 0;
4362 argv[i++] = agentbuf;
4363 argv[i++] = pathbuf;
4364 argv[i] = NULL;
4366 i = 0;
4367 /* minimal command environment */
4368 envp[i++] = "HOME=/";
4369 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4370 envp[i] = NULL;
4372 /* Drop the lock while we invoke the usermode helper,
4373 * since the exec could involve hitting disk and hence
4374 * be a slow process */
4375 mutex_unlock(&cgroup_mutex);
4376 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4377 mutex_lock(&cgroup_mutex);
4378 continue_free:
4379 kfree(pathbuf);
4380 kfree(agentbuf);
4381 spin_lock(&release_list_lock);
4383 spin_unlock(&release_list_lock);
4384 mutex_unlock(&cgroup_mutex);
4387 static int __init cgroup_disable(char *str)
4389 int i;
4390 char *token;
4392 while ((token = strsep(&str, ",")) != NULL) {
4393 if (!*token)
4394 continue;
4396 * cgroup_disable, being at boot time, can't know about module
4397 * subsystems, so we don't worry about them.
4399 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4400 struct cgroup_subsys *ss = subsys[i];
4402 if (!strcmp(token, ss->name)) {
4403 ss->disabled = 1;
4404 printk(KERN_INFO "Disabling %s control group"
4405 " subsystem\n", ss->name);
4406 break;
4410 return 1;
4412 __setup("cgroup_disable=", cgroup_disable);
4415 * Functons for CSS ID.
4419 *To get ID other than 0, this should be called when !cgroup_is_removed().
4421 unsigned short css_id(struct cgroup_subsys_state *css)
4423 struct css_id *cssid = rcu_dereference(css->id);
4425 if (cssid)
4426 return cssid->id;
4427 return 0;
4429 EXPORT_SYMBOL_GPL(css_id);
4431 unsigned short css_depth(struct cgroup_subsys_state *css)
4433 struct css_id *cssid = rcu_dereference(css->id);
4435 if (cssid)
4436 return cssid->depth;
4437 return 0;
4439 EXPORT_SYMBOL_GPL(css_depth);
4441 bool css_is_ancestor(struct cgroup_subsys_state *child,
4442 const struct cgroup_subsys_state *root)
4444 struct css_id *child_id = rcu_dereference(child->id);
4445 struct css_id *root_id = rcu_dereference(root->id);
4447 if (!child_id || !root_id || (child_id->depth < root_id->depth))
4448 return false;
4449 return child_id->stack[root_id->depth] == root_id->id;
4452 static void __free_css_id_cb(struct rcu_head *head)
4454 struct css_id *id;
4456 id = container_of(head, struct css_id, rcu_head);
4457 kfree(id);
4460 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
4462 struct css_id *id = css->id;
4463 /* When this is called before css_id initialization, id can be NULL */
4464 if (!id)
4465 return;
4467 BUG_ON(!ss->use_id);
4469 rcu_assign_pointer(id->css, NULL);
4470 rcu_assign_pointer(css->id, NULL);
4471 spin_lock(&ss->id_lock);
4472 idr_remove(&ss->idr, id->id);
4473 spin_unlock(&ss->id_lock);
4474 call_rcu(&id->rcu_head, __free_css_id_cb);
4476 EXPORT_SYMBOL_GPL(free_css_id);
4479 * This is called by init or create(). Then, calls to this function are
4480 * always serialized (By cgroup_mutex() at create()).
4483 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
4485 struct css_id *newid;
4486 int myid, error, size;
4488 BUG_ON(!ss->use_id);
4490 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
4491 newid = kzalloc(size, GFP_KERNEL);
4492 if (!newid)
4493 return ERR_PTR(-ENOMEM);
4494 /* get id */
4495 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
4496 error = -ENOMEM;
4497 goto err_out;
4499 spin_lock(&ss->id_lock);
4500 /* Don't use 0. allocates an ID of 1-65535 */
4501 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
4502 spin_unlock(&ss->id_lock);
4504 /* Returns error when there are no free spaces for new ID.*/
4505 if (error) {
4506 error = -ENOSPC;
4507 goto err_out;
4509 if (myid > CSS_ID_MAX)
4510 goto remove_idr;
4512 newid->id = myid;
4513 newid->depth = depth;
4514 return newid;
4515 remove_idr:
4516 error = -ENOSPC;
4517 spin_lock(&ss->id_lock);
4518 idr_remove(&ss->idr, myid);
4519 spin_unlock(&ss->id_lock);
4520 err_out:
4521 kfree(newid);
4522 return ERR_PTR(error);
4526 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
4527 struct cgroup_subsys_state *rootcss)
4529 struct css_id *newid;
4531 spin_lock_init(&ss->id_lock);
4532 idr_init(&ss->idr);
4534 newid = get_new_cssid(ss, 0);
4535 if (IS_ERR(newid))
4536 return PTR_ERR(newid);
4538 newid->stack[0] = newid->id;
4539 newid->css = rootcss;
4540 rootcss->id = newid;
4541 return 0;
4544 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
4545 struct cgroup *child)
4547 int subsys_id, i, depth = 0;
4548 struct cgroup_subsys_state *parent_css, *child_css;
4549 struct css_id *child_id, *parent_id = NULL;
4551 subsys_id = ss->subsys_id;
4552 parent_css = parent->subsys[subsys_id];
4553 child_css = child->subsys[subsys_id];
4554 depth = css_depth(parent_css) + 1;
4555 parent_id = parent_css->id;
4557 child_id = get_new_cssid(ss, depth);
4558 if (IS_ERR(child_id))
4559 return PTR_ERR(child_id);
4561 for (i = 0; i < depth; i++)
4562 child_id->stack[i] = parent_id->stack[i];
4563 child_id->stack[depth] = child_id->id;
4565 * child_id->css pointer will be set after this cgroup is available
4566 * see cgroup_populate_dir()
4568 rcu_assign_pointer(child_css->id, child_id);
4570 return 0;
4574 * css_lookup - lookup css by id
4575 * @ss: cgroup subsys to be looked into.
4576 * @id: the id
4578 * Returns pointer to cgroup_subsys_state if there is valid one with id.
4579 * NULL if not. Should be called under rcu_read_lock()
4581 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
4583 struct css_id *cssid = NULL;
4585 BUG_ON(!ss->use_id);
4586 cssid = idr_find(&ss->idr, id);
4588 if (unlikely(!cssid))
4589 return NULL;
4591 return rcu_dereference(cssid->css);
4593 EXPORT_SYMBOL_GPL(css_lookup);
4596 * css_get_next - lookup next cgroup under specified hierarchy.
4597 * @ss: pointer to subsystem
4598 * @id: current position of iteration.
4599 * @root: pointer to css. search tree under this.
4600 * @foundid: position of found object.
4602 * Search next css under the specified hierarchy of rootid. Calling under
4603 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
4605 struct cgroup_subsys_state *
4606 css_get_next(struct cgroup_subsys *ss, int id,
4607 struct cgroup_subsys_state *root, int *foundid)
4609 struct cgroup_subsys_state *ret = NULL;
4610 struct css_id *tmp;
4611 int tmpid;
4612 int rootid = css_id(root);
4613 int depth = css_depth(root);
4615 if (!rootid)
4616 return NULL;
4618 BUG_ON(!ss->use_id);
4619 /* fill start point for scan */
4620 tmpid = id;
4621 while (1) {
4623 * scan next entry from bitmap(tree), tmpid is updated after
4624 * idr_get_next().
4626 spin_lock(&ss->id_lock);
4627 tmp = idr_get_next(&ss->idr, &tmpid);
4628 spin_unlock(&ss->id_lock);
4630 if (!tmp)
4631 break;
4632 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
4633 ret = rcu_dereference(tmp->css);
4634 if (ret) {
4635 *foundid = tmpid;
4636 break;
4639 /* continue to scan from next id */
4640 tmpid = tmpid + 1;
4642 return ret;
4645 #ifdef CONFIG_CGROUP_DEBUG
4646 static struct cgroup_subsys_state *debug_create(struct cgroup_subsys *ss,
4647 struct cgroup *cont)
4649 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4651 if (!css)
4652 return ERR_PTR(-ENOMEM);
4654 return css;
4657 static void debug_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
4659 kfree(cont->subsys[debug_subsys_id]);
4662 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
4664 return atomic_read(&cont->count);
4667 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
4669 return cgroup_task_count(cont);
4672 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
4674 return (u64)(unsigned long)current->cgroups;
4677 static u64 current_css_set_refcount_read(struct cgroup *cont,
4678 struct cftype *cft)
4680 u64 count;
4682 rcu_read_lock();
4683 count = atomic_read(&current->cgroups->refcount);
4684 rcu_read_unlock();
4685 return count;
4688 static int current_css_set_cg_links_read(struct cgroup *cont,
4689 struct cftype *cft,
4690 struct seq_file *seq)
4692 struct cg_cgroup_link *link;
4693 struct css_set *cg;
4695 read_lock(&css_set_lock);
4696 rcu_read_lock();
4697 cg = rcu_dereference(current->cgroups);
4698 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
4699 struct cgroup *c = link->cgrp;
4700 const char *name;
4702 if (c->dentry)
4703 name = c->dentry->d_name.name;
4704 else
4705 name = "?";
4706 seq_printf(seq, "Root %d group %s\n",
4707 c->root->hierarchy_id, name);
4709 rcu_read_unlock();
4710 read_unlock(&css_set_lock);
4711 return 0;
4714 #define MAX_TASKS_SHOWN_PER_CSS 25
4715 static int cgroup_css_links_read(struct cgroup *cont,
4716 struct cftype *cft,
4717 struct seq_file *seq)
4719 struct cg_cgroup_link *link;
4721 read_lock(&css_set_lock);
4722 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
4723 struct css_set *cg = link->cg;
4724 struct task_struct *task;
4725 int count = 0;
4726 seq_printf(seq, "css_set %p\n", cg);
4727 list_for_each_entry(task, &cg->tasks, cg_list) {
4728 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
4729 seq_puts(seq, " ...\n");
4730 break;
4731 } else {
4732 seq_printf(seq, " task %d\n",
4733 task_pid_vnr(task));
4737 read_unlock(&css_set_lock);
4738 return 0;
4741 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
4743 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
4746 static struct cftype debug_files[] = {
4748 .name = "cgroup_refcount",
4749 .read_u64 = cgroup_refcount_read,
4752 .name = "taskcount",
4753 .read_u64 = debug_taskcount_read,
4757 .name = "current_css_set",
4758 .read_u64 = current_css_set_read,
4762 .name = "current_css_set_refcount",
4763 .read_u64 = current_css_set_refcount_read,
4767 .name = "current_css_set_cg_links",
4768 .read_seq_string = current_css_set_cg_links_read,
4772 .name = "cgroup_css_links",
4773 .read_seq_string = cgroup_css_links_read,
4777 .name = "releasable",
4778 .read_u64 = releasable_read,
4782 static int debug_populate(struct cgroup_subsys *ss, struct cgroup *cont)
4784 return cgroup_add_files(cont, ss, debug_files,
4785 ARRAY_SIZE(debug_files));
4788 struct cgroup_subsys debug_subsys = {
4789 .name = "debug",
4790 .create = debug_create,
4791 .destroy = debug_destroy,
4792 .populate = debug_populate,
4793 .subsys_id = debug_subsys_id,
4795 #endif /* CONFIG_CGROUP_DEBUG */