Merge branch 'cgroup-rmdir-updates' into cgroup/for-3.8
[linux-2.6/libata-dev.git] / kernel / cgroup.c
blobe3045ad4267a94fed84a99c84ab6b5f36b3fd436
1 /*
2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/fs.h>
34 #include <linux/init_task.h>
35 #include <linux/kernel.h>
36 #include <linux/list.h>
37 #include <linux/mm.h>
38 #include <linux/mutex.h>
39 #include <linux/mount.h>
40 #include <linux/pagemap.h>
41 #include <linux/proc_fs.h>
42 #include <linux/rcupdate.h>
43 #include <linux/sched.h>
44 #include <linux/backing-dev.h>
45 #include <linux/seq_file.h>
46 #include <linux/slab.h>
47 #include <linux/magic.h>
48 #include <linux/spinlock.h>
49 #include <linux/string.h>
50 #include <linux/sort.h>
51 #include <linux/kmod.h>
52 #include <linux/module.h>
53 #include <linux/delayacct.h>
54 #include <linux/cgroupstats.h>
55 #include <linux/hash.h>
56 #include <linux/namei.h>
57 #include <linux/pid_namespace.h>
58 #include <linux/idr.h>
59 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
60 #include <linux/eventfd.h>
61 #include <linux/poll.h>
62 #include <linux/flex_array.h> /* used in cgroup_attach_proc */
63 #include <linux/kthread.h>
65 #include <linux/atomic.h>
67 /* css deactivation bias, makes css->refcnt negative to deny new trygets */
68 #define CSS_DEACT_BIAS INT_MIN
71 * cgroup_mutex is the master lock. Any modification to cgroup or its
72 * hierarchy must be performed while holding it.
74 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
75 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
76 * release_agent_path and so on. Modifying requires both cgroup_mutex and
77 * cgroup_root_mutex. Readers can acquire either of the two. This is to
78 * break the following locking order cycle.
80 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
81 * B. namespace_sem -> cgroup_mutex
83 * B happens only through cgroup_show_options() and using cgroup_root_mutex
84 * breaks it.
86 static DEFINE_MUTEX(cgroup_mutex);
87 static DEFINE_MUTEX(cgroup_root_mutex);
90 * Generate an array of cgroup subsystem pointers. At boot time, this is
91 * populated with the built in subsystems, and modular subsystems are
92 * registered after that. The mutable section of this array is protected by
93 * cgroup_mutex.
95 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
96 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
97 static struct cgroup_subsys *subsys[CGROUP_SUBSYS_COUNT] = {
98 #include <linux/cgroup_subsys.h>
101 #define MAX_CGROUP_ROOT_NAMELEN 64
104 * A cgroupfs_root represents the root of a cgroup hierarchy,
105 * and may be associated with a superblock to form an active
106 * hierarchy
108 struct cgroupfs_root {
109 struct super_block *sb;
112 * The bitmask of subsystems intended to be attached to this
113 * hierarchy
115 unsigned long subsys_mask;
117 /* Unique id for this hierarchy. */
118 int hierarchy_id;
120 /* The bitmask of subsystems currently attached to this hierarchy */
121 unsigned long actual_subsys_mask;
123 /* A list running through the attached subsystems */
124 struct list_head subsys_list;
126 /* The root cgroup for this hierarchy */
127 struct cgroup top_cgroup;
129 /* Tracks how many cgroups are currently defined in hierarchy.*/
130 int number_of_cgroups;
132 /* A list running through the active hierarchies */
133 struct list_head root_list;
135 /* All cgroups on this root, cgroup_mutex protected */
136 struct list_head allcg_list;
138 /* Hierarchy-specific flags */
139 unsigned long flags;
141 /* The path to use for release notifications. */
142 char release_agent_path[PATH_MAX];
144 /* The name for this hierarchy - may be empty */
145 char name[MAX_CGROUP_ROOT_NAMELEN];
149 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
150 * subsystems that are otherwise unattached - it never has more than a
151 * single cgroup, and all tasks are part of that cgroup.
153 static struct cgroupfs_root rootnode;
156 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
158 struct cfent {
159 struct list_head node;
160 struct dentry *dentry;
161 struct cftype *type;
165 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
166 * cgroup_subsys->use_id != 0.
168 #define CSS_ID_MAX (65535)
169 struct css_id {
171 * The css to which this ID points. This pointer is set to valid value
172 * after cgroup is populated. If cgroup is removed, this will be NULL.
173 * This pointer is expected to be RCU-safe because destroy()
174 * is called after synchronize_rcu(). But for safe use, css_tryget()
175 * should be used for avoiding race.
177 struct cgroup_subsys_state __rcu *css;
179 * ID of this css.
181 unsigned short id;
183 * Depth in hierarchy which this ID belongs to.
185 unsigned short depth;
187 * ID is freed by RCU. (and lookup routine is RCU safe.)
189 struct rcu_head rcu_head;
191 * Hierarchy of CSS ID belongs to.
193 unsigned short stack[0]; /* Array of Length (depth+1) */
197 * cgroup_event represents events which userspace want to receive.
199 struct cgroup_event {
201 * Cgroup which the event belongs to.
203 struct cgroup *cgrp;
205 * Control file which the event associated.
207 struct cftype *cft;
209 * eventfd to signal userspace about the event.
211 struct eventfd_ctx *eventfd;
213 * Each of these stored in a list by the cgroup.
215 struct list_head list;
217 * All fields below needed to unregister event when
218 * userspace closes eventfd.
220 poll_table pt;
221 wait_queue_head_t *wqh;
222 wait_queue_t wait;
223 struct work_struct remove;
226 /* The list of hierarchy roots */
228 static LIST_HEAD(roots);
229 static int root_count;
231 static DEFINE_IDA(hierarchy_ida);
232 static int next_hierarchy_id;
233 static DEFINE_SPINLOCK(hierarchy_id_lock);
235 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
236 #define dummytop (&rootnode.top_cgroup)
238 /* This flag indicates whether tasks in the fork and exit paths should
239 * check for fork/exit handlers to call. This avoids us having to do
240 * extra work in the fork/exit path if none of the subsystems need to
241 * be called.
243 static int need_forkexit_callback __read_mostly;
245 #ifdef CONFIG_PROVE_LOCKING
246 int cgroup_lock_is_held(void)
248 return lockdep_is_held(&cgroup_mutex);
250 #else /* #ifdef CONFIG_PROVE_LOCKING */
251 int cgroup_lock_is_held(void)
253 return mutex_is_locked(&cgroup_mutex);
255 #endif /* #else #ifdef CONFIG_PROVE_LOCKING */
257 EXPORT_SYMBOL_GPL(cgroup_lock_is_held);
259 static int css_unbias_refcnt(int refcnt)
261 return refcnt >= 0 ? refcnt : refcnt - CSS_DEACT_BIAS;
264 /* the current nr of refs, always >= 0 whether @css is deactivated or not */
265 static int css_refcnt(struct cgroup_subsys_state *css)
267 int v = atomic_read(&css->refcnt);
269 return css_unbias_refcnt(v);
272 /* convenient tests for these bits */
273 inline int cgroup_is_removed(const struct cgroup *cgrp)
275 return test_bit(CGRP_REMOVED, &cgrp->flags);
278 /* bits in struct cgroupfs_root flags field */
279 enum {
280 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
281 ROOT_XATTR, /* supports extended attributes */
284 static int cgroup_is_releasable(const struct cgroup *cgrp)
286 const int bits =
287 (1 << CGRP_RELEASABLE) |
288 (1 << CGRP_NOTIFY_ON_RELEASE);
289 return (cgrp->flags & bits) == bits;
292 static int notify_on_release(const struct cgroup *cgrp)
294 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
297 static int clone_children(const struct cgroup *cgrp)
299 return test_bit(CGRP_CLONE_CHILDREN, &cgrp->flags);
303 * for_each_subsys() allows you to iterate on each subsystem attached to
304 * an active hierarchy
306 #define for_each_subsys(_root, _ss) \
307 list_for_each_entry(_ss, &_root->subsys_list, sibling)
309 /* for_each_active_root() allows you to iterate across the active hierarchies */
310 #define for_each_active_root(_root) \
311 list_for_each_entry(_root, &roots, root_list)
313 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
315 return dentry->d_fsdata;
318 static inline struct cfent *__d_cfe(struct dentry *dentry)
320 return dentry->d_fsdata;
323 static inline struct cftype *__d_cft(struct dentry *dentry)
325 return __d_cfe(dentry)->type;
328 /* the list of cgroups eligible for automatic release. Protected by
329 * release_list_lock */
330 static LIST_HEAD(release_list);
331 static DEFINE_RAW_SPINLOCK(release_list_lock);
332 static void cgroup_release_agent(struct work_struct *work);
333 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
334 static void check_for_release(struct cgroup *cgrp);
336 /* Link structure for associating css_set objects with cgroups */
337 struct cg_cgroup_link {
339 * List running through cg_cgroup_links associated with a
340 * cgroup, anchored on cgroup->css_sets
342 struct list_head cgrp_link_list;
343 struct cgroup *cgrp;
345 * List running through cg_cgroup_links pointing at a
346 * single css_set object, anchored on css_set->cg_links
348 struct list_head cg_link_list;
349 struct css_set *cg;
352 /* The default css_set - used by init and its children prior to any
353 * hierarchies being mounted. It contains a pointer to the root state
354 * for each subsystem. Also used to anchor the list of css_sets. Not
355 * reference-counted, to improve performance when child cgroups
356 * haven't been created.
359 static struct css_set init_css_set;
360 static struct cg_cgroup_link init_css_set_link;
362 static int cgroup_init_idr(struct cgroup_subsys *ss,
363 struct cgroup_subsys_state *css);
365 /* css_set_lock protects the list of css_set objects, and the
366 * chain of tasks off each css_set. Nests outside task->alloc_lock
367 * due to cgroup_iter_start() */
368 static DEFINE_RWLOCK(css_set_lock);
369 static int css_set_count;
372 * hash table for cgroup groups. This improves the performance to find
373 * an existing css_set. This hash doesn't (currently) take into
374 * account cgroups in empty hierarchies.
376 #define CSS_SET_HASH_BITS 7
377 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
378 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
380 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
382 int i;
383 int index;
384 unsigned long tmp = 0UL;
386 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
387 tmp += (unsigned long)css[i];
388 tmp = (tmp >> 16) ^ tmp;
390 index = hash_long(tmp, CSS_SET_HASH_BITS);
392 return &css_set_table[index];
395 /* We don't maintain the lists running through each css_set to its
396 * task until after the first call to cgroup_iter_start(). This
397 * reduces the fork()/exit() overhead for people who have cgroups
398 * compiled into their kernel but not actually in use */
399 static int use_task_css_set_links __read_mostly;
401 static void __put_css_set(struct css_set *cg, int taskexit)
403 struct cg_cgroup_link *link;
404 struct cg_cgroup_link *saved_link;
406 * Ensure that the refcount doesn't hit zero while any readers
407 * can see it. Similar to atomic_dec_and_lock(), but for an
408 * rwlock
410 if (atomic_add_unless(&cg->refcount, -1, 1))
411 return;
412 write_lock(&css_set_lock);
413 if (!atomic_dec_and_test(&cg->refcount)) {
414 write_unlock(&css_set_lock);
415 return;
418 /* This css_set is dead. unlink it and release cgroup refcounts */
419 hlist_del(&cg->hlist);
420 css_set_count--;
422 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
423 cg_link_list) {
424 struct cgroup *cgrp = link->cgrp;
425 list_del(&link->cg_link_list);
426 list_del(&link->cgrp_link_list);
427 if (atomic_dec_and_test(&cgrp->count) &&
428 notify_on_release(cgrp)) {
429 if (taskexit)
430 set_bit(CGRP_RELEASABLE, &cgrp->flags);
431 check_for_release(cgrp);
434 kfree(link);
437 write_unlock(&css_set_lock);
438 kfree_rcu(cg, rcu_head);
442 * refcounted get/put for css_set objects
444 static inline void get_css_set(struct css_set *cg)
446 atomic_inc(&cg->refcount);
449 static inline void put_css_set(struct css_set *cg)
451 __put_css_set(cg, 0);
454 static inline void put_css_set_taskexit(struct css_set *cg)
456 __put_css_set(cg, 1);
460 * compare_css_sets - helper function for find_existing_css_set().
461 * @cg: candidate css_set being tested
462 * @old_cg: existing css_set for a task
463 * @new_cgrp: cgroup that's being entered by the task
464 * @template: desired set of css pointers in css_set (pre-calculated)
466 * Returns true if "cg" matches "old_cg" except for the hierarchy
467 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
469 static bool compare_css_sets(struct css_set *cg,
470 struct css_set *old_cg,
471 struct cgroup *new_cgrp,
472 struct cgroup_subsys_state *template[])
474 struct list_head *l1, *l2;
476 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
477 /* Not all subsystems matched */
478 return false;
482 * Compare cgroup pointers in order to distinguish between
483 * different cgroups in heirarchies with no subsystems. We
484 * could get by with just this check alone (and skip the
485 * memcmp above) but on most setups the memcmp check will
486 * avoid the need for this more expensive check on almost all
487 * candidates.
490 l1 = &cg->cg_links;
491 l2 = &old_cg->cg_links;
492 while (1) {
493 struct cg_cgroup_link *cgl1, *cgl2;
494 struct cgroup *cg1, *cg2;
496 l1 = l1->next;
497 l2 = l2->next;
498 /* See if we reached the end - both lists are equal length. */
499 if (l1 == &cg->cg_links) {
500 BUG_ON(l2 != &old_cg->cg_links);
501 break;
502 } else {
503 BUG_ON(l2 == &old_cg->cg_links);
505 /* Locate the cgroups associated with these links. */
506 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
507 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
508 cg1 = cgl1->cgrp;
509 cg2 = cgl2->cgrp;
510 /* Hierarchies should be linked in the same order. */
511 BUG_ON(cg1->root != cg2->root);
514 * If this hierarchy is the hierarchy of the cgroup
515 * that's changing, then we need to check that this
516 * css_set points to the new cgroup; if it's any other
517 * hierarchy, then this css_set should point to the
518 * same cgroup as the old css_set.
520 if (cg1->root == new_cgrp->root) {
521 if (cg1 != new_cgrp)
522 return false;
523 } else {
524 if (cg1 != cg2)
525 return false;
528 return true;
532 * find_existing_css_set() is a helper for
533 * find_css_set(), and checks to see whether an existing
534 * css_set is suitable.
536 * oldcg: the cgroup group that we're using before the cgroup
537 * transition
539 * cgrp: the cgroup that we're moving into
541 * template: location in which to build the desired set of subsystem
542 * state objects for the new cgroup group
544 static struct css_set *find_existing_css_set(
545 struct css_set *oldcg,
546 struct cgroup *cgrp,
547 struct cgroup_subsys_state *template[])
549 int i;
550 struct cgroupfs_root *root = cgrp->root;
551 struct hlist_head *hhead;
552 struct hlist_node *node;
553 struct css_set *cg;
556 * Build the set of subsystem state objects that we want to see in the
557 * new css_set. while subsystems can change globally, the entries here
558 * won't change, so no need for locking.
560 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
561 if (root->subsys_mask & (1UL << i)) {
562 /* Subsystem is in this hierarchy. So we want
563 * the subsystem state from the new
564 * cgroup */
565 template[i] = cgrp->subsys[i];
566 } else {
567 /* Subsystem is not in this hierarchy, so we
568 * don't want to change the subsystem state */
569 template[i] = oldcg->subsys[i];
573 hhead = css_set_hash(template);
574 hlist_for_each_entry(cg, node, hhead, hlist) {
575 if (!compare_css_sets(cg, oldcg, cgrp, template))
576 continue;
578 /* This css_set matches what we need */
579 return cg;
582 /* No existing cgroup group matched */
583 return NULL;
586 static void free_cg_links(struct list_head *tmp)
588 struct cg_cgroup_link *link;
589 struct cg_cgroup_link *saved_link;
591 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
592 list_del(&link->cgrp_link_list);
593 kfree(link);
598 * allocate_cg_links() allocates "count" cg_cgroup_link structures
599 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
600 * success or a negative error
602 static int allocate_cg_links(int count, struct list_head *tmp)
604 struct cg_cgroup_link *link;
605 int i;
606 INIT_LIST_HEAD(tmp);
607 for (i = 0; i < count; i++) {
608 link = kmalloc(sizeof(*link), GFP_KERNEL);
609 if (!link) {
610 free_cg_links(tmp);
611 return -ENOMEM;
613 list_add(&link->cgrp_link_list, tmp);
615 return 0;
619 * link_css_set - a helper function to link a css_set to a cgroup
620 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
621 * @cg: the css_set to be linked
622 * @cgrp: the destination cgroup
624 static void link_css_set(struct list_head *tmp_cg_links,
625 struct css_set *cg, struct cgroup *cgrp)
627 struct cg_cgroup_link *link;
629 BUG_ON(list_empty(tmp_cg_links));
630 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
631 cgrp_link_list);
632 link->cg = cg;
633 link->cgrp = cgrp;
634 atomic_inc(&cgrp->count);
635 list_move(&link->cgrp_link_list, &cgrp->css_sets);
637 * Always add links to the tail of the list so that the list
638 * is sorted by order of hierarchy creation
640 list_add_tail(&link->cg_link_list, &cg->cg_links);
644 * find_css_set() takes an existing cgroup group and a
645 * cgroup object, and returns a css_set object that's
646 * equivalent to the old group, but with the given cgroup
647 * substituted into the appropriate hierarchy. Must be called with
648 * cgroup_mutex held
650 static struct css_set *find_css_set(
651 struct css_set *oldcg, struct cgroup *cgrp)
653 struct css_set *res;
654 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
656 struct list_head tmp_cg_links;
658 struct hlist_head *hhead;
659 struct cg_cgroup_link *link;
661 /* First see if we already have a cgroup group that matches
662 * the desired set */
663 read_lock(&css_set_lock);
664 res = find_existing_css_set(oldcg, cgrp, template);
665 if (res)
666 get_css_set(res);
667 read_unlock(&css_set_lock);
669 if (res)
670 return res;
672 res = kmalloc(sizeof(*res), GFP_KERNEL);
673 if (!res)
674 return NULL;
676 /* Allocate all the cg_cgroup_link objects that we'll need */
677 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
678 kfree(res);
679 return NULL;
682 atomic_set(&res->refcount, 1);
683 INIT_LIST_HEAD(&res->cg_links);
684 INIT_LIST_HEAD(&res->tasks);
685 INIT_HLIST_NODE(&res->hlist);
687 /* Copy the set of subsystem state objects generated in
688 * find_existing_css_set() */
689 memcpy(res->subsys, template, sizeof(res->subsys));
691 write_lock(&css_set_lock);
692 /* Add reference counts and links from the new css_set. */
693 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
694 struct cgroup *c = link->cgrp;
695 if (c->root == cgrp->root)
696 c = cgrp;
697 link_css_set(&tmp_cg_links, res, c);
700 BUG_ON(!list_empty(&tmp_cg_links));
702 css_set_count++;
704 /* Add this cgroup group to the hash table */
705 hhead = css_set_hash(res->subsys);
706 hlist_add_head(&res->hlist, hhead);
708 write_unlock(&css_set_lock);
710 return res;
714 * Return the cgroup for "task" from the given hierarchy. Must be
715 * called with cgroup_mutex held.
717 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
718 struct cgroupfs_root *root)
720 struct css_set *css;
721 struct cgroup *res = NULL;
723 BUG_ON(!mutex_is_locked(&cgroup_mutex));
724 read_lock(&css_set_lock);
726 * No need to lock the task - since we hold cgroup_mutex the
727 * task can't change groups, so the only thing that can happen
728 * is that it exits and its css is set back to init_css_set.
730 css = task->cgroups;
731 if (css == &init_css_set) {
732 res = &root->top_cgroup;
733 } else {
734 struct cg_cgroup_link *link;
735 list_for_each_entry(link, &css->cg_links, cg_link_list) {
736 struct cgroup *c = link->cgrp;
737 if (c->root == root) {
738 res = c;
739 break;
743 read_unlock(&css_set_lock);
744 BUG_ON(!res);
745 return res;
749 * There is one global cgroup mutex. We also require taking
750 * task_lock() when dereferencing a task's cgroup subsys pointers.
751 * See "The task_lock() exception", at the end of this comment.
753 * A task must hold cgroup_mutex to modify cgroups.
755 * Any task can increment and decrement the count field without lock.
756 * So in general, code holding cgroup_mutex can't rely on the count
757 * field not changing. However, if the count goes to zero, then only
758 * cgroup_attach_task() can increment it again. Because a count of zero
759 * means that no tasks are currently attached, therefore there is no
760 * way a task attached to that cgroup can fork (the other way to
761 * increment the count). So code holding cgroup_mutex can safely
762 * assume that if the count is zero, it will stay zero. Similarly, if
763 * a task holds cgroup_mutex on a cgroup with zero count, it
764 * knows that the cgroup won't be removed, as cgroup_rmdir()
765 * needs that mutex.
767 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
768 * (usually) take cgroup_mutex. These are the two most performance
769 * critical pieces of code here. The exception occurs on cgroup_exit(),
770 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
771 * is taken, and if the cgroup count is zero, a usermode call made
772 * to the release agent with the name of the cgroup (path relative to
773 * the root of cgroup file system) as the argument.
775 * A cgroup can only be deleted if both its 'count' of using tasks
776 * is zero, and its list of 'children' cgroups is empty. Since all
777 * tasks in the system use _some_ cgroup, and since there is always at
778 * least one task in the system (init, pid == 1), therefore, top_cgroup
779 * always has either children cgroups and/or using tasks. So we don't
780 * need a special hack to ensure that top_cgroup cannot be deleted.
782 * The task_lock() exception
784 * The need for this exception arises from the action of
785 * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
786 * another. It does so using cgroup_mutex, however there are
787 * several performance critical places that need to reference
788 * task->cgroup without the expense of grabbing a system global
789 * mutex. Therefore except as noted below, when dereferencing or, as
790 * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
791 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
792 * the task_struct routinely used for such matters.
794 * P.S. One more locking exception. RCU is used to guard the
795 * update of a tasks cgroup pointer by cgroup_attach_task()
799 * cgroup_lock - lock out any changes to cgroup structures
802 void cgroup_lock(void)
804 mutex_lock(&cgroup_mutex);
806 EXPORT_SYMBOL_GPL(cgroup_lock);
809 * cgroup_unlock - release lock on cgroup changes
811 * Undo the lock taken in a previous cgroup_lock() call.
813 void cgroup_unlock(void)
815 mutex_unlock(&cgroup_mutex);
817 EXPORT_SYMBOL_GPL(cgroup_unlock);
820 * A couple of forward declarations required, due to cyclic reference loop:
821 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
822 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
823 * -> cgroup_mkdir.
826 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
827 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
828 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
829 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
830 unsigned long subsys_mask);
831 static const struct inode_operations cgroup_dir_inode_operations;
832 static const struct file_operations proc_cgroupstats_operations;
834 static struct backing_dev_info cgroup_backing_dev_info = {
835 .name = "cgroup",
836 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
839 static int alloc_css_id(struct cgroup_subsys *ss,
840 struct cgroup *parent, struct cgroup *child);
842 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
844 struct inode *inode = new_inode(sb);
846 if (inode) {
847 inode->i_ino = get_next_ino();
848 inode->i_mode = mode;
849 inode->i_uid = current_fsuid();
850 inode->i_gid = current_fsgid();
851 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
852 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
854 return inode;
857 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
859 /* is dentry a directory ? if so, kfree() associated cgroup */
860 if (S_ISDIR(inode->i_mode)) {
861 struct cgroup *cgrp = dentry->d_fsdata;
862 struct cgroup_subsys *ss;
863 BUG_ON(!(cgroup_is_removed(cgrp)));
864 /* It's possible for external users to be holding css
865 * reference counts on a cgroup; css_put() needs to
866 * be able to access the cgroup after decrementing
867 * the reference count in order to know if it needs to
868 * queue the cgroup to be handled by the release
869 * agent */
870 synchronize_rcu();
872 mutex_lock(&cgroup_mutex);
874 * Release the subsystem state objects.
876 for_each_subsys(cgrp->root, ss)
877 ss->destroy(cgrp);
879 cgrp->root->number_of_cgroups--;
880 mutex_unlock(&cgroup_mutex);
883 * Drop the active superblock reference that we took when we
884 * created the cgroup
886 deactivate_super(cgrp->root->sb);
889 * if we're getting rid of the cgroup, refcount should ensure
890 * that there are no pidlists left.
892 BUG_ON(!list_empty(&cgrp->pidlists));
894 simple_xattrs_free(&cgrp->xattrs);
896 kfree_rcu(cgrp, rcu_head);
897 } else {
898 struct cfent *cfe = __d_cfe(dentry);
899 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
900 struct cftype *cft = cfe->type;
902 WARN_ONCE(!list_empty(&cfe->node) &&
903 cgrp != &cgrp->root->top_cgroup,
904 "cfe still linked for %s\n", cfe->type->name);
905 kfree(cfe);
906 simple_xattrs_free(&cft->xattrs);
908 iput(inode);
911 static int cgroup_delete(const struct dentry *d)
913 return 1;
916 static void remove_dir(struct dentry *d)
918 struct dentry *parent = dget(d->d_parent);
920 d_delete(d);
921 simple_rmdir(parent->d_inode, d);
922 dput(parent);
925 static int cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
927 struct cfent *cfe;
929 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
930 lockdep_assert_held(&cgroup_mutex);
932 list_for_each_entry(cfe, &cgrp->files, node) {
933 struct dentry *d = cfe->dentry;
935 if (cft && cfe->type != cft)
936 continue;
938 dget(d);
939 d_delete(d);
940 simple_unlink(cgrp->dentry->d_inode, d);
941 list_del_init(&cfe->node);
942 dput(d);
944 return 0;
946 return -ENOENT;
950 * cgroup_clear_directory - selective removal of base and subsystem files
951 * @dir: directory containing the files
952 * @base_files: true if the base files should be removed
953 * @subsys_mask: mask of the subsystem ids whose files should be removed
955 static void cgroup_clear_directory(struct dentry *dir, bool base_files,
956 unsigned long subsys_mask)
958 struct cgroup *cgrp = __d_cgrp(dir);
959 struct cgroup_subsys *ss;
961 for_each_subsys(cgrp->root, ss) {
962 struct cftype_set *set;
963 if (!test_bit(ss->subsys_id, &subsys_mask))
964 continue;
965 list_for_each_entry(set, &ss->cftsets, node)
966 cgroup_rm_file(cgrp, set->cfts);
968 if (base_files) {
969 while (!list_empty(&cgrp->files))
970 cgroup_rm_file(cgrp, NULL);
975 * NOTE : the dentry must have been dget()'ed
977 static void cgroup_d_remove_dir(struct dentry *dentry)
979 struct dentry *parent;
980 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
982 cgroup_clear_directory(dentry, true, root->subsys_mask);
984 parent = dentry->d_parent;
985 spin_lock(&parent->d_lock);
986 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
987 list_del_init(&dentry->d_u.d_child);
988 spin_unlock(&dentry->d_lock);
989 spin_unlock(&parent->d_lock);
990 remove_dir(dentry);
994 * Call with cgroup_mutex held. Drops reference counts on modules, including
995 * any duplicate ones that parse_cgroupfs_options took. If this function
996 * returns an error, no reference counts are touched.
998 static int rebind_subsystems(struct cgroupfs_root *root,
999 unsigned long final_subsys_mask)
1001 unsigned long added_mask, removed_mask;
1002 struct cgroup *cgrp = &root->top_cgroup;
1003 int i;
1005 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1006 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1008 removed_mask = root->actual_subsys_mask & ~final_subsys_mask;
1009 added_mask = final_subsys_mask & ~root->actual_subsys_mask;
1010 /* Check that any added subsystems are currently free */
1011 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1012 unsigned long bit = 1UL << i;
1013 struct cgroup_subsys *ss = subsys[i];
1014 if (!(bit & added_mask))
1015 continue;
1017 * Nobody should tell us to do a subsys that doesn't exist:
1018 * parse_cgroupfs_options should catch that case and refcounts
1019 * ensure that subsystems won't disappear once selected.
1021 BUG_ON(ss == NULL);
1022 if (ss->root != &rootnode) {
1023 /* Subsystem isn't free */
1024 return -EBUSY;
1028 /* Currently we don't handle adding/removing subsystems when
1029 * any child cgroups exist. This is theoretically supportable
1030 * but involves complex error handling, so it's being left until
1031 * later */
1032 if (root->number_of_cgroups > 1)
1033 return -EBUSY;
1035 /* Process each subsystem */
1036 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1037 struct cgroup_subsys *ss = subsys[i];
1038 unsigned long bit = 1UL << i;
1039 if (bit & added_mask) {
1040 /* We're binding this subsystem to this hierarchy */
1041 BUG_ON(ss == NULL);
1042 BUG_ON(cgrp->subsys[i]);
1043 BUG_ON(!dummytop->subsys[i]);
1044 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
1045 cgrp->subsys[i] = dummytop->subsys[i];
1046 cgrp->subsys[i]->cgroup = cgrp;
1047 list_move(&ss->sibling, &root->subsys_list);
1048 ss->root = root;
1049 if (ss->bind)
1050 ss->bind(cgrp);
1051 /* refcount was already taken, and we're keeping it */
1052 } else if (bit & removed_mask) {
1053 /* We're removing this subsystem */
1054 BUG_ON(ss == NULL);
1055 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1056 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1057 if (ss->bind)
1058 ss->bind(dummytop);
1059 dummytop->subsys[i]->cgroup = dummytop;
1060 cgrp->subsys[i] = NULL;
1061 subsys[i]->root = &rootnode;
1062 list_move(&ss->sibling, &rootnode.subsys_list);
1063 /* subsystem is now free - drop reference on module */
1064 module_put(ss->module);
1065 } else if (bit & final_subsys_mask) {
1066 /* Subsystem state should already exist */
1067 BUG_ON(ss == NULL);
1068 BUG_ON(!cgrp->subsys[i]);
1070 * a refcount was taken, but we already had one, so
1071 * drop the extra reference.
1073 module_put(ss->module);
1074 #ifdef CONFIG_MODULE_UNLOAD
1075 BUG_ON(ss->module && !module_refcount(ss->module));
1076 #endif
1077 } else {
1078 /* Subsystem state shouldn't exist */
1079 BUG_ON(cgrp->subsys[i]);
1082 root->subsys_mask = root->actual_subsys_mask = final_subsys_mask;
1083 synchronize_rcu();
1085 return 0;
1088 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1090 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1091 struct cgroup_subsys *ss;
1093 mutex_lock(&cgroup_root_mutex);
1094 for_each_subsys(root, ss)
1095 seq_printf(seq, ",%s", ss->name);
1096 if (test_bit(ROOT_NOPREFIX, &root->flags))
1097 seq_puts(seq, ",noprefix");
1098 if (test_bit(ROOT_XATTR, &root->flags))
1099 seq_puts(seq, ",xattr");
1100 if (strlen(root->release_agent_path))
1101 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1102 if (clone_children(&root->top_cgroup))
1103 seq_puts(seq, ",clone_children");
1104 if (strlen(root->name))
1105 seq_printf(seq, ",name=%s", root->name);
1106 mutex_unlock(&cgroup_root_mutex);
1107 return 0;
1110 struct cgroup_sb_opts {
1111 unsigned long subsys_mask;
1112 unsigned long flags;
1113 char *release_agent;
1114 bool clone_children;
1115 char *name;
1116 /* User explicitly requested empty subsystem */
1117 bool none;
1119 struct cgroupfs_root *new_root;
1124 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1125 * with cgroup_mutex held to protect the subsys[] array. This function takes
1126 * refcounts on subsystems to be used, unless it returns error, in which case
1127 * no refcounts are taken.
1129 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1131 char *token, *o = data;
1132 bool all_ss = false, one_ss = false;
1133 unsigned long mask = (unsigned long)-1;
1134 int i;
1135 bool module_pin_failed = false;
1137 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1139 #ifdef CONFIG_CPUSETS
1140 mask = ~(1UL << cpuset_subsys_id);
1141 #endif
1143 memset(opts, 0, sizeof(*opts));
1145 while ((token = strsep(&o, ",")) != NULL) {
1146 if (!*token)
1147 return -EINVAL;
1148 if (!strcmp(token, "none")) {
1149 /* Explicitly have no subsystems */
1150 opts->none = true;
1151 continue;
1153 if (!strcmp(token, "all")) {
1154 /* Mutually exclusive option 'all' + subsystem name */
1155 if (one_ss)
1156 return -EINVAL;
1157 all_ss = true;
1158 continue;
1160 if (!strcmp(token, "noprefix")) {
1161 set_bit(ROOT_NOPREFIX, &opts->flags);
1162 continue;
1164 if (!strcmp(token, "clone_children")) {
1165 opts->clone_children = true;
1166 continue;
1168 if (!strcmp(token, "xattr")) {
1169 set_bit(ROOT_XATTR, &opts->flags);
1170 continue;
1172 if (!strncmp(token, "release_agent=", 14)) {
1173 /* Specifying two release agents is forbidden */
1174 if (opts->release_agent)
1175 return -EINVAL;
1176 opts->release_agent =
1177 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1178 if (!opts->release_agent)
1179 return -ENOMEM;
1180 continue;
1182 if (!strncmp(token, "name=", 5)) {
1183 const char *name = token + 5;
1184 /* Can't specify an empty name */
1185 if (!strlen(name))
1186 return -EINVAL;
1187 /* Must match [\w.-]+ */
1188 for (i = 0; i < strlen(name); i++) {
1189 char c = name[i];
1190 if (isalnum(c))
1191 continue;
1192 if ((c == '.') || (c == '-') || (c == '_'))
1193 continue;
1194 return -EINVAL;
1196 /* Specifying two names is forbidden */
1197 if (opts->name)
1198 return -EINVAL;
1199 opts->name = kstrndup(name,
1200 MAX_CGROUP_ROOT_NAMELEN - 1,
1201 GFP_KERNEL);
1202 if (!opts->name)
1203 return -ENOMEM;
1205 continue;
1208 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1209 struct cgroup_subsys *ss = subsys[i];
1210 if (ss == NULL)
1211 continue;
1212 if (strcmp(token, ss->name))
1213 continue;
1214 if (ss->disabled)
1215 continue;
1217 /* Mutually exclusive option 'all' + subsystem name */
1218 if (all_ss)
1219 return -EINVAL;
1220 set_bit(i, &opts->subsys_mask);
1221 one_ss = true;
1223 break;
1225 if (i == CGROUP_SUBSYS_COUNT)
1226 return -ENOENT;
1230 * If the 'all' option was specified select all the subsystems,
1231 * otherwise if 'none', 'name=' and a subsystem name options
1232 * were not specified, let's default to 'all'
1234 if (all_ss || (!one_ss && !opts->none && !opts->name)) {
1235 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1236 struct cgroup_subsys *ss = subsys[i];
1237 if (ss == NULL)
1238 continue;
1239 if (ss->disabled)
1240 continue;
1241 set_bit(i, &opts->subsys_mask);
1245 /* Consistency checks */
1248 * Option noprefix was introduced just for backward compatibility
1249 * with the old cpuset, so we allow noprefix only if mounting just
1250 * the cpuset subsystem.
1252 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1253 (opts->subsys_mask & mask))
1254 return -EINVAL;
1257 /* Can't specify "none" and some subsystems */
1258 if (opts->subsys_mask && opts->none)
1259 return -EINVAL;
1262 * We either have to specify by name or by subsystems. (So all
1263 * empty hierarchies must have a name).
1265 if (!opts->subsys_mask && !opts->name)
1266 return -EINVAL;
1269 * Grab references on all the modules we'll need, so the subsystems
1270 * don't dance around before rebind_subsystems attaches them. This may
1271 * take duplicate reference counts on a subsystem that's already used,
1272 * but rebind_subsystems handles this case.
1274 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1275 unsigned long bit = 1UL << i;
1277 if (!(bit & opts->subsys_mask))
1278 continue;
1279 if (!try_module_get(subsys[i]->module)) {
1280 module_pin_failed = true;
1281 break;
1284 if (module_pin_failed) {
1286 * oops, one of the modules was going away. this means that we
1287 * raced with a module_delete call, and to the user this is
1288 * essentially a "subsystem doesn't exist" case.
1290 for (i--; i >= 0; i--) {
1291 /* drop refcounts only on the ones we took */
1292 unsigned long bit = 1UL << i;
1294 if (!(bit & opts->subsys_mask))
1295 continue;
1296 module_put(subsys[i]->module);
1298 return -ENOENT;
1301 return 0;
1304 static void drop_parsed_module_refcounts(unsigned long subsys_mask)
1306 int i;
1307 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1308 unsigned long bit = 1UL << i;
1310 if (!(bit & subsys_mask))
1311 continue;
1312 module_put(subsys[i]->module);
1316 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1318 int ret = 0;
1319 struct cgroupfs_root *root = sb->s_fs_info;
1320 struct cgroup *cgrp = &root->top_cgroup;
1321 struct cgroup_sb_opts opts;
1322 unsigned long added_mask, removed_mask;
1324 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1325 mutex_lock(&cgroup_mutex);
1326 mutex_lock(&cgroup_root_mutex);
1328 /* See what subsystems are wanted */
1329 ret = parse_cgroupfs_options(data, &opts);
1330 if (ret)
1331 goto out_unlock;
1333 /* See feature-removal-schedule.txt */
1334 if (opts.subsys_mask != root->actual_subsys_mask || opts.release_agent)
1335 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1336 task_tgid_nr(current), current->comm);
1338 added_mask = opts.subsys_mask & ~root->subsys_mask;
1339 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1341 /* Don't allow flags or name to change at remount */
1342 if (opts.flags != root->flags ||
1343 (opts.name && strcmp(opts.name, root->name))) {
1344 ret = -EINVAL;
1345 drop_parsed_module_refcounts(opts.subsys_mask);
1346 goto out_unlock;
1349 ret = rebind_subsystems(root, opts.subsys_mask);
1350 if (ret) {
1351 drop_parsed_module_refcounts(opts.subsys_mask);
1352 goto out_unlock;
1355 /* clear out any existing files and repopulate subsystem files */
1356 cgroup_clear_directory(cgrp->dentry, false, removed_mask);
1357 /* re-populate subsystem files */
1358 cgroup_populate_dir(cgrp, false, added_mask);
1360 if (opts.release_agent)
1361 strcpy(root->release_agent_path, opts.release_agent);
1362 out_unlock:
1363 kfree(opts.release_agent);
1364 kfree(opts.name);
1365 mutex_unlock(&cgroup_root_mutex);
1366 mutex_unlock(&cgroup_mutex);
1367 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1368 return ret;
1371 static const struct super_operations cgroup_ops = {
1372 .statfs = simple_statfs,
1373 .drop_inode = generic_delete_inode,
1374 .show_options = cgroup_show_options,
1375 .remount_fs = cgroup_remount,
1378 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1380 INIT_LIST_HEAD(&cgrp->sibling);
1381 INIT_LIST_HEAD(&cgrp->children);
1382 INIT_LIST_HEAD(&cgrp->files);
1383 INIT_LIST_HEAD(&cgrp->css_sets);
1384 INIT_LIST_HEAD(&cgrp->release_list);
1385 INIT_LIST_HEAD(&cgrp->pidlists);
1386 mutex_init(&cgrp->pidlist_mutex);
1387 INIT_LIST_HEAD(&cgrp->event_list);
1388 spin_lock_init(&cgrp->event_list_lock);
1389 simple_xattrs_init(&cgrp->xattrs);
1392 static void init_cgroup_root(struct cgroupfs_root *root)
1394 struct cgroup *cgrp = &root->top_cgroup;
1396 INIT_LIST_HEAD(&root->subsys_list);
1397 INIT_LIST_HEAD(&root->root_list);
1398 INIT_LIST_HEAD(&root->allcg_list);
1399 root->number_of_cgroups = 1;
1400 cgrp->root = root;
1401 cgrp->top_cgroup = cgrp;
1402 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
1403 init_cgroup_housekeeping(cgrp);
1406 static bool init_root_id(struct cgroupfs_root *root)
1408 int ret = 0;
1410 do {
1411 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1412 return false;
1413 spin_lock(&hierarchy_id_lock);
1414 /* Try to allocate the next unused ID */
1415 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1416 &root->hierarchy_id);
1417 if (ret == -ENOSPC)
1418 /* Try again starting from 0 */
1419 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1420 if (!ret) {
1421 next_hierarchy_id = root->hierarchy_id + 1;
1422 } else if (ret != -EAGAIN) {
1423 /* Can only get here if the 31-bit IDR is full ... */
1424 BUG_ON(ret);
1426 spin_unlock(&hierarchy_id_lock);
1427 } while (ret);
1428 return true;
1431 static int cgroup_test_super(struct super_block *sb, void *data)
1433 struct cgroup_sb_opts *opts = data;
1434 struct cgroupfs_root *root = sb->s_fs_info;
1436 /* If we asked for a name then it must match */
1437 if (opts->name && strcmp(opts->name, root->name))
1438 return 0;
1441 * If we asked for subsystems (or explicitly for no
1442 * subsystems) then they must match
1444 if ((opts->subsys_mask || opts->none)
1445 && (opts->subsys_mask != root->subsys_mask))
1446 return 0;
1448 return 1;
1451 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1453 struct cgroupfs_root *root;
1455 if (!opts->subsys_mask && !opts->none)
1456 return NULL;
1458 root = kzalloc(sizeof(*root), GFP_KERNEL);
1459 if (!root)
1460 return ERR_PTR(-ENOMEM);
1462 if (!init_root_id(root)) {
1463 kfree(root);
1464 return ERR_PTR(-ENOMEM);
1466 init_cgroup_root(root);
1468 root->subsys_mask = opts->subsys_mask;
1469 root->flags = opts->flags;
1470 if (opts->release_agent)
1471 strcpy(root->release_agent_path, opts->release_agent);
1472 if (opts->name)
1473 strcpy(root->name, opts->name);
1474 if (opts->clone_children)
1475 set_bit(CGRP_CLONE_CHILDREN, &root->top_cgroup.flags);
1476 return root;
1479 static void cgroup_drop_root(struct cgroupfs_root *root)
1481 if (!root)
1482 return;
1484 BUG_ON(!root->hierarchy_id);
1485 spin_lock(&hierarchy_id_lock);
1486 ida_remove(&hierarchy_ida, root->hierarchy_id);
1487 spin_unlock(&hierarchy_id_lock);
1488 kfree(root);
1491 static int cgroup_set_super(struct super_block *sb, void *data)
1493 int ret;
1494 struct cgroup_sb_opts *opts = data;
1496 /* If we don't have a new root, we can't set up a new sb */
1497 if (!opts->new_root)
1498 return -EINVAL;
1500 BUG_ON(!opts->subsys_mask && !opts->none);
1502 ret = set_anon_super(sb, NULL);
1503 if (ret)
1504 return ret;
1506 sb->s_fs_info = opts->new_root;
1507 opts->new_root->sb = sb;
1509 sb->s_blocksize = PAGE_CACHE_SIZE;
1510 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1511 sb->s_magic = CGROUP_SUPER_MAGIC;
1512 sb->s_op = &cgroup_ops;
1514 return 0;
1517 static int cgroup_get_rootdir(struct super_block *sb)
1519 static const struct dentry_operations cgroup_dops = {
1520 .d_iput = cgroup_diput,
1521 .d_delete = cgroup_delete,
1524 struct inode *inode =
1525 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1527 if (!inode)
1528 return -ENOMEM;
1530 inode->i_fop = &simple_dir_operations;
1531 inode->i_op = &cgroup_dir_inode_operations;
1532 /* directories start off with i_nlink == 2 (for "." entry) */
1533 inc_nlink(inode);
1534 sb->s_root = d_make_root(inode);
1535 if (!sb->s_root)
1536 return -ENOMEM;
1537 /* for everything else we want ->d_op set */
1538 sb->s_d_op = &cgroup_dops;
1539 return 0;
1542 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1543 int flags, const char *unused_dev_name,
1544 void *data)
1546 struct cgroup_sb_opts opts;
1547 struct cgroupfs_root *root;
1548 int ret = 0;
1549 struct super_block *sb;
1550 struct cgroupfs_root *new_root;
1551 struct inode *inode;
1553 /* First find the desired set of subsystems */
1554 mutex_lock(&cgroup_mutex);
1555 ret = parse_cgroupfs_options(data, &opts);
1556 mutex_unlock(&cgroup_mutex);
1557 if (ret)
1558 goto out_err;
1561 * Allocate a new cgroup root. We may not need it if we're
1562 * reusing an existing hierarchy.
1564 new_root = cgroup_root_from_opts(&opts);
1565 if (IS_ERR(new_root)) {
1566 ret = PTR_ERR(new_root);
1567 goto drop_modules;
1569 opts.new_root = new_root;
1571 /* Locate an existing or new sb for this hierarchy */
1572 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1573 if (IS_ERR(sb)) {
1574 ret = PTR_ERR(sb);
1575 cgroup_drop_root(opts.new_root);
1576 goto drop_modules;
1579 root = sb->s_fs_info;
1580 BUG_ON(!root);
1581 if (root == opts.new_root) {
1582 /* We used the new root structure, so this is a new hierarchy */
1583 struct list_head tmp_cg_links;
1584 struct cgroup *root_cgrp = &root->top_cgroup;
1585 struct cgroupfs_root *existing_root;
1586 const struct cred *cred;
1587 int i;
1589 BUG_ON(sb->s_root != NULL);
1591 ret = cgroup_get_rootdir(sb);
1592 if (ret)
1593 goto drop_new_super;
1594 inode = sb->s_root->d_inode;
1596 mutex_lock(&inode->i_mutex);
1597 mutex_lock(&cgroup_mutex);
1598 mutex_lock(&cgroup_root_mutex);
1600 /* Check for name clashes with existing mounts */
1601 ret = -EBUSY;
1602 if (strlen(root->name))
1603 for_each_active_root(existing_root)
1604 if (!strcmp(existing_root->name, root->name))
1605 goto unlock_drop;
1608 * We're accessing css_set_count without locking
1609 * css_set_lock here, but that's OK - it can only be
1610 * increased by someone holding cgroup_lock, and
1611 * that's us. The worst that can happen is that we
1612 * have some link structures left over
1614 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1615 if (ret)
1616 goto unlock_drop;
1618 ret = rebind_subsystems(root, root->subsys_mask);
1619 if (ret == -EBUSY) {
1620 free_cg_links(&tmp_cg_links);
1621 goto unlock_drop;
1624 * There must be no failure case after here, since rebinding
1625 * takes care of subsystems' refcounts, which are explicitly
1626 * dropped in the failure exit path.
1629 /* EBUSY should be the only error here */
1630 BUG_ON(ret);
1632 list_add(&root->root_list, &roots);
1633 root_count++;
1635 sb->s_root->d_fsdata = root_cgrp;
1636 root->top_cgroup.dentry = sb->s_root;
1638 /* Link the top cgroup in this hierarchy into all
1639 * the css_set objects */
1640 write_lock(&css_set_lock);
1641 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1642 struct hlist_head *hhead = &css_set_table[i];
1643 struct hlist_node *node;
1644 struct css_set *cg;
1646 hlist_for_each_entry(cg, node, hhead, hlist)
1647 link_css_set(&tmp_cg_links, cg, root_cgrp);
1649 write_unlock(&css_set_lock);
1651 free_cg_links(&tmp_cg_links);
1653 BUG_ON(!list_empty(&root_cgrp->sibling));
1654 BUG_ON(!list_empty(&root_cgrp->children));
1655 BUG_ON(root->number_of_cgroups != 1);
1657 cred = override_creds(&init_cred);
1658 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1659 revert_creds(cred);
1660 mutex_unlock(&cgroup_root_mutex);
1661 mutex_unlock(&cgroup_mutex);
1662 mutex_unlock(&inode->i_mutex);
1663 } else {
1665 * We re-used an existing hierarchy - the new root (if
1666 * any) is not needed
1668 cgroup_drop_root(opts.new_root);
1669 /* no subsys rebinding, so refcounts don't change */
1670 drop_parsed_module_refcounts(opts.subsys_mask);
1673 kfree(opts.release_agent);
1674 kfree(opts.name);
1675 return dget(sb->s_root);
1677 unlock_drop:
1678 mutex_unlock(&cgroup_root_mutex);
1679 mutex_unlock(&cgroup_mutex);
1680 mutex_unlock(&inode->i_mutex);
1681 drop_new_super:
1682 deactivate_locked_super(sb);
1683 drop_modules:
1684 drop_parsed_module_refcounts(opts.subsys_mask);
1685 out_err:
1686 kfree(opts.release_agent);
1687 kfree(opts.name);
1688 return ERR_PTR(ret);
1691 static void cgroup_kill_sb(struct super_block *sb) {
1692 struct cgroupfs_root *root = sb->s_fs_info;
1693 struct cgroup *cgrp = &root->top_cgroup;
1694 int ret;
1695 struct cg_cgroup_link *link;
1696 struct cg_cgroup_link *saved_link;
1698 BUG_ON(!root);
1700 BUG_ON(root->number_of_cgroups != 1);
1701 BUG_ON(!list_empty(&cgrp->children));
1702 BUG_ON(!list_empty(&cgrp->sibling));
1704 mutex_lock(&cgroup_mutex);
1705 mutex_lock(&cgroup_root_mutex);
1707 /* Rebind all subsystems back to the default hierarchy */
1708 ret = rebind_subsystems(root, 0);
1709 /* Shouldn't be able to fail ... */
1710 BUG_ON(ret);
1713 * Release all the links from css_sets to this hierarchy's
1714 * root cgroup
1716 write_lock(&css_set_lock);
1718 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1719 cgrp_link_list) {
1720 list_del(&link->cg_link_list);
1721 list_del(&link->cgrp_link_list);
1722 kfree(link);
1724 write_unlock(&css_set_lock);
1726 if (!list_empty(&root->root_list)) {
1727 list_del(&root->root_list);
1728 root_count--;
1731 mutex_unlock(&cgroup_root_mutex);
1732 mutex_unlock(&cgroup_mutex);
1734 simple_xattrs_free(&cgrp->xattrs);
1736 kill_litter_super(sb);
1737 cgroup_drop_root(root);
1740 static struct file_system_type cgroup_fs_type = {
1741 .name = "cgroup",
1742 .mount = cgroup_mount,
1743 .kill_sb = cgroup_kill_sb,
1746 static struct kobject *cgroup_kobj;
1749 * cgroup_path - generate the path of a cgroup
1750 * @cgrp: the cgroup in question
1751 * @buf: the buffer to write the path into
1752 * @buflen: the length of the buffer
1754 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1755 * reference. Writes path of cgroup into buf. Returns 0 on success,
1756 * -errno on error.
1758 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1760 char *start;
1761 struct dentry *dentry = rcu_dereference_check(cgrp->dentry,
1762 cgroup_lock_is_held());
1764 if (!dentry || cgrp == dummytop) {
1766 * Inactive subsystems have no dentry for their root
1767 * cgroup
1769 strcpy(buf, "/");
1770 return 0;
1773 start = buf + buflen;
1775 *--start = '\0';
1776 for (;;) {
1777 int len = dentry->d_name.len;
1779 if ((start -= len) < buf)
1780 return -ENAMETOOLONG;
1781 memcpy(start, dentry->d_name.name, len);
1782 cgrp = cgrp->parent;
1783 if (!cgrp)
1784 break;
1786 dentry = rcu_dereference_check(cgrp->dentry,
1787 cgroup_lock_is_held());
1788 if (!cgrp->parent)
1789 continue;
1790 if (--start < buf)
1791 return -ENAMETOOLONG;
1792 *start = '/';
1794 memmove(buf, start, buf + buflen - start);
1795 return 0;
1797 EXPORT_SYMBOL_GPL(cgroup_path);
1800 * Control Group taskset
1802 struct task_and_cgroup {
1803 struct task_struct *task;
1804 struct cgroup *cgrp;
1805 struct css_set *cg;
1808 struct cgroup_taskset {
1809 struct task_and_cgroup single;
1810 struct flex_array *tc_array;
1811 int tc_array_len;
1812 int idx;
1813 struct cgroup *cur_cgrp;
1817 * cgroup_taskset_first - reset taskset and return the first task
1818 * @tset: taskset of interest
1820 * @tset iteration is initialized and the first task is returned.
1822 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1824 if (tset->tc_array) {
1825 tset->idx = 0;
1826 return cgroup_taskset_next(tset);
1827 } else {
1828 tset->cur_cgrp = tset->single.cgrp;
1829 return tset->single.task;
1832 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1835 * cgroup_taskset_next - iterate to the next task in taskset
1836 * @tset: taskset of interest
1838 * Return the next task in @tset. Iteration must have been initialized
1839 * with cgroup_taskset_first().
1841 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1843 struct task_and_cgroup *tc;
1845 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1846 return NULL;
1848 tc = flex_array_get(tset->tc_array, tset->idx++);
1849 tset->cur_cgrp = tc->cgrp;
1850 return tc->task;
1852 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1855 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1856 * @tset: taskset of interest
1858 * Return the cgroup for the current (last returned) task of @tset. This
1859 * function must be preceded by either cgroup_taskset_first() or
1860 * cgroup_taskset_next().
1862 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1864 return tset->cur_cgrp;
1866 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1869 * cgroup_taskset_size - return the number of tasks in taskset
1870 * @tset: taskset of interest
1872 int cgroup_taskset_size(struct cgroup_taskset *tset)
1874 return tset->tc_array ? tset->tc_array_len : 1;
1876 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1880 * cgroup_task_migrate - move a task from one cgroup to another.
1882 * 'guarantee' is set if the caller promises that a new css_set for the task
1883 * will already exist. If not set, this function might sleep, and can fail with
1884 * -ENOMEM. Must be called with cgroup_mutex and threadgroup locked.
1886 static void cgroup_task_migrate(struct cgroup *cgrp, struct cgroup *oldcgrp,
1887 struct task_struct *tsk, struct css_set *newcg)
1889 struct css_set *oldcg;
1892 * We are synchronized through threadgroup_lock() against PF_EXITING
1893 * setting such that we can't race against cgroup_exit() changing the
1894 * css_set to init_css_set and dropping the old one.
1896 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1897 oldcg = tsk->cgroups;
1899 task_lock(tsk);
1900 rcu_assign_pointer(tsk->cgroups, newcg);
1901 task_unlock(tsk);
1903 /* Update the css_set linked lists if we're using them */
1904 write_lock(&css_set_lock);
1905 if (!list_empty(&tsk->cg_list))
1906 list_move(&tsk->cg_list, &newcg->tasks);
1907 write_unlock(&css_set_lock);
1910 * We just gained a reference on oldcg by taking it from the task. As
1911 * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1912 * it here; it will be freed under RCU.
1914 put_css_set(oldcg);
1916 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1920 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1921 * @cgrp: the cgroup the task is attaching to
1922 * @tsk: the task to be attached
1924 * Call with cgroup_mutex and threadgroup locked. May take task_lock of
1925 * @tsk during call.
1927 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1929 int retval = 0;
1930 struct cgroup_subsys *ss, *failed_ss = NULL;
1931 struct cgroup *oldcgrp;
1932 struct cgroupfs_root *root = cgrp->root;
1933 struct cgroup_taskset tset = { };
1934 struct css_set *newcg;
1936 /* @tsk either already exited or can't exit until the end */
1937 if (tsk->flags & PF_EXITING)
1938 return -ESRCH;
1940 /* Nothing to do if the task is already in that cgroup */
1941 oldcgrp = task_cgroup_from_root(tsk, root);
1942 if (cgrp == oldcgrp)
1943 return 0;
1945 tset.single.task = tsk;
1946 tset.single.cgrp = oldcgrp;
1948 for_each_subsys(root, ss) {
1949 if (ss->can_attach) {
1950 retval = ss->can_attach(cgrp, &tset);
1951 if (retval) {
1953 * Remember on which subsystem the can_attach()
1954 * failed, so that we only call cancel_attach()
1955 * against the subsystems whose can_attach()
1956 * succeeded. (See below)
1958 failed_ss = ss;
1959 goto out;
1964 newcg = find_css_set(tsk->cgroups, cgrp);
1965 if (!newcg) {
1966 retval = -ENOMEM;
1967 goto out;
1970 cgroup_task_migrate(cgrp, oldcgrp, tsk, newcg);
1972 for_each_subsys(root, ss) {
1973 if (ss->attach)
1974 ss->attach(cgrp, &tset);
1977 synchronize_rcu();
1978 out:
1979 if (retval) {
1980 for_each_subsys(root, ss) {
1981 if (ss == failed_ss)
1983 * This subsystem was the one that failed the
1984 * can_attach() check earlier, so we don't need
1985 * to call cancel_attach() against it or any
1986 * remaining subsystems.
1988 break;
1989 if (ss->cancel_attach)
1990 ss->cancel_attach(cgrp, &tset);
1993 return retval;
1997 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
1998 * @from: attach to all cgroups of a given task
1999 * @tsk: the task to be attached
2001 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2003 struct cgroupfs_root *root;
2004 int retval = 0;
2006 cgroup_lock();
2007 for_each_active_root(root) {
2008 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2010 retval = cgroup_attach_task(from_cg, tsk);
2011 if (retval)
2012 break;
2014 cgroup_unlock();
2016 return retval;
2018 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2021 * cgroup_attach_proc - attach all threads in a threadgroup to a cgroup
2022 * @cgrp: the cgroup to attach to
2023 * @leader: the threadgroup leader task_struct of the group to be attached
2025 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
2026 * task_lock of each thread in leader's threadgroup individually in turn.
2028 static int cgroup_attach_proc(struct cgroup *cgrp, struct task_struct *leader)
2030 int retval, i, group_size;
2031 struct cgroup_subsys *ss, *failed_ss = NULL;
2032 /* guaranteed to be initialized later, but the compiler needs this */
2033 struct cgroupfs_root *root = cgrp->root;
2034 /* threadgroup list cursor and array */
2035 struct task_struct *tsk;
2036 struct task_and_cgroup *tc;
2037 struct flex_array *group;
2038 struct cgroup_taskset tset = { };
2041 * step 0: in order to do expensive, possibly blocking operations for
2042 * every thread, we cannot iterate the thread group list, since it needs
2043 * rcu or tasklist locked. instead, build an array of all threads in the
2044 * group - group_rwsem prevents new threads from appearing, and if
2045 * threads exit, this will just be an over-estimate.
2047 group_size = get_nr_threads(leader);
2048 /* flex_array supports very large thread-groups better than kmalloc. */
2049 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2050 if (!group)
2051 return -ENOMEM;
2052 /* pre-allocate to guarantee space while iterating in rcu read-side. */
2053 retval = flex_array_prealloc(group, 0, group_size - 1, GFP_KERNEL);
2054 if (retval)
2055 goto out_free_group_list;
2057 tsk = leader;
2058 i = 0;
2060 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2061 * already PF_EXITING could be freed from underneath us unless we
2062 * take an rcu_read_lock.
2064 rcu_read_lock();
2065 do {
2066 struct task_and_cgroup ent;
2068 /* @tsk either already exited or can't exit until the end */
2069 if (tsk->flags & PF_EXITING)
2070 continue;
2072 /* as per above, nr_threads may decrease, but not increase. */
2073 BUG_ON(i >= group_size);
2074 ent.task = tsk;
2075 ent.cgrp = task_cgroup_from_root(tsk, root);
2076 /* nothing to do if this task is already in the cgroup */
2077 if (ent.cgrp == cgrp)
2078 continue;
2080 * saying GFP_ATOMIC has no effect here because we did prealloc
2081 * earlier, but it's good form to communicate our expectations.
2083 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2084 BUG_ON(retval != 0);
2085 i++;
2086 } while_each_thread(leader, tsk);
2087 rcu_read_unlock();
2088 /* remember the number of threads in the array for later. */
2089 group_size = i;
2090 tset.tc_array = group;
2091 tset.tc_array_len = group_size;
2093 /* methods shouldn't be called if no task is actually migrating */
2094 retval = 0;
2095 if (!group_size)
2096 goto out_free_group_list;
2099 * step 1: check that we can legitimately attach to the cgroup.
2101 for_each_subsys(root, ss) {
2102 if (ss->can_attach) {
2103 retval = ss->can_attach(cgrp, &tset);
2104 if (retval) {
2105 failed_ss = ss;
2106 goto out_cancel_attach;
2112 * step 2: make sure css_sets exist for all threads to be migrated.
2113 * we use find_css_set, which allocates a new one if necessary.
2115 for (i = 0; i < group_size; i++) {
2116 tc = flex_array_get(group, i);
2117 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2118 if (!tc->cg) {
2119 retval = -ENOMEM;
2120 goto out_put_css_set_refs;
2125 * step 3: now that we're guaranteed success wrt the css_sets,
2126 * proceed to move all tasks to the new cgroup. There are no
2127 * failure cases after here, so this is the commit point.
2129 for (i = 0; i < group_size; i++) {
2130 tc = flex_array_get(group, i);
2131 cgroup_task_migrate(cgrp, tc->cgrp, tc->task, tc->cg);
2133 /* nothing is sensitive to fork() after this point. */
2136 * step 4: do subsystem attach callbacks.
2138 for_each_subsys(root, ss) {
2139 if (ss->attach)
2140 ss->attach(cgrp, &tset);
2144 * step 5: success! and cleanup
2146 synchronize_rcu();
2147 retval = 0;
2148 out_put_css_set_refs:
2149 if (retval) {
2150 for (i = 0; i < group_size; i++) {
2151 tc = flex_array_get(group, i);
2152 if (!tc->cg)
2153 break;
2154 put_css_set(tc->cg);
2157 out_cancel_attach:
2158 if (retval) {
2159 for_each_subsys(root, ss) {
2160 if (ss == failed_ss)
2161 break;
2162 if (ss->cancel_attach)
2163 ss->cancel_attach(cgrp, &tset);
2166 out_free_group_list:
2167 flex_array_free(group);
2168 return retval;
2172 * Find the task_struct of the task to attach by vpid and pass it along to the
2173 * function to attach either it or all tasks in its threadgroup. Will lock
2174 * cgroup_mutex and threadgroup; may take task_lock of task.
2176 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2178 struct task_struct *tsk;
2179 const struct cred *cred = current_cred(), *tcred;
2180 int ret;
2182 if (!cgroup_lock_live_group(cgrp))
2183 return -ENODEV;
2185 retry_find_task:
2186 rcu_read_lock();
2187 if (pid) {
2188 tsk = find_task_by_vpid(pid);
2189 if (!tsk) {
2190 rcu_read_unlock();
2191 ret= -ESRCH;
2192 goto out_unlock_cgroup;
2195 * even if we're attaching all tasks in the thread group, we
2196 * only need to check permissions on one of them.
2198 tcred = __task_cred(tsk);
2199 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2200 !uid_eq(cred->euid, tcred->uid) &&
2201 !uid_eq(cred->euid, tcred->suid)) {
2202 rcu_read_unlock();
2203 ret = -EACCES;
2204 goto out_unlock_cgroup;
2206 } else
2207 tsk = current;
2209 if (threadgroup)
2210 tsk = tsk->group_leader;
2213 * Workqueue threads may acquire PF_THREAD_BOUND and become
2214 * trapped in a cpuset, or RT worker may be born in a cgroup
2215 * with no rt_runtime allocated. Just say no.
2217 if (tsk == kthreadd_task || (tsk->flags & PF_THREAD_BOUND)) {
2218 ret = -EINVAL;
2219 rcu_read_unlock();
2220 goto out_unlock_cgroup;
2223 get_task_struct(tsk);
2224 rcu_read_unlock();
2226 threadgroup_lock(tsk);
2227 if (threadgroup) {
2228 if (!thread_group_leader(tsk)) {
2230 * a race with de_thread from another thread's exec()
2231 * may strip us of our leadership, if this happens,
2232 * there is no choice but to throw this task away and
2233 * try again; this is
2234 * "double-double-toil-and-trouble-check locking".
2236 threadgroup_unlock(tsk);
2237 put_task_struct(tsk);
2238 goto retry_find_task;
2240 ret = cgroup_attach_proc(cgrp, tsk);
2241 } else
2242 ret = cgroup_attach_task(cgrp, tsk);
2243 threadgroup_unlock(tsk);
2245 put_task_struct(tsk);
2246 out_unlock_cgroup:
2247 cgroup_unlock();
2248 return ret;
2251 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2253 return attach_task_by_pid(cgrp, pid, false);
2256 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2258 return attach_task_by_pid(cgrp, tgid, true);
2262 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
2263 * @cgrp: the cgroup to be checked for liveness
2265 * On success, returns true; the lock should be later released with
2266 * cgroup_unlock(). On failure returns false with no lock held.
2268 bool cgroup_lock_live_group(struct cgroup *cgrp)
2270 mutex_lock(&cgroup_mutex);
2271 if (cgroup_is_removed(cgrp)) {
2272 mutex_unlock(&cgroup_mutex);
2273 return false;
2275 return true;
2277 EXPORT_SYMBOL_GPL(cgroup_lock_live_group);
2279 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2280 const char *buffer)
2282 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2283 if (strlen(buffer) >= PATH_MAX)
2284 return -EINVAL;
2285 if (!cgroup_lock_live_group(cgrp))
2286 return -ENODEV;
2287 mutex_lock(&cgroup_root_mutex);
2288 strcpy(cgrp->root->release_agent_path, buffer);
2289 mutex_unlock(&cgroup_root_mutex);
2290 cgroup_unlock();
2291 return 0;
2294 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2295 struct seq_file *seq)
2297 if (!cgroup_lock_live_group(cgrp))
2298 return -ENODEV;
2299 seq_puts(seq, cgrp->root->release_agent_path);
2300 seq_putc(seq, '\n');
2301 cgroup_unlock();
2302 return 0;
2305 /* A buffer size big enough for numbers or short strings */
2306 #define CGROUP_LOCAL_BUFFER_SIZE 64
2308 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2309 struct file *file,
2310 const char __user *userbuf,
2311 size_t nbytes, loff_t *unused_ppos)
2313 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2314 int retval = 0;
2315 char *end;
2317 if (!nbytes)
2318 return -EINVAL;
2319 if (nbytes >= sizeof(buffer))
2320 return -E2BIG;
2321 if (copy_from_user(buffer, userbuf, nbytes))
2322 return -EFAULT;
2324 buffer[nbytes] = 0; /* nul-terminate */
2325 if (cft->write_u64) {
2326 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2327 if (*end)
2328 return -EINVAL;
2329 retval = cft->write_u64(cgrp, cft, val);
2330 } else {
2331 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2332 if (*end)
2333 return -EINVAL;
2334 retval = cft->write_s64(cgrp, cft, val);
2336 if (!retval)
2337 retval = nbytes;
2338 return retval;
2341 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2342 struct file *file,
2343 const char __user *userbuf,
2344 size_t nbytes, loff_t *unused_ppos)
2346 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2347 int retval = 0;
2348 size_t max_bytes = cft->max_write_len;
2349 char *buffer = local_buffer;
2351 if (!max_bytes)
2352 max_bytes = sizeof(local_buffer) - 1;
2353 if (nbytes >= max_bytes)
2354 return -E2BIG;
2355 /* Allocate a dynamic buffer if we need one */
2356 if (nbytes >= sizeof(local_buffer)) {
2357 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2358 if (buffer == NULL)
2359 return -ENOMEM;
2361 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2362 retval = -EFAULT;
2363 goto out;
2366 buffer[nbytes] = 0; /* nul-terminate */
2367 retval = cft->write_string(cgrp, cft, strstrip(buffer));
2368 if (!retval)
2369 retval = nbytes;
2370 out:
2371 if (buffer != local_buffer)
2372 kfree(buffer);
2373 return retval;
2376 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2377 size_t nbytes, loff_t *ppos)
2379 struct cftype *cft = __d_cft(file->f_dentry);
2380 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2382 if (cgroup_is_removed(cgrp))
2383 return -ENODEV;
2384 if (cft->write)
2385 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2386 if (cft->write_u64 || cft->write_s64)
2387 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2388 if (cft->write_string)
2389 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2390 if (cft->trigger) {
2391 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2392 return ret ? ret : nbytes;
2394 return -EINVAL;
2397 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2398 struct file *file,
2399 char __user *buf, size_t nbytes,
2400 loff_t *ppos)
2402 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2403 u64 val = cft->read_u64(cgrp, cft);
2404 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2406 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2409 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2410 struct file *file,
2411 char __user *buf, size_t nbytes,
2412 loff_t *ppos)
2414 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2415 s64 val = cft->read_s64(cgrp, cft);
2416 int len = sprintf(tmp, "%lld\n", (long long) val);
2418 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2421 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2422 size_t nbytes, loff_t *ppos)
2424 struct cftype *cft = __d_cft(file->f_dentry);
2425 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2427 if (cgroup_is_removed(cgrp))
2428 return -ENODEV;
2430 if (cft->read)
2431 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2432 if (cft->read_u64)
2433 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2434 if (cft->read_s64)
2435 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2436 return -EINVAL;
2440 * seqfile ops/methods for returning structured data. Currently just
2441 * supports string->u64 maps, but can be extended in future.
2444 struct cgroup_seqfile_state {
2445 struct cftype *cft;
2446 struct cgroup *cgroup;
2449 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2451 struct seq_file *sf = cb->state;
2452 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2455 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2457 struct cgroup_seqfile_state *state = m->private;
2458 struct cftype *cft = state->cft;
2459 if (cft->read_map) {
2460 struct cgroup_map_cb cb = {
2461 .fill = cgroup_map_add,
2462 .state = m,
2464 return cft->read_map(state->cgroup, cft, &cb);
2466 return cft->read_seq_string(state->cgroup, cft, m);
2469 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2471 struct seq_file *seq = file->private_data;
2472 kfree(seq->private);
2473 return single_release(inode, file);
2476 static const struct file_operations cgroup_seqfile_operations = {
2477 .read = seq_read,
2478 .write = cgroup_file_write,
2479 .llseek = seq_lseek,
2480 .release = cgroup_seqfile_release,
2483 static int cgroup_file_open(struct inode *inode, struct file *file)
2485 int err;
2486 struct cftype *cft;
2488 err = generic_file_open(inode, file);
2489 if (err)
2490 return err;
2491 cft = __d_cft(file->f_dentry);
2493 if (cft->read_map || cft->read_seq_string) {
2494 struct cgroup_seqfile_state *state =
2495 kzalloc(sizeof(*state), GFP_USER);
2496 if (!state)
2497 return -ENOMEM;
2498 state->cft = cft;
2499 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2500 file->f_op = &cgroup_seqfile_operations;
2501 err = single_open(file, cgroup_seqfile_show, state);
2502 if (err < 0)
2503 kfree(state);
2504 } else if (cft->open)
2505 err = cft->open(inode, file);
2506 else
2507 err = 0;
2509 return err;
2512 static int cgroup_file_release(struct inode *inode, struct file *file)
2514 struct cftype *cft = __d_cft(file->f_dentry);
2515 if (cft->release)
2516 return cft->release(inode, file);
2517 return 0;
2521 * cgroup_rename - Only allow simple rename of directories in place.
2523 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2524 struct inode *new_dir, struct dentry *new_dentry)
2526 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2527 return -ENOTDIR;
2528 if (new_dentry->d_inode)
2529 return -EEXIST;
2530 if (old_dir != new_dir)
2531 return -EIO;
2532 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2535 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2537 if (S_ISDIR(dentry->d_inode->i_mode))
2538 return &__d_cgrp(dentry)->xattrs;
2539 else
2540 return &__d_cft(dentry)->xattrs;
2543 static inline int xattr_enabled(struct dentry *dentry)
2545 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2546 return test_bit(ROOT_XATTR, &root->flags);
2549 static bool is_valid_xattr(const char *name)
2551 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2552 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2553 return true;
2554 return false;
2557 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2558 const void *val, size_t size, int flags)
2560 if (!xattr_enabled(dentry))
2561 return -EOPNOTSUPP;
2562 if (!is_valid_xattr(name))
2563 return -EINVAL;
2564 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2567 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2569 if (!xattr_enabled(dentry))
2570 return -EOPNOTSUPP;
2571 if (!is_valid_xattr(name))
2572 return -EINVAL;
2573 return simple_xattr_remove(__d_xattrs(dentry), name);
2576 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2577 void *buf, size_t size)
2579 if (!xattr_enabled(dentry))
2580 return -EOPNOTSUPP;
2581 if (!is_valid_xattr(name))
2582 return -EINVAL;
2583 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2586 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2588 if (!xattr_enabled(dentry))
2589 return -EOPNOTSUPP;
2590 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2593 static const struct file_operations cgroup_file_operations = {
2594 .read = cgroup_file_read,
2595 .write = cgroup_file_write,
2596 .llseek = generic_file_llseek,
2597 .open = cgroup_file_open,
2598 .release = cgroup_file_release,
2601 static const struct inode_operations cgroup_file_inode_operations = {
2602 .setxattr = cgroup_setxattr,
2603 .getxattr = cgroup_getxattr,
2604 .listxattr = cgroup_listxattr,
2605 .removexattr = cgroup_removexattr,
2608 static const struct inode_operations cgroup_dir_inode_operations = {
2609 .lookup = cgroup_lookup,
2610 .mkdir = cgroup_mkdir,
2611 .rmdir = cgroup_rmdir,
2612 .rename = cgroup_rename,
2613 .setxattr = cgroup_setxattr,
2614 .getxattr = cgroup_getxattr,
2615 .listxattr = cgroup_listxattr,
2616 .removexattr = cgroup_removexattr,
2619 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2621 if (dentry->d_name.len > NAME_MAX)
2622 return ERR_PTR(-ENAMETOOLONG);
2623 d_add(dentry, NULL);
2624 return NULL;
2628 * Check if a file is a control file
2630 static inline struct cftype *__file_cft(struct file *file)
2632 if (file->f_dentry->d_inode->i_fop != &cgroup_file_operations)
2633 return ERR_PTR(-EINVAL);
2634 return __d_cft(file->f_dentry);
2637 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2638 struct super_block *sb)
2640 struct inode *inode;
2642 if (!dentry)
2643 return -ENOENT;
2644 if (dentry->d_inode)
2645 return -EEXIST;
2647 inode = cgroup_new_inode(mode, sb);
2648 if (!inode)
2649 return -ENOMEM;
2651 if (S_ISDIR(mode)) {
2652 inode->i_op = &cgroup_dir_inode_operations;
2653 inode->i_fop = &simple_dir_operations;
2655 /* start off with i_nlink == 2 (for "." entry) */
2656 inc_nlink(inode);
2658 /* start with the directory inode held, so that we can
2659 * populate it without racing with another mkdir */
2660 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
2661 } else if (S_ISREG(mode)) {
2662 inode->i_size = 0;
2663 inode->i_fop = &cgroup_file_operations;
2664 inode->i_op = &cgroup_file_inode_operations;
2666 d_instantiate(dentry, inode);
2667 dget(dentry); /* Extra count - pin the dentry in core */
2668 return 0;
2672 * cgroup_create_dir - create a directory for an object.
2673 * @cgrp: the cgroup we create the directory for. It must have a valid
2674 * ->parent field. And we are going to fill its ->dentry field.
2675 * @dentry: dentry of the new cgroup
2676 * @mode: mode to set on new directory.
2678 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
2679 umode_t mode)
2681 struct dentry *parent;
2682 int error = 0;
2684 parent = cgrp->parent->dentry;
2685 error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
2686 if (!error) {
2687 dentry->d_fsdata = cgrp;
2688 inc_nlink(parent->d_inode);
2689 rcu_assign_pointer(cgrp->dentry, dentry);
2690 dget(dentry);
2692 dput(dentry);
2694 return error;
2698 * cgroup_file_mode - deduce file mode of a control file
2699 * @cft: the control file in question
2701 * returns cft->mode if ->mode is not 0
2702 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2703 * returns S_IRUGO if it has only a read handler
2704 * returns S_IWUSR if it has only a write hander
2706 static umode_t cgroup_file_mode(const struct cftype *cft)
2708 umode_t mode = 0;
2710 if (cft->mode)
2711 return cft->mode;
2713 if (cft->read || cft->read_u64 || cft->read_s64 ||
2714 cft->read_map || cft->read_seq_string)
2715 mode |= S_IRUGO;
2717 if (cft->write || cft->write_u64 || cft->write_s64 ||
2718 cft->write_string || cft->trigger)
2719 mode |= S_IWUSR;
2721 return mode;
2724 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2725 struct cftype *cft)
2727 struct dentry *dir = cgrp->dentry;
2728 struct cgroup *parent = __d_cgrp(dir);
2729 struct dentry *dentry;
2730 struct cfent *cfe;
2731 int error;
2732 umode_t mode;
2733 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2735 simple_xattrs_init(&cft->xattrs);
2737 /* does @cft->flags tell us to skip creation on @cgrp? */
2738 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2739 return 0;
2740 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2741 return 0;
2743 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2744 strcpy(name, subsys->name);
2745 strcat(name, ".");
2747 strcat(name, cft->name);
2749 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2751 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2752 if (!cfe)
2753 return -ENOMEM;
2755 dentry = lookup_one_len(name, dir, strlen(name));
2756 if (IS_ERR(dentry)) {
2757 error = PTR_ERR(dentry);
2758 goto out;
2761 mode = cgroup_file_mode(cft);
2762 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2763 if (!error) {
2764 cfe->type = (void *)cft;
2765 cfe->dentry = dentry;
2766 dentry->d_fsdata = cfe;
2767 list_add_tail(&cfe->node, &parent->files);
2768 cfe = NULL;
2770 dput(dentry);
2771 out:
2772 kfree(cfe);
2773 return error;
2776 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2777 struct cftype cfts[], bool is_add)
2779 struct cftype *cft;
2780 int err, ret = 0;
2782 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2783 if (is_add)
2784 err = cgroup_add_file(cgrp, subsys, cft);
2785 else
2786 err = cgroup_rm_file(cgrp, cft);
2787 if (err) {
2788 pr_warning("cgroup_addrm_files: failed to %s %s, err=%d\n",
2789 is_add ? "add" : "remove", cft->name, err);
2790 ret = err;
2793 return ret;
2796 static DEFINE_MUTEX(cgroup_cft_mutex);
2798 static void cgroup_cfts_prepare(void)
2799 __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2802 * Thanks to the entanglement with vfs inode locking, we can't walk
2803 * the existing cgroups under cgroup_mutex and create files.
2804 * Instead, we increment reference on all cgroups and build list of
2805 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2806 * exclusive access to the field.
2808 mutex_lock(&cgroup_cft_mutex);
2809 mutex_lock(&cgroup_mutex);
2812 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2813 struct cftype *cfts, bool is_add)
2814 __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2816 LIST_HEAD(pending);
2817 struct cgroup *cgrp, *n;
2819 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2820 if (cfts && ss->root != &rootnode) {
2821 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2822 dget(cgrp->dentry);
2823 list_add_tail(&cgrp->cft_q_node, &pending);
2827 mutex_unlock(&cgroup_mutex);
2830 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2831 * files for all cgroups which were created before.
2833 list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2834 struct inode *inode = cgrp->dentry->d_inode;
2836 mutex_lock(&inode->i_mutex);
2837 mutex_lock(&cgroup_mutex);
2838 if (!cgroup_is_removed(cgrp))
2839 cgroup_addrm_files(cgrp, ss, cfts, is_add);
2840 mutex_unlock(&cgroup_mutex);
2841 mutex_unlock(&inode->i_mutex);
2843 list_del_init(&cgrp->cft_q_node);
2844 dput(cgrp->dentry);
2847 mutex_unlock(&cgroup_cft_mutex);
2851 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2852 * @ss: target cgroup subsystem
2853 * @cfts: zero-length name terminated array of cftypes
2855 * Register @cfts to @ss. Files described by @cfts are created for all
2856 * existing cgroups to which @ss is attached and all future cgroups will
2857 * have them too. This function can be called anytime whether @ss is
2858 * attached or not.
2860 * Returns 0 on successful registration, -errno on failure. Note that this
2861 * function currently returns 0 as long as @cfts registration is successful
2862 * even if some file creation attempts on existing cgroups fail.
2864 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2866 struct cftype_set *set;
2868 set = kzalloc(sizeof(*set), GFP_KERNEL);
2869 if (!set)
2870 return -ENOMEM;
2872 cgroup_cfts_prepare();
2873 set->cfts = cfts;
2874 list_add_tail(&set->node, &ss->cftsets);
2875 cgroup_cfts_commit(ss, cfts, true);
2877 return 0;
2879 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2882 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2883 * @ss: target cgroup subsystem
2884 * @cfts: zero-length name terminated array of cftypes
2886 * Unregister @cfts from @ss. Files described by @cfts are removed from
2887 * all existing cgroups to which @ss is attached and all future cgroups
2888 * won't have them either. This function can be called anytime whether @ss
2889 * is attached or not.
2891 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2892 * registered with @ss.
2894 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2896 struct cftype_set *set;
2898 cgroup_cfts_prepare();
2900 list_for_each_entry(set, &ss->cftsets, node) {
2901 if (set->cfts == cfts) {
2902 list_del_init(&set->node);
2903 cgroup_cfts_commit(ss, cfts, false);
2904 return 0;
2908 cgroup_cfts_commit(ss, NULL, false);
2909 return -ENOENT;
2913 * cgroup_task_count - count the number of tasks in a cgroup.
2914 * @cgrp: the cgroup in question
2916 * Return the number of tasks in the cgroup.
2918 int cgroup_task_count(const struct cgroup *cgrp)
2920 int count = 0;
2921 struct cg_cgroup_link *link;
2923 read_lock(&css_set_lock);
2924 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2925 count += atomic_read(&link->cg->refcount);
2927 read_unlock(&css_set_lock);
2928 return count;
2932 * Advance a list_head iterator. The iterator should be positioned at
2933 * the start of a css_set
2935 static void cgroup_advance_iter(struct cgroup *cgrp,
2936 struct cgroup_iter *it)
2938 struct list_head *l = it->cg_link;
2939 struct cg_cgroup_link *link;
2940 struct css_set *cg;
2942 /* Advance to the next non-empty css_set */
2943 do {
2944 l = l->next;
2945 if (l == &cgrp->css_sets) {
2946 it->cg_link = NULL;
2947 return;
2949 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2950 cg = link->cg;
2951 } while (list_empty(&cg->tasks));
2952 it->cg_link = l;
2953 it->task = cg->tasks.next;
2957 * To reduce the fork() overhead for systems that are not actually
2958 * using their cgroups capability, we don't maintain the lists running
2959 * through each css_set to its tasks until we see the list actually
2960 * used - in other words after the first call to cgroup_iter_start().
2962 static void cgroup_enable_task_cg_lists(void)
2964 struct task_struct *p, *g;
2965 write_lock(&css_set_lock);
2966 use_task_css_set_links = 1;
2968 * We need tasklist_lock because RCU is not safe against
2969 * while_each_thread(). Besides, a forking task that has passed
2970 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2971 * is not guaranteed to have its child immediately visible in the
2972 * tasklist if we walk through it with RCU.
2974 read_lock(&tasklist_lock);
2975 do_each_thread(g, p) {
2976 task_lock(p);
2978 * We should check if the process is exiting, otherwise
2979 * it will race with cgroup_exit() in that the list
2980 * entry won't be deleted though the process has exited.
2982 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2983 list_add(&p->cg_list, &p->cgroups->tasks);
2984 task_unlock(p);
2985 } while_each_thread(g, p);
2986 read_unlock(&tasklist_lock);
2987 write_unlock(&css_set_lock);
2990 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
2991 __acquires(css_set_lock)
2994 * The first time anyone tries to iterate across a cgroup,
2995 * we need to enable the list linking each css_set to its
2996 * tasks, and fix up all existing tasks.
2998 if (!use_task_css_set_links)
2999 cgroup_enable_task_cg_lists();
3001 read_lock(&css_set_lock);
3002 it->cg_link = &cgrp->css_sets;
3003 cgroup_advance_iter(cgrp, it);
3006 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3007 struct cgroup_iter *it)
3009 struct task_struct *res;
3010 struct list_head *l = it->task;
3011 struct cg_cgroup_link *link;
3013 /* If the iterator cg is NULL, we have no tasks */
3014 if (!it->cg_link)
3015 return NULL;
3016 res = list_entry(l, struct task_struct, cg_list);
3017 /* Advance iterator to find next entry */
3018 l = l->next;
3019 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3020 if (l == &link->cg->tasks) {
3021 /* We reached the end of this task list - move on to
3022 * the next cg_cgroup_link */
3023 cgroup_advance_iter(cgrp, it);
3024 } else {
3025 it->task = l;
3027 return res;
3030 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3031 __releases(css_set_lock)
3033 read_unlock(&css_set_lock);
3036 static inline int started_after_time(struct task_struct *t1,
3037 struct timespec *time,
3038 struct task_struct *t2)
3040 int start_diff = timespec_compare(&t1->start_time, time);
3041 if (start_diff > 0) {
3042 return 1;
3043 } else if (start_diff < 0) {
3044 return 0;
3045 } else {
3047 * Arbitrarily, if two processes started at the same
3048 * time, we'll say that the lower pointer value
3049 * started first. Note that t2 may have exited by now
3050 * so this may not be a valid pointer any longer, but
3051 * that's fine - it still serves to distinguish
3052 * between two tasks started (effectively) simultaneously.
3054 return t1 > t2;
3059 * This function is a callback from heap_insert() and is used to order
3060 * the heap.
3061 * In this case we order the heap in descending task start time.
3063 static inline int started_after(void *p1, void *p2)
3065 struct task_struct *t1 = p1;
3066 struct task_struct *t2 = p2;
3067 return started_after_time(t1, &t2->start_time, t2);
3071 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3072 * @scan: struct cgroup_scanner containing arguments for the scan
3074 * Arguments include pointers to callback functions test_task() and
3075 * process_task().
3076 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3077 * and if it returns true, call process_task() for it also.
3078 * The test_task pointer may be NULL, meaning always true (select all tasks).
3079 * Effectively duplicates cgroup_iter_{start,next,end}()
3080 * but does not lock css_set_lock for the call to process_task().
3081 * The struct cgroup_scanner may be embedded in any structure of the caller's
3082 * creation.
3083 * It is guaranteed that process_task() will act on every task that
3084 * is a member of the cgroup for the duration of this call. This
3085 * function may or may not call process_task() for tasks that exit
3086 * or move to a different cgroup during the call, or are forked or
3087 * move into the cgroup during the call.
3089 * Note that test_task() may be called with locks held, and may in some
3090 * situations be called multiple times for the same task, so it should
3091 * be cheap.
3092 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3093 * pre-allocated and will be used for heap operations (and its "gt" member will
3094 * be overwritten), else a temporary heap will be used (allocation of which
3095 * may cause this function to fail).
3097 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3099 int retval, i;
3100 struct cgroup_iter it;
3101 struct task_struct *p, *dropped;
3102 /* Never dereference latest_task, since it's not refcounted */
3103 struct task_struct *latest_task = NULL;
3104 struct ptr_heap tmp_heap;
3105 struct ptr_heap *heap;
3106 struct timespec latest_time = { 0, 0 };
3108 if (scan->heap) {
3109 /* The caller supplied our heap and pre-allocated its memory */
3110 heap = scan->heap;
3111 heap->gt = &started_after;
3112 } else {
3113 /* We need to allocate our own heap memory */
3114 heap = &tmp_heap;
3115 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3116 if (retval)
3117 /* cannot allocate the heap */
3118 return retval;
3121 again:
3123 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3124 * to determine which are of interest, and using the scanner's
3125 * "process_task" callback to process any of them that need an update.
3126 * Since we don't want to hold any locks during the task updates,
3127 * gather tasks to be processed in a heap structure.
3128 * The heap is sorted by descending task start time.
3129 * If the statically-sized heap fills up, we overflow tasks that
3130 * started later, and in future iterations only consider tasks that
3131 * started after the latest task in the previous pass. This
3132 * guarantees forward progress and that we don't miss any tasks.
3134 heap->size = 0;
3135 cgroup_iter_start(scan->cg, &it);
3136 while ((p = cgroup_iter_next(scan->cg, &it))) {
3138 * Only affect tasks that qualify per the caller's callback,
3139 * if he provided one
3141 if (scan->test_task && !scan->test_task(p, scan))
3142 continue;
3144 * Only process tasks that started after the last task
3145 * we processed
3147 if (!started_after_time(p, &latest_time, latest_task))
3148 continue;
3149 dropped = heap_insert(heap, p);
3150 if (dropped == NULL) {
3152 * The new task was inserted; the heap wasn't
3153 * previously full
3155 get_task_struct(p);
3156 } else if (dropped != p) {
3158 * The new task was inserted, and pushed out a
3159 * different task
3161 get_task_struct(p);
3162 put_task_struct(dropped);
3165 * Else the new task was newer than anything already in
3166 * the heap and wasn't inserted
3169 cgroup_iter_end(scan->cg, &it);
3171 if (heap->size) {
3172 for (i = 0; i < heap->size; i++) {
3173 struct task_struct *q = heap->ptrs[i];
3174 if (i == 0) {
3175 latest_time = q->start_time;
3176 latest_task = q;
3178 /* Process the task per the caller's callback */
3179 scan->process_task(q, scan);
3180 put_task_struct(q);
3183 * If we had to process any tasks at all, scan again
3184 * in case some of them were in the middle of forking
3185 * children that didn't get processed.
3186 * Not the most efficient way to do it, but it avoids
3187 * having to take callback_mutex in the fork path
3189 goto again;
3191 if (heap == &tmp_heap)
3192 heap_free(&tmp_heap);
3193 return 0;
3197 * Stuff for reading the 'tasks'/'procs' files.
3199 * Reading this file can return large amounts of data if a cgroup has
3200 * *lots* of attached tasks. So it may need several calls to read(),
3201 * but we cannot guarantee that the information we produce is correct
3202 * unless we produce it entirely atomically.
3206 /* which pidlist file are we talking about? */
3207 enum cgroup_filetype {
3208 CGROUP_FILE_PROCS,
3209 CGROUP_FILE_TASKS,
3213 * A pidlist is a list of pids that virtually represents the contents of one
3214 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3215 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3216 * to the cgroup.
3218 struct cgroup_pidlist {
3220 * used to find which pidlist is wanted. doesn't change as long as
3221 * this particular list stays in the list.
3223 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3224 /* array of xids */
3225 pid_t *list;
3226 /* how many elements the above list has */
3227 int length;
3228 /* how many files are using the current array */
3229 int use_count;
3230 /* each of these stored in a list by its cgroup */
3231 struct list_head links;
3232 /* pointer to the cgroup we belong to, for list removal purposes */
3233 struct cgroup *owner;
3234 /* protects the other fields */
3235 struct rw_semaphore mutex;
3239 * The following two functions "fix" the issue where there are more pids
3240 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3241 * TODO: replace with a kernel-wide solution to this problem
3243 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3244 static void *pidlist_allocate(int count)
3246 if (PIDLIST_TOO_LARGE(count))
3247 return vmalloc(count * sizeof(pid_t));
3248 else
3249 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3251 static void pidlist_free(void *p)
3253 if (is_vmalloc_addr(p))
3254 vfree(p);
3255 else
3256 kfree(p);
3258 static void *pidlist_resize(void *p, int newcount)
3260 void *newlist;
3261 /* note: if new alloc fails, old p will still be valid either way */
3262 if (is_vmalloc_addr(p)) {
3263 newlist = vmalloc(newcount * sizeof(pid_t));
3264 if (!newlist)
3265 return NULL;
3266 memcpy(newlist, p, newcount * sizeof(pid_t));
3267 vfree(p);
3268 } else {
3269 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
3271 return newlist;
3275 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3276 * If the new stripped list is sufficiently smaller and there's enough memory
3277 * to allocate a new buffer, will let go of the unneeded memory. Returns the
3278 * number of unique elements.
3280 /* is the size difference enough that we should re-allocate the array? */
3281 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
3282 static int pidlist_uniq(pid_t **p, int length)
3284 int src, dest = 1;
3285 pid_t *list = *p;
3286 pid_t *newlist;
3289 * we presume the 0th element is unique, so i starts at 1. trivial
3290 * edge cases first; no work needs to be done for either
3292 if (length == 0 || length == 1)
3293 return length;
3294 /* src and dest walk down the list; dest counts unique elements */
3295 for (src = 1; src < length; src++) {
3296 /* find next unique element */
3297 while (list[src] == list[src-1]) {
3298 src++;
3299 if (src == length)
3300 goto after;
3302 /* dest always points to where the next unique element goes */
3303 list[dest] = list[src];
3304 dest++;
3306 after:
3308 * if the length difference is large enough, we want to allocate a
3309 * smaller buffer to save memory. if this fails due to out of memory,
3310 * we'll just stay with what we've got.
3312 if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
3313 newlist = pidlist_resize(list, dest);
3314 if (newlist)
3315 *p = newlist;
3317 return dest;
3320 static int cmppid(const void *a, const void *b)
3322 return *(pid_t *)a - *(pid_t *)b;
3326 * find the appropriate pidlist for our purpose (given procs vs tasks)
3327 * returns with the lock on that pidlist already held, and takes care
3328 * of the use count, or returns NULL with no locks held if we're out of
3329 * memory.
3331 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3332 enum cgroup_filetype type)
3334 struct cgroup_pidlist *l;
3335 /* don't need task_nsproxy() if we're looking at ourself */
3336 struct pid_namespace *ns = current->nsproxy->pid_ns;
3339 * We can't drop the pidlist_mutex before taking the l->mutex in case
3340 * the last ref-holder is trying to remove l from the list at the same
3341 * time. Holding the pidlist_mutex precludes somebody taking whichever
3342 * list we find out from under us - compare release_pid_array().
3344 mutex_lock(&cgrp->pidlist_mutex);
3345 list_for_each_entry(l, &cgrp->pidlists, links) {
3346 if (l->key.type == type && l->key.ns == ns) {
3347 /* make sure l doesn't vanish out from under us */
3348 down_write(&l->mutex);
3349 mutex_unlock(&cgrp->pidlist_mutex);
3350 return l;
3353 /* entry not found; create a new one */
3354 l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3355 if (!l) {
3356 mutex_unlock(&cgrp->pidlist_mutex);
3357 return l;
3359 init_rwsem(&l->mutex);
3360 down_write(&l->mutex);
3361 l->key.type = type;
3362 l->key.ns = get_pid_ns(ns);
3363 l->use_count = 0; /* don't increment here */
3364 l->list = NULL;
3365 l->owner = cgrp;
3366 list_add(&l->links, &cgrp->pidlists);
3367 mutex_unlock(&cgrp->pidlist_mutex);
3368 return l;
3372 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3374 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3375 struct cgroup_pidlist **lp)
3377 pid_t *array;
3378 int length;
3379 int pid, n = 0; /* used for populating the array */
3380 struct cgroup_iter it;
3381 struct task_struct *tsk;
3382 struct cgroup_pidlist *l;
3385 * If cgroup gets more users after we read count, we won't have
3386 * enough space - tough. This race is indistinguishable to the
3387 * caller from the case that the additional cgroup users didn't
3388 * show up until sometime later on.
3390 length = cgroup_task_count(cgrp);
3391 array = pidlist_allocate(length);
3392 if (!array)
3393 return -ENOMEM;
3394 /* now, populate the array */
3395 cgroup_iter_start(cgrp, &it);
3396 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3397 if (unlikely(n == length))
3398 break;
3399 /* get tgid or pid for procs or tasks file respectively */
3400 if (type == CGROUP_FILE_PROCS)
3401 pid = task_tgid_vnr(tsk);
3402 else
3403 pid = task_pid_vnr(tsk);
3404 if (pid > 0) /* make sure to only use valid results */
3405 array[n++] = pid;
3407 cgroup_iter_end(cgrp, &it);
3408 length = n;
3409 /* now sort & (if procs) strip out duplicates */
3410 sort(array, length, sizeof(pid_t), cmppid, NULL);
3411 if (type == CGROUP_FILE_PROCS)
3412 length = pidlist_uniq(&array, length);
3413 l = cgroup_pidlist_find(cgrp, type);
3414 if (!l) {
3415 pidlist_free(array);
3416 return -ENOMEM;
3418 /* store array, freeing old if necessary - lock already held */
3419 pidlist_free(l->list);
3420 l->list = array;
3421 l->length = length;
3422 l->use_count++;
3423 up_write(&l->mutex);
3424 *lp = l;
3425 return 0;
3429 * cgroupstats_build - build and fill cgroupstats
3430 * @stats: cgroupstats to fill information into
3431 * @dentry: A dentry entry belonging to the cgroup for which stats have
3432 * been requested.
3434 * Build and fill cgroupstats so that taskstats can export it to user
3435 * space.
3437 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3439 int ret = -EINVAL;
3440 struct cgroup *cgrp;
3441 struct cgroup_iter it;
3442 struct task_struct *tsk;
3445 * Validate dentry by checking the superblock operations,
3446 * and make sure it's a directory.
3448 if (dentry->d_sb->s_op != &cgroup_ops ||
3449 !S_ISDIR(dentry->d_inode->i_mode))
3450 goto err;
3452 ret = 0;
3453 cgrp = dentry->d_fsdata;
3455 cgroup_iter_start(cgrp, &it);
3456 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3457 switch (tsk->state) {
3458 case TASK_RUNNING:
3459 stats->nr_running++;
3460 break;
3461 case TASK_INTERRUPTIBLE:
3462 stats->nr_sleeping++;
3463 break;
3464 case TASK_UNINTERRUPTIBLE:
3465 stats->nr_uninterruptible++;
3466 break;
3467 case TASK_STOPPED:
3468 stats->nr_stopped++;
3469 break;
3470 default:
3471 if (delayacct_is_task_waiting_on_io(tsk))
3472 stats->nr_io_wait++;
3473 break;
3476 cgroup_iter_end(cgrp, &it);
3478 err:
3479 return ret;
3484 * seq_file methods for the tasks/procs files. The seq_file position is the
3485 * next pid to display; the seq_file iterator is a pointer to the pid
3486 * in the cgroup->l->list array.
3489 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3492 * Initially we receive a position value that corresponds to
3493 * one more than the last pid shown (or 0 on the first call or
3494 * after a seek to the start). Use a binary-search to find the
3495 * next pid to display, if any
3497 struct cgroup_pidlist *l = s->private;
3498 int index = 0, pid = *pos;
3499 int *iter;
3501 down_read(&l->mutex);
3502 if (pid) {
3503 int end = l->length;
3505 while (index < end) {
3506 int mid = (index + end) / 2;
3507 if (l->list[mid] == pid) {
3508 index = mid;
3509 break;
3510 } else if (l->list[mid] <= pid)
3511 index = mid + 1;
3512 else
3513 end = mid;
3516 /* If we're off the end of the array, we're done */
3517 if (index >= l->length)
3518 return NULL;
3519 /* Update the abstract position to be the actual pid that we found */
3520 iter = l->list + index;
3521 *pos = *iter;
3522 return iter;
3525 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3527 struct cgroup_pidlist *l = s->private;
3528 up_read(&l->mutex);
3531 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3533 struct cgroup_pidlist *l = s->private;
3534 pid_t *p = v;
3535 pid_t *end = l->list + l->length;
3537 * Advance to the next pid in the array. If this goes off the
3538 * end, we're done
3540 p++;
3541 if (p >= end) {
3542 return NULL;
3543 } else {
3544 *pos = *p;
3545 return p;
3549 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3551 return seq_printf(s, "%d\n", *(int *)v);
3555 * seq_operations functions for iterating on pidlists through seq_file -
3556 * independent of whether it's tasks or procs
3558 static const struct seq_operations cgroup_pidlist_seq_operations = {
3559 .start = cgroup_pidlist_start,
3560 .stop = cgroup_pidlist_stop,
3561 .next = cgroup_pidlist_next,
3562 .show = cgroup_pidlist_show,
3565 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3568 * the case where we're the last user of this particular pidlist will
3569 * have us remove it from the cgroup's list, which entails taking the
3570 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3571 * pidlist_mutex, we have to take pidlist_mutex first.
3573 mutex_lock(&l->owner->pidlist_mutex);
3574 down_write(&l->mutex);
3575 BUG_ON(!l->use_count);
3576 if (!--l->use_count) {
3577 /* we're the last user if refcount is 0; remove and free */
3578 list_del(&l->links);
3579 mutex_unlock(&l->owner->pidlist_mutex);
3580 pidlist_free(l->list);
3581 put_pid_ns(l->key.ns);
3582 up_write(&l->mutex);
3583 kfree(l);
3584 return;
3586 mutex_unlock(&l->owner->pidlist_mutex);
3587 up_write(&l->mutex);
3590 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3592 struct cgroup_pidlist *l;
3593 if (!(file->f_mode & FMODE_READ))
3594 return 0;
3596 * the seq_file will only be initialized if the file was opened for
3597 * reading; hence we check if it's not null only in that case.
3599 l = ((struct seq_file *)file->private_data)->private;
3600 cgroup_release_pid_array(l);
3601 return seq_release(inode, file);
3604 static const struct file_operations cgroup_pidlist_operations = {
3605 .read = seq_read,
3606 .llseek = seq_lseek,
3607 .write = cgroup_file_write,
3608 .release = cgroup_pidlist_release,
3612 * The following functions handle opens on a file that displays a pidlist
3613 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3614 * in the cgroup.
3616 /* helper function for the two below it */
3617 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3619 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3620 struct cgroup_pidlist *l;
3621 int retval;
3623 /* Nothing to do for write-only files */
3624 if (!(file->f_mode & FMODE_READ))
3625 return 0;
3627 /* have the array populated */
3628 retval = pidlist_array_load(cgrp, type, &l);
3629 if (retval)
3630 return retval;
3631 /* configure file information */
3632 file->f_op = &cgroup_pidlist_operations;
3634 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3635 if (retval) {
3636 cgroup_release_pid_array(l);
3637 return retval;
3639 ((struct seq_file *)file->private_data)->private = l;
3640 return 0;
3642 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3644 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3646 static int cgroup_procs_open(struct inode *unused, struct file *file)
3648 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3651 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3652 struct cftype *cft)
3654 return notify_on_release(cgrp);
3657 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3658 struct cftype *cft,
3659 u64 val)
3661 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3662 if (val)
3663 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3664 else
3665 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3666 return 0;
3670 * Unregister event and free resources.
3672 * Gets called from workqueue.
3674 static void cgroup_event_remove(struct work_struct *work)
3676 struct cgroup_event *event = container_of(work, struct cgroup_event,
3677 remove);
3678 struct cgroup *cgrp = event->cgrp;
3680 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3682 eventfd_ctx_put(event->eventfd);
3683 kfree(event);
3684 dput(cgrp->dentry);
3688 * Gets called on POLLHUP on eventfd when user closes it.
3690 * Called with wqh->lock held and interrupts disabled.
3692 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3693 int sync, void *key)
3695 struct cgroup_event *event = container_of(wait,
3696 struct cgroup_event, wait);
3697 struct cgroup *cgrp = event->cgrp;
3698 unsigned long flags = (unsigned long)key;
3700 if (flags & POLLHUP) {
3701 __remove_wait_queue(event->wqh, &event->wait);
3702 spin_lock(&cgrp->event_list_lock);
3703 list_del(&event->list);
3704 spin_unlock(&cgrp->event_list_lock);
3706 * We are in atomic context, but cgroup_event_remove() may
3707 * sleep, so we have to call it in workqueue.
3709 schedule_work(&event->remove);
3712 return 0;
3715 static void cgroup_event_ptable_queue_proc(struct file *file,
3716 wait_queue_head_t *wqh, poll_table *pt)
3718 struct cgroup_event *event = container_of(pt,
3719 struct cgroup_event, pt);
3721 event->wqh = wqh;
3722 add_wait_queue(wqh, &event->wait);
3726 * Parse input and register new cgroup event handler.
3728 * Input must be in format '<event_fd> <control_fd> <args>'.
3729 * Interpretation of args is defined by control file implementation.
3731 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3732 const char *buffer)
3734 struct cgroup_event *event = NULL;
3735 unsigned int efd, cfd;
3736 struct file *efile = NULL;
3737 struct file *cfile = NULL;
3738 char *endp;
3739 int ret;
3741 efd = simple_strtoul(buffer, &endp, 10);
3742 if (*endp != ' ')
3743 return -EINVAL;
3744 buffer = endp + 1;
3746 cfd = simple_strtoul(buffer, &endp, 10);
3747 if ((*endp != ' ') && (*endp != '\0'))
3748 return -EINVAL;
3749 buffer = endp + 1;
3751 event = kzalloc(sizeof(*event), GFP_KERNEL);
3752 if (!event)
3753 return -ENOMEM;
3754 event->cgrp = cgrp;
3755 INIT_LIST_HEAD(&event->list);
3756 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3757 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3758 INIT_WORK(&event->remove, cgroup_event_remove);
3760 efile = eventfd_fget(efd);
3761 if (IS_ERR(efile)) {
3762 ret = PTR_ERR(efile);
3763 goto fail;
3766 event->eventfd = eventfd_ctx_fileget(efile);
3767 if (IS_ERR(event->eventfd)) {
3768 ret = PTR_ERR(event->eventfd);
3769 goto fail;
3772 cfile = fget(cfd);
3773 if (!cfile) {
3774 ret = -EBADF;
3775 goto fail;
3778 /* the process need read permission on control file */
3779 /* AV: shouldn't we check that it's been opened for read instead? */
3780 ret = inode_permission(cfile->f_path.dentry->d_inode, MAY_READ);
3781 if (ret < 0)
3782 goto fail;
3784 event->cft = __file_cft(cfile);
3785 if (IS_ERR(event->cft)) {
3786 ret = PTR_ERR(event->cft);
3787 goto fail;
3790 if (!event->cft->register_event || !event->cft->unregister_event) {
3791 ret = -EINVAL;
3792 goto fail;
3795 ret = event->cft->register_event(cgrp, event->cft,
3796 event->eventfd, buffer);
3797 if (ret)
3798 goto fail;
3800 if (efile->f_op->poll(efile, &event->pt) & POLLHUP) {
3801 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3802 ret = 0;
3803 goto fail;
3807 * Events should be removed after rmdir of cgroup directory, but before
3808 * destroying subsystem state objects. Let's take reference to cgroup
3809 * directory dentry to do that.
3811 dget(cgrp->dentry);
3813 spin_lock(&cgrp->event_list_lock);
3814 list_add(&event->list, &cgrp->event_list);
3815 spin_unlock(&cgrp->event_list_lock);
3817 fput(cfile);
3818 fput(efile);
3820 return 0;
3822 fail:
3823 if (cfile)
3824 fput(cfile);
3826 if (event && event->eventfd && !IS_ERR(event->eventfd))
3827 eventfd_ctx_put(event->eventfd);
3829 if (!IS_ERR_OR_NULL(efile))
3830 fput(efile);
3832 kfree(event);
3834 return ret;
3837 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
3838 struct cftype *cft)
3840 return clone_children(cgrp);
3843 static int cgroup_clone_children_write(struct cgroup *cgrp,
3844 struct cftype *cft,
3845 u64 val)
3847 if (val)
3848 set_bit(CGRP_CLONE_CHILDREN, &cgrp->flags);
3849 else
3850 clear_bit(CGRP_CLONE_CHILDREN, &cgrp->flags);
3851 return 0;
3855 * for the common functions, 'private' gives the type of file
3857 /* for hysterical raisins, we can't put this on the older files */
3858 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3859 static struct cftype files[] = {
3861 .name = "tasks",
3862 .open = cgroup_tasks_open,
3863 .write_u64 = cgroup_tasks_write,
3864 .release = cgroup_pidlist_release,
3865 .mode = S_IRUGO | S_IWUSR,
3868 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
3869 .open = cgroup_procs_open,
3870 .write_u64 = cgroup_procs_write,
3871 .release = cgroup_pidlist_release,
3872 .mode = S_IRUGO | S_IWUSR,
3875 .name = "notify_on_release",
3876 .read_u64 = cgroup_read_notify_on_release,
3877 .write_u64 = cgroup_write_notify_on_release,
3880 .name = CGROUP_FILE_GENERIC_PREFIX "event_control",
3881 .write_string = cgroup_write_event_control,
3882 .mode = S_IWUGO,
3885 .name = "cgroup.clone_children",
3886 .read_u64 = cgroup_clone_children_read,
3887 .write_u64 = cgroup_clone_children_write,
3890 .name = "release_agent",
3891 .flags = CFTYPE_ONLY_ON_ROOT,
3892 .read_seq_string = cgroup_release_agent_show,
3893 .write_string = cgroup_release_agent_write,
3894 .max_write_len = PATH_MAX,
3896 { } /* terminate */
3900 * cgroup_populate_dir - selectively creation of files in a directory
3901 * @cgrp: target cgroup
3902 * @base_files: true if the base files should be added
3903 * @subsys_mask: mask of the subsystem ids whose files should be added
3905 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
3906 unsigned long subsys_mask)
3908 int err;
3909 struct cgroup_subsys *ss;
3911 if (base_files) {
3912 err = cgroup_addrm_files(cgrp, NULL, files, true);
3913 if (err < 0)
3914 return err;
3917 /* process cftsets of each subsystem */
3918 for_each_subsys(cgrp->root, ss) {
3919 struct cftype_set *set;
3920 if (!test_bit(ss->subsys_id, &subsys_mask))
3921 continue;
3923 list_for_each_entry(set, &ss->cftsets, node)
3924 cgroup_addrm_files(cgrp, ss, set->cfts, true);
3927 /* This cgroup is ready now */
3928 for_each_subsys(cgrp->root, ss) {
3929 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3931 * Update id->css pointer and make this css visible from
3932 * CSS ID functions. This pointer will be dereferened
3933 * from RCU-read-side without locks.
3935 if (css->id)
3936 rcu_assign_pointer(css->id->css, css);
3939 return 0;
3942 static void css_dput_fn(struct work_struct *work)
3944 struct cgroup_subsys_state *css =
3945 container_of(work, struct cgroup_subsys_state, dput_work);
3946 struct dentry *dentry = css->cgroup->dentry;
3947 struct super_block *sb = dentry->d_sb;
3949 atomic_inc(&sb->s_active);
3950 dput(dentry);
3951 deactivate_super(sb);
3954 static void init_cgroup_css(struct cgroup_subsys_state *css,
3955 struct cgroup_subsys *ss,
3956 struct cgroup *cgrp)
3958 css->cgroup = cgrp;
3959 atomic_set(&css->refcnt, 1);
3960 css->flags = 0;
3961 css->id = NULL;
3962 if (cgrp == dummytop)
3963 set_bit(CSS_ROOT, &css->flags);
3964 BUG_ON(cgrp->subsys[ss->subsys_id]);
3965 cgrp->subsys[ss->subsys_id] = css;
3968 * css holds an extra ref to @cgrp->dentry which is put on the last
3969 * css_put(). dput() requires process context, which css_put() may
3970 * be called without. @css->dput_work will be used to invoke
3971 * dput() asynchronously from css_put().
3973 INIT_WORK(&css->dput_work, css_dput_fn);
3977 * cgroup_create - create a cgroup
3978 * @parent: cgroup that will be parent of the new cgroup
3979 * @dentry: dentry of the new cgroup
3980 * @mode: mode to set on new inode
3982 * Must be called with the mutex on the parent inode held
3984 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
3985 umode_t mode)
3987 struct cgroup *cgrp;
3988 struct cgroupfs_root *root = parent->root;
3989 int err = 0;
3990 struct cgroup_subsys *ss;
3991 struct super_block *sb = root->sb;
3993 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
3994 if (!cgrp)
3995 return -ENOMEM;
3998 * Only live parents can have children. Note that the liveliness
3999 * check isn't strictly necessary because cgroup_mkdir() and
4000 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4001 * anyway so that locking is contained inside cgroup proper and we
4002 * don't get nasty surprises if we ever grow another caller.
4004 if (!cgroup_lock_live_group(parent)) {
4005 err = -ENODEV;
4006 goto err_free;
4009 /* Grab a reference on the superblock so the hierarchy doesn't
4010 * get deleted on unmount if there are child cgroups. This
4011 * can be done outside cgroup_mutex, since the sb can't
4012 * disappear while someone has an open control file on the
4013 * fs */
4014 atomic_inc(&sb->s_active);
4016 init_cgroup_housekeeping(cgrp);
4018 cgrp->parent = parent;
4019 cgrp->root = parent->root;
4020 cgrp->top_cgroup = parent->top_cgroup;
4022 if (notify_on_release(parent))
4023 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4025 if (clone_children(parent))
4026 set_bit(CGRP_CLONE_CHILDREN, &cgrp->flags);
4028 for_each_subsys(root, ss) {
4029 struct cgroup_subsys_state *css;
4031 css = ss->create(cgrp);
4032 if (IS_ERR(css)) {
4033 err = PTR_ERR(css);
4034 goto err_destroy;
4036 init_cgroup_css(css, ss, cgrp);
4037 if (ss->use_id) {
4038 err = alloc_css_id(ss, parent, cgrp);
4039 if (err)
4040 goto err_destroy;
4042 /* At error, ->destroy() callback has to free assigned ID. */
4043 if (clone_children(parent) && ss->post_clone)
4044 ss->post_clone(cgrp);
4046 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4047 parent->parent) {
4048 pr_warning("cgroup: %s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4049 current->comm, current->pid, ss->name);
4050 if (!strcmp(ss->name, "memory"))
4051 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4052 ss->warned_broken_hierarchy = true;
4056 list_add(&cgrp->sibling, &cgrp->parent->children);
4057 root->number_of_cgroups++;
4059 err = cgroup_create_dir(cgrp, dentry, mode);
4060 if (err < 0)
4061 goto err_remove;
4063 /* each css holds a ref to the cgroup's dentry */
4064 for_each_subsys(root, ss)
4065 dget(dentry);
4067 /* The cgroup directory was pre-locked for us */
4068 BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
4070 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4072 err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4073 /* If err < 0, we have a half-filled directory - oh well ;) */
4075 mutex_unlock(&cgroup_mutex);
4076 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4078 return 0;
4080 err_remove:
4082 list_del(&cgrp->sibling);
4083 root->number_of_cgroups--;
4085 err_destroy:
4087 for_each_subsys(root, ss) {
4088 if (cgrp->subsys[ss->subsys_id])
4089 ss->destroy(cgrp);
4092 mutex_unlock(&cgroup_mutex);
4094 /* Release the reference count that we took on the superblock */
4095 deactivate_super(sb);
4096 err_free:
4097 kfree(cgrp);
4098 return err;
4101 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4103 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4105 /* the vfs holds inode->i_mutex already */
4106 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4110 * Check the reference count on each subsystem. Since we already
4111 * established that there are no tasks in the cgroup, if the css refcount
4112 * is also 1, then there should be no outstanding references, so the
4113 * subsystem is safe to destroy. We scan across all subsystems rather than
4114 * using the per-hierarchy linked list of mounted subsystems since we can
4115 * be called via check_for_release() with no synchronization other than
4116 * RCU, and the subsystem linked list isn't RCU-safe.
4118 static int cgroup_has_css_refs(struct cgroup *cgrp)
4120 int i;
4123 * We won't need to lock the subsys array, because the subsystems
4124 * we're concerned about aren't going anywhere since our cgroup root
4125 * has a reference on them.
4127 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4128 struct cgroup_subsys *ss = subsys[i];
4129 struct cgroup_subsys_state *css;
4131 /* Skip subsystems not present or not in this hierarchy */
4132 if (ss == NULL || ss->root != cgrp->root)
4133 continue;
4135 css = cgrp->subsys[ss->subsys_id];
4137 * When called from check_for_release() it's possible
4138 * that by this point the cgroup has been removed
4139 * and the css deleted. But a false-positive doesn't
4140 * matter, since it can only happen if the cgroup
4141 * has been deleted and hence no longer needs the
4142 * release agent to be called anyway.
4144 if (css && css_refcnt(css) > 1)
4145 return 1;
4147 return 0;
4150 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4152 struct cgroup *cgrp = dentry->d_fsdata;
4153 struct dentry *d;
4154 struct cgroup *parent;
4155 DEFINE_WAIT(wait);
4156 struct cgroup_event *event, *tmp;
4157 struct cgroup_subsys *ss;
4159 /* the vfs holds both inode->i_mutex already */
4160 mutex_lock(&cgroup_mutex);
4161 parent = cgrp->parent;
4162 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
4163 mutex_unlock(&cgroup_mutex);
4164 return -EBUSY;
4168 * Block new css_tryget() by deactivating refcnt and mark @cgrp
4169 * removed. This makes future css_tryget() and child creation
4170 * attempts fail thus maintaining the removal conditions verified
4171 * above.
4173 for_each_subsys(cgrp->root, ss) {
4174 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4176 WARN_ON(atomic_read(&css->refcnt) < 0);
4177 atomic_add(CSS_DEACT_BIAS, &css->refcnt);
4179 set_bit(CGRP_REMOVED, &cgrp->flags);
4182 * Tell subsystems to initate destruction. pre_destroy() should be
4183 * called with cgroup_mutex unlocked. See 3fa59dfbc3 ("cgroup: fix
4184 * potential deadlock in pre_destroy") for details.
4186 mutex_unlock(&cgroup_mutex);
4187 for_each_subsys(cgrp->root, ss)
4188 if (ss->pre_destroy)
4189 ss->pre_destroy(cgrp);
4190 mutex_lock(&cgroup_mutex);
4193 * Put all the base refs. Each css holds an extra reference to the
4194 * cgroup's dentry and cgroup removal proceeds regardless of css
4195 * refs. On the last put of each css, whenever that may be, the
4196 * extra dentry ref is put so that dentry destruction happens only
4197 * after all css's are released.
4199 for_each_subsys(cgrp->root, ss)
4200 css_put(cgrp->subsys[ss->subsys_id]);
4202 raw_spin_lock(&release_list_lock);
4203 if (!list_empty(&cgrp->release_list))
4204 list_del_init(&cgrp->release_list);
4205 raw_spin_unlock(&release_list_lock);
4207 /* delete this cgroup from parent->children */
4208 list_del_init(&cgrp->sibling);
4210 list_del_init(&cgrp->allcg_node);
4212 d = dget(cgrp->dentry);
4214 cgroup_d_remove_dir(d);
4215 dput(d);
4217 set_bit(CGRP_RELEASABLE, &parent->flags);
4218 check_for_release(parent);
4221 * Unregister events and notify userspace.
4222 * Notify userspace about cgroup removing only after rmdir of cgroup
4223 * directory to avoid race between userspace and kernelspace
4225 spin_lock(&cgrp->event_list_lock);
4226 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4227 list_del(&event->list);
4228 remove_wait_queue(event->wqh, &event->wait);
4229 eventfd_signal(event->eventfd, 1);
4230 schedule_work(&event->remove);
4232 spin_unlock(&cgrp->event_list_lock);
4234 mutex_unlock(&cgroup_mutex);
4235 return 0;
4238 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4240 INIT_LIST_HEAD(&ss->cftsets);
4243 * base_cftset is embedded in subsys itself, no need to worry about
4244 * deregistration.
4246 if (ss->base_cftypes) {
4247 ss->base_cftset.cfts = ss->base_cftypes;
4248 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4252 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4254 struct cgroup_subsys_state *css;
4256 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4258 /* init base cftset */
4259 cgroup_init_cftsets(ss);
4261 /* Create the top cgroup state for this subsystem */
4262 list_add(&ss->sibling, &rootnode.subsys_list);
4263 ss->root = &rootnode;
4264 css = ss->create(dummytop);
4265 /* We don't handle early failures gracefully */
4266 BUG_ON(IS_ERR(css));
4267 init_cgroup_css(css, ss, dummytop);
4269 /* Update the init_css_set to contain a subsys
4270 * pointer to this state - since the subsystem is
4271 * newly registered, all tasks and hence the
4272 * init_css_set is in the subsystem's top cgroup. */
4273 init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
4275 need_forkexit_callback |= ss->fork || ss->exit;
4277 /* At system boot, before all subsystems have been
4278 * registered, no tasks have been forked, so we don't
4279 * need to invoke fork callbacks here. */
4280 BUG_ON(!list_empty(&init_task.tasks));
4282 ss->active = 1;
4284 /* this function shouldn't be used with modular subsystems, since they
4285 * need to register a subsys_id, among other things */
4286 BUG_ON(ss->module);
4290 * cgroup_load_subsys: load and register a modular subsystem at runtime
4291 * @ss: the subsystem to load
4293 * This function should be called in a modular subsystem's initcall. If the
4294 * subsystem is built as a module, it will be assigned a new subsys_id and set
4295 * up for use. If the subsystem is built-in anyway, work is delegated to the
4296 * simpler cgroup_init_subsys.
4298 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4300 int i;
4301 struct cgroup_subsys_state *css;
4303 /* check name and function validity */
4304 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4305 ss->create == NULL || ss->destroy == NULL)
4306 return -EINVAL;
4309 * we don't support callbacks in modular subsystems. this check is
4310 * before the ss->module check for consistency; a subsystem that could
4311 * be a module should still have no callbacks even if the user isn't
4312 * compiling it as one.
4314 if (ss->fork || ss->exit)
4315 return -EINVAL;
4318 * an optionally modular subsystem is built-in: we want to do nothing,
4319 * since cgroup_init_subsys will have already taken care of it.
4321 if (ss->module == NULL) {
4322 /* a sanity check */
4323 BUG_ON(subsys[ss->subsys_id] != ss);
4324 return 0;
4327 /* init base cftset */
4328 cgroup_init_cftsets(ss);
4330 mutex_lock(&cgroup_mutex);
4331 subsys[ss->subsys_id] = ss;
4334 * no ss->create seems to need anything important in the ss struct, so
4335 * this can happen first (i.e. before the rootnode attachment).
4337 css = ss->create(dummytop);
4338 if (IS_ERR(css)) {
4339 /* failure case - need to deassign the subsys[] slot. */
4340 subsys[ss->subsys_id] = NULL;
4341 mutex_unlock(&cgroup_mutex);
4342 return PTR_ERR(css);
4345 list_add(&ss->sibling, &rootnode.subsys_list);
4346 ss->root = &rootnode;
4348 /* our new subsystem will be attached to the dummy hierarchy. */
4349 init_cgroup_css(css, ss, dummytop);
4350 /* init_idr must be after init_cgroup_css because it sets css->id. */
4351 if (ss->use_id) {
4352 int ret = cgroup_init_idr(ss, css);
4353 if (ret) {
4354 dummytop->subsys[ss->subsys_id] = NULL;
4355 ss->destroy(dummytop);
4356 subsys[ss->subsys_id] = NULL;
4357 mutex_unlock(&cgroup_mutex);
4358 return ret;
4363 * Now we need to entangle the css into the existing css_sets. unlike
4364 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4365 * will need a new pointer to it; done by iterating the css_set_table.
4366 * furthermore, modifying the existing css_sets will corrupt the hash
4367 * table state, so each changed css_set will need its hash recomputed.
4368 * this is all done under the css_set_lock.
4370 write_lock(&css_set_lock);
4371 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
4372 struct css_set *cg;
4373 struct hlist_node *node, *tmp;
4374 struct hlist_head *bucket = &css_set_table[i], *new_bucket;
4376 hlist_for_each_entry_safe(cg, node, tmp, bucket, hlist) {
4377 /* skip entries that we already rehashed */
4378 if (cg->subsys[ss->subsys_id])
4379 continue;
4380 /* remove existing entry */
4381 hlist_del(&cg->hlist);
4382 /* set new value */
4383 cg->subsys[ss->subsys_id] = css;
4384 /* recompute hash and restore entry */
4385 new_bucket = css_set_hash(cg->subsys);
4386 hlist_add_head(&cg->hlist, new_bucket);
4389 write_unlock(&css_set_lock);
4391 ss->active = 1;
4393 /* success! */
4394 mutex_unlock(&cgroup_mutex);
4395 return 0;
4397 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4400 * cgroup_unload_subsys: unload a modular subsystem
4401 * @ss: the subsystem to unload
4403 * This function should be called in a modular subsystem's exitcall. When this
4404 * function is invoked, the refcount on the subsystem's module will be 0, so
4405 * the subsystem will not be attached to any hierarchy.
4407 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4409 struct cg_cgroup_link *link;
4410 struct hlist_head *hhead;
4412 BUG_ON(ss->module == NULL);
4415 * we shouldn't be called if the subsystem is in use, and the use of
4416 * try_module_get in parse_cgroupfs_options should ensure that it
4417 * doesn't start being used while we're killing it off.
4419 BUG_ON(ss->root != &rootnode);
4421 mutex_lock(&cgroup_mutex);
4422 /* deassign the subsys_id */
4423 subsys[ss->subsys_id] = NULL;
4425 /* remove subsystem from rootnode's list of subsystems */
4426 list_del_init(&ss->sibling);
4429 * disentangle the css from all css_sets attached to the dummytop. as
4430 * in loading, we need to pay our respects to the hashtable gods.
4432 write_lock(&css_set_lock);
4433 list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
4434 struct css_set *cg = link->cg;
4436 hlist_del(&cg->hlist);
4437 BUG_ON(!cg->subsys[ss->subsys_id]);
4438 cg->subsys[ss->subsys_id] = NULL;
4439 hhead = css_set_hash(cg->subsys);
4440 hlist_add_head(&cg->hlist, hhead);
4442 write_unlock(&css_set_lock);
4445 * remove subsystem's css from the dummytop and free it - need to free
4446 * before marking as null because ss->destroy needs the cgrp->subsys
4447 * pointer to find their state. note that this also takes care of
4448 * freeing the css_id.
4450 ss->destroy(dummytop);
4451 dummytop->subsys[ss->subsys_id] = NULL;
4453 mutex_unlock(&cgroup_mutex);
4455 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4458 * cgroup_init_early - cgroup initialization at system boot
4460 * Initialize cgroups at system boot, and initialize any
4461 * subsystems that request early init.
4463 int __init cgroup_init_early(void)
4465 int i;
4466 atomic_set(&init_css_set.refcount, 1);
4467 INIT_LIST_HEAD(&init_css_set.cg_links);
4468 INIT_LIST_HEAD(&init_css_set.tasks);
4469 INIT_HLIST_NODE(&init_css_set.hlist);
4470 css_set_count = 1;
4471 init_cgroup_root(&rootnode);
4472 root_count = 1;
4473 init_task.cgroups = &init_css_set;
4475 init_css_set_link.cg = &init_css_set;
4476 init_css_set_link.cgrp = dummytop;
4477 list_add(&init_css_set_link.cgrp_link_list,
4478 &rootnode.top_cgroup.css_sets);
4479 list_add(&init_css_set_link.cg_link_list,
4480 &init_css_set.cg_links);
4482 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
4483 INIT_HLIST_HEAD(&css_set_table[i]);
4485 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4486 struct cgroup_subsys *ss = subsys[i];
4488 /* at bootup time, we don't worry about modular subsystems */
4489 if (!ss || ss->module)
4490 continue;
4492 BUG_ON(!ss->name);
4493 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4494 BUG_ON(!ss->create);
4495 BUG_ON(!ss->destroy);
4496 if (ss->subsys_id != i) {
4497 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4498 ss->name, ss->subsys_id);
4499 BUG();
4502 if (ss->early_init)
4503 cgroup_init_subsys(ss);
4505 return 0;
4509 * cgroup_init - cgroup initialization
4511 * Register cgroup filesystem and /proc file, and initialize
4512 * any subsystems that didn't request early init.
4514 int __init cgroup_init(void)
4516 int err;
4517 int i;
4518 struct hlist_head *hhead;
4520 err = bdi_init(&cgroup_backing_dev_info);
4521 if (err)
4522 return err;
4524 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4525 struct cgroup_subsys *ss = subsys[i];
4527 /* at bootup time, we don't worry about modular subsystems */
4528 if (!ss || ss->module)
4529 continue;
4530 if (!ss->early_init)
4531 cgroup_init_subsys(ss);
4532 if (ss->use_id)
4533 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4536 /* Add init_css_set to the hash table */
4537 hhead = css_set_hash(init_css_set.subsys);
4538 hlist_add_head(&init_css_set.hlist, hhead);
4539 BUG_ON(!init_root_id(&rootnode));
4541 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4542 if (!cgroup_kobj) {
4543 err = -ENOMEM;
4544 goto out;
4547 err = register_filesystem(&cgroup_fs_type);
4548 if (err < 0) {
4549 kobject_put(cgroup_kobj);
4550 goto out;
4553 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4555 out:
4556 if (err)
4557 bdi_destroy(&cgroup_backing_dev_info);
4559 return err;
4563 * proc_cgroup_show()
4564 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4565 * - Used for /proc/<pid>/cgroup.
4566 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4567 * doesn't really matter if tsk->cgroup changes after we read it,
4568 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4569 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4570 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4571 * cgroup to top_cgroup.
4574 /* TODO: Use a proper seq_file iterator */
4575 static int proc_cgroup_show(struct seq_file *m, void *v)
4577 struct pid *pid;
4578 struct task_struct *tsk;
4579 char *buf;
4580 int retval;
4581 struct cgroupfs_root *root;
4583 retval = -ENOMEM;
4584 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4585 if (!buf)
4586 goto out;
4588 retval = -ESRCH;
4589 pid = m->private;
4590 tsk = get_pid_task(pid, PIDTYPE_PID);
4591 if (!tsk)
4592 goto out_free;
4594 retval = 0;
4596 mutex_lock(&cgroup_mutex);
4598 for_each_active_root(root) {
4599 struct cgroup_subsys *ss;
4600 struct cgroup *cgrp;
4601 int count = 0;
4603 seq_printf(m, "%d:", root->hierarchy_id);
4604 for_each_subsys(root, ss)
4605 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4606 if (strlen(root->name))
4607 seq_printf(m, "%sname=%s", count ? "," : "",
4608 root->name);
4609 seq_putc(m, ':');
4610 cgrp = task_cgroup_from_root(tsk, root);
4611 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4612 if (retval < 0)
4613 goto out_unlock;
4614 seq_puts(m, buf);
4615 seq_putc(m, '\n');
4618 out_unlock:
4619 mutex_unlock(&cgroup_mutex);
4620 put_task_struct(tsk);
4621 out_free:
4622 kfree(buf);
4623 out:
4624 return retval;
4627 static int cgroup_open(struct inode *inode, struct file *file)
4629 struct pid *pid = PROC_I(inode)->pid;
4630 return single_open(file, proc_cgroup_show, pid);
4633 const struct file_operations proc_cgroup_operations = {
4634 .open = cgroup_open,
4635 .read = seq_read,
4636 .llseek = seq_lseek,
4637 .release = single_release,
4640 /* Display information about each subsystem and each hierarchy */
4641 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4643 int i;
4645 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4647 * ideally we don't want subsystems moving around while we do this.
4648 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4649 * subsys/hierarchy state.
4651 mutex_lock(&cgroup_mutex);
4652 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4653 struct cgroup_subsys *ss = subsys[i];
4654 if (ss == NULL)
4655 continue;
4656 seq_printf(m, "%s\t%d\t%d\t%d\n",
4657 ss->name, ss->root->hierarchy_id,
4658 ss->root->number_of_cgroups, !ss->disabled);
4660 mutex_unlock(&cgroup_mutex);
4661 return 0;
4664 static int cgroupstats_open(struct inode *inode, struct file *file)
4666 return single_open(file, proc_cgroupstats_show, NULL);
4669 static const struct file_operations proc_cgroupstats_operations = {
4670 .open = cgroupstats_open,
4671 .read = seq_read,
4672 .llseek = seq_lseek,
4673 .release = single_release,
4677 * cgroup_fork - attach newly forked task to its parents cgroup.
4678 * @child: pointer to task_struct of forking parent process.
4680 * Description: A task inherits its parent's cgroup at fork().
4682 * A pointer to the shared css_set was automatically copied in
4683 * fork.c by dup_task_struct(). However, we ignore that copy, since
4684 * it was not made under the protection of RCU, cgroup_mutex or
4685 * threadgroup_change_begin(), so it might no longer be a valid
4686 * cgroup pointer. cgroup_attach_task() might have already changed
4687 * current->cgroups, allowing the previously referenced cgroup
4688 * group to be removed and freed.
4690 * Outside the pointer validity we also need to process the css_set
4691 * inheritance between threadgoup_change_begin() and
4692 * threadgoup_change_end(), this way there is no leak in any process
4693 * wide migration performed by cgroup_attach_proc() that could otherwise
4694 * miss a thread because it is too early or too late in the fork stage.
4696 * At the point that cgroup_fork() is called, 'current' is the parent
4697 * task, and the passed argument 'child' points to the child task.
4699 void cgroup_fork(struct task_struct *child)
4702 * We don't need to task_lock() current because current->cgroups
4703 * can't be changed concurrently here. The parent obviously hasn't
4704 * exited and called cgroup_exit(), and we are synchronized against
4705 * cgroup migration through threadgroup_change_begin().
4707 child->cgroups = current->cgroups;
4708 get_css_set(child->cgroups);
4709 INIT_LIST_HEAD(&child->cg_list);
4713 * cgroup_post_fork - called on a new task after adding it to the task list
4714 * @child: the task in question
4716 * Adds the task to the list running through its css_set if necessary and
4717 * call the subsystem fork() callbacks. Has to be after the task is
4718 * visible on the task list in case we race with the first call to
4719 * cgroup_iter_start() - to guarantee that the new task ends up on its
4720 * list.
4722 void cgroup_post_fork(struct task_struct *child)
4724 int i;
4727 * use_task_css_set_links is set to 1 before we walk the tasklist
4728 * under the tasklist_lock and we read it here after we added the child
4729 * to the tasklist under the tasklist_lock as well. If the child wasn't
4730 * yet in the tasklist when we walked through it from
4731 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4732 * should be visible now due to the paired locking and barriers implied
4733 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4734 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4735 * lock on fork.
4737 if (use_task_css_set_links) {
4738 write_lock(&css_set_lock);
4739 if (list_empty(&child->cg_list)) {
4741 * It's safe to use child->cgroups without task_lock()
4742 * here because we are protected through
4743 * threadgroup_change_begin() against concurrent
4744 * css_set change in cgroup_task_migrate(). Also
4745 * the task can't exit at that point until
4746 * wake_up_new_task() is called, so we are protected
4747 * against cgroup_exit() setting child->cgroup to
4748 * init_css_set.
4750 list_add(&child->cg_list, &child->cgroups->tasks);
4752 write_unlock(&css_set_lock);
4756 * Call ss->fork(). This must happen after @child is linked on
4757 * css_set; otherwise, @child might change state between ->fork()
4758 * and addition to css_set.
4760 if (need_forkexit_callback) {
4761 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4762 struct cgroup_subsys *ss = subsys[i];
4765 * fork/exit callbacks are supported only for
4766 * builtin subsystems and we don't need further
4767 * synchronization as they never go away.
4769 if (!ss || ss->module)
4770 continue;
4772 if (ss->fork)
4773 ss->fork(child);
4779 * cgroup_exit - detach cgroup from exiting task
4780 * @tsk: pointer to task_struct of exiting process
4781 * @run_callback: run exit callbacks?
4783 * Description: Detach cgroup from @tsk and release it.
4785 * Note that cgroups marked notify_on_release force every task in
4786 * them to take the global cgroup_mutex mutex when exiting.
4787 * This could impact scaling on very large systems. Be reluctant to
4788 * use notify_on_release cgroups where very high task exit scaling
4789 * is required on large systems.
4791 * the_top_cgroup_hack:
4793 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4795 * We call cgroup_exit() while the task is still competent to
4796 * handle notify_on_release(), then leave the task attached to the
4797 * root cgroup in each hierarchy for the remainder of its exit.
4799 * To do this properly, we would increment the reference count on
4800 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4801 * code we would add a second cgroup function call, to drop that
4802 * reference. This would just create an unnecessary hot spot on
4803 * the top_cgroup reference count, to no avail.
4805 * Normally, holding a reference to a cgroup without bumping its
4806 * count is unsafe. The cgroup could go away, or someone could
4807 * attach us to a different cgroup, decrementing the count on
4808 * the first cgroup that we never incremented. But in this case,
4809 * top_cgroup isn't going away, and either task has PF_EXITING set,
4810 * which wards off any cgroup_attach_task() attempts, or task is a failed
4811 * fork, never visible to cgroup_attach_task.
4813 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4815 struct css_set *cg;
4816 int i;
4819 * Unlink from the css_set task list if necessary.
4820 * Optimistically check cg_list before taking
4821 * css_set_lock
4823 if (!list_empty(&tsk->cg_list)) {
4824 write_lock(&css_set_lock);
4825 if (!list_empty(&tsk->cg_list))
4826 list_del_init(&tsk->cg_list);
4827 write_unlock(&css_set_lock);
4830 /* Reassign the task to the init_css_set. */
4831 task_lock(tsk);
4832 cg = tsk->cgroups;
4833 tsk->cgroups = &init_css_set;
4835 if (run_callbacks && need_forkexit_callback) {
4836 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4837 struct cgroup_subsys *ss = subsys[i];
4839 /* modular subsystems can't use callbacks */
4840 if (!ss || ss->module)
4841 continue;
4843 if (ss->exit) {
4844 struct cgroup *old_cgrp =
4845 rcu_dereference_raw(cg->subsys[i])->cgroup;
4846 struct cgroup *cgrp = task_cgroup(tsk, i);
4847 ss->exit(cgrp, old_cgrp, tsk);
4851 task_unlock(tsk);
4853 if (cg)
4854 put_css_set_taskexit(cg);
4858 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
4859 * @cgrp: the cgroup in question
4860 * @task: the task in question
4862 * See if @cgrp is a descendant of @task's cgroup in the appropriate
4863 * hierarchy.
4865 * If we are sending in dummytop, then presumably we are creating
4866 * the top cgroup in the subsystem.
4868 * Called only by the ns (nsproxy) cgroup.
4870 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
4872 int ret;
4873 struct cgroup *target;
4875 if (cgrp == dummytop)
4876 return 1;
4878 target = task_cgroup_from_root(task, cgrp->root);
4879 while (cgrp != target && cgrp!= cgrp->top_cgroup)
4880 cgrp = cgrp->parent;
4881 ret = (cgrp == target);
4882 return ret;
4885 static void check_for_release(struct cgroup *cgrp)
4887 /* All of these checks rely on RCU to keep the cgroup
4888 * structure alive */
4889 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
4890 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
4891 /* Control Group is currently removeable. If it's not
4892 * already queued for a userspace notification, queue
4893 * it now */
4894 int need_schedule_work = 0;
4895 raw_spin_lock(&release_list_lock);
4896 if (!cgroup_is_removed(cgrp) &&
4897 list_empty(&cgrp->release_list)) {
4898 list_add(&cgrp->release_list, &release_list);
4899 need_schedule_work = 1;
4901 raw_spin_unlock(&release_list_lock);
4902 if (need_schedule_work)
4903 schedule_work(&release_agent_work);
4907 /* Caller must verify that the css is not for root cgroup */
4908 bool __css_tryget(struct cgroup_subsys_state *css)
4910 while (true) {
4911 int t, v;
4913 v = css_refcnt(css);
4914 t = atomic_cmpxchg(&css->refcnt, v, v + 1);
4915 if (likely(t == v))
4916 return true;
4917 else if (t < 0)
4918 return false;
4919 cpu_relax();
4922 EXPORT_SYMBOL_GPL(__css_tryget);
4924 /* Caller must verify that the css is not for root cgroup */
4925 void __css_put(struct cgroup_subsys_state *css)
4927 struct cgroup *cgrp = css->cgroup;
4928 int v;
4930 rcu_read_lock();
4931 v = css_unbias_refcnt(atomic_dec_return(&css->refcnt));
4933 switch (v) {
4934 case 1:
4935 if (notify_on_release(cgrp)) {
4936 set_bit(CGRP_RELEASABLE, &cgrp->flags);
4937 check_for_release(cgrp);
4939 break;
4940 case 0:
4941 schedule_work(&css->dput_work);
4942 break;
4944 rcu_read_unlock();
4946 EXPORT_SYMBOL_GPL(__css_put);
4949 * Notify userspace when a cgroup is released, by running the
4950 * configured release agent with the name of the cgroup (path
4951 * relative to the root of cgroup file system) as the argument.
4953 * Most likely, this user command will try to rmdir this cgroup.
4955 * This races with the possibility that some other task will be
4956 * attached to this cgroup before it is removed, or that some other
4957 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4958 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4959 * unused, and this cgroup will be reprieved from its death sentence,
4960 * to continue to serve a useful existence. Next time it's released,
4961 * we will get notified again, if it still has 'notify_on_release' set.
4963 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4964 * means only wait until the task is successfully execve()'d. The
4965 * separate release agent task is forked by call_usermodehelper(),
4966 * then control in this thread returns here, without waiting for the
4967 * release agent task. We don't bother to wait because the caller of
4968 * this routine has no use for the exit status of the release agent
4969 * task, so no sense holding our caller up for that.
4971 static void cgroup_release_agent(struct work_struct *work)
4973 BUG_ON(work != &release_agent_work);
4974 mutex_lock(&cgroup_mutex);
4975 raw_spin_lock(&release_list_lock);
4976 while (!list_empty(&release_list)) {
4977 char *argv[3], *envp[3];
4978 int i;
4979 char *pathbuf = NULL, *agentbuf = NULL;
4980 struct cgroup *cgrp = list_entry(release_list.next,
4981 struct cgroup,
4982 release_list);
4983 list_del_init(&cgrp->release_list);
4984 raw_spin_unlock(&release_list_lock);
4985 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4986 if (!pathbuf)
4987 goto continue_free;
4988 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
4989 goto continue_free;
4990 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4991 if (!agentbuf)
4992 goto continue_free;
4994 i = 0;
4995 argv[i++] = agentbuf;
4996 argv[i++] = pathbuf;
4997 argv[i] = NULL;
4999 i = 0;
5000 /* minimal command environment */
5001 envp[i++] = "HOME=/";
5002 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5003 envp[i] = NULL;
5005 /* Drop the lock while we invoke the usermode helper,
5006 * since the exec could involve hitting disk and hence
5007 * be a slow process */
5008 mutex_unlock(&cgroup_mutex);
5009 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5010 mutex_lock(&cgroup_mutex);
5011 continue_free:
5012 kfree(pathbuf);
5013 kfree(agentbuf);
5014 raw_spin_lock(&release_list_lock);
5016 raw_spin_unlock(&release_list_lock);
5017 mutex_unlock(&cgroup_mutex);
5020 static int __init cgroup_disable(char *str)
5022 int i;
5023 char *token;
5025 while ((token = strsep(&str, ",")) != NULL) {
5026 if (!*token)
5027 continue;
5028 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
5029 struct cgroup_subsys *ss = subsys[i];
5032 * cgroup_disable, being at boot time, can't
5033 * know about module subsystems, so we don't
5034 * worry about them.
5036 if (!ss || ss->module)
5037 continue;
5039 if (!strcmp(token, ss->name)) {
5040 ss->disabled = 1;
5041 printk(KERN_INFO "Disabling %s control group"
5042 " subsystem\n", ss->name);
5043 break;
5047 return 1;
5049 __setup("cgroup_disable=", cgroup_disable);
5052 * Functons for CSS ID.
5056 *To get ID other than 0, this should be called when !cgroup_is_removed().
5058 unsigned short css_id(struct cgroup_subsys_state *css)
5060 struct css_id *cssid;
5063 * This css_id() can return correct value when somone has refcnt
5064 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5065 * it's unchanged until freed.
5067 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5069 if (cssid)
5070 return cssid->id;
5071 return 0;
5073 EXPORT_SYMBOL_GPL(css_id);
5075 unsigned short css_depth(struct cgroup_subsys_state *css)
5077 struct css_id *cssid;
5079 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5081 if (cssid)
5082 return cssid->depth;
5083 return 0;
5085 EXPORT_SYMBOL_GPL(css_depth);
5088 * css_is_ancestor - test "root" css is an ancestor of "child"
5089 * @child: the css to be tested.
5090 * @root: the css supporsed to be an ancestor of the child.
5092 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5093 * this function reads css->id, the caller must hold rcu_read_lock().
5094 * But, considering usual usage, the csses should be valid objects after test.
5095 * Assuming that the caller will do some action to the child if this returns
5096 * returns true, the caller must take "child";s reference count.
5097 * If "child" is valid object and this returns true, "root" is valid, too.
5100 bool css_is_ancestor(struct cgroup_subsys_state *child,
5101 const struct cgroup_subsys_state *root)
5103 struct css_id *child_id;
5104 struct css_id *root_id;
5106 child_id = rcu_dereference(child->id);
5107 if (!child_id)
5108 return false;
5109 root_id = rcu_dereference(root->id);
5110 if (!root_id)
5111 return false;
5112 if (child_id->depth < root_id->depth)
5113 return false;
5114 if (child_id->stack[root_id->depth] != root_id->id)
5115 return false;
5116 return true;
5119 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5121 struct css_id *id = css->id;
5122 /* When this is called before css_id initialization, id can be NULL */
5123 if (!id)
5124 return;
5126 BUG_ON(!ss->use_id);
5128 rcu_assign_pointer(id->css, NULL);
5129 rcu_assign_pointer(css->id, NULL);
5130 spin_lock(&ss->id_lock);
5131 idr_remove(&ss->idr, id->id);
5132 spin_unlock(&ss->id_lock);
5133 kfree_rcu(id, rcu_head);
5135 EXPORT_SYMBOL_GPL(free_css_id);
5138 * This is called by init or create(). Then, calls to this function are
5139 * always serialized (By cgroup_mutex() at create()).
5142 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5144 struct css_id *newid;
5145 int myid, error, size;
5147 BUG_ON(!ss->use_id);
5149 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5150 newid = kzalloc(size, GFP_KERNEL);
5151 if (!newid)
5152 return ERR_PTR(-ENOMEM);
5153 /* get id */
5154 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
5155 error = -ENOMEM;
5156 goto err_out;
5158 spin_lock(&ss->id_lock);
5159 /* Don't use 0. allocates an ID of 1-65535 */
5160 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
5161 spin_unlock(&ss->id_lock);
5163 /* Returns error when there are no free spaces for new ID.*/
5164 if (error) {
5165 error = -ENOSPC;
5166 goto err_out;
5168 if (myid > CSS_ID_MAX)
5169 goto remove_idr;
5171 newid->id = myid;
5172 newid->depth = depth;
5173 return newid;
5174 remove_idr:
5175 error = -ENOSPC;
5176 spin_lock(&ss->id_lock);
5177 idr_remove(&ss->idr, myid);
5178 spin_unlock(&ss->id_lock);
5179 err_out:
5180 kfree(newid);
5181 return ERR_PTR(error);
5185 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5186 struct cgroup_subsys_state *rootcss)
5188 struct css_id *newid;
5190 spin_lock_init(&ss->id_lock);
5191 idr_init(&ss->idr);
5193 newid = get_new_cssid(ss, 0);
5194 if (IS_ERR(newid))
5195 return PTR_ERR(newid);
5197 newid->stack[0] = newid->id;
5198 newid->css = rootcss;
5199 rootcss->id = newid;
5200 return 0;
5203 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5204 struct cgroup *child)
5206 int subsys_id, i, depth = 0;
5207 struct cgroup_subsys_state *parent_css, *child_css;
5208 struct css_id *child_id, *parent_id;
5210 subsys_id = ss->subsys_id;
5211 parent_css = parent->subsys[subsys_id];
5212 child_css = child->subsys[subsys_id];
5213 parent_id = parent_css->id;
5214 depth = parent_id->depth + 1;
5216 child_id = get_new_cssid(ss, depth);
5217 if (IS_ERR(child_id))
5218 return PTR_ERR(child_id);
5220 for (i = 0; i < depth; i++)
5221 child_id->stack[i] = parent_id->stack[i];
5222 child_id->stack[depth] = child_id->id;
5224 * child_id->css pointer will be set after this cgroup is available
5225 * see cgroup_populate_dir()
5227 rcu_assign_pointer(child_css->id, child_id);
5229 return 0;
5233 * css_lookup - lookup css by id
5234 * @ss: cgroup subsys to be looked into.
5235 * @id: the id
5237 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5238 * NULL if not. Should be called under rcu_read_lock()
5240 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5242 struct css_id *cssid = NULL;
5244 BUG_ON(!ss->use_id);
5245 cssid = idr_find(&ss->idr, id);
5247 if (unlikely(!cssid))
5248 return NULL;
5250 return rcu_dereference(cssid->css);
5252 EXPORT_SYMBOL_GPL(css_lookup);
5255 * css_get_next - lookup next cgroup under specified hierarchy.
5256 * @ss: pointer to subsystem
5257 * @id: current position of iteration.
5258 * @root: pointer to css. search tree under this.
5259 * @foundid: position of found object.
5261 * Search next css under the specified hierarchy of rootid. Calling under
5262 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
5264 struct cgroup_subsys_state *
5265 css_get_next(struct cgroup_subsys *ss, int id,
5266 struct cgroup_subsys_state *root, int *foundid)
5268 struct cgroup_subsys_state *ret = NULL;
5269 struct css_id *tmp;
5270 int tmpid;
5271 int rootid = css_id(root);
5272 int depth = css_depth(root);
5274 if (!rootid)
5275 return NULL;
5277 BUG_ON(!ss->use_id);
5278 WARN_ON_ONCE(!rcu_read_lock_held());
5280 /* fill start point for scan */
5281 tmpid = id;
5282 while (1) {
5284 * scan next entry from bitmap(tree), tmpid is updated after
5285 * idr_get_next().
5287 tmp = idr_get_next(&ss->idr, &tmpid);
5288 if (!tmp)
5289 break;
5290 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
5291 ret = rcu_dereference(tmp->css);
5292 if (ret) {
5293 *foundid = tmpid;
5294 break;
5297 /* continue to scan from next id */
5298 tmpid = tmpid + 1;
5300 return ret;
5304 * get corresponding css from file open on cgroupfs directory
5306 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5308 struct cgroup *cgrp;
5309 struct inode *inode;
5310 struct cgroup_subsys_state *css;
5312 inode = f->f_dentry->d_inode;
5313 /* check in cgroup filesystem dir */
5314 if (inode->i_op != &cgroup_dir_inode_operations)
5315 return ERR_PTR(-EBADF);
5317 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5318 return ERR_PTR(-EINVAL);
5320 /* get cgroup */
5321 cgrp = __d_cgrp(f->f_dentry);
5322 css = cgrp->subsys[id];
5323 return css ? css : ERR_PTR(-ENOENT);
5326 #ifdef CONFIG_CGROUP_DEBUG
5327 static struct cgroup_subsys_state *debug_create(struct cgroup *cont)
5329 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5331 if (!css)
5332 return ERR_PTR(-ENOMEM);
5334 return css;
5337 static void debug_destroy(struct cgroup *cont)
5339 kfree(cont->subsys[debug_subsys_id]);
5342 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
5344 return atomic_read(&cont->count);
5347 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5349 return cgroup_task_count(cont);
5352 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5354 return (u64)(unsigned long)current->cgroups;
5357 static u64 current_css_set_refcount_read(struct cgroup *cont,
5358 struct cftype *cft)
5360 u64 count;
5362 rcu_read_lock();
5363 count = atomic_read(&current->cgroups->refcount);
5364 rcu_read_unlock();
5365 return count;
5368 static int current_css_set_cg_links_read(struct cgroup *cont,
5369 struct cftype *cft,
5370 struct seq_file *seq)
5372 struct cg_cgroup_link *link;
5373 struct css_set *cg;
5375 read_lock(&css_set_lock);
5376 rcu_read_lock();
5377 cg = rcu_dereference(current->cgroups);
5378 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
5379 struct cgroup *c = link->cgrp;
5380 const char *name;
5382 if (c->dentry)
5383 name = c->dentry->d_name.name;
5384 else
5385 name = "?";
5386 seq_printf(seq, "Root %d group %s\n",
5387 c->root->hierarchy_id, name);
5389 rcu_read_unlock();
5390 read_unlock(&css_set_lock);
5391 return 0;
5394 #define MAX_TASKS_SHOWN_PER_CSS 25
5395 static int cgroup_css_links_read(struct cgroup *cont,
5396 struct cftype *cft,
5397 struct seq_file *seq)
5399 struct cg_cgroup_link *link;
5401 read_lock(&css_set_lock);
5402 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
5403 struct css_set *cg = link->cg;
5404 struct task_struct *task;
5405 int count = 0;
5406 seq_printf(seq, "css_set %p\n", cg);
5407 list_for_each_entry(task, &cg->tasks, cg_list) {
5408 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5409 seq_puts(seq, " ...\n");
5410 break;
5411 } else {
5412 seq_printf(seq, " task %d\n",
5413 task_pid_vnr(task));
5417 read_unlock(&css_set_lock);
5418 return 0;
5421 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5423 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5426 static struct cftype debug_files[] = {
5428 .name = "cgroup_refcount",
5429 .read_u64 = cgroup_refcount_read,
5432 .name = "taskcount",
5433 .read_u64 = debug_taskcount_read,
5437 .name = "current_css_set",
5438 .read_u64 = current_css_set_read,
5442 .name = "current_css_set_refcount",
5443 .read_u64 = current_css_set_refcount_read,
5447 .name = "current_css_set_cg_links",
5448 .read_seq_string = current_css_set_cg_links_read,
5452 .name = "cgroup_css_links",
5453 .read_seq_string = cgroup_css_links_read,
5457 .name = "releasable",
5458 .read_u64 = releasable_read,
5461 { } /* terminate */
5464 struct cgroup_subsys debug_subsys = {
5465 .name = "debug",
5466 .create = debug_create,
5467 .destroy = debug_destroy,
5468 .subsys_id = debug_subsys_id,
5469 .base_cftypes = debug_files,
5471 #endif /* CONFIG_CGROUP_DEBUG */