tracing/sched: show CPU task wakes up on in trace event
[linux-2.6/linux-2.6-openrd.git] / kernel / cgroup.c
blobb6eadfe30e7be1627e81b8158e1d581c4575b11f
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 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 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
606 static int alloc_css_id(struct cgroup_subsys *ss,
607 struct cgroup *parent, struct cgroup *child);
609 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
611 struct inode *inode = new_inode(sb);
613 if (inode) {
614 inode->i_mode = mode;
615 inode->i_uid = current_fsuid();
616 inode->i_gid = current_fsgid();
617 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
618 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
620 return inode;
624 * Call subsys's pre_destroy handler.
625 * This is called before css refcnt check.
627 static int cgroup_call_pre_destroy(struct cgroup *cgrp)
629 struct cgroup_subsys *ss;
630 int ret = 0;
632 for_each_subsys(cgrp->root, ss)
633 if (ss->pre_destroy) {
634 ret = ss->pre_destroy(ss, cgrp);
635 if (ret)
636 break;
638 return ret;
641 static void free_cgroup_rcu(struct rcu_head *obj)
643 struct cgroup *cgrp = container_of(obj, struct cgroup, rcu_head);
645 kfree(cgrp);
648 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
650 /* is dentry a directory ? if so, kfree() associated cgroup */
651 if (S_ISDIR(inode->i_mode)) {
652 struct cgroup *cgrp = dentry->d_fsdata;
653 struct cgroup_subsys *ss;
654 BUG_ON(!(cgroup_is_removed(cgrp)));
655 /* It's possible for external users to be holding css
656 * reference counts on a cgroup; css_put() needs to
657 * be able to access the cgroup after decrementing
658 * the reference count in order to know if it needs to
659 * queue the cgroup to be handled by the release
660 * agent */
661 synchronize_rcu();
663 mutex_lock(&cgroup_mutex);
665 * Release the subsystem state objects.
667 for_each_subsys(cgrp->root, ss)
668 ss->destroy(ss, cgrp);
670 cgrp->root->number_of_cgroups--;
671 mutex_unlock(&cgroup_mutex);
674 * Drop the active superblock reference that we took when we
675 * created the cgroup
677 deactivate_super(cgrp->root->sb);
679 call_rcu(&cgrp->rcu_head, free_cgroup_rcu);
681 iput(inode);
684 static void remove_dir(struct dentry *d)
686 struct dentry *parent = dget(d->d_parent);
688 d_delete(d);
689 simple_rmdir(parent->d_inode, d);
690 dput(parent);
693 static void cgroup_clear_directory(struct dentry *dentry)
695 struct list_head *node;
697 BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
698 spin_lock(&dcache_lock);
699 node = dentry->d_subdirs.next;
700 while (node != &dentry->d_subdirs) {
701 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
702 list_del_init(node);
703 if (d->d_inode) {
704 /* This should never be called on a cgroup
705 * directory with child cgroups */
706 BUG_ON(d->d_inode->i_mode & S_IFDIR);
707 d = dget_locked(d);
708 spin_unlock(&dcache_lock);
709 d_delete(d);
710 simple_unlink(dentry->d_inode, d);
711 dput(d);
712 spin_lock(&dcache_lock);
714 node = dentry->d_subdirs.next;
716 spin_unlock(&dcache_lock);
720 * NOTE : the dentry must have been dget()'ed
722 static void cgroup_d_remove_dir(struct dentry *dentry)
724 cgroup_clear_directory(dentry);
726 spin_lock(&dcache_lock);
727 list_del_init(&dentry->d_u.d_child);
728 spin_unlock(&dcache_lock);
729 remove_dir(dentry);
733 * A queue for waiters to do rmdir() cgroup. A tasks will sleep when
734 * cgroup->count == 0 && list_empty(&cgroup->children) && subsys has some
735 * reference to css->refcnt. In general, this refcnt is expected to goes down
736 * to zero, soon.
738 * CGRP_WAIT_ON_RMDIR flag is set under cgroup's inode->i_mutex;
740 DECLARE_WAIT_QUEUE_HEAD(cgroup_rmdir_waitq);
742 static void cgroup_wakeup_rmdir_waiter(struct cgroup *cgrp)
744 if (unlikely(test_and_clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags)))
745 wake_up_all(&cgroup_rmdir_waitq);
748 void cgroup_exclude_rmdir(struct cgroup_subsys_state *css)
750 css_get(css);
753 void cgroup_release_and_wakeup_rmdir(struct cgroup_subsys_state *css)
755 cgroup_wakeup_rmdir_waiter(css->cgroup);
756 css_put(css);
760 static int rebind_subsystems(struct cgroupfs_root *root,
761 unsigned long final_bits)
763 unsigned long added_bits, removed_bits;
764 struct cgroup *cgrp = &root->top_cgroup;
765 int i;
767 removed_bits = root->actual_subsys_bits & ~final_bits;
768 added_bits = final_bits & ~root->actual_subsys_bits;
769 /* Check that any added subsystems are currently free */
770 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
771 unsigned long bit = 1UL << i;
772 struct cgroup_subsys *ss = subsys[i];
773 if (!(bit & added_bits))
774 continue;
775 if (ss->root != &rootnode) {
776 /* Subsystem isn't free */
777 return -EBUSY;
781 /* Currently we don't handle adding/removing subsystems when
782 * any child cgroups exist. This is theoretically supportable
783 * but involves complex error handling, so it's being left until
784 * later */
785 if (root->number_of_cgroups > 1)
786 return -EBUSY;
788 /* Process each subsystem */
789 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
790 struct cgroup_subsys *ss = subsys[i];
791 unsigned long bit = 1UL << i;
792 if (bit & added_bits) {
793 /* We're binding this subsystem to this hierarchy */
794 BUG_ON(cgrp->subsys[i]);
795 BUG_ON(!dummytop->subsys[i]);
796 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
797 mutex_lock(&ss->hierarchy_mutex);
798 cgrp->subsys[i] = dummytop->subsys[i];
799 cgrp->subsys[i]->cgroup = cgrp;
800 list_move(&ss->sibling, &root->subsys_list);
801 ss->root = root;
802 if (ss->bind)
803 ss->bind(ss, cgrp);
804 mutex_unlock(&ss->hierarchy_mutex);
805 } else if (bit & removed_bits) {
806 /* We're removing this subsystem */
807 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
808 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
809 mutex_lock(&ss->hierarchy_mutex);
810 if (ss->bind)
811 ss->bind(ss, dummytop);
812 dummytop->subsys[i]->cgroup = dummytop;
813 cgrp->subsys[i] = NULL;
814 subsys[i]->root = &rootnode;
815 list_move(&ss->sibling, &rootnode.subsys_list);
816 mutex_unlock(&ss->hierarchy_mutex);
817 } else if (bit & final_bits) {
818 /* Subsystem state should already exist */
819 BUG_ON(!cgrp->subsys[i]);
820 } else {
821 /* Subsystem state shouldn't exist */
822 BUG_ON(cgrp->subsys[i]);
825 root->subsys_bits = root->actual_subsys_bits = final_bits;
826 synchronize_rcu();
828 return 0;
831 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
833 struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
834 struct cgroup_subsys *ss;
836 mutex_lock(&cgroup_mutex);
837 for_each_subsys(root, ss)
838 seq_printf(seq, ",%s", ss->name);
839 if (test_bit(ROOT_NOPREFIX, &root->flags))
840 seq_puts(seq, ",noprefix");
841 if (strlen(root->release_agent_path))
842 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
843 mutex_unlock(&cgroup_mutex);
844 return 0;
847 struct cgroup_sb_opts {
848 unsigned long subsys_bits;
849 unsigned long flags;
850 char *release_agent;
853 /* Convert a hierarchy specifier into a bitmask of subsystems and
854 * flags. */
855 static int parse_cgroupfs_options(char *data,
856 struct cgroup_sb_opts *opts)
858 char *token, *o = data ?: "all";
859 unsigned long mask = (unsigned long)-1;
861 #ifdef CONFIG_CPUSETS
862 mask = ~(1UL << cpuset_subsys_id);
863 #endif
865 opts->subsys_bits = 0;
866 opts->flags = 0;
867 opts->release_agent = NULL;
869 while ((token = strsep(&o, ",")) != NULL) {
870 if (!*token)
871 return -EINVAL;
872 if (!strcmp(token, "all")) {
873 /* Add all non-disabled subsystems */
874 int i;
875 opts->subsys_bits = 0;
876 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
877 struct cgroup_subsys *ss = subsys[i];
878 if (!ss->disabled)
879 opts->subsys_bits |= 1ul << i;
881 } else if (!strcmp(token, "noprefix")) {
882 set_bit(ROOT_NOPREFIX, &opts->flags);
883 } else if (!strncmp(token, "release_agent=", 14)) {
884 /* Specifying two release agents is forbidden */
885 if (opts->release_agent)
886 return -EINVAL;
887 opts->release_agent = kzalloc(PATH_MAX, GFP_KERNEL);
888 if (!opts->release_agent)
889 return -ENOMEM;
890 strncpy(opts->release_agent, token + 14, PATH_MAX - 1);
891 opts->release_agent[PATH_MAX - 1] = 0;
892 } else {
893 struct cgroup_subsys *ss;
894 int i;
895 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
896 ss = subsys[i];
897 if (!strcmp(token, ss->name)) {
898 if (!ss->disabled)
899 set_bit(i, &opts->subsys_bits);
900 break;
903 if (i == CGROUP_SUBSYS_COUNT)
904 return -ENOENT;
909 * Option noprefix was introduced just for backward compatibility
910 * with the old cpuset, so we allow noprefix only if mounting just
911 * the cpuset subsystem.
913 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
914 (opts->subsys_bits & mask))
915 return -EINVAL;
917 /* We can't have an empty hierarchy */
918 if (!opts->subsys_bits)
919 return -EINVAL;
921 return 0;
924 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
926 int ret = 0;
927 struct cgroupfs_root *root = sb->s_fs_info;
928 struct cgroup *cgrp = &root->top_cgroup;
929 struct cgroup_sb_opts opts;
931 lock_kernel();
932 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
933 mutex_lock(&cgroup_mutex);
935 /* See what subsystems are wanted */
936 ret = parse_cgroupfs_options(data, &opts);
937 if (ret)
938 goto out_unlock;
940 /* Don't allow flags to change at remount */
941 if (opts.flags != root->flags) {
942 ret = -EINVAL;
943 goto out_unlock;
946 ret = rebind_subsystems(root, opts.subsys_bits);
947 if (ret)
948 goto out_unlock;
950 /* (re)populate subsystem files */
951 cgroup_populate_dir(cgrp);
953 if (opts.release_agent)
954 strcpy(root->release_agent_path, opts.release_agent);
955 out_unlock:
956 kfree(opts.release_agent);
957 mutex_unlock(&cgroup_mutex);
958 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
959 unlock_kernel();
960 return ret;
963 static struct super_operations cgroup_ops = {
964 .statfs = simple_statfs,
965 .drop_inode = generic_delete_inode,
966 .show_options = cgroup_show_options,
967 .remount_fs = cgroup_remount,
970 static void init_cgroup_housekeeping(struct cgroup *cgrp)
972 INIT_LIST_HEAD(&cgrp->sibling);
973 INIT_LIST_HEAD(&cgrp->children);
974 INIT_LIST_HEAD(&cgrp->css_sets);
975 INIT_LIST_HEAD(&cgrp->release_list);
976 INIT_LIST_HEAD(&cgrp->pids_list);
977 init_rwsem(&cgrp->pids_mutex);
979 static void init_cgroup_root(struct cgroupfs_root *root)
981 struct cgroup *cgrp = &root->top_cgroup;
982 INIT_LIST_HEAD(&root->subsys_list);
983 INIT_LIST_HEAD(&root->root_list);
984 root->number_of_cgroups = 1;
985 cgrp->root = root;
986 cgrp->top_cgroup = cgrp;
987 init_cgroup_housekeeping(cgrp);
990 static int cgroup_test_super(struct super_block *sb, void *data)
992 struct cgroupfs_root *new = data;
993 struct cgroupfs_root *root = sb->s_fs_info;
995 /* First check subsystems */
996 if (new->subsys_bits != root->subsys_bits)
997 return 0;
999 /* Next check flags */
1000 if (new->flags != root->flags)
1001 return 0;
1003 return 1;
1006 static int cgroup_set_super(struct super_block *sb, void *data)
1008 int ret;
1009 struct cgroupfs_root *root = data;
1011 ret = set_anon_super(sb, NULL);
1012 if (ret)
1013 return ret;
1015 sb->s_fs_info = root;
1016 root->sb = sb;
1018 sb->s_blocksize = PAGE_CACHE_SIZE;
1019 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1020 sb->s_magic = CGROUP_SUPER_MAGIC;
1021 sb->s_op = &cgroup_ops;
1023 return 0;
1026 static int cgroup_get_rootdir(struct super_block *sb)
1028 struct inode *inode =
1029 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1030 struct dentry *dentry;
1032 if (!inode)
1033 return -ENOMEM;
1035 inode->i_fop = &simple_dir_operations;
1036 inode->i_op = &cgroup_dir_inode_operations;
1037 /* directories start off with i_nlink == 2 (for "." entry) */
1038 inc_nlink(inode);
1039 dentry = d_alloc_root(inode);
1040 if (!dentry) {
1041 iput(inode);
1042 return -ENOMEM;
1044 sb->s_root = dentry;
1045 return 0;
1048 static int cgroup_get_sb(struct file_system_type *fs_type,
1049 int flags, const char *unused_dev_name,
1050 void *data, struct vfsmount *mnt)
1052 struct cgroup_sb_opts opts;
1053 int ret = 0;
1054 struct super_block *sb;
1055 struct cgroupfs_root *root;
1056 struct list_head tmp_cg_links;
1058 /* First find the desired set of subsystems */
1059 ret = parse_cgroupfs_options(data, &opts);
1060 if (ret) {
1061 kfree(opts.release_agent);
1062 return ret;
1065 root = kzalloc(sizeof(*root), GFP_KERNEL);
1066 if (!root) {
1067 kfree(opts.release_agent);
1068 return -ENOMEM;
1071 init_cgroup_root(root);
1072 root->subsys_bits = opts.subsys_bits;
1073 root->flags = opts.flags;
1074 if (opts.release_agent) {
1075 strcpy(root->release_agent_path, opts.release_agent);
1076 kfree(opts.release_agent);
1079 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, root);
1081 if (IS_ERR(sb)) {
1082 kfree(root);
1083 return PTR_ERR(sb);
1086 if (sb->s_fs_info != root) {
1087 /* Reusing an existing superblock */
1088 BUG_ON(sb->s_root == NULL);
1089 kfree(root);
1090 root = NULL;
1091 } else {
1092 /* New superblock */
1093 struct cgroup *root_cgrp = &root->top_cgroup;
1094 struct inode *inode;
1095 int i;
1097 BUG_ON(sb->s_root != NULL);
1099 ret = cgroup_get_rootdir(sb);
1100 if (ret)
1101 goto drop_new_super;
1102 inode = sb->s_root->d_inode;
1104 mutex_lock(&inode->i_mutex);
1105 mutex_lock(&cgroup_mutex);
1108 * We're accessing css_set_count without locking
1109 * css_set_lock here, but that's OK - it can only be
1110 * increased by someone holding cgroup_lock, and
1111 * that's us. The worst that can happen is that we
1112 * have some link structures left over
1114 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1115 if (ret) {
1116 mutex_unlock(&cgroup_mutex);
1117 mutex_unlock(&inode->i_mutex);
1118 goto drop_new_super;
1121 ret = rebind_subsystems(root, root->subsys_bits);
1122 if (ret == -EBUSY) {
1123 mutex_unlock(&cgroup_mutex);
1124 mutex_unlock(&inode->i_mutex);
1125 goto free_cg_links;
1128 /* EBUSY should be the only error here */
1129 BUG_ON(ret);
1131 list_add(&root->root_list, &roots);
1132 root_count++;
1134 sb->s_root->d_fsdata = root_cgrp;
1135 root->top_cgroup.dentry = sb->s_root;
1137 /* Link the top cgroup in this hierarchy into all
1138 * the css_set objects */
1139 write_lock(&css_set_lock);
1140 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1141 struct hlist_head *hhead = &css_set_table[i];
1142 struct hlist_node *node;
1143 struct css_set *cg;
1145 hlist_for_each_entry(cg, node, hhead, hlist)
1146 link_css_set(&tmp_cg_links, cg, root_cgrp);
1148 write_unlock(&css_set_lock);
1150 free_cg_links(&tmp_cg_links);
1152 BUG_ON(!list_empty(&root_cgrp->sibling));
1153 BUG_ON(!list_empty(&root_cgrp->children));
1154 BUG_ON(root->number_of_cgroups != 1);
1156 cgroup_populate_dir(root_cgrp);
1157 mutex_unlock(&inode->i_mutex);
1158 mutex_unlock(&cgroup_mutex);
1161 simple_set_mnt(mnt, sb);
1162 return 0;
1164 free_cg_links:
1165 free_cg_links(&tmp_cg_links);
1166 drop_new_super:
1167 deactivate_locked_super(sb);
1168 return ret;
1171 static void cgroup_kill_sb(struct super_block *sb) {
1172 struct cgroupfs_root *root = sb->s_fs_info;
1173 struct cgroup *cgrp = &root->top_cgroup;
1174 int ret;
1175 struct cg_cgroup_link *link;
1176 struct cg_cgroup_link *saved_link;
1178 BUG_ON(!root);
1180 BUG_ON(root->number_of_cgroups != 1);
1181 BUG_ON(!list_empty(&cgrp->children));
1182 BUG_ON(!list_empty(&cgrp->sibling));
1184 mutex_lock(&cgroup_mutex);
1186 /* Rebind all subsystems back to the default hierarchy */
1187 ret = rebind_subsystems(root, 0);
1188 /* Shouldn't be able to fail ... */
1189 BUG_ON(ret);
1192 * Release all the links from css_sets to this hierarchy's
1193 * root cgroup
1195 write_lock(&css_set_lock);
1197 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1198 cgrp_link_list) {
1199 list_del(&link->cg_link_list);
1200 list_del(&link->cgrp_link_list);
1201 kfree(link);
1203 write_unlock(&css_set_lock);
1205 if (!list_empty(&root->root_list)) {
1206 list_del(&root->root_list);
1207 root_count--;
1210 mutex_unlock(&cgroup_mutex);
1212 kill_litter_super(sb);
1213 kfree(root);
1216 static struct file_system_type cgroup_fs_type = {
1217 .name = "cgroup",
1218 .get_sb = cgroup_get_sb,
1219 .kill_sb = cgroup_kill_sb,
1222 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1224 return dentry->d_fsdata;
1227 static inline struct cftype *__d_cft(struct dentry *dentry)
1229 return dentry->d_fsdata;
1233 * cgroup_path - generate the path of a cgroup
1234 * @cgrp: the cgroup in question
1235 * @buf: the buffer to write the path into
1236 * @buflen: the length of the buffer
1238 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1239 * reference. Writes path of cgroup into buf. Returns 0 on success,
1240 * -errno on error.
1242 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1244 char *start;
1245 struct dentry *dentry = rcu_dereference(cgrp->dentry);
1247 if (!dentry || cgrp == dummytop) {
1249 * Inactive subsystems have no dentry for their root
1250 * cgroup
1252 strcpy(buf, "/");
1253 return 0;
1256 start = buf + buflen;
1258 *--start = '\0';
1259 for (;;) {
1260 int len = dentry->d_name.len;
1261 if ((start -= len) < buf)
1262 return -ENAMETOOLONG;
1263 memcpy(start, cgrp->dentry->d_name.name, len);
1264 cgrp = cgrp->parent;
1265 if (!cgrp)
1266 break;
1267 dentry = rcu_dereference(cgrp->dentry);
1268 if (!cgrp->parent)
1269 continue;
1270 if (--start < buf)
1271 return -ENAMETOOLONG;
1272 *start = '/';
1274 memmove(buf, start, buf + buflen - start);
1275 return 0;
1279 * Return the first subsystem attached to a cgroup's hierarchy, and
1280 * its subsystem id.
1283 static void get_first_subsys(const struct cgroup *cgrp,
1284 struct cgroup_subsys_state **css, int *subsys_id)
1286 const struct cgroupfs_root *root = cgrp->root;
1287 const struct cgroup_subsys *test_ss;
1288 BUG_ON(list_empty(&root->subsys_list));
1289 test_ss = list_entry(root->subsys_list.next,
1290 struct cgroup_subsys, sibling);
1291 if (css) {
1292 *css = cgrp->subsys[test_ss->subsys_id];
1293 BUG_ON(!*css);
1295 if (subsys_id)
1296 *subsys_id = test_ss->subsys_id;
1300 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1301 * @cgrp: the cgroup the task is attaching to
1302 * @tsk: the task to be attached
1304 * Call holding cgroup_mutex. May take task_lock of
1305 * the task 'tsk' during call.
1307 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1309 int retval = 0;
1310 struct cgroup_subsys *ss;
1311 struct cgroup *oldcgrp;
1312 struct css_set *cg;
1313 struct css_set *newcg;
1314 struct cgroupfs_root *root = cgrp->root;
1315 int subsys_id;
1317 get_first_subsys(cgrp, NULL, &subsys_id);
1319 /* Nothing to do if the task is already in that cgroup */
1320 oldcgrp = task_cgroup(tsk, subsys_id);
1321 if (cgrp == oldcgrp)
1322 return 0;
1324 for_each_subsys(root, ss) {
1325 if (ss->can_attach) {
1326 retval = ss->can_attach(ss, cgrp, tsk);
1327 if (retval)
1328 return retval;
1332 task_lock(tsk);
1333 cg = tsk->cgroups;
1334 get_css_set(cg);
1335 task_unlock(tsk);
1337 * Locate or allocate a new css_set for this task,
1338 * based on its final set of cgroups
1340 newcg = find_css_set(cg, cgrp);
1341 put_css_set(cg);
1342 if (!newcg)
1343 return -ENOMEM;
1345 task_lock(tsk);
1346 if (tsk->flags & PF_EXITING) {
1347 task_unlock(tsk);
1348 put_css_set(newcg);
1349 return -ESRCH;
1351 rcu_assign_pointer(tsk->cgroups, newcg);
1352 task_unlock(tsk);
1354 /* Update the css_set linked lists if we're using them */
1355 write_lock(&css_set_lock);
1356 if (!list_empty(&tsk->cg_list)) {
1357 list_del(&tsk->cg_list);
1358 list_add(&tsk->cg_list, &newcg->tasks);
1360 write_unlock(&css_set_lock);
1362 for_each_subsys(root, ss) {
1363 if (ss->attach)
1364 ss->attach(ss, cgrp, oldcgrp, tsk);
1366 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1367 synchronize_rcu();
1368 put_css_set(cg);
1371 * wake up rmdir() waiter. the rmdir should fail since the cgroup
1372 * is no longer empty.
1374 cgroup_wakeup_rmdir_waiter(cgrp);
1375 return 0;
1379 * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
1380 * held. May take task_lock of task
1382 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
1384 struct task_struct *tsk;
1385 const struct cred *cred = current_cred(), *tcred;
1386 int ret;
1388 if (pid) {
1389 rcu_read_lock();
1390 tsk = find_task_by_vpid(pid);
1391 if (!tsk || tsk->flags & PF_EXITING) {
1392 rcu_read_unlock();
1393 return -ESRCH;
1396 tcred = __task_cred(tsk);
1397 if (cred->euid &&
1398 cred->euid != tcred->uid &&
1399 cred->euid != tcred->suid) {
1400 rcu_read_unlock();
1401 return -EACCES;
1403 get_task_struct(tsk);
1404 rcu_read_unlock();
1405 } else {
1406 tsk = current;
1407 get_task_struct(tsk);
1410 ret = cgroup_attach_task(cgrp, tsk);
1411 put_task_struct(tsk);
1412 return ret;
1415 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
1417 int ret;
1418 if (!cgroup_lock_live_group(cgrp))
1419 return -ENODEV;
1420 ret = attach_task_by_pid(cgrp, pid);
1421 cgroup_unlock();
1422 return ret;
1425 /* The various types of files and directories in a cgroup file system */
1426 enum cgroup_filetype {
1427 FILE_ROOT,
1428 FILE_DIR,
1429 FILE_TASKLIST,
1430 FILE_NOTIFY_ON_RELEASE,
1431 FILE_RELEASE_AGENT,
1435 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1436 * @cgrp: the cgroup to be checked for liveness
1438 * On success, returns true; the lock should be later released with
1439 * cgroup_unlock(). On failure returns false with no lock held.
1441 bool cgroup_lock_live_group(struct cgroup *cgrp)
1443 mutex_lock(&cgroup_mutex);
1444 if (cgroup_is_removed(cgrp)) {
1445 mutex_unlock(&cgroup_mutex);
1446 return false;
1448 return true;
1451 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1452 const char *buffer)
1454 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1455 if (!cgroup_lock_live_group(cgrp))
1456 return -ENODEV;
1457 strcpy(cgrp->root->release_agent_path, buffer);
1458 cgroup_unlock();
1459 return 0;
1462 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1463 struct seq_file *seq)
1465 if (!cgroup_lock_live_group(cgrp))
1466 return -ENODEV;
1467 seq_puts(seq, cgrp->root->release_agent_path);
1468 seq_putc(seq, '\n');
1469 cgroup_unlock();
1470 return 0;
1473 /* A buffer size big enough for numbers or short strings */
1474 #define CGROUP_LOCAL_BUFFER_SIZE 64
1476 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1477 struct file *file,
1478 const char __user *userbuf,
1479 size_t nbytes, loff_t *unused_ppos)
1481 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1482 int retval = 0;
1483 char *end;
1485 if (!nbytes)
1486 return -EINVAL;
1487 if (nbytes >= sizeof(buffer))
1488 return -E2BIG;
1489 if (copy_from_user(buffer, userbuf, nbytes))
1490 return -EFAULT;
1492 buffer[nbytes] = 0; /* nul-terminate */
1493 strstrip(buffer);
1494 if (cft->write_u64) {
1495 u64 val = simple_strtoull(buffer, &end, 0);
1496 if (*end)
1497 return -EINVAL;
1498 retval = cft->write_u64(cgrp, cft, val);
1499 } else {
1500 s64 val = simple_strtoll(buffer, &end, 0);
1501 if (*end)
1502 return -EINVAL;
1503 retval = cft->write_s64(cgrp, cft, val);
1505 if (!retval)
1506 retval = nbytes;
1507 return retval;
1510 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1511 struct file *file,
1512 const char __user *userbuf,
1513 size_t nbytes, loff_t *unused_ppos)
1515 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1516 int retval = 0;
1517 size_t max_bytes = cft->max_write_len;
1518 char *buffer = local_buffer;
1520 if (!max_bytes)
1521 max_bytes = sizeof(local_buffer) - 1;
1522 if (nbytes >= max_bytes)
1523 return -E2BIG;
1524 /* Allocate a dynamic buffer if we need one */
1525 if (nbytes >= sizeof(local_buffer)) {
1526 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1527 if (buffer == NULL)
1528 return -ENOMEM;
1530 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
1531 retval = -EFAULT;
1532 goto out;
1535 buffer[nbytes] = 0; /* nul-terminate */
1536 strstrip(buffer);
1537 retval = cft->write_string(cgrp, cft, buffer);
1538 if (!retval)
1539 retval = nbytes;
1540 out:
1541 if (buffer != local_buffer)
1542 kfree(buffer);
1543 return retval;
1546 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1547 size_t nbytes, loff_t *ppos)
1549 struct cftype *cft = __d_cft(file->f_dentry);
1550 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1552 if (cgroup_is_removed(cgrp))
1553 return -ENODEV;
1554 if (cft->write)
1555 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1556 if (cft->write_u64 || cft->write_s64)
1557 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1558 if (cft->write_string)
1559 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1560 if (cft->trigger) {
1561 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1562 return ret ? ret : nbytes;
1564 return -EINVAL;
1567 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1568 struct file *file,
1569 char __user *buf, size_t nbytes,
1570 loff_t *ppos)
1572 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1573 u64 val = cft->read_u64(cgrp, cft);
1574 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1576 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1579 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1580 struct file *file,
1581 char __user *buf, size_t nbytes,
1582 loff_t *ppos)
1584 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1585 s64 val = cft->read_s64(cgrp, cft);
1586 int len = sprintf(tmp, "%lld\n", (long long) val);
1588 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1591 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1592 size_t nbytes, loff_t *ppos)
1594 struct cftype *cft = __d_cft(file->f_dentry);
1595 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1597 if (cgroup_is_removed(cgrp))
1598 return -ENODEV;
1600 if (cft->read)
1601 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1602 if (cft->read_u64)
1603 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1604 if (cft->read_s64)
1605 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1606 return -EINVAL;
1610 * seqfile ops/methods for returning structured data. Currently just
1611 * supports string->u64 maps, but can be extended in future.
1614 struct cgroup_seqfile_state {
1615 struct cftype *cft;
1616 struct cgroup *cgroup;
1619 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1621 struct seq_file *sf = cb->state;
1622 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1625 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1627 struct cgroup_seqfile_state *state = m->private;
1628 struct cftype *cft = state->cft;
1629 if (cft->read_map) {
1630 struct cgroup_map_cb cb = {
1631 .fill = cgroup_map_add,
1632 .state = m,
1634 return cft->read_map(state->cgroup, cft, &cb);
1636 return cft->read_seq_string(state->cgroup, cft, m);
1639 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
1641 struct seq_file *seq = file->private_data;
1642 kfree(seq->private);
1643 return single_release(inode, file);
1646 static struct file_operations cgroup_seqfile_operations = {
1647 .read = seq_read,
1648 .write = cgroup_file_write,
1649 .llseek = seq_lseek,
1650 .release = cgroup_seqfile_release,
1653 static int cgroup_file_open(struct inode *inode, struct file *file)
1655 int err;
1656 struct cftype *cft;
1658 err = generic_file_open(inode, file);
1659 if (err)
1660 return err;
1661 cft = __d_cft(file->f_dentry);
1663 if (cft->read_map || cft->read_seq_string) {
1664 struct cgroup_seqfile_state *state =
1665 kzalloc(sizeof(*state), GFP_USER);
1666 if (!state)
1667 return -ENOMEM;
1668 state->cft = cft;
1669 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
1670 file->f_op = &cgroup_seqfile_operations;
1671 err = single_open(file, cgroup_seqfile_show, state);
1672 if (err < 0)
1673 kfree(state);
1674 } else if (cft->open)
1675 err = cft->open(inode, file);
1676 else
1677 err = 0;
1679 return err;
1682 static int cgroup_file_release(struct inode *inode, struct file *file)
1684 struct cftype *cft = __d_cft(file->f_dentry);
1685 if (cft->release)
1686 return cft->release(inode, file);
1687 return 0;
1691 * cgroup_rename - Only allow simple rename of directories in place.
1693 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
1694 struct inode *new_dir, struct dentry *new_dentry)
1696 if (!S_ISDIR(old_dentry->d_inode->i_mode))
1697 return -ENOTDIR;
1698 if (new_dentry->d_inode)
1699 return -EEXIST;
1700 if (old_dir != new_dir)
1701 return -EIO;
1702 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1705 static struct file_operations cgroup_file_operations = {
1706 .read = cgroup_file_read,
1707 .write = cgroup_file_write,
1708 .llseek = generic_file_llseek,
1709 .open = cgroup_file_open,
1710 .release = cgroup_file_release,
1713 static struct inode_operations cgroup_dir_inode_operations = {
1714 .lookup = simple_lookup,
1715 .mkdir = cgroup_mkdir,
1716 .rmdir = cgroup_rmdir,
1717 .rename = cgroup_rename,
1720 static int cgroup_create_file(struct dentry *dentry, mode_t mode,
1721 struct super_block *sb)
1723 static const struct dentry_operations cgroup_dops = {
1724 .d_iput = cgroup_diput,
1727 struct inode *inode;
1729 if (!dentry)
1730 return -ENOENT;
1731 if (dentry->d_inode)
1732 return -EEXIST;
1734 inode = cgroup_new_inode(mode, sb);
1735 if (!inode)
1736 return -ENOMEM;
1738 if (S_ISDIR(mode)) {
1739 inode->i_op = &cgroup_dir_inode_operations;
1740 inode->i_fop = &simple_dir_operations;
1742 /* start off with i_nlink == 2 (for "." entry) */
1743 inc_nlink(inode);
1745 /* start with the directory inode held, so that we can
1746 * populate it without racing with another mkdir */
1747 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
1748 } else if (S_ISREG(mode)) {
1749 inode->i_size = 0;
1750 inode->i_fop = &cgroup_file_operations;
1752 dentry->d_op = &cgroup_dops;
1753 d_instantiate(dentry, inode);
1754 dget(dentry); /* Extra count - pin the dentry in core */
1755 return 0;
1759 * cgroup_create_dir - create a directory for an object.
1760 * @cgrp: the cgroup we create the directory for. It must have a valid
1761 * ->parent field. And we are going to fill its ->dentry field.
1762 * @dentry: dentry of the new cgroup
1763 * @mode: mode to set on new directory.
1765 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
1766 mode_t mode)
1768 struct dentry *parent;
1769 int error = 0;
1771 parent = cgrp->parent->dentry;
1772 error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
1773 if (!error) {
1774 dentry->d_fsdata = cgrp;
1775 inc_nlink(parent->d_inode);
1776 rcu_assign_pointer(cgrp->dentry, dentry);
1777 dget(dentry);
1779 dput(dentry);
1781 return error;
1785 * cgroup_file_mode - deduce file mode of a control file
1786 * @cft: the control file in question
1788 * returns cft->mode if ->mode is not 0
1789 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1790 * returns S_IRUGO if it has only a read handler
1791 * returns S_IWUSR if it has only a write hander
1793 static mode_t cgroup_file_mode(const struct cftype *cft)
1795 mode_t mode = 0;
1797 if (cft->mode)
1798 return cft->mode;
1800 if (cft->read || cft->read_u64 || cft->read_s64 ||
1801 cft->read_map || cft->read_seq_string)
1802 mode |= S_IRUGO;
1804 if (cft->write || cft->write_u64 || cft->write_s64 ||
1805 cft->write_string || cft->trigger)
1806 mode |= S_IWUSR;
1808 return mode;
1811 int cgroup_add_file(struct cgroup *cgrp,
1812 struct cgroup_subsys *subsys,
1813 const struct cftype *cft)
1815 struct dentry *dir = cgrp->dentry;
1816 struct dentry *dentry;
1817 int error;
1818 mode_t mode;
1820 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
1821 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
1822 strcpy(name, subsys->name);
1823 strcat(name, ".");
1825 strcat(name, cft->name);
1826 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
1827 dentry = lookup_one_len(name, dir, strlen(name));
1828 if (!IS_ERR(dentry)) {
1829 mode = cgroup_file_mode(cft);
1830 error = cgroup_create_file(dentry, mode | S_IFREG,
1831 cgrp->root->sb);
1832 if (!error)
1833 dentry->d_fsdata = (void *)cft;
1834 dput(dentry);
1835 } else
1836 error = PTR_ERR(dentry);
1837 return error;
1840 int cgroup_add_files(struct cgroup *cgrp,
1841 struct cgroup_subsys *subsys,
1842 const struct cftype cft[],
1843 int count)
1845 int i, err;
1846 for (i = 0; i < count; i++) {
1847 err = cgroup_add_file(cgrp, subsys, &cft[i]);
1848 if (err)
1849 return err;
1851 return 0;
1855 * cgroup_task_count - count the number of tasks in a cgroup.
1856 * @cgrp: the cgroup in question
1858 * Return the number of tasks in the cgroup.
1860 int cgroup_task_count(const struct cgroup *cgrp)
1862 int count = 0;
1863 struct cg_cgroup_link *link;
1865 read_lock(&css_set_lock);
1866 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
1867 count += atomic_read(&link->cg->refcount);
1869 read_unlock(&css_set_lock);
1870 return count;
1874 * Advance a list_head iterator. The iterator should be positioned at
1875 * the start of a css_set
1877 static void cgroup_advance_iter(struct cgroup *cgrp,
1878 struct cgroup_iter *it)
1880 struct list_head *l = it->cg_link;
1881 struct cg_cgroup_link *link;
1882 struct css_set *cg;
1884 /* Advance to the next non-empty css_set */
1885 do {
1886 l = l->next;
1887 if (l == &cgrp->css_sets) {
1888 it->cg_link = NULL;
1889 return;
1891 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
1892 cg = link->cg;
1893 } while (list_empty(&cg->tasks));
1894 it->cg_link = l;
1895 it->task = cg->tasks.next;
1899 * To reduce the fork() overhead for systems that are not actually
1900 * using their cgroups capability, we don't maintain the lists running
1901 * through each css_set to its tasks until we see the list actually
1902 * used - in other words after the first call to cgroup_iter_start().
1904 * The tasklist_lock is not held here, as do_each_thread() and
1905 * while_each_thread() are protected by RCU.
1907 static void cgroup_enable_task_cg_lists(void)
1909 struct task_struct *p, *g;
1910 write_lock(&css_set_lock);
1911 use_task_css_set_links = 1;
1912 do_each_thread(g, p) {
1913 task_lock(p);
1915 * We should check if the process is exiting, otherwise
1916 * it will race with cgroup_exit() in that the list
1917 * entry won't be deleted though the process has exited.
1919 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
1920 list_add(&p->cg_list, &p->cgroups->tasks);
1921 task_unlock(p);
1922 } while_each_thread(g, p);
1923 write_unlock(&css_set_lock);
1926 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
1929 * The first time anyone tries to iterate across a cgroup,
1930 * we need to enable the list linking each css_set to its
1931 * tasks, and fix up all existing tasks.
1933 if (!use_task_css_set_links)
1934 cgroup_enable_task_cg_lists();
1936 read_lock(&css_set_lock);
1937 it->cg_link = &cgrp->css_sets;
1938 cgroup_advance_iter(cgrp, it);
1941 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
1942 struct cgroup_iter *it)
1944 struct task_struct *res;
1945 struct list_head *l = it->task;
1946 struct cg_cgroup_link *link;
1948 /* If the iterator cg is NULL, we have no tasks */
1949 if (!it->cg_link)
1950 return NULL;
1951 res = list_entry(l, struct task_struct, cg_list);
1952 /* Advance iterator to find next entry */
1953 l = l->next;
1954 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
1955 if (l == &link->cg->tasks) {
1956 /* We reached the end of this task list - move on to
1957 * the next cg_cgroup_link */
1958 cgroup_advance_iter(cgrp, it);
1959 } else {
1960 it->task = l;
1962 return res;
1965 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
1967 read_unlock(&css_set_lock);
1970 static inline int started_after_time(struct task_struct *t1,
1971 struct timespec *time,
1972 struct task_struct *t2)
1974 int start_diff = timespec_compare(&t1->start_time, time);
1975 if (start_diff > 0) {
1976 return 1;
1977 } else if (start_diff < 0) {
1978 return 0;
1979 } else {
1981 * Arbitrarily, if two processes started at the same
1982 * time, we'll say that the lower pointer value
1983 * started first. Note that t2 may have exited by now
1984 * so this may not be a valid pointer any longer, but
1985 * that's fine - it still serves to distinguish
1986 * between two tasks started (effectively) simultaneously.
1988 return t1 > t2;
1993 * This function is a callback from heap_insert() and is used to order
1994 * the heap.
1995 * In this case we order the heap in descending task start time.
1997 static inline int started_after(void *p1, void *p2)
1999 struct task_struct *t1 = p1;
2000 struct task_struct *t2 = p2;
2001 return started_after_time(t1, &t2->start_time, t2);
2005 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
2006 * @scan: struct cgroup_scanner containing arguments for the scan
2008 * Arguments include pointers to callback functions test_task() and
2009 * process_task().
2010 * Iterate through all the tasks in a cgroup, calling test_task() for each,
2011 * and if it returns true, call process_task() for it also.
2012 * The test_task pointer may be NULL, meaning always true (select all tasks).
2013 * Effectively duplicates cgroup_iter_{start,next,end}()
2014 * but does not lock css_set_lock for the call to process_task().
2015 * The struct cgroup_scanner may be embedded in any structure of the caller's
2016 * creation.
2017 * It is guaranteed that process_task() will act on every task that
2018 * is a member of the cgroup for the duration of this call. This
2019 * function may or may not call process_task() for tasks that exit
2020 * or move to a different cgroup during the call, or are forked or
2021 * move into the cgroup during the call.
2023 * Note that test_task() may be called with locks held, and may in some
2024 * situations be called multiple times for the same task, so it should
2025 * be cheap.
2026 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
2027 * pre-allocated and will be used for heap operations (and its "gt" member will
2028 * be overwritten), else a temporary heap will be used (allocation of which
2029 * may cause this function to fail).
2031 int cgroup_scan_tasks(struct cgroup_scanner *scan)
2033 int retval, i;
2034 struct cgroup_iter it;
2035 struct task_struct *p, *dropped;
2036 /* Never dereference latest_task, since it's not refcounted */
2037 struct task_struct *latest_task = NULL;
2038 struct ptr_heap tmp_heap;
2039 struct ptr_heap *heap;
2040 struct timespec latest_time = { 0, 0 };
2042 if (scan->heap) {
2043 /* The caller supplied our heap and pre-allocated its memory */
2044 heap = scan->heap;
2045 heap->gt = &started_after;
2046 } else {
2047 /* We need to allocate our own heap memory */
2048 heap = &tmp_heap;
2049 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2050 if (retval)
2051 /* cannot allocate the heap */
2052 return retval;
2055 again:
2057 * Scan tasks in the cgroup, using the scanner's "test_task" callback
2058 * to determine which are of interest, and using the scanner's
2059 * "process_task" callback to process any of them that need an update.
2060 * Since we don't want to hold any locks during the task updates,
2061 * gather tasks to be processed in a heap structure.
2062 * The heap is sorted by descending task start time.
2063 * If the statically-sized heap fills up, we overflow tasks that
2064 * started later, and in future iterations only consider tasks that
2065 * started after the latest task in the previous pass. This
2066 * guarantees forward progress and that we don't miss any tasks.
2068 heap->size = 0;
2069 cgroup_iter_start(scan->cg, &it);
2070 while ((p = cgroup_iter_next(scan->cg, &it))) {
2072 * Only affect tasks that qualify per the caller's callback,
2073 * if he provided one
2075 if (scan->test_task && !scan->test_task(p, scan))
2076 continue;
2078 * Only process tasks that started after the last task
2079 * we processed
2081 if (!started_after_time(p, &latest_time, latest_task))
2082 continue;
2083 dropped = heap_insert(heap, p);
2084 if (dropped == NULL) {
2086 * The new task was inserted; the heap wasn't
2087 * previously full
2089 get_task_struct(p);
2090 } else if (dropped != p) {
2092 * The new task was inserted, and pushed out a
2093 * different task
2095 get_task_struct(p);
2096 put_task_struct(dropped);
2099 * Else the new task was newer than anything already in
2100 * the heap and wasn't inserted
2103 cgroup_iter_end(scan->cg, &it);
2105 if (heap->size) {
2106 for (i = 0; i < heap->size; i++) {
2107 struct task_struct *q = heap->ptrs[i];
2108 if (i == 0) {
2109 latest_time = q->start_time;
2110 latest_task = q;
2112 /* Process the task per the caller's callback */
2113 scan->process_task(q, scan);
2114 put_task_struct(q);
2117 * If we had to process any tasks at all, scan again
2118 * in case some of them were in the middle of forking
2119 * children that didn't get processed.
2120 * Not the most efficient way to do it, but it avoids
2121 * having to take callback_mutex in the fork path
2123 goto again;
2125 if (heap == &tmp_heap)
2126 heap_free(&tmp_heap);
2127 return 0;
2131 * Stuff for reading the 'tasks' file.
2133 * Reading this file can return large amounts of data if a cgroup has
2134 * *lots* of attached tasks. So it may need several calls to read(),
2135 * but we cannot guarantee that the information we produce is correct
2136 * unless we produce it entirely atomically.
2141 * Load into 'pidarray' up to 'npids' of the tasks using cgroup
2142 * 'cgrp'. Return actual number of pids loaded. No need to
2143 * task_lock(p) when reading out p->cgroup, since we're in an RCU
2144 * read section, so the css_set can't go away, and is
2145 * immutable after creation.
2147 static int pid_array_load(pid_t *pidarray, int npids, struct cgroup *cgrp)
2149 int n = 0, pid;
2150 struct cgroup_iter it;
2151 struct task_struct *tsk;
2152 cgroup_iter_start(cgrp, &it);
2153 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2154 if (unlikely(n == npids))
2155 break;
2156 pid = task_pid_vnr(tsk);
2157 if (pid > 0)
2158 pidarray[n++] = pid;
2160 cgroup_iter_end(cgrp, &it);
2161 return n;
2165 * cgroupstats_build - build and fill cgroupstats
2166 * @stats: cgroupstats to fill information into
2167 * @dentry: A dentry entry belonging to the cgroup for which stats have
2168 * been requested.
2170 * Build and fill cgroupstats so that taskstats can export it to user
2171 * space.
2173 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2175 int ret = -EINVAL;
2176 struct cgroup *cgrp;
2177 struct cgroup_iter it;
2178 struct task_struct *tsk;
2181 * Validate dentry by checking the superblock operations,
2182 * and make sure it's a directory.
2184 if (dentry->d_sb->s_op != &cgroup_ops ||
2185 !S_ISDIR(dentry->d_inode->i_mode))
2186 goto err;
2188 ret = 0;
2189 cgrp = dentry->d_fsdata;
2191 cgroup_iter_start(cgrp, &it);
2192 while ((tsk = cgroup_iter_next(cgrp, &it))) {
2193 switch (tsk->state) {
2194 case TASK_RUNNING:
2195 stats->nr_running++;
2196 break;
2197 case TASK_INTERRUPTIBLE:
2198 stats->nr_sleeping++;
2199 break;
2200 case TASK_UNINTERRUPTIBLE:
2201 stats->nr_uninterruptible++;
2202 break;
2203 case TASK_STOPPED:
2204 stats->nr_stopped++;
2205 break;
2206 default:
2207 if (delayacct_is_task_waiting_on_io(tsk))
2208 stats->nr_io_wait++;
2209 break;
2212 cgroup_iter_end(cgrp, &it);
2214 err:
2215 return ret;
2219 * Cache pids for all threads in the same pid namespace that are
2220 * opening the same "tasks" file.
2222 struct cgroup_pids {
2223 /* The node in cgrp->pids_list */
2224 struct list_head list;
2225 /* The cgroup those pids belong to */
2226 struct cgroup *cgrp;
2227 /* The namepsace those pids belong to */
2228 struct pid_namespace *ns;
2229 /* Array of process ids in the cgroup */
2230 pid_t *tasks_pids;
2231 /* How many files are using the this tasks_pids array */
2232 int use_count;
2233 /* Length of the current tasks_pids array */
2234 int length;
2237 static int cmppid(const void *a, const void *b)
2239 return *(pid_t *)a - *(pid_t *)b;
2243 * seq_file methods for the "tasks" file. The seq_file position is the
2244 * next pid to display; the seq_file iterator is a pointer to the pid
2245 * in the cgroup->tasks_pids array.
2248 static void *cgroup_tasks_start(struct seq_file *s, loff_t *pos)
2251 * Initially we receive a position value that corresponds to
2252 * one more than the last pid shown (or 0 on the first call or
2253 * after a seek to the start). Use a binary-search to find the
2254 * next pid to display, if any
2256 struct cgroup_pids *cp = s->private;
2257 struct cgroup *cgrp = cp->cgrp;
2258 int index = 0, pid = *pos;
2259 int *iter;
2261 down_read(&cgrp->pids_mutex);
2262 if (pid) {
2263 int end = cp->length;
2265 while (index < end) {
2266 int mid = (index + end) / 2;
2267 if (cp->tasks_pids[mid] == pid) {
2268 index = mid;
2269 break;
2270 } else if (cp->tasks_pids[mid] <= pid)
2271 index = mid + 1;
2272 else
2273 end = mid;
2276 /* If we're off the end of the array, we're done */
2277 if (index >= cp->length)
2278 return NULL;
2279 /* Update the abstract position to be the actual pid that we found */
2280 iter = cp->tasks_pids + index;
2281 *pos = *iter;
2282 return iter;
2285 static void cgroup_tasks_stop(struct seq_file *s, void *v)
2287 struct cgroup_pids *cp = s->private;
2288 struct cgroup *cgrp = cp->cgrp;
2289 up_read(&cgrp->pids_mutex);
2292 static void *cgroup_tasks_next(struct seq_file *s, void *v, loff_t *pos)
2294 struct cgroup_pids *cp = s->private;
2295 int *p = v;
2296 int *end = cp->tasks_pids + cp->length;
2299 * Advance to the next pid in the array. If this goes off the
2300 * end, we're done
2302 p++;
2303 if (p >= end) {
2304 return NULL;
2305 } else {
2306 *pos = *p;
2307 return p;
2311 static int cgroup_tasks_show(struct seq_file *s, void *v)
2313 return seq_printf(s, "%d\n", *(int *)v);
2316 static struct seq_operations cgroup_tasks_seq_operations = {
2317 .start = cgroup_tasks_start,
2318 .stop = cgroup_tasks_stop,
2319 .next = cgroup_tasks_next,
2320 .show = cgroup_tasks_show,
2323 static void release_cgroup_pid_array(struct cgroup_pids *cp)
2325 struct cgroup *cgrp = cp->cgrp;
2327 down_write(&cgrp->pids_mutex);
2328 BUG_ON(!cp->use_count);
2329 if (!--cp->use_count) {
2330 list_del(&cp->list);
2331 put_pid_ns(cp->ns);
2332 kfree(cp->tasks_pids);
2333 kfree(cp);
2335 up_write(&cgrp->pids_mutex);
2338 static int cgroup_tasks_release(struct inode *inode, struct file *file)
2340 struct seq_file *seq;
2341 struct cgroup_pids *cp;
2343 if (!(file->f_mode & FMODE_READ))
2344 return 0;
2346 seq = file->private_data;
2347 cp = seq->private;
2349 release_cgroup_pid_array(cp);
2350 return seq_release(inode, file);
2353 static struct file_operations cgroup_tasks_operations = {
2354 .read = seq_read,
2355 .llseek = seq_lseek,
2356 .write = cgroup_file_write,
2357 .release = cgroup_tasks_release,
2361 * Handle an open on 'tasks' file. Prepare an array containing the
2362 * process id's of tasks currently attached to the cgroup being opened.
2365 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2367 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2368 struct pid_namespace *ns = current->nsproxy->pid_ns;
2369 struct cgroup_pids *cp;
2370 pid_t *pidarray;
2371 int npids;
2372 int retval;
2374 /* Nothing to do for write-only files */
2375 if (!(file->f_mode & FMODE_READ))
2376 return 0;
2379 * If cgroup gets more users after we read count, we won't have
2380 * enough space - tough. This race is indistinguishable to the
2381 * caller from the case that the additional cgroup users didn't
2382 * show up until sometime later on.
2384 npids = cgroup_task_count(cgrp);
2385 pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
2386 if (!pidarray)
2387 return -ENOMEM;
2388 npids = pid_array_load(pidarray, npids, cgrp);
2389 sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
2392 * Store the array in the cgroup, freeing the old
2393 * array if necessary
2395 down_write(&cgrp->pids_mutex);
2397 list_for_each_entry(cp, &cgrp->pids_list, list) {
2398 if (ns == cp->ns)
2399 goto found;
2402 cp = kzalloc(sizeof(*cp), GFP_KERNEL);
2403 if (!cp) {
2404 up_write(&cgrp->pids_mutex);
2405 kfree(pidarray);
2406 return -ENOMEM;
2408 cp->cgrp = cgrp;
2409 cp->ns = ns;
2410 get_pid_ns(ns);
2411 list_add(&cp->list, &cgrp->pids_list);
2412 found:
2413 kfree(cp->tasks_pids);
2414 cp->tasks_pids = pidarray;
2415 cp->length = npids;
2416 cp->use_count++;
2417 up_write(&cgrp->pids_mutex);
2419 file->f_op = &cgroup_tasks_operations;
2421 retval = seq_open(file, &cgroup_tasks_seq_operations);
2422 if (retval) {
2423 release_cgroup_pid_array(cp);
2424 return retval;
2426 ((struct seq_file *)file->private_data)->private = cp;
2427 return 0;
2430 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2431 struct cftype *cft)
2433 return notify_on_release(cgrp);
2436 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2437 struct cftype *cft,
2438 u64 val)
2440 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2441 if (val)
2442 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2443 else
2444 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2445 return 0;
2449 * for the common functions, 'private' gives the type of file
2451 static struct cftype files[] = {
2453 .name = "tasks",
2454 .open = cgroup_tasks_open,
2455 .write_u64 = cgroup_tasks_write,
2456 .release = cgroup_tasks_release,
2457 .private = FILE_TASKLIST,
2458 .mode = S_IRUGO | S_IWUSR,
2462 .name = "notify_on_release",
2463 .read_u64 = cgroup_read_notify_on_release,
2464 .write_u64 = cgroup_write_notify_on_release,
2465 .private = FILE_NOTIFY_ON_RELEASE,
2469 static struct cftype cft_release_agent = {
2470 .name = "release_agent",
2471 .read_seq_string = cgroup_release_agent_show,
2472 .write_string = cgroup_release_agent_write,
2473 .max_write_len = PATH_MAX,
2474 .private = FILE_RELEASE_AGENT,
2477 static int cgroup_populate_dir(struct cgroup *cgrp)
2479 int err;
2480 struct cgroup_subsys *ss;
2482 /* First clear out any existing files */
2483 cgroup_clear_directory(cgrp->dentry);
2485 err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2486 if (err < 0)
2487 return err;
2489 if (cgrp == cgrp->top_cgroup) {
2490 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2491 return err;
2494 for_each_subsys(cgrp->root, ss) {
2495 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2496 return err;
2498 /* This cgroup is ready now */
2499 for_each_subsys(cgrp->root, ss) {
2500 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2502 * Update id->css pointer and make this css visible from
2503 * CSS ID functions. This pointer will be dereferened
2504 * from RCU-read-side without locks.
2506 if (css->id)
2507 rcu_assign_pointer(css->id->css, css);
2510 return 0;
2513 static void init_cgroup_css(struct cgroup_subsys_state *css,
2514 struct cgroup_subsys *ss,
2515 struct cgroup *cgrp)
2517 css->cgroup = cgrp;
2518 atomic_set(&css->refcnt, 1);
2519 css->flags = 0;
2520 css->id = NULL;
2521 if (cgrp == dummytop)
2522 set_bit(CSS_ROOT, &css->flags);
2523 BUG_ON(cgrp->subsys[ss->subsys_id]);
2524 cgrp->subsys[ss->subsys_id] = css;
2527 static void cgroup_lock_hierarchy(struct cgroupfs_root *root)
2529 /* We need to take each hierarchy_mutex in a consistent order */
2530 int i;
2532 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2533 struct cgroup_subsys *ss = subsys[i];
2534 if (ss->root == root)
2535 mutex_lock(&ss->hierarchy_mutex);
2539 static void cgroup_unlock_hierarchy(struct cgroupfs_root *root)
2541 int i;
2543 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2544 struct cgroup_subsys *ss = subsys[i];
2545 if (ss->root == root)
2546 mutex_unlock(&ss->hierarchy_mutex);
2551 * cgroup_create - create a cgroup
2552 * @parent: cgroup that will be parent of the new cgroup
2553 * @dentry: dentry of the new cgroup
2554 * @mode: mode to set on new inode
2556 * Must be called with the mutex on the parent inode held
2558 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
2559 mode_t mode)
2561 struct cgroup *cgrp;
2562 struct cgroupfs_root *root = parent->root;
2563 int err = 0;
2564 struct cgroup_subsys *ss;
2565 struct super_block *sb = root->sb;
2567 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
2568 if (!cgrp)
2569 return -ENOMEM;
2571 /* Grab a reference on the superblock so the hierarchy doesn't
2572 * get deleted on unmount if there are child cgroups. This
2573 * can be done outside cgroup_mutex, since the sb can't
2574 * disappear while someone has an open control file on the
2575 * fs */
2576 atomic_inc(&sb->s_active);
2578 mutex_lock(&cgroup_mutex);
2580 init_cgroup_housekeeping(cgrp);
2582 cgrp->parent = parent;
2583 cgrp->root = parent->root;
2584 cgrp->top_cgroup = parent->top_cgroup;
2586 if (notify_on_release(parent))
2587 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2589 for_each_subsys(root, ss) {
2590 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
2591 if (IS_ERR(css)) {
2592 err = PTR_ERR(css);
2593 goto err_destroy;
2595 init_cgroup_css(css, ss, cgrp);
2596 if (ss->use_id)
2597 if (alloc_css_id(ss, parent, cgrp))
2598 goto err_destroy;
2599 /* At error, ->destroy() callback has to free assigned ID. */
2602 cgroup_lock_hierarchy(root);
2603 list_add(&cgrp->sibling, &cgrp->parent->children);
2604 cgroup_unlock_hierarchy(root);
2605 root->number_of_cgroups++;
2607 err = cgroup_create_dir(cgrp, dentry, mode);
2608 if (err < 0)
2609 goto err_remove;
2611 /* The cgroup directory was pre-locked for us */
2612 BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
2614 err = cgroup_populate_dir(cgrp);
2615 /* If err < 0, we have a half-filled directory - oh well ;) */
2617 mutex_unlock(&cgroup_mutex);
2618 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
2620 return 0;
2622 err_remove:
2624 cgroup_lock_hierarchy(root);
2625 list_del(&cgrp->sibling);
2626 cgroup_unlock_hierarchy(root);
2627 root->number_of_cgroups--;
2629 err_destroy:
2631 for_each_subsys(root, ss) {
2632 if (cgrp->subsys[ss->subsys_id])
2633 ss->destroy(ss, cgrp);
2636 mutex_unlock(&cgroup_mutex);
2638 /* Release the reference count that we took on the superblock */
2639 deactivate_super(sb);
2641 kfree(cgrp);
2642 return err;
2645 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2647 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
2649 /* the vfs holds inode->i_mutex already */
2650 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
2653 static int cgroup_has_css_refs(struct cgroup *cgrp)
2655 /* Check the reference count on each subsystem. Since we
2656 * already established that there are no tasks in the
2657 * cgroup, if the css refcount is also 1, then there should
2658 * be no outstanding references, so the subsystem is safe to
2659 * destroy. We scan across all subsystems rather than using
2660 * the per-hierarchy linked list of mounted subsystems since
2661 * we can be called via check_for_release() with no
2662 * synchronization other than RCU, and the subsystem linked
2663 * list isn't RCU-safe */
2664 int i;
2665 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2666 struct cgroup_subsys *ss = subsys[i];
2667 struct cgroup_subsys_state *css;
2668 /* Skip subsystems not in this hierarchy */
2669 if (ss->root != cgrp->root)
2670 continue;
2671 css = cgrp->subsys[ss->subsys_id];
2672 /* When called from check_for_release() it's possible
2673 * that by this point the cgroup has been removed
2674 * and the css deleted. But a false-positive doesn't
2675 * matter, since it can only happen if the cgroup
2676 * has been deleted and hence no longer needs the
2677 * release agent to be called anyway. */
2678 if (css && (atomic_read(&css->refcnt) > 1))
2679 return 1;
2681 return 0;
2685 * Atomically mark all (or else none) of the cgroup's CSS objects as
2686 * CSS_REMOVED. Return true on success, or false if the cgroup has
2687 * busy subsystems. Call with cgroup_mutex held
2690 static int cgroup_clear_css_refs(struct cgroup *cgrp)
2692 struct cgroup_subsys *ss;
2693 unsigned long flags;
2694 bool failed = false;
2695 local_irq_save(flags);
2696 for_each_subsys(cgrp->root, ss) {
2697 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2698 int refcnt;
2699 while (1) {
2700 /* We can only remove a CSS with a refcnt==1 */
2701 refcnt = atomic_read(&css->refcnt);
2702 if (refcnt > 1) {
2703 failed = true;
2704 goto done;
2706 BUG_ON(!refcnt);
2708 * Drop the refcnt to 0 while we check other
2709 * subsystems. This will cause any racing
2710 * css_tryget() to spin until we set the
2711 * CSS_REMOVED bits or abort
2713 if (atomic_cmpxchg(&css->refcnt, refcnt, 0) == refcnt)
2714 break;
2715 cpu_relax();
2718 done:
2719 for_each_subsys(cgrp->root, ss) {
2720 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2721 if (failed) {
2723 * Restore old refcnt if we previously managed
2724 * to clear it from 1 to 0
2726 if (!atomic_read(&css->refcnt))
2727 atomic_set(&css->refcnt, 1);
2728 } else {
2729 /* Commit the fact that the CSS is removed */
2730 set_bit(CSS_REMOVED, &css->flags);
2733 local_irq_restore(flags);
2734 return !failed;
2737 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
2739 struct cgroup *cgrp = dentry->d_fsdata;
2740 struct dentry *d;
2741 struct cgroup *parent;
2742 DEFINE_WAIT(wait);
2743 int ret;
2745 /* the vfs holds both inode->i_mutex already */
2746 again:
2747 mutex_lock(&cgroup_mutex);
2748 if (atomic_read(&cgrp->count) != 0) {
2749 mutex_unlock(&cgroup_mutex);
2750 return -EBUSY;
2752 if (!list_empty(&cgrp->children)) {
2753 mutex_unlock(&cgroup_mutex);
2754 return -EBUSY;
2756 mutex_unlock(&cgroup_mutex);
2759 * In general, subsystem has no css->refcnt after pre_destroy(). But
2760 * in racy cases, subsystem may have to get css->refcnt after
2761 * pre_destroy() and it makes rmdir return with -EBUSY. This sometimes
2762 * make rmdir return -EBUSY too often. To avoid that, we use waitqueue
2763 * for cgroup's rmdir. CGRP_WAIT_ON_RMDIR is for synchronizing rmdir
2764 * and subsystem's reference count handling. Please see css_get/put
2765 * and css_tryget() and cgroup_wakeup_rmdir_waiter() implementation.
2767 set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2770 * Call pre_destroy handlers of subsys. Notify subsystems
2771 * that rmdir() request comes.
2773 ret = cgroup_call_pre_destroy(cgrp);
2774 if (ret) {
2775 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2776 return ret;
2779 mutex_lock(&cgroup_mutex);
2780 parent = cgrp->parent;
2781 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
2782 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2783 mutex_unlock(&cgroup_mutex);
2784 return -EBUSY;
2786 prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
2787 if (!cgroup_clear_css_refs(cgrp)) {
2788 mutex_unlock(&cgroup_mutex);
2790 * Because someone may call cgroup_wakeup_rmdir_waiter() before
2791 * prepare_to_wait(), we need to check this flag.
2793 if (test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))
2794 schedule();
2795 finish_wait(&cgroup_rmdir_waitq, &wait);
2796 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2797 if (signal_pending(current))
2798 return -EINTR;
2799 goto again;
2801 /* NO css_tryget() can success after here. */
2802 finish_wait(&cgroup_rmdir_waitq, &wait);
2803 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
2805 spin_lock(&release_list_lock);
2806 set_bit(CGRP_REMOVED, &cgrp->flags);
2807 if (!list_empty(&cgrp->release_list))
2808 list_del(&cgrp->release_list);
2809 spin_unlock(&release_list_lock);
2811 cgroup_lock_hierarchy(cgrp->root);
2812 /* delete this cgroup from parent->children */
2813 list_del(&cgrp->sibling);
2814 cgroup_unlock_hierarchy(cgrp->root);
2816 spin_lock(&cgrp->dentry->d_lock);
2817 d = dget(cgrp->dentry);
2818 spin_unlock(&d->d_lock);
2820 cgroup_d_remove_dir(d);
2821 dput(d);
2823 set_bit(CGRP_RELEASABLE, &parent->flags);
2824 check_for_release(parent);
2826 mutex_unlock(&cgroup_mutex);
2827 return 0;
2830 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
2832 struct cgroup_subsys_state *css;
2834 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
2836 /* Create the top cgroup state for this subsystem */
2837 list_add(&ss->sibling, &rootnode.subsys_list);
2838 ss->root = &rootnode;
2839 css = ss->create(ss, dummytop);
2840 /* We don't handle early failures gracefully */
2841 BUG_ON(IS_ERR(css));
2842 init_cgroup_css(css, ss, dummytop);
2844 /* Update the init_css_set to contain a subsys
2845 * pointer to this state - since the subsystem is
2846 * newly registered, all tasks and hence the
2847 * init_css_set is in the subsystem's top cgroup. */
2848 init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
2850 need_forkexit_callback |= ss->fork || ss->exit;
2852 /* At system boot, before all subsystems have been
2853 * registered, no tasks have been forked, so we don't
2854 * need to invoke fork callbacks here. */
2855 BUG_ON(!list_empty(&init_task.tasks));
2857 mutex_init(&ss->hierarchy_mutex);
2858 lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
2859 ss->active = 1;
2863 * cgroup_init_early - cgroup initialization at system boot
2865 * Initialize cgroups at system boot, and initialize any
2866 * subsystems that request early init.
2868 int __init cgroup_init_early(void)
2870 int i;
2871 atomic_set(&init_css_set.refcount, 1);
2872 INIT_LIST_HEAD(&init_css_set.cg_links);
2873 INIT_LIST_HEAD(&init_css_set.tasks);
2874 INIT_HLIST_NODE(&init_css_set.hlist);
2875 css_set_count = 1;
2876 init_cgroup_root(&rootnode);
2877 root_count = 1;
2878 init_task.cgroups = &init_css_set;
2880 init_css_set_link.cg = &init_css_set;
2881 list_add(&init_css_set_link.cgrp_link_list,
2882 &rootnode.top_cgroup.css_sets);
2883 list_add(&init_css_set_link.cg_link_list,
2884 &init_css_set.cg_links);
2886 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
2887 INIT_HLIST_HEAD(&css_set_table[i]);
2889 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2890 struct cgroup_subsys *ss = subsys[i];
2892 BUG_ON(!ss->name);
2893 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
2894 BUG_ON(!ss->create);
2895 BUG_ON(!ss->destroy);
2896 if (ss->subsys_id != i) {
2897 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
2898 ss->name, ss->subsys_id);
2899 BUG();
2902 if (ss->early_init)
2903 cgroup_init_subsys(ss);
2905 return 0;
2909 * cgroup_init - cgroup initialization
2911 * Register cgroup filesystem and /proc file, and initialize
2912 * any subsystems that didn't request early init.
2914 int __init cgroup_init(void)
2916 int err;
2917 int i;
2918 struct hlist_head *hhead;
2920 err = bdi_init(&cgroup_backing_dev_info);
2921 if (err)
2922 return err;
2924 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2925 struct cgroup_subsys *ss = subsys[i];
2926 if (!ss->early_init)
2927 cgroup_init_subsys(ss);
2928 if (ss->use_id)
2929 cgroup_subsys_init_idr(ss);
2932 /* Add init_css_set to the hash table */
2933 hhead = css_set_hash(init_css_set.subsys);
2934 hlist_add_head(&init_css_set.hlist, hhead);
2936 err = register_filesystem(&cgroup_fs_type);
2937 if (err < 0)
2938 goto out;
2940 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
2942 out:
2943 if (err)
2944 bdi_destroy(&cgroup_backing_dev_info);
2946 return err;
2950 * proc_cgroup_show()
2951 * - Print task's cgroup paths into seq_file, one line for each hierarchy
2952 * - Used for /proc/<pid>/cgroup.
2953 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
2954 * doesn't really matter if tsk->cgroup changes after we read it,
2955 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
2956 * anyway. No need to check that tsk->cgroup != NULL, thanks to
2957 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
2958 * cgroup to top_cgroup.
2961 /* TODO: Use a proper seq_file iterator */
2962 static int proc_cgroup_show(struct seq_file *m, void *v)
2964 struct pid *pid;
2965 struct task_struct *tsk;
2966 char *buf;
2967 int retval;
2968 struct cgroupfs_root *root;
2970 retval = -ENOMEM;
2971 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
2972 if (!buf)
2973 goto out;
2975 retval = -ESRCH;
2976 pid = m->private;
2977 tsk = get_pid_task(pid, PIDTYPE_PID);
2978 if (!tsk)
2979 goto out_free;
2981 retval = 0;
2983 mutex_lock(&cgroup_mutex);
2985 for_each_active_root(root) {
2986 struct cgroup_subsys *ss;
2987 struct cgroup *cgrp;
2988 int subsys_id;
2989 int count = 0;
2991 seq_printf(m, "%lu:", root->subsys_bits);
2992 for_each_subsys(root, ss)
2993 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
2994 seq_putc(m, ':');
2995 get_first_subsys(&root->top_cgroup, NULL, &subsys_id);
2996 cgrp = task_cgroup(tsk, subsys_id);
2997 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
2998 if (retval < 0)
2999 goto out_unlock;
3000 seq_puts(m, buf);
3001 seq_putc(m, '\n');
3004 out_unlock:
3005 mutex_unlock(&cgroup_mutex);
3006 put_task_struct(tsk);
3007 out_free:
3008 kfree(buf);
3009 out:
3010 return retval;
3013 static int cgroup_open(struct inode *inode, struct file *file)
3015 struct pid *pid = PROC_I(inode)->pid;
3016 return single_open(file, proc_cgroup_show, pid);
3019 struct file_operations proc_cgroup_operations = {
3020 .open = cgroup_open,
3021 .read = seq_read,
3022 .llseek = seq_lseek,
3023 .release = single_release,
3026 /* Display information about each subsystem and each hierarchy */
3027 static int proc_cgroupstats_show(struct seq_file *m, void *v)
3029 int i;
3031 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
3032 mutex_lock(&cgroup_mutex);
3033 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3034 struct cgroup_subsys *ss = subsys[i];
3035 seq_printf(m, "%s\t%lu\t%d\t%d\n",
3036 ss->name, ss->root->subsys_bits,
3037 ss->root->number_of_cgroups, !ss->disabled);
3039 mutex_unlock(&cgroup_mutex);
3040 return 0;
3043 static int cgroupstats_open(struct inode *inode, struct file *file)
3045 return single_open(file, proc_cgroupstats_show, NULL);
3048 static struct file_operations proc_cgroupstats_operations = {
3049 .open = cgroupstats_open,
3050 .read = seq_read,
3051 .llseek = seq_lseek,
3052 .release = single_release,
3056 * cgroup_fork - attach newly forked task to its parents cgroup.
3057 * @child: pointer to task_struct of forking parent process.
3059 * Description: A task inherits its parent's cgroup at fork().
3061 * A pointer to the shared css_set was automatically copied in
3062 * fork.c by dup_task_struct(). However, we ignore that copy, since
3063 * it was not made under the protection of RCU or cgroup_mutex, so
3064 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
3065 * have already changed current->cgroups, allowing the previously
3066 * referenced cgroup group to be removed and freed.
3068 * At the point that cgroup_fork() is called, 'current' is the parent
3069 * task, and the passed argument 'child' points to the child task.
3071 void cgroup_fork(struct task_struct *child)
3073 task_lock(current);
3074 child->cgroups = current->cgroups;
3075 get_css_set(child->cgroups);
3076 task_unlock(current);
3077 INIT_LIST_HEAD(&child->cg_list);
3081 * cgroup_fork_callbacks - run fork callbacks
3082 * @child: the new task
3084 * Called on a new task very soon before adding it to the
3085 * tasklist. No need to take any locks since no-one can
3086 * be operating on this task.
3088 void cgroup_fork_callbacks(struct task_struct *child)
3090 if (need_forkexit_callback) {
3091 int i;
3092 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3093 struct cgroup_subsys *ss = subsys[i];
3094 if (ss->fork)
3095 ss->fork(ss, child);
3101 * cgroup_post_fork - called on a new task after adding it to the task list
3102 * @child: the task in question
3104 * Adds the task to the list running through its css_set if necessary.
3105 * Has to be after the task is visible on the task list in case we race
3106 * with the first call to cgroup_iter_start() - to guarantee that the
3107 * new task ends up on its list.
3109 void cgroup_post_fork(struct task_struct *child)
3111 if (use_task_css_set_links) {
3112 write_lock(&css_set_lock);
3113 task_lock(child);
3114 if (list_empty(&child->cg_list))
3115 list_add(&child->cg_list, &child->cgroups->tasks);
3116 task_unlock(child);
3117 write_unlock(&css_set_lock);
3121 * cgroup_exit - detach cgroup from exiting task
3122 * @tsk: pointer to task_struct of exiting process
3123 * @run_callback: run exit callbacks?
3125 * Description: Detach cgroup from @tsk and release it.
3127 * Note that cgroups marked notify_on_release force every task in
3128 * them to take the global cgroup_mutex mutex when exiting.
3129 * This could impact scaling on very large systems. Be reluctant to
3130 * use notify_on_release cgroups where very high task exit scaling
3131 * is required on large systems.
3133 * the_top_cgroup_hack:
3135 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
3137 * We call cgroup_exit() while the task is still competent to
3138 * handle notify_on_release(), then leave the task attached to the
3139 * root cgroup in each hierarchy for the remainder of its exit.
3141 * To do this properly, we would increment the reference count on
3142 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
3143 * code we would add a second cgroup function call, to drop that
3144 * reference. This would just create an unnecessary hot spot on
3145 * the top_cgroup reference count, to no avail.
3147 * Normally, holding a reference to a cgroup without bumping its
3148 * count is unsafe. The cgroup could go away, or someone could
3149 * attach us to a different cgroup, decrementing the count on
3150 * the first cgroup that we never incremented. But in this case,
3151 * top_cgroup isn't going away, and either task has PF_EXITING set,
3152 * which wards off any cgroup_attach_task() attempts, or task is a failed
3153 * fork, never visible to cgroup_attach_task.
3155 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
3157 int i;
3158 struct css_set *cg;
3160 if (run_callbacks && need_forkexit_callback) {
3161 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3162 struct cgroup_subsys *ss = subsys[i];
3163 if (ss->exit)
3164 ss->exit(ss, tsk);
3169 * Unlink from the css_set task list if necessary.
3170 * Optimistically check cg_list before taking
3171 * css_set_lock
3173 if (!list_empty(&tsk->cg_list)) {
3174 write_lock(&css_set_lock);
3175 if (!list_empty(&tsk->cg_list))
3176 list_del(&tsk->cg_list);
3177 write_unlock(&css_set_lock);
3180 /* Reassign the task to the init_css_set. */
3181 task_lock(tsk);
3182 cg = tsk->cgroups;
3183 tsk->cgroups = &init_css_set;
3184 task_unlock(tsk);
3185 if (cg)
3186 put_css_set_taskexit(cg);
3190 * cgroup_clone - clone the cgroup the given subsystem is attached to
3191 * @tsk: the task to be moved
3192 * @subsys: the given subsystem
3193 * @nodename: the name for the new cgroup
3195 * Duplicate the current cgroup in the hierarchy that the given
3196 * subsystem is attached to, and move this task into the new
3197 * child.
3199 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
3200 char *nodename)
3202 struct dentry *dentry;
3203 int ret = 0;
3204 struct cgroup *parent, *child;
3205 struct inode *inode;
3206 struct css_set *cg;
3207 struct cgroupfs_root *root;
3208 struct cgroup_subsys *ss;
3210 /* We shouldn't be called by an unregistered subsystem */
3211 BUG_ON(!subsys->active);
3213 /* First figure out what hierarchy and cgroup we're dealing
3214 * with, and pin them so we can drop cgroup_mutex */
3215 mutex_lock(&cgroup_mutex);
3216 again:
3217 root = subsys->root;
3218 if (root == &rootnode) {
3219 mutex_unlock(&cgroup_mutex);
3220 return 0;
3223 /* Pin the hierarchy */
3224 if (!atomic_inc_not_zero(&root->sb->s_active)) {
3225 /* We race with the final deactivate_super() */
3226 mutex_unlock(&cgroup_mutex);
3227 return 0;
3230 /* Keep the cgroup alive */
3231 task_lock(tsk);
3232 parent = task_cgroup(tsk, subsys->subsys_id);
3233 cg = tsk->cgroups;
3234 get_css_set(cg);
3235 task_unlock(tsk);
3237 mutex_unlock(&cgroup_mutex);
3239 /* Now do the VFS work to create a cgroup */
3240 inode = parent->dentry->d_inode;
3242 /* Hold the parent directory mutex across this operation to
3243 * stop anyone else deleting the new cgroup */
3244 mutex_lock(&inode->i_mutex);
3245 dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
3246 if (IS_ERR(dentry)) {
3247 printk(KERN_INFO
3248 "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
3249 PTR_ERR(dentry));
3250 ret = PTR_ERR(dentry);
3251 goto out_release;
3254 /* Create the cgroup directory, which also creates the cgroup */
3255 ret = vfs_mkdir(inode, dentry, 0755);
3256 child = __d_cgrp(dentry);
3257 dput(dentry);
3258 if (ret) {
3259 printk(KERN_INFO
3260 "Failed to create cgroup %s: %d\n", nodename,
3261 ret);
3262 goto out_release;
3265 /* The cgroup now exists. Retake cgroup_mutex and check
3266 * that we're still in the same state that we thought we
3267 * were. */
3268 mutex_lock(&cgroup_mutex);
3269 if ((root != subsys->root) ||
3270 (parent != task_cgroup(tsk, subsys->subsys_id))) {
3271 /* Aargh, we raced ... */
3272 mutex_unlock(&inode->i_mutex);
3273 put_css_set(cg);
3275 deactivate_super(root->sb);
3276 /* The cgroup is still accessible in the VFS, but
3277 * we're not going to try to rmdir() it at this
3278 * point. */
3279 printk(KERN_INFO
3280 "Race in cgroup_clone() - leaking cgroup %s\n",
3281 nodename);
3282 goto again;
3285 /* do any required auto-setup */
3286 for_each_subsys(root, ss) {
3287 if (ss->post_clone)
3288 ss->post_clone(ss, child);
3291 /* All seems fine. Finish by moving the task into the new cgroup */
3292 ret = cgroup_attach_task(child, tsk);
3293 mutex_unlock(&cgroup_mutex);
3295 out_release:
3296 mutex_unlock(&inode->i_mutex);
3298 mutex_lock(&cgroup_mutex);
3299 put_css_set(cg);
3300 mutex_unlock(&cgroup_mutex);
3301 deactivate_super(root->sb);
3302 return ret;
3306 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
3307 * @cgrp: the cgroup in question
3308 * @task: the task in question
3310 * See if @cgrp is a descendant of @task's cgroup in the appropriate
3311 * hierarchy.
3313 * If we are sending in dummytop, then presumably we are creating
3314 * the top cgroup in the subsystem.
3316 * Called only by the ns (nsproxy) cgroup.
3318 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
3320 int ret;
3321 struct cgroup *target;
3322 int subsys_id;
3324 if (cgrp == dummytop)
3325 return 1;
3327 get_first_subsys(cgrp, NULL, &subsys_id);
3328 target = task_cgroup(task, subsys_id);
3329 while (cgrp != target && cgrp!= cgrp->top_cgroup)
3330 cgrp = cgrp->parent;
3331 ret = (cgrp == target);
3332 return ret;
3335 static void check_for_release(struct cgroup *cgrp)
3337 /* All of these checks rely on RCU to keep the cgroup
3338 * structure alive */
3339 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
3340 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
3341 /* Control Group is currently removeable. If it's not
3342 * already queued for a userspace notification, queue
3343 * it now */
3344 int need_schedule_work = 0;
3345 spin_lock(&release_list_lock);
3346 if (!cgroup_is_removed(cgrp) &&
3347 list_empty(&cgrp->release_list)) {
3348 list_add(&cgrp->release_list, &release_list);
3349 need_schedule_work = 1;
3351 spin_unlock(&release_list_lock);
3352 if (need_schedule_work)
3353 schedule_work(&release_agent_work);
3357 void __css_put(struct cgroup_subsys_state *css)
3359 struct cgroup *cgrp = css->cgroup;
3360 rcu_read_lock();
3361 if (atomic_dec_return(&css->refcnt) == 1) {
3362 if (notify_on_release(cgrp)) {
3363 set_bit(CGRP_RELEASABLE, &cgrp->flags);
3364 check_for_release(cgrp);
3366 cgroup_wakeup_rmdir_waiter(cgrp);
3368 rcu_read_unlock();
3372 * Notify userspace when a cgroup is released, by running the
3373 * configured release agent with the name of the cgroup (path
3374 * relative to the root of cgroup file system) as the argument.
3376 * Most likely, this user command will try to rmdir this cgroup.
3378 * This races with the possibility that some other task will be
3379 * attached to this cgroup before it is removed, or that some other
3380 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
3381 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
3382 * unused, and this cgroup will be reprieved from its death sentence,
3383 * to continue to serve a useful existence. Next time it's released,
3384 * we will get notified again, if it still has 'notify_on_release' set.
3386 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
3387 * means only wait until the task is successfully execve()'d. The
3388 * separate release agent task is forked by call_usermodehelper(),
3389 * then control in this thread returns here, without waiting for the
3390 * release agent task. We don't bother to wait because the caller of
3391 * this routine has no use for the exit status of the release agent
3392 * task, so no sense holding our caller up for that.
3394 static void cgroup_release_agent(struct work_struct *work)
3396 BUG_ON(work != &release_agent_work);
3397 mutex_lock(&cgroup_mutex);
3398 spin_lock(&release_list_lock);
3399 while (!list_empty(&release_list)) {
3400 char *argv[3], *envp[3];
3401 int i;
3402 char *pathbuf = NULL, *agentbuf = NULL;
3403 struct cgroup *cgrp = list_entry(release_list.next,
3404 struct cgroup,
3405 release_list);
3406 list_del_init(&cgrp->release_list);
3407 spin_unlock(&release_list_lock);
3408 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3409 if (!pathbuf)
3410 goto continue_free;
3411 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
3412 goto continue_free;
3413 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
3414 if (!agentbuf)
3415 goto continue_free;
3417 i = 0;
3418 argv[i++] = agentbuf;
3419 argv[i++] = pathbuf;
3420 argv[i] = NULL;
3422 i = 0;
3423 /* minimal command environment */
3424 envp[i++] = "HOME=/";
3425 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3426 envp[i] = NULL;
3428 /* Drop the lock while we invoke the usermode helper,
3429 * since the exec could involve hitting disk and hence
3430 * be a slow process */
3431 mutex_unlock(&cgroup_mutex);
3432 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3433 mutex_lock(&cgroup_mutex);
3434 continue_free:
3435 kfree(pathbuf);
3436 kfree(agentbuf);
3437 spin_lock(&release_list_lock);
3439 spin_unlock(&release_list_lock);
3440 mutex_unlock(&cgroup_mutex);
3443 static int __init cgroup_disable(char *str)
3445 int i;
3446 char *token;
3448 while ((token = strsep(&str, ",")) != NULL) {
3449 if (!*token)
3450 continue;
3452 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3453 struct cgroup_subsys *ss = subsys[i];
3455 if (!strcmp(token, ss->name)) {
3456 ss->disabled = 1;
3457 printk(KERN_INFO "Disabling %s control group"
3458 " subsystem\n", ss->name);
3459 break;
3463 return 1;
3465 __setup("cgroup_disable=", cgroup_disable);
3468 * Functons for CSS ID.
3472 *To get ID other than 0, this should be called when !cgroup_is_removed().
3474 unsigned short css_id(struct cgroup_subsys_state *css)
3476 struct css_id *cssid = rcu_dereference(css->id);
3478 if (cssid)
3479 return cssid->id;
3480 return 0;
3483 unsigned short css_depth(struct cgroup_subsys_state *css)
3485 struct css_id *cssid = rcu_dereference(css->id);
3487 if (cssid)
3488 return cssid->depth;
3489 return 0;
3492 bool css_is_ancestor(struct cgroup_subsys_state *child,
3493 const struct cgroup_subsys_state *root)
3495 struct css_id *child_id = rcu_dereference(child->id);
3496 struct css_id *root_id = rcu_dereference(root->id);
3498 if (!child_id || !root_id || (child_id->depth < root_id->depth))
3499 return false;
3500 return child_id->stack[root_id->depth] == root_id->id;
3503 static void __free_css_id_cb(struct rcu_head *head)
3505 struct css_id *id;
3507 id = container_of(head, struct css_id, rcu_head);
3508 kfree(id);
3511 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
3513 struct css_id *id = css->id;
3514 /* When this is called before css_id initialization, id can be NULL */
3515 if (!id)
3516 return;
3518 BUG_ON(!ss->use_id);
3520 rcu_assign_pointer(id->css, NULL);
3521 rcu_assign_pointer(css->id, NULL);
3522 spin_lock(&ss->id_lock);
3523 idr_remove(&ss->idr, id->id);
3524 spin_unlock(&ss->id_lock);
3525 call_rcu(&id->rcu_head, __free_css_id_cb);
3529 * This is called by init or create(). Then, calls to this function are
3530 * always serialized (By cgroup_mutex() at create()).
3533 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
3535 struct css_id *newid;
3536 int myid, error, size;
3538 BUG_ON(!ss->use_id);
3540 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
3541 newid = kzalloc(size, GFP_KERNEL);
3542 if (!newid)
3543 return ERR_PTR(-ENOMEM);
3544 /* get id */
3545 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
3546 error = -ENOMEM;
3547 goto err_out;
3549 spin_lock(&ss->id_lock);
3550 /* Don't use 0. allocates an ID of 1-65535 */
3551 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
3552 spin_unlock(&ss->id_lock);
3554 /* Returns error when there are no free spaces for new ID.*/
3555 if (error) {
3556 error = -ENOSPC;
3557 goto err_out;
3559 if (myid > CSS_ID_MAX)
3560 goto remove_idr;
3562 newid->id = myid;
3563 newid->depth = depth;
3564 return newid;
3565 remove_idr:
3566 error = -ENOSPC;
3567 spin_lock(&ss->id_lock);
3568 idr_remove(&ss->idr, myid);
3569 spin_unlock(&ss->id_lock);
3570 err_out:
3571 kfree(newid);
3572 return ERR_PTR(error);
3576 static int __init cgroup_subsys_init_idr(struct cgroup_subsys *ss)
3578 struct css_id *newid;
3579 struct cgroup_subsys_state *rootcss;
3581 spin_lock_init(&ss->id_lock);
3582 idr_init(&ss->idr);
3584 rootcss = init_css_set.subsys[ss->subsys_id];
3585 newid = get_new_cssid(ss, 0);
3586 if (IS_ERR(newid))
3587 return PTR_ERR(newid);
3589 newid->stack[0] = newid->id;
3590 newid->css = rootcss;
3591 rootcss->id = newid;
3592 return 0;
3595 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
3596 struct cgroup *child)
3598 int subsys_id, i, depth = 0;
3599 struct cgroup_subsys_state *parent_css, *child_css;
3600 struct css_id *child_id, *parent_id = NULL;
3602 subsys_id = ss->subsys_id;
3603 parent_css = parent->subsys[subsys_id];
3604 child_css = child->subsys[subsys_id];
3605 depth = css_depth(parent_css) + 1;
3606 parent_id = parent_css->id;
3608 child_id = get_new_cssid(ss, depth);
3609 if (IS_ERR(child_id))
3610 return PTR_ERR(child_id);
3612 for (i = 0; i < depth; i++)
3613 child_id->stack[i] = parent_id->stack[i];
3614 child_id->stack[depth] = child_id->id;
3616 * child_id->css pointer will be set after this cgroup is available
3617 * see cgroup_populate_dir()
3619 rcu_assign_pointer(child_css->id, child_id);
3621 return 0;
3625 * css_lookup - lookup css by id
3626 * @ss: cgroup subsys to be looked into.
3627 * @id: the id
3629 * Returns pointer to cgroup_subsys_state if there is valid one with id.
3630 * NULL if not. Should be called under rcu_read_lock()
3632 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
3634 struct css_id *cssid = NULL;
3636 BUG_ON(!ss->use_id);
3637 cssid = idr_find(&ss->idr, id);
3639 if (unlikely(!cssid))
3640 return NULL;
3642 return rcu_dereference(cssid->css);
3646 * css_get_next - lookup next cgroup under specified hierarchy.
3647 * @ss: pointer to subsystem
3648 * @id: current position of iteration.
3649 * @root: pointer to css. search tree under this.
3650 * @foundid: position of found object.
3652 * Search next css under the specified hierarchy of rootid. Calling under
3653 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
3655 struct cgroup_subsys_state *
3656 css_get_next(struct cgroup_subsys *ss, int id,
3657 struct cgroup_subsys_state *root, int *foundid)
3659 struct cgroup_subsys_state *ret = NULL;
3660 struct css_id *tmp;
3661 int tmpid;
3662 int rootid = css_id(root);
3663 int depth = css_depth(root);
3665 if (!rootid)
3666 return NULL;
3668 BUG_ON(!ss->use_id);
3669 /* fill start point for scan */
3670 tmpid = id;
3671 while (1) {
3673 * scan next entry from bitmap(tree), tmpid is updated after
3674 * idr_get_next().
3676 spin_lock(&ss->id_lock);
3677 tmp = idr_get_next(&ss->idr, &tmpid);
3678 spin_unlock(&ss->id_lock);
3680 if (!tmp)
3681 break;
3682 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
3683 ret = rcu_dereference(tmp->css);
3684 if (ret) {
3685 *foundid = tmpid;
3686 break;
3689 /* continue to scan from next id */
3690 tmpid = tmpid + 1;
3692 return ret;