[SCSI] hpsa: allow modifying device queue depth.
[linux-2.6/next.git] / kernel / cgroup.c
blob4fd90e12977236f54a4dd29168bc2db04bb1cdbc
1 /*
2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Copyright notices from the original cpuset code:
8 * --------------------------------------------------
9 * Copyright (C) 2003 BULL SA.
10 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
12 * Portions derived from Patrick Mochel's sysfs code.
13 * sysfs is Copyright (c) 2001-3 Patrick Mochel
15 * 2003-10-10 Written by Simon Derr.
16 * 2003-10-22 Updates by Stephen Hemminger.
17 * 2004 May-July Rework by Paul Jackson.
18 * ---------------------------------------------------
20 * This file is subject to the terms and conditions of the GNU General Public
21 * License. See the file COPYING in the main directory of the Linux
22 * distribution for more details.
25 #include <linux/cgroup.h>
26 #include <linux/module.h>
27 #include <linux/ctype.h>
28 #include <linux/errno.h>
29 #include <linux/fs.h>
30 #include <linux/kernel.h>
31 #include <linux/list.h>
32 #include <linux/mm.h>
33 #include <linux/mutex.h>
34 #include <linux/mount.h>
35 #include <linux/pagemap.h>
36 #include <linux/proc_fs.h>
37 #include <linux/rcupdate.h>
38 #include <linux/sched.h>
39 #include <linux/backing-dev.h>
40 #include <linux/seq_file.h>
41 #include <linux/slab.h>
42 #include <linux/magic.h>
43 #include <linux/spinlock.h>
44 #include <linux/string.h>
45 #include <linux/sort.h>
46 #include <linux/kmod.h>
47 #include <linux/delayacct.h>
48 #include <linux/cgroupstats.h>
49 #include <linux/hash.h>
50 #include <linux/namei.h>
51 #include <linux/smp_lock.h>
52 #include <linux/pid_namespace.h>
53 #include <linux/idr.h>
54 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
56 #include <asm/atomic.h>
58 static DEFINE_MUTEX(cgroup_mutex);
60 /* Generate an array of cgroup subsystem pointers */
61 #define SUBSYS(_x) &_x ## _subsys,
63 static struct cgroup_subsys *subsys[] = {
64 #include <linux/cgroup_subsys.h>
67 #define MAX_CGROUP_ROOT_NAMELEN 64
70 * A cgroupfs_root represents the root of a cgroup hierarchy,
71 * and may be associated with a superblock to form an active
72 * hierarchy
74 struct cgroupfs_root {
75 struct super_block *sb;
78 * The bitmask of subsystems intended to be attached to this
79 * hierarchy
81 unsigned long subsys_bits;
83 /* Unique id for this hierarchy. */
84 int hierarchy_id;
86 /* The bitmask of subsystems currently attached to this hierarchy */
87 unsigned long actual_subsys_bits;
89 /* A list running through the attached subsystems */
90 struct list_head subsys_list;
92 /* The root cgroup for this hierarchy */
93 struct cgroup top_cgroup;
95 /* Tracks how many cgroups are currently defined in hierarchy.*/
96 int number_of_cgroups;
98 /* A list running through the active hierarchies */
99 struct list_head root_list;
101 /* Hierarchy-specific flags */
102 unsigned long flags;
104 /* The path to use for release notifications. */
105 char release_agent_path[PATH_MAX];
107 /* The name for this hierarchy - may be empty */
108 char name[MAX_CGROUP_ROOT_NAMELEN];
112 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
113 * subsystems that are otherwise unattached - it never has more than a
114 * single cgroup, and all tasks are part of that cgroup.
116 static struct cgroupfs_root rootnode;
119 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
120 * cgroup_subsys->use_id != 0.
122 #define CSS_ID_MAX (65535)
123 struct css_id {
125 * The css to which this ID points. This pointer is set to valid value
126 * after cgroup is populated. If cgroup is removed, this will be NULL.
127 * This pointer is expected to be RCU-safe because destroy()
128 * is called after synchronize_rcu(). But for safe use, css_is_removed()
129 * css_tryget() should be used for avoiding race.
131 struct cgroup_subsys_state *css;
133 * ID of this css.
135 unsigned short id;
137 * Depth in hierarchy which this ID belongs to.
139 unsigned short depth;
141 * ID is freed by RCU. (and lookup routine is RCU safe.)
143 struct rcu_head rcu_head;
145 * Hierarchy of CSS ID belongs to.
147 unsigned short stack[0]; /* Array of Length (depth+1) */
151 /* The list of hierarchy roots */
153 static LIST_HEAD(roots);
154 static int root_count;
156 static DEFINE_IDA(hierarchy_ida);
157 static int next_hierarchy_id;
158 static DEFINE_SPINLOCK(hierarchy_id_lock);
160 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
161 #define dummytop (&rootnode.top_cgroup)
163 /* This flag indicates whether tasks in the fork and exit paths should
164 * check for fork/exit handlers to call. This avoids us having to do
165 * extra work in the fork/exit path if none of the subsystems need to
166 * be called.
168 static int need_forkexit_callback __read_mostly;
170 #ifdef CONFIG_PROVE_LOCKING
171 int cgroup_lock_is_held(void)
173 return lockdep_is_held(&cgroup_mutex);
175 #else /* #ifdef CONFIG_PROVE_LOCKING */
176 int cgroup_lock_is_held(void)
178 return mutex_is_locked(&cgroup_mutex);
180 #endif /* #else #ifdef CONFIG_PROVE_LOCKING */
182 EXPORT_SYMBOL_GPL(cgroup_lock_is_held);
184 /* convenient tests for these bits */
185 inline int cgroup_is_removed(const struct cgroup *cgrp)
187 return test_bit(CGRP_REMOVED, &cgrp->flags);
190 /* bits in struct cgroupfs_root flags field */
191 enum {
192 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
195 static int cgroup_is_releasable(const struct cgroup *cgrp)
197 const int bits =
198 (1 << CGRP_RELEASABLE) |
199 (1 << CGRP_NOTIFY_ON_RELEASE);
200 return (cgrp->flags & bits) == bits;
203 static int notify_on_release(const struct cgroup *cgrp)
205 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
209 * for_each_subsys() allows you to iterate on each subsystem attached to
210 * an active hierarchy
212 #define for_each_subsys(_root, _ss) \
213 list_for_each_entry(_ss, &_root->subsys_list, sibling)
215 /* for_each_active_root() allows you to iterate across the active hierarchies */
216 #define for_each_active_root(_root) \
217 list_for_each_entry(_root, &roots, root_list)
219 /* the list of cgroups eligible for automatic release. Protected by
220 * release_list_lock */
221 static LIST_HEAD(release_list);
222 static DEFINE_SPINLOCK(release_list_lock);
223 static void cgroup_release_agent(struct work_struct *work);
224 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
225 static void check_for_release(struct cgroup *cgrp);
227 /* Link structure for associating css_set objects with cgroups */
228 struct cg_cgroup_link {
230 * List running through cg_cgroup_links associated with a
231 * cgroup, anchored on cgroup->css_sets
233 struct list_head cgrp_link_list;
234 struct cgroup *cgrp;
236 * List running through cg_cgroup_links pointing at a
237 * single css_set object, anchored on css_set->cg_links
239 struct list_head cg_link_list;
240 struct css_set *cg;
243 /* The default css_set - used by init and its children prior to any
244 * hierarchies being mounted. It contains a pointer to the root state
245 * for each subsystem. Also used to anchor the list of css_sets. Not
246 * reference-counted, to improve performance when child cgroups
247 * haven't been created.
250 static struct css_set init_css_set;
251 static struct cg_cgroup_link init_css_set_link;
253 static int cgroup_subsys_init_idr(struct cgroup_subsys *ss);
255 /* css_set_lock protects the list of css_set objects, and the
256 * chain of tasks off each css_set. Nests outside task->alloc_lock
257 * due to cgroup_iter_start() */
258 static DEFINE_RWLOCK(css_set_lock);
259 static int css_set_count;
262 * hash table for cgroup groups. This improves the performance to find
263 * an existing css_set. This hash doesn't (currently) take into
264 * account cgroups in empty hierarchies.
266 #define CSS_SET_HASH_BITS 7
267 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
268 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
270 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
272 int i;
273 int index;
274 unsigned long tmp = 0UL;
276 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
277 tmp += (unsigned long)css[i];
278 tmp = (tmp >> 16) ^ tmp;
280 index = hash_long(tmp, CSS_SET_HASH_BITS);
282 return &css_set_table[index];
285 static void free_css_set_rcu(struct rcu_head *obj)
287 struct css_set *cg = container_of(obj, struct css_set, rcu_head);
288 kfree(cg);
291 /* We don't maintain the lists running through each css_set to its
292 * task until after the first call to cgroup_iter_start(). This
293 * reduces the fork()/exit() overhead for people who have cgroups
294 * compiled into their kernel but not actually in use */
295 static int use_task_css_set_links __read_mostly;
297 static void __put_css_set(struct css_set *cg, int taskexit)
299 struct cg_cgroup_link *link;
300 struct cg_cgroup_link *saved_link;
302 * Ensure that the refcount doesn't hit zero while any readers
303 * can see it. Similar to atomic_dec_and_lock(), but for an
304 * rwlock
306 if (atomic_add_unless(&cg->refcount, -1, 1))
307 return;
308 write_lock(&css_set_lock);
309 if (!atomic_dec_and_test(&cg->refcount)) {
310 write_unlock(&css_set_lock);
311 return;
314 /* This css_set is dead. unlink it and release cgroup refcounts */
315 hlist_del(&cg->hlist);
316 css_set_count--;
318 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
319 cg_link_list) {
320 struct cgroup *cgrp = link->cgrp;
321 list_del(&link->cg_link_list);
322 list_del(&link->cgrp_link_list);
323 if (atomic_dec_and_test(&cgrp->count) &&
324 notify_on_release(cgrp)) {
325 if (taskexit)
326 set_bit(CGRP_RELEASABLE, &cgrp->flags);
327 check_for_release(cgrp);
330 kfree(link);
333 write_unlock(&css_set_lock);
334 call_rcu(&cg->rcu_head, free_css_set_rcu);
338 * refcounted get/put for css_set objects
340 static inline void get_css_set(struct css_set *cg)
342 atomic_inc(&cg->refcount);
345 static inline void put_css_set(struct css_set *cg)
347 __put_css_set(cg, 0);
350 static inline void put_css_set_taskexit(struct css_set *cg)
352 __put_css_set(cg, 1);
356 * compare_css_sets - helper function for find_existing_css_set().
357 * @cg: candidate css_set being tested
358 * @old_cg: existing css_set for a task
359 * @new_cgrp: cgroup that's being entered by the task
360 * @template: desired set of css pointers in css_set (pre-calculated)
362 * Returns true if "cg" matches "old_cg" except for the hierarchy
363 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
365 static bool compare_css_sets(struct css_set *cg,
366 struct css_set *old_cg,
367 struct cgroup *new_cgrp,
368 struct cgroup_subsys_state *template[])
370 struct list_head *l1, *l2;
372 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
373 /* Not all subsystems matched */
374 return false;
378 * Compare cgroup pointers in order to distinguish between
379 * different cgroups in heirarchies with no subsystems. We
380 * could get by with just this check alone (and skip the
381 * memcmp above) but on most setups the memcmp check will
382 * avoid the need for this more expensive check on almost all
383 * candidates.
386 l1 = &cg->cg_links;
387 l2 = &old_cg->cg_links;
388 while (1) {
389 struct cg_cgroup_link *cgl1, *cgl2;
390 struct cgroup *cg1, *cg2;
392 l1 = l1->next;
393 l2 = l2->next;
394 /* See if we reached the end - both lists are equal length. */
395 if (l1 == &cg->cg_links) {
396 BUG_ON(l2 != &old_cg->cg_links);
397 break;
398 } else {
399 BUG_ON(l2 == &old_cg->cg_links);
401 /* Locate the cgroups associated with these links. */
402 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
403 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
404 cg1 = cgl1->cgrp;
405 cg2 = cgl2->cgrp;
406 /* Hierarchies should be linked in the same order. */
407 BUG_ON(cg1->root != cg2->root);
410 * If this hierarchy is the hierarchy of the cgroup
411 * that's changing, then we need to check that this
412 * css_set points to the new cgroup; if it's any other
413 * hierarchy, then this css_set should point to the
414 * same cgroup as the old css_set.
416 if (cg1->root == new_cgrp->root) {
417 if (cg1 != new_cgrp)
418 return false;
419 } else {
420 if (cg1 != cg2)
421 return false;
424 return true;
428 * find_existing_css_set() is a helper for
429 * find_css_set(), and checks to see whether an existing
430 * css_set is suitable.
432 * oldcg: the cgroup group that we're using before the cgroup
433 * transition
435 * cgrp: the cgroup that we're moving into
437 * template: location in which to build the desired set of subsystem
438 * state objects for the new cgroup group
440 static struct css_set *find_existing_css_set(
441 struct css_set *oldcg,
442 struct cgroup *cgrp,
443 struct cgroup_subsys_state *template[])
445 int i;
446 struct cgroupfs_root *root = cgrp->root;
447 struct hlist_head *hhead;
448 struct hlist_node *node;
449 struct css_set *cg;
451 /* Built the set of subsystem state objects that we want to
452 * see in the new css_set */
453 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
454 if (root->subsys_bits & (1UL << i)) {
455 /* Subsystem is in this hierarchy. So we want
456 * the subsystem state from the new
457 * cgroup */
458 template[i] = cgrp->subsys[i];
459 } else {
460 /* Subsystem is not in this hierarchy, so we
461 * don't want to change the subsystem state */
462 template[i] = oldcg->subsys[i];
466 hhead = css_set_hash(template);
467 hlist_for_each_entry(cg, node, hhead, hlist) {
468 if (!compare_css_sets(cg, oldcg, cgrp, template))
469 continue;
471 /* This css_set matches what we need */
472 return cg;
475 /* No existing cgroup group matched */
476 return NULL;
479 static void free_cg_links(struct list_head *tmp)
481 struct cg_cgroup_link *link;
482 struct cg_cgroup_link *saved_link;
484 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
485 list_del(&link->cgrp_link_list);
486 kfree(link);
491 * allocate_cg_links() allocates "count" cg_cgroup_link structures
492 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
493 * success or a negative error
495 static int allocate_cg_links(int count, struct list_head *tmp)
497 struct cg_cgroup_link *link;
498 int i;
499 INIT_LIST_HEAD(tmp);
500 for (i = 0; i < count; i++) {
501 link = kmalloc(sizeof(*link), GFP_KERNEL);
502 if (!link) {
503 free_cg_links(tmp);
504 return -ENOMEM;
506 list_add(&link->cgrp_link_list, tmp);
508 return 0;
512 * link_css_set - a helper function to link a css_set to a cgroup
513 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
514 * @cg: the css_set to be linked
515 * @cgrp: the destination cgroup
517 static void link_css_set(struct list_head *tmp_cg_links,
518 struct css_set *cg, struct cgroup *cgrp)
520 struct cg_cgroup_link *link;
522 BUG_ON(list_empty(tmp_cg_links));
523 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
524 cgrp_link_list);
525 link->cg = cg;
526 link->cgrp = cgrp;
527 atomic_inc(&cgrp->count);
528 list_move(&link->cgrp_link_list, &cgrp->css_sets);
530 * Always add links to the tail of the list so that the list
531 * is sorted by order of hierarchy creation
533 list_add_tail(&link->cg_link_list, &cg->cg_links);
537 * find_css_set() takes an existing cgroup group and a
538 * cgroup object, and returns a css_set object that's
539 * equivalent to the old group, but with the given cgroup
540 * substituted into the appropriate hierarchy. Must be called with
541 * cgroup_mutex held
543 static struct css_set *find_css_set(
544 struct css_set *oldcg, struct cgroup *cgrp)
546 struct css_set *res;
547 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
549 struct list_head tmp_cg_links;
551 struct hlist_head *hhead;
552 struct cg_cgroup_link *link;
554 /* First see if we already have a cgroup group that matches
555 * the desired set */
556 read_lock(&css_set_lock);
557 res = find_existing_css_set(oldcg, cgrp, template);
558 if (res)
559 get_css_set(res);
560 read_unlock(&css_set_lock);
562 if (res)
563 return res;
565 res = kmalloc(sizeof(*res), GFP_KERNEL);
566 if (!res)
567 return NULL;
569 /* Allocate all the cg_cgroup_link objects that we'll need */
570 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
571 kfree(res);
572 return NULL;
575 atomic_set(&res->refcount, 1);
576 INIT_LIST_HEAD(&res->cg_links);
577 INIT_LIST_HEAD(&res->tasks);
578 INIT_HLIST_NODE(&res->hlist);
580 /* Copy the set of subsystem state objects generated in
581 * find_existing_css_set() */
582 memcpy(res->subsys, template, sizeof(res->subsys));
584 write_lock(&css_set_lock);
585 /* Add reference counts and links from the new css_set. */
586 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
587 struct cgroup *c = link->cgrp;
588 if (c->root == cgrp->root)
589 c = cgrp;
590 link_css_set(&tmp_cg_links, res, c);
593 BUG_ON(!list_empty(&tmp_cg_links));
595 css_set_count++;
597 /* Add this cgroup group to the hash table */
598 hhead = css_set_hash(res->subsys);
599 hlist_add_head(&res->hlist, hhead);
601 write_unlock(&css_set_lock);
603 return res;
607 * Return the cgroup for "task" from the given hierarchy. Must be
608 * called with cgroup_mutex held.
610 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
611 struct cgroupfs_root *root)
613 struct css_set *css;
614 struct cgroup *res = NULL;
616 BUG_ON(!mutex_is_locked(&cgroup_mutex));
617 read_lock(&css_set_lock);
619 * No need to lock the task - since we hold cgroup_mutex the
620 * task can't change groups, so the only thing that can happen
621 * is that it exits and its css is set back to init_css_set.
623 css = task->cgroups;
624 if (css == &init_css_set) {
625 res = &root->top_cgroup;
626 } else {
627 struct cg_cgroup_link *link;
628 list_for_each_entry(link, &css->cg_links, cg_link_list) {
629 struct cgroup *c = link->cgrp;
630 if (c->root == root) {
631 res = c;
632 break;
636 read_unlock(&css_set_lock);
637 BUG_ON(!res);
638 return res;
642 * There is one global cgroup mutex. We also require taking
643 * task_lock() when dereferencing a task's cgroup subsys pointers.
644 * See "The task_lock() exception", at the end of this comment.
646 * A task must hold cgroup_mutex to modify cgroups.
648 * Any task can increment and decrement the count field without lock.
649 * So in general, code holding cgroup_mutex can't rely on the count
650 * field not changing. However, if the count goes to zero, then only
651 * cgroup_attach_task() can increment it again. Because a count of zero
652 * means that no tasks are currently attached, therefore there is no
653 * way a task attached to that cgroup can fork (the other way to
654 * increment the count). So code holding cgroup_mutex can safely
655 * assume that if the count is zero, it will stay zero. Similarly, if
656 * a task holds cgroup_mutex on a cgroup with zero count, it
657 * knows that the cgroup won't be removed, as cgroup_rmdir()
658 * needs that mutex.
660 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
661 * (usually) take cgroup_mutex. These are the two most performance
662 * critical pieces of code here. The exception occurs on cgroup_exit(),
663 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
664 * is taken, and if the cgroup count is zero, a usermode call made
665 * to the release agent with the name of the cgroup (path relative to
666 * the root of cgroup file system) as the argument.
668 * A cgroup can only be deleted if both its 'count' of using tasks
669 * is zero, and its list of 'children' cgroups is empty. Since all
670 * tasks in the system use _some_ cgroup, and since there is always at
671 * least one task in the system (init, pid == 1), therefore, top_cgroup
672 * always has either children cgroups and/or using tasks. So we don't
673 * need a special hack to ensure that top_cgroup cannot be deleted.
675 * The task_lock() exception
677 * The need for this exception arises from the action of
678 * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
679 * another. It does so using cgroup_mutex, however there are
680 * several performance critical places that need to reference
681 * task->cgroup without the expense of grabbing a system global
682 * mutex. Therefore except as noted below, when dereferencing or, as
683 * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
684 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
685 * the task_struct routinely used for such matters.
687 * P.S. One more locking exception. RCU is used to guard the
688 * update of a tasks cgroup pointer by cgroup_attach_task()
692 * cgroup_lock - lock out any changes to cgroup structures
695 void cgroup_lock(void)
697 mutex_lock(&cgroup_mutex);
701 * cgroup_unlock - release lock on cgroup changes
703 * Undo the lock taken in a previous cgroup_lock() call.
705 void cgroup_unlock(void)
707 mutex_unlock(&cgroup_mutex);
711 * A couple of forward declarations required, due to cyclic reference loop:
712 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
713 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
714 * -> cgroup_mkdir.
717 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
718 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
719 static int cgroup_populate_dir(struct cgroup *cgrp);
720 static const struct inode_operations cgroup_dir_inode_operations;
721 static const struct file_operations proc_cgroupstats_operations;
723 static struct backing_dev_info cgroup_backing_dev_info = {
724 .name = "cgroup",
725 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
728 static int alloc_css_id(struct cgroup_subsys *ss,
729 struct cgroup *parent, struct cgroup *child);
731 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
733 struct inode *inode = new_inode(sb);
735 if (inode) {
736 inode->i_mode = mode;
737 inode->i_uid = current_fsuid();
738 inode->i_gid = current_fsgid();
739 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
740 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
742 return inode;
746 * Call subsys's pre_destroy handler.
747 * This is called before css refcnt check.
749 static int cgroup_call_pre_destroy(struct cgroup *cgrp)
751 struct cgroup_subsys *ss;
752 int ret = 0;
754 for_each_subsys(cgrp->root, ss)
755 if (ss->pre_destroy) {
756 ret = ss->pre_destroy(ss, cgrp);
757 if (ret)
758 break;
760 return ret;
763 static void free_cgroup_rcu(struct rcu_head *obj)
765 struct cgroup *cgrp = container_of(obj, struct cgroup, rcu_head);
767 kfree(cgrp);
770 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
772 /* is dentry a directory ? if so, kfree() associated cgroup */
773 if (S_ISDIR(inode->i_mode)) {
774 struct cgroup *cgrp = dentry->d_fsdata;
775 struct cgroup_subsys *ss;
776 BUG_ON(!(cgroup_is_removed(cgrp)));
777 /* It's possible for external users to be holding css
778 * reference counts on a cgroup; css_put() needs to
779 * be able to access the cgroup after decrementing
780 * the reference count in order to know if it needs to
781 * queue the cgroup to be handled by the release
782 * agent */
783 synchronize_rcu();
785 mutex_lock(&cgroup_mutex);
787 * Release the subsystem state objects.
789 for_each_subsys(cgrp->root, ss)
790 ss->destroy(ss, cgrp);
792 cgrp->root->number_of_cgroups--;
793 mutex_unlock(&cgroup_mutex);
796 * Drop the active superblock reference that we took when we
797 * created the cgroup
799 deactivate_super(cgrp->root->sb);
802 * if we're getting rid of the cgroup, refcount should ensure
803 * that there are no pidlists left.
805 BUG_ON(!list_empty(&cgrp->pidlists));
807 call_rcu(&cgrp->rcu_head, free_cgroup_rcu);
809 iput(inode);
812 static void remove_dir(struct dentry *d)
814 struct dentry *parent = dget(d->d_parent);
816 d_delete(d);
817 simple_rmdir(parent->d_inode, d);
818 dput(parent);
821 static void cgroup_clear_directory(struct dentry *dentry)
823 struct list_head *node;
825 BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
826 spin_lock(&dcache_lock);
827 node = dentry->d_subdirs.next;
828 while (node != &dentry->d_subdirs) {
829 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
830 list_del_init(node);
831 if (d->d_inode) {
832 /* This should never be called on a cgroup
833 * directory with child cgroups */
834 BUG_ON(d->d_inode->i_mode & S_IFDIR);
835 d = dget_locked(d);
836 spin_unlock(&dcache_lock);
837 d_delete(d);
838 simple_unlink(dentry->d_inode, d);
839 dput(d);
840 spin_lock(&dcache_lock);
842 node = dentry->d_subdirs.next;
844 spin_unlock(&dcache_lock);
848 * NOTE : the dentry must have been dget()'ed
850 static void cgroup_d_remove_dir(struct dentry *dentry)
852 cgroup_clear_directory(dentry);
854 spin_lock(&dcache_lock);
855 list_del_init(&dentry->d_u.d_child);
856 spin_unlock(&dcache_lock);
857 remove_dir(dentry);
861 * A queue for waiters to do rmdir() cgroup. A tasks will sleep when
862 * cgroup->count == 0 && list_empty(&cgroup->children) && subsys has some
863 * reference to css->refcnt. In general, this refcnt is expected to goes down
864 * to zero, soon.
866 * CGRP_WAIT_ON_RMDIR flag is set under cgroup's inode->i_mutex;
868 DECLARE_WAIT_QUEUE_HEAD(cgroup_rmdir_waitq);
870 static void cgroup_wakeup_rmdir_waiter(struct cgroup *cgrp)
872 if (unlikely(test_and_clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags)))
873 wake_up_all(&cgroup_rmdir_waitq);
876 void cgroup_exclude_rmdir(struct cgroup_subsys_state *css)
878 css_get(css);
881 void cgroup_release_and_wakeup_rmdir(struct cgroup_subsys_state *css)
883 cgroup_wakeup_rmdir_waiter(css->cgroup);
884 css_put(css);
888 static int rebind_subsystems(struct cgroupfs_root *root,
889 unsigned long final_bits)
891 unsigned long added_bits, removed_bits;
892 struct cgroup *cgrp = &root->top_cgroup;
893 int i;
895 removed_bits = root->actual_subsys_bits & ~final_bits;
896 added_bits = final_bits & ~root->actual_subsys_bits;
897 /* Check that any added subsystems are currently free */
898 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
899 unsigned long bit = 1UL << i;
900 struct cgroup_subsys *ss = subsys[i];
901 if (!(bit & added_bits))
902 continue;
903 if (ss->root != &rootnode) {
904 /* Subsystem isn't free */
905 return -EBUSY;
909 /* Currently we don't handle adding/removing subsystems when
910 * any child cgroups exist. This is theoretically supportable
911 * but involves complex error handling, so it's being left until
912 * later */
913 if (root->number_of_cgroups > 1)
914 return -EBUSY;
916 /* Process each subsystem */
917 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
918 struct cgroup_subsys *ss = subsys[i];
919 unsigned long bit = 1UL << i;
920 if (bit & added_bits) {
921 /* We're binding this subsystem to this hierarchy */
922 BUG_ON(cgrp->subsys[i]);
923 BUG_ON(!dummytop->subsys[i]);
924 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
925 mutex_lock(&ss->hierarchy_mutex);
926 cgrp->subsys[i] = dummytop->subsys[i];
927 cgrp->subsys[i]->cgroup = cgrp;
928 list_move(&ss->sibling, &root->subsys_list);
929 ss->root = root;
930 if (ss->bind)
931 ss->bind(ss, cgrp);
932 mutex_unlock(&ss->hierarchy_mutex);
933 } else if (bit & removed_bits) {
934 /* We're removing this subsystem */
935 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
936 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
937 mutex_lock(&ss->hierarchy_mutex);
938 if (ss->bind)
939 ss->bind(ss, dummytop);
940 dummytop->subsys[i]->cgroup = dummytop;
941 cgrp->subsys[i] = NULL;
942 subsys[i]->root = &rootnode;
943 list_move(&ss->sibling, &rootnode.subsys_list);
944 mutex_unlock(&ss->hierarchy_mutex);
945 } else if (bit & final_bits) {
946 /* Subsystem state should already exist */
947 BUG_ON(!cgrp->subsys[i]);
948 } else {
949 /* Subsystem state shouldn't exist */
950 BUG_ON(cgrp->subsys[i]);
953 root->subsys_bits = root->actual_subsys_bits = final_bits;
954 synchronize_rcu();
956 return 0;
959 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
961 struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
962 struct cgroup_subsys *ss;
964 mutex_lock(&cgroup_mutex);
965 for_each_subsys(root, ss)
966 seq_printf(seq, ",%s", ss->name);
967 if (test_bit(ROOT_NOPREFIX, &root->flags))
968 seq_puts(seq, ",noprefix");
969 if (strlen(root->release_agent_path))
970 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
971 if (strlen(root->name))
972 seq_printf(seq, ",name=%s", root->name);
973 mutex_unlock(&cgroup_mutex);
974 return 0;
977 struct cgroup_sb_opts {
978 unsigned long subsys_bits;
979 unsigned long flags;
980 char *release_agent;
981 char *name;
982 /* User explicitly requested empty subsystem */
983 bool none;
985 struct cgroupfs_root *new_root;
989 /* Convert a hierarchy specifier into a bitmask of subsystems and
990 * flags. */
991 static int parse_cgroupfs_options(char *data,
992 struct cgroup_sb_opts *opts)
994 char *token, *o = data ?: "all";
995 unsigned long mask = (unsigned long)-1;
997 #ifdef CONFIG_CPUSETS
998 mask = ~(1UL << cpuset_subsys_id);
999 #endif
1001 memset(opts, 0, sizeof(*opts));
1003 while ((token = strsep(&o, ",")) != NULL) {
1004 if (!*token)
1005 return -EINVAL;
1006 if (!strcmp(token, "all")) {
1007 /* Add all non-disabled subsystems */
1008 int i;
1009 opts->subsys_bits = 0;
1010 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1011 struct cgroup_subsys *ss = subsys[i];
1012 if (!ss->disabled)
1013 opts->subsys_bits |= 1ul << i;
1015 } else if (!strcmp(token, "none")) {
1016 /* Explicitly have no subsystems */
1017 opts->none = true;
1018 } else if (!strcmp(token, "noprefix")) {
1019 set_bit(ROOT_NOPREFIX, &opts->flags);
1020 } else if (!strncmp(token, "release_agent=", 14)) {
1021 /* Specifying two release agents is forbidden */
1022 if (opts->release_agent)
1023 return -EINVAL;
1024 opts->release_agent =
1025 kstrndup(token + 14, PATH_MAX, GFP_KERNEL);
1026 if (!opts->release_agent)
1027 return -ENOMEM;
1028 } else if (!strncmp(token, "name=", 5)) {
1029 int i;
1030 const char *name = token + 5;
1031 /* Can't specify an empty name */
1032 if (!strlen(name))
1033 return -EINVAL;
1034 /* Must match [\w.-]+ */
1035 for (i = 0; i < strlen(name); i++) {
1036 char c = name[i];
1037 if (isalnum(c))
1038 continue;
1039 if ((c == '.') || (c == '-') || (c == '_'))
1040 continue;
1041 return -EINVAL;
1043 /* Specifying two names is forbidden */
1044 if (opts->name)
1045 return -EINVAL;
1046 opts->name = kstrndup(name,
1047 MAX_CGROUP_ROOT_NAMELEN,
1048 GFP_KERNEL);
1049 if (!opts->name)
1050 return -ENOMEM;
1051 } else {
1052 struct cgroup_subsys *ss;
1053 int i;
1054 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1055 ss = subsys[i];
1056 if (!strcmp(token, ss->name)) {
1057 if (!ss->disabled)
1058 set_bit(i, &opts->subsys_bits);
1059 break;
1062 if (i == CGROUP_SUBSYS_COUNT)
1063 return -ENOENT;
1067 /* Consistency checks */
1070 * Option noprefix was introduced just for backward compatibility
1071 * with the old cpuset, so we allow noprefix only if mounting just
1072 * the cpuset subsystem.
1074 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1075 (opts->subsys_bits & mask))
1076 return -EINVAL;
1079 /* Can't specify "none" and some subsystems */
1080 if (opts->subsys_bits && opts->none)
1081 return -EINVAL;
1084 * We either have to specify by name or by subsystems. (So all
1085 * empty hierarchies must have a name).
1087 if (!opts->subsys_bits && !opts->name)
1088 return -EINVAL;
1090 return 0;
1093 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1095 int ret = 0;
1096 struct cgroupfs_root *root = sb->s_fs_info;
1097 struct cgroup *cgrp = &root->top_cgroup;
1098 struct cgroup_sb_opts opts;
1100 lock_kernel();
1101 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1102 mutex_lock(&cgroup_mutex);
1104 /* See what subsystems are wanted */
1105 ret = parse_cgroupfs_options(data, &opts);
1106 if (ret)
1107 goto out_unlock;
1109 /* Don't allow flags to change at remount */
1110 if (opts.flags != root->flags) {
1111 ret = -EINVAL;
1112 goto out_unlock;
1115 /* Don't allow name to change at remount */
1116 if (opts.name && strcmp(opts.name, root->name)) {
1117 ret = -EINVAL;
1118 goto out_unlock;
1121 ret = rebind_subsystems(root, opts.subsys_bits);
1122 if (ret)
1123 goto out_unlock;
1125 /* (re)populate subsystem files */
1126 cgroup_populate_dir(cgrp);
1128 if (opts.release_agent)
1129 strcpy(root->release_agent_path, opts.release_agent);
1130 out_unlock:
1131 kfree(opts.release_agent);
1132 kfree(opts.name);
1133 mutex_unlock(&cgroup_mutex);
1134 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1135 unlock_kernel();
1136 return ret;
1139 static const struct super_operations cgroup_ops = {
1140 .statfs = simple_statfs,
1141 .drop_inode = generic_delete_inode,
1142 .show_options = cgroup_show_options,
1143 .remount_fs = cgroup_remount,
1146 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1148 INIT_LIST_HEAD(&cgrp->sibling);
1149 INIT_LIST_HEAD(&cgrp->children);
1150 INIT_LIST_HEAD(&cgrp->css_sets);
1151 INIT_LIST_HEAD(&cgrp->release_list);
1152 INIT_LIST_HEAD(&cgrp->pidlists);
1153 mutex_init(&cgrp->pidlist_mutex);
1156 static void init_cgroup_root(struct cgroupfs_root *root)
1158 struct cgroup *cgrp = &root->top_cgroup;
1159 INIT_LIST_HEAD(&root->subsys_list);
1160 INIT_LIST_HEAD(&root->root_list);
1161 root->number_of_cgroups = 1;
1162 cgrp->root = root;
1163 cgrp->top_cgroup = cgrp;
1164 init_cgroup_housekeeping(cgrp);
1167 static bool init_root_id(struct cgroupfs_root *root)
1169 int ret = 0;
1171 do {
1172 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1173 return false;
1174 spin_lock(&hierarchy_id_lock);
1175 /* Try to allocate the next unused ID */
1176 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1177 &root->hierarchy_id);
1178 if (ret == -ENOSPC)
1179 /* Try again starting from 0 */
1180 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1181 if (!ret) {
1182 next_hierarchy_id = root->hierarchy_id + 1;
1183 } else if (ret != -EAGAIN) {
1184 /* Can only get here if the 31-bit IDR is full ... */
1185 BUG_ON(ret);
1187 spin_unlock(&hierarchy_id_lock);
1188 } while (ret);
1189 return true;
1192 static int cgroup_test_super(struct super_block *sb, void *data)
1194 struct cgroup_sb_opts *opts = data;
1195 struct cgroupfs_root *root = sb->s_fs_info;
1197 /* If we asked for a name then it must match */
1198 if (opts->name && strcmp(opts->name, root->name))
1199 return 0;
1202 * If we asked for subsystems (or explicitly for no
1203 * subsystems) then they must match
1205 if ((opts->subsys_bits || opts->none)
1206 && (opts->subsys_bits != root->subsys_bits))
1207 return 0;
1209 return 1;
1212 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1214 struct cgroupfs_root *root;
1216 if (!opts->subsys_bits && !opts->none)
1217 return NULL;
1219 root = kzalloc(sizeof(*root), GFP_KERNEL);
1220 if (!root)
1221 return ERR_PTR(-ENOMEM);
1223 if (!init_root_id(root)) {
1224 kfree(root);
1225 return ERR_PTR(-ENOMEM);
1227 init_cgroup_root(root);
1229 root->subsys_bits = opts->subsys_bits;
1230 root->flags = opts->flags;
1231 if (opts->release_agent)
1232 strcpy(root->release_agent_path, opts->release_agent);
1233 if (opts->name)
1234 strcpy(root->name, opts->name);
1235 return root;
1238 static void cgroup_drop_root(struct cgroupfs_root *root)
1240 if (!root)
1241 return;
1243 BUG_ON(!root->hierarchy_id);
1244 spin_lock(&hierarchy_id_lock);
1245 ida_remove(&hierarchy_ida, root->hierarchy_id);
1246 spin_unlock(&hierarchy_id_lock);
1247 kfree(root);
1250 static int cgroup_set_super(struct super_block *sb, void *data)
1252 int ret;
1253 struct cgroup_sb_opts *opts = data;
1255 /* If we don't have a new root, we can't set up a new sb */
1256 if (!opts->new_root)
1257 return -EINVAL;
1259 BUG_ON(!opts->subsys_bits && !opts->none);
1261 ret = set_anon_super(sb, NULL);
1262 if (ret)
1263 return ret;
1265 sb->s_fs_info = opts->new_root;
1266 opts->new_root->sb = sb;
1268 sb->s_blocksize = PAGE_CACHE_SIZE;
1269 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1270 sb->s_magic = CGROUP_SUPER_MAGIC;
1271 sb->s_op = &cgroup_ops;
1273 return 0;
1276 static int cgroup_get_rootdir(struct super_block *sb)
1278 struct inode *inode =
1279 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1280 struct dentry *dentry;
1282 if (!inode)
1283 return -ENOMEM;
1285 inode->i_fop = &simple_dir_operations;
1286 inode->i_op = &cgroup_dir_inode_operations;
1287 /* directories start off with i_nlink == 2 (for "." entry) */
1288 inc_nlink(inode);
1289 dentry = d_alloc_root(inode);
1290 if (!dentry) {
1291 iput(inode);
1292 return -ENOMEM;
1294 sb->s_root = dentry;
1295 return 0;
1298 static int cgroup_get_sb(struct file_system_type *fs_type,
1299 int flags, const char *unused_dev_name,
1300 void *data, struct vfsmount *mnt)
1302 struct cgroup_sb_opts opts;
1303 struct cgroupfs_root *root;
1304 int ret = 0;
1305 struct super_block *sb;
1306 struct cgroupfs_root *new_root;
1308 /* First find the desired set of subsystems */
1309 ret = parse_cgroupfs_options(data, &opts);
1310 if (ret)
1311 goto out_err;
1314 * Allocate a new cgroup root. We may not need it if we're
1315 * reusing an existing hierarchy.
1317 new_root = cgroup_root_from_opts(&opts);
1318 if (IS_ERR(new_root)) {
1319 ret = PTR_ERR(new_root);
1320 goto out_err;
1322 opts.new_root = new_root;
1324 /* Locate an existing or new sb for this hierarchy */
1325 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, &opts);
1326 if (IS_ERR(sb)) {
1327 ret = PTR_ERR(sb);
1328 cgroup_drop_root(opts.new_root);
1329 goto out_err;
1332 root = sb->s_fs_info;
1333 BUG_ON(!root);
1334 if (root == opts.new_root) {
1335 /* We used the new root structure, so this is a new hierarchy */
1336 struct list_head tmp_cg_links;
1337 struct cgroup *root_cgrp = &root->top_cgroup;
1338 struct inode *inode;
1339 struct cgroupfs_root *existing_root;
1340 int i;
1342 BUG_ON(sb->s_root != NULL);
1344 ret = cgroup_get_rootdir(sb);
1345 if (ret)
1346 goto drop_new_super;
1347 inode = sb->s_root->d_inode;
1349 mutex_lock(&inode->i_mutex);
1350 mutex_lock(&cgroup_mutex);
1352 if (strlen(root->name)) {
1353 /* Check for name clashes with existing mounts */
1354 for_each_active_root(existing_root) {
1355 if (!strcmp(existing_root->name, root->name)) {
1356 ret = -EBUSY;
1357 mutex_unlock(&cgroup_mutex);
1358 mutex_unlock(&inode->i_mutex);
1359 goto drop_new_super;
1365 * We're accessing css_set_count without locking
1366 * css_set_lock here, but that's OK - it can only be
1367 * increased by someone holding cgroup_lock, and
1368 * that's us. The worst that can happen is that we
1369 * have some link structures left over
1371 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1372 if (ret) {
1373 mutex_unlock(&cgroup_mutex);
1374 mutex_unlock(&inode->i_mutex);
1375 goto drop_new_super;
1378 ret = rebind_subsystems(root, root->subsys_bits);
1379 if (ret == -EBUSY) {
1380 mutex_unlock(&cgroup_mutex);
1381 mutex_unlock(&inode->i_mutex);
1382 free_cg_links(&tmp_cg_links);
1383 goto drop_new_super;
1386 /* EBUSY should be the only error here */
1387 BUG_ON(ret);
1389 list_add(&root->root_list, &roots);
1390 root_count++;
1392 sb->s_root->d_fsdata = root_cgrp;
1393 root->top_cgroup.dentry = sb->s_root;
1395 /* Link the top cgroup in this hierarchy into all
1396 * the css_set objects */
1397 write_lock(&css_set_lock);
1398 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1399 struct hlist_head *hhead = &css_set_table[i];
1400 struct hlist_node *node;
1401 struct css_set *cg;
1403 hlist_for_each_entry(cg, node, hhead, hlist)
1404 link_css_set(&tmp_cg_links, cg, root_cgrp);
1406 write_unlock(&css_set_lock);
1408 free_cg_links(&tmp_cg_links);
1410 BUG_ON(!list_empty(&root_cgrp->sibling));
1411 BUG_ON(!list_empty(&root_cgrp->children));
1412 BUG_ON(root->number_of_cgroups != 1);
1414 cgroup_populate_dir(root_cgrp);
1415 mutex_unlock(&cgroup_mutex);
1416 mutex_unlock(&inode->i_mutex);
1417 } else {
1419 * We re-used an existing hierarchy - the new root (if
1420 * any) is not needed
1422 cgroup_drop_root(opts.new_root);
1425 simple_set_mnt(mnt, sb);
1426 kfree(opts.release_agent);
1427 kfree(opts.name);
1428 return 0;
1430 drop_new_super:
1431 deactivate_locked_super(sb);
1432 out_err:
1433 kfree(opts.release_agent);
1434 kfree(opts.name);
1436 return ret;
1439 static void cgroup_kill_sb(struct super_block *sb) {
1440 struct cgroupfs_root *root = sb->s_fs_info;
1441 struct cgroup *cgrp = &root->top_cgroup;
1442 int ret;
1443 struct cg_cgroup_link *link;
1444 struct cg_cgroup_link *saved_link;
1446 BUG_ON(!root);
1448 BUG_ON(root->number_of_cgroups != 1);
1449 BUG_ON(!list_empty(&cgrp->children));
1450 BUG_ON(!list_empty(&cgrp->sibling));
1452 mutex_lock(&cgroup_mutex);
1454 /* Rebind all subsystems back to the default hierarchy */
1455 ret = rebind_subsystems(root, 0);
1456 /* Shouldn't be able to fail ... */
1457 BUG_ON(ret);
1460 * Release all the links from css_sets to this hierarchy's
1461 * root cgroup
1463 write_lock(&css_set_lock);
1465 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1466 cgrp_link_list) {
1467 list_del(&link->cg_link_list);
1468 list_del(&link->cgrp_link_list);
1469 kfree(link);
1471 write_unlock(&css_set_lock);
1473 if (!list_empty(&root->root_list)) {
1474 list_del(&root->root_list);
1475 root_count--;
1478 mutex_unlock(&cgroup_mutex);
1480 kill_litter_super(sb);
1481 cgroup_drop_root(root);
1484 static struct file_system_type cgroup_fs_type = {
1485 .name = "cgroup",
1486 .get_sb = cgroup_get_sb,
1487 .kill_sb = cgroup_kill_sb,
1490 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1492 return dentry->d_fsdata;
1495 static inline struct cftype *__d_cft(struct dentry *dentry)
1497 return dentry->d_fsdata;
1501 * cgroup_path - generate the path of a cgroup
1502 * @cgrp: the cgroup in question
1503 * @buf: the buffer to write the path into
1504 * @buflen: the length of the buffer
1506 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1507 * reference. Writes path of cgroup into buf. Returns 0 on success,
1508 * -errno on error.
1510 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1512 char *start;
1513 struct dentry *dentry = rcu_dereference(cgrp->dentry);
1515 if (!dentry || cgrp == dummytop) {
1517 * Inactive subsystems have no dentry for their root
1518 * cgroup
1520 strcpy(buf, "/");
1521 return 0;
1524 start = buf + buflen;
1526 *--start = '\0';
1527 for (;;) {
1528 int len = dentry->d_name.len;
1529 if ((start -= len) < buf)
1530 return -ENAMETOOLONG;
1531 memcpy(start, cgrp->dentry->d_name.name, len);
1532 cgrp = cgrp->parent;
1533 if (!cgrp)
1534 break;
1535 dentry = rcu_dereference(cgrp->dentry);
1536 if (!cgrp->parent)
1537 continue;
1538 if (--start < buf)
1539 return -ENAMETOOLONG;
1540 *start = '/';
1542 memmove(buf, start, buf + buflen - start);
1543 return 0;
1547 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1548 * @cgrp: the cgroup the task is attaching to
1549 * @tsk: the task to be attached
1551 * Call holding cgroup_mutex. May take task_lock of
1552 * the task 'tsk' during call.
1554 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1556 int retval = 0;
1557 struct cgroup_subsys *ss;
1558 struct cgroup *oldcgrp;
1559 struct css_set *cg;
1560 struct css_set *newcg;
1561 struct cgroupfs_root *root = cgrp->root;
1563 /* Nothing to do if the task is already in that cgroup */
1564 oldcgrp = task_cgroup_from_root(tsk, root);
1565 if (cgrp == oldcgrp)
1566 return 0;
1568 for_each_subsys(root, ss) {
1569 if (ss->can_attach) {
1570 retval = ss->can_attach(ss, cgrp, tsk, false);
1571 if (retval)
1572 return retval;
1576 task_lock(tsk);
1577 cg = tsk->cgroups;
1578 get_css_set(cg);
1579 task_unlock(tsk);
1581 * Locate or allocate a new css_set for this task,
1582 * based on its final set of cgroups
1584 newcg = find_css_set(cg, cgrp);
1585 put_css_set(cg);
1586 if (!newcg)
1587 return -ENOMEM;
1589 task_lock(tsk);
1590 if (tsk->flags & PF_EXITING) {
1591 task_unlock(tsk);
1592 put_css_set(newcg);
1593 return -ESRCH;
1595 rcu_assign_pointer(tsk->cgroups, newcg);
1596 task_unlock(tsk);
1598 /* Update the css_set linked lists if we're using them */
1599 write_lock(&css_set_lock);
1600 if (!list_empty(&tsk->cg_list)) {
1601 list_del(&tsk->cg_list);
1602 list_add(&tsk->cg_list, &newcg->tasks);
1604 write_unlock(&css_set_lock);
1606 for_each_subsys(root, ss) {
1607 if (ss->attach)
1608 ss->attach(ss, cgrp, oldcgrp, tsk, false);
1610 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1611 synchronize_rcu();
1612 put_css_set(cg);
1615 * wake up rmdir() waiter. the rmdir should fail since the cgroup
1616 * is no longer empty.
1618 cgroup_wakeup_rmdir_waiter(cgrp);
1619 return 0;
1623 * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
1624 * held. May take task_lock of task
1626 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
1628 struct task_struct *tsk;
1629 const struct cred *cred = current_cred(), *tcred;
1630 int ret;
1632 if (pid) {
1633 rcu_read_lock();
1634 tsk = find_task_by_vpid(pid);
1635 if (!tsk || tsk->flags & PF_EXITING) {
1636 rcu_read_unlock();
1637 return -ESRCH;
1640 tcred = __task_cred(tsk);
1641 if (cred->euid &&
1642 cred->euid != tcred->uid &&
1643 cred->euid != tcred->suid) {
1644 rcu_read_unlock();
1645 return -EACCES;
1647 get_task_struct(tsk);
1648 rcu_read_unlock();
1649 } else {
1650 tsk = current;
1651 get_task_struct(tsk);
1654 ret = cgroup_attach_task(cgrp, tsk);
1655 put_task_struct(tsk);
1656 return ret;
1659 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
1661 int ret;
1662 if (!cgroup_lock_live_group(cgrp))
1663 return -ENODEV;
1664 ret = attach_task_by_pid(cgrp, pid);
1665 cgroup_unlock();
1666 return ret;
1670 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1671 * @cgrp: the cgroup to be checked for liveness
1673 * On success, returns true; the lock should be later released with
1674 * cgroup_unlock(). On failure returns false with no lock held.
1676 bool cgroup_lock_live_group(struct cgroup *cgrp)
1678 mutex_lock(&cgroup_mutex);
1679 if (cgroup_is_removed(cgrp)) {
1680 mutex_unlock(&cgroup_mutex);
1681 return false;
1683 return true;
1686 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1687 const char *buffer)
1689 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1690 if (!cgroup_lock_live_group(cgrp))
1691 return -ENODEV;
1692 strcpy(cgrp->root->release_agent_path, buffer);
1693 cgroup_unlock();
1694 return 0;
1697 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1698 struct seq_file *seq)
1700 if (!cgroup_lock_live_group(cgrp))
1701 return -ENODEV;
1702 seq_puts(seq, cgrp->root->release_agent_path);
1703 seq_putc(seq, '\n');
1704 cgroup_unlock();
1705 return 0;
1708 /* A buffer size big enough for numbers or short strings */
1709 #define CGROUP_LOCAL_BUFFER_SIZE 64
1711 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1712 struct file *file,
1713 const char __user *userbuf,
1714 size_t nbytes, loff_t *unused_ppos)
1716 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1717 int retval = 0;
1718 char *end;
1720 if (!nbytes)
1721 return -EINVAL;
1722 if (nbytes >= sizeof(buffer))
1723 return -E2BIG;
1724 if (copy_from_user(buffer, userbuf, nbytes))
1725 return -EFAULT;
1727 buffer[nbytes] = 0; /* nul-terminate */
1728 if (cft->write_u64) {
1729 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
1730 if (*end)
1731 return -EINVAL;
1732 retval = cft->write_u64(cgrp, cft, val);
1733 } else {
1734 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
1735 if (*end)
1736 return -EINVAL;
1737 retval = cft->write_s64(cgrp, cft, val);
1739 if (!retval)
1740 retval = nbytes;
1741 return retval;
1744 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1745 struct file *file,
1746 const char __user *userbuf,
1747 size_t nbytes, loff_t *unused_ppos)
1749 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1750 int retval = 0;
1751 size_t max_bytes = cft->max_write_len;
1752 char *buffer = local_buffer;
1754 if (!max_bytes)
1755 max_bytes = sizeof(local_buffer) - 1;
1756 if (nbytes >= max_bytes)
1757 return -E2BIG;
1758 /* Allocate a dynamic buffer if we need one */
1759 if (nbytes >= sizeof(local_buffer)) {
1760 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1761 if (buffer == NULL)
1762 return -ENOMEM;
1764 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
1765 retval = -EFAULT;
1766 goto out;
1769 buffer[nbytes] = 0; /* nul-terminate */
1770 retval = cft->write_string(cgrp, cft, strstrip(buffer));
1771 if (!retval)
1772 retval = nbytes;
1773 out:
1774 if (buffer != local_buffer)
1775 kfree(buffer);
1776 return retval;
1779 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1780 size_t nbytes, loff_t *ppos)
1782 struct cftype *cft = __d_cft(file->f_dentry);
1783 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1785 if (cgroup_is_removed(cgrp))
1786 return -ENODEV;
1787 if (cft->write)
1788 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1789 if (cft->write_u64 || cft->write_s64)
1790 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1791 if (cft->write_string)
1792 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1793 if (cft->trigger) {
1794 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1795 return ret ? ret : nbytes;
1797 return -EINVAL;
1800 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1801 struct file *file,
1802 char __user *buf, size_t nbytes,
1803 loff_t *ppos)
1805 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1806 u64 val = cft->read_u64(cgrp, cft);
1807 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1809 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1812 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1813 struct file *file,
1814 char __user *buf, size_t nbytes,
1815 loff_t *ppos)
1817 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1818 s64 val = cft->read_s64(cgrp, cft);
1819 int len = sprintf(tmp, "%lld\n", (long long) val);
1821 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1824 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1825 size_t nbytes, loff_t *ppos)
1827 struct cftype *cft = __d_cft(file->f_dentry);
1828 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1830 if (cgroup_is_removed(cgrp))
1831 return -ENODEV;
1833 if (cft->read)
1834 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1835 if (cft->read_u64)
1836 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1837 if (cft->read_s64)
1838 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1839 return -EINVAL;
1843 * seqfile ops/methods for returning structured data. Currently just
1844 * supports string->u64 maps, but can be extended in future.
1847 struct cgroup_seqfile_state {
1848 struct cftype *cft;
1849 struct cgroup *cgroup;
1852 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1854 struct seq_file *sf = cb->state;
1855 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1858 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1860 struct cgroup_seqfile_state *state = m->private;
1861 struct cftype *cft = state->cft;
1862 if (cft->read_map) {
1863 struct cgroup_map_cb cb = {
1864 .fill = cgroup_map_add,
1865 .state = m,
1867 return cft->read_map(state->cgroup, cft, &cb);
1869 return cft->read_seq_string(state->cgroup, cft, m);
1872 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
1874 struct seq_file *seq = file->private_data;
1875 kfree(seq->private);
1876 return single_release(inode, file);
1879 static const struct file_operations cgroup_seqfile_operations = {
1880 .read = seq_read,
1881 .write = cgroup_file_write,
1882 .llseek = seq_lseek,
1883 .release = cgroup_seqfile_release,
1886 static int cgroup_file_open(struct inode *inode, struct file *file)
1888 int err;
1889 struct cftype *cft;
1891 err = generic_file_open(inode, file);
1892 if (err)
1893 return err;
1894 cft = __d_cft(file->f_dentry);
1896 if (cft->read_map || cft->read_seq_string) {
1897 struct cgroup_seqfile_state *state =
1898 kzalloc(sizeof(*state), GFP_USER);
1899 if (!state)
1900 return -ENOMEM;
1901 state->cft = cft;
1902 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
1903 file->f_op = &cgroup_seqfile_operations;
1904 err = single_open(file, cgroup_seqfile_show, state);
1905 if (err < 0)
1906 kfree(state);
1907 } else if (cft->open)
1908 err = cft->open(inode, file);
1909 else
1910 err = 0;
1912 return err;
1915 static int cgroup_file_release(struct inode *inode, struct file *file)
1917 struct cftype *cft = __d_cft(file->f_dentry);
1918 if (cft->release)
1919 return cft->release(inode, file);
1920 return 0;
1924 * cgroup_rename - Only allow simple rename of directories in place.
1926 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
1927 struct inode *new_dir, struct dentry *new_dentry)
1929 if (!S_ISDIR(old_dentry->d_inode->i_mode))
1930 return -ENOTDIR;
1931 if (new_dentry->d_inode)
1932 return -EEXIST;
1933 if (old_dir != new_dir)
1934 return -EIO;
1935 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1938 static const struct file_operations cgroup_file_operations = {
1939 .read = cgroup_file_read,
1940 .write = cgroup_file_write,
1941 .llseek = generic_file_llseek,
1942 .open = cgroup_file_open,
1943 .release = cgroup_file_release,
1946 static const struct inode_operations cgroup_dir_inode_operations = {
1947 .lookup = simple_lookup,
1948 .mkdir = cgroup_mkdir,
1949 .rmdir = cgroup_rmdir,
1950 .rename = cgroup_rename,
1953 static int cgroup_create_file(struct dentry *dentry, mode_t mode,
1954 struct super_block *sb)
1956 static const struct dentry_operations cgroup_dops = {
1957 .d_iput = cgroup_diput,
1960 struct inode *inode;
1962 if (!dentry)
1963 return -ENOENT;
1964 if (dentry->d_inode)
1965 return -EEXIST;
1967 inode = cgroup_new_inode(mode, sb);
1968 if (!inode)
1969 return -ENOMEM;
1971 if (S_ISDIR(mode)) {
1972 inode->i_op = &cgroup_dir_inode_operations;
1973 inode->i_fop = &simple_dir_operations;
1975 /* start off with i_nlink == 2 (for "." entry) */
1976 inc_nlink(inode);
1978 /* start with the directory inode held, so that we can
1979 * populate it without racing with another mkdir */
1980 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
1981 } else if (S_ISREG(mode)) {
1982 inode->i_size = 0;
1983 inode->i_fop = &cgroup_file_operations;
1985 dentry->d_op = &cgroup_dops;
1986 d_instantiate(dentry, inode);
1987 dget(dentry); /* Extra count - pin the dentry in core */
1988 return 0;
1992 * cgroup_create_dir - create a directory for an object.
1993 * @cgrp: the cgroup we create the directory for. It must have a valid
1994 * ->parent field. And we are going to fill its ->dentry field.
1995 * @dentry: dentry of the new cgroup
1996 * @mode: mode to set on new directory.
1998 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
1999 mode_t mode)
2001 struct dentry *parent;
2002 int error = 0;
2004 parent = cgrp->parent->dentry;
2005 error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
2006 if (!error) {
2007 dentry->d_fsdata = cgrp;
2008 inc_nlink(parent->d_inode);
2009 rcu_assign_pointer(cgrp->dentry, dentry);
2010 dget(dentry);
2012 dput(dentry);
2014 return error;
2018 * cgroup_file_mode - deduce file mode of a control file
2019 * @cft: the control file in question
2021 * returns cft->mode if ->mode is not 0
2022 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2023 * returns S_IRUGO if it has only a read handler
2024 * returns S_IWUSR if it has only a write hander
2026 static mode_t cgroup_file_mode(const struct cftype *cft)
2028 mode_t mode = 0;
2030 if (cft->mode)
2031 return cft->mode;
2033 if (cft->read || cft->read_u64 || cft->read_s64 ||
2034 cft->read_map || cft->read_seq_string)
2035 mode |= S_IRUGO;
2037 if (cft->write || cft->write_u64 || cft->write_s64 ||
2038 cft->write_string || cft->trigger)
2039 mode |= S_IWUSR;
2041 return mode;
2044 int cgroup_add_file(struct cgroup *cgrp,
2045 struct cgroup_subsys *subsys,
2046 const struct cftype *cft)
2048 struct dentry *dir = cgrp->dentry;
2049 struct dentry *dentry;
2050 int error;
2051 mode_t mode;
2053 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2054 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2055 strcpy(name, subsys->name);
2056 strcat(name, ".");
2058 strcat(name, cft->name);
2059 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2060 dentry = lookup_one_len(name, dir, strlen(name));
2061 if (!IS_ERR(dentry)) {
2062 mode = cgroup_file_mode(cft);
2063 error = cgroup_create_file(dentry, mode | S_IFREG,
2064 cgrp->root->sb);
2065 if (!error)
2066 dentry->d_fsdata = (void *)cft;
2067 dput(dentry);
2068 } else
2069 error = PTR_ERR(dentry);
2070 return error;
2073 int cgroup_add_files(struct cgroup *cgrp,
2074 struct cgroup_subsys *subsys,
2075 const struct cftype cft[],
2076 int count)
2078 int i, err;
2079 for (i = 0; i < count; i++) {
2080 err = cgroup_add_file(cgrp, subsys, &cft[i]);
2081 if (err)
2082 return err;
2084 return 0;
2088 * cgroup_task_count - count the number of tasks in a cgroup.
2089 * @cgrp: the cgroup in question
2091 * Return the number of tasks in the cgroup.
2093 int cgroup_task_count(const struct cgroup *cgrp)
2095 int count = 0;
2096 struct cg_cgroup_link *link;
2098 read_lock(&css_set_lock);
2099 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2100 count += atomic_read(&link->cg->refcount);
2102 read_unlock(&css_set_lock);
2103 return count;
2107 * Advance a list_head iterator. The iterator should be positioned at
2108 * the start of a css_set
2110 static void cgroup_advance_iter(struct cgroup *cgrp,
2111 struct cgroup_iter *it)
2113 struct list_head *l = it->cg_link;
2114 struct cg_cgroup_link *link;
2115 struct css_set *cg;
2117 /* Advance to the next non-empty css_set */
2118 do {
2119 l = l->next;
2120 if (l == &cgrp->css_sets) {
2121 it->cg_link = NULL;
2122 return;
2124 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2125 cg = link->cg;
2126 } while (list_empty(&cg->tasks));
2127 it->cg_link = l;
2128 it->task = cg->tasks.next;
2132 * To reduce the fork() overhead for systems that are not actually
2133 * using their cgroups capability, we don't maintain the lists running
2134 * through each css_set to its tasks until we see the list actually
2135 * used - in other words after the first call to cgroup_iter_start().
2137 * The tasklist_lock is not held here, as do_each_thread() and
2138 * while_each_thread() are protected by RCU.
2140 static void cgroup_enable_task_cg_lists(void)
2142 struct task_struct *p, *g;
2143 write_lock(&css_set_lock);
2144 use_task_css_set_links = 1;
2145 do_each_thread(g, p) {
2146 task_lock(p);
2148 * We should check if the process is exiting, otherwise
2149 * it will race with cgroup_exit() in that the list
2150 * entry won't be deleted though the process has exited.
2152 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2153 list_add(&p->cg_list, &p->cgroups->tasks);
2154 task_unlock(p);
2155 } while_each_thread(g, p);
2156 write_unlock(&css_set_lock);
2159 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
2162 * The first time anyone tries to iterate across a cgroup,
2163 * we need to enable the list linking each css_set to its
2164 * tasks, and fix up all existing tasks.
2166 if (!use_task_css_set_links)
2167 cgroup_enable_task_cg_lists();
2169 read_lock(&css_set_lock);
2170 it->cg_link = &cgrp->css_sets;
2171 cgroup_advance_iter(cgrp, it);
2174 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
2175 struct cgroup_iter *it)
2177 struct task_struct *res;
2178 struct list_head *l = it->task;
2179 struct cg_cgroup_link *link;
2181 /* If the iterator cg is NULL, we have no tasks */
2182 if (!it->cg_link)
2183 return NULL;
2184 res = list_entry(l, struct task_struct, cg_list);
2185 /* Advance iterator to find next entry */
2186 l = l->next;
2187 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
2188 if (l == &link->cg->tasks) {
2189 /* We reached the end of this task list - move on to
2190 * the next cg_cgroup_link */
2191 cgroup_advance_iter(cgrp, it);
2192 } else {
2193 it->task = l;
2195 return res;
2198 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
2200 read_unlock(&css_set_lock);
2203 static inline int started_after_time(struct task_struct *t1,
2204 struct timespec *time,
2205 struct task_struct *t2)
2207 int start_diff = timespec_compare(&t1->start_time, time);
2208 if (start_diff > 0) {
2209 return 1;
2210 } else if (start_diff < 0) {
2211 return 0;
2212 } else {
2214 * Arbitrarily, if two processes started at the same
2215 * time, we'll say that the lower pointer value
2216 * started first. Note that t2 may have exited by now
2217 * so this may not be a valid pointer any longer, but
2218 * that's fine - it still serves to distinguish
2219 * between two tasks started (effectively) simultaneously.
2221 return t1 > t2;
2226 * This function is a callback from heap_insert() and is used to order
2227 * the heap.
2228 * In this case we order the heap in descending task start time.
2230 static inline int started_after(void *p1, void *p2)
2232 struct task_struct *t1 = p1;
2233 struct task_struct *t2 = p2;
2234 return started_after_time(t1, &t2->start_time, t2);
2238 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
2239 * @scan: struct cgroup_scanner containing arguments for the scan
2241 * Arguments include pointers to callback functions test_task() and
2242 * process_task().
2243 * Iterate through all the tasks in a cgroup, calling test_task() for each,
2244 * and if it returns true, call process_task() for it also.
2245 * The test_task pointer may be NULL, meaning always true (select all tasks).
2246 * Effectively duplicates cgroup_iter_{start,next,end}()
2247 * but does not lock css_set_lock for the call to process_task().
2248 * The struct cgroup_scanner may be embedded in any structure of the caller's
2249 * creation.
2250 * It is guaranteed that process_task() will act on every task that
2251 * is a member of the cgroup for the duration of this call. This
2252 * function may or may not call process_task() for tasks that exit
2253 * or move to a different cgroup during the call, or are forked or
2254 * move into the cgroup during the call.
2256 * Note that test_task() may be called with locks held, and may in some
2257 * situations be called multiple times for the same task, so it should
2258 * be cheap.
2259 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
2260 * pre-allocated and will be used for heap operations (and its "gt" member will
2261 * be overwritten), else a temporary heap will be used (allocation of which
2262 * may cause this function to fail).
2264 int cgroup_scan_tasks(struct cgroup_scanner *scan)
2266 int retval, i;
2267 struct cgroup_iter it;
2268 struct task_struct *p, *dropped;
2269 /* Never dereference latest_task, since it's not refcounted */
2270 struct task_struct *latest_task = NULL;
2271 struct ptr_heap tmp_heap;
2272 struct ptr_heap *heap;
2273 struct timespec latest_time = { 0, 0 };
2275 if (scan->heap) {
2276 /* The caller supplied our heap and pre-allocated its memory */
2277 heap = scan->heap;
2278 heap->gt = &started_after;
2279 } else {
2280 /* We need to allocate our own heap memory */
2281 heap = &tmp_heap;
2282 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2283 if (retval)
2284 /* cannot allocate the heap */
2285 return retval;
2288 again:
2290 * Scan tasks in the cgroup, using the scanner's "test_task" callback
2291 * to determine which are of interest, and using the scanner's
2292 * "process_task" callback to process any of them that need an update.
2293 * Since we don't want to hold any locks during the task updates,
2294 * gather tasks to be processed in a heap structure.
2295 * The heap is sorted by descending task start time.
2296 * If the statically-sized heap fills up, we overflow tasks that
2297 * started later, and in future iterations only consider tasks that
2298 * started after the latest task in the previous pass. This
2299 * guarantees forward progress and that we don't miss any tasks.
2301 heap->size = 0;
2302 cgroup_iter_start(scan->cg, &it);
2303 while ((p = cgroup_iter_next(scan->cg, &it))) {
2305 * Only affect tasks that qualify per the caller's callback,
2306 * if he provided one
2308 if (scan->test_task && !scan->test_task(p, scan))
2309 continue;
2311 * Only process tasks that started after the last task
2312 * we processed
2314 if (!started_after_time(p, &latest_time, latest_task))
2315 continue;
2316 dropped = heap_insert(heap, p);
2317 if (dropped == NULL) {
2319 * The new task was inserted; the heap wasn't
2320 * previously full
2322 get_task_struct(p);
2323 } else if (dropped != p) {
2325 * The new task was inserted, and pushed out a
2326 * different task
2328 get_task_struct(p);
2329 put_task_struct(dropped);
2332 * Else the new task was newer than anything already in
2333 * the heap and wasn't inserted
2336 cgroup_iter_end(scan->cg, &it);
2338 if (heap->size) {
2339 for (i = 0; i < heap->size; i++) {
2340 struct task_struct *q = heap->ptrs[i];
2341 if (i == 0) {
2342 latest_time = q->start_time;
2343 latest_task = q;
2345 /* Process the task per the caller's callback */
2346 scan->process_task(q, scan);
2347 put_task_struct(q);
2350 * If we had to process any tasks at all, scan again
2351 * in case some of them were in the middle of forking
2352 * children that didn't get processed.
2353 * Not the most efficient way to do it, but it avoids
2354 * having to take callback_mutex in the fork path
2356 goto again;
2358 if (heap == &tmp_heap)
2359 heap_free(&tmp_heap);
2360 return 0;
2364 * Stuff for reading the 'tasks'/'procs' files.
2366 * Reading this file can return large amounts of data if a cgroup has
2367 * *lots* of attached tasks. So it may need several calls to read(),
2368 * but we cannot guarantee that the information we produce is correct
2369 * unless we produce it entirely atomically.
2374 * The following two functions "fix" the issue where there are more pids
2375 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
2376 * TODO: replace with a kernel-wide solution to this problem
2378 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
2379 static void *pidlist_allocate(int count)
2381 if (PIDLIST_TOO_LARGE(count))
2382 return vmalloc(count * sizeof(pid_t));
2383 else
2384 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
2386 static void pidlist_free(void *p)
2388 if (is_vmalloc_addr(p))
2389 vfree(p);
2390 else
2391 kfree(p);
2393 static void *pidlist_resize(void *p, int newcount)
2395 void *newlist;
2396 /* note: if new alloc fails, old p will still be valid either way */
2397 if (is_vmalloc_addr(p)) {
2398 newlist = vmalloc(newcount * sizeof(pid_t));
2399 if (!newlist)
2400 return NULL;
2401 memcpy(newlist, p, newcount * sizeof(pid_t));
2402 vfree(p);
2403 } else {
2404 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
2406 return newlist;
2410 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
2411 * If the new stripped list is sufficiently smaller and there's enough memory
2412 * to allocate a new buffer, will let go of the unneeded memory. Returns the
2413 * number of unique elements.
2415 /* is the size difference enough that we should re-allocate the array? */
2416 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
2417 static int pidlist_uniq(pid_t **p, int length)
2419 int src, dest = 1;
2420 pid_t *list = *p;
2421 pid_t *newlist;
2424 * we presume the 0th element is unique, so i starts at 1. trivial
2425 * edge cases first; no work needs to be done for either
2427 if (length == 0 || length == 1)
2428 return length;
2429 /* src and dest walk down the list; dest counts unique elements */
2430 for (src = 1; src < length; src++) {
2431 /* find next unique element */
2432 while (list[src] == list[src-1]) {
2433 src++;
2434 if (src == length)
2435 goto after;
2437 /* dest always points to where the next unique element goes */
2438 list[dest] = list[src];
2439 dest++;
2441 after:
2443 * if the length difference is large enough, we want to allocate a
2444 * smaller buffer to save memory. if this fails due to out of memory,
2445 * we'll just stay with what we've got.
2447 if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
2448 newlist = pidlist_resize(list, dest);
2449 if (newlist)
2450 *p = newlist;
2452 return dest;
2455 static int cmppid(const void *a, const void *b)
2457 return *(pid_t *)a - *(pid_t *)b;
2461 * find the appropriate pidlist for our purpose (given procs vs tasks)
2462 * returns with the lock on that pidlist already held, and takes care
2463 * of the use count, or returns NULL with no locks held if we're out of
2464 * memory.
2466 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
2467 enum cgroup_filetype type)
2469 struct cgroup_pidlist *l;
2470 /* don't need task_nsproxy() if we're looking at ourself */
2471 struct pid_namespace *ns = get_pid_ns(current->nsproxy->pid_ns);
2473 * We can't drop the pidlist_mutex before taking the l->mutex in case
2474 * the last ref-holder is trying to remove l from the list at the same
2475 * time. Holding the pidlist_mutex precludes somebody taking whichever
2476 * list we find out from under us - compare release_pid_array().
2478 mutex_lock(&cgrp->pidlist_mutex);
2479 list_for_each_entry(l, &cgrp->pidlists, links) {
2480 if (l->key.type == type && l->key.ns == ns) {
2481 /* found a matching list - drop the extra refcount */
2482 put_pid_ns(ns);
2483 /* make sure l doesn't vanish out from under us */
2484 down_write(&l->mutex);
2485 mutex_unlock(&cgrp->pidlist_mutex);
2486 return l;
2489 /* entry not found; create a new one */
2490 l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
2491 if (!l) {
2492 mutex_unlock(&cgrp->pidlist_mutex);
2493 put_pid_ns(ns);
2494 return l;
2496 init_rwsem(&l->mutex);
2497 down_write(&l->mutex);
2498 l->key.type = type;
2499 l->key.ns = ns;
2500 l->use_count = 0; /* don't increment here */
2501 l->list = NULL;
2502 l->owner = cgrp;
2503 list_add(&l->links, &cgrp->pidlists);
2504 mutex_unlock(&cgrp->pidlist_mutex);
2505 return l;
2509 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
2511 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
2512 struct cgroup_pidlist **lp)
2514 pid_t *array;
2515 int length;
2516 int pid, n = 0; /* used for populating the array */
2517 struct cgroup_iter it;
2518 struct task_struct *tsk;
2519 struct cgroup_pidlist *l;
2522 * If cgroup gets more users after we read count, we won't have
2523 * enough space - tough. This race is indistinguishable to the
2524 * caller from the case that the additional cgroup users didn't
2525 * show up until sometime later on.
2527 length = cgroup_task_count(cgrp);
2528 array = pidlist_allocate(length);
2529 if (!array)
2530 return -ENOMEM;
2531 /* now, populate the array */
2532 cgroup_iter_start(cgrp, &it);
2533 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2534 if (unlikely(n == length))
2535 break;
2536 /* get tgid or pid for procs or tasks file respectively */
2537 if (type == CGROUP_FILE_PROCS)
2538 pid = task_tgid_vnr(tsk);
2539 else
2540 pid = task_pid_vnr(tsk);
2541 if (pid > 0) /* make sure to only use valid results */
2542 array[n++] = pid;
2544 cgroup_iter_end(cgrp, &it);
2545 length = n;
2546 /* now sort & (if procs) strip out duplicates */
2547 sort(array, length, sizeof(pid_t), cmppid, NULL);
2548 if (type == CGROUP_FILE_PROCS)
2549 length = pidlist_uniq(&array, length);
2550 l = cgroup_pidlist_find(cgrp, type);
2551 if (!l) {
2552 pidlist_free(array);
2553 return -ENOMEM;
2555 /* store array, freeing old if necessary - lock already held */
2556 pidlist_free(l->list);
2557 l->list = array;
2558 l->length = length;
2559 l->use_count++;
2560 up_write(&l->mutex);
2561 *lp = l;
2562 return 0;
2566 * cgroupstats_build - build and fill cgroupstats
2567 * @stats: cgroupstats to fill information into
2568 * @dentry: A dentry entry belonging to the cgroup for which stats have
2569 * been requested.
2571 * Build and fill cgroupstats so that taskstats can export it to user
2572 * space.
2574 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2576 int ret = -EINVAL;
2577 struct cgroup *cgrp;
2578 struct cgroup_iter it;
2579 struct task_struct *tsk;
2582 * Validate dentry by checking the superblock operations,
2583 * and make sure it's a directory.
2585 if (dentry->d_sb->s_op != &cgroup_ops ||
2586 !S_ISDIR(dentry->d_inode->i_mode))
2587 goto err;
2589 ret = 0;
2590 cgrp = dentry->d_fsdata;
2592 cgroup_iter_start(cgrp, &it);
2593 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2594 switch (tsk->state) {
2595 case TASK_RUNNING:
2596 stats->nr_running++;
2597 break;
2598 case TASK_INTERRUPTIBLE:
2599 stats->nr_sleeping++;
2600 break;
2601 case TASK_UNINTERRUPTIBLE:
2602 stats->nr_uninterruptible++;
2603 break;
2604 case TASK_STOPPED:
2605 stats->nr_stopped++;
2606 break;
2607 default:
2608 if (delayacct_is_task_waiting_on_io(tsk))
2609 stats->nr_io_wait++;
2610 break;
2613 cgroup_iter_end(cgrp, &it);
2615 err:
2616 return ret;
2621 * seq_file methods for the tasks/procs files. The seq_file position is the
2622 * next pid to display; the seq_file iterator is a pointer to the pid
2623 * in the cgroup->l->list array.
2626 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
2629 * Initially we receive a position value that corresponds to
2630 * one more than the last pid shown (or 0 on the first call or
2631 * after a seek to the start). Use a binary-search to find the
2632 * next pid to display, if any
2634 struct cgroup_pidlist *l = s->private;
2635 int index = 0, pid = *pos;
2636 int *iter;
2638 down_read(&l->mutex);
2639 if (pid) {
2640 int end = l->length;
2642 while (index < end) {
2643 int mid = (index + end) / 2;
2644 if (l->list[mid] == pid) {
2645 index = mid;
2646 break;
2647 } else if (l->list[mid] <= pid)
2648 index = mid + 1;
2649 else
2650 end = mid;
2653 /* If we're off the end of the array, we're done */
2654 if (index >= l->length)
2655 return NULL;
2656 /* Update the abstract position to be the actual pid that we found */
2657 iter = l->list + index;
2658 *pos = *iter;
2659 return iter;
2662 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
2664 struct cgroup_pidlist *l = s->private;
2665 up_read(&l->mutex);
2668 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
2670 struct cgroup_pidlist *l = s->private;
2671 pid_t *p = v;
2672 pid_t *end = l->list + l->length;
2674 * Advance to the next pid in the array. If this goes off the
2675 * end, we're done
2677 p++;
2678 if (p >= end) {
2679 return NULL;
2680 } else {
2681 *pos = *p;
2682 return p;
2686 static int cgroup_pidlist_show(struct seq_file *s, void *v)
2688 return seq_printf(s, "%d\n", *(int *)v);
2692 * seq_operations functions for iterating on pidlists through seq_file -
2693 * independent of whether it's tasks or procs
2695 static const struct seq_operations cgroup_pidlist_seq_operations = {
2696 .start = cgroup_pidlist_start,
2697 .stop = cgroup_pidlist_stop,
2698 .next = cgroup_pidlist_next,
2699 .show = cgroup_pidlist_show,
2702 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
2705 * the case where we're the last user of this particular pidlist will
2706 * have us remove it from the cgroup's list, which entails taking the
2707 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
2708 * pidlist_mutex, we have to take pidlist_mutex first.
2710 mutex_lock(&l->owner->pidlist_mutex);
2711 down_write(&l->mutex);
2712 BUG_ON(!l->use_count);
2713 if (!--l->use_count) {
2714 /* we're the last user if refcount is 0; remove and free */
2715 list_del(&l->links);
2716 mutex_unlock(&l->owner->pidlist_mutex);
2717 pidlist_free(l->list);
2718 put_pid_ns(l->key.ns);
2719 up_write(&l->mutex);
2720 kfree(l);
2721 return;
2723 mutex_unlock(&l->owner->pidlist_mutex);
2724 up_write(&l->mutex);
2727 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
2729 struct cgroup_pidlist *l;
2730 if (!(file->f_mode & FMODE_READ))
2731 return 0;
2733 * the seq_file will only be initialized if the file was opened for
2734 * reading; hence we check if it's not null only in that case.
2736 l = ((struct seq_file *)file->private_data)->private;
2737 cgroup_release_pid_array(l);
2738 return seq_release(inode, file);
2741 static const struct file_operations cgroup_pidlist_operations = {
2742 .read = seq_read,
2743 .llseek = seq_lseek,
2744 .write = cgroup_file_write,
2745 .release = cgroup_pidlist_release,
2749 * The following functions handle opens on a file that displays a pidlist
2750 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
2751 * in the cgroup.
2753 /* helper function for the two below it */
2754 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
2756 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2757 struct cgroup_pidlist *l;
2758 int retval;
2760 /* Nothing to do for write-only files */
2761 if (!(file->f_mode & FMODE_READ))
2762 return 0;
2764 /* have the array populated */
2765 retval = pidlist_array_load(cgrp, type, &l);
2766 if (retval)
2767 return retval;
2768 /* configure file information */
2769 file->f_op = &cgroup_pidlist_operations;
2771 retval = seq_open(file, &cgroup_pidlist_seq_operations);
2772 if (retval) {
2773 cgroup_release_pid_array(l);
2774 return retval;
2776 ((struct seq_file *)file->private_data)->private = l;
2777 return 0;
2779 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2781 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
2783 static int cgroup_procs_open(struct inode *unused, struct file *file)
2785 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
2788 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2789 struct cftype *cft)
2791 return notify_on_release(cgrp);
2794 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2795 struct cftype *cft,
2796 u64 val)
2798 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2799 if (val)
2800 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2801 else
2802 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2803 return 0;
2807 * for the common functions, 'private' gives the type of file
2809 /* for hysterical raisins, we can't put this on the older files */
2810 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
2811 static struct cftype files[] = {
2813 .name = "tasks",
2814 .open = cgroup_tasks_open,
2815 .write_u64 = cgroup_tasks_write,
2816 .release = cgroup_pidlist_release,
2817 .mode = S_IRUGO | S_IWUSR,
2820 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
2821 .open = cgroup_procs_open,
2822 /* .write_u64 = cgroup_procs_write, TODO */
2823 .release = cgroup_pidlist_release,
2824 .mode = S_IRUGO,
2827 .name = "notify_on_release",
2828 .read_u64 = cgroup_read_notify_on_release,
2829 .write_u64 = cgroup_write_notify_on_release,
2833 static struct cftype cft_release_agent = {
2834 .name = "release_agent",
2835 .read_seq_string = cgroup_release_agent_show,
2836 .write_string = cgroup_release_agent_write,
2837 .max_write_len = PATH_MAX,
2840 static int cgroup_populate_dir(struct cgroup *cgrp)
2842 int err;
2843 struct cgroup_subsys *ss;
2845 /* First clear out any existing files */
2846 cgroup_clear_directory(cgrp->dentry);
2848 err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2849 if (err < 0)
2850 return err;
2852 if (cgrp == cgrp->top_cgroup) {
2853 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2854 return err;
2857 for_each_subsys(cgrp->root, ss) {
2858 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2859 return err;
2861 /* This cgroup is ready now */
2862 for_each_subsys(cgrp->root, ss) {
2863 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2865 * Update id->css pointer and make this css visible from
2866 * CSS ID functions. This pointer will be dereferened
2867 * from RCU-read-side without locks.
2869 if (css->id)
2870 rcu_assign_pointer(css->id->css, css);
2873 return 0;
2876 static void init_cgroup_css(struct cgroup_subsys_state *css,
2877 struct cgroup_subsys *ss,
2878 struct cgroup *cgrp)
2880 css->cgroup = cgrp;
2881 atomic_set(&css->refcnt, 1);
2882 css->flags = 0;
2883 css->id = NULL;
2884 if (cgrp == dummytop)
2885 set_bit(CSS_ROOT, &css->flags);
2886 BUG_ON(cgrp->subsys[ss->subsys_id]);
2887 cgrp->subsys[ss->subsys_id] = css;
2890 static void cgroup_lock_hierarchy(struct cgroupfs_root *root)
2892 /* We need to take each hierarchy_mutex in a consistent order */
2893 int i;
2895 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2896 struct cgroup_subsys *ss = subsys[i];
2897 if (ss->root == root)
2898 mutex_lock(&ss->hierarchy_mutex);
2902 static void cgroup_unlock_hierarchy(struct cgroupfs_root *root)
2904 int i;
2906 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2907 struct cgroup_subsys *ss = subsys[i];
2908 if (ss->root == root)
2909 mutex_unlock(&ss->hierarchy_mutex);
2914 * cgroup_create - create a cgroup
2915 * @parent: cgroup that will be parent of the new cgroup
2916 * @dentry: dentry of the new cgroup
2917 * @mode: mode to set on new inode
2919 * Must be called with the mutex on the parent inode held
2921 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
2922 mode_t mode)
2924 struct cgroup *cgrp;
2925 struct cgroupfs_root *root = parent->root;
2926 int err = 0;
2927 struct cgroup_subsys *ss;
2928 struct super_block *sb = root->sb;
2930 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
2931 if (!cgrp)
2932 return -ENOMEM;
2934 /* Grab a reference on the superblock so the hierarchy doesn't
2935 * get deleted on unmount if there are child cgroups. This
2936 * can be done outside cgroup_mutex, since the sb can't
2937 * disappear while someone has an open control file on the
2938 * fs */
2939 atomic_inc(&sb->s_active);
2941 mutex_lock(&cgroup_mutex);
2943 init_cgroup_housekeeping(cgrp);
2945 cgrp->parent = parent;
2946 cgrp->root = parent->root;
2947 cgrp->top_cgroup = parent->top_cgroup;
2949 if (notify_on_release(parent))
2950 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2952 for_each_subsys(root, ss) {
2953 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
2955 if (IS_ERR(css)) {
2956 err = PTR_ERR(css);
2957 goto err_destroy;
2959 init_cgroup_css(css, ss, cgrp);
2960 if (ss->use_id) {
2961 err = alloc_css_id(ss, parent, cgrp);
2962 if (err)
2963 goto err_destroy;
2965 /* At error, ->destroy() callback has to free assigned ID. */
2968 cgroup_lock_hierarchy(root);
2969 list_add(&cgrp->sibling, &cgrp->parent->children);
2970 cgroup_unlock_hierarchy(root);
2971 root->number_of_cgroups++;
2973 err = cgroup_create_dir(cgrp, dentry, mode);
2974 if (err < 0)
2975 goto err_remove;
2977 /* The cgroup directory was pre-locked for us */
2978 BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
2980 err = cgroup_populate_dir(cgrp);
2981 /* If err < 0, we have a half-filled directory - oh well ;) */
2983 mutex_unlock(&cgroup_mutex);
2984 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
2986 return 0;
2988 err_remove:
2990 cgroup_lock_hierarchy(root);
2991 list_del(&cgrp->sibling);
2992 cgroup_unlock_hierarchy(root);
2993 root->number_of_cgroups--;
2995 err_destroy:
2997 for_each_subsys(root, ss) {
2998 if (cgrp->subsys[ss->subsys_id])
2999 ss->destroy(ss, cgrp);
3002 mutex_unlock(&cgroup_mutex);
3004 /* Release the reference count that we took on the superblock */
3005 deactivate_super(sb);
3007 kfree(cgrp);
3008 return err;
3011 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
3013 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
3015 /* the vfs holds inode->i_mutex already */
3016 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
3019 static int cgroup_has_css_refs(struct cgroup *cgrp)
3021 /* Check the reference count on each subsystem. Since we
3022 * already established that there are no tasks in the
3023 * cgroup, if the css refcount is also 1, then there should
3024 * be no outstanding references, so the subsystem is safe to
3025 * destroy. We scan across all subsystems rather than using
3026 * the per-hierarchy linked list of mounted subsystems since
3027 * we can be called via check_for_release() with no
3028 * synchronization other than RCU, and the subsystem linked
3029 * list isn't RCU-safe */
3030 int i;
3031 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3032 struct cgroup_subsys *ss = subsys[i];
3033 struct cgroup_subsys_state *css;
3034 /* Skip subsystems not in this hierarchy */
3035 if (ss->root != cgrp->root)
3036 continue;
3037 css = cgrp->subsys[ss->subsys_id];
3038 /* When called from check_for_release() it's possible
3039 * that by this point the cgroup has been removed
3040 * and the css deleted. But a false-positive doesn't
3041 * matter, since it can only happen if the cgroup
3042 * has been deleted and hence no longer needs the
3043 * release agent to be called anyway. */
3044 if (css && (atomic_read(&css->refcnt) > 1))
3045 return 1;
3047 return 0;
3051 * Atomically mark all (or else none) of the cgroup's CSS objects as
3052 * CSS_REMOVED. Return true on success, or false if the cgroup has
3053 * busy subsystems. Call with cgroup_mutex held
3056 static int cgroup_clear_css_refs(struct cgroup *cgrp)
3058 struct cgroup_subsys *ss;
3059 unsigned long flags;
3060 bool failed = false;
3061 local_irq_save(flags);
3062 for_each_subsys(cgrp->root, ss) {
3063 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3064 int refcnt;
3065 while (1) {
3066 /* We can only remove a CSS with a refcnt==1 */
3067 refcnt = atomic_read(&css->refcnt);
3068 if (refcnt > 1) {
3069 failed = true;
3070 goto done;
3072 BUG_ON(!refcnt);
3074 * Drop the refcnt to 0 while we check other
3075 * subsystems. This will cause any racing
3076 * css_tryget() to spin until we set the
3077 * CSS_REMOVED bits or abort
3079 if (atomic_cmpxchg(&css->refcnt, refcnt, 0) == refcnt)
3080 break;
3081 cpu_relax();
3084 done:
3085 for_each_subsys(cgrp->root, ss) {
3086 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3087 if (failed) {
3089 * Restore old refcnt if we previously managed
3090 * to clear it from 1 to 0
3092 if (!atomic_read(&css->refcnt))
3093 atomic_set(&css->refcnt, 1);
3094 } else {
3095 /* Commit the fact that the CSS is removed */
3096 set_bit(CSS_REMOVED, &css->flags);
3099 local_irq_restore(flags);
3100 return !failed;
3103 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
3105 struct cgroup *cgrp = dentry->d_fsdata;
3106 struct dentry *d;
3107 struct cgroup *parent;
3108 DEFINE_WAIT(wait);
3109 int ret;
3111 /* the vfs holds both inode->i_mutex already */
3112 again:
3113 mutex_lock(&cgroup_mutex);
3114 if (atomic_read(&cgrp->count) != 0) {
3115 mutex_unlock(&cgroup_mutex);
3116 return -EBUSY;
3118 if (!list_empty(&cgrp->children)) {
3119 mutex_unlock(&cgroup_mutex);
3120 return -EBUSY;
3122 mutex_unlock(&cgroup_mutex);
3125 * In general, subsystem has no css->refcnt after pre_destroy(). But
3126 * in racy cases, subsystem may have to get css->refcnt after
3127 * pre_destroy() and it makes rmdir return with -EBUSY. This sometimes
3128 * make rmdir return -EBUSY too often. To avoid that, we use waitqueue
3129 * for cgroup's rmdir. CGRP_WAIT_ON_RMDIR is for synchronizing rmdir
3130 * and subsystem's reference count handling. Please see css_get/put
3131 * and css_tryget() and cgroup_wakeup_rmdir_waiter() implementation.
3133 set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3136 * Call pre_destroy handlers of subsys. Notify subsystems
3137 * that rmdir() request comes.
3139 ret = cgroup_call_pre_destroy(cgrp);
3140 if (ret) {
3141 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3142 return ret;
3145 mutex_lock(&cgroup_mutex);
3146 parent = cgrp->parent;
3147 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
3148 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3149 mutex_unlock(&cgroup_mutex);
3150 return -EBUSY;
3152 prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
3153 if (!cgroup_clear_css_refs(cgrp)) {
3154 mutex_unlock(&cgroup_mutex);
3156 * Because someone may call cgroup_wakeup_rmdir_waiter() before
3157 * prepare_to_wait(), we need to check this flag.
3159 if (test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))
3160 schedule();
3161 finish_wait(&cgroup_rmdir_waitq, &wait);
3162 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3163 if (signal_pending(current))
3164 return -EINTR;
3165 goto again;
3167 /* NO css_tryget() can success after here. */
3168 finish_wait(&cgroup_rmdir_waitq, &wait);
3169 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3171 spin_lock(&release_list_lock);
3172 set_bit(CGRP_REMOVED, &cgrp->flags);
3173 if (!list_empty(&cgrp->release_list))
3174 list_del(&cgrp->release_list);
3175 spin_unlock(&release_list_lock);
3177 cgroup_lock_hierarchy(cgrp->root);
3178 /* delete this cgroup from parent->children */
3179 list_del(&cgrp->sibling);
3180 cgroup_unlock_hierarchy(cgrp->root);
3182 spin_lock(&cgrp->dentry->d_lock);
3183 d = dget(cgrp->dentry);
3184 spin_unlock(&d->d_lock);
3186 cgroup_d_remove_dir(d);
3187 dput(d);
3189 set_bit(CGRP_RELEASABLE, &parent->flags);
3190 check_for_release(parent);
3192 mutex_unlock(&cgroup_mutex);
3193 return 0;
3196 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
3198 struct cgroup_subsys_state *css;
3200 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
3202 /* Create the top cgroup state for this subsystem */
3203 list_add(&ss->sibling, &rootnode.subsys_list);
3204 ss->root = &rootnode;
3205 css = ss->create(ss, dummytop);
3206 /* We don't handle early failures gracefully */
3207 BUG_ON(IS_ERR(css));
3208 init_cgroup_css(css, ss, dummytop);
3210 /* Update the init_css_set to contain a subsys
3211 * pointer to this state - since the subsystem is
3212 * newly registered, all tasks and hence the
3213 * init_css_set is in the subsystem's top cgroup. */
3214 init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
3216 need_forkexit_callback |= ss->fork || ss->exit;
3218 /* At system boot, before all subsystems have been
3219 * registered, no tasks have been forked, so we don't
3220 * need to invoke fork callbacks here. */
3221 BUG_ON(!list_empty(&init_task.tasks));
3223 mutex_init(&ss->hierarchy_mutex);
3224 lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
3225 ss->active = 1;
3229 * cgroup_init_early - cgroup initialization at system boot
3231 * Initialize cgroups at system boot, and initialize any
3232 * subsystems that request early init.
3234 int __init cgroup_init_early(void)
3236 int i;
3237 atomic_set(&init_css_set.refcount, 1);
3238 INIT_LIST_HEAD(&init_css_set.cg_links);
3239 INIT_LIST_HEAD(&init_css_set.tasks);
3240 INIT_HLIST_NODE(&init_css_set.hlist);
3241 css_set_count = 1;
3242 init_cgroup_root(&rootnode);
3243 root_count = 1;
3244 init_task.cgroups = &init_css_set;
3246 init_css_set_link.cg = &init_css_set;
3247 init_css_set_link.cgrp = dummytop;
3248 list_add(&init_css_set_link.cgrp_link_list,
3249 &rootnode.top_cgroup.css_sets);
3250 list_add(&init_css_set_link.cg_link_list,
3251 &init_css_set.cg_links);
3253 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
3254 INIT_HLIST_HEAD(&css_set_table[i]);
3256 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3257 struct cgroup_subsys *ss = subsys[i];
3259 BUG_ON(!ss->name);
3260 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
3261 BUG_ON(!ss->create);
3262 BUG_ON(!ss->destroy);
3263 if (ss->subsys_id != i) {
3264 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
3265 ss->name, ss->subsys_id);
3266 BUG();
3269 if (ss->early_init)
3270 cgroup_init_subsys(ss);
3272 return 0;
3276 * cgroup_init - cgroup initialization
3278 * Register cgroup filesystem and /proc file, and initialize
3279 * any subsystems that didn't request early init.
3281 int __init cgroup_init(void)
3283 int err;
3284 int i;
3285 struct hlist_head *hhead;
3287 err = bdi_init(&cgroup_backing_dev_info);
3288 if (err)
3289 return err;
3291 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3292 struct cgroup_subsys *ss = subsys[i];
3293 if (!ss->early_init)
3294 cgroup_init_subsys(ss);
3295 if (ss->use_id)
3296 cgroup_subsys_init_idr(ss);
3299 /* Add init_css_set to the hash table */
3300 hhead = css_set_hash(init_css_set.subsys);
3301 hlist_add_head(&init_css_set.hlist, hhead);
3302 BUG_ON(!init_root_id(&rootnode));
3303 err = register_filesystem(&cgroup_fs_type);
3304 if (err < 0)
3305 goto out;
3307 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
3309 out:
3310 if (err)
3311 bdi_destroy(&cgroup_backing_dev_info);
3313 return err;
3317 * proc_cgroup_show()
3318 * - Print task's cgroup paths into seq_file, one line for each hierarchy
3319 * - Used for /proc/<pid>/cgroup.
3320 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
3321 * doesn't really matter if tsk->cgroup changes after we read it,
3322 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
3323 * anyway. No need to check that tsk->cgroup != NULL, thanks to
3324 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
3325 * cgroup to top_cgroup.
3328 /* TODO: Use a proper seq_file iterator */
3329 static int proc_cgroup_show(struct seq_file *m, void *v)
3331 struct pid *pid;
3332 struct task_struct *tsk;
3333 char *buf;
3334 int retval;
3335 struct cgroupfs_root *root;
3337 retval = -ENOMEM;
3338 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3339 if (!buf)
3340 goto out;
3342 retval = -ESRCH;
3343 pid = m->private;
3344 tsk = get_pid_task(pid, PIDTYPE_PID);
3345 if (!tsk)
3346 goto out_free;
3348 retval = 0;
3350 mutex_lock(&cgroup_mutex);
3352 for_each_active_root(root) {
3353 struct cgroup_subsys *ss;
3354 struct cgroup *cgrp;
3355 int count = 0;
3357 seq_printf(m, "%d:", root->hierarchy_id);
3358 for_each_subsys(root, ss)
3359 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
3360 if (strlen(root->name))
3361 seq_printf(m, "%sname=%s", count ? "," : "",
3362 root->name);
3363 seq_putc(m, ':');
3364 cgrp = task_cgroup_from_root(tsk, root);
3365 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
3366 if (retval < 0)
3367 goto out_unlock;
3368 seq_puts(m, buf);
3369 seq_putc(m, '\n');
3372 out_unlock:
3373 mutex_unlock(&cgroup_mutex);
3374 put_task_struct(tsk);
3375 out_free:
3376 kfree(buf);
3377 out:
3378 return retval;
3381 static int cgroup_open(struct inode *inode, struct file *file)
3383 struct pid *pid = PROC_I(inode)->pid;
3384 return single_open(file, proc_cgroup_show, pid);
3387 const struct file_operations proc_cgroup_operations = {
3388 .open = cgroup_open,
3389 .read = seq_read,
3390 .llseek = seq_lseek,
3391 .release = single_release,
3394 /* Display information about each subsystem and each hierarchy */
3395 static int proc_cgroupstats_show(struct seq_file *m, void *v)
3397 int i;
3399 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
3400 mutex_lock(&cgroup_mutex);
3401 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3402 struct cgroup_subsys *ss = subsys[i];
3403 seq_printf(m, "%s\t%d\t%d\t%d\n",
3404 ss->name, ss->root->hierarchy_id,
3405 ss->root->number_of_cgroups, !ss->disabled);
3407 mutex_unlock(&cgroup_mutex);
3408 return 0;
3411 static int cgroupstats_open(struct inode *inode, struct file *file)
3413 return single_open(file, proc_cgroupstats_show, NULL);
3416 static const struct file_operations proc_cgroupstats_operations = {
3417 .open = cgroupstats_open,
3418 .read = seq_read,
3419 .llseek = seq_lseek,
3420 .release = single_release,
3424 * cgroup_fork - attach newly forked task to its parents cgroup.
3425 * @child: pointer to task_struct of forking parent process.
3427 * Description: A task inherits its parent's cgroup at fork().
3429 * A pointer to the shared css_set was automatically copied in
3430 * fork.c by dup_task_struct(). However, we ignore that copy, since
3431 * it was not made under the protection of RCU or cgroup_mutex, so
3432 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
3433 * have already changed current->cgroups, allowing the previously
3434 * referenced cgroup group to be removed and freed.
3436 * At the point that cgroup_fork() is called, 'current' is the parent
3437 * task, and the passed argument 'child' points to the child task.
3439 void cgroup_fork(struct task_struct *child)
3441 task_lock(current);
3442 child->cgroups = current->cgroups;
3443 get_css_set(child->cgroups);
3444 task_unlock(current);
3445 INIT_LIST_HEAD(&child->cg_list);
3449 * cgroup_fork_callbacks - run fork callbacks
3450 * @child: the new task
3452 * Called on a new task very soon before adding it to the
3453 * tasklist. No need to take any locks since no-one can
3454 * be operating on this task.
3456 void cgroup_fork_callbacks(struct task_struct *child)
3458 if (need_forkexit_callback) {
3459 int i;
3460 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3461 struct cgroup_subsys *ss = subsys[i];
3462 if (ss->fork)
3463 ss->fork(ss, child);
3469 * cgroup_post_fork - called on a new task after adding it to the task list
3470 * @child: the task in question
3472 * Adds the task to the list running through its css_set if necessary.
3473 * Has to be after the task is visible on the task list in case we race
3474 * with the first call to cgroup_iter_start() - to guarantee that the
3475 * new task ends up on its list.
3477 void cgroup_post_fork(struct task_struct *child)
3479 if (use_task_css_set_links) {
3480 write_lock(&css_set_lock);
3481 task_lock(child);
3482 if (list_empty(&child->cg_list))
3483 list_add(&child->cg_list, &child->cgroups->tasks);
3484 task_unlock(child);
3485 write_unlock(&css_set_lock);
3489 * cgroup_exit - detach cgroup from exiting task
3490 * @tsk: pointer to task_struct of exiting process
3491 * @run_callback: run exit callbacks?
3493 * Description: Detach cgroup from @tsk and release it.
3495 * Note that cgroups marked notify_on_release force every task in
3496 * them to take the global cgroup_mutex mutex when exiting.
3497 * This could impact scaling on very large systems. Be reluctant to
3498 * use notify_on_release cgroups where very high task exit scaling
3499 * is required on large systems.
3501 * the_top_cgroup_hack:
3503 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
3505 * We call cgroup_exit() while the task is still competent to
3506 * handle notify_on_release(), then leave the task attached to the
3507 * root cgroup in each hierarchy for the remainder of its exit.
3509 * To do this properly, we would increment the reference count on
3510 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
3511 * code we would add a second cgroup function call, to drop that
3512 * reference. This would just create an unnecessary hot spot on
3513 * the top_cgroup reference count, to no avail.
3515 * Normally, holding a reference to a cgroup without bumping its
3516 * count is unsafe. The cgroup could go away, or someone could
3517 * attach us to a different cgroup, decrementing the count on
3518 * the first cgroup that we never incremented. But in this case,
3519 * top_cgroup isn't going away, and either task has PF_EXITING set,
3520 * which wards off any cgroup_attach_task() attempts, or task is a failed
3521 * fork, never visible to cgroup_attach_task.
3523 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
3525 int i;
3526 struct css_set *cg;
3528 if (run_callbacks && need_forkexit_callback) {
3529 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3530 struct cgroup_subsys *ss = subsys[i];
3531 if (ss->exit)
3532 ss->exit(ss, tsk);
3537 * Unlink from the css_set task list if necessary.
3538 * Optimistically check cg_list before taking
3539 * css_set_lock
3541 if (!list_empty(&tsk->cg_list)) {
3542 write_lock(&css_set_lock);
3543 if (!list_empty(&tsk->cg_list))
3544 list_del(&tsk->cg_list);
3545 write_unlock(&css_set_lock);
3548 /* Reassign the task to the init_css_set. */
3549 task_lock(tsk);
3550 cg = tsk->cgroups;
3551 tsk->cgroups = &init_css_set;
3552 task_unlock(tsk);
3553 if (cg)
3554 put_css_set_taskexit(cg);
3558 * cgroup_clone - clone the cgroup the given subsystem is attached to
3559 * @tsk: the task to be moved
3560 * @subsys: the given subsystem
3561 * @nodename: the name for the new cgroup
3563 * Duplicate the current cgroup in the hierarchy that the given
3564 * subsystem is attached to, and move this task into the new
3565 * child.
3567 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
3568 char *nodename)
3570 struct dentry *dentry;
3571 int ret = 0;
3572 struct cgroup *parent, *child;
3573 struct inode *inode;
3574 struct css_set *cg;
3575 struct cgroupfs_root *root;
3576 struct cgroup_subsys *ss;
3578 /* We shouldn't be called by an unregistered subsystem */
3579 BUG_ON(!subsys->active);
3581 /* First figure out what hierarchy and cgroup we're dealing
3582 * with, and pin them so we can drop cgroup_mutex */
3583 mutex_lock(&cgroup_mutex);
3584 again:
3585 root = subsys->root;
3586 if (root == &rootnode) {
3587 mutex_unlock(&cgroup_mutex);
3588 return 0;
3591 /* Pin the hierarchy */
3592 if (!atomic_inc_not_zero(&root->sb->s_active)) {
3593 /* We race with the final deactivate_super() */
3594 mutex_unlock(&cgroup_mutex);
3595 return 0;
3598 /* Keep the cgroup alive */
3599 task_lock(tsk);
3600 parent = task_cgroup(tsk, subsys->subsys_id);
3601 cg = tsk->cgroups;
3602 get_css_set(cg);
3603 task_unlock(tsk);
3605 mutex_unlock(&cgroup_mutex);
3607 /* Now do the VFS work to create a cgroup */
3608 inode = parent->dentry->d_inode;
3610 /* Hold the parent directory mutex across this operation to
3611 * stop anyone else deleting the new cgroup */
3612 mutex_lock(&inode->i_mutex);
3613 dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
3614 if (IS_ERR(dentry)) {
3615 printk(KERN_INFO
3616 "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
3617 PTR_ERR(dentry));
3618 ret = PTR_ERR(dentry);
3619 goto out_release;
3622 /* Create the cgroup directory, which also creates the cgroup */
3623 ret = vfs_mkdir(inode, dentry, 0755);
3624 child = __d_cgrp(dentry);
3625 dput(dentry);
3626 if (ret) {
3627 printk(KERN_INFO
3628 "Failed to create cgroup %s: %d\n", nodename,
3629 ret);
3630 goto out_release;
3633 /* The cgroup now exists. Retake cgroup_mutex and check
3634 * that we're still in the same state that we thought we
3635 * were. */
3636 mutex_lock(&cgroup_mutex);
3637 if ((root != subsys->root) ||
3638 (parent != task_cgroup(tsk, subsys->subsys_id))) {
3639 /* Aargh, we raced ... */
3640 mutex_unlock(&inode->i_mutex);
3641 put_css_set(cg);
3643 deactivate_super(root->sb);
3644 /* The cgroup is still accessible in the VFS, but
3645 * we're not going to try to rmdir() it at this
3646 * point. */
3647 printk(KERN_INFO
3648 "Race in cgroup_clone() - leaking cgroup %s\n",
3649 nodename);
3650 goto again;
3653 /* do any required auto-setup */
3654 for_each_subsys(root, ss) {
3655 if (ss->post_clone)
3656 ss->post_clone(ss, child);
3659 /* All seems fine. Finish by moving the task into the new cgroup */
3660 ret = cgroup_attach_task(child, tsk);
3661 mutex_unlock(&cgroup_mutex);
3663 out_release:
3664 mutex_unlock(&inode->i_mutex);
3666 mutex_lock(&cgroup_mutex);
3667 put_css_set(cg);
3668 mutex_unlock(&cgroup_mutex);
3669 deactivate_super(root->sb);
3670 return ret;
3674 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
3675 * @cgrp: the cgroup in question
3676 * @task: the task in question
3678 * See if @cgrp is a descendant of @task's cgroup in the appropriate
3679 * hierarchy.
3681 * If we are sending in dummytop, then presumably we are creating
3682 * the top cgroup in the subsystem.
3684 * Called only by the ns (nsproxy) cgroup.
3686 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
3688 int ret;
3689 struct cgroup *target;
3691 if (cgrp == dummytop)
3692 return 1;
3694 target = task_cgroup_from_root(task, cgrp->root);
3695 while (cgrp != target && cgrp!= cgrp->top_cgroup)
3696 cgrp = cgrp->parent;
3697 ret = (cgrp == target);
3698 return ret;
3701 static void check_for_release(struct cgroup *cgrp)
3703 /* All of these checks rely on RCU to keep the cgroup
3704 * structure alive */
3705 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
3706 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
3707 /* Control Group is currently removeable. If it's not
3708 * already queued for a userspace notification, queue
3709 * it now */
3710 int need_schedule_work = 0;
3711 spin_lock(&release_list_lock);
3712 if (!cgroup_is_removed(cgrp) &&
3713 list_empty(&cgrp->release_list)) {
3714 list_add(&cgrp->release_list, &release_list);
3715 need_schedule_work = 1;
3717 spin_unlock(&release_list_lock);
3718 if (need_schedule_work)
3719 schedule_work(&release_agent_work);
3723 void __css_put(struct cgroup_subsys_state *css)
3725 struct cgroup *cgrp = css->cgroup;
3726 int val;
3727 rcu_read_lock();
3728 val = atomic_dec_return(&css->refcnt);
3729 if (val == 1) {
3730 if (notify_on_release(cgrp)) {
3731 set_bit(CGRP_RELEASABLE, &cgrp->flags);
3732 check_for_release(cgrp);
3734 cgroup_wakeup_rmdir_waiter(cgrp);
3736 rcu_read_unlock();
3737 WARN_ON_ONCE(val < 1);
3741 * Notify userspace when a cgroup is released, by running the
3742 * configured release agent with the name of the cgroup (path
3743 * relative to the root of cgroup file system) as the argument.
3745 * Most likely, this user command will try to rmdir this cgroup.
3747 * This races with the possibility that some other task will be
3748 * attached to this cgroup before it is removed, or that some other
3749 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
3750 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
3751 * unused, and this cgroup will be reprieved from its death sentence,
3752 * to continue to serve a useful existence. Next time it's released,
3753 * we will get notified again, if it still has 'notify_on_release' set.
3755 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
3756 * means only wait until the task is successfully execve()'d. The
3757 * separate release agent task is forked by call_usermodehelper(),
3758 * then control in this thread returns here, without waiting for the
3759 * release agent task. We don't bother to wait because the caller of
3760 * this routine has no use for the exit status of the release agent
3761 * task, so no sense holding our caller up for that.
3763 static void cgroup_release_agent(struct work_struct *work)
3765 BUG_ON(work != &release_agent_work);
3766 mutex_lock(&cgroup_mutex);
3767 spin_lock(&release_list_lock);
3768 while (!list_empty(&release_list)) {
3769 char *argv[3], *envp[3];
3770 int i;
3771 char *pathbuf = NULL, *agentbuf = NULL;
3772 struct cgroup *cgrp = list_entry(release_list.next,
3773 struct cgroup,
3774 release_list);
3775 list_del_init(&cgrp->release_list);
3776 spin_unlock(&release_list_lock);
3777 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3778 if (!pathbuf)
3779 goto continue_free;
3780 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
3781 goto continue_free;
3782 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
3783 if (!agentbuf)
3784 goto continue_free;
3786 i = 0;
3787 argv[i++] = agentbuf;
3788 argv[i++] = pathbuf;
3789 argv[i] = NULL;
3791 i = 0;
3792 /* minimal command environment */
3793 envp[i++] = "HOME=/";
3794 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3795 envp[i] = NULL;
3797 /* Drop the lock while we invoke the usermode helper,
3798 * since the exec could involve hitting disk and hence
3799 * be a slow process */
3800 mutex_unlock(&cgroup_mutex);
3801 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3802 mutex_lock(&cgroup_mutex);
3803 continue_free:
3804 kfree(pathbuf);
3805 kfree(agentbuf);
3806 spin_lock(&release_list_lock);
3808 spin_unlock(&release_list_lock);
3809 mutex_unlock(&cgroup_mutex);
3812 static int __init cgroup_disable(char *str)
3814 int i;
3815 char *token;
3817 while ((token = strsep(&str, ",")) != NULL) {
3818 if (!*token)
3819 continue;
3821 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3822 struct cgroup_subsys *ss = subsys[i];
3824 if (!strcmp(token, ss->name)) {
3825 ss->disabled = 1;
3826 printk(KERN_INFO "Disabling %s control group"
3827 " subsystem\n", ss->name);
3828 break;
3832 return 1;
3834 __setup("cgroup_disable=", cgroup_disable);
3837 * Functons for CSS ID.
3841 *To get ID other than 0, this should be called when !cgroup_is_removed().
3843 unsigned short css_id(struct cgroup_subsys_state *css)
3845 struct css_id *cssid = rcu_dereference(css->id);
3847 if (cssid)
3848 return cssid->id;
3849 return 0;
3852 unsigned short css_depth(struct cgroup_subsys_state *css)
3854 struct css_id *cssid = rcu_dereference(css->id);
3856 if (cssid)
3857 return cssid->depth;
3858 return 0;
3861 bool css_is_ancestor(struct cgroup_subsys_state *child,
3862 const struct cgroup_subsys_state *root)
3864 struct css_id *child_id = rcu_dereference(child->id);
3865 struct css_id *root_id = rcu_dereference(root->id);
3867 if (!child_id || !root_id || (child_id->depth < root_id->depth))
3868 return false;
3869 return child_id->stack[root_id->depth] == root_id->id;
3872 static void __free_css_id_cb(struct rcu_head *head)
3874 struct css_id *id;
3876 id = container_of(head, struct css_id, rcu_head);
3877 kfree(id);
3880 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
3882 struct css_id *id = css->id;
3883 /* When this is called before css_id initialization, id can be NULL */
3884 if (!id)
3885 return;
3887 BUG_ON(!ss->use_id);
3889 rcu_assign_pointer(id->css, NULL);
3890 rcu_assign_pointer(css->id, NULL);
3891 spin_lock(&ss->id_lock);
3892 idr_remove(&ss->idr, id->id);
3893 spin_unlock(&ss->id_lock);
3894 call_rcu(&id->rcu_head, __free_css_id_cb);
3898 * This is called by init or create(). Then, calls to this function are
3899 * always serialized (By cgroup_mutex() at create()).
3902 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
3904 struct css_id *newid;
3905 int myid, error, size;
3907 BUG_ON(!ss->use_id);
3909 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
3910 newid = kzalloc(size, GFP_KERNEL);
3911 if (!newid)
3912 return ERR_PTR(-ENOMEM);
3913 /* get id */
3914 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
3915 error = -ENOMEM;
3916 goto err_out;
3918 spin_lock(&ss->id_lock);
3919 /* Don't use 0. allocates an ID of 1-65535 */
3920 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
3921 spin_unlock(&ss->id_lock);
3923 /* Returns error when there are no free spaces for new ID.*/
3924 if (error) {
3925 error = -ENOSPC;
3926 goto err_out;
3928 if (myid > CSS_ID_MAX)
3929 goto remove_idr;
3931 newid->id = myid;
3932 newid->depth = depth;
3933 return newid;
3934 remove_idr:
3935 error = -ENOSPC;
3936 spin_lock(&ss->id_lock);
3937 idr_remove(&ss->idr, myid);
3938 spin_unlock(&ss->id_lock);
3939 err_out:
3940 kfree(newid);
3941 return ERR_PTR(error);
3945 static int __init cgroup_subsys_init_idr(struct cgroup_subsys *ss)
3947 struct css_id *newid;
3948 struct cgroup_subsys_state *rootcss;
3950 spin_lock_init(&ss->id_lock);
3951 idr_init(&ss->idr);
3953 rootcss = init_css_set.subsys[ss->subsys_id];
3954 newid = get_new_cssid(ss, 0);
3955 if (IS_ERR(newid))
3956 return PTR_ERR(newid);
3958 newid->stack[0] = newid->id;
3959 newid->css = rootcss;
3960 rootcss->id = newid;
3961 return 0;
3964 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
3965 struct cgroup *child)
3967 int subsys_id, i, depth = 0;
3968 struct cgroup_subsys_state *parent_css, *child_css;
3969 struct css_id *child_id, *parent_id = NULL;
3971 subsys_id = ss->subsys_id;
3972 parent_css = parent->subsys[subsys_id];
3973 child_css = child->subsys[subsys_id];
3974 depth = css_depth(parent_css) + 1;
3975 parent_id = parent_css->id;
3977 child_id = get_new_cssid(ss, depth);
3978 if (IS_ERR(child_id))
3979 return PTR_ERR(child_id);
3981 for (i = 0; i < depth; i++)
3982 child_id->stack[i] = parent_id->stack[i];
3983 child_id->stack[depth] = child_id->id;
3985 * child_id->css pointer will be set after this cgroup is available
3986 * see cgroup_populate_dir()
3988 rcu_assign_pointer(child_css->id, child_id);
3990 return 0;
3994 * css_lookup - lookup css by id
3995 * @ss: cgroup subsys to be looked into.
3996 * @id: the id
3998 * Returns pointer to cgroup_subsys_state if there is valid one with id.
3999 * NULL if not. Should be called under rcu_read_lock()
4001 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
4003 struct css_id *cssid = NULL;
4005 BUG_ON(!ss->use_id);
4006 cssid = idr_find(&ss->idr, id);
4008 if (unlikely(!cssid))
4009 return NULL;
4011 return rcu_dereference(cssid->css);
4015 * css_get_next - lookup next cgroup under specified hierarchy.
4016 * @ss: pointer to subsystem
4017 * @id: current position of iteration.
4018 * @root: pointer to css. search tree under this.
4019 * @foundid: position of found object.
4021 * Search next css under the specified hierarchy of rootid. Calling under
4022 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
4024 struct cgroup_subsys_state *
4025 css_get_next(struct cgroup_subsys *ss, int id,
4026 struct cgroup_subsys_state *root, int *foundid)
4028 struct cgroup_subsys_state *ret = NULL;
4029 struct css_id *tmp;
4030 int tmpid;
4031 int rootid = css_id(root);
4032 int depth = css_depth(root);
4034 if (!rootid)
4035 return NULL;
4037 BUG_ON(!ss->use_id);
4038 /* fill start point for scan */
4039 tmpid = id;
4040 while (1) {
4042 * scan next entry from bitmap(tree), tmpid is updated after
4043 * idr_get_next().
4045 spin_lock(&ss->id_lock);
4046 tmp = idr_get_next(&ss->idr, &tmpid);
4047 spin_unlock(&ss->id_lock);
4049 if (!tmp)
4050 break;
4051 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
4052 ret = rcu_dereference(tmp->css);
4053 if (ret) {
4054 *foundid = tmpid;
4055 break;
4058 /* continue to scan from next id */
4059 tmpid = tmpid + 1;
4061 return ret;
4064 #ifdef CONFIG_CGROUP_DEBUG
4065 static struct cgroup_subsys_state *debug_create(struct cgroup_subsys *ss,
4066 struct cgroup *cont)
4068 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4070 if (!css)
4071 return ERR_PTR(-ENOMEM);
4073 return css;
4076 static void debug_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
4078 kfree(cont->subsys[debug_subsys_id]);
4081 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
4083 return atomic_read(&cont->count);
4086 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
4088 return cgroup_task_count(cont);
4091 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
4093 return (u64)(unsigned long)current->cgroups;
4096 static u64 current_css_set_refcount_read(struct cgroup *cont,
4097 struct cftype *cft)
4099 u64 count;
4101 rcu_read_lock();
4102 count = atomic_read(&current->cgroups->refcount);
4103 rcu_read_unlock();
4104 return count;
4107 static int current_css_set_cg_links_read(struct cgroup *cont,
4108 struct cftype *cft,
4109 struct seq_file *seq)
4111 struct cg_cgroup_link *link;
4112 struct css_set *cg;
4114 read_lock(&css_set_lock);
4115 rcu_read_lock();
4116 cg = rcu_dereference(current->cgroups);
4117 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
4118 struct cgroup *c = link->cgrp;
4119 const char *name;
4121 if (c->dentry)
4122 name = c->dentry->d_name.name;
4123 else
4124 name = "?";
4125 seq_printf(seq, "Root %d group %s\n",
4126 c->root->hierarchy_id, name);
4128 rcu_read_unlock();
4129 read_unlock(&css_set_lock);
4130 return 0;
4133 #define MAX_TASKS_SHOWN_PER_CSS 25
4134 static int cgroup_css_links_read(struct cgroup *cont,
4135 struct cftype *cft,
4136 struct seq_file *seq)
4138 struct cg_cgroup_link *link;
4140 read_lock(&css_set_lock);
4141 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
4142 struct css_set *cg = link->cg;
4143 struct task_struct *task;
4144 int count = 0;
4145 seq_printf(seq, "css_set %p\n", cg);
4146 list_for_each_entry(task, &cg->tasks, cg_list) {
4147 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
4148 seq_puts(seq, " ...\n");
4149 break;
4150 } else {
4151 seq_printf(seq, " task %d\n",
4152 task_pid_vnr(task));
4156 read_unlock(&css_set_lock);
4157 return 0;
4160 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
4162 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
4165 static struct cftype debug_files[] = {
4167 .name = "cgroup_refcount",
4168 .read_u64 = cgroup_refcount_read,
4171 .name = "taskcount",
4172 .read_u64 = debug_taskcount_read,
4176 .name = "current_css_set",
4177 .read_u64 = current_css_set_read,
4181 .name = "current_css_set_refcount",
4182 .read_u64 = current_css_set_refcount_read,
4186 .name = "current_css_set_cg_links",
4187 .read_seq_string = current_css_set_cg_links_read,
4191 .name = "cgroup_css_links",
4192 .read_seq_string = cgroup_css_links_read,
4196 .name = "releasable",
4197 .read_u64 = releasable_read,
4201 static int debug_populate(struct cgroup_subsys *ss, struct cgroup *cont)
4203 return cgroup_add_files(cont, ss, debug_files,
4204 ARRAY_SIZE(debug_files));
4207 struct cgroup_subsys debug_subsys = {
4208 .name = "debug",
4209 .create = debug_create,
4210 .destroy = debug_destroy,
4211 .populate = debug_populate,
4212 .subsys_id = debug_subsys_id,
4214 #endif /* CONFIG_CGROUP_DEBUG */