Merge branch 'linus' into x86/urgent
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / kernel / cgroup.c
blobcd83d9933b6b85cd05bf6db17f424056d2d504fc
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/errno.h>
27 #include <linux/fs.h>
28 #include <linux/kernel.h>
29 #include <linux/list.h>
30 #include <linux/mm.h>
31 #include <linux/mutex.h>
32 #include <linux/mount.h>
33 #include <linux/pagemap.h>
34 #include <linux/proc_fs.h>
35 #include <linux/rcupdate.h>
36 #include <linux/sched.h>
37 #include <linux/backing-dev.h>
38 #include <linux/seq_file.h>
39 #include <linux/slab.h>
40 #include <linux/magic.h>
41 #include <linux/spinlock.h>
42 #include <linux/string.h>
43 #include <linux/sort.h>
44 #include <linux/kmod.h>
45 #include <linux/delayacct.h>
46 #include <linux/cgroupstats.h>
47 #include <linux/hash.h>
48 #include <linux/namei.h>
49 #include <linux/smp_lock.h>
50 #include <linux/pid_namespace.h>
52 #include <asm/atomic.h>
54 static DEFINE_MUTEX(cgroup_mutex);
56 /* Generate an array of cgroup subsystem pointers */
57 #define SUBSYS(_x) &_x ## _subsys,
59 static struct cgroup_subsys *subsys[] = {
60 #include <linux/cgroup_subsys.h>
64 * A cgroupfs_root represents the root of a cgroup hierarchy,
65 * and may be associated with a superblock to form an active
66 * hierarchy
68 struct cgroupfs_root {
69 struct super_block *sb;
72 * The bitmask of subsystems intended to be attached to this
73 * hierarchy
75 unsigned long subsys_bits;
77 /* The bitmask of subsystems currently attached to this hierarchy */
78 unsigned long actual_subsys_bits;
80 /* A list running through the attached subsystems */
81 struct list_head subsys_list;
83 /* The root cgroup for this hierarchy */
84 struct cgroup top_cgroup;
86 /* Tracks how many cgroups are currently defined in hierarchy.*/
87 int number_of_cgroups;
89 /* A list running through the active hierarchies */
90 struct list_head root_list;
92 /* Hierarchy-specific flags */
93 unsigned long flags;
95 /* The path to use for release notifications. */
96 char release_agent_path[PATH_MAX];
100 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
101 * subsystems that are otherwise unattached - it never has more than a
102 * single cgroup, and all tasks are part of that cgroup.
104 static struct cgroupfs_root rootnode;
107 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
108 * cgroup_subsys->use_id != 0.
110 #define CSS_ID_MAX (65535)
111 struct css_id {
113 * The css to which this ID points. This pointer is set to valid value
114 * after cgroup is populated. If cgroup is removed, this will be NULL.
115 * This pointer is expected to be RCU-safe because destroy()
116 * is called after synchronize_rcu(). But for safe use, css_is_removed()
117 * css_tryget() should be used for avoiding race.
119 struct cgroup_subsys_state *css;
121 * ID of this css.
123 unsigned short id;
125 * Depth in hierarchy which this ID belongs to.
127 unsigned short depth;
129 * ID is freed by RCU. (and lookup routine is RCU safe.)
131 struct rcu_head rcu_head;
133 * Hierarchy of CSS ID belongs to.
135 unsigned short stack[0]; /* Array of Length (depth+1) */
139 /* The list of hierarchy roots */
141 static LIST_HEAD(roots);
142 static int root_count;
144 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
145 #define dummytop (&rootnode.top_cgroup)
147 /* This flag indicates whether tasks in the fork and exit paths should
148 * check for fork/exit handlers to call. This avoids us having to do
149 * extra work in the fork/exit path if none of the subsystems need to
150 * be called.
152 static int need_forkexit_callback __read_mostly;
154 /* convenient tests for these bits */
155 inline int cgroup_is_removed(const struct cgroup *cgrp)
157 return test_bit(CGRP_REMOVED, &cgrp->flags);
160 /* bits in struct cgroupfs_root flags field */
161 enum {
162 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
165 static int cgroup_is_releasable(const struct cgroup *cgrp)
167 const int bits =
168 (1 << CGRP_RELEASABLE) |
169 (1 << CGRP_NOTIFY_ON_RELEASE);
170 return (cgrp->flags & bits) == bits;
173 static int notify_on_release(const struct cgroup *cgrp)
175 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
179 * for_each_subsys() allows you to iterate on each subsystem attached to
180 * an active hierarchy
182 #define for_each_subsys(_root, _ss) \
183 list_for_each_entry(_ss, &_root->subsys_list, sibling)
185 /* for_each_active_root() allows you to iterate across the active hierarchies */
186 #define for_each_active_root(_root) \
187 list_for_each_entry(_root, &roots, root_list)
189 /* the list of cgroups eligible for automatic release. Protected by
190 * release_list_lock */
191 static LIST_HEAD(release_list);
192 static DEFINE_SPINLOCK(release_list_lock);
193 static void cgroup_release_agent(struct work_struct *work);
194 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
195 static void check_for_release(struct cgroup *cgrp);
197 /* Link structure for associating css_set objects with cgroups */
198 struct cg_cgroup_link {
200 * List running through cg_cgroup_links associated with a
201 * cgroup, anchored on cgroup->css_sets
203 struct list_head cgrp_link_list;
205 * List running through cg_cgroup_links pointing at a
206 * single css_set object, anchored on css_set->cg_links
208 struct list_head cg_link_list;
209 struct css_set *cg;
212 /* The default css_set - used by init and its children prior to any
213 * hierarchies being mounted. It contains a pointer to the root state
214 * for each subsystem. Also used to anchor the list of css_sets. Not
215 * reference-counted, to improve performance when child cgroups
216 * haven't been created.
219 static struct css_set init_css_set;
220 static struct cg_cgroup_link init_css_set_link;
222 static int cgroup_subsys_init_idr(struct cgroup_subsys *ss);
224 /* css_set_lock protects the list of css_set objects, and the
225 * chain of tasks off each css_set. Nests outside task->alloc_lock
226 * due to cgroup_iter_start() */
227 static DEFINE_RWLOCK(css_set_lock);
228 static int css_set_count;
230 /* hash table for cgroup groups. This improves the performance to
231 * find an existing css_set */
232 #define CSS_SET_HASH_BITS 7
233 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
234 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
236 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
238 int i;
239 int index;
240 unsigned long tmp = 0UL;
242 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
243 tmp += (unsigned long)css[i];
244 tmp = (tmp >> 16) ^ tmp;
246 index = hash_long(tmp, CSS_SET_HASH_BITS);
248 return &css_set_table[index];
251 /* We don't maintain the lists running through each css_set to its
252 * task until after the first call to cgroup_iter_start(). This
253 * reduces the fork()/exit() overhead for people who have cgroups
254 * compiled into their kernel but not actually in use */
255 static int use_task_css_set_links __read_mostly;
257 /* When we create or destroy a css_set, the operation simply
258 * takes/releases a reference count on all the cgroups referenced
259 * by subsystems in this css_set. This can end up multiple-counting
260 * some cgroups, but that's OK - the ref-count is just a
261 * busy/not-busy indicator; ensuring that we only count each cgroup
262 * once would require taking a global lock to ensure that no
263 * subsystems moved between hierarchies while we were doing so.
265 * Possible TODO: decide at boot time based on the number of
266 * registered subsystems and the number of CPUs or NUMA nodes whether
267 * it's better for performance to ref-count every subsystem, or to
268 * take a global lock and only add one ref count to each hierarchy.
272 * unlink a css_set from the list and free it
274 static void unlink_css_set(struct css_set *cg)
276 struct cg_cgroup_link *link;
277 struct cg_cgroup_link *saved_link;
279 hlist_del(&cg->hlist);
280 css_set_count--;
282 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
283 cg_link_list) {
284 list_del(&link->cg_link_list);
285 list_del(&link->cgrp_link_list);
286 kfree(link);
290 static void __put_css_set(struct css_set *cg, int taskexit)
292 int i;
294 * Ensure that the refcount doesn't hit zero while any readers
295 * can see it. Similar to atomic_dec_and_lock(), but for an
296 * rwlock
298 if (atomic_add_unless(&cg->refcount, -1, 1))
299 return;
300 write_lock(&css_set_lock);
301 if (!atomic_dec_and_test(&cg->refcount)) {
302 write_unlock(&css_set_lock);
303 return;
305 unlink_css_set(cg);
306 write_unlock(&css_set_lock);
308 rcu_read_lock();
309 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
310 struct cgroup *cgrp = rcu_dereference(cg->subsys[i]->cgroup);
311 if (atomic_dec_and_test(&cgrp->count) &&
312 notify_on_release(cgrp)) {
313 if (taskexit)
314 set_bit(CGRP_RELEASABLE, &cgrp->flags);
315 check_for_release(cgrp);
318 rcu_read_unlock();
319 kfree(cg);
323 * refcounted get/put for css_set objects
325 static inline void get_css_set(struct css_set *cg)
327 atomic_inc(&cg->refcount);
330 static inline void put_css_set(struct css_set *cg)
332 __put_css_set(cg, 0);
335 static inline void put_css_set_taskexit(struct css_set *cg)
337 __put_css_set(cg, 1);
341 * find_existing_css_set() is a helper for
342 * find_css_set(), and checks to see whether an existing
343 * css_set is suitable.
345 * oldcg: the cgroup group that we're using before the cgroup
346 * transition
348 * cgrp: the cgroup that we're moving into
350 * template: location in which to build the desired set of subsystem
351 * state objects for the new cgroup group
353 static struct css_set *find_existing_css_set(
354 struct css_set *oldcg,
355 struct cgroup *cgrp,
356 struct cgroup_subsys_state *template[])
358 int i;
359 struct cgroupfs_root *root = cgrp->root;
360 struct hlist_head *hhead;
361 struct hlist_node *node;
362 struct css_set *cg;
364 /* Built the set of subsystem state objects that we want to
365 * see in the new css_set */
366 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
367 if (root->subsys_bits & (1UL << i)) {
368 /* Subsystem is in this hierarchy. So we want
369 * the subsystem state from the new
370 * cgroup */
371 template[i] = cgrp->subsys[i];
372 } else {
373 /* Subsystem is not in this hierarchy, so we
374 * don't want to change the subsystem state */
375 template[i] = oldcg->subsys[i];
379 hhead = css_set_hash(template);
380 hlist_for_each_entry(cg, node, hhead, hlist) {
381 if (!memcmp(template, cg->subsys, sizeof(cg->subsys))) {
382 /* All subsystems matched */
383 return cg;
387 /* No existing cgroup group matched */
388 return NULL;
391 static void free_cg_links(struct list_head *tmp)
393 struct cg_cgroup_link *link;
394 struct cg_cgroup_link *saved_link;
396 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
397 list_del(&link->cgrp_link_list);
398 kfree(link);
403 * allocate_cg_links() allocates "count" cg_cgroup_link structures
404 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
405 * success or a negative error
407 static int allocate_cg_links(int count, struct list_head *tmp)
409 struct cg_cgroup_link *link;
410 int i;
411 INIT_LIST_HEAD(tmp);
412 for (i = 0; i < count; i++) {
413 link = kmalloc(sizeof(*link), GFP_KERNEL);
414 if (!link) {
415 free_cg_links(tmp);
416 return -ENOMEM;
418 list_add(&link->cgrp_link_list, tmp);
420 return 0;
424 * link_css_set - a helper function to link a css_set to a cgroup
425 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
426 * @cg: the css_set to be linked
427 * @cgrp: the destination cgroup
429 static void link_css_set(struct list_head *tmp_cg_links,
430 struct css_set *cg, struct cgroup *cgrp)
432 struct cg_cgroup_link *link;
434 BUG_ON(list_empty(tmp_cg_links));
435 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
436 cgrp_link_list);
437 link->cg = cg;
438 list_move(&link->cgrp_link_list, &cgrp->css_sets);
439 list_add(&link->cg_link_list, &cg->cg_links);
443 * find_css_set() takes an existing cgroup group and a
444 * cgroup object, and returns a css_set object that's
445 * equivalent to the old group, but with the given cgroup
446 * substituted into the appropriate hierarchy. Must be called with
447 * cgroup_mutex held
449 static struct css_set *find_css_set(
450 struct css_set *oldcg, struct cgroup *cgrp)
452 struct css_set *res;
453 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
454 int i;
456 struct list_head tmp_cg_links;
458 struct hlist_head *hhead;
460 /* First see if we already have a cgroup group that matches
461 * the desired set */
462 read_lock(&css_set_lock);
463 res = find_existing_css_set(oldcg, cgrp, template);
464 if (res)
465 get_css_set(res);
466 read_unlock(&css_set_lock);
468 if (res)
469 return res;
471 res = kmalloc(sizeof(*res), GFP_KERNEL);
472 if (!res)
473 return NULL;
475 /* Allocate all the cg_cgroup_link objects that we'll need */
476 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
477 kfree(res);
478 return NULL;
481 atomic_set(&res->refcount, 1);
482 INIT_LIST_HEAD(&res->cg_links);
483 INIT_LIST_HEAD(&res->tasks);
484 INIT_HLIST_NODE(&res->hlist);
486 /* Copy the set of subsystem state objects generated in
487 * find_existing_css_set() */
488 memcpy(res->subsys, template, sizeof(res->subsys));
490 write_lock(&css_set_lock);
491 /* Add reference counts and links from the new css_set. */
492 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
493 struct cgroup *cgrp = res->subsys[i]->cgroup;
494 struct cgroup_subsys *ss = subsys[i];
495 atomic_inc(&cgrp->count);
497 * We want to add a link once per cgroup, so we
498 * only do it for the first subsystem in each
499 * hierarchy
501 if (ss->root->subsys_list.next == &ss->sibling)
502 link_css_set(&tmp_cg_links, res, cgrp);
504 if (list_empty(&rootnode.subsys_list))
505 link_css_set(&tmp_cg_links, res, dummytop);
507 BUG_ON(!list_empty(&tmp_cg_links));
509 css_set_count++;
511 /* Add this cgroup group to the hash table */
512 hhead = css_set_hash(res->subsys);
513 hlist_add_head(&res->hlist, hhead);
515 write_unlock(&css_set_lock);
517 return res;
521 * There is one global cgroup mutex. We also require taking
522 * task_lock() when dereferencing a task's cgroup subsys pointers.
523 * See "The task_lock() exception", at the end of this comment.
525 * A task must hold cgroup_mutex to modify cgroups.
527 * Any task can increment and decrement the count field without lock.
528 * So in general, code holding cgroup_mutex can't rely on the count
529 * field not changing. However, if the count goes to zero, then only
530 * cgroup_attach_task() can increment it again. Because a count of zero
531 * means that no tasks are currently attached, therefore there is no
532 * way a task attached to that cgroup can fork (the other way to
533 * increment the count). So code holding cgroup_mutex can safely
534 * assume that if the count is zero, it will stay zero. Similarly, if
535 * a task holds cgroup_mutex on a cgroup with zero count, it
536 * knows that the cgroup won't be removed, as cgroup_rmdir()
537 * needs that mutex.
539 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
540 * (usually) take cgroup_mutex. These are the two most performance
541 * critical pieces of code here. The exception occurs on cgroup_exit(),
542 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
543 * is taken, and if the cgroup count is zero, a usermode call made
544 * to the release agent with the name of the cgroup (path relative to
545 * the root of cgroup file system) as the argument.
547 * A cgroup can only be deleted if both its 'count' of using tasks
548 * is zero, and its list of 'children' cgroups is empty. Since all
549 * tasks in the system use _some_ cgroup, and since there is always at
550 * least one task in the system (init, pid == 1), therefore, top_cgroup
551 * always has either children cgroups and/or using tasks. So we don't
552 * need a special hack to ensure that top_cgroup cannot be deleted.
554 * The task_lock() exception
556 * The need for this exception arises from the action of
557 * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
558 * another. It does so using cgroup_mutex, however there are
559 * several performance critical places that need to reference
560 * task->cgroup without the expense of grabbing a system global
561 * mutex. Therefore except as noted below, when dereferencing or, as
562 * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
563 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
564 * the task_struct routinely used for such matters.
566 * P.S. One more locking exception. RCU is used to guard the
567 * update of a tasks cgroup pointer by cgroup_attach_task()
571 * cgroup_lock - lock out any changes to cgroup structures
574 void cgroup_lock(void)
576 mutex_lock(&cgroup_mutex);
580 * cgroup_unlock - release lock on cgroup changes
582 * Undo the lock taken in a previous cgroup_lock() call.
584 void cgroup_unlock(void)
586 mutex_unlock(&cgroup_mutex);
590 * A couple of forward declarations required, due to cyclic reference loop:
591 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
592 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
593 * -> cgroup_mkdir.
596 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
597 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
598 static int cgroup_populate_dir(struct cgroup *cgrp);
599 static const struct inode_operations cgroup_dir_inode_operations;
600 static struct file_operations proc_cgroupstats_operations;
602 static struct backing_dev_info cgroup_backing_dev_info = {
603 .name = "cgroup",
604 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
607 static int alloc_css_id(struct cgroup_subsys *ss,
608 struct cgroup *parent, struct cgroup *child);
610 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
612 struct inode *inode = new_inode(sb);
614 if (inode) {
615 inode->i_mode = mode;
616 inode->i_uid = current_fsuid();
617 inode->i_gid = current_fsgid();
618 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
619 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
621 return inode;
625 * Call subsys's pre_destroy handler.
626 * This is called before css refcnt check.
628 static int cgroup_call_pre_destroy(struct cgroup *cgrp)
630 struct cgroup_subsys *ss;
631 int ret = 0;
633 for_each_subsys(cgrp->root, ss)
634 if (ss->pre_destroy) {
635 ret = ss->pre_destroy(ss, cgrp);
636 if (ret)
637 break;
639 return ret;
642 static void free_cgroup_rcu(struct rcu_head *obj)
644 struct cgroup *cgrp = container_of(obj, struct cgroup, rcu_head);
646 kfree(cgrp);
649 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
651 /* is dentry a directory ? if so, kfree() associated cgroup */
652 if (S_ISDIR(inode->i_mode)) {
653 struct cgroup *cgrp = dentry->d_fsdata;
654 struct cgroup_subsys *ss;
655 BUG_ON(!(cgroup_is_removed(cgrp)));
656 /* It's possible for external users to be holding css
657 * reference counts on a cgroup; css_put() needs to
658 * be able to access the cgroup after decrementing
659 * the reference count in order to know if it needs to
660 * queue the cgroup to be handled by the release
661 * agent */
662 synchronize_rcu();
664 mutex_lock(&cgroup_mutex);
666 * Release the subsystem state objects.
668 for_each_subsys(cgrp->root, ss)
669 ss->destroy(ss, cgrp);
671 cgrp->root->number_of_cgroups--;
672 mutex_unlock(&cgroup_mutex);
675 * Drop the active superblock reference that we took when we
676 * created the cgroup
678 deactivate_super(cgrp->root->sb);
680 call_rcu(&cgrp->rcu_head, free_cgroup_rcu);
682 iput(inode);
685 static void remove_dir(struct dentry *d)
687 struct dentry *parent = dget(d->d_parent);
689 d_delete(d);
690 simple_rmdir(parent->d_inode, d);
691 dput(parent);
694 static void cgroup_clear_directory(struct dentry *dentry)
696 struct list_head *node;
698 BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
699 spin_lock(&dcache_lock);
700 node = dentry->d_subdirs.next;
701 while (node != &dentry->d_subdirs) {
702 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
703 list_del_init(node);
704 if (d->d_inode) {
705 /* This should never be called on a cgroup
706 * directory with child cgroups */
707 BUG_ON(d->d_inode->i_mode & S_IFDIR);
708 d = dget_locked(d);
709 spin_unlock(&dcache_lock);
710 d_delete(d);
711 simple_unlink(dentry->d_inode, d);
712 dput(d);
713 spin_lock(&dcache_lock);
715 node = dentry->d_subdirs.next;
717 spin_unlock(&dcache_lock);
721 * NOTE : the dentry must have been dget()'ed
723 static void cgroup_d_remove_dir(struct dentry *dentry)
725 cgroup_clear_directory(dentry);
727 spin_lock(&dcache_lock);
728 list_del_init(&dentry->d_u.d_child);
729 spin_unlock(&dcache_lock);
730 remove_dir(dentry);
734 * A queue for waiters to do rmdir() cgroup. A tasks will sleep when
735 * cgroup->count == 0 && list_empty(&cgroup->children) && subsys has some
736 * reference to css->refcnt. In general, this refcnt is expected to goes down
737 * to zero, soon.
739 * CGRP_WAIT_ON_RMDIR flag is set under cgroup's inode->i_mutex;
741 DECLARE_WAIT_QUEUE_HEAD(cgroup_rmdir_waitq);
743 static void cgroup_wakeup_rmdir_waiter(struct cgroup *cgrp)
745 if (unlikely(test_and_clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags)))
746 wake_up_all(&cgroup_rmdir_waitq);
749 void cgroup_exclude_rmdir(struct cgroup_subsys_state *css)
751 css_get(css);
754 void cgroup_release_and_wakeup_rmdir(struct cgroup_subsys_state *css)
756 cgroup_wakeup_rmdir_waiter(css->cgroup);
757 css_put(css);
761 static int rebind_subsystems(struct cgroupfs_root *root,
762 unsigned long final_bits)
764 unsigned long added_bits, removed_bits;
765 struct cgroup *cgrp = &root->top_cgroup;
766 int i;
768 removed_bits = root->actual_subsys_bits & ~final_bits;
769 added_bits = final_bits & ~root->actual_subsys_bits;
770 /* Check that any added subsystems are currently free */
771 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
772 unsigned long bit = 1UL << i;
773 struct cgroup_subsys *ss = subsys[i];
774 if (!(bit & added_bits))
775 continue;
776 if (ss->root != &rootnode) {
777 /* Subsystem isn't free */
778 return -EBUSY;
782 /* Currently we don't handle adding/removing subsystems when
783 * any child cgroups exist. This is theoretically supportable
784 * but involves complex error handling, so it's being left until
785 * later */
786 if (root->number_of_cgroups > 1)
787 return -EBUSY;
789 /* Process each subsystem */
790 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
791 struct cgroup_subsys *ss = subsys[i];
792 unsigned long bit = 1UL << i;
793 if (bit & added_bits) {
794 /* We're binding this subsystem to this hierarchy */
795 BUG_ON(cgrp->subsys[i]);
796 BUG_ON(!dummytop->subsys[i]);
797 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
798 mutex_lock(&ss->hierarchy_mutex);
799 cgrp->subsys[i] = dummytop->subsys[i];
800 cgrp->subsys[i]->cgroup = cgrp;
801 list_move(&ss->sibling, &root->subsys_list);
802 ss->root = root;
803 if (ss->bind)
804 ss->bind(ss, cgrp);
805 mutex_unlock(&ss->hierarchy_mutex);
806 } else if (bit & removed_bits) {
807 /* We're removing this subsystem */
808 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
809 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
810 mutex_lock(&ss->hierarchy_mutex);
811 if (ss->bind)
812 ss->bind(ss, dummytop);
813 dummytop->subsys[i]->cgroup = dummytop;
814 cgrp->subsys[i] = NULL;
815 subsys[i]->root = &rootnode;
816 list_move(&ss->sibling, &rootnode.subsys_list);
817 mutex_unlock(&ss->hierarchy_mutex);
818 } else if (bit & final_bits) {
819 /* Subsystem state should already exist */
820 BUG_ON(!cgrp->subsys[i]);
821 } else {
822 /* Subsystem state shouldn't exist */
823 BUG_ON(cgrp->subsys[i]);
826 root->subsys_bits = root->actual_subsys_bits = final_bits;
827 synchronize_rcu();
829 return 0;
832 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
834 struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
835 struct cgroup_subsys *ss;
837 mutex_lock(&cgroup_mutex);
838 for_each_subsys(root, ss)
839 seq_printf(seq, ",%s", ss->name);
840 if (test_bit(ROOT_NOPREFIX, &root->flags))
841 seq_puts(seq, ",noprefix");
842 if (strlen(root->release_agent_path))
843 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
844 mutex_unlock(&cgroup_mutex);
845 return 0;
848 struct cgroup_sb_opts {
849 unsigned long subsys_bits;
850 unsigned long flags;
851 char *release_agent;
854 /* Convert a hierarchy specifier into a bitmask of subsystems and
855 * flags. */
856 static int parse_cgroupfs_options(char *data,
857 struct cgroup_sb_opts *opts)
859 char *token, *o = data ?: "all";
860 unsigned long mask = (unsigned long)-1;
862 #ifdef CONFIG_CPUSETS
863 mask = ~(1UL << cpuset_subsys_id);
864 #endif
866 opts->subsys_bits = 0;
867 opts->flags = 0;
868 opts->release_agent = NULL;
870 while ((token = strsep(&o, ",")) != NULL) {
871 if (!*token)
872 return -EINVAL;
873 if (!strcmp(token, "all")) {
874 /* Add all non-disabled subsystems */
875 int i;
876 opts->subsys_bits = 0;
877 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
878 struct cgroup_subsys *ss = subsys[i];
879 if (!ss->disabled)
880 opts->subsys_bits |= 1ul << i;
882 } else if (!strcmp(token, "noprefix")) {
883 set_bit(ROOT_NOPREFIX, &opts->flags);
884 } else if (!strncmp(token, "release_agent=", 14)) {
885 /* Specifying two release agents is forbidden */
886 if (opts->release_agent)
887 return -EINVAL;
888 opts->release_agent = kzalloc(PATH_MAX, GFP_KERNEL);
889 if (!opts->release_agent)
890 return -ENOMEM;
891 strncpy(opts->release_agent, token + 14, PATH_MAX - 1);
892 opts->release_agent[PATH_MAX - 1] = 0;
893 } else {
894 struct cgroup_subsys *ss;
895 int i;
896 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
897 ss = subsys[i];
898 if (!strcmp(token, ss->name)) {
899 if (!ss->disabled)
900 set_bit(i, &opts->subsys_bits);
901 break;
904 if (i == CGROUP_SUBSYS_COUNT)
905 return -ENOENT;
910 * Option noprefix was introduced just for backward compatibility
911 * with the old cpuset, so we allow noprefix only if mounting just
912 * the cpuset subsystem.
914 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
915 (opts->subsys_bits & mask))
916 return -EINVAL;
918 /* We can't have an empty hierarchy */
919 if (!opts->subsys_bits)
920 return -EINVAL;
922 return 0;
925 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
927 int ret = 0;
928 struct cgroupfs_root *root = sb->s_fs_info;
929 struct cgroup *cgrp = &root->top_cgroup;
930 struct cgroup_sb_opts opts;
932 lock_kernel();
933 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
934 mutex_lock(&cgroup_mutex);
936 /* See what subsystems are wanted */
937 ret = parse_cgroupfs_options(data, &opts);
938 if (ret)
939 goto out_unlock;
941 /* Don't allow flags to change at remount */
942 if (opts.flags != root->flags) {
943 ret = -EINVAL;
944 goto out_unlock;
947 ret = rebind_subsystems(root, opts.subsys_bits);
948 if (ret)
949 goto out_unlock;
951 /* (re)populate subsystem files */
952 cgroup_populate_dir(cgrp);
954 if (opts.release_agent)
955 strcpy(root->release_agent_path, opts.release_agent);
956 out_unlock:
957 kfree(opts.release_agent);
958 mutex_unlock(&cgroup_mutex);
959 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
960 unlock_kernel();
961 return ret;
964 static const struct super_operations cgroup_ops = {
965 .statfs = simple_statfs,
966 .drop_inode = generic_delete_inode,
967 .show_options = cgroup_show_options,
968 .remount_fs = cgroup_remount,
971 static void init_cgroup_housekeeping(struct cgroup *cgrp)
973 INIT_LIST_HEAD(&cgrp->sibling);
974 INIT_LIST_HEAD(&cgrp->children);
975 INIT_LIST_HEAD(&cgrp->css_sets);
976 INIT_LIST_HEAD(&cgrp->release_list);
977 INIT_LIST_HEAD(&cgrp->pids_list);
978 init_rwsem(&cgrp->pids_mutex);
980 static void init_cgroup_root(struct cgroupfs_root *root)
982 struct cgroup *cgrp = &root->top_cgroup;
983 INIT_LIST_HEAD(&root->subsys_list);
984 INIT_LIST_HEAD(&root->root_list);
985 root->number_of_cgroups = 1;
986 cgrp->root = root;
987 cgrp->top_cgroup = cgrp;
988 init_cgroup_housekeeping(cgrp);
991 static int cgroup_test_super(struct super_block *sb, void *data)
993 struct cgroupfs_root *new = data;
994 struct cgroupfs_root *root = sb->s_fs_info;
996 /* First check subsystems */
997 if (new->subsys_bits != root->subsys_bits)
998 return 0;
1000 /* Next check flags */
1001 if (new->flags != root->flags)
1002 return 0;
1004 return 1;
1007 static int cgroup_set_super(struct super_block *sb, void *data)
1009 int ret;
1010 struct cgroupfs_root *root = data;
1012 ret = set_anon_super(sb, NULL);
1013 if (ret)
1014 return ret;
1016 sb->s_fs_info = root;
1017 root->sb = sb;
1019 sb->s_blocksize = PAGE_CACHE_SIZE;
1020 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1021 sb->s_magic = CGROUP_SUPER_MAGIC;
1022 sb->s_op = &cgroup_ops;
1024 return 0;
1027 static int cgroup_get_rootdir(struct super_block *sb)
1029 struct inode *inode =
1030 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1031 struct dentry *dentry;
1033 if (!inode)
1034 return -ENOMEM;
1036 inode->i_fop = &simple_dir_operations;
1037 inode->i_op = &cgroup_dir_inode_operations;
1038 /* directories start off with i_nlink == 2 (for "." entry) */
1039 inc_nlink(inode);
1040 dentry = d_alloc_root(inode);
1041 if (!dentry) {
1042 iput(inode);
1043 return -ENOMEM;
1045 sb->s_root = dentry;
1046 return 0;
1049 static int cgroup_get_sb(struct file_system_type *fs_type,
1050 int flags, const char *unused_dev_name,
1051 void *data, struct vfsmount *mnt)
1053 struct cgroup_sb_opts opts;
1054 int ret = 0;
1055 struct super_block *sb;
1056 struct cgroupfs_root *root;
1057 struct list_head tmp_cg_links;
1059 /* First find the desired set of subsystems */
1060 ret = parse_cgroupfs_options(data, &opts);
1061 if (ret) {
1062 kfree(opts.release_agent);
1063 return ret;
1066 root = kzalloc(sizeof(*root), GFP_KERNEL);
1067 if (!root) {
1068 kfree(opts.release_agent);
1069 return -ENOMEM;
1072 init_cgroup_root(root);
1073 root->subsys_bits = opts.subsys_bits;
1074 root->flags = opts.flags;
1075 if (opts.release_agent) {
1076 strcpy(root->release_agent_path, opts.release_agent);
1077 kfree(opts.release_agent);
1080 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, root);
1082 if (IS_ERR(sb)) {
1083 kfree(root);
1084 return PTR_ERR(sb);
1087 if (sb->s_fs_info != root) {
1088 /* Reusing an existing superblock */
1089 BUG_ON(sb->s_root == NULL);
1090 kfree(root);
1091 root = NULL;
1092 } else {
1093 /* New superblock */
1094 struct cgroup *root_cgrp = &root->top_cgroup;
1095 struct inode *inode;
1096 int i;
1098 BUG_ON(sb->s_root != NULL);
1100 ret = cgroup_get_rootdir(sb);
1101 if (ret)
1102 goto drop_new_super;
1103 inode = sb->s_root->d_inode;
1105 mutex_lock(&inode->i_mutex);
1106 mutex_lock(&cgroup_mutex);
1109 * We're accessing css_set_count without locking
1110 * css_set_lock here, but that's OK - it can only be
1111 * increased by someone holding cgroup_lock, and
1112 * that's us. The worst that can happen is that we
1113 * have some link structures left over
1115 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1116 if (ret) {
1117 mutex_unlock(&cgroup_mutex);
1118 mutex_unlock(&inode->i_mutex);
1119 goto drop_new_super;
1122 ret = rebind_subsystems(root, root->subsys_bits);
1123 if (ret == -EBUSY) {
1124 mutex_unlock(&cgroup_mutex);
1125 mutex_unlock(&inode->i_mutex);
1126 goto free_cg_links;
1129 /* EBUSY should be the only error here */
1130 BUG_ON(ret);
1132 list_add(&root->root_list, &roots);
1133 root_count++;
1135 sb->s_root->d_fsdata = root_cgrp;
1136 root->top_cgroup.dentry = sb->s_root;
1138 /* Link the top cgroup in this hierarchy into all
1139 * the css_set objects */
1140 write_lock(&css_set_lock);
1141 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1142 struct hlist_head *hhead = &css_set_table[i];
1143 struct hlist_node *node;
1144 struct css_set *cg;
1146 hlist_for_each_entry(cg, node, hhead, hlist)
1147 link_css_set(&tmp_cg_links, cg, root_cgrp);
1149 write_unlock(&css_set_lock);
1151 free_cg_links(&tmp_cg_links);
1153 BUG_ON(!list_empty(&root_cgrp->sibling));
1154 BUG_ON(!list_empty(&root_cgrp->children));
1155 BUG_ON(root->number_of_cgroups != 1);
1157 cgroup_populate_dir(root_cgrp);
1158 mutex_unlock(&inode->i_mutex);
1159 mutex_unlock(&cgroup_mutex);
1162 simple_set_mnt(mnt, sb);
1163 return 0;
1165 free_cg_links:
1166 free_cg_links(&tmp_cg_links);
1167 drop_new_super:
1168 deactivate_locked_super(sb);
1169 return ret;
1172 static void cgroup_kill_sb(struct super_block *sb) {
1173 struct cgroupfs_root *root = sb->s_fs_info;
1174 struct cgroup *cgrp = &root->top_cgroup;
1175 int ret;
1176 struct cg_cgroup_link *link;
1177 struct cg_cgroup_link *saved_link;
1179 BUG_ON(!root);
1181 BUG_ON(root->number_of_cgroups != 1);
1182 BUG_ON(!list_empty(&cgrp->children));
1183 BUG_ON(!list_empty(&cgrp->sibling));
1185 mutex_lock(&cgroup_mutex);
1187 /* Rebind all subsystems back to the default hierarchy */
1188 ret = rebind_subsystems(root, 0);
1189 /* Shouldn't be able to fail ... */
1190 BUG_ON(ret);
1193 * Release all the links from css_sets to this hierarchy's
1194 * root cgroup
1196 write_lock(&css_set_lock);
1198 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1199 cgrp_link_list) {
1200 list_del(&link->cg_link_list);
1201 list_del(&link->cgrp_link_list);
1202 kfree(link);
1204 write_unlock(&css_set_lock);
1206 if (!list_empty(&root->root_list)) {
1207 list_del(&root->root_list);
1208 root_count--;
1211 mutex_unlock(&cgroup_mutex);
1213 kill_litter_super(sb);
1214 kfree(root);
1217 static struct file_system_type cgroup_fs_type = {
1218 .name = "cgroup",
1219 .get_sb = cgroup_get_sb,
1220 .kill_sb = cgroup_kill_sb,
1223 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1225 return dentry->d_fsdata;
1228 static inline struct cftype *__d_cft(struct dentry *dentry)
1230 return dentry->d_fsdata;
1234 * cgroup_path - generate the path of a cgroup
1235 * @cgrp: the cgroup in question
1236 * @buf: the buffer to write the path into
1237 * @buflen: the length of the buffer
1239 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1240 * reference. Writes path of cgroup into buf. Returns 0 on success,
1241 * -errno on error.
1243 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1245 char *start;
1246 struct dentry *dentry = rcu_dereference(cgrp->dentry);
1248 if (!dentry || cgrp == dummytop) {
1250 * Inactive subsystems have no dentry for their root
1251 * cgroup
1253 strcpy(buf, "/");
1254 return 0;
1257 start = buf + buflen;
1259 *--start = '\0';
1260 for (;;) {
1261 int len = dentry->d_name.len;
1262 if ((start -= len) < buf)
1263 return -ENAMETOOLONG;
1264 memcpy(start, cgrp->dentry->d_name.name, len);
1265 cgrp = cgrp->parent;
1266 if (!cgrp)
1267 break;
1268 dentry = rcu_dereference(cgrp->dentry);
1269 if (!cgrp->parent)
1270 continue;
1271 if (--start < buf)
1272 return -ENAMETOOLONG;
1273 *start = '/';
1275 memmove(buf, start, buf + buflen - start);
1276 return 0;
1280 * Return the first subsystem attached to a cgroup's hierarchy, and
1281 * its subsystem id.
1284 static void get_first_subsys(const struct cgroup *cgrp,
1285 struct cgroup_subsys_state **css, int *subsys_id)
1287 const struct cgroupfs_root *root = cgrp->root;
1288 const struct cgroup_subsys *test_ss;
1289 BUG_ON(list_empty(&root->subsys_list));
1290 test_ss = list_entry(root->subsys_list.next,
1291 struct cgroup_subsys, sibling);
1292 if (css) {
1293 *css = cgrp->subsys[test_ss->subsys_id];
1294 BUG_ON(!*css);
1296 if (subsys_id)
1297 *subsys_id = test_ss->subsys_id;
1301 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1302 * @cgrp: the cgroup the task is attaching to
1303 * @tsk: the task to be attached
1305 * Call holding cgroup_mutex. May take task_lock of
1306 * the task 'tsk' during call.
1308 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1310 int retval = 0;
1311 struct cgroup_subsys *ss;
1312 struct cgroup *oldcgrp;
1313 struct css_set *cg;
1314 struct css_set *newcg;
1315 struct cgroupfs_root *root = cgrp->root;
1316 int subsys_id;
1318 get_first_subsys(cgrp, NULL, &subsys_id);
1320 /* Nothing to do if the task is already in that cgroup */
1321 oldcgrp = task_cgroup(tsk, subsys_id);
1322 if (cgrp == oldcgrp)
1323 return 0;
1325 for_each_subsys(root, ss) {
1326 if (ss->can_attach) {
1327 retval = ss->can_attach(ss, cgrp, tsk);
1328 if (retval)
1329 return retval;
1333 task_lock(tsk);
1334 cg = tsk->cgroups;
1335 get_css_set(cg);
1336 task_unlock(tsk);
1338 * Locate or allocate a new css_set for this task,
1339 * based on its final set of cgroups
1341 newcg = find_css_set(cg, cgrp);
1342 put_css_set(cg);
1343 if (!newcg)
1344 return -ENOMEM;
1346 task_lock(tsk);
1347 if (tsk->flags & PF_EXITING) {
1348 task_unlock(tsk);
1349 put_css_set(newcg);
1350 return -ESRCH;
1352 rcu_assign_pointer(tsk->cgroups, newcg);
1353 task_unlock(tsk);
1355 /* Update the css_set linked lists if we're using them */
1356 write_lock(&css_set_lock);
1357 if (!list_empty(&tsk->cg_list)) {
1358 list_del(&tsk->cg_list);
1359 list_add(&tsk->cg_list, &newcg->tasks);
1361 write_unlock(&css_set_lock);
1363 for_each_subsys(root, ss) {
1364 if (ss->attach)
1365 ss->attach(ss, cgrp, oldcgrp, tsk);
1367 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1368 synchronize_rcu();
1369 put_css_set(cg);
1372 * wake up rmdir() waiter. the rmdir should fail since the cgroup
1373 * is no longer empty.
1375 cgroup_wakeup_rmdir_waiter(cgrp);
1376 return 0;
1380 * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
1381 * held. May take task_lock of task
1383 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
1385 struct task_struct *tsk;
1386 const struct cred *cred = current_cred(), *tcred;
1387 int ret;
1389 if (pid) {
1390 rcu_read_lock();
1391 tsk = find_task_by_vpid(pid);
1392 if (!tsk || tsk->flags & PF_EXITING) {
1393 rcu_read_unlock();
1394 return -ESRCH;
1397 tcred = __task_cred(tsk);
1398 if (cred->euid &&
1399 cred->euid != tcred->uid &&
1400 cred->euid != tcred->suid) {
1401 rcu_read_unlock();
1402 return -EACCES;
1404 get_task_struct(tsk);
1405 rcu_read_unlock();
1406 } else {
1407 tsk = current;
1408 get_task_struct(tsk);
1411 ret = cgroup_attach_task(cgrp, tsk);
1412 put_task_struct(tsk);
1413 return ret;
1416 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
1418 int ret;
1419 if (!cgroup_lock_live_group(cgrp))
1420 return -ENODEV;
1421 ret = attach_task_by_pid(cgrp, pid);
1422 cgroup_unlock();
1423 return ret;
1426 /* The various types of files and directories in a cgroup file system */
1427 enum cgroup_filetype {
1428 FILE_ROOT,
1429 FILE_DIR,
1430 FILE_TASKLIST,
1431 FILE_NOTIFY_ON_RELEASE,
1432 FILE_RELEASE_AGENT,
1436 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1437 * @cgrp: the cgroup to be checked for liveness
1439 * On success, returns true; the lock should be later released with
1440 * cgroup_unlock(). On failure returns false with no lock held.
1442 bool cgroup_lock_live_group(struct cgroup *cgrp)
1444 mutex_lock(&cgroup_mutex);
1445 if (cgroup_is_removed(cgrp)) {
1446 mutex_unlock(&cgroup_mutex);
1447 return false;
1449 return true;
1452 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1453 const char *buffer)
1455 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1456 if (!cgroup_lock_live_group(cgrp))
1457 return -ENODEV;
1458 strcpy(cgrp->root->release_agent_path, buffer);
1459 cgroup_unlock();
1460 return 0;
1463 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1464 struct seq_file *seq)
1466 if (!cgroup_lock_live_group(cgrp))
1467 return -ENODEV;
1468 seq_puts(seq, cgrp->root->release_agent_path);
1469 seq_putc(seq, '\n');
1470 cgroup_unlock();
1471 return 0;
1474 /* A buffer size big enough for numbers or short strings */
1475 #define CGROUP_LOCAL_BUFFER_SIZE 64
1477 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1478 struct file *file,
1479 const char __user *userbuf,
1480 size_t nbytes, loff_t *unused_ppos)
1482 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1483 int retval = 0;
1484 char *end;
1486 if (!nbytes)
1487 return -EINVAL;
1488 if (nbytes >= sizeof(buffer))
1489 return -E2BIG;
1490 if (copy_from_user(buffer, userbuf, nbytes))
1491 return -EFAULT;
1493 buffer[nbytes] = 0; /* nul-terminate */
1494 strstrip(buffer);
1495 if (cft->write_u64) {
1496 u64 val = simple_strtoull(buffer, &end, 0);
1497 if (*end)
1498 return -EINVAL;
1499 retval = cft->write_u64(cgrp, cft, val);
1500 } else {
1501 s64 val = simple_strtoll(buffer, &end, 0);
1502 if (*end)
1503 return -EINVAL;
1504 retval = cft->write_s64(cgrp, cft, val);
1506 if (!retval)
1507 retval = nbytes;
1508 return retval;
1511 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1512 struct file *file,
1513 const char __user *userbuf,
1514 size_t nbytes, loff_t *unused_ppos)
1516 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1517 int retval = 0;
1518 size_t max_bytes = cft->max_write_len;
1519 char *buffer = local_buffer;
1521 if (!max_bytes)
1522 max_bytes = sizeof(local_buffer) - 1;
1523 if (nbytes >= max_bytes)
1524 return -E2BIG;
1525 /* Allocate a dynamic buffer if we need one */
1526 if (nbytes >= sizeof(local_buffer)) {
1527 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1528 if (buffer == NULL)
1529 return -ENOMEM;
1531 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
1532 retval = -EFAULT;
1533 goto out;
1536 buffer[nbytes] = 0; /* nul-terminate */
1537 strstrip(buffer);
1538 retval = cft->write_string(cgrp, cft, buffer);
1539 if (!retval)
1540 retval = nbytes;
1541 out:
1542 if (buffer != local_buffer)
1543 kfree(buffer);
1544 return retval;
1547 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1548 size_t nbytes, loff_t *ppos)
1550 struct cftype *cft = __d_cft(file->f_dentry);
1551 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1553 if (cgroup_is_removed(cgrp))
1554 return -ENODEV;
1555 if (cft->write)
1556 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1557 if (cft->write_u64 || cft->write_s64)
1558 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1559 if (cft->write_string)
1560 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1561 if (cft->trigger) {
1562 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1563 return ret ? ret : nbytes;
1565 return -EINVAL;
1568 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1569 struct file *file,
1570 char __user *buf, size_t nbytes,
1571 loff_t *ppos)
1573 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1574 u64 val = cft->read_u64(cgrp, cft);
1575 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1577 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1580 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1581 struct file *file,
1582 char __user *buf, size_t nbytes,
1583 loff_t *ppos)
1585 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1586 s64 val = cft->read_s64(cgrp, cft);
1587 int len = sprintf(tmp, "%lld\n", (long long) val);
1589 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1592 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1593 size_t nbytes, loff_t *ppos)
1595 struct cftype *cft = __d_cft(file->f_dentry);
1596 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1598 if (cgroup_is_removed(cgrp))
1599 return -ENODEV;
1601 if (cft->read)
1602 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1603 if (cft->read_u64)
1604 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1605 if (cft->read_s64)
1606 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1607 return -EINVAL;
1611 * seqfile ops/methods for returning structured data. Currently just
1612 * supports string->u64 maps, but can be extended in future.
1615 struct cgroup_seqfile_state {
1616 struct cftype *cft;
1617 struct cgroup *cgroup;
1620 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1622 struct seq_file *sf = cb->state;
1623 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1626 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1628 struct cgroup_seqfile_state *state = m->private;
1629 struct cftype *cft = state->cft;
1630 if (cft->read_map) {
1631 struct cgroup_map_cb cb = {
1632 .fill = cgroup_map_add,
1633 .state = m,
1635 return cft->read_map(state->cgroup, cft, &cb);
1637 return cft->read_seq_string(state->cgroup, cft, m);
1640 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
1642 struct seq_file *seq = file->private_data;
1643 kfree(seq->private);
1644 return single_release(inode, file);
1647 static struct file_operations cgroup_seqfile_operations = {
1648 .read = seq_read,
1649 .write = cgroup_file_write,
1650 .llseek = seq_lseek,
1651 .release = cgroup_seqfile_release,
1654 static int cgroup_file_open(struct inode *inode, struct file *file)
1656 int err;
1657 struct cftype *cft;
1659 err = generic_file_open(inode, file);
1660 if (err)
1661 return err;
1662 cft = __d_cft(file->f_dentry);
1664 if (cft->read_map || cft->read_seq_string) {
1665 struct cgroup_seqfile_state *state =
1666 kzalloc(sizeof(*state), GFP_USER);
1667 if (!state)
1668 return -ENOMEM;
1669 state->cft = cft;
1670 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
1671 file->f_op = &cgroup_seqfile_operations;
1672 err = single_open(file, cgroup_seqfile_show, state);
1673 if (err < 0)
1674 kfree(state);
1675 } else if (cft->open)
1676 err = cft->open(inode, file);
1677 else
1678 err = 0;
1680 return err;
1683 static int cgroup_file_release(struct inode *inode, struct file *file)
1685 struct cftype *cft = __d_cft(file->f_dentry);
1686 if (cft->release)
1687 return cft->release(inode, file);
1688 return 0;
1692 * cgroup_rename - Only allow simple rename of directories in place.
1694 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
1695 struct inode *new_dir, struct dentry *new_dentry)
1697 if (!S_ISDIR(old_dentry->d_inode->i_mode))
1698 return -ENOTDIR;
1699 if (new_dentry->d_inode)
1700 return -EEXIST;
1701 if (old_dir != new_dir)
1702 return -EIO;
1703 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1706 static struct file_operations cgroup_file_operations = {
1707 .read = cgroup_file_read,
1708 .write = cgroup_file_write,
1709 .llseek = generic_file_llseek,
1710 .open = cgroup_file_open,
1711 .release = cgroup_file_release,
1714 static const struct inode_operations cgroup_dir_inode_operations = {
1715 .lookup = simple_lookup,
1716 .mkdir = cgroup_mkdir,
1717 .rmdir = cgroup_rmdir,
1718 .rename = cgroup_rename,
1721 static int cgroup_create_file(struct dentry *dentry, mode_t mode,
1722 struct super_block *sb)
1724 static const struct dentry_operations cgroup_dops = {
1725 .d_iput = cgroup_diput,
1728 struct inode *inode;
1730 if (!dentry)
1731 return -ENOENT;
1732 if (dentry->d_inode)
1733 return -EEXIST;
1735 inode = cgroup_new_inode(mode, sb);
1736 if (!inode)
1737 return -ENOMEM;
1739 if (S_ISDIR(mode)) {
1740 inode->i_op = &cgroup_dir_inode_operations;
1741 inode->i_fop = &simple_dir_operations;
1743 /* start off with i_nlink == 2 (for "." entry) */
1744 inc_nlink(inode);
1746 /* start with the directory inode held, so that we can
1747 * populate it without racing with another mkdir */
1748 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
1749 } else if (S_ISREG(mode)) {
1750 inode->i_size = 0;
1751 inode->i_fop = &cgroup_file_operations;
1753 dentry->d_op = &cgroup_dops;
1754 d_instantiate(dentry, inode);
1755 dget(dentry); /* Extra count - pin the dentry in core */
1756 return 0;
1760 * cgroup_create_dir - create a directory for an object.
1761 * @cgrp: the cgroup we create the directory for. It must have a valid
1762 * ->parent field. And we are going to fill its ->dentry field.
1763 * @dentry: dentry of the new cgroup
1764 * @mode: mode to set on new directory.
1766 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
1767 mode_t mode)
1769 struct dentry *parent;
1770 int error = 0;
1772 parent = cgrp->parent->dentry;
1773 error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
1774 if (!error) {
1775 dentry->d_fsdata = cgrp;
1776 inc_nlink(parent->d_inode);
1777 rcu_assign_pointer(cgrp->dentry, dentry);
1778 dget(dentry);
1780 dput(dentry);
1782 return error;
1786 * cgroup_file_mode - deduce file mode of a control file
1787 * @cft: the control file in question
1789 * returns cft->mode if ->mode is not 0
1790 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1791 * returns S_IRUGO if it has only a read handler
1792 * returns S_IWUSR if it has only a write hander
1794 static mode_t cgroup_file_mode(const struct cftype *cft)
1796 mode_t mode = 0;
1798 if (cft->mode)
1799 return cft->mode;
1801 if (cft->read || cft->read_u64 || cft->read_s64 ||
1802 cft->read_map || cft->read_seq_string)
1803 mode |= S_IRUGO;
1805 if (cft->write || cft->write_u64 || cft->write_s64 ||
1806 cft->write_string || cft->trigger)
1807 mode |= S_IWUSR;
1809 return mode;
1812 int cgroup_add_file(struct cgroup *cgrp,
1813 struct cgroup_subsys *subsys,
1814 const struct cftype *cft)
1816 struct dentry *dir = cgrp->dentry;
1817 struct dentry *dentry;
1818 int error;
1819 mode_t mode;
1821 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
1822 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
1823 strcpy(name, subsys->name);
1824 strcat(name, ".");
1826 strcat(name, cft->name);
1827 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
1828 dentry = lookup_one_len(name, dir, strlen(name));
1829 if (!IS_ERR(dentry)) {
1830 mode = cgroup_file_mode(cft);
1831 error = cgroup_create_file(dentry, mode | S_IFREG,
1832 cgrp->root->sb);
1833 if (!error)
1834 dentry->d_fsdata = (void *)cft;
1835 dput(dentry);
1836 } else
1837 error = PTR_ERR(dentry);
1838 return error;
1841 int cgroup_add_files(struct cgroup *cgrp,
1842 struct cgroup_subsys *subsys,
1843 const struct cftype cft[],
1844 int count)
1846 int i, err;
1847 for (i = 0; i < count; i++) {
1848 err = cgroup_add_file(cgrp, subsys, &cft[i]);
1849 if (err)
1850 return err;
1852 return 0;
1856 * cgroup_task_count - count the number of tasks in a cgroup.
1857 * @cgrp: the cgroup in question
1859 * Return the number of tasks in the cgroup.
1861 int cgroup_task_count(const struct cgroup *cgrp)
1863 int count = 0;
1864 struct cg_cgroup_link *link;
1866 read_lock(&css_set_lock);
1867 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
1868 count += atomic_read(&link->cg->refcount);
1870 read_unlock(&css_set_lock);
1871 return count;
1875 * Advance a list_head iterator. The iterator should be positioned at
1876 * the start of a css_set
1878 static void cgroup_advance_iter(struct cgroup *cgrp,
1879 struct cgroup_iter *it)
1881 struct list_head *l = it->cg_link;
1882 struct cg_cgroup_link *link;
1883 struct css_set *cg;
1885 /* Advance to the next non-empty css_set */
1886 do {
1887 l = l->next;
1888 if (l == &cgrp->css_sets) {
1889 it->cg_link = NULL;
1890 return;
1892 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
1893 cg = link->cg;
1894 } while (list_empty(&cg->tasks));
1895 it->cg_link = l;
1896 it->task = cg->tasks.next;
1900 * To reduce the fork() overhead for systems that are not actually
1901 * using their cgroups capability, we don't maintain the lists running
1902 * through each css_set to its tasks until we see the list actually
1903 * used - in other words after the first call to cgroup_iter_start().
1905 * The tasklist_lock is not held here, as do_each_thread() and
1906 * while_each_thread() are protected by RCU.
1908 static void cgroup_enable_task_cg_lists(void)
1910 struct task_struct *p, *g;
1911 write_lock(&css_set_lock);
1912 use_task_css_set_links = 1;
1913 do_each_thread(g, p) {
1914 task_lock(p);
1916 * We should check if the process is exiting, otherwise
1917 * it will race with cgroup_exit() in that the list
1918 * entry won't be deleted though the process has exited.
1920 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
1921 list_add(&p->cg_list, &p->cgroups->tasks);
1922 task_unlock(p);
1923 } while_each_thread(g, p);
1924 write_unlock(&css_set_lock);
1927 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
1930 * The first time anyone tries to iterate across a cgroup,
1931 * we need to enable the list linking each css_set to its
1932 * tasks, and fix up all existing tasks.
1934 if (!use_task_css_set_links)
1935 cgroup_enable_task_cg_lists();
1937 read_lock(&css_set_lock);
1938 it->cg_link = &cgrp->css_sets;
1939 cgroup_advance_iter(cgrp, it);
1942 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
1943 struct cgroup_iter *it)
1945 struct task_struct *res;
1946 struct list_head *l = it->task;
1947 struct cg_cgroup_link *link;
1949 /* If the iterator cg is NULL, we have no tasks */
1950 if (!it->cg_link)
1951 return NULL;
1952 res = list_entry(l, struct task_struct, cg_list);
1953 /* Advance iterator to find next entry */
1954 l = l->next;
1955 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
1956 if (l == &link->cg->tasks) {
1957 /* We reached the end of this task list - move on to
1958 * the next cg_cgroup_link */
1959 cgroup_advance_iter(cgrp, it);
1960 } else {
1961 it->task = l;
1963 return res;
1966 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
1968 read_unlock(&css_set_lock);
1971 static inline int started_after_time(struct task_struct *t1,
1972 struct timespec *time,
1973 struct task_struct *t2)
1975 int start_diff = timespec_compare(&t1->start_time, time);
1976 if (start_diff > 0) {
1977 return 1;
1978 } else if (start_diff < 0) {
1979 return 0;
1980 } else {
1982 * Arbitrarily, if two processes started at the same
1983 * time, we'll say that the lower pointer value
1984 * started first. Note that t2 may have exited by now
1985 * so this may not be a valid pointer any longer, but
1986 * that's fine - it still serves to distinguish
1987 * between two tasks started (effectively) simultaneously.
1989 return t1 > t2;
1994 * This function is a callback from heap_insert() and is used to order
1995 * the heap.
1996 * In this case we order the heap in descending task start time.
1998 static inline int started_after(void *p1, void *p2)
2000 struct task_struct *t1 = p1;
2001 struct task_struct *t2 = p2;
2002 return started_after_time(t1, &t2->start_time, t2);
2006 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
2007 * @scan: struct cgroup_scanner containing arguments for the scan
2009 * Arguments include pointers to callback functions test_task() and
2010 * process_task().
2011 * Iterate through all the tasks in a cgroup, calling test_task() for each,
2012 * and if it returns true, call process_task() for it also.
2013 * The test_task pointer may be NULL, meaning always true (select all tasks).
2014 * Effectively duplicates cgroup_iter_{start,next,end}()
2015 * but does not lock css_set_lock for the call to process_task().
2016 * The struct cgroup_scanner may be embedded in any structure of the caller's
2017 * creation.
2018 * It is guaranteed that process_task() will act on every task that
2019 * is a member of the cgroup for the duration of this call. This
2020 * function may or may not call process_task() for tasks that exit
2021 * or move to a different cgroup during the call, or are forked or
2022 * move into the cgroup during the call.
2024 * Note that test_task() may be called with locks held, and may in some
2025 * situations be called multiple times for the same task, so it should
2026 * be cheap.
2027 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
2028 * pre-allocated and will be used for heap operations (and its "gt" member will
2029 * be overwritten), else a temporary heap will be used (allocation of which
2030 * may cause this function to fail).
2032 int cgroup_scan_tasks(struct cgroup_scanner *scan)
2034 int retval, i;
2035 struct cgroup_iter it;
2036 struct task_struct *p, *dropped;
2037 /* Never dereference latest_task, since it's not refcounted */
2038 struct task_struct *latest_task = NULL;
2039 struct ptr_heap tmp_heap;
2040 struct ptr_heap *heap;
2041 struct timespec latest_time = { 0, 0 };
2043 if (scan->heap) {
2044 /* The caller supplied our heap and pre-allocated its memory */
2045 heap = scan->heap;
2046 heap->gt = &started_after;
2047 } else {
2048 /* We need to allocate our own heap memory */
2049 heap = &tmp_heap;
2050 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2051 if (retval)
2052 /* cannot allocate the heap */
2053 return retval;
2056 again:
2058 * Scan tasks in the cgroup, using the scanner's "test_task" callback
2059 * to determine which are of interest, and using the scanner's
2060 * "process_task" callback to process any of them that need an update.
2061 * Since we don't want to hold any locks during the task updates,
2062 * gather tasks to be processed in a heap structure.
2063 * The heap is sorted by descending task start time.
2064 * If the statically-sized heap fills up, we overflow tasks that
2065 * started later, and in future iterations only consider tasks that
2066 * started after the latest task in the previous pass. This
2067 * guarantees forward progress and that we don't miss any tasks.
2069 heap->size = 0;
2070 cgroup_iter_start(scan->cg, &it);
2071 while ((p = cgroup_iter_next(scan->cg, &it))) {
2073 * Only affect tasks that qualify per the caller's callback,
2074 * if he provided one
2076 if (scan->test_task && !scan->test_task(p, scan))
2077 continue;
2079 * Only process tasks that started after the last task
2080 * we processed
2082 if (!started_after_time(p, &latest_time, latest_task))
2083 continue;
2084 dropped = heap_insert(heap, p);
2085 if (dropped == NULL) {
2087 * The new task was inserted; the heap wasn't
2088 * previously full
2090 get_task_struct(p);
2091 } else if (dropped != p) {
2093 * The new task was inserted, and pushed out a
2094 * different task
2096 get_task_struct(p);
2097 put_task_struct(dropped);
2100 * Else the new task was newer than anything already in
2101 * the heap and wasn't inserted
2104 cgroup_iter_end(scan->cg, &it);
2106 if (heap->size) {
2107 for (i = 0; i < heap->size; i++) {
2108 struct task_struct *q = heap->ptrs[i];
2109 if (i == 0) {
2110 latest_time = q->start_time;
2111 latest_task = q;
2113 /* Process the task per the caller's callback */
2114 scan->process_task(q, scan);
2115 put_task_struct(q);
2118 * If we had to process any tasks at all, scan again
2119 * in case some of them were in the middle of forking
2120 * children that didn't get processed.
2121 * Not the most efficient way to do it, but it avoids
2122 * having to take callback_mutex in the fork path
2124 goto again;
2126 if (heap == &tmp_heap)
2127 heap_free(&tmp_heap);
2128 return 0;
2132 * Stuff for reading the 'tasks' file.
2134 * Reading this file can return large amounts of data if a cgroup has
2135 * *lots* of attached tasks. So it may need several calls to read(),
2136 * but we cannot guarantee that the information we produce is correct
2137 * unless we produce it entirely atomically.
2142 * Load into 'pidarray' up to 'npids' of the tasks using cgroup
2143 * 'cgrp'. Return actual number of pids loaded. No need to
2144 * task_lock(p) when reading out p->cgroup, since we're in an RCU
2145 * read section, so the css_set can't go away, and is
2146 * immutable after creation.
2148 static int pid_array_load(pid_t *pidarray, int npids, struct cgroup *cgrp)
2150 int n = 0, pid;
2151 struct cgroup_iter it;
2152 struct task_struct *tsk;
2153 cgroup_iter_start(cgrp, &it);
2154 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2155 if (unlikely(n == npids))
2156 break;
2157 pid = task_pid_vnr(tsk);
2158 if (pid > 0)
2159 pidarray[n++] = pid;
2161 cgroup_iter_end(cgrp, &it);
2162 return n;
2166 * cgroupstats_build - build and fill cgroupstats
2167 * @stats: cgroupstats to fill information into
2168 * @dentry: A dentry entry belonging to the cgroup for which stats have
2169 * been requested.
2171 * Build and fill cgroupstats so that taskstats can export it to user
2172 * space.
2174 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2176 int ret = -EINVAL;
2177 struct cgroup *cgrp;
2178 struct cgroup_iter it;
2179 struct task_struct *tsk;
2182 * Validate dentry by checking the superblock operations,
2183 * and make sure it's a directory.
2185 if (dentry->d_sb->s_op != &cgroup_ops ||
2186 !S_ISDIR(dentry->d_inode->i_mode))
2187 goto err;
2189 ret = 0;
2190 cgrp = dentry->d_fsdata;
2192 cgroup_iter_start(cgrp, &it);
2193 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2194 switch (tsk->state) {
2195 case TASK_RUNNING:
2196 stats->nr_running++;
2197 break;
2198 case TASK_INTERRUPTIBLE:
2199 stats->nr_sleeping++;
2200 break;
2201 case TASK_UNINTERRUPTIBLE:
2202 stats->nr_uninterruptible++;
2203 break;
2204 case TASK_STOPPED:
2205 stats->nr_stopped++;
2206 break;
2207 default:
2208 if (delayacct_is_task_waiting_on_io(tsk))
2209 stats->nr_io_wait++;
2210 break;
2213 cgroup_iter_end(cgrp, &it);
2215 err:
2216 return ret;
2220 * Cache pids for all threads in the same pid namespace that are
2221 * opening the same "tasks" file.
2223 struct cgroup_pids {
2224 /* The node in cgrp->pids_list */
2225 struct list_head list;
2226 /* The cgroup those pids belong to */
2227 struct cgroup *cgrp;
2228 /* The namepsace those pids belong to */
2229 struct pid_namespace *ns;
2230 /* Array of process ids in the cgroup */
2231 pid_t *tasks_pids;
2232 /* How many files are using the this tasks_pids array */
2233 int use_count;
2234 /* Length of the current tasks_pids array */
2235 int length;
2238 static int cmppid(const void *a, const void *b)
2240 return *(pid_t *)a - *(pid_t *)b;
2244 * seq_file methods for the "tasks" file. The seq_file position is the
2245 * next pid to display; the seq_file iterator is a pointer to the pid
2246 * in the cgroup->tasks_pids array.
2249 static void *cgroup_tasks_start(struct seq_file *s, loff_t *pos)
2252 * Initially we receive a position value that corresponds to
2253 * one more than the last pid shown (or 0 on the first call or
2254 * after a seek to the start). Use a binary-search to find the
2255 * next pid to display, if any
2257 struct cgroup_pids *cp = s->private;
2258 struct cgroup *cgrp = cp->cgrp;
2259 int index = 0, pid = *pos;
2260 int *iter;
2262 down_read(&cgrp->pids_mutex);
2263 if (pid) {
2264 int end = cp->length;
2266 while (index < end) {
2267 int mid = (index + end) / 2;
2268 if (cp->tasks_pids[mid] == pid) {
2269 index = mid;
2270 break;
2271 } else if (cp->tasks_pids[mid] <= pid)
2272 index = mid + 1;
2273 else
2274 end = mid;
2277 /* If we're off the end of the array, we're done */
2278 if (index >= cp->length)
2279 return NULL;
2280 /* Update the abstract position to be the actual pid that we found */
2281 iter = cp->tasks_pids + index;
2282 *pos = *iter;
2283 return iter;
2286 static void cgroup_tasks_stop(struct seq_file *s, void *v)
2288 struct cgroup_pids *cp = s->private;
2289 struct cgroup *cgrp = cp->cgrp;
2290 up_read(&cgrp->pids_mutex);
2293 static void *cgroup_tasks_next(struct seq_file *s, void *v, loff_t *pos)
2295 struct cgroup_pids *cp = s->private;
2296 int *p = v;
2297 int *end = cp->tasks_pids + cp->length;
2300 * Advance to the next pid in the array. If this goes off the
2301 * end, we're done
2303 p++;
2304 if (p >= end) {
2305 return NULL;
2306 } else {
2307 *pos = *p;
2308 return p;
2312 static int cgroup_tasks_show(struct seq_file *s, void *v)
2314 return seq_printf(s, "%d\n", *(int *)v);
2317 static const struct seq_operations cgroup_tasks_seq_operations = {
2318 .start = cgroup_tasks_start,
2319 .stop = cgroup_tasks_stop,
2320 .next = cgroup_tasks_next,
2321 .show = cgroup_tasks_show,
2324 static void release_cgroup_pid_array(struct cgroup_pids *cp)
2326 struct cgroup *cgrp = cp->cgrp;
2328 down_write(&cgrp->pids_mutex);
2329 BUG_ON(!cp->use_count);
2330 if (!--cp->use_count) {
2331 list_del(&cp->list);
2332 put_pid_ns(cp->ns);
2333 kfree(cp->tasks_pids);
2334 kfree(cp);
2336 up_write(&cgrp->pids_mutex);
2339 static int cgroup_tasks_release(struct inode *inode, struct file *file)
2341 struct seq_file *seq;
2342 struct cgroup_pids *cp;
2344 if (!(file->f_mode & FMODE_READ))
2345 return 0;
2347 seq = file->private_data;
2348 cp = seq->private;
2350 release_cgroup_pid_array(cp);
2351 return seq_release(inode, file);
2354 static struct file_operations cgroup_tasks_operations = {
2355 .read = seq_read,
2356 .llseek = seq_lseek,
2357 .write = cgroup_file_write,
2358 .release = cgroup_tasks_release,
2362 * Handle an open on 'tasks' file. Prepare an array containing the
2363 * process id's of tasks currently attached to the cgroup being opened.
2366 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2368 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2369 struct pid_namespace *ns = current->nsproxy->pid_ns;
2370 struct cgroup_pids *cp;
2371 pid_t *pidarray;
2372 int npids;
2373 int retval;
2375 /* Nothing to do for write-only files */
2376 if (!(file->f_mode & FMODE_READ))
2377 return 0;
2380 * If cgroup gets more users after we read count, we won't have
2381 * enough space - tough. This race is indistinguishable to the
2382 * caller from the case that the additional cgroup users didn't
2383 * show up until sometime later on.
2385 npids = cgroup_task_count(cgrp);
2386 pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
2387 if (!pidarray)
2388 return -ENOMEM;
2389 npids = pid_array_load(pidarray, npids, cgrp);
2390 sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
2393 * Store the array in the cgroup, freeing the old
2394 * array if necessary
2396 down_write(&cgrp->pids_mutex);
2398 list_for_each_entry(cp, &cgrp->pids_list, list) {
2399 if (ns == cp->ns)
2400 goto found;
2403 cp = kzalloc(sizeof(*cp), GFP_KERNEL);
2404 if (!cp) {
2405 up_write(&cgrp->pids_mutex);
2406 kfree(pidarray);
2407 return -ENOMEM;
2409 cp->cgrp = cgrp;
2410 cp->ns = ns;
2411 get_pid_ns(ns);
2412 list_add(&cp->list, &cgrp->pids_list);
2413 found:
2414 kfree(cp->tasks_pids);
2415 cp->tasks_pids = pidarray;
2416 cp->length = npids;
2417 cp->use_count++;
2418 up_write(&cgrp->pids_mutex);
2420 file->f_op = &cgroup_tasks_operations;
2422 retval = seq_open(file, &cgroup_tasks_seq_operations);
2423 if (retval) {
2424 release_cgroup_pid_array(cp);
2425 return retval;
2427 ((struct seq_file *)file->private_data)->private = cp;
2428 return 0;
2431 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2432 struct cftype *cft)
2434 return notify_on_release(cgrp);
2437 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2438 struct cftype *cft,
2439 u64 val)
2441 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2442 if (val)
2443 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2444 else
2445 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2446 return 0;
2450 * for the common functions, 'private' gives the type of file
2452 static struct cftype files[] = {
2454 .name = "tasks",
2455 .open = cgroup_tasks_open,
2456 .write_u64 = cgroup_tasks_write,
2457 .release = cgroup_tasks_release,
2458 .private = FILE_TASKLIST,
2459 .mode = S_IRUGO | S_IWUSR,
2463 .name = "notify_on_release",
2464 .read_u64 = cgroup_read_notify_on_release,
2465 .write_u64 = cgroup_write_notify_on_release,
2466 .private = FILE_NOTIFY_ON_RELEASE,
2470 static struct cftype cft_release_agent = {
2471 .name = "release_agent",
2472 .read_seq_string = cgroup_release_agent_show,
2473 .write_string = cgroup_release_agent_write,
2474 .max_write_len = PATH_MAX,
2475 .private = FILE_RELEASE_AGENT,
2478 static int cgroup_populate_dir(struct cgroup *cgrp)
2480 int err;
2481 struct cgroup_subsys *ss;
2483 /* First clear out any existing files */
2484 cgroup_clear_directory(cgrp->dentry);
2486 err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2487 if (err < 0)
2488 return err;
2490 if (cgrp == cgrp->top_cgroup) {
2491 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2492 return err;
2495 for_each_subsys(cgrp->root, ss) {
2496 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2497 return err;
2499 /* This cgroup is ready now */
2500 for_each_subsys(cgrp->root, ss) {
2501 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2503 * Update id->css pointer and make this css visible from
2504 * CSS ID functions. This pointer will be dereferened
2505 * from RCU-read-side without locks.
2507 if (css->id)
2508 rcu_assign_pointer(css->id->css, css);
2511 return 0;
2514 static void init_cgroup_css(struct cgroup_subsys_state *css,
2515 struct cgroup_subsys *ss,
2516 struct cgroup *cgrp)
2518 css->cgroup = cgrp;
2519 atomic_set(&css->refcnt, 1);
2520 css->flags = 0;
2521 css->id = NULL;
2522 if (cgrp == dummytop)
2523 set_bit(CSS_ROOT, &css->flags);
2524 BUG_ON(cgrp->subsys[ss->subsys_id]);
2525 cgrp->subsys[ss->subsys_id] = css;
2528 static void cgroup_lock_hierarchy(struct cgroupfs_root *root)
2530 /* We need to take each hierarchy_mutex in a consistent order */
2531 int i;
2533 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2534 struct cgroup_subsys *ss = subsys[i];
2535 if (ss->root == root)
2536 mutex_lock(&ss->hierarchy_mutex);
2540 static void cgroup_unlock_hierarchy(struct cgroupfs_root *root)
2542 int i;
2544 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2545 struct cgroup_subsys *ss = subsys[i];
2546 if (ss->root == root)
2547 mutex_unlock(&ss->hierarchy_mutex);
2552 * cgroup_create - create a cgroup
2553 * @parent: cgroup that will be parent of the new cgroup
2554 * @dentry: dentry of the new cgroup
2555 * @mode: mode to set on new inode
2557 * Must be called with the mutex on the parent inode held
2559 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
2560 mode_t mode)
2562 struct cgroup *cgrp;
2563 struct cgroupfs_root *root = parent->root;
2564 int err = 0;
2565 struct cgroup_subsys *ss;
2566 struct super_block *sb = root->sb;
2568 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
2569 if (!cgrp)
2570 return -ENOMEM;
2572 /* Grab a reference on the superblock so the hierarchy doesn't
2573 * get deleted on unmount if there are child cgroups. This
2574 * can be done outside cgroup_mutex, since the sb can't
2575 * disappear while someone has an open control file on the
2576 * fs */
2577 atomic_inc(&sb->s_active);
2579 mutex_lock(&cgroup_mutex);
2581 init_cgroup_housekeeping(cgrp);
2583 cgrp->parent = parent;
2584 cgrp->root = parent->root;
2585 cgrp->top_cgroup = parent->top_cgroup;
2587 if (notify_on_release(parent))
2588 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2590 for_each_subsys(root, ss) {
2591 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
2592 if (IS_ERR(css)) {
2593 err = PTR_ERR(css);
2594 goto err_destroy;
2596 init_cgroup_css(css, ss, cgrp);
2597 if (ss->use_id)
2598 if (alloc_css_id(ss, parent, cgrp))
2599 goto err_destroy;
2600 /* At error, ->destroy() callback has to free assigned ID. */
2603 cgroup_lock_hierarchy(root);
2604 list_add(&cgrp->sibling, &cgrp->parent->children);
2605 cgroup_unlock_hierarchy(root);
2606 root->number_of_cgroups++;
2608 err = cgroup_create_dir(cgrp, dentry, mode);
2609 if (err < 0)
2610 goto err_remove;
2612 /* The cgroup directory was pre-locked for us */
2613 BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
2615 err = cgroup_populate_dir(cgrp);
2616 /* If err < 0, we have a half-filled directory - oh well ;) */
2618 mutex_unlock(&cgroup_mutex);
2619 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
2621 return 0;
2623 err_remove:
2625 cgroup_lock_hierarchy(root);
2626 list_del(&cgrp->sibling);
2627 cgroup_unlock_hierarchy(root);
2628 root->number_of_cgroups--;
2630 err_destroy:
2632 for_each_subsys(root, ss) {
2633 if (cgrp->subsys[ss->subsys_id])
2634 ss->destroy(ss, cgrp);
2637 mutex_unlock(&cgroup_mutex);
2639 /* Release the reference count that we took on the superblock */
2640 deactivate_super(sb);
2642 kfree(cgrp);
2643 return err;
2646 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2648 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
2650 /* the vfs holds inode->i_mutex already */
2651 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
2654 static int cgroup_has_css_refs(struct cgroup *cgrp)
2656 /* Check the reference count on each subsystem. Since we
2657 * already established that there are no tasks in the
2658 * cgroup, if the css refcount is also 1, then there should
2659 * be no outstanding references, so the subsystem is safe to
2660 * destroy. We scan across all subsystems rather than using
2661 * the per-hierarchy linked list of mounted subsystems since
2662 * we can be called via check_for_release() with no
2663 * synchronization other than RCU, and the subsystem linked
2664 * list isn't RCU-safe */
2665 int i;
2666 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2667 struct cgroup_subsys *ss = subsys[i];
2668 struct cgroup_subsys_state *css;
2669 /* Skip subsystems not in this hierarchy */
2670 if (ss->root != cgrp->root)
2671 continue;
2672 css = cgrp->subsys[ss->subsys_id];
2673 /* When called from check_for_release() it's possible
2674 * that by this point the cgroup has been removed
2675 * and the css deleted. But a false-positive doesn't
2676 * matter, since it can only happen if the cgroup
2677 * has been deleted and hence no longer needs the
2678 * release agent to be called anyway. */
2679 if (css && (atomic_read(&css->refcnt) > 1))
2680 return 1;
2682 return 0;
2686 * Atomically mark all (or else none) of the cgroup's CSS objects as
2687 * CSS_REMOVED. Return true on success, or false if the cgroup has
2688 * busy subsystems. Call with cgroup_mutex held
2691 static int cgroup_clear_css_refs(struct cgroup *cgrp)
2693 struct cgroup_subsys *ss;
2694 unsigned long flags;
2695 bool failed = false;
2696 local_irq_save(flags);
2697 for_each_subsys(cgrp->root, ss) {
2698 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2699 int refcnt;
2700 while (1) {
2701 /* We can only remove a CSS with a refcnt==1 */
2702 refcnt = atomic_read(&css->refcnt);
2703 if (refcnt > 1) {
2704 failed = true;
2705 goto done;
2707 BUG_ON(!refcnt);
2709 * Drop the refcnt to 0 while we check other
2710 * subsystems. This will cause any racing
2711 * css_tryget() to spin until we set the
2712 * CSS_REMOVED bits or abort
2714 if (atomic_cmpxchg(&css->refcnt, refcnt, 0) == refcnt)
2715 break;
2716 cpu_relax();
2719 done:
2720 for_each_subsys(cgrp->root, ss) {
2721 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2722 if (failed) {
2724 * Restore old refcnt if we previously managed
2725 * to clear it from 1 to 0
2727 if (!atomic_read(&css->refcnt))
2728 atomic_set(&css->refcnt, 1);
2729 } else {
2730 /* Commit the fact that the CSS is removed */
2731 set_bit(CSS_REMOVED, &css->flags);
2734 local_irq_restore(flags);
2735 return !failed;
2738 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
2740 struct cgroup *cgrp = dentry->d_fsdata;
2741 struct dentry *d;
2742 struct cgroup *parent;
2743 DEFINE_WAIT(wait);
2744 int ret;
2746 /* the vfs holds both inode->i_mutex already */
2747 again:
2748 mutex_lock(&cgroup_mutex);
2749 if (atomic_read(&cgrp->count) != 0) {
2750 mutex_unlock(&cgroup_mutex);
2751 return -EBUSY;
2753 if (!list_empty(&cgrp->children)) {
2754 mutex_unlock(&cgroup_mutex);
2755 return -EBUSY;
2757 mutex_unlock(&cgroup_mutex);
2760 * In general, subsystem has no css->refcnt after pre_destroy(). But
2761 * in racy cases, subsystem may have to get css->refcnt after
2762 * pre_destroy() and it makes rmdir return with -EBUSY. This sometimes
2763 * make rmdir return -EBUSY too often. To avoid that, we use waitqueue
2764 * for cgroup's rmdir. CGRP_WAIT_ON_RMDIR is for synchronizing rmdir
2765 * and subsystem's reference count handling. Please see css_get/put
2766 * and css_tryget() and cgroup_wakeup_rmdir_waiter() implementation.
2768 set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2771 * Call pre_destroy handlers of subsys. Notify subsystems
2772 * that rmdir() request comes.
2774 ret = cgroup_call_pre_destroy(cgrp);
2775 if (ret) {
2776 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2777 return ret;
2780 mutex_lock(&cgroup_mutex);
2781 parent = cgrp->parent;
2782 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
2783 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2784 mutex_unlock(&cgroup_mutex);
2785 return -EBUSY;
2787 prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
2788 if (!cgroup_clear_css_refs(cgrp)) {
2789 mutex_unlock(&cgroup_mutex);
2791 * Because someone may call cgroup_wakeup_rmdir_waiter() before
2792 * prepare_to_wait(), we need to check this flag.
2794 if (test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))
2795 schedule();
2796 finish_wait(&cgroup_rmdir_waitq, &wait);
2797 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2798 if (signal_pending(current))
2799 return -EINTR;
2800 goto again;
2802 /* NO css_tryget() can success after here. */
2803 finish_wait(&cgroup_rmdir_waitq, &wait);
2804 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2806 spin_lock(&release_list_lock);
2807 set_bit(CGRP_REMOVED, &cgrp->flags);
2808 if (!list_empty(&cgrp->release_list))
2809 list_del(&cgrp->release_list);
2810 spin_unlock(&release_list_lock);
2812 cgroup_lock_hierarchy(cgrp->root);
2813 /* delete this cgroup from parent->children */
2814 list_del(&cgrp->sibling);
2815 cgroup_unlock_hierarchy(cgrp->root);
2817 spin_lock(&cgrp->dentry->d_lock);
2818 d = dget(cgrp->dentry);
2819 spin_unlock(&d->d_lock);
2821 cgroup_d_remove_dir(d);
2822 dput(d);
2824 set_bit(CGRP_RELEASABLE, &parent->flags);
2825 check_for_release(parent);
2827 mutex_unlock(&cgroup_mutex);
2828 return 0;
2831 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
2833 struct cgroup_subsys_state *css;
2835 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
2837 /* Create the top cgroup state for this subsystem */
2838 list_add(&ss->sibling, &rootnode.subsys_list);
2839 ss->root = &rootnode;
2840 css = ss->create(ss, dummytop);
2841 /* We don't handle early failures gracefully */
2842 BUG_ON(IS_ERR(css));
2843 init_cgroup_css(css, ss, dummytop);
2845 /* Update the init_css_set to contain a subsys
2846 * pointer to this state - since the subsystem is
2847 * newly registered, all tasks and hence the
2848 * init_css_set is in the subsystem's top cgroup. */
2849 init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
2851 need_forkexit_callback |= ss->fork || ss->exit;
2853 /* At system boot, before all subsystems have been
2854 * registered, no tasks have been forked, so we don't
2855 * need to invoke fork callbacks here. */
2856 BUG_ON(!list_empty(&init_task.tasks));
2858 mutex_init(&ss->hierarchy_mutex);
2859 lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
2860 ss->active = 1;
2864 * cgroup_init_early - cgroup initialization at system boot
2866 * Initialize cgroups at system boot, and initialize any
2867 * subsystems that request early init.
2869 int __init cgroup_init_early(void)
2871 int i;
2872 atomic_set(&init_css_set.refcount, 1);
2873 INIT_LIST_HEAD(&init_css_set.cg_links);
2874 INIT_LIST_HEAD(&init_css_set.tasks);
2875 INIT_HLIST_NODE(&init_css_set.hlist);
2876 css_set_count = 1;
2877 init_cgroup_root(&rootnode);
2878 root_count = 1;
2879 init_task.cgroups = &init_css_set;
2881 init_css_set_link.cg = &init_css_set;
2882 list_add(&init_css_set_link.cgrp_link_list,
2883 &rootnode.top_cgroup.css_sets);
2884 list_add(&init_css_set_link.cg_link_list,
2885 &init_css_set.cg_links);
2887 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
2888 INIT_HLIST_HEAD(&css_set_table[i]);
2890 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2891 struct cgroup_subsys *ss = subsys[i];
2893 BUG_ON(!ss->name);
2894 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
2895 BUG_ON(!ss->create);
2896 BUG_ON(!ss->destroy);
2897 if (ss->subsys_id != i) {
2898 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
2899 ss->name, ss->subsys_id);
2900 BUG();
2903 if (ss->early_init)
2904 cgroup_init_subsys(ss);
2906 return 0;
2910 * cgroup_init - cgroup initialization
2912 * Register cgroup filesystem and /proc file, and initialize
2913 * any subsystems that didn't request early init.
2915 int __init cgroup_init(void)
2917 int err;
2918 int i;
2919 struct hlist_head *hhead;
2921 err = bdi_init(&cgroup_backing_dev_info);
2922 if (err)
2923 return err;
2925 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2926 struct cgroup_subsys *ss = subsys[i];
2927 if (!ss->early_init)
2928 cgroup_init_subsys(ss);
2929 if (ss->use_id)
2930 cgroup_subsys_init_idr(ss);
2933 /* Add init_css_set to the hash table */
2934 hhead = css_set_hash(init_css_set.subsys);
2935 hlist_add_head(&init_css_set.hlist, hhead);
2937 err = register_filesystem(&cgroup_fs_type);
2938 if (err < 0)
2939 goto out;
2941 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
2943 out:
2944 if (err)
2945 bdi_destroy(&cgroup_backing_dev_info);
2947 return err;
2951 * proc_cgroup_show()
2952 * - Print task's cgroup paths into seq_file, one line for each hierarchy
2953 * - Used for /proc/<pid>/cgroup.
2954 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
2955 * doesn't really matter if tsk->cgroup changes after we read it,
2956 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
2957 * anyway. No need to check that tsk->cgroup != NULL, thanks to
2958 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
2959 * cgroup to top_cgroup.
2962 /* TODO: Use a proper seq_file iterator */
2963 static int proc_cgroup_show(struct seq_file *m, void *v)
2965 struct pid *pid;
2966 struct task_struct *tsk;
2967 char *buf;
2968 int retval;
2969 struct cgroupfs_root *root;
2971 retval = -ENOMEM;
2972 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
2973 if (!buf)
2974 goto out;
2976 retval = -ESRCH;
2977 pid = m->private;
2978 tsk = get_pid_task(pid, PIDTYPE_PID);
2979 if (!tsk)
2980 goto out_free;
2982 retval = 0;
2984 mutex_lock(&cgroup_mutex);
2986 for_each_active_root(root) {
2987 struct cgroup_subsys *ss;
2988 struct cgroup *cgrp;
2989 int subsys_id;
2990 int count = 0;
2992 seq_printf(m, "%lu:", root->subsys_bits);
2993 for_each_subsys(root, ss)
2994 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
2995 seq_putc(m, ':');
2996 get_first_subsys(&root->top_cgroup, NULL, &subsys_id);
2997 cgrp = task_cgroup(tsk, subsys_id);
2998 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
2999 if (retval < 0)
3000 goto out_unlock;
3001 seq_puts(m, buf);
3002 seq_putc(m, '\n');
3005 out_unlock:
3006 mutex_unlock(&cgroup_mutex);
3007 put_task_struct(tsk);
3008 out_free:
3009 kfree(buf);
3010 out:
3011 return retval;
3014 static int cgroup_open(struct inode *inode, struct file *file)
3016 struct pid *pid = PROC_I(inode)->pid;
3017 return single_open(file, proc_cgroup_show, pid);
3020 struct file_operations proc_cgroup_operations = {
3021 .open = cgroup_open,
3022 .read = seq_read,
3023 .llseek = seq_lseek,
3024 .release = single_release,
3027 /* Display information about each subsystem and each hierarchy */
3028 static int proc_cgroupstats_show(struct seq_file *m, void *v)
3030 int i;
3032 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
3033 mutex_lock(&cgroup_mutex);
3034 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3035 struct cgroup_subsys *ss = subsys[i];
3036 seq_printf(m, "%s\t%lu\t%d\t%d\n",
3037 ss->name, ss->root->subsys_bits,
3038 ss->root->number_of_cgroups, !ss->disabled);
3040 mutex_unlock(&cgroup_mutex);
3041 return 0;
3044 static int cgroupstats_open(struct inode *inode, struct file *file)
3046 return single_open(file, proc_cgroupstats_show, NULL);
3049 static struct file_operations proc_cgroupstats_operations = {
3050 .open = cgroupstats_open,
3051 .read = seq_read,
3052 .llseek = seq_lseek,
3053 .release = single_release,
3057 * cgroup_fork - attach newly forked task to its parents cgroup.
3058 * @child: pointer to task_struct of forking parent process.
3060 * Description: A task inherits its parent's cgroup at fork().
3062 * A pointer to the shared css_set was automatically copied in
3063 * fork.c by dup_task_struct(). However, we ignore that copy, since
3064 * it was not made under the protection of RCU or cgroup_mutex, so
3065 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
3066 * have already changed current->cgroups, allowing the previously
3067 * referenced cgroup group to be removed and freed.
3069 * At the point that cgroup_fork() is called, 'current' is the parent
3070 * task, and the passed argument 'child' points to the child task.
3072 void cgroup_fork(struct task_struct *child)
3074 task_lock(current);
3075 child->cgroups = current->cgroups;
3076 get_css_set(child->cgroups);
3077 task_unlock(current);
3078 INIT_LIST_HEAD(&child->cg_list);
3082 * cgroup_fork_callbacks - run fork callbacks
3083 * @child: the new task
3085 * Called on a new task very soon before adding it to the
3086 * tasklist. No need to take any locks since no-one can
3087 * be operating on this task.
3089 void cgroup_fork_callbacks(struct task_struct *child)
3091 if (need_forkexit_callback) {
3092 int i;
3093 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3094 struct cgroup_subsys *ss = subsys[i];
3095 if (ss->fork)
3096 ss->fork(ss, child);
3102 * cgroup_post_fork - called on a new task after adding it to the task list
3103 * @child: the task in question
3105 * Adds the task to the list running through its css_set if necessary.
3106 * Has to be after the task is visible on the task list in case we race
3107 * with the first call to cgroup_iter_start() - to guarantee that the
3108 * new task ends up on its list.
3110 void cgroup_post_fork(struct task_struct *child)
3112 if (use_task_css_set_links) {
3113 write_lock(&css_set_lock);
3114 task_lock(child);
3115 if (list_empty(&child->cg_list))
3116 list_add(&child->cg_list, &child->cgroups->tasks);
3117 task_unlock(child);
3118 write_unlock(&css_set_lock);
3122 * cgroup_exit - detach cgroup from exiting task
3123 * @tsk: pointer to task_struct of exiting process
3124 * @run_callback: run exit callbacks?
3126 * Description: Detach cgroup from @tsk and release it.
3128 * Note that cgroups marked notify_on_release force every task in
3129 * them to take the global cgroup_mutex mutex when exiting.
3130 * This could impact scaling on very large systems. Be reluctant to
3131 * use notify_on_release cgroups where very high task exit scaling
3132 * is required on large systems.
3134 * the_top_cgroup_hack:
3136 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
3138 * We call cgroup_exit() while the task is still competent to
3139 * handle notify_on_release(), then leave the task attached to the
3140 * root cgroup in each hierarchy for the remainder of its exit.
3142 * To do this properly, we would increment the reference count on
3143 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
3144 * code we would add a second cgroup function call, to drop that
3145 * reference. This would just create an unnecessary hot spot on
3146 * the top_cgroup reference count, to no avail.
3148 * Normally, holding a reference to a cgroup without bumping its
3149 * count is unsafe. The cgroup could go away, or someone could
3150 * attach us to a different cgroup, decrementing the count on
3151 * the first cgroup that we never incremented. But in this case,
3152 * top_cgroup isn't going away, and either task has PF_EXITING set,
3153 * which wards off any cgroup_attach_task() attempts, or task is a failed
3154 * fork, never visible to cgroup_attach_task.
3156 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
3158 int i;
3159 struct css_set *cg;
3161 if (run_callbacks && need_forkexit_callback) {
3162 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3163 struct cgroup_subsys *ss = subsys[i];
3164 if (ss->exit)
3165 ss->exit(ss, tsk);
3170 * Unlink from the css_set task list if necessary.
3171 * Optimistically check cg_list before taking
3172 * css_set_lock
3174 if (!list_empty(&tsk->cg_list)) {
3175 write_lock(&css_set_lock);
3176 if (!list_empty(&tsk->cg_list))
3177 list_del(&tsk->cg_list);
3178 write_unlock(&css_set_lock);
3181 /* Reassign the task to the init_css_set. */
3182 task_lock(tsk);
3183 cg = tsk->cgroups;
3184 tsk->cgroups = &init_css_set;
3185 task_unlock(tsk);
3186 if (cg)
3187 put_css_set_taskexit(cg);
3191 * cgroup_clone - clone the cgroup the given subsystem is attached to
3192 * @tsk: the task to be moved
3193 * @subsys: the given subsystem
3194 * @nodename: the name for the new cgroup
3196 * Duplicate the current cgroup in the hierarchy that the given
3197 * subsystem is attached to, and move this task into the new
3198 * child.
3200 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
3201 char *nodename)
3203 struct dentry *dentry;
3204 int ret = 0;
3205 struct cgroup *parent, *child;
3206 struct inode *inode;
3207 struct css_set *cg;
3208 struct cgroupfs_root *root;
3209 struct cgroup_subsys *ss;
3211 /* We shouldn't be called by an unregistered subsystem */
3212 BUG_ON(!subsys->active);
3214 /* First figure out what hierarchy and cgroup we're dealing
3215 * with, and pin them so we can drop cgroup_mutex */
3216 mutex_lock(&cgroup_mutex);
3217 again:
3218 root = subsys->root;
3219 if (root == &rootnode) {
3220 mutex_unlock(&cgroup_mutex);
3221 return 0;
3224 /* Pin the hierarchy */
3225 if (!atomic_inc_not_zero(&root->sb->s_active)) {
3226 /* We race with the final deactivate_super() */
3227 mutex_unlock(&cgroup_mutex);
3228 return 0;
3231 /* Keep the cgroup alive */
3232 task_lock(tsk);
3233 parent = task_cgroup(tsk, subsys->subsys_id);
3234 cg = tsk->cgroups;
3235 get_css_set(cg);
3236 task_unlock(tsk);
3238 mutex_unlock(&cgroup_mutex);
3240 /* Now do the VFS work to create a cgroup */
3241 inode = parent->dentry->d_inode;
3243 /* Hold the parent directory mutex across this operation to
3244 * stop anyone else deleting the new cgroup */
3245 mutex_lock(&inode->i_mutex);
3246 dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
3247 if (IS_ERR(dentry)) {
3248 printk(KERN_INFO
3249 "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
3250 PTR_ERR(dentry));
3251 ret = PTR_ERR(dentry);
3252 goto out_release;
3255 /* Create the cgroup directory, which also creates the cgroup */
3256 ret = vfs_mkdir(inode, dentry, 0755);
3257 child = __d_cgrp(dentry);
3258 dput(dentry);
3259 if (ret) {
3260 printk(KERN_INFO
3261 "Failed to create cgroup %s: %d\n", nodename,
3262 ret);
3263 goto out_release;
3266 /* The cgroup now exists. Retake cgroup_mutex and check
3267 * that we're still in the same state that we thought we
3268 * were. */
3269 mutex_lock(&cgroup_mutex);
3270 if ((root != subsys->root) ||
3271 (parent != task_cgroup(tsk, subsys->subsys_id))) {
3272 /* Aargh, we raced ... */
3273 mutex_unlock(&inode->i_mutex);
3274 put_css_set(cg);
3276 deactivate_super(root->sb);
3277 /* The cgroup is still accessible in the VFS, but
3278 * we're not going to try to rmdir() it at this
3279 * point. */
3280 printk(KERN_INFO
3281 "Race in cgroup_clone() - leaking cgroup %s\n",
3282 nodename);
3283 goto again;
3286 /* do any required auto-setup */
3287 for_each_subsys(root, ss) {
3288 if (ss->post_clone)
3289 ss->post_clone(ss, child);
3292 /* All seems fine. Finish by moving the task into the new cgroup */
3293 ret = cgroup_attach_task(child, tsk);
3294 mutex_unlock(&cgroup_mutex);
3296 out_release:
3297 mutex_unlock(&inode->i_mutex);
3299 mutex_lock(&cgroup_mutex);
3300 put_css_set(cg);
3301 mutex_unlock(&cgroup_mutex);
3302 deactivate_super(root->sb);
3303 return ret;
3307 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
3308 * @cgrp: the cgroup in question
3309 * @task: the task in question
3311 * See if @cgrp is a descendant of @task's cgroup in the appropriate
3312 * hierarchy.
3314 * If we are sending in dummytop, then presumably we are creating
3315 * the top cgroup in the subsystem.
3317 * Called only by the ns (nsproxy) cgroup.
3319 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
3321 int ret;
3322 struct cgroup *target;
3323 int subsys_id;
3325 if (cgrp == dummytop)
3326 return 1;
3328 get_first_subsys(cgrp, NULL, &subsys_id);
3329 target = task_cgroup(task, subsys_id);
3330 while (cgrp != target && cgrp!= cgrp->top_cgroup)
3331 cgrp = cgrp->parent;
3332 ret = (cgrp == target);
3333 return ret;
3336 static void check_for_release(struct cgroup *cgrp)
3338 /* All of these checks rely on RCU to keep the cgroup
3339 * structure alive */
3340 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
3341 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
3342 /* Control Group is currently removeable. If it's not
3343 * already queued for a userspace notification, queue
3344 * it now */
3345 int need_schedule_work = 0;
3346 spin_lock(&release_list_lock);
3347 if (!cgroup_is_removed(cgrp) &&
3348 list_empty(&cgrp->release_list)) {
3349 list_add(&cgrp->release_list, &release_list);
3350 need_schedule_work = 1;
3352 spin_unlock(&release_list_lock);
3353 if (need_schedule_work)
3354 schedule_work(&release_agent_work);
3358 void __css_put(struct cgroup_subsys_state *css)
3360 struct cgroup *cgrp = css->cgroup;
3361 rcu_read_lock();
3362 if (atomic_dec_return(&css->refcnt) == 1) {
3363 if (notify_on_release(cgrp)) {
3364 set_bit(CGRP_RELEASABLE, &cgrp->flags);
3365 check_for_release(cgrp);
3367 cgroup_wakeup_rmdir_waiter(cgrp);
3369 rcu_read_unlock();
3373 * Notify userspace when a cgroup is released, by running the
3374 * configured release agent with the name of the cgroup (path
3375 * relative to the root of cgroup file system) as the argument.
3377 * Most likely, this user command will try to rmdir this cgroup.
3379 * This races with the possibility that some other task will be
3380 * attached to this cgroup before it is removed, or that some other
3381 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
3382 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
3383 * unused, and this cgroup will be reprieved from its death sentence,
3384 * to continue to serve a useful existence. Next time it's released,
3385 * we will get notified again, if it still has 'notify_on_release' set.
3387 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
3388 * means only wait until the task is successfully execve()'d. The
3389 * separate release agent task is forked by call_usermodehelper(),
3390 * then control in this thread returns here, without waiting for the
3391 * release agent task. We don't bother to wait because the caller of
3392 * this routine has no use for the exit status of the release agent
3393 * task, so no sense holding our caller up for that.
3395 static void cgroup_release_agent(struct work_struct *work)
3397 BUG_ON(work != &release_agent_work);
3398 mutex_lock(&cgroup_mutex);
3399 spin_lock(&release_list_lock);
3400 while (!list_empty(&release_list)) {
3401 char *argv[3], *envp[3];
3402 int i;
3403 char *pathbuf = NULL, *agentbuf = NULL;
3404 struct cgroup *cgrp = list_entry(release_list.next,
3405 struct cgroup,
3406 release_list);
3407 list_del_init(&cgrp->release_list);
3408 spin_unlock(&release_list_lock);
3409 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3410 if (!pathbuf)
3411 goto continue_free;
3412 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
3413 goto continue_free;
3414 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
3415 if (!agentbuf)
3416 goto continue_free;
3418 i = 0;
3419 argv[i++] = agentbuf;
3420 argv[i++] = pathbuf;
3421 argv[i] = NULL;
3423 i = 0;
3424 /* minimal command environment */
3425 envp[i++] = "HOME=/";
3426 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3427 envp[i] = NULL;
3429 /* Drop the lock while we invoke the usermode helper,
3430 * since the exec could involve hitting disk and hence
3431 * be a slow process */
3432 mutex_unlock(&cgroup_mutex);
3433 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3434 mutex_lock(&cgroup_mutex);
3435 continue_free:
3436 kfree(pathbuf);
3437 kfree(agentbuf);
3438 spin_lock(&release_list_lock);
3440 spin_unlock(&release_list_lock);
3441 mutex_unlock(&cgroup_mutex);
3444 static int __init cgroup_disable(char *str)
3446 int i;
3447 char *token;
3449 while ((token = strsep(&str, ",")) != NULL) {
3450 if (!*token)
3451 continue;
3453 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3454 struct cgroup_subsys *ss = subsys[i];
3456 if (!strcmp(token, ss->name)) {
3457 ss->disabled = 1;
3458 printk(KERN_INFO "Disabling %s control group"
3459 " subsystem\n", ss->name);
3460 break;
3464 return 1;
3466 __setup("cgroup_disable=", cgroup_disable);
3469 * Functons for CSS ID.
3473 *To get ID other than 0, this should be called when !cgroup_is_removed().
3475 unsigned short css_id(struct cgroup_subsys_state *css)
3477 struct css_id *cssid = rcu_dereference(css->id);
3479 if (cssid)
3480 return cssid->id;
3481 return 0;
3484 unsigned short css_depth(struct cgroup_subsys_state *css)
3486 struct css_id *cssid = rcu_dereference(css->id);
3488 if (cssid)
3489 return cssid->depth;
3490 return 0;
3493 bool css_is_ancestor(struct cgroup_subsys_state *child,
3494 const struct cgroup_subsys_state *root)
3496 struct css_id *child_id = rcu_dereference(child->id);
3497 struct css_id *root_id = rcu_dereference(root->id);
3499 if (!child_id || !root_id || (child_id->depth < root_id->depth))
3500 return false;
3501 return child_id->stack[root_id->depth] == root_id->id;
3504 static void __free_css_id_cb(struct rcu_head *head)
3506 struct css_id *id;
3508 id = container_of(head, struct css_id, rcu_head);
3509 kfree(id);
3512 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
3514 struct css_id *id = css->id;
3515 /* When this is called before css_id initialization, id can be NULL */
3516 if (!id)
3517 return;
3519 BUG_ON(!ss->use_id);
3521 rcu_assign_pointer(id->css, NULL);
3522 rcu_assign_pointer(css->id, NULL);
3523 spin_lock(&ss->id_lock);
3524 idr_remove(&ss->idr, id->id);
3525 spin_unlock(&ss->id_lock);
3526 call_rcu(&id->rcu_head, __free_css_id_cb);
3530 * This is called by init or create(). Then, calls to this function are
3531 * always serialized (By cgroup_mutex() at create()).
3534 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
3536 struct css_id *newid;
3537 int myid, error, size;
3539 BUG_ON(!ss->use_id);
3541 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
3542 newid = kzalloc(size, GFP_KERNEL);
3543 if (!newid)
3544 return ERR_PTR(-ENOMEM);
3545 /* get id */
3546 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
3547 error = -ENOMEM;
3548 goto err_out;
3550 spin_lock(&ss->id_lock);
3551 /* Don't use 0. allocates an ID of 1-65535 */
3552 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
3553 spin_unlock(&ss->id_lock);
3555 /* Returns error when there are no free spaces for new ID.*/
3556 if (error) {
3557 error = -ENOSPC;
3558 goto err_out;
3560 if (myid > CSS_ID_MAX)
3561 goto remove_idr;
3563 newid->id = myid;
3564 newid->depth = depth;
3565 return newid;
3566 remove_idr:
3567 error = -ENOSPC;
3568 spin_lock(&ss->id_lock);
3569 idr_remove(&ss->idr, myid);
3570 spin_unlock(&ss->id_lock);
3571 err_out:
3572 kfree(newid);
3573 return ERR_PTR(error);
3577 static int __init cgroup_subsys_init_idr(struct cgroup_subsys *ss)
3579 struct css_id *newid;
3580 struct cgroup_subsys_state *rootcss;
3582 spin_lock_init(&ss->id_lock);
3583 idr_init(&ss->idr);
3585 rootcss = init_css_set.subsys[ss->subsys_id];
3586 newid = get_new_cssid(ss, 0);
3587 if (IS_ERR(newid))
3588 return PTR_ERR(newid);
3590 newid->stack[0] = newid->id;
3591 newid->css = rootcss;
3592 rootcss->id = newid;
3593 return 0;
3596 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
3597 struct cgroup *child)
3599 int subsys_id, i, depth = 0;
3600 struct cgroup_subsys_state *parent_css, *child_css;
3601 struct css_id *child_id, *parent_id = NULL;
3603 subsys_id = ss->subsys_id;
3604 parent_css = parent->subsys[subsys_id];
3605 child_css = child->subsys[subsys_id];
3606 depth = css_depth(parent_css) + 1;
3607 parent_id = parent_css->id;
3609 child_id = get_new_cssid(ss, depth);
3610 if (IS_ERR(child_id))
3611 return PTR_ERR(child_id);
3613 for (i = 0; i < depth; i++)
3614 child_id->stack[i] = parent_id->stack[i];
3615 child_id->stack[depth] = child_id->id;
3617 * child_id->css pointer will be set after this cgroup is available
3618 * see cgroup_populate_dir()
3620 rcu_assign_pointer(child_css->id, child_id);
3622 return 0;
3626 * css_lookup - lookup css by id
3627 * @ss: cgroup subsys to be looked into.
3628 * @id: the id
3630 * Returns pointer to cgroup_subsys_state if there is valid one with id.
3631 * NULL if not. Should be called under rcu_read_lock()
3633 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
3635 struct css_id *cssid = NULL;
3637 BUG_ON(!ss->use_id);
3638 cssid = idr_find(&ss->idr, id);
3640 if (unlikely(!cssid))
3641 return NULL;
3643 return rcu_dereference(cssid->css);
3647 * css_get_next - lookup next cgroup under specified hierarchy.
3648 * @ss: pointer to subsystem
3649 * @id: current position of iteration.
3650 * @root: pointer to css. search tree under this.
3651 * @foundid: position of found object.
3653 * Search next css under the specified hierarchy of rootid. Calling under
3654 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
3656 struct cgroup_subsys_state *
3657 css_get_next(struct cgroup_subsys *ss, int id,
3658 struct cgroup_subsys_state *root, int *foundid)
3660 struct cgroup_subsys_state *ret = NULL;
3661 struct css_id *tmp;
3662 int tmpid;
3663 int rootid = css_id(root);
3664 int depth = css_depth(root);
3666 if (!rootid)
3667 return NULL;
3669 BUG_ON(!ss->use_id);
3670 /* fill start point for scan */
3671 tmpid = id;
3672 while (1) {
3674 * scan next entry from bitmap(tree), tmpid is updated after
3675 * idr_get_next().
3677 spin_lock(&ss->id_lock);
3678 tmp = idr_get_next(&ss->idr, &tmpid);
3679 spin_unlock(&ss->id_lock);
3681 if (!tmp)
3682 break;
3683 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
3684 ret = rcu_dereference(tmp->css);
3685 if (ret) {
3686 *foundid = tmpid;
3687 break;
3690 /* continue to scan from next id */
3691 tmpid = tmpid + 1;
3693 return ret;